diff --git a/.gitignore b/.gitignore index 00b49e20..602f0a65 100644 --- a/.gitignore +++ b/.gitignore @@ -70,3 +70,18 @@ memory/ # Python byte-code from local scripts __pycache__/ *.pyc + +# Roadshow decks and prompts: pitch material for one audience, not product docs. +/微信流路演/ +/路演PPT提示词.md + +# Third-party signing library; save_video.py/sign.mjs fetch it from its origin +# on first run, so the repository never redistributes someone else's code. +shared/Skills/wechat-video-download/scripts/enc.js + +# Icon exploration rounds stay local; only the brief and the final masters ship. +/design/chatbridge-icon/* +!/design/chatbridge-icon/v3/ +/design/chatbridge-icon/v3/* +!/design/chatbridge-icon/v3/brief.md +!/design/chatbridge-icon/v3/final/ diff --git a/PRODUCT_CAPABILITIES.zh-CN.md b/PRODUCT_CAPABILITIES.zh-CN.md index d1dfee90..d85d7a98 100644 --- a/PRODUCT_CAPABILITIES.zh-CN.md +++ b/PRODUCT_CAPABILITIES.zh-CN.md @@ -1,12 +1,12 @@ # 微信流(WeChatBridge)产品能力文档 -> 基于 main 分支当前代码整理 -> 平台:macOS 13 及以上 -> 文档日期:2026-09-20 +> 基于 v0.1.16 代码整理 +> 平台:macOS 13 及以上(本文只描述 macOS 版) +> 文档日期:2026-11-24 ## 1. 产品定义 -微信流是一个完全本地运行的 macOS 微信聊天记录转发与归档工具。它把微信“转发到其他应用”产生的 ZIP、TXT 和媒体文件,送到 Codex、Claude、豆包、千问办公、WorkBuddy、WeSight、Obsidian、其他应用或剪贴板。 +微信流是一个以本地接收和归档为基础的 macOS 微信聊天记录转发工具,可选接入云端技能。它把微信“转发到其他应用”产生的 ZIP、TXT 和媒体文件,送到 Codex、Claude、豆包、千问办公、WorkBuddy、WeSight、DeepSeek Harness、Obsidian、本地文件夹、其他应用或剪贴板。 核心价值: @@ -177,7 +177,9 @@ ### 8.2 网络 -- 除软件更新外不联网。 +- 默认本地转发与归档不上传整份聊天。 +- 用户启用云端账号/技能后,App 和签名 wcb 访问所配置服务。执行只提交经用户授权的必要输入;账号、目录、报价与授权元数据也会联网。 +- 目标 Agent 是独立的数据处理方,其保存行为不由微信流控制。 - 十二个 Share Extension 均在沙盒中运行。 - 扩展没有网络权限。 @@ -200,7 +202,7 @@ - 支持 Universal 2,即 `arm64` 和 `x86_64`。 - 使用 Developer ID Application 签名。 - App 和 DMG 支持 Apple 公证与 stapling。 -- 提供 DMG、Homebrew Cask、SHA-256 校验文件。 +- 提供 DMG 与 SHA-256 校验文件(Homebrew Cask 仍在路线图中)。 - 支持 Sparkle 更新源。 - MIT 许可证。 @@ -212,7 +214,7 @@ 4. 自动粘贴依赖辅助功能权限、目标 App 可激活性和窗口焦点。 5. 场景识别群名依赖屏幕录制权限和微信标题栏可读性。 6. Codex/Claude 转发进入目标应用的输入区域,不等于官方 API 建场景。 -7. 不提供 Windows、iOS、Android 或云端版本。 +7. 本文只覆盖 macOS 版。Windows 版见 `windows/docs/`,iOS 版(信息桥)尚未正式发布,不提供 Android 版;云端技能是可选能力,默认不启用。 8. 不提供多设备同步、团队共享空间或服务端搜索。 ## 11. 关键实现位置 @@ -221,7 +223,7 @@ |---|---| | 十二个分享入口 | `macos/Scripts/share-slots.sh` | | Share Extension 接入 | `macos/Sources/WeChatBridgeShare/ShareViewController.swift` | -| 附件复制与命名 | `macos/Sources/WeChatBridgeShare/AttachmentImporter.swift` | +| 附件复制与命名 | `macos/Sources/WeChatBridgeCore/AttachmentImporter.swift` | | 目标应用定义 | `macos/Sources/WeChatBridgeCore/ShareAction.swift` | | 自定义目标 | `macos/Sources/WeChatBridgeCore/ForwardTarget.swift` | | 激活和自动粘贴 | `macos/Sources/WeChatBridgeApp/AutoPaste.swift` | @@ -229,8 +231,10 @@ | 场景匹配与快捷键 | `macos/Sources/WeChatBridgeCore/Scene.swift`、`macos/Sources/WeChatBridgeApp/SceneShortcutController.swift` | | 技能模型与安装 | `macos/Sources/WeChatBridgeCore/AgentID.swift`、`macos/Sources/WeChatBridgeApp/SkillLibrary.swift` | | 技能页面 | `macos/Sources/WeChatBridgeApp/Views/Settings/SkillsPane.swift` | -| Obsidian 投递 | `macos/Sources/WeChatBridgeApp/KnowledgeDelivery.swift`、`macos/Sources/WeChatBridgeCore/ObsidianNote.swift` | +| Obsidian 投递 | `macos/Sources/WeChatBridgeCore/KnowledgeDelivery.swift`、`macos/Sources/WeChatBridgeCore/ObsidianNote.swift` | | 批次状态 | `macos/Sources/WeChatBridgeCore/BatchState.swift` | | 共享目录 | `macos/Sources/WeChatBridgeCore/Inbox.swift` | +| 云端账号与付费技能(可选) | `macos/Sources/WeChatBridgeApp/CloudAccount.swift`、`macos/Sources/WeChatBridgeCore/Commerce.swift`、`macos/Sources/WeChatBridgeCore/SkillMonetization.swift` | +| 命令行桥 wcb | `macos/Sources/wcb/main.swift` | | App 打包和签名 | `macos/Scripts/make-app.sh` | | 发布和公证 | `macos/Scripts/release.sh` | diff --git a/README.md b/README.md index 61a54f89..98991de3 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ WeChatBridge 图标

WeChatBridge(微信流)

群里几百条消息没空翻?多选、转发,一步交给 AI 总结,或存进你的知识库。

-

在微信「转发到其他应用」里直接选 Codex、Claude、豆包、千问、Obsidian……不读数据库、不注入微信,全程本地。

+

在微信「转发到其他应用」里直接选 Codex、Claude、豆包、千问、Obsidian……不读数据库、不注入微信,聊天记录默认留在本地,可选接入云端技能。

- 免费下载 + 免费下载 加入交流群 GitHub Stars MIT License @@ -69,8 +69,9 @@ | --- | --- | --- | | macOS 13+(Apple Silicon 与 Intel) | [wwbsr.lanzout.com/b0umjur8h](https://wwbsr.lanzout.com/b0umjur8h) | `向明` | | Windows | [wwbsr.lanzout.com/b0umjur4d](https://wwbsr.lanzout.com/b0umjur4d) | `向明` | +| Android 8.0+(`1.0.0-beta1`) | [wwbsr.lanzout.com/b0umpq8mj](https://wwbsr.lanzout.com/b0umpq8mj) | `向明` | -macOS 版打开 DMG,把「微信流」拖入「应用程序」即可(图标带 🚫 或提示「无法验证」见[常见问题](USAGE.zh-CN.md#常见问题));Windows 版解压后按目录内说明运行。iOS 版正在开发中,进群可以第一时间知道进展。 +macOS 版打开 DMG,把「微信流」拖入「应用程序」即可(图标带 🚫 或提示「无法验证」见[常见问题](USAGE.zh-CN.md#常见问题));Windows 版解压后按目录内说明运行;Android 版(`1.0.0-beta1`,支持 Android 8.0 ~ Android 16,纯本地无联网权限)也可在 [GitHub Releases](https://github.com/freestylefly/WeChatBridge/releases/tag/v1.0.0-android-beta1) 下载,详情见 [android/README.md](android/README.md)。iOS 版正在开发中,进群可以第一时间知道进展。 ## 加入交流群 @@ -188,7 +189,8 @@ flowchart LR - 聊天内容只来自微信主动导出的文件。 - 不读取微信数据库,不解密、不注入、不修改微信进程。 -- 聊天归档、场景和记录保存在本机。 +- 聊天归档、场景和记录默认保存在本机。 +- 可选云端技能会访问用户配置的服务:账号、技能目录与执行授权需要联网;按量执行只提交用户授权的必要输入。 - Share Extension 在 macOS 沙盒中运行且没有网络权限。 - 屏幕录制权限只用于识别微信标题栏中的聊天名,图像仅在内存中处理。 - 辅助功能权限只用于激活目标应用和执行粘贴。 @@ -205,7 +207,7 @@ flowchart LR 苍何 - 公众号「向明」二维码 + 向明微信二维码 苍何微信二维码 @@ -216,7 +218,7 @@ flowchart LR ### 从源码构建 -需要 macOS 14+,以及 Xcode 16 或兼容 Swift 6 的 Command Line Tools。 +构建需要 Xcode 16 或兼容 Swift 6 的 Command Line Tools(Xcode 16 本身要求 macOS 14.5+);构建出的 App 可在 macOS 13+ 运行。 ```bash git clone https://github.com/freestylefly/WeChatBridge.git @@ -248,6 +250,9 @@ Scripts/dev-preview.sh # 构建、安装并打开开发 # Windows dotnet test windows/WeChatBridge.Windows.sln -c Release + +# Android(需 JDK 21 与 Android SDK) +bash android/scripts/verify.sh --release ```

@@ -265,6 +270,11 @@ macos/ # macOS 端 — 完整 SwiftPM 包 ios/ # iOS 端(开发中)— XcodeGen 工程,复用 WeChatBridgeCore +android/ # Android 端(1.0.0-beta1)— Gradle / Jetpack Compose 工程 +├── core/ # 纯 Kotlin/JVM 核心逻辑(Inbox 契约、归档解析、场景与笔记导出) +├── app/ # Android 主应用、分享接收、投递编排、悬浮球与快捷磁贴 +└── scripts/ # 一键构建、单测、lint 与权限白名单校验脚本 + windows/ # Windows 端 — .NET WPF 解决方案 ├── src/WeChatBridge.Windows/ # 主程序(WPF) ├── src/WeChatBridge.Windows.Core/ # Inbox 契约、投递、场景、技能(无 UI 依赖) @@ -283,7 +293,7 @@ shared/ # 多端共用的资产与契约 site/ # Sparkle 更新源与版本说明 ``` -项目使用 Swift Package Manager 管理 macOS 源码和 Sparkle 依赖。`macos/Scripts/make-app.sh` 会把主程序与十二个 Share Extension 组装成完整的 `.app`。iOS 侧见 `ios/project.yml`,Windows 侧见 `windows/AGENTS.md` 与 `windows/docs/README.zh-CN.md`。 +项目使用 Swift Package Manager 管理 macOS 源码和 Sparkle 依赖。`macos/Scripts/make-app.sh` 会把主程序与十二个 Share Extension 组装成完整的 `.app`。iOS 侧见 `ios/project.yml`,Windows 侧见 `windows/docs/README.zh-CN.md`。
@@ -308,6 +318,7 @@ site/ # Sparkle 更新源与版本说明 - [x] Universal 2 构建、签名与公证流程 - [x] 首个公开 DMG Release - [x] Windows 版 +- [x] Android 版(`1.0.0-beta1`) - [ ] iOS 版 - [ ] Homebrew Cask - [ ] 更多社区场景和技能包 diff --git a/README_EN.md b/README_EN.md index d8f438a4..090456fd 100644 --- a/README_EN.md +++ b/README_EN.md @@ -2,7 +2,7 @@ WeChatBridge icon

WeChatBridge (微信流)

Hundreds of unread group messages? Select, forward, and hand them to AI for a summary—or save them to your knowledge base.

-

Pick Codex, Claude, Doubao, QwenWork, Obsidian, and more straight from WeChat's “Forward to other apps” menu. No database access, no injection into WeChat, fully local.

+

Pick Codex, Claude, Doubao, QwenWork, Obsidian, and more straight from WeChat's “Forward to other apps” menu. No database access, no injection into WeChat. Chats stay local by default, with optional cloud skills.

Free download @@ -184,11 +184,12 @@ When collecting in batches, select each batch in WeChat and share it to “Colle ## Privacy by design -Your conversations only move around on your own computer: +By default your conversations stay on your own computer: - Conversation content only comes from files explicitly exported by WeChat. - The app does not read WeChat databases, decrypt data, inject code, or modify WeChat. -- Archives, scenes, and history stay on your computer. +- Archives, scenes, and history stay on your computer by default. +- Optional cloud skills (in development) talk to a service you configure: accounts, the skill catalog and execution grants need the network, and metered runs submit only the inputs you authorize. Local archives are never uploaded in bulk, and cloud credentials are kept separate between the app and its signed `wcb` CLI. - Every Share Extension runs inside the macOS sandbox without network access. - Screen Recording is used only to recognize the chat name in WeChat's title bar; images are processed in memory. - Accessibility is used only to activate a destination and perform the paste action. @@ -203,7 +204,7 @@ For project updates and tips, follow our WeChat Official Account or add us on We 苍何 - QR code for the WeChat Official Account 向明 + WeChat QR code for 向明 WeChat QR code for 苍何 @@ -214,7 +215,7 @@ For project updates and tips, follow our WeChat Official Account or add us on We ### Build from source -Requires macOS 14+ and Xcode 16 or Command Line Tools with Swift 6 support. +Building requires Xcode 16 or Command Line Tools with Swift 6 support (Xcode 16 itself needs macOS 14.5+); the built app runs on macOS 13+. ```bash git clone https://github.com/freestylefly/WeChatBridge.git @@ -263,7 +264,7 @@ shared/ # Agent logos, design assets, screenshots, demos, and site/ # Sparkle update feed and release notes ``` -Swift Package Manager owns the macOS source layout and the Sparkle dependency. `macos/Scripts/make-app.sh` assembles the host executable and twelve Share Extensions into a complete `.app` bundle. For iOS see `ios/project.yml`; for Windows see `windows/AGENTS.md` and `windows/docs/README.zh-CN.md`. +Swift Package Manager owns the macOS source layout and the Sparkle dependency. `macos/Scripts/make-app.sh` assembles the host executable and twelve Share Extensions into a complete `.app` bundle. For iOS see `ios/project.yml`; for Windows see `windows/docs/README.zh-CN.md`. diff --git a/README_JA.md b/README_JA.md index ef14d87c..535e7fdc 100644 --- a/README_JA.md +++ b/README_JA.md @@ -2,7 +2,7 @@ WeChatBridge のアイコン

WeChatBridge (微信流)

グループの未読メッセージが何百件も? 選んで転送し、AI に要約を任せるか、ナレッジベースに保存しましょう。

-

WeChat の「Forward to other apps」メニューから、Codex、Claude、Doubao、QwenWork、Obsidian などを直接選べます。データベースへのアクセスも、WeChat へのインジェクションもなく、すべてローカルで動きます。

+

WeChat の「Forward to other apps」メニューから、Codex、Claude、Doubao、QwenWork、Obsidian などを直接選べます。データベースへのアクセスも、WeChat へのインジェクションもありません。会話は既定でローカルにとどまり、クラウドスキルは任意で利用できます。

無料ダウンロード @@ -67,7 +67,7 @@ macOS 版 WeChat 4.1.13 以降が必要です。詳しい手順、権限、ト | プラットフォーム | ダウンロード | パスワード | | --- | --- | --- | -| macOS 14+(Apple Silicon と Intel) | [wwbsr.lanzout.com/b0umjur8h](https://wwbsr.lanzout.com/b0umjur8h) | `向明` | +| macOS 13+(Apple Silicon と Intel) | [wwbsr.lanzout.com/b0umjur8h](https://wwbsr.lanzout.com/b0umjur8h) | `向明` | | Windows | [wwbsr.lanzout.com/b0umjur4d](https://wwbsr.lanzout.com/b0umjur4d) | `向明` | macOS では、DMG を開いて WeChatBridge を「アプリケーション」にドラッグします。Windows では、アーカイブを展開して中の手順に従ってください。iOS 版は開発中です。グループに参加すると、いち早く情報を受け取れます。 @@ -176,11 +176,12 @@ flowchart LR ## プライバシーを考えた設計 -会話はあなた自身のコンピューターの中でしか移動しません: +会話は既定であなた自身のコンピューターの中にとどまります: - 会話の内容は、WeChat が明示的に書き出したファイルからしか取得しません。 - アプリは WeChat のデータベースを読んだり、データを復号したり、コードをインジェクションしたり、WeChat を改変したりしません。 -- アーカイブ、シーン、履歴はコンピューターの中にとどまります。 +- アーカイブ、シーン、履歴は既定でコンピューターの中にとどまります。 +- 任意のクラウドスキル(開発中)は、ユーザーが設定したサービスにアクセスします。アカウント、スキル一覧、実行の許可にはネットワークが必要で、従量制の実行では許可した入力だけを送信します。 - すべての Share Extension は、ネットワークにアクセスできない macOS のサンドボックス内で動きます。 - 画面収録は、WeChat のタイトルバーにあるチャット名を認識するためだけに使い、画像はメモリ内で処理します。 - アクセシビリティは、送り先を起動して貼り付けの操作を行うためだけに使います。 @@ -206,7 +207,7 @@ flowchart LR ### ソースからビルドする -macOS 14+ と、Swift 6 に対応した Xcode 16 または Command Line Tools が必要です。 +ビルドには Swift 6 に対応した Xcode 16 または Command Line Tools が必要です(Xcode 16 自体は macOS 14.5+ が必要)。ビルドしたアプリは macOS 13+ で動作します。 ```bash git clone https://github.com/freestylefly/WeChatBridge.git @@ -255,7 +256,7 @@ shared/ # Agent logos, design assets, screenshots, demos, and site/ # Sparkle update feed and release notes ``` -macOS のソースの構成と Sparkle の依存関係は Swift Package Manager で管理しています。`macos/Scripts/make-app.sh` は、ホストの実行ファイルと 12 個の Share Extension を組み立てて、完全な `.app` バンドルにします。iOS については `ios/project.yml` を、Windows については `windows/AGENTS.md` と `windows/docs/README.zh-CN.md` を参照してください。 +macOS のソースの構成と Sparkle の依存関係は Swift Package Manager で管理しています。`macos/Scripts/make-app.sh` は、ホストの実行ファイルと 12 個の Share Extension を組み立てて、完全な `.app` バンドルにします。iOS については `ios/project.yml` を、Windows については `windows/docs/README.zh-CN.md` を参照してください。 diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 00000000..beb32c90 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,20 @@ +# Gradle / 构建产物 +.gradle/ +.kotlin/ +build/ +**/build/ +captures/ +.externalNativeBuild/ +.cxx/ + +# 本机配置 +local.properties +signing.properties +keystore.properties +*.keystore +*.jks + +# IDE +.idea/ +*.iml +.DS_Store diff --git a/android/README.md b/android/README.md new file mode 100644 index 00000000..f8e59a02 --- /dev/null +++ b/android/README.md @@ -0,0 +1,61 @@ +# WeChatBridge(微信流)Android + +> **当前版本**:`1.0.0-beta1`(`versionCode = 1`) +> **支持系统**:Android 8.0 ~ Android 16(`minSdk = 26`,`targetSdk = 35`,`compileSdk = 36`) +> **安装包下载**:[蓝奏云直链](https://wwbsr.lanzout.com/b0umpq8mj)(提取密码:`向明`) · [GitHub Releases (`v1.0.0-android-beta1`)](https://github.com/freestylefly/WeChatBridge/releases/tag/v1.0.0-android-beta1) + +微信流 Android 版承接微信原生分享,让你在手机上把群聊记录、图片、文件一步整理并投递给常用 AI 应用或本地知识库(Obsidian / 文件夹),全程本地流转,**不申请网络权限**。 + +## 核心能力 + +- **微信原生分享接收**:在微信多选聊天记录 → 转发/更多 → 其他应用 → 选择「微信流」或「分批收集到微信流」,自动解析原生聊天 ZIP(含发言人、时间与图片附件);同时支持文件、相册多图、链接与剪贴板收入。 +- **分批收集**:超过单次转发上限时连续收多批,收齐后合并一次投递。 +- **AI 与知识库投递**:支持投递到 ChatGPT、Claude、Gemini、元宝、豆包、千问、DeepSeek、飞书、语雀、Obsidian 以及任意本地文件夹(SAF 导出为 Markdown 与附件)。 +- **场景提示词**:为不同群聊保存常用提示词,投递时一键附带。 +- **悬浮边缘条 & 快捷设置磁贴**:在其他应用上方随时展开暂存清单,支持拖拽填入、一键复制,以及可选的无障碍「一键填入」输入框(仅填入不自动发送)。 +- **双语界面**:完整支持简体中文与 English。 + +## 隐私与权限边界 + +APK 经过自动化脚本(`scripts/verify.sh --release`)与 `aapt2` 白名单校验,**不包含 `INTERNET` 权限**,也不申请通用存储或 `QUERY_ALL_PACKAGES` 权限: + +| 权限 | 用途 | 是否必需 | +| --- | --- | --- | +| `POST_NOTIFICATIONS` | 分批收集常驻通知与快捷投递通知(Android 13+ 运行时授权) | 可选 | +| `SYSTEM_ALERT_WINDOW` | 悬浮边缘条与暂存面板显示在其他应用上层 | 仅开启悬浮球时需要 | +| `FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_SPECIAL_USE` | 保持用户主动开启的悬浮边缘条不被系统回收 | 仅开启悬浮球时需要 | +| 无障碍服务(系统设置中手动开启) | 点击「填入」时将暂存内容写入当前应用输入框,绝不自动发送 | 可选 | + +## 从源码构建与验证 + +环境要求:JDK 21(`verify.sh` 会自动探测 Zulu 21 / `JAVA_HOME`)与 Android SDK(`compileSdk = 36`)。 + +```bash +cd android + +# 运行 :core 单测、:app 单测、debug 构建与 Manifest 权限检查 +bash scripts/verify.sh + +# 构建 release APK(R8 压缩混淆)、lintRelease 并用 aapt2 校验权限白名单 +bash scripts/verify.sh --release +``` + +### Release 正式签名配置 + +1. 复制 `keystore.properties.example` 为 `keystore.properties`(已被 `.gitignore` 忽略,切勿入库)。 +2. 填入你的 `.jks` 路径、别名与密码。 +3. 运行 `bash scripts/verify.sh --release`,产物输出至 `app/build/outputs/apk/release/app-release.apk`。 + +> 未配置 `keystore.properties` 时,release 构建会退回使用 debug 签名,仅供本机测试,不可对外分发。 + +## 模块结构 + +```text +android/ +├── core/ # 纯 Kotlin/JVM 核心逻辑(ZIP 解析、批次合并、场景、Markdown 导出),全量单测 +├── app/ # Jetpack Compose UI、分享接收、投递编排、悬浮球、快捷磁贴与无障碍填入 +├── scripts/ # verify.sh、真机 Intent 抓包与目标探测脚本 +└── keystore.properties.example +``` + +更多设计、验收与上架说明见 `docs/design/android-*.zh-CN.md`。 diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 00000000..6a47280d --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,132 @@ +import java.util.Properties +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +// :app —— AGP 9 内置 Kotlin 支持,无需再应用 org.jetbrains.kotlin.android。 +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) +} + +// release 签名:密钥只在本机 android/keystore.properties(git 忽略,模板见 keystore.properties.example)。 +// 文件不存在时 release 退回 debug 签名,只能本机测试,不能对外分发。 +val keystorePropertiesFile = rootProject.file("keystore.properties") +val keystoreProperties: Properties? = keystorePropertiesFile.takeIf { it.isFile }?.let { file -> + Properties().apply { file.inputStream().use { load(it) } } +} +if (keystoreProperties == null && + gradle.startParameter.taskNames.any { it.contains("release", ignoreCase = true) } +) { + logger.warn("w: 未找到 keystore.properties,release 用 debug 签名,仅供本机测试") +} + +android { + namespace = "com.xiangming.wechatbridge" + compileSdk = 36 + + defaultConfig { + applicationId = "com.xiangming.wechatbridge" + minSdk = 26 + targetSdk = 35 + versionCode = 1 + versionName = "1.0.0-beta1" + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + signingConfigs { + if (keystoreProperties != null) { + create("release") { + storeFile = rootProject.file(keystoreProperties.getProperty("storeFile")) + storePassword = keystoreProperties.getProperty("storePassword") + keyAlias = keystoreProperties.getProperty("keyAlias") + keyPassword = keystoreProperties.getProperty("keyPassword") + } + } + } + + buildTypes { + release { + isMinifyEnabled = true + isShrinkResources = true + signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug") + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + buildFeatures { + compose = true + } + + lint { + // values-en 已补齐(A4.8):缺译重新算 error,新增中文文案必须同时写英文。 + error += "MissingTranslation" + } + + testOptions { + unitTests.isIncludeAndroidResources = true + } +} + +// R8 打开后 Compose 插件会额外拉 compose-group-mapping 生成混淆映射(只用于 Android Studio +// 还原 Compose 组名);离线构建拿不到它,release 栈另有 mapping.txt,这里关掉。 +composeCompiler { + includeComposeMappingFile.set(false) +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } +} + +// lint 规则类路径(只找依赖里打包的 lint.jar)不带 Android 平台属性,会把 material-icons-core +// 解析成 -desktop 变体;该变体不含 lint 规则也不进 APK,离线缓存里没有,排除即可。 +configurations.matching { it.name.endsWith("LintChecksClasspath") }.configureEach { + exclude(group = "androidx.compose.material", module = "material-icons-core-desktop") +} + +dependencies { + implementation(project(":core")) + + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.lifecycle.viewmodel.compose) + + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.material.icons.core) + implementation(libs.androidx.navigation.compose) + + implementation(libs.androidx.datastore.preferences) + implementation(libs.coil.compose) + implementation(libs.kotlinx.serialization.json) + implementation(libs.kotlinx.coroutines.android) + + debugImplementation(libs.androidx.compose.ui.tooling) + debugImplementation(libs.androidx.compose.ui.test.manifest) + + testImplementation(libs.junit4) + testImplementation(libs.robolectric) + testImplementation(libs.androidx.test.core) + testImplementation(libs.kotlinx.coroutines.test) + + // 中转站搜索栏的界面行为单测(Robolectric + Compose 语义树)。 + testImplementation(platform(libs.androidx.compose.bom)) + testImplementation(libs.androidx.compose.ui.test.junit4) + + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.test.ext.junit) + androidTestImplementation(libs.androidx.test.runner) + androidTestImplementation(libs.androidx.test.espresso.core) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 00000000..5a9ad666 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,47 @@ +# 微信流 release 的 R8 规则(A4.9)。 +# 依赖库(kotlinx.serialization 1.7+、DataStore、Compose、Coil、AndroidX)自带 consumer 规则; +# 这里只补本项目自身需要的,以及对序列化的保守兜底——JSON 字段名要与 Mac / iOS 一致, +# 混淆掉 @Serializable 类会导致跨端清单(manifest.json、state.json、scenes.json…)读写失败。 + +# 崩溃栈可读:保留行号,源文件名统一成 SourceFile。 +-keepattributes SourceFile,LineNumberTable +-renamesourcefileattribute SourceFile + +# ---- kotlinx.serialization(:core 与 :app 的 @Serializable 类)---- +-keepattributes *Annotation*, InnerClasses, Signature, Exceptions, EnclosingMethod +-dontnote kotlinx.serialization.** + +# 生成的 $serializer 与 Companion.serializer() +-keepclassmembers @kotlinx.serialization.Serializable class com.xiangming.wechatbridge.** { + static ** Companion; + static **$* *; + *** Companion; + kotlinx.serialization.KSerializer serializer(...); +} +-keepclassmembers class com.xiangming.wechatbridge.**$Companion { + kotlinx.serialization.KSerializer serializer(...); +} +-keep,includedescriptorclasses class com.xiangming.wechatbridge.**$$serializer { *; } +# 枚举的 @SerialName 通过生成的描述符读取,保留枚举值名以防万一。 +-keepclassmembers enum com.xiangming.wechatbridge.** { + ; + public static **[] values(); + public static ** valueOf(java.lang.String); +} + +# ---- Manifest 组件:activity-alias 的 targetActivity、receiver、provider ---- +# AAPT 会为 Manifest 里的类生成 keep 规则;这里显式再写一遍,避免以后改成反射/字符串引用时漏掉。 +-keep class com.xiangming.wechatbridge.App { (); } +-keep class com.xiangming.wechatbridge.MainActivity { (); } +-keep class com.xiangming.wechatbridge.receive.ShareReceiverActivity { (); } +-keep class com.xiangming.wechatbridge.deliver.ShareFileProvider { (); } +-keep class com.xiangming.wechatbridge.notify.CollectActionReceiver { (); } + +# ---- DataStore Preferences ---- +# DataStore 的 protobuf-lite 实现靠字段名反射;库自带规则,这里兜底。 +-keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite { + ; +} + +# ---- Compose ---- +# Compose 运行时与 Material3 自带规则,无需额外配置。 diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000..2682348a --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,16 @@ + + + + + + + diff --git a/android/app/src/debug/assets/fixtures/files-only.zip b/android/app/src/debug/assets/fixtures/files-only.zip new file mode 100644 index 00000000..41fa009d Binary files /dev/null and b/android/app/src/debug/assets/fixtures/files-only.zip differ diff --git a/android/app/src/debug/assets/fixtures/group-a-later.zip b/android/app/src/debug/assets/fixtures/group-a-later.zip new file mode 100644 index 00000000..4fd730e2 Binary files /dev/null and b/android/app/src/debug/assets/fixtures/group-a-later.zip differ diff --git a/android/app/src/debug/assets/fixtures/group-a.zip b/android/app/src/debug/assets/fixtures/group-a.zip new file mode 100644 index 00000000..2fc1e6ce Binary files /dev/null and b/android/app/src/debug/assets/fixtures/group-a.zip differ diff --git a/android/app/src/debug/assets/fixtures/interleave.zip b/android/app/src/debug/assets/fixtures/interleave.zip new file mode 100644 index 00000000..14f99a98 Binary files /dev/null and b/android/app/src/debug/assets/fixtures/interleave.zip differ diff --git a/android/app/src/debug/assets/fixtures/text-note.zip b/android/app/src/debug/assets/fixtures/text-note.zip new file mode 100644 index 00000000..40f69765 Binary files /dev/null and b/android/app/src/debug/assets/fixtures/text-note.zip differ diff --git a/android/app/src/debug/kotlin/com/xiangming/wechatbridge/debug/ProbeActivity.kt b/android/app/src/debug/kotlin/com/xiangming/wechatbridge/debug/ProbeActivity.kt new file mode 100644 index 00000000..f3273cd1 --- /dev/null +++ b/android/app/src/debug/kotlin/com/xiangming/wechatbridge/debug/ProbeActivity.kt @@ -0,0 +1,190 @@ +package com.xiangming.wechatbridge.debug + +import androidx.activity.ComponentActivity +import android.os.Bundle +import android.util.Log +import android.widget.ScrollView +import android.widget.TextView +import androidx.lifecycle.lifecycleScope +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.core.archive.WeChatArchive +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import com.xiangming.wechatbridge.deliver.DeliveryRequest +import com.xiangming.wechatbridge.deliver.Destination +import com.xiangming.wechatbridge.deliver.DispatchResult +import com.xiangming.wechatbridge.deliver.IntentDispatcher +import com.xiangming.wechatbridge.deliver.OutgoingFile +import com.xiangming.wechatbridge.deliver.PromptClipboard +import com.xiangming.wechatbridge.deliver.ShareFileProvider +import com.xiangming.wechatbridge.deliver.TargetResolver +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ShareItem +import kotlinx.coroutines.launch +import java.io.File +import java.io.InputStream + +/** + * Delivery probe, debug builds only (android-plan A0.5). Driven from adb: + * + * ``` + * adb shell am start -n com.xiangming.wechatbridge/.debug.ProbeActivity \ + * --es target chatgpt --es format zip --es fixture group-a.zip + * ``` + * + * Send extras: + * - `target`: a built-in id (`chatgpt`, `claude`, `gemini`, …; `other` = chooser), + * or omit it and give `pkg` (+ optional `activity`) for any app. + * - `format`: `zip` (application/zip), `octet` (the ZIP as octet-stream), + * `txt` (the transcript file), `images` (the images, SEND_MULTIPLE image wildcard), + * `mixed` (TXT + images, SEND_MULTIPLE full wildcard), `inline` (transcript as EXTRA_TEXT). + * - `fixture`: a file in `assets/fixtures/` (default `group-a.zip`). + * - `prompt`: EXTRA_TEXT alongside the files, also copied to the clipboard. + * - `--ez chooser true`: skip straight to the system chooser. + * + * Import extras: `--es import ` takes `/` + * (push it to `/sdcard/Android/data/com.xiangming.wechatbridge/files/`) as + * one received share through `UriImporter`; `--ez collect true` for the + * collect entry. + * + * Every line is logged under tag `WBProbe`. + */ +class ProbeActivity : ComponentActivity() { + private lateinit var output: TextView + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + output = TextView(this).apply { setPadding(32, 96, 32, 32); textSize = 14f } + setContentView(ScrollView(this).apply { addView(output) }) + if (savedInstanceState != null) return + run() + } + + /** A second `am start` while the probe is on top lands here instead of onCreate. */ + override fun onNewIntent(intent: android.content.Intent) { + super.onNewIntent(intent) + setIntent(intent) + output.text = "" + run() + } + + private fun run() { + val importPath = intent.getStringExtra("import") + if (importPath != null) runImport(importPath, intent.getBooleanExtra("collect", false)) + else runSend() + } + + private fun log(line: String) { + Log.i(TAG, line) + output.append(line + "\n") + } + + // MARK: send + + private fun runSend() { + val targetId = intent.getStringExtra("target") + val pkg = intent.getStringExtra("pkg") + val format = intent.getStringExtra("format") ?: "zip" + val fixture = intent.getStringExtra("fixture") ?: "group-a.zip" + val prompt = intent.getStringExtra("prompt") + val forceChooser = intent.getBooleanExtra("chooser", false) + + val destination: Destination = when { + forceChooser -> Destination.Chooser + pkg != null -> Destination.App(listOf(pkg), intent.getStringExtra("activity")) + targetId != null -> { + val profile = BuiltInTargets.byId(targetId) ?: return log("ERROR unknown target $targetId") + Destination.of(profile) ?: return log("ERROR target $targetId is a SAF writer, not an Intent target") + } + else -> return log("ERROR give --es target or --es pkg ") + } + log("send target=${targetId ?: pkg} format=$format fixture=$fixture destination=$destination") + + val request = try { + prepare(format, fixture, prompt) + } catch (e: Exception) { + return log("ERROR preparing fixture: ${e.javaClass.simpleName}: ${e.message}") + } + log("files=${request.files.map { "${it.displayName ?: it.file.name} (${it.mimeType})" }} text=${request.text?.length ?: 0} chars") + + if (prompt != null) log("clipboard: ${PromptClipboard(this).copy(prompt)}") + + val result = IntentDispatcher(TargetResolver(this)).dispatch(this, request, destination) + log("RESULT $result") + if (result is DispatchResult.Sent) finish() + } + + private fun prepare(format: String, fixture: String, prompt: String?): DeliveryRequest { + require(!fixture.contains('/')) { "fixture is a file name in assets/fixtures/" } + val dir = ShareFileProvider.newDeliveryDir(this, "probe-${System.currentTimeMillis()}") + val zip = File(dir, fixture) + assets.open("fixtures/$fixture").use { input -> zip.outputStream().use { input.copyTo(it) } } + if (format == "zip" || format == "octet") { + val mime = if (format == "zip") "application/zip" else "application/octet-stream" + return DeliveryRequest(listOf(OutgoingFile(zip, mime)), text = prompt) + } + + val unpacked = File(dir, "unpacked").apply { mkdirs() } + val paths = WeChatArchive.extract(zip, unpacked) + val files = paths.map { File(unpacked, it) }.filter { it.isFile } + val txt = files.filter { it.extension.equals("txt", ignoreCase = true) } + val images = files.filter { imageMime(it) != null } + fun outgoingTxt() = txt.map { OutgoingFile(it, "text/plain") } + fun outgoingImages() = images.map { OutgoingFile(it, imageMime(it)!!) } + return when (format) { + "txt" -> DeliveryRequest(outgoingTxt(), text = prompt) + "images" -> DeliveryRequest(outgoingImages(), text = prompt) + "mixed" -> DeliveryRequest(outgoingTxt() + outgoingImages(), text = prompt) + "inline" -> { + val body = txt.joinToString("\n\n") { it.readText() } + DeliveryRequest(emptyList(), text = listOfNotNull(prompt, body).joinToString("\n\n")) + } + else -> throw IllegalArgumentException("unknown format $format") + } + } + + private fun imageMime(file: File): String? = when (file.extension.lowercase()) { + "png" -> "image/png" + "jpg", "jpeg" -> "image/jpeg" + "gif" -> "image/gif" + "webp" -> "image/webp" + "heic" -> "image/heic" + else -> null + } + + // MARK: import + + private fun runImport(relative: String, collect: Boolean) { + val root = getExternalFilesDir(null) ?: return log("ERROR no external files dir") + val file = File(root, relative) + val inside = runCatching { file.canonicalPath.startsWith(root.canonicalPath + File.separator) }.getOrDefault(false) + if (!inside) return log("ERROR $relative is outside ${root.path}") + if (!file.isFile) return log("ERROR not a file: ${file.path}") + log("import ${file.name} (${file.length()} B) collect=$collect") + + val item = object : ShareItem.Stream { + override val mimeType: String? = when (file.extension.lowercase()) { + "zip" -> "application/zip" + "txt" -> "text/plain" + else -> imageMime(file) ?: "application/octet-stream" + } + override val loadStrategy = LoadStrategy.FILE_URL + override fun displayName(): String = file.name + override fun open(): InputStream = file.inputStream() + } + val importer = (application as App).container.uriImporter + lifecycleScope.launch { + when (val outcome = importer.import(listOf(item), collect)) { + is ImportOutcome.Saved -> log( + "RESULT Saved batch=${outcome.batchId} items=${outcome.items.size} " + + "archives=${outcome.archives} records=${outcome.records.size} dir=${outcome.directory.path}", + ) + is ImportOutcome.Failed -> log("RESULT Failed ${outcome.failure}") + } + } + } + + private companion object { + const val TAG = "WBProbe" + } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..ca4853bd --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/App.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/App.kt new file mode 100644 index 00000000..d9df766d --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/App.kt @@ -0,0 +1,19 @@ +package com.xiangming.wechatbridge + +import android.app.Application +import com.xiangming.wechatbridge.bubble.BubbleService +import com.xiangming.wechatbridge.notify.CollectNotification + +class App : Application() { + lateinit var container: AppContainer + private set + + override fun onCreate() { + super.onCreate() + container = AppContainer(this) + // 进行中的收集在进程重启后恢复常驻通知,之后通知跟着收集记录走。 + CollectNotification.restore(this) + // 悬浮球开着且有悬浮窗权限:拉起前台服务(后台启动被系统拒绝时,下次回到前台再试)。 + BubbleService.sync(this) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppContainer.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppContainer.kt new file mode 100644 index 00000000..7892240e --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppContainer.kt @@ -0,0 +1,91 @@ +package com.xiangming.wechatbridge + +import android.content.Context +import android.webkit.MimeTypeMap +import androidx.core.content.pm.PackageInfoCompat +import com.xiangming.wechatbridge.bubble.BubbleSettings +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.data.Preferences +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.data.SceneStore +import com.xiangming.wechatbridge.data.SummaryCache +import com.xiangming.wechatbridge.receive.UriImporter +import com.xiangming.wechatbridge.saf.TreeStore +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.first +import java.io.File +import com.xiangming.wechatbridge.deliver.Dispatch +import com.xiangming.wechatbridge.deliver.IntentDispatch +import com.xiangming.wechatbridge.deliver.IntentDispatcher +import com.xiangming.wechatbridge.deliver.PromptClipboard +import com.xiangming.wechatbridge.deliver.TargetResolver + +/** + * 手写依赖容器(不引入 Hilt / KSP)。 + * + * 槽位由骨架任务 A0.2 一次预留;后续任务只在自己负责的槽位里填实现, + * 需要新增槽位时向主线执行者提出(见 android-plan §5.8)。 + */ +class AppContainer(context: Context) { + val appContext: Context = context.applicationContext + + /** Process-lifetime scope for work that must outlive screens (store loads, the undo timer). */ + val appScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + + // data/ —— RelayStore:中转站批次读写(A2.1)。首次取用时加载并按保留天数清理一次。 + val relayStore: RelayStore by lazy { + RelayStore( + inbox = inbox, + relayFilesRoot = File(appContext.cacheDir, "Relay"), + deliveriesDirectory = File(appContext.cacheDir, "deliveries"), + scope = appScope, + summaryCache = summaryCache, + ).also { store -> store.start { preferences.retentionDays.first() } } + } + + // data/ —— Preferences:DataStore 偏好(目标顺序、隐藏、格式覆盖、最近目标、保留天数、引导)(A2.1) + val preferences: Preferences by lazy { Preferences.create(appContext) } + + // data/ —— SummaryCache:卡片摘要缓存(与 iOS 一致,放在批次目录的 relay-cache.json)(A2.1) + val summaryCache: SummaryCache by lazy { SummaryCache() } + + // receive/ —— Inbox:/inbox(staging / ready / diagnostics,android-plan §3.3)(A1.10) + val inbox: Inbox by lazy { Inbox(File(appContext.filesDir, "inbox")) } + + // receive/ —— UriImporter:接收分享并写入 staging(A1.10) + val uriImporter: UriImporter by lazy { + UriImporter( + inbox = inbox, + buildVersion = buildVersion(), + extensionLookup = { MimeTypeMap.getSingleton().getExtensionFromMimeType(it) }, + ) + } + + /** versionCode, like iOS CFBundleVersion in diagnostics; "?" when unreadable. */ + private fun buildVersion(): String = runCatching { + @Suppress("DEPRECATION") + val info = appContext.packageManager.getPackageInfo(appContext.packageName, 0) + PackageInfoCompat.getLongVersionCode(info).toString() + }.getOrDefault("?") + + // deliver/ —— TargetResolver / IntentDispatcher:投递目标与 Intent 发送(A3.x) + val targetResolver: TargetResolver by lazy { TargetResolver(appContext) } + val intentDispatcher: IntentDispatcher by lazy { IntentDispatcher(targetResolver) } + val promptClipboard: PromptClipboard by lazy { PromptClipboard(appContext) } + + /** What DeliverViewModel sends through; replaceable in tests (A3.4). */ + val dispatch: Dispatch by lazy { IntentDispatch(intentDispatcher) } + + // saf/ —— TreeStore:Obsidian 库与默认文件夹的 SAF 目录、持久授权与失效检测(A4.1) + // 读写走 ContentResolver:调用方在 IO 线程上用。 + val treeStore: TreeStore by lazy { TreeStore.create(appContext) } + + // scene/ —— 场景与群记忆存储(/scenes.json、group-memories.json,JSON 与 iOS 一致)(A3.4) + // 首次读文件发生在第一次调用时;调用方在 IO 线程上用。 + val sceneStore: SceneStore by lazy { SceneStore(appContext.filesDir) } + + // bubble/ —— 悬浮球开关与位置(SharedPreferences,接收入口和 App 启动时同步读) + val bubbleSettings: BubbleSettings by lazy { BubbleSettings(appContext) } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppNav.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppNav.kt new file mode 100644 index 00000000..66c86c8f --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/AppNav.kt @@ -0,0 +1,487 @@ +package com.xiangming.wechatbridge + +import androidx.annotation.StringRes +import androidx.compose.animation.AnimatedContentTransitionScope +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.navigation.NavBackStackEntry +import androidx.navigation.NavHostController +import androidx.navigation.NavType +import androidx.navigation.compose.NavHost +import androidx.navigation.compose.composable +import androidx.navigation.compose.currentBackStackEntryAsState +import androidx.navigation.compose.rememberNavController +import androidx.navigation.navArgument +import com.xiangming.wechatbridge.receive.DeliverLaunch +import com.xiangming.wechatbridge.ui.collection.CollectionScreen +import com.xiangming.wechatbridge.ui.deliver.DeliverScreen +import com.xiangming.wechatbridge.ui.detail.DetailScreen +import com.xiangming.wechatbridge.ui.onboarding.OnboardingScreen +import com.xiangming.wechatbridge.ui.relay.RelayScreen +import com.xiangming.wechatbridge.ui.scenes.ScenesScreen +import com.xiangming.wechatbridge.ui.settings.SettingsScreen +import com.xiangming.wechatbridge.ui.settings.TargetsScreen +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.BridgeBottomBarScrim +import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale + +/** + * 全部路由与底部 3 Tab 导航壳。 + */ +object Routes { + const val RELAY = "relay" + const val DETAIL = "detail/{batchId}" + const val DELIVER = "deliver/{batchIds}" + const val SCENES = "scenes" + const val SETTINGS = "settings" + const val TARGETS = "settings/targets" + const val ONBOARDING = "onboarding" + const val COLLECTION = "collection/{id}" + + const val ARG_BATCH_ID = "batchId" + const val ARG_BATCH_IDS = "batchIds" + const val ARG_COLLECTION_ID = "id" + + /** 批次 ID 是 UUID,不含逗号,用逗号连接多个。 */ + private const val ID_SEPARATOR = "," + + fun detail(batchId: String) = "detail/$batchId" + fun deliver(batchIds: List) = "deliver/" + batchIds.joinToString(ID_SEPARATOR) + fun collection(id: String) = "collection/$id" + + fun parseBatchIds(raw: String?): List = + raw.orEmpty().split(ID_SEPARATOR).filter { it.isNotBlank() } +} + +private val TopLevelRoutes = setOf(Routes.RELAY, Routes.SCENES, Routes.SETTINGS) + +private data class BottomTabItem( + val route: String, + @param:StringRes val labelRes: Int, + val icon: ImageVector, +) + +private val BottomTabs = listOf( + BottomTabItem(Routes.RELAY, R.string.nav_relay, AppIcons.NavRelay), + BottomTabItem(Routes.SCENES, R.string.nav_scenes, AppIcons.NavScenes), + BottomTabItem(Routes.SETTINGS, R.string.nav_settings, AppIcons.NavSettings), +) + +/** + * The target the delivery panel should preselect when it was opened by + * 「投给上次目标」 (a [DeliverLaunch]); null otherwise. Provided around + * `DeliverScreen`, which passes it to `DeliverViewModel.create(initialTargetId = ...)`. + */ +val LocalInitialTargetId = staticCompositionLocalOf { null } + +/** Key in the deliver entry's SavedStateHandle, so the preselection survives recreation. */ +private const val INITIAL_TARGET_KEY = "initialTargetId" + +@Composable +fun AppNav( + container: AppContainer, + navController: NavHostController = rememberNavController(), + startDestination: String = Routes.RELAY, + /** Open the delivery panel on arrival (receipt 「投给上次目标」); [onLaunchConsumed] then clears it. */ + launch: DeliverLaunch? = null, + onLaunchConsumed: () -> Unit = {}, +) { + if (launch != null) { + LaunchedEffect(launch) { + navController.navigate(Routes.deliver(launch.batchIds)) { launchSingleTop = true } + navController.currentBackStackEntry?.savedStateHandle?.set(INITIAL_TARGET_KEY, launch.targetId) + onLaunchConsumed() + } + } + + val backStackEntry by navController.currentBackStackEntryAsState() + val currentRoute = backStackEntry?.destination?.route + val showBottomBar = currentRoute in TopLevelRoutes + + val entries by container.relayStore.entries.collectAsStateWithLifecycle() + val undeliveredCount = remember(entries) { entries.count { !it.isDelivered } } + + fun switchTab(route: String) { + if (navController.currentDestination?.route == route) return + if (route == Routes.RELAY) { + if (navController.popBackStack(Routes.RELAY, inclusive = false)) return + navController.navigate(Routes.RELAY) { + launchSingleTop = true + } + return + } + navController.navigate(route) { + popUpTo(Routes.RELAY) { + saveState = true + } + launchSingleTop = true + restoreState = true + } + } + + Box(modifier = Modifier.fillMaxSize()) { + NavHost( + navController = navController, + startDestination = startDestination, + modifier = Modifier.fillMaxSize(), + ) { + composable( + route = Routes.RELAY, + enterTransition = { topLevelEnter() }, + exitTransition = { topLevelExit() }, + popEnterTransition = { topLevelPopEnter() }, + popExitTransition = { topLevelPopExit() }, + ) { + RelayScreen( + onOpenBatch = { navController.navigate(Routes.detail(it)) }, + onDeliver = { navController.navigate(Routes.deliver(it)) }, + onOpenCollection = { navController.navigate(Routes.collection(it)) }, + onOpenScenes = { switchTab(Routes.SCENES) }, + onOpenSettings = { switchTab(Routes.SETTINGS) }, + ) + } + composable( + route = Routes.DETAIL, + arguments = listOf(navArgument(Routes.ARG_BATCH_ID) { type = NavType.StringType }), + enterTransition = { AppMotion.pushEnter }, + exitTransition = { + if (targetState.destination.route == Routes.DELIVER) ExitTransition.None else AppMotion.pushExit + }, + popEnterTransition = { + if (initialState.destination.route == Routes.DELIVER) EnterTransition.None else AppMotion.popEnter + }, + popExitTransition = { AppMotion.popExit }, + ) { entry -> + DetailScreen( + batchId = entry.arguments?.getString(Routes.ARG_BATCH_ID).orEmpty(), + onBack = { navController.popBackStack() }, + onDeliver = { navController.navigate(Routes.deliver(listOf(it))) }, + ) + } + composable( + route = Routes.DELIVER, + arguments = listOf(navArgument(Routes.ARG_BATCH_IDS) { type = NavType.StringType }), + enterTransition = { AppMotion.sheetEnter }, + exitTransition = { AppMotion.sheetExit }, + popEnterTransition = { AppMotion.sheetEnter }, + popExitTransition = { AppMotion.sheetExit }, + ) { entry -> + CompositionLocalProvider( + LocalInitialTargetId provides entry.savedStateHandle.get(INITIAL_TARGET_KEY), + ) { + DeliverScreen( + batchIds = Routes.parseBatchIds(entry.arguments?.getString(Routes.ARG_BATCH_IDS)), + onBack = { navController.popBackStack() }, + onDone = { navController.popBackStack(Routes.RELAY, inclusive = false) }, + ) + } + } + composable( + route = Routes.SCENES, + enterTransition = { topLevelEnter() }, + exitTransition = { topLevelExit() }, + popEnterTransition = { topLevelPopEnter() }, + popExitTransition = { topLevelPopExit() }, + ) { + ScenesScreen(onBack = { switchTab(Routes.RELAY) }) + } + composable( + route = Routes.SETTINGS, + enterTransition = { topLevelEnter() }, + exitTransition = { topLevelExit() }, + popEnterTransition = { topLevelPopEnter() }, + popExitTransition = { topLevelPopExit() }, + ) { + SettingsScreen( + onBack = { switchTab(Routes.RELAY) }, + onOpenScenes = { switchTab(Routes.SCENES) }, + onOpenOnboarding = { navController.navigate(Routes.ONBOARDING) }, + onOpenTargets = { navController.navigate(Routes.TARGETS) }, + ) + } + composable( + route = Routes.TARGETS, + enterTransition = { AppMotion.pushEnter }, + exitTransition = { AppMotion.pushExit }, + popEnterTransition = { AppMotion.popEnter }, + popExitTransition = { AppMotion.popExit }, + ) { + TargetsScreen(onBack = { navController.popBackStack() }) + } + composable( + route = Routes.ONBOARDING, + enterTransition = { AppMotion.pushEnter }, + exitTransition = { AppMotion.pushExit }, + popEnterTransition = { AppMotion.popEnter }, + popExitTransition = { AppMotion.popExit }, + ) { + OnboardingScreen( + onFinish = { + // 从设置里重开的引导:回到设置;首装的引导:换成中转站。 + if (navController.previousBackStackEntry != null) { + navController.popBackStack() + return@OnboardingScreen + } + navController.navigate(Routes.RELAY) { + popUpTo(Routes.ONBOARDING) { inclusive = true } + launchSingleTop = true + } + }, + ) + } + composable( + route = Routes.COLLECTION, + arguments = listOf(navArgument(Routes.ARG_COLLECTION_ID) { type = NavType.StringType }), + enterTransition = { AppMotion.pushEnter }, + exitTransition = { + if (targetState.destination.route == Routes.DELIVER) ExitTransition.None else AppMotion.pushExit + }, + popEnterTransition = { + if (initialState.destination.route == Routes.DELIVER) EnterTransition.None else AppMotion.popEnter + }, + popExitTransition = { AppMotion.popExit }, + ) { entry -> + CollectionScreen( + collectionId = entry.arguments?.getString(Routes.ARG_COLLECTION_ID).orEmpty(), + onBack = { navController.popBackStack() }, + onDeliver = { navController.navigate(Routes.deliver(it)) }, + ) + } + } + + if (showBottomBar) { + val navBottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + BridgeBottomBarScrim( + height = 100.dp + navBottom, + modifier = Modifier.align(Alignment.BottomCenter), + ) + } + AnimatedVisibility( + visible = showBottomBar, + enter = slideInVertically(tween(AppMotion.PAGE_SLIDE_MS)) { it } + fadeIn(tween(150)), + exit = slideOutVertically(tween(200)) { it } + fadeOut(tween(120)), + modifier = Modifier + .align(Alignment.BottomCenter) + .navigationBarsPadding() + .padding(horizontal = 24.dp, vertical = 10.dp), + ) { + AppBottomBar( + currentRoute = currentRoute, + undeliveredCount = undeliveredCount, + onSelect = { switchTab(it) }, + ) + } + } +} + +private fun AnimatedContentTransitionScope.topLevelEnter(): EnterTransition = + if (initialState.destination.route in TopLevelRoutes) AppMotion.tabEnter else AppMotion.popEnter + +private fun AnimatedContentTransitionScope.topLevelExit(): ExitTransition = + when (targetState.destination.route) { + in TopLevelRoutes -> AppMotion.tabExit + Routes.DELIVER -> ExitTransition.None + else -> AppMotion.pushExit + } + +private fun AnimatedContentTransitionScope.topLevelPopEnter(): EnterTransition = + when (initialState.destination.route) { + in TopLevelRoutes -> AppMotion.tabEnter + Routes.DELIVER -> EnterTransition.None + else -> AppMotion.popEnter + } + +private fun AnimatedContentTransitionScope.topLevelPopExit(): ExitTransition = + if (targetState.destination.route in TopLevelRoutes) AppMotion.tabExit else AppMotion.popExit + +@Composable +private fun AppBottomBar( + currentRoute: String?, + undeliveredCount: Int, + onSelect: (String) -> Unit, +) { + BridgeGlassSurface( + shape = CircleShape, + shadowElevation = 14.dp, + modifier = Modifier + .fillMaxWidth() + .height(64.dp), + ) { + Row( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = 8.dp, vertical = 5.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + for (tab in BottomTabs) { + val isSelected = currentRoute == tab.route + val badgeCount = if (tab.route == Routes.RELAY) undeliveredCount else 0 + BottomTabButton( + tab = tab, + selected = isSelected, + badgeCount = badgeCount, + onClick = { onSelect(tab.route) }, + modifier = Modifier.weight(1f), + ) + } + } + } +} + +@Composable +private fun BottomTabButton( + tab: BottomTabItem, + selected: Boolean, + badgeCount: Int, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val appColors = LocalAppColors.current + val interactionSource = remember { MutableInteractionSource() } + val contentColor by animateColorAsState( + targetValue = if (selected) MaterialTheme.colorScheme.primary else appColors.onSurfaceMuted, + animationSpec = tween(160), + label = "tabColor", + ) + val pillWidth by animateDpAsState( + targetValue = if (selected) 56.dp else 20.dp, + animationSpec = AppMotion.snappySpring(), + label = "tabPillWidth", + ) + val pillAlpha by animateFloatAsState( + targetValue = if (selected) 1f else 0f, + animationSpec = tween(150), + label = "tabPillAlpha", + ) + val label = stringResource(tab.labelRes) + + Column( + modifier = modifier + .fillMaxHeight() + .clickable( + interactionSource = interactionSource, + indication = null, + role = Role.Tab, + onClick = onClick, + ) + .semantics { this.selected = selected } + .pressScale(interactionSource, targetScale = 0.94f), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box( + modifier = Modifier.height(30.dp), + contentAlignment = Alignment.Center, + ) { + Box( + modifier = Modifier + .width(pillWidth) + .height(30.dp) + .alpha(pillAlpha) + .clip(CircleShape) + .background(appColors.primarySoft), + ) + Icon( + imageVector = tab.icon, + contentDescription = null, + tint = contentColor, + modifier = Modifier.size(21.dp), + ) + androidx.compose.animation.AnimatedVisibility( + visible = badgeCount > 0, + enter = scaleIn(AppMotion.playfulSpring()) + fadeIn(tween(120)), + exit = scaleOut(tween(120)) + fadeOut(tween(120)), + modifier = Modifier + .align(Alignment.TopEnd) + .offset(x = 12.dp, y = (-2).dp), + ) { + Box( + modifier = Modifier + .defaultMinSize(minWidth = 16.dp, minHeight = 16.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.primary) + .padding(horizontal = 4.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = if (badgeCount > 99) "99+" else badgeCount.toString(), + color = MaterialTheme.colorScheme.onPrimary, + fontSize = 10.sp, + lineHeight = 12.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + ) + } + } + } + Spacer(Modifier.height(2.dp)) + Text( + text = label, + style = MaterialTheme.typography.labelSmall, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, + color = contentColor, + maxLines = 1, + ) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/MainActivity.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/MainActivity.kt new file mode 100644 index 00000000..66581803 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/MainActivity.kt @@ -0,0 +1,110 @@ +package com.xiangming.wechatbridge + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.lifecycleScope +import com.xiangming.wechatbridge.bubble.BubbleService +import com.xiangming.wechatbridge.notify.CollectNotification +import com.xiangming.wechatbridge.notify.QuickDeliverNotification +import com.xiangming.wechatbridge.receive.ActivityDropPermissions +import com.xiangming.wechatbridge.receive.DeliverLaunch +import com.xiangming.wechatbridge.receive.DropReceiver +import com.xiangming.wechatbridge.ui.drop.DropHost +import com.xiangming.wechatbridge.ui.drop.LocalDropHost +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme + +class MainActivity : ComponentActivity() { + /** A 「投给上次目标」 request not yet acted on; cleared once AppNav has navigated. */ + private val pendingLaunch = mutableStateOf(null) + + /** + * Drops from other apps (small window, split screen). Scoped to this + * Activity: the URI grants end with it, so a copy still running when it is + * destroyed is cancelled and its staging discarded. + */ + private val dropHost: DropHost by lazy { + val container = (application as App).container + DropHost( + receiver = DropReceiver( + importer = container.uriImporter, + scope = lifecycleScope, + reload = container.relayStore::reload, + joinCollection = container.relayStore::joinCollection, + onCollected = { CollectNotification.sync(application, container.relayStore) }, + ), + permissions = ActivityDropPermissions(this), + context = this, + ) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val container = (application as App).container + // A recreated Activity has its back stack restored; the request was handled already. + if (savedInstanceState == null) pendingLaunch.value = DeliverLaunch.parse(intent)?.let(::consume) + // Pick up batches received while away; commit a pending delete before + // the process can be killed, or it would come back. + lifecycle.addObserver(object : DefaultLifecycleObserver { + override fun onStart(owner: LifecycleOwner) { + container.relayStore.refresh() + // In front now, so a bubble start the system refused from the background goes through. + BubbleService.sync(this@MainActivity) + } + override fun onStop(owner: LifecycleOwner) = container.relayStore.flushDeletion() + }) + setContent { + WeChatBridgeTheme { + // 首装先走引导;读偏好要一点时间,读完前只画背景,免得中转站闪一下。 + // 带着投递请求进来(通知、收据卡)时直接去投递,不拦引导。 + val onboardingDone by produceState(null) { + value = runCatching { container.preferences.current().onboardingDone }.getOrDefault(true) + } + when (val done = onboardingDone) { + null -> Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {} + else -> CompositionLocalProvider(LocalDropHost provides dropHost) { + AppNav( + container = container, + startDestination = remember { + if (done || pendingLaunch.value != null) Routes.RELAY else Routes.ONBOARDING + }, + launch = pendingLaunch.value, + onLaunchConsumed = { pendingLaunch.value = null }, + ) + } + } + } + } + } + + /** singleTask: a receipt tap while the app is open arrives here. */ + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + DeliverLaunch.parse(intent)?.let { pendingLaunch.value = consume(it) } + } + + /** + * Dismisses the quick-deliver notification and marks the batches used. A + * relaunch from recents (nothing first-time) opens the panel without + * preselecting the target, so it never sends twice. + */ + private fun consume(launch: DeliverLaunch): DeliverLaunch { + val fresh = QuickDeliverNotification.onLaunched(this, launch) + return if (fresh.isEmpty() && launch.targetId != null) launch.copy(targetId = null) else launch + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDrag.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDrag.kt new file mode 100644 index 00000000..3d21654d --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDrag.kt @@ -0,0 +1,150 @@ +package com.xiangming.wechatbridge.bubble + +import android.view.WindowManager +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.DeliveryPlanException +import com.xiangming.wechatbridge.core.deliver.DeliveryPlanner +import com.xiangming.wechatbridge.core.deliver.Evidence +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import com.xiangming.wechatbridge.core.scene.GroupName +import com.xiangming.wechatbridge.core.scene.ScenePrompt +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.core.transcript.BatchInsights +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.data.SceneStore +import com.xiangming.wechatbridge.deliver.SceneBinding +import java.io.File +import java.time.ZoneId +import com.xiangming.wechatbridge.core.deliver.DeliveryRequest as PlanRequest + +/** What a long press on a staged row (or 「全部合并投递」) can drag out. */ +sealed interface DragText { + data class Ready(val text: String) : DragText + + /** Only attachments: nothing readable to drop into an input box. */ + data object NoText : DragText + + /** Over [DeliveryPlanner.INLINE_TEXT_LIMIT], where delivery would send a file instead. */ + data object TooLarge : DragText + + /** Reading the batch failed. */ + data object Failed : DragText +} + +/** + * The text a drag (or the row's copy button) carries: exactly what the + * delivery panel puts in `EXTRA_TEXT` on the inline-text route — the scene + * prompt, a blank line, then [DeliveryPlanner]'s inline body (one transcript, + * several merged by time, or a shared text / link note as it is). + */ +object BubbleDragText { + /** + * A text-only target for [DeliveryPlanner]: inline text, no images. Never + * shown or sent to; it only selects the route. + */ + internal val TEXT_ONLY = TargetProfile( + id = "bubble-drag", + displayNameKey = null, + kind = TargetKind.CHOOSER, + formats = listOf(DeliveryFormat.INLINE_TEXT), + formatEvidence = Evidence.DECLARED, + ) + + /** + * Known to hold nothing readable: summarized as plain files (no + * transcript) and no shared text / link note. A batch not summarized yet + * is not judged here; [build] finds out. + */ + fun isTextless(entry: RelayEntry): Boolean { + if (entry.batch.items.isEmpty()) return true + val summary = entry.summary ?: return false + if (summary.kind != RelaySummary.Kind.FILES) return false + return entry.batch.items.none { it.contentType == ShareOrigin.NOTE_CONTENT_TYPE } + } + + /** Every one textless: say so without starting a drag. */ + fun allTextless(entries: List): Boolean = entries.all(::isTextless) + + /** 「全部合并投递」's order: oldest first, as [BubbleStaging.mergeIds]. */ + fun mergeOrder(staged: List): List = staged.sortedBy { it.batch.createdAt } + + /** The delivery panel's `EXTRA_TEXT`: prompt (trimmed, if any), a blank line, the body. */ + fun join(prompt: String?, body: String): String = + listOfNotNull(prompt?.trim()?.takeIf { it.isNotEmpty() }, body).joinToString("\n\n") + + /** Chat records get a scene prompt; texts and links go as they are. */ + internal fun isChat(entries: List, insights: BatchInsights): Boolean = + entries.any { it.summary?.kind == RelaySummary.Kind.CHAT } || + (entries.any { it.summary == null } && insights.senders.isNotEmpty()) + + /** + * The scene prompt the delivery panel would open with for [entries]: + * [SceneBinding.open] on the chat name or summary title and the speakers, + * falling back to the default scene; then `ScenePrompt.render` with the + * group's last summary boundary. Blocking (reads the scene files). + */ + internal fun prompt(entries: List, scenes: SceneStore, insights: BatchInsights, zone: ZoneId): String? { + val snapshot = scenes.current() + val chatName = entries.firstNotNullOfOrNull { it.batch.chatName } + val title = entries.mapNotNull { it.summary }.firstOrNull { it.kind == RelaySummary.Kind.CHAT }?.title + val opening = SceneBinding(scenes).open(chatName, title, snapshot.settings, snapshot.memories, insights.senders) + val scene = opening.resolution.scene ?: return null + val memory = opening.group.name?.let { snapshot.memories[GroupName.normalize(it)] } + return ScenePrompt.render(scene, memory?.lastSummaryAt, insights.end, zone = zone)?.trim()?.ifEmpty { null } + } + + /** + * Builds the drag text for [entries] (one batch, or the merge in the + * order given). Textless batches are left out of a merge. Blocking file + * IO: call on an IO dispatcher. [newWorkDirectory] is a fresh scratch + * directory, removed again before returning. + */ + fun build( + entries: List, + scenes: SceneStore, + newWorkDirectory: () -> File, + zone: ZoneId = ZoneId.systemDefault(), + ): DragText { + val readable = entries.filterNot(::isTextless) + if (readable.isEmpty()) return DragText.NoText + var work: File? = null + return try { + val batches = readable.map { it.batch } + val insights = runCatching { BatchInsights.read(batches.flatMap { b -> b.items.map { it.file } }, zone) } + .getOrDefault(BatchInsights.EMPTY) + val prompt = if (isChat(readable, insights)) runCatching { prompt(readable, scenes, insights, zone) }.getOrNull() else null + val dir = newWorkDirectory().also { work = it } + val planned = DeliveryPlanner.plan(PlanRequest(batches, TEXT_ONLY, prompt, DeliveryFormat.INLINE_TEXT, zone), dir) + val body = planned.inlineText + when { + body != null -> DragText.Ready(join(prompt, body)) + planned.inlineFellBackToFile -> DragText.TooLarge + else -> DragText.NoText + } + } catch (e: DeliveryPlanException) { + if (e.reason == DeliveryPlanException.Reason.NO_ARCHIVE) DragText.NoText else DragText.Failed + } catch (_: Exception) { + DragText.Failed + } finally { + work?.deleteRecursively() + } + } +} + +/** + * Window flags while a drag is out: the panel and the ball must let the drop + * through to the app underneath (not touchable) and must not hold focus, or + * the target's input box cannot take it. Afterwards the panel takes focus + * again (back closes it); the ball never does. + */ +object DragWindowFlags { + private const val DRAG_BITS = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE + + fun flags(current: Int, dragging: Boolean, focusableAtRest: Boolean): Int = when { + dragging -> current or DRAG_BITS + focusableAtRest -> current and DRAG_BITS.inv() + else -> (current and WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE.inv()) or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragShadow.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragShadow.kt new file mode 100644 index 00000000..5aad185c --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragShadow.kt @@ -0,0 +1,53 @@ +package com.xiangming.wechatbridge.bubble + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Point +import android.graphics.RectF +import android.text.TextPaint +import android.text.TextUtils +import android.util.TypedValue +import android.view.View +import kotlin.math.ceil +import kotlin.math.roundToInt + +/** Colours for the drag card, taken from the Compose theme by the panel. */ +internal data class DragShadowStyle(val background: Int, val foreground: Int) + +/** + * The shadow under the finger while a batch is dragged out: a small rounded + * card with the batch title (one line, ellipsized), not a picture of the row. + */ +internal class DragCardShadow(context: Context, title: String, private val colors: DragShadowStyle) : View.DragShadowBuilder() { + private val metrics = context.resources.displayMetrics + private fun dp(value: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, metrics) + + private val paddingX = dp(14f) + private val paddingY = dp(10f) + private val radius = dp(12f) + private val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { + color = colors.foreground + textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14f, metrics) + } + private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = colors.background } + private val text: String = TextUtils.ellipsize(title, textPaint, dp(MAX_TEXT_DP), TextUtils.TruncateAt.END).toString() + private val width = (ceil(textPaint.measureText(text)) + paddingX * 2).roundToInt().coerceAtLeast(dp(48f).roundToInt()) + private val height = (textPaint.fontMetrics.let { it.descent - it.ascent } + paddingY * 2).roundToInt() + + override fun onProvideShadowMetrics(outShadowSize: Point, outShadowTouchPoint: Point) { + outShadowSize.set(width, height) + // The finger sits at the bottom edge of the card, so the card stays visible above it. + outShadowTouchPoint.set(width / 2, (height - 1).coerceAtLeast(0)) + } + + override fun onDrawShadow(canvas: Canvas) { + canvas.drawRoundRect(RectF(0f, 0f, width.toFloat(), height.toFloat()), radius, radius, backgroundPaint) + val baseline = paddingY - textPaint.fontMetrics.ascent + canvas.drawText(text, paddingX, baseline, textPaint) + } + + private companion object { + const val MAX_TEXT_DP = 220f + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogic.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogic.kt new file mode 100644 index 00000000..00a33d0d --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogic.kt @@ -0,0 +1,232 @@ +package com.xiangming.wechatbridge.bubble + +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.receive.ReceiptUiState +import java.time.Instant +import java.util.UUID +import kotlin.math.abs +import kotlin.math.roundToInt + +/** Which screen edge the handle rests on. */ +enum class BubbleEdge { LEFT, RIGHT } + +/** Where the handle rests: an edge and how far down the usable height (0 = top, 1 = bottom). */ +data class BubblePlacement(val edge: BubbleEdge, val yFraction: Float) { + companion object { + val DEFAULT = BubblePlacement(BubbleEdge.RIGHT, 0.6f) + } +} + +/** + * Pure geometry for dragging, inward swipe, and snapping, in window pixels. Kept apart from + * WindowManager so it can be unit tested; [BubbleWindow] feeds it the screen. + */ +object BubbleGeometry { + /** Outcome of a touch sequence on the docked edge handle. */ + enum class EdgeGesture { + /** Short press without moving past touch slop: open the staged panel. */ + TAP, + + /** Deliberate inward horizontal swipe from the docked edge: open the staged panel. */ + OPEN_PANEL, + + /** Vertical move or cross-screen horizontal drag: snap to edge & remember position. */ + REPOSITION, + } + + /** Released left of the middle goes left; the middle itself goes right. */ + fun edgeFor(centerX: Int, screenWidth: Int): BubbleEdge = + if (centerX * 2 < screenWidth) BubbleEdge.LEFT else BubbleEdge.RIGHT + + fun xFor(edge: BubbleEdge, screenWidth: Int, windowSize: Int): Int = when (edge) { + BubbleEdge.LEFT -> 0 + BubbleEdge.RIGHT -> (screenWidth - windowSize).coerceAtLeast(0) + } + + /** Valid window tops: below [topInset], with the window above [bottomInset]. */ + fun yRange(screenHeight: Int, windowSize: Int, topInset: Int, bottomInset: Int): IntRange { + val top = topInset.coerceAtLeast(0) + val bottom = (screenHeight - bottomInset - windowSize).coerceAtLeast(top) + return top..bottom + } + + fun clampX(x: Int, screenWidth: Int, windowSize: Int): Int = + x.coerceIn(0, (screenWidth - windowSize).coerceAtLeast(0)) + + fun yFor(fraction: Float, range: IntRange): Int { + val f = if (fraction.isNaN()) BubblePlacement.DEFAULT.yFraction else fraction.coerceIn(0f, 1f) + return range.first + ((range.last - range.first) * f).roundToInt() + } + + fun fractionFor(y: Int, range: IntRange): Float { + val span = range.last - range.first + if (span <= 0) return 0.5f + return (y.coerceIn(range) - range.first).toFloat() / span + } + + /** Where a release at window position ([x], [y]) settles. */ + fun snap(x: Int, y: Int, screenWidth: Int, windowSize: Int, range: IntRange): BubblePlacement = + BubblePlacement(edgeFor(x + windowSize / 2, screenWidth), fractionFor(y, range)) + + /** Moved further than the touch slop: a drag, not a tap. */ + fun isDrag(dx: Float, dy: Float, slop: Int): Boolean = dx * dx + dy * dy > slop.toFloat() * slop + + /** + * Classifies a touch release on the edge handle: + * - within [slop] -> [EdgeGesture.TAP] + * - mostly-horizontal inward pull between [swipeThreshold] and [crossThreshold] -> [EdgeGesture.OPEN_PANEL] + * - otherwise -> [EdgeGesture.REPOSITION] (vertical slide or cross-screen edge switch) + */ + fun classifyRelease( + edge: BubbleEdge, + dx: Float, + dy: Float, + slop: Int, + swipeThreshold: Float, + crossThreshold: Float, + ): EdgeGesture { + if (!isDrag(dx, dy, slop)) return EdgeGesture.TAP + val inwardDx = if (edge == BubbleEdge.RIGHT) -dx else dx + val mostlyHorizontal = abs(dx) > abs(dy) * 1.3f + return if (inwardDx >= swipeThreshold && inwardDx < crossThreshold && mostlyHorizontal) { + EdgeGesture.OPEN_PANEL + } else { + EdgeGesture.REPOSITION + } + } +} + +/** + * What the bubble counts: batches the relay would list under 「未投递」 + * (`RelayFilter.UNDELIVERED`, i.e. no `delivered` outcome yet), newest first. + */ +object BubbleStaging { + /** The panel lists at most this many; 「全部合并投递」 still takes them all. */ + const val PANEL_LIMIT = 30 + + fun staged(entries: List): List = + entries.filter { !it.isDelivered }.sortedByDescending { it.batch.createdAt } + + /** Ids for 「全部合并投递」: oldest first, the order a merge reads in (as the relay's own selection). */ + fun mergeIds(staged: List): List = + staged.sortedBy { it.batch.createdAt }.map { it.id.toString().uppercase() } + + /** The badge: nothing for 0, the number up to 99, then 「99+」. */ + fun badge(count: Int): String? = when { + count <= 0 -> null + count > 99 -> "99+" + else -> count.toString() + } + + /** + * Bounce when a batch appears that was not there before and arrived after + * [since] (the service start), so loading the existing list does not bounce. + */ + fun shouldPulse(previous: Set, current: List, since: Instant): Boolean = + current.any { it.id !in previous && !it.batch.createdAt.isBefore(since) } +} + +/** Should the service run (and silent receive stay active)? */ +object BubbleGate { + fun shouldRun(enabled: Boolean, canDrawOverlays: Boolean): Boolean = enabled && canDrawOverlays +} + +/** + * Whether the slim edge handle itself should be visible on screen. + * The foreground service and [SilentReceive] stay active even when the handle + * is hidden due to [autoHideWhenEmpty] or [zeroOverlayMode]. + */ +object BubbleVisibility { + fun shouldShowHandle( + enabled: Boolean, + canDrawOverlays: Boolean, + stagedCount: Int, + autoHideWhenEmpty: Boolean, + zeroOverlayMode: Boolean, + panelOpen: Boolean = false, + ): Boolean { + if (!BubbleGate.shouldRun(enabled, canDrawOverlays)) return false + if (zeroOverlayMode) return false + if (panelOpen) return false + if (autoHideWhenEmpty && stagedCount <= 0) return false + return true + } + + /** + * Whether an on-demand service instance (launched via QS Tile while the main switch is off) + * is safe to stop. Must stay alive while the panel is open or an async fill is in progress. + */ + fun shouldStopOnDemand( + onDemandOnly: Boolean, + enabled: Boolean, + panelOpen: Boolean, + fillInProgress: Boolean = false, + ): Boolean = onDemandOnly && !enabled && !panelOpen && !fillInProgress +} + +/** + * The share receiver with the bubble on: no receipt card, back to the sender + * as soon as the batch is in; only a failure says anything. Otherwise the + * receipt card behaves as before. + */ +object SilentReceive { + enum class Mode { RECEIPT, SILENT } + + enum class Step { + /** Still copying: keep the Activity (the URI grant ends with it). */ + WAIT, + + /** Saved: finish at once; the bubble's count picks it up. */ + FINISH, + + /** Not saved: say why (Toast), then finish. */ + FAIL, + } + + /** The bubble must actually be able to show, or the user would get no sign at all. */ + fun mode(bubbleEnabled: Boolean, canDrawOverlays: Boolean): Mode = + if (BubbleGate.shouldRun(bubbleEnabled, canDrawOverlays)) Mode.SILENT else Mode.RECEIPT + + fun step(state: ReceiptUiState?): Step = when (state) { + null, is ReceiptUiState.Importing -> Step.WAIT + is ReceiptUiState.Saved -> Step.FINISH + is ReceiptUiState.NotSaved -> Step.FAIL + } + + /** A long copy shows the progress card after this, so a quick one never flashes it. */ + const val PROGRESS_DELAY_MILLIS = 400L +} + +/** The settings switch. */ +object BubbleToggle { + enum class Action { + /** Save on and start the service. */ + ENABLE, + + /** Open the system overlay page; decide again on return. */ + REQUEST_PERMISSION, + + /** Save off and stop the service. */ + DISABLE, + } + + fun onSwitch(turnOn: Boolean, canDrawOverlays: Boolean): Action = when { + !turnOn -> Action.DISABLE + canDrawOverlays -> Action.ENABLE + else -> Action.REQUEST_PERMISSION + } + + /** Back from the system page (or resumed) while waiting for the permission: enable if it was granted. */ + fun onReturn(awaitingPermission: Boolean, canDrawOverlays: Boolean): Action? = when { + !awaitingPermission -> null + canDrawOverlays -> Action.ENABLE + else -> null + } + + /** HyperOS / MIUI also gate overlays behind their own 「后台弹出界面」 and 「显示悬浮窗」. */ + fun isXiaomi(manufacturer: String?, brand: String? = null): Boolean = + listOf(manufacturer, brand).any { value -> + val v = value?.lowercase().orEmpty() + v.contains("xiaomi") || v.contains("redmi") || v.contains("poco") + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleMedia.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleMedia.kt new file mode 100644 index 00000000..b02bd5c5 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleMedia.kt @@ -0,0 +1,150 @@ +package com.xiangming.wechatbridge.bubble + +import android.content.ClipData +import android.content.ClipDescription +import android.net.Uri +import com.xiangming.wechatbridge.core.deliver.DeliveryPlanner +import com.xiangming.wechatbridge.core.inbox.ReadyItem +import com.xiangming.wechatbridge.core.summary.RelayFiles +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.data.RelayEntry +import java.io.File +import java.nio.file.Files +import java.util.Locale +import java.util.UUID + +/** A file a drag can carry: where it is now, the name it goes out under, its MIME type. */ +data class DragFile(val file: File, val name: String, val mimeType: String) + +/** + * What a staged batch can drag out besides text: its images (loose files, + * or unpacked from a chat ZIP) and, for a native WeChat chat export, the + * original ZIP. Other attachments (PDF, video, a plain ZIP…) are not here. + */ +data class BatchMedia(val images: List, val archive: DragFile?) { + companion object { + val EMPTY = BatchMedia(emptyList(), null) + } +} + +/** The images one drag takes: the first [files] of [total]. */ +data class ImageSelection(val files: List, val total: Int) { + val truncated: Boolean get() = total > files.size +} + +object BubbleMedia { + /** Most images one drag carries; the rest are left out with a toast. */ + const val MAX_IMAGES = 9 + + const val ZIP_MIME = "application/zip" + + /** Directory-name prefix under `cacheDir/deliveries/` for drag copies (cleaned with the other deliveries). */ + const val DIRECTORY_PREFIX = "bubble-drag-" + + private fun isZip(name: String) = name.lowercase(Locale.ROOT).endsWith(".zip") + + /** + * The native chat export of a chat batch: the summary's archive item, or + * the first ZIP. Null for anything else (a ZIP in a files batch stays an + * attachment). + */ + fun chatArchive(entry: RelayEntry): ReadyItem? { + val summary = entry.summary ?: return null + if (summary.kind != RelaySummary.Kind.CHAT) return null + val items = entry.batch.items + val item = summary.archiveItemId?.let { id -> items.firstOrNull { it.id == id } } + ?: items.firstOrNull { isZip(it.file.name) || isZip(it.displayName) } + ?: return null + return item.takeIf { isZip(it.file.name) || isZip(it.displayName) } + } + + /** The name a loose image goes out under, with an image extension; null when it is no image. */ + fun imageName(displayName: String, fileName: String): String? { + val shown = displayName.substringAfterLast('/').trim() + if (shown.isNotEmpty() && DeliveryPlanner.isImage(shown)) return shown + if (!DeliveryPlanner.isImage(fileName)) return null + val ext = fileName.substringAfterLast('.') + val base = shown.substringBeforeLast('.').ifEmpty { fileName.substringBeforeLast('.') }.ifEmpty { "image" } + return "$base.$ext" + } + + /** WeChat's suggested name, kept readable, always ending in `.zip`. */ + fun archiveName(displayName: String): String { + val shown = displayName.substringAfterLast('/').trim().ifEmpty { "聊天记录.zip" } + return if (isZip(shown)) shown else "$shown.zip" + } + + /** Images of [names] (archive entry paths; folders skipped) in [directory], in order. */ + fun imagesIn(directory: File, names: List, skip: String? = null): List = + names.filter { it != skip && !it.endsWith("/") }.mapNotNull { path -> + val leaf = path.substringAfterLast('/') + if (!DeliveryPlanner.isImage(leaf)) null else DragFile(File(directory, path), leaf, DeliveryPlanner.mimeType(leaf)) + } + + /** + * Looks [entry] over (blocking file IO). The chat ZIP is unpacked with + * [extract] — by default [RelayFiles.extract], the cached copy the + * summary and the detail page already use. + */ + fun scan( + entry: RelayEntry, + extract: (File, UUID) -> RelayFiles.Extracted = RelayFiles::extract, + ): BatchMedia { + val archiveItem = chatArchive(entry) + val images = mutableListOf() + for (item in entry.batch.items) { + if (item.id == archiveItem?.id) { + val unpacked = runCatching { extract(item.file, entry.batch.id) }.getOrNull() ?: continue + images += imagesIn(unpacked.directory, unpacked.names) + continue + } + if (item.contentType == ShareOrigin.NOTE_CONTENT_TYPE) continue + val name = imageName(item.displayName, item.file.name) ?: continue + images += DragFile(item.file, name, DeliveryPlanner.mimeType(name)) + } + val archive = archiveItem?.takeIf { it.file.isFile }?.let { + DragFile(it.file, archiveName(it.displayName), ZIP_MIME) + } + return BatchMedia(images.filter { it.file.isFile }, archive) + } + + /** At most [limit], in order. */ + fun select(images: List, limit: Int = MAX_IMAGES): ImageSelection = + ImageSelection(images.take(limit), images.size) + + /** + * Copies [files] into [directory] (under `cacheDir/deliveries/`, which the + * FileProvider serves): inbox originals never leave the app. Names are + * made unique (`a.png`, `a (2).png`) and keep their extensions. + */ + fun stage(files: List, directory: File): List { + if (!directory.isDirectory && !directory.mkdirs()) throw java.io.IOException("cannot create $directory") + val used = HashSet() + return files.map { source -> + val name = DeliveryPlanner.uniqueName(source.name.replace('/', '_'), used) + val destination = File(directory, name) + Files.copy(source.file.toPath(), destination.toPath()) + source.copy(file = destination, name = name) + } + } +} + +/** What goes into a drag's ClipData: one item per URI, the distinct MIME types in order. */ +data class ClipPlan(val mimeTypes: List, val itemCount: Int) + +object DragClip { + fun plan(mimeTypes: List): ClipPlan = ClipPlan(mimeTypes.distinct(), mimeTypes.size) + + /** + * URIs only, no text: an input box would paste a URI it finds next to + * text. Null when there is nothing to carry. + */ + fun build(label: String, items: List>): ClipData? { + if (items.isEmpty()) return null + val plan = plan(items.map { it.second }) + val clip = ClipData(ClipDescription(label, plan.mimeTypes.toTypedArray()), ClipData.Item(items.first().first)) + items.drop(1).forEach { clip.addItem(ClipData.Item(it.first)) } + return clip + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleNotification.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleNotification.kt new file mode 100644 index 00000000..776cef94 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleNotification.kt @@ -0,0 +1,101 @@ +package com.xiangming.wechatbridge.bubble + +import android.Manifest +import android.annotation.SuppressLint +import android.app.Notification +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.NotificationChannelCompat +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import com.xiangming.wechatbridge.MainActivity +import com.xiangming.wechatbridge.R + +/** + * The foreground service's quiet notification (channel `bubble`, minimum + * importance): keeps the process alive and serves as a zero-overlay trigger + * to open the staged panel directly over the foreground app. + */ +internal object BubbleNotification { + const val CHANNEL_ID = "bubble" + const val NOTIFICATION_ID = 0x0B0BB1E + + private const val REQUEST_OPEN_APP = 1 + private const val REQUEST_HIDE = 2 + private const val REQUEST_OPEN_PANEL = 3 + + fun build(context: Context, stagedCount: Int): Notification { + ensureChannel(context) + val text = if (stagedCount > 0) { + context.resources.getQuantityString(R.plurals.bubble_notification_text, stagedCount, stagedCount) + } else { + context.getString(R.string.bubble_notification_text_empty) + } + return NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_stat_wechatbridge) + .setContentTitle(context.getString(R.string.bubble_notification_title)) + .setContentText(text) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setSilent(true) + .setShowWhen(false) + .setCategory(NotificationCompat.CATEGORY_SERVICE) + .setPriority(NotificationCompat.PRIORITY_MIN) + .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_DEFERRED) + .setContentIntent(openPanel(context)) + .addAction(0, context.getString(R.string.bubble_notification_open_panel), openPanel(context)) + .addAction(0, context.getString(R.string.bubble_notification_open_app), openApp(context)) + .addAction(0, context.getString(R.string.bubble_notification_hide), hide(context)) + .build() + } + + /** Refreshes the count; skipped when notifications are not allowed. */ + @SuppressLint("MissingPermission") // checked in canPost + fun update(context: Context, stagedCount: Int) { + if (!canPost(context)) return + runCatching { NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, build(context, stagedCount)) } + } + + private fun canPost(context: Context): Boolean { + if (Build.VERSION.SDK_INT >= 33 && + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED + ) { + return false + } + return NotificationManagerCompat.from(context).areNotificationsEnabled() + } + + private fun ensureChannel(context: Context) { + val channel = NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_MIN) + .setName(context.getString(R.string.bubble_channel_name)) + .setDescription(context.getString(R.string.bubble_channel_description)) + .setShowBadge(false) + .build() + NotificationManagerCompat.from(context).createNotificationChannel(channel) + } + + private fun openPanel(context: Context): PendingIntent = PendingIntent.getActivity( + context, + REQUEST_OPEN_PANEL, + BubblePanelTriggerActivity.intent(context), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity( + context, + REQUEST_OPEN_APP, + Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + private fun hide(context: Context): PendingIntent = PendingIntent.getService( + context, + REQUEST_HIDE, + Intent(context, BubbleService::class.java).setAction(BubbleService.ACTION_HIDE), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanel.kt new file mode 100644 index 00000000..31c95029 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanel.kt @@ -0,0 +1,1098 @@ +package com.xiangming.wechatbridge.bubble + +import android.content.ClipData +import android.content.Context +import android.graphics.PixelFormat +import android.os.Build +import android.view.DragEvent +import android.view.KeyEvent +import android.view.View +import android.view.WindowManager +import android.widget.FrameLayout +import android.widget.Toast +import androidx.annotation.StringRes +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.graphics.Color +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.BiasAlignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.TransformOrigin +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.deliver.PromptClipboard +import com.xiangming.wechatbridge.deliver.ShareFileProvider +import com.xiangming.wechatbridge.fill.FillAccess +import com.xiangming.wechatbridge.ui.relay.RelayCardText +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import com.xiangming.wechatbridge.ui.theme.pressScale +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.util.UUID +import java.time.Instant +import java.time.ZoneId + +/** What the panel's buttons do; the service carries them out and closes the panel. */ +internal interface BubblePanelActions { + fun openBatch(entry: RelayEntry) + fun mergeAll(staged: List) + fun openApp() + fun hideBubble() + fun dismiss() + + /** 「填入」: close the panel and put [text] into the input box of the app in front (never sends). */ + fun fill(text: String) + fun openAccessibilitySettings() + fun openAppDetails() +} + +/** What the panel needs from the service for dragging text out. */ +internal interface BubbleDragHost { + /** [BubbleDragText.build] for [entries]; blocking, called on an IO dispatcher. */ + fun build(entries: List): DragText + + /** [PromptClipboard.copy]. */ + fun copy(text: String): PromptClipboard.Result + + /** The ball window lets drops through while a drag is out. */ + fun setBallDragging(dragging: Boolean) + + /** [BubbleMedia.scan] for [entry]; blocking, called on an IO dispatcher. */ + fun media(entry: RelayEntry): BatchMedia + + /** A fresh, empty directory under `cacheDir/deliveries/` for one drag's copies. */ + fun newMediaDirectory(): File + + /** Whether the fill accessibility service is on and connected. */ + fun fillState(): FillAccess.State +} + +/** Long press and copy, from the panel's rows and the merge button to [BubblePanelWindow]. */ +internal interface BubbleDragActions { + fun drag(source: View, title: String, entries: List, style: DragShadowStyle) + fun copy(entries: List) + + /** Up to [BubbleMedia.MAX_IMAGES] of the batch's images, as content URIs. */ + fun dragImages(source: View, entry: RelayEntry, style: DragShadowStyle) + + /** The batch's original chat ZIP, as one content URI. */ + fun dragArchive(source: View, entry: RelayEntry, style: DragShadowStyle) + + /** A tap on a capsule: say it takes a long press. */ + fun capsuleHint() + + /** 「填入」 / 「全部填入」: the same text as a drag, into the front app's input box. */ + fun fill(entries: List) + + /** Leaves the 「开启一键填入」 guide for the list again. */ + fun closeFillGuide() + + object None : BubbleDragActions { + override fun fill(entries: List) = Unit + override fun closeFillGuide() = Unit + override fun drag(source: View, title: String, entries: List, style: DragShadowStyle) = Unit + override fun copy(entries: List) = Unit + override fun dragImages(source: View, entry: RelayEntry, style: DragShadowStyle) = Unit + override fun dragArchive(source: View, entry: RelayEntry, style: DragShadowStyle) = Unit + override fun capsuleHint() = Unit + } +} + +/** + * Real cross-window frosted glass on Android 12+. Older releases keep the opaque + * panel fill instead. Radius is converted from dp because WindowManager uses pixels. + */ +internal object BubbleWindowBlur { + private const val RADIUS_DP = 28 + + fun apply(params: WindowManager.LayoutParams, enabled: Boolean, density: Float) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return + params.flags = if (enabled) { + params.flags or WindowManager.LayoutParams.FLAG_BLUR_BEHIND + } else { + params.flags and WindowManager.LayoutParams.FLAG_BLUR_BEHIND.inv() + } + params.blurBehindRadius = if (enabled) (RADIUS_DP * density).toInt() else 0 + } +} + +/** + * The staged list, in a full-screen overlay window over whatever app is in + * front: a scrim (tap to close) and a card beside the ball's edge. The window + * takes focus so the back key closes it. + */ +internal class BubblePanelWindow( + private val context: Context, + private val windowManager: WindowManager, + private val owner: OverlayOwner, + private val staged: StateFlow>, + private val actions: BubblePanelActions, + private val host: BubbleDragHost, +) : BubbleDragActions { + private var root: FrameLayout? = null + private var params: WindowManager.LayoutParams? = null + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + + /** Drag texts for this opening of the panel, by batch ids; built once each. */ + private val texts = HashMap>() + + /** Images and archive per batch, for this opening; the capsules show once known. */ + private val scans = HashMap>() + private val media = MutableStateFlow>(emptyMap()) + + /** Shown instead of the list after 「填入」 while the accessibility service is not ready. */ + private val fillGuide = MutableStateFlow(null) + + /** Drives smooth scale + fade collapse before removing the overlay window. */ + private val panelVisible = MutableStateFlow(true) + private var dismissing = false + + @OptIn(ExperimentalCoroutinesApi::class) + private val mediaDispatcher = Dispatchers.IO.limitedParallelism(1) + private var dragging = false + + /** Copies of the drag in progress; removed again when nothing took them. */ + private var dragDirectory: File? = null + + val isShown: Boolean get() = root != null + + private fun requestAnimatedDismiss() { + if (dismissing || root == null) return + dismissing = true + panelVisible.value = false + scope.launch { + delay(COLLAPSE_ANIM_MILLIS) + actions.dismiss() + } + } + + fun show(placement: BubblePlacement): Boolean { + if (root != null) return true + dismissing = false + panelVisible.value = true + val params = WindowManager.LayoutParams( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, + PixelFormat.TRANSLUCENT, + ).apply { + title = "WeChatBridgeBubblePanel" + BubbleWindowBlur.apply(this, enabled = true, density = context.resources.displayMetrics.density) + } + val layer = BackLayer(context) { requestAnimatedDismiss() } + val animatedActions = object : BubblePanelActions by actions { + override fun dismiss() = requestAnimatedDismiss() + } + val compose = ComposeView(context).apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow) + setContent { + WeChatBridgeTheme { + val list by staged.collectAsStateWithLifecycle() + val known by media.collectAsStateWithLifecycle() + val guide by fillGuide.collectAsStateWithLifecycle() + val visible by panelVisible.collectAsStateWithLifecycle() + BubblePanelContent( + staged = list, + placement = placement, + actions = animatedActions, + drag = this@BubblePanelWindow, + media = known, + fillGuide = guide, + visible = visible, + ) + } + } + } + layer.addView(compose, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)) + owner.attach(layer) + return try { + windowManager.addView(layer, params) + root = layer + this.params = params + prefetch(staged.value) + scope.launch { staged.collect { list -> list.take(BubbleStaging.PANEL_LIMIT).forEach(::scan) } } + true + } catch (_: RuntimeException) { + false + } + } + + fun remove() { + val view = root ?: return + root = null + params = null + if (dragging) { + dragging = false + host.setBallDragging(false) + // A drop may still come: leave the copies to the deliveries clean-up. + dragDirectory = null + } + discardDragDirectory() + scope.cancel() + runCatching { windowManager.removeViewImmediate(view) } + } + + // region Drag out + + /** The first rows, one at a time in the background, so a long press usually finds its text ready. */ + @OptIn(ExperimentalCoroutinesApi::class) + private fun prefetch(entries: List) { + val background = Dispatchers.IO.limitedParallelism(1) + entries.take(PREFETCH_LIMIT).filterNot(BubbleDragText::isTextless).forEach { text(listOf(it), background) } + } + + private fun text(entries: List, dispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.IO): Deferred { + val key = entries.joinToString(",") { it.id.toString() } + return texts.getOrPut(key) { scope.async(dispatcher) { host.build(entries) } } + } + + override fun drag(source: View, title: String, entries: List, style: DragShadowStyle) { + if (dragging || root == null) return + if (BubbleDragText.allTextless(entries)) { + toast(R.string.bubble_drag_no_text) + return + } + scope.launch { + when (val result = text(entries).await()) { + is DragText.Ready -> begin(source, title, result.text, style) + else -> toast(messageFor(result)) + } + } + } + + override fun copy(entries: List) { + if (dragging || root == null) return + if (BubbleDragText.allTextless(entries)) { + toast(R.string.bubble_drag_no_text) + return + } + scope.launch { + when (val result = text(entries).await()) { + is DragText.Ready -> when (val copied = host.copy(result.text)) { + is PromptClipboard.Result.Copied -> { + // Android 13+ confirms a copy itself; saying it twice is noise. + if (!copied.systemConfirms) toast(R.string.bubble_copy_done) + actions.dismiss() + } + else -> toast(R.string.bubble_copy_failed) + } + else -> toast(messageFor(result)) + } + } + } + + private fun begin(source: View, title: String, text: String, style: DragShadowStyle) { + // Plain text only: a URI in the clip makes some input boxes refuse it or paste the URI. + val clip = ClipData.newPlainText(CLIP_LABEL, text) + start(source, clip, DragCardShadow(context, title, style), View.DRAG_FLAG_GLOBAL, R.string.bubble_drag_not_dropped) + } + + private fun scan(entry: RelayEntry): Deferred = scans.getOrPut(entry.id) { + scope.async(mediaDispatcher) { runCatching { host.media(entry) }.getOrDefault(BatchMedia.EMPTY) }.also { job -> + scope.launch { val found = job.await(); media.update { it + (entry.id to found) } } + } + } + + override fun dragImages(source: View, entry: RelayEntry, style: DragShadowStyle) { + if (dragging || root == null) return + scope.launch { + val selection = BubbleMedia.select(scan(entry).await().images) + if (selection.files.isEmpty()) { + toast(if (BubbleDragText.isTextless(entry)) R.string.bubble_drag_nothing else R.string.bubble_drag_no_images) + return@launch + } + val title = context.resources.getQuantityString(R.plurals.bubble_media_images_shadow, selection.files.size, selection.files.size) + val clip = stageClip(selection.files) ?: return@launch toast(R.string.bubble_drag_images_failed) + if (selection.truncated) { + Toast.makeText(context, context.getString(R.string.bubble_drag_images_limit, BubbleMedia.MAX_IMAGES), Toast.LENGTH_SHORT).show() + } + start(source, clip, DragCardShadow(context, title, style), URI_FLAGS, R.string.bubble_drag_images_not_dropped) + } + } + + override fun dragArchive(source: View, entry: RelayEntry, style: DragShadowStyle) { + if (dragging || root == null) return + scope.launch { + val archive = scan(entry).await().archive ?: return@launch toast(R.string.bubble_drag_archive_failed) + val clip = stageClip(listOf(archive)) ?: return@launch toast(R.string.bubble_drag_archive_failed) + start(source, clip, DragCardShadow(context, archive.name, style), URI_FLAGS, R.string.bubble_drag_file_not_dropped) + } + } + + override fun capsuleHint() = toast(R.string.bubble_capsule_hint) + + override fun fill(entries: List) { + if (dragging || root == null) return + if (BubbleDragText.allTextless(entries)) { + toast(R.string.bubble_drag_no_text) + return + } + val state = host.fillState() + if (state != FillAccess.State.READY) { + fillGuide.value = state + return + } + scope.launch { + when (val result = text(entries).await()) { + is DragText.Ready -> actions.fill(result.text) + else -> toast(messageFor(result)) + } + } + } + + override fun closeFillGuide() { + fillGuide.value = null + } + + /** Copies into a fresh directory under deliveries/ (off the main thread), then one URI item each. */ + private suspend fun stageClip(files: List): ClipData? { + discardDragDirectory() + val staged = withContext(Dispatchers.IO) { + var made: File? = null + runCatching { + val dir = host.newMediaDirectory().also { made = it } + dir to BubbleMedia.stage(files, dir).map { ShareFileProvider.uriFor(context, it.file, it.name) to it.mimeType } + }.onFailure { made?.deleteRecursively() }.getOrNull() + } ?: return null + if (root == null) { + staged.first.deleteRecursively() + return null + } + dragDirectory = staged.first + return DragClip.build(CLIP_LABEL, staged.second) + } + + private fun discardDragDirectory() { + val dir = dragDirectory ?: return + dragDirectory = null + Thread { dir.deleteRecursively() }.start() + } + + /** + * Starts the drag and keeps the windows out of its way until it ends; + * [notDropped] is the toast when nothing took it. + */ + private fun start(source: View, clip: ClipData, shadow: View.DragShadowBuilder, flags: Int, @StringRes notDropped: Int) { + if (dragging || root == null || !source.isAttachedToWindow) { + discardDragDirectory() + return + } + source.setOnDragListener { view, event -> + when (event.action) { + DragEvent.ACTION_DRAG_STARTED -> true + DragEvent.ACTION_DRAG_ENDED -> { + view.setOnDragListener(null) + val dropped = event.result + // After the system is done with the event; never remove the window mid-drag. + view.post { finish(dropped, notDropped) } + true + } + // Our window lets drops through; it is never the target. + DragEvent.ACTION_DROP -> false + else -> true + } + } + val started = runCatching { + source.startDragAndDrop(clip, shadow, null, flags) + }.getOrDefault(false) + if (!started) { + source.setOnDragListener(null) + discardDragDirectory() + toast(R.string.bubble_drag_not_started) + return + } + // Only after the drag holds the touch: changing flags first could cancel it. + setDragging(true) + } + + private fun finish(dropped: Boolean, @StringRes notDropped: Int) { + if (!dragging) return + setDragging(false) + if (dropped) { + // The target may still be reading: the copies stay until the deliveries clean-up. + dragDirectory = null + actions.dismiss() + toast(R.string.bubble_drag_dropped) + } else { + discardDragDirectory() + toast(notDropped) + } + } + + /** Out of the way while dragging: invisible, not touchable, not focused; but still added. */ + private fun setDragging(on: Boolean) { + val view = root ?: return + val p = params ?: return + dragging = on + p.flags = DragWindowFlags.flags(p.flags, dragging = on, focusableAtRest = false) + view.alpha = if (on) 0f else 1f + runCatching { windowManager.updateViewLayout(view, p) } + host.setBallDragging(on) + } + + private fun messageFor(result: DragText): Int = when (result) { + DragText.TooLarge -> R.string.bubble_drag_too_large + DragText.Failed -> R.string.bubble_drag_failed + else -> R.string.bubble_drag_no_text + } + + private fun toast(@StringRes id: Int) { + Toast.makeText(context, id, Toast.LENGTH_SHORT).show() + } + + // endregion + + /** Container for the panel overlay; stays non-focusable so underlying apps keep IME/input focus. */ + private class BackLayer(context: Context, private val onBack: () -> Unit) : FrameLayout(context) { + init { + isFocusable = false + isFocusableInTouchMode = false + } + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (event.keyCode == KeyEvent.KEYCODE_BACK) { + if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) onBack() + return true + } + return super.dispatchKeyEvent(event) + } + } + + private companion object { + const val CLIP_LABEL = "WeChatBridge" + const val PREFETCH_LIMIT = 5 + const val COLLAPSE_ANIM_MILLIS = 150L + + /** The drop target may read the content URIs (granted only on a drop). */ + const val URI_FLAGS = View.DRAG_FLAG_GLOBAL or View.DRAG_FLAG_GLOBAL_URI_READ + } +} + +@Composable +internal fun BubblePanelContent( + staged: List, + placement: BubblePlacement, + actions: BubblePanelActions, + drag: BubbleDragActions = BubbleDragActions.None, + media: Map = emptyMap(), + fillGuide: FillAccess.State? = null, + now: Instant = Instant.now(), + visible: Boolean = true, +) { + val resources = LocalContext.current.resources + val view = LocalView.current + val colors = MaterialTheme.colorScheme + val ext = LocalAppColors.current + val shadow = DragShadowStyle(colors.primaryContainer.toArgb(), colors.onPrimaryContainer.toArgb()) + val text = remember(resources, now) { RelayCardText(resources, now, ZoneId.systemDefault()) } + val horizontal = if (placement.edge == BubbleEdge.LEFT) -1f else 1f + val vertical = (placement.yFraction.coerceIn(0f, 1f) * 2f - 1f) + + var entered by remember { mutableStateOf(false) } + LaunchedEffect(Unit) { entered = true } + val active = entered && visible + + val scrimAlpha by animateFloatAsState( + targetValue = if (active) 0.30f else 0f, + animationSpec = tween(durationMillis = if (active) 180 else 140), + label = "panelScrimAlpha", + ) + val cardScale by animateFloatAsState( + targetValue = if (active) 1f else 0.92f, + animationSpec = if (active) AppMotion.snappySpring() else tween(durationMillis = 140), + label = "panelCardScale", + ) + val cardSlideFraction by animateFloatAsState( + targetValue = if (active) 0f else 1f, + animationSpec = if (active) AppMotion.snappySpring() else tween(durationMillis = 140), + label = "panelCardSlide", + ) + val cardAlpha by animateFloatAsState( + targetValue = if (active) 1f else 0f, + animationSpec = tween(durationMillis = if (active) 160 else 130), + label = "panelCardAlpha", + ) + val origin = remember(placement) { + TransformOrigin( + pivotFractionX = if (placement.edge == BubbleEdge.LEFT) 0.04f else 0.96f, + pivotFractionY = placement.yFraction.coerceIn(0.15f, 0.85f), + ) + } + val panelSurfaceColor = colors.surface.copy(alpha = if (ext.isDark) 0.97f else 0.98f) + val panelBorderColor = if (ext.isDark) Color.White.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.72f) + + Box( + modifier = Modifier + .fillMaxSize() + .background(colors.scrim.copy(alpha = scrimAlpha)) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClickLabel = stringResource(R.string.bubble_panel_close), + role = Role.Button, + onClick = actions::dismiss, + ) + .safeDrawingPadding() + .padding(14.dp), + ) { + Surface( + shape = RoundedCornerShape(24.dp), + color = panelSurfaceColor, + border = BorderStroke(1.dp, panelBorderColor), + shadowElevation = 16.dp, + modifier = Modifier + .align(BiasAlignment(horizontal, vertical)) + .widthIn(max = 356.dp) + .fillMaxWidth() + .graphicsLayer { + scaleX = cardScale + scaleY = cardScale + translationX = cardSlideFraction * (if (placement.edge == BubbleEdge.LEFT) -28f else 28f) + alpha = cardAlpha + transformOrigin = origin + } + // Taps on the card itself must not reach the scrim. + .pointerInput(Unit) { detectTapGestures { } }, + ) { + Column(Modifier.padding(top = 14.dp, bottom = 14.dp)) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth().padding(start = 18.dp, end = 8.dp), + ) { + if (staged.isNotEmpty()) { + Box( + modifier = Modifier + .size(8.dp) + .clip(CircleShape) + .background(colors.primary), + ) + } + Text( + text = if (staged.isEmpty()) { + stringResource(R.string.bubble_panel_title_empty) + } else { + pluralStringResource(R.plurals.bubble_panel_title, staged.size, staged.size) + }, + style = MaterialTheme.typography.titleMedium, + color = colors.onSurface, + modifier = Modifier.weight(1f), + ) + IconButton( + onClick = actions::dismiss, + modifier = Modifier.size(36.dp), + ) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = stringResource(R.string.bubble_panel_close), + tint = ext.onSurfaceMuted, + modifier = Modifier.size(18.dp), + ) + } + } + if (fillGuide == null && staged.isNotEmpty()) { + Text( + text = stringResource(R.string.bubble_drag_hint), + style = MaterialTheme.typography.labelSmall, + color = ext.onSurfaceMuted, + modifier = Modifier.padding(start = 18.dp, end = 18.dp, bottom = 6.dp), + ) + } + if (fillGuide != null) { + // In place of the list until 「返回」. + FillGuide(fillGuide, actions, drag) + } else if (staged.isEmpty()) { + Text( + text = stringResource(R.string.bubble_panel_empty), + style = MaterialTheme.typography.bodyMedium, + color = colors.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp), + ) + } else { + val shown = staged.take(BubbleStaging.PANEL_LIMIT) + LazyColumn(Modifier.heightIn(max = 320.dp)) { + itemsIndexed(shown, key = { _, it -> it.id }) { index, entry -> + val title = text.title(entry) + val found = media[entry.id] ?: BatchMedia.EMPTY + // Nothing readable: the row itself carries the images. + val imagesOnRow = BubbleDragText.isTextless(entry) + StagedRow( + title = title, + detail = listOfNotNull(entry.summary?.let(text::counts), text.time(entry)) + .filter { it.isNotEmpty() } + .joinToString(" · "), + deliverLabel = stringResource(R.string.bubble_panel_open_batch, title), + onClick = { actions.openBatch(entry) }, + longClickLabel = stringResource( + if (imagesOnRow) R.string.bubble_drag_images_action else R.string.bubble_drag_action, + ), + onLongClick = { + if (imagesOnRow) drag.dragImages(view, entry, shadow) else drag.drag(view, title, listOf(entry), shadow) + }, + hasText = !imagesOnRow, + onDragText = { drag.drag(view, title, listOf(entry), shadow) }, + onCopy = { drag.copy(listOf(entry)) }, + // Only attachments: nothing to type into a box. + onFill = if (imagesOnRow) null else ({ drag.fill(listOf(entry)) }), + imageCount = found.images.size, + showPlainImageCapsule = imagesOnRow && found.images.isEmpty(), + hasArchive = found.archive != null, + onDragImages = { drag.dragImages(view, entry, shadow) }, + onDragArchive = { drag.dragArchive(view, entry, shadow) }, + onCapsuleTap = drag::capsuleHint, + ) + if (index < shown.lastIndex) { + HorizontalDivider( + color = ext.subtleDivider, + modifier = Modifier.padding(horizontal = 18.dp), + ) + } + } + } + if (staged.size > shown.size) { + Text( + text = pluralStringResource(R.plurals.bubble_panel_more, staged.size - shown.size, staged.size - shown.size), + style = MaterialTheme.typography.bodySmall, + color = ext.onSurfaceMuted, + modifier = Modifier.padding(horizontal = 18.dp, vertical = 4.dp), + ) + } + if (staged.size > 1) { + val canFillAll = !BubbleDragText.allTextless(staged) + val primaryLabel = if (canFillAll) { + pluralStringResource(R.plurals.bubble_panel_merge_fill_all, staged.size, staged.size) + } else { + pluralStringResource(R.plurals.bubble_panel_merge_all, staged.size, staged.size) + } + MergePrimaryButton( + label = primaryLabel, + onClick = { + if (canFillAll) { + drag.fill(BubbleDragText.mergeOrder(staged)) + } else { + actions.mergeAll(staged) + } + }, + onLongClick = { + drag.drag(view, primaryLabel, BubbleDragText.mergeOrder(staged), shadow) + }, + ) + } + } + HorizontalDivider( + color = ext.subtleDivider, + modifier = Modifier.padding(top = 8.dp, bottom = 10.dp), + ) + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + ) { + val openInteraction = remember { MutableInteractionSource() } + Button( + onClick = actions::openApp, + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.buttonColors( + containerColor = ext.surfaceSub, + contentColor = colors.onSurface, + ), + elevation = ButtonDefaults.buttonElevation(0.dp, 0.dp, 0.dp, 0.dp, 0.dp), + contentPadding = PaddingValues(horizontal = 14.dp, vertical = 9.dp), + interactionSource = openInteraction, + modifier = Modifier + .weight(1f) + .pressScale(openInteraction), + ) { + Text( + text = stringResource(R.string.bubble_panel_open_app), + style = MaterialTheme.typography.labelLarge, + maxLines = 1, + ) + } + TextButton( + onClick = actions::hideBubble, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp), + ) { + Text( + text = stringResource(R.string.bubble_panel_hide), + style = MaterialTheme.typography.labelMedium, + color = ext.onSurfaceMuted, + maxLines = 1, + ) + } + } + } + } + } +} + +/** 底部主按钮:微信绿 12dp 圆角,纯文字「全部合并填入」,支持长按拖出合并全文。 */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun MergePrimaryButton(label: String, onClick: () -> Unit, onLongClick: () -> Unit) { + val haptic = LocalHapticFeedback.current + val interaction = remember { MutableInteractionSource() } + val shape = RoundedCornerShape(12.dp) + Surface( + shape = shape, + color = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary, + modifier = Modifier + .fillMaxWidth() + .padding(start = 16.dp, end = 16.dp, top = 10.dp) + .pressScale(interaction) + .clip(shape) + .combinedClickable( + interactionSource = interaction, + indication = null, + role = Role.Button, + onLongClickLabel = stringResource(R.string.bubble_drag_action), + onLongClick = { + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + onLongClick() + }, + onClick = onClick, + ), + ) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 42.dp) + .padding(horizontal = 16.dp, vertical = 10.dp), + ) { + Text( + text = label, + style = MaterialTheme.typography.labelLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun StagedRow( + title: String, + detail: String, + deliverLabel: String, + longClickLabel: String, + onClick: () -> Unit, + onLongClick: () -> Unit, + hasText: Boolean, + onDragText: () -> Unit, + onCopy: () -> Unit, + onFill: (() -> Unit)? = null, + imageCount: Int = 0, + showPlainImageCapsule: Boolean = false, + hasArchive: Boolean = false, + onDragImages: () -> Unit = {}, + onDragArchive: () -> Unit = {}, + onCapsuleTap: () -> Unit = {}, +) { + val haptic = LocalHapticFeedback.current + val colors = MaterialTheme.colorScheme + val ext = LocalAppColors.current + Column( + modifier = Modifier + .fillMaxWidth() + .combinedClickable( + onClickLabel = deliverLabel, + role = Role.Button, + onLongClickLabel = longClickLabel, + onLongClick = { + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + onLongClick() + }, + onClick = onClick, + ) + .padding(horizontal = 18.dp, vertical = 11.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth(), + ) { + Column(Modifier.weight(1f)) { + Text( + text = title, + style = MaterialTheme.typography.titleSmall, + color = colors.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (detail.isNotEmpty()) { + Text( + text = detail, + style = MaterialTheme.typography.labelSmall, + color = ext.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(top = 2.dp), + ) + } + } + if (onFill != null) { + val fillInteraction = remember { MutableInteractionSource() } + val fillShape = RoundedCornerShape(10.dp) + Surface( + shape = fillShape, + color = ext.primarySoft, + contentColor = colors.primary, + modifier = Modifier + .pressScale(fillInteraction, targetScale = 0.95f) + .clip(fillShape) + .clickable( + interactionSource = fillInteraction, + indication = null, + role = Role.Button, + onClickLabel = stringResource(R.string.fill_action_batch, title), + onClick = onFill, + ), + ) { + Text( + text = stringResource(R.string.bubble_action_fill), + style = MaterialTheme.typography.labelLarge, + modifier = Modifier.padding(horizontal = 13.dp, vertical = 6.dp), + ) + } + } + } + val showImagesCapsule = imageCount > 0 || showPlainImageCapsule + if (hasText || showImagesCapsule || hasArchive) { + Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier + .fillMaxWidth() + .padding(top = 8.dp) + .horizontalScroll(rememberScrollState()), + ) { + if (hasText) { + DragCapsule( + label = stringResource(R.string.bubble_capsule_text), + longClickLabel = stringResource(R.string.bubble_drag_action), + onClick = onCapsuleTap, + onLongClick = onDragText, + ) + } + if (showImagesCapsule) { + val shownCount = minOf(imageCount.coerceAtLeast(1), BubbleMedia.MAX_IMAGES) + DragCapsule( + label = if (imageCount > 0) { + stringResource(R.string.bubble_capsule_drag_images, imageCount) + } else { + stringResource(R.string.bubble_capsule_drag_images_plain) + }, + longClickLabel = pluralStringResource(R.plurals.bubble_capsule_images_action, shownCount, shownCount), + onClick = onCapsuleTap, + onLongClick = onDragImages, + ) + } + if (hasArchive) { + DragCapsule( + label = stringResource(R.string.bubble_capsule_archive), + longClickLabel = stringResource(R.string.bubble_capsule_archive_action), + onClick = onCapsuleTap, + onLongClick = onDragArchive, + ) + } + if (hasText) { + TapCapsule( + label = stringResource(R.string.bubble_action_copy), + clickLabel = stringResource(R.string.bubble_copy_batch, title), + onClick = onCopy, + ) + } + } + } + } +} + +/** 「开启一键填入」, in place of the list: what the service does, and the system pages to turn it on. */ +@Composable +private fun FillGuide(state: FillAccess.State, actions: BubblePanelActions, drag: BubbleDragActions) { + Column(Modifier.padding(horizontal = 18.dp, vertical = 6.dp)) { + Text(stringResource(R.string.fill_guide_title), style = MaterialTheme.typography.titleSmall) + Text( + stringResource(if (state == FillAccess.State.NOT_RUNNING) R.string.fill_guide_not_running else R.string.fill_guide_off), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 4.dp), + ) + if (FillAccess.mayBeRestricted) { + Text( + stringResource(R.string.fill_guide_restricted), + style = MaterialTheme.typography.bodySmall, + color = LocalAppColors.current.onSurfaceMuted, + modifier = Modifier.padding(top = 6.dp), + ) + } + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth().padding(top = 10.dp), + ) { + TextButton(onClick = drag::closeFillGuide) { Text(stringResource(R.string.fill_guide_back)) } + Box(Modifier.weight(1f)) + if (FillAccess.mayBeRestricted) { + OutlinedButton( + onClick = actions::openAppDetails, + shape = RoundedCornerShape(12.dp), + ) { Text(stringResource(R.string.fill_guide_open_details)) } + } + Button( + onClick = actions::openAccessibilitySettings, + shape = RoundedCornerShape(12.dp), + ) { Text(stringResource(R.string.fill_guide_open_settings)) } + } + } +} + +/** 纯文字拖拽胶囊:长按拖出文字 / 图片 / 原包。 */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun DragCapsule( + label: String, + longClickLabel: String, + onClick: () -> Unit, + onLongClick: () -> Unit, +) { + val haptic = LocalHapticFeedback.current + val interaction = remember { MutableInteractionSource() } + val shape = RoundedCornerShape(50) + Surface( + shape = shape, + color = LocalAppColors.current.surfaceSub, + contentColor = MaterialTheme.colorScheme.onSurfaceVariant, + border = BorderStroke(0.75.dp, LocalAppColors.current.subtleDivider), + modifier = Modifier + .pressScale(interaction, targetScale = 0.96f) + .clip(shape) + .combinedClickable( + interactionSource = interaction, + indication = null, + role = Role.Button, + onLongClickLabel = longClickLabel, + onLongClick = { + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + onLongClick() + }, + onClick = onClick, + ), + ) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.heightIn(min = 26.dp).padding(horizontal = 10.dp, vertical = 4.dp), + ) { + Text(text = label, style = MaterialTheme.typography.labelMedium, maxLines = 1) + } + } +} + +/** 轻量点按胶囊(例如单行「复制」)。 */ +@Composable +private fun TapCapsule( + label: String, + clickLabel: String, + onClick: () -> Unit, +) { + val interaction = remember { MutableInteractionSource() } + val shape = RoundedCornerShape(50) + Surface( + shape = shape, + color = LocalAppColors.current.surfaceSub, + contentColor = MaterialTheme.colorScheme.onSurfaceVariant, + border = BorderStroke(0.75.dp, LocalAppColors.current.subtleDivider), + modifier = Modifier + .pressScale(interaction, targetScale = 0.96f) + .clip(shape) + .clickable( + interactionSource = interaction, + indication = null, + role = Role.Button, + onClickLabel = clickLabel, + onClick = onClick, + ), + ) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.heightIn(min = 26.dp).padding(horizontal = 10.dp, vertical = 4.dp), + ) { + Text(text = label, style = MaterialTheme.typography.labelMedium, maxLines = 1) + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanelTriggerActivity.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanelTriggerActivity.kt new file mode 100644 index 00000000..ba928d0a --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubblePanelTriggerActivity.kt @@ -0,0 +1,47 @@ +package com.xiangming.wechatbridge.bubble + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Bundle +import com.xiangming.wechatbridge.MainActivity + +/** + * Invisible no-history trampoline used by [BubbleTileService] and [BubbleNotification] + * so tapping the Quick Settings tile or notification cleanly collapses the system shade + * on Android 12–16 and opens [BubblePanelWindow] directly over the foreground app. + */ +class BubblePanelTriggerActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (OverlayPermission.canDraw(this)) { + BubbleService.openPanel(this) + } else { + runCatching { + startActivity( + Intent(this, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP), + ) + } + } + finish() + suppressTransition() + } + + @Suppress("DEPRECATION") + private fun suppressTransition() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + overrideActivityTransition(OVERRIDE_TRANSITION_OPEN, 0, 0) + overrideActivityTransition(OVERRIDE_TRANSITION_CLOSE, 0, 0) + } else { + overridePendingTransition(0, 0) + } + } + + companion object { + fun intent(context: Context): Intent = + Intent(context, BubblePanelTriggerActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleService.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleService.kt new file mode 100644 index 00000000..381d8d68 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleService.kt @@ -0,0 +1,403 @@ +package com.xiangming.wechatbridge.bubble + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.content.res.Configuration +import android.os.Build +import android.os.IBinder +import android.view.WindowManager +import android.widget.Toast +import androidx.core.content.ContextCompat +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.MainActivity +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.deliver.PromptClipboard +import com.xiangming.wechatbridge.deliver.ShareFileProvider +import com.xiangming.wechatbridge.fill.FillAccess +import com.xiangming.wechatbridge.fill.FillAccessibilityService +import com.xiangming.wechatbridge.fill.FillMessages +import com.xiangming.wechatbridge.fill.FillOutcome +import com.xiangming.wechatbridge.receive.DeliverLaunch +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import java.io.File +import java.time.Instant +import java.util.UUID + +/** + * Keeps the floating bubble on screen: a foreground service (type + * `specialUse`, quiet notification on channel `bubble`) owning two overlay + * windows, the ball ([BubbleWindow]) and, while open, the staged list + * ([BubblePanelWindow]). + * + * The count follows `RelayStore.entries`, which every save, delivery and + * delete already republishes, so nothing else has to tell the service. + * Started through [sync] (App start, the settings switch, the share receiver, + * MainActivity coming to the front). + */ +class BubbleService : Service() { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val owner = OverlayOwner() + private val staged = MutableStateFlow>(emptyList()) + private val count = MutableStateFlow(0) + private val pulse = MutableStateFlow(0) + + /** Batches from shortly before the start count as new too: the share that started us. */ + private val startedAt: Instant = Instant.now().minusSeconds(NEW_BATCH_GRACE_SECONDS) + + private var bubble: BubbleWindow? = null + private var panel: BubblePanelWindow? = null + private var observing: Job? = null + private var filling: Job? = null + private var onDemandOnly = false + + private val container get() = (application as App).container + private val windowManager get() = getSystemService(WindowManager::class.java) + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onCreate() { + super.onCreate() + owner.create() + // Leftovers from a build the process did not live to clean up. + scope.launch(Dispatchers.IO) { File(cacheDir, DRAG_DIR).deleteRecursively() } + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + // Always first: a service started with startForegroundService must call it, even to stop. + goForeground() + val settings = container.bubbleSettings + when (intent?.action) { + ACTION_HIDE -> { + hideBubble() + return START_NOT_STICKY + } + ACTION_OPEN_PANEL -> { + if (!OverlayPermission.canDraw(this)) { + stopSelf() + return START_NOT_STICKY + } + onDemandOnly = !settings.isEnabled + observe() + openPanel() + return if (onDemandOnly) START_NOT_STICKY else START_STICKY + } + } + onDemandOnly = false + if (!BubbleGate.shouldRun(settings.isEnabled, OverlayPermission.canDraw(this))) { + stopSelf() + return START_NOT_STICKY + } + observe() + if (!syncHandleVisibility()) { + stopSelf() + return START_NOT_STICKY + } + return START_STICKY + } + + private fun goForeground() { + val notification = BubbleNotification.build(this, count.value) + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + startForeground(BubbleNotification.NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) + } else { + startForeground(BubbleNotification.NOTIFICATION_ID, notification) + } + } catch (_: RuntimeException) { + // Refused from the background (Android 12+): the overlay still shows while the process lives. + } + } + + /** + * Synchronizes the slim edge handle window with [BubbleVisibility.shouldShowHandle]. + * Returns false only if the handle needed to be shown and WindowManager refused (permission revoked). + */ + private fun syncHandleVisibility(): Boolean { + val settings = container.bubbleSettings + val canDraw = OverlayPermission.canDraw(this) + val shouldShow = BubbleVisibility.shouldShowHandle( + enabled = settings.isEnabled, + canDrawOverlays = canDraw, + stagedCount = count.value, + autoHideWhenEmpty = settings.isAutoHideWhenEmpty, + zeroOverlayMode = settings.isZeroOverlayMode, + panelOpen = panel?.isShown == true, + ) + if (!shouldShow) { + if (settings.isZeroOverlayMode || !settings.isEnabled) { + bubble?.remove() + bubble = null + } else { + bubble?.setVisible(false) + } + return true + } + val existing = bubble + if (existing != null) { + return existing.show() + } + val wm = windowManager ?: return false + val window = BubbleWindow( + context = this, + windowManager = wm, + owner = owner, + settings = settings, + count = count, + pulse = pulse, + onTap = ::togglePanel, + ) + if (!window.show()) return false + bubble = window + return true + } + + private fun observe() { + if (observing != null) return + val store = container.relayStore + val settings = container.bubbleSettings + // Seed initial state synchronously so on-demand panel open sees existing items immediately. + val initial = BubbleStaging.staged(store.entries.value) + staged.value = initial + count.value = initial.size + observing = scope.launch { + launch { + store.entries.collect { entries -> + val next = BubbleStaging.staged(entries) + val previous = staged.value.mapTo(mutableSetOf()) { it.id } + val arrived = BubbleStaging.shouldPulse(previous, next, startedAt) + if (arrived) pulse.update { it + 1 } + staged.value = next + val countChanged = count.value != next.size + if (countChanged) { + count.value = next.size + bubble?.updateDescription(next.size) + BubbleNotification.update(this@BubbleService, next.size) + BubbleTileService.requestUpdate(this@BubbleService) + } + syncHandleVisibility() + if (arrived && next.isNotEmpty()) { + bubble?.showArrivalMicroPill() + } + } + } + launch { + settings.enabled.collect { enabled -> + if (!enabled && !onDemandOnly) stopSelf() + } + } + launch { + settings.autoHideWhenEmpty.collect { syncHandleVisibility() } + } + launch { + settings.zeroOverlayMode.collect { syncHandleVisibility() } + } + } + } + + private fun togglePanel() { + if (panel?.isShown == true) { + closePanel() + return + } + openPanel() + } + + private fun openPanel() { + if (panel?.isShown == true) return + val wm = windowManager ?: return + val window = BubblePanelWindow(this, wm, owner, staged, actions, dragHost) + if (window.show(container.bubbleSettings.placement)) { + panel = window + syncHandleVisibility() + } + } + + private fun closePanel(stopIfOnDemand: Boolean = true) { + panel?.remove() + panel = null + bubble?.setDragging(false) + if (stopIfOnDemand && shouldStopOnDemand(fillInProgress = filling?.isActive == true)) { + stopSelf() + } else { + syncHandleVisibility() + } + } + + private fun shouldStopOnDemand(fillInProgress: Boolean = false): Boolean = + BubbleVisibility.shouldStopOnDemand( + onDemandOnly = onDemandOnly, + enabled = container.bubbleSettings.isEnabled, + panelOpen = panel?.isShown == true, + fillInProgress = fillInProgress, + ) + + /** Dragging / copying a batch's text never marks it delivered: the count stays. */ + private val dragHost = object : BubbleDragHost { + override fun build(entries: List): DragText = BubbleDragText.build( + entries = entries, + scenes = container.sceneStore, + newWorkDirectory = { File(cacheDir, "$DRAG_DIR/${UUID.randomUUID()}").apply { mkdirs() } }, + ) + + override fun copy(text: String): PromptClipboard.Result = container.promptClipboard.copy(text) + + override fun setBallDragging(dragging: Boolean) { + bubble?.setDragging(dragging) + } + + override fun media(entry: RelayEntry): BatchMedia = BubbleMedia.scan(entry) + + override fun newMediaDirectory(): File = + ShareFileProvider.newDeliveryDir(this@BubbleService, BubbleMedia.DIRECTORY_PREFIX + UUID.randomUUID()) + + override fun fillState(): FillAccess.State = FillAccess.state(this@BubbleService) + } + + private val actions = object : BubblePanelActions { + override fun openBatch(entry: RelayEntry) { + open(DeliverLaunch(listOf(entry.id.toString().uppercase()), targetId = null).intent(this@BubbleService)) + } + + override fun mergeAll(staged: List) { + val ids = BubbleStaging.mergeIds(staged) + if (ids.isEmpty()) return + open(DeliverLaunch(ids, targetId = null).intent(this@BubbleService)) + } + + override fun openApp() { + open(Intent(this@BubbleService, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + + override fun hideBubble() = this@BubbleService.hideBubble() + + override fun dismiss() = closePanel() + + override fun fill(text: String) = this@BubbleService.fill(text) + + override fun openAccessibilitySettings() { + closePanel() + FillAccess.openAccessibilitySettings(this@BubbleService) + } + + override fun openAppDetails() { + closePanel() + FillAccess.openAppDetails(this@BubbleService) + } + } + + /** + * Closes the panel (it holds focus and covers the app), then lets the + * accessibility service put [text] into the front app's input box. Like a + * drag or copy, it never marks the batch delivered. No box found: the + * panel opens again so the user can tap the box and retry. + */ + private fun fill(text: String) { + val service = FillAccessibilityService.running + closePanel(stopIfOnDemand = false) + if (service == null) { + Toast.makeText(this, R.string.fill_failed, Toast.LENGTH_SHORT).show() + if (shouldStopOnDemand(fillInProgress = false)) stopSelf() + return + } + filling?.cancel() + filling = scope.launch { + val outcome = service.fill(text) + Toast.makeText(this@BubbleService, FillMessages.toast(outcome), Toast.LENGTH_LONG).show() + if (outcome == FillOutcome.NO_TARGET && panel == null) { + openPanel() + } else if (shouldStopOnDemand(fillInProgress = false)) { + stopSelf() + } + } + } + + private fun open(intent: Intent) { + closePanel() + runCatching { startActivity(intent) } + } + + /** 「隐藏」 turns the setting off; the switch in 设置 turns it back on. */ + private fun hideBubble() { + container.bubbleSettings.setEnabled(false) + Toast.makeText(this, R.string.bubble_hidden_toast, Toast.LENGTH_SHORT).show() + stopSelf() + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + closePanel() + bubble?.reposition() + } + + override fun onDestroy() { + panel?.remove() + panel = null + bubble?.remove() + bubble = null + owner.destroy() + scope.cancel() + super.onDestroy() + } + + companion object { + const val ACTION_HIDE = "com.xiangming.wechatbridge.action.HIDE_BUBBLE" + const val ACTION_OPEN_PANEL = "com.xiangming.wechatbridge.action.OPEN_PANEL" + private const val NEW_BATCH_GRACE_SECONDS = 30L + + /** Scratch space under cacheDir for building drag texts; emptied after each build. */ + private const val DRAG_DIR = "bubble-drag" + + /** + * Opens the staged panel directly over the foreground app (used by Quick Settings Tile + * and notification action). Requires overlay permission; works even in zero-overlay mode. + */ + fun openPanel(context: Context): Boolean { + val app = context.applicationContext + if (!OverlayPermission.canDraw(app)) return false + val intent = Intent(app, BubbleService::class.java).setAction(ACTION_OPEN_PANEL) + return try { + ContextCompat.startForegroundService(app, intent) + true + } catch (_: IllegalStateException) { + false + } catch (_: SecurityException) { + false + } + } + + /** + * Starts the service when the switch is on and the overlay permission is + * there, stops it otherwise. Returns whether it is (being) started. A + * start refused from the background (Android 12+) returns false; the next + * foreground call (MainActivity, the receiver) tries again. + */ + fun sync(context: Context): Boolean { + val app = context.applicationContext + val settings = (app as App).container.bubbleSettings + BubbleTileService.requestUpdate(app) + if (!BubbleGate.shouldRun(settings.isEnabled, OverlayPermission.canDraw(app))) { + app.stopService(Intent(app, BubbleService::class.java)) + return false + } + return try { + ContextCompat.startForegroundService(app, Intent(app, BubbleService::class.java)) + true + } catch (_: IllegalStateException) { + // ForegroundServiceStartNotAllowedException is an IllegalStateException. + false + } catch (_: SecurityException) { + false + } + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleSettings.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleSettings.kt new file mode 100644 index 00000000..f24f2d8a --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleSettings.kt @@ -0,0 +1,124 @@ +package com.xiangming.wechatbridge.bubble + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.content.SharedPreferences +import android.net.Uri +import android.os.Build +import android.provider.Settings +import androidx.core.content.edit +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** + * The bubble switch and where the bubble rests, in plain SharedPreferences: + * the share receiver and `App.onCreate` read them synchronously, before any + * coroutine could load DataStore. Device-local, like the overlay permission. + */ +class BubbleSettings(private val prefs: SharedPreferences) { + constructor(context: Context) : this( + context.applicationContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE), + ) + + private val _enabled = MutableStateFlow(prefs.getBoolean(KEY_ENABLED, false)) + + /** The user's switch; whether the bubble can show also needs the overlay permission. */ + val enabled: StateFlow = _enabled.asStateFlow() + + val isEnabled: Boolean get() = _enabled.value + + fun setEnabled(value: Boolean) { + prefs.edit { putBoolean(KEY_ENABLED, value) } + _enabled.value = value + } + + private val _autoHideWhenEmpty = MutableStateFlow(prefs.getBoolean(KEY_AUTO_HIDE_EMPTY, true)) + + /** Hide the slim edge handle when staged count == 0; service keeps listening. Default ON. */ + val autoHideWhenEmpty: StateFlow = _autoHideWhenEmpty.asStateFlow() + + val isAutoHideWhenEmpty: Boolean get() = _autoHideWhenEmpty.value + + fun setAutoHideWhenEmpty(value: Boolean) { + prefs.edit { putBoolean(KEY_AUTO_HIDE_EMPTY, value) } + _autoHideWhenEmpty.value = value + } + + private val _zeroOverlayMode = MutableStateFlow(prefs.getBoolean(KEY_ZERO_OVERLAY, false)) + + /** Never show the edge handle; open the staged panel via Quick Settings Tile or notification. Default OFF. */ + val zeroOverlayMode: StateFlow = _zeroOverlayMode.asStateFlow() + + val isZeroOverlayMode: Boolean get() = _zeroOverlayMode.value + + fun setZeroOverlayMode(value: Boolean) { + prefs.edit { putBoolean(KEY_ZERO_OVERLAY, value) } + _zeroOverlayMode.value = value + } + + var placement: BubblePlacement + get() { + val edge = when (prefs.getString(KEY_EDGE, null)) { + EDGE_LEFT -> BubbleEdge.LEFT + EDGE_RIGHT -> BubbleEdge.RIGHT + else -> BubblePlacement.DEFAULT.edge + } + val y = prefs.getFloat(KEY_Y, BubblePlacement.DEFAULT.yFraction) + return BubblePlacement(edge, if (y.isNaN()) BubblePlacement.DEFAULT.yFraction else y.coerceIn(0f, 1f)) + } + set(value) { + prefs.edit { + putString(KEY_EDGE, if (value.edge == BubbleEdge.LEFT) EDGE_LEFT else EDGE_RIGHT) + putFloat(KEY_Y, value.yFraction.coerceIn(0f, 1f)) + } + } + + companion object { + const val FILE_NAME = "bubble" + const val KEY_ENABLED = "enabled" + const val KEY_AUTO_HIDE_EMPTY = "auto_hide_empty" + const val KEY_ZERO_OVERLAY = "zero_overlay" + const val KEY_EDGE = "edge" + const val KEY_Y = "y_fraction" + private const val EDGE_LEFT = "left" + private const val EDGE_RIGHT = "right" + } +} + +/** 「显示在其他应用上层」 and the Xiaomi extras. */ +object OverlayPermission { + fun canDraw(context: Context): Boolean = Settings.canDrawOverlays(context) + + /** The system page for this app's overlay permission. */ + fun settingsIntent(context: Context): Intent = + Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.packageName)) + + val isXiaomi: Boolean get() = BubbleToggle.isXiaomi(Build.MANUFACTURER, Build.BRAND) + + /** + * MIUI / HyperOS 「应用权限」 page (其他权限 → 后台弹出界面 / 显示悬浮窗). A private + * page that may be missing or locked down, so it falls back to the app's + * system details page. Returns whether anything opened. + */ + fun openXiaomiPermissions(context: Context): Boolean { + val miui = Intent("miui.intent.action.APP_PERM_EDITOR") + .setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity") + .putExtra("extra_pkgname", context.packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + if (tryStart(context, miui)) return true + val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + return tryStart(context, details) + } + + private fun tryStart(context: Context, intent: Intent): Boolean = try { + context.startActivity(intent) + true + } catch (_: ActivityNotFoundException) { + false + } catch (_: SecurityException) { + false + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleTileService.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleTileService.kt new file mode 100644 index 00000000..f274c99f --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleTileService.kt @@ -0,0 +1,73 @@ +package com.xiangming.wechatbridge.bubble + +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.ComponentName +import android.content.Context +import android.os.Build +import android.service.quicksettings.Tile +import android.service.quicksettings.TileService +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R + +/** + * Quick Settings tile for on-demand access to the WeChatBridge staged panel. + * + * Requires no extra dangerous permissions. Tapping the tile collapses the shade + * and opens [BubblePanelWindow] directly over the foreground app (or falls back + * gracefully to the main app when overlay permission has not been granted). + */ +class BubbleTileService : TileService() { + override fun onStartListening() { + super.onStartListening() + refreshTile() + } + + override fun onClick() { + super.onClick() + val triggerIntent = BubblePanelTriggerActivity.intent(this) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + val pendingIntent = PendingIntent.getActivity( + this, + REQUEST_TILE_OPEN, + triggerIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + runCatching { startActivityAndCollapse(pendingIntent) } + } else { + @Suppress("DEPRECATION") + @SuppressLint("StartActivityAndCollapseDeprecated") + runCatching { startActivityAndCollapse(triggerIntent) } + } + } + + private fun refreshTile() { + val tile = qsTile ?: return + val container = (application as? App)?.container ?: return + val stagedCount = BubbleStaging.staged(container.relayStore.entries.value).size + val active = stagedCount > 0 || container.bubbleSettings.isEnabled + tile.state = if (active) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE + tile.label = getString(R.string.bubble_tile_label) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + tile.subtitle = if (stagedCount > 0) { + resources.getQuantityString(R.plurals.bubble_tile_subtitle, stagedCount, stagedCount) + } else { + getString(R.string.bubble_tile_subtitle_empty) + } + } + tile.updateTile() + } + + companion object { + private const val REQUEST_TILE_OPEN = 101 + + fun requestUpdate(context: Context) { + runCatching { + requestListeningState( + context.applicationContext, + ComponentName(context.applicationContext, BubbleTileService::class.java), + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleWindow.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleWindow.kt new file mode 100644 index 00000000..a2b396e5 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/BubbleWindow.kt @@ -0,0 +1,699 @@ +package com.xiangming.wechatbridge.bubble + +import android.animation.TimeInterpolator +import android.animation.ValueAnimator +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.PixelFormat +import android.graphics.Rect +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.util.DisplayMetrics +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.WindowInsets +import android.view.WindowManager +import android.widget.FrameLayout +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.TransformOrigin +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import com.xiangming.wechatbridge.ui.theme.WeChatGreen +import com.xiangming.wechatbridge.ui.theme.WeChatGreenDark +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import kotlin.math.cos +import kotlin.math.exp +import kotlin.math.roundToInt +import kotlin.math.sin +import kotlin.math.sqrt + +/** Touch target width and window height for the slim edge handle (64dp << Android's 200dp exclusion limit). */ +internal const val EDGE_TOUCH_WIDTH_DP = 26 +internal const val EDGE_PILL_WINDOW_WIDTH_DP = 188 +internal const val EDGE_WINDOW_HEIGHT_DP = 64 + +/** + * Slim translucent edge handle tucked flush to the LEFT or RIGHT screen edge. + * + * - Idle auto-fade: fades to alpha 0.28f after 3000ms without touch or arrival; restores on touch/arrival. + * - Incoming share micro-pill: expands inward for ~1800ms showing "+1 · 暂存 N 批" then springs back. + * - Gestures: tap or inward swipe opens the staged panel; vertical drag repositions along the edge; + * horizontal drag past screen midline snaps to the opposite edge with a damped spring. + * - Tightly sets `View.setSystemGestureExclusionRects` around the 64dp handle to avoid back-gesture conflicts. + */ +internal class BubbleWindow( + private val context: Context, + private val windowManager: WindowManager, + private val owner: OverlayOwner, + private val settings: BubbleSettings, + private val count: StateFlow, + private val pulse: StateFlow, + private val onTap: () -> Unit, +) { + private val density = context.resources.displayMetrics.density + private val handleWindowWidth = (EDGE_TOUCH_WIDTH_DP * density).roundToInt() + private val pillWindowWidth = (EDGE_PILL_WINDOW_WIDTH_DP * density).roundToInt() + private val windowHeight = (EDGE_WINDOW_HEIGHT_DP * density).roundToInt() + private val swipeOpenThreshold = SWIPE_OPEN_DP * density + + private val mainHandler = Handler(Looper.getMainLooper()) + private var snapAnimator: ValueAnimator? = null + private var currentWindowWidth = handleWindowWidth + private var pillExpandedWindow = false + + private val dockedEdge = MutableStateFlow(settings.placement.edge) + private val touched = MutableStateFlow(false) + private val interactionTick = MutableStateFlow(0) + private val microPillVisible = MutableStateFlow(false) + + private val hidePillRunnable = Runnable { + microPillVisible.value = false + mainHandler.removeCallbacks(shrinkWindowRunnable) + mainHandler.postDelayed(shrinkWindowRunnable, MICRO_PILL_EXIT_MILLIS) + } + + private val shrinkWindowRunnable = Runnable { + setPillWindowExpanded(false) + } + + @SuppressLint("RtlHardcoded") + private val params = WindowManager.LayoutParams( + handleWindowWidth, + windowHeight, + WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, + PixelFormat.TRANSLUCENT, + ).apply { + // Absolute LEFT: x counts from the left edge whatever the layout direction. + gravity = Gravity.TOP or Gravity.LEFT + title = "WeChatBridgeEdgeHandle" + } + + private val root: TouchLayer = TouchLayer(context).apply { + contentDescription = describe(count.value) + val compose = ComposeView(context).apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow) + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + setContent { + WeChatBridgeTheme { + val n by count.collectAsStateWithLifecycle() + val p by pulse.collectAsStateWithLifecycle() + val edge by dockedEdge.collectAsStateWithLifecycle() + val isTouched by touched.collectAsStateWithLifecycle() + val tick by interactionTick.collectAsStateWithLifecycle() + val pillShown by microPillVisible.collectAsStateWithLifecycle() + EdgeHandle( + count = n, + pulse = p, + edge = edge, + isTouched = isTouched, + interactionTick = tick, + microPillVisible = pillShown, + ) + } + } + } + addView(compose, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)) + owner.attach(this) + } + + var isShown = false + private set + + /** Adds the window; false when the system refuses (permission gone). */ + fun show(): Boolean { + if (isShown) { + root.visibility = View.VISIBLE + wakeIdleTimer() + root.updateExclusionRects() + return true + } + val placement = settings.placement + dockedEdge.value = placement.edge + place(placement) + return try { + windowManager.addView(root, params) + isShown = true + wakeIdleTimer() + root.updateExclusionRects() + true + } catch (_: RuntimeException) { + // BadTokenException / SecurityException when the overlay permission was withdrawn. + false + } + } + + fun setVisible(visible: Boolean) { + if (!visible) { + collapseMicroPillImmediately() + } + root.visibility = if (visible) View.VISIBLE else View.GONE + if (visible) { + wakeIdleTimer() + root.updateExclusionRects() + } + } + + /** Triggers the ~1800ms frosted micro-pill expansion on new incoming WeChat share. */ + fun showArrivalMicroPill() { + if (!isShown || root.visibility != View.VISIBLE) return + if (count.value <= 0) return + wakeIdleTimer() + mainHandler.removeCallbacks(hidePillRunnable) + mainHandler.removeCallbacks(shrinkWindowRunnable) + setPillWindowExpanded(true) + microPillVisible.value = true + mainHandler.postDelayed(hidePillRunnable, MICRO_PILL_DISPLAY_MILLIS) + } + + /** While text is dragged out of the panel: let drops through to the app below ([DragWindowFlags]). */ + fun setDragging(dragging: Boolean) { + val next = DragWindowFlags.flags(params.flags, dragging, focusableAtRest = false) + if (next == params.flags) return + params.flags = next + update() + } + + fun remove() { + snapAnimator?.cancel() + mainHandler.removeCallbacks(hidePillRunnable) + mainHandler.removeCallbacks(shrinkWindowRunnable) + microPillVisible.value = false + pillExpandedWindow = false + currentWindowWidth = handleWindowWidth + params.width = handleWindowWidth + if (!isShown) return + isShown = false + runCatching { windowManager.removeViewImmediate(root) } + } + + fun updateDescription(n: Int) { + root.contentDescription = describe(n) + } + + /** Rotation or a new display size: the same edge and height share. */ + fun reposition() { + if (!isShown) return + snapAnimator?.cancel() + collapseMicroPillImmediately() + val placement = settings.placement + dockedEdge.value = placement.edge + place(placement) + update() + root.updateExclusionRects() + } + + private fun wakeIdleTimer() { + interactionTick.update { it + 1 } + } + + private fun collapseMicroPillImmediately() { + mainHandler.removeCallbacks(hidePillRunnable) + mainHandler.removeCallbacks(shrinkWindowRunnable) + microPillVisible.value = false + setPillWindowExpanded(false) + } + + private fun setPillWindowExpanded(expanded: Boolean) { + if (pillExpandedWindow == expanded) return + pillExpandedWindow = expanded + val screen = screen() + val targetWidth = if (expanded) pillWindowWidth.coerceAtMost(screen.width) else handleWindowWidth + currentWindowWidth = targetWidth + params.width = targetWidth + params.x = BubbleGeometry.xFor(dockedEdge.value, screen.width, targetWidth) + BubbleWindowBlur.apply(params, enabled = expanded, density = density) + update() + root.updateExclusionRects() + } + + private fun describe(n: Int): String = + context.resources.getQuantityString(R.plurals.bubble_ball_description, n, n) + + private fun place(placement: BubblePlacement) { + val screen = screen() + params.width = currentWindowWidth + params.height = windowHeight + params.x = BubbleGeometry.xFor(placement.edge, screen.width, currentWindowWidth) + params.y = BubbleGeometry.yFor(placement.yFraction, screen.yRange) + } + + private fun update() { + if (!isShown) return + runCatching { windowManager.updateViewLayout(root, params) } + } + + private fun moveTo(x: Int, y: Int) { + val screen = screen() + params.x = BubbleGeometry.clampX(x, screen.width, currentWindowWidth) + params.y = y.coerceIn(0, (screen.height - windowHeight).coerceAtLeast(0)) + update() + } + + private fun settle(persistPlacement: Boolean = true) { + val screen = screen() + val placement = if (persistPlacement) { + BubbleGeometry.snap(params.x, params.y, screen.width, currentWindowWidth, screen.yRange).also { + settings.placement = it + dockedEdge.value = it.edge + } + } else { + settings.placement + } + val fromX = params.x + val fromY = params.y + val toX = BubbleGeometry.xFor(placement.edge, screen.width, currentWindowWidth) + val toY = BubbleGeometry.yFor(placement.yFraction, screen.yRange) + snapAnimator?.cancel() + snapAnimator = ValueAnimator.ofFloat(0f, 1f).apply { + duration = SNAP_MILLIS + interpolator = DampedSpringInterpolator() + addUpdateListener { + val t = it.animatedValue as Float + params.x = BubbleGeometry.clampX( + (fromX + (toX - fromX) * t).roundToInt(), + screen.width, + currentWindowWidth, + ) + params.y = (fromY + (toY - fromY) * t).roundToInt() + .coerceIn(0, (screen.height - windowHeight).coerceAtLeast(0)) + update() + } + start() + } + root.updateExclusionRects() + } + + /** Screen size and the band the handle may rest in (clear of the status and navigation bars). */ + private class Screen(val width: Int, val height: Int, val yRange: IntRange) + + private fun screen(): Screen { + val width: Int + val height: Int + val top: Int + val bottom: Int + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val metrics = windowManager.currentWindowMetrics + val insets = metrics.windowInsets.getInsetsIgnoringVisibility( + WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout(), + ) + width = metrics.bounds.width() + height = metrics.bounds.height() + top = insets.top + bottom = insets.bottom + } else { + val metrics = DisplayMetrics() + @Suppress("DEPRECATION") + windowManager.defaultDisplay.getRealMetrics(metrics) + width = metrics.widthPixels + height = metrics.heightPixels + top = (LEGACY_TOP_DP * density).roundToInt() + bottom = (LEGACY_BOTTOM_DP * density).roundToInt() + } + return Screen(width, height, BubbleGeometry.yRange(height, windowHeight, top, bottom)) + } + + /** + * Takes every touch from the ComposeView: + * - Tap or inward swipe opens the staged panel. + * - Vertical drag repositions along the edge. + * - Horizontal drag past screen midline snaps to the opposite edge. + * Also maintains tight [View.setSystemGestureExclusionRects] around the 64dp edge handle. + */ + private inner class TouchLayer(context: Context) : FrameLayout(context) { + private val slop = ViewConfiguration.get(context).scaledTouchSlop + private var downX = 0f + private var downY = 0f + private var startX = 0 + private var startY = 0 + private var dragging = false + private var downEdge = BubbleEdge.RIGHT + + init { + isClickable = true + isFocusable = false + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + super.onLayout(changed, left, top, right, bottom) + updateExclusionRects() + } + + fun updateExclusionRects() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return + val w = width.takeIf { it > 0 } ?: currentWindowWidth + val h = height.takeIf { it > 0 } ?: windowHeight + if (w <= 0 || h <= 0) return + val edgeRect = if (dockedEdge.value == BubbleEdge.LEFT) { + Rect(0, 0, handleWindowWidth.coerceAtMost(w), h) + } else { + Rect((w - handleWindowWidth).coerceAtLeast(0), 0, w, h) + } + systemGestureExclusionRects = listOf(edgeRect) + } + + override fun onInterceptTouchEvent(ev: MotionEvent): Boolean = true + + override fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + snapAnimator?.cancel() + touched.value = true + wakeIdleTimer() + downX = event.rawX + downY = event.rawY + downEdge = dockedEdge.value + startX = params.x + startY = params.y + dragging = false + } + MotionEvent.ACTION_MOVE -> { + val dx = event.rawX - downX + val dy = event.rawY - downY + if (!dragging && BubbleGeometry.isDrag(dx, dy, slop)) { + dragging = true + if (pillExpandedWindow) { + collapseMicroPillImmediately() + startX = params.x + } + } + if (dragging) moveTo(startX + dx.roundToInt(), startY + dy.roundToInt()) + } + MotionEvent.ACTION_UP -> { + touched.value = false + wakeIdleTimer() + val dx = event.rawX - downX + val dy = event.rawY - downY + val crossThreshold = screen().width * CROSS_MIDLINE_FRACTION + when ( + BubbleGeometry.classifyRelease( + edge = downEdge, + dx = dx, + dy = dy, + slop = slop, + swipeThreshold = swipeOpenThreshold, + crossThreshold = crossThreshold, + ) + ) { + BubbleGeometry.EdgeGesture.TAP -> { + collapseMicroPillImmediately() + performClick() + } + BubbleGeometry.EdgeGesture.OPEN_PANEL -> { + collapseMicroPillImmediately() + settle(persistPlacement = false) + performClick() + } + BubbleGeometry.EdgeGesture.REPOSITION -> settle(persistPlacement = true) + } + } + MotionEvent.ACTION_CANCEL -> { + touched.value = false + wakeIdleTimer() + if (dragging) settle(persistPlacement = true) + } + } + return true + } + + override fun performClick(): Boolean { + super.performClick() + onTap() + return true + } + } + + /** Critically-to-lightly damped spring curve for tactile edge snapping without harsh bounce. */ + private class DampedSpringInterpolator( + private val zeta: Double = 0.86, + private val omega: Double = 11.0, + ) : TimeInterpolator { + private val omegaD = omega * sqrt(1.0 - zeta * zeta) + private val endValue = raw(1.0) + + private fun raw(t: Double): Double { + val decay = exp(-zeta * omega * t) + return 1.0 - decay * (cos(omegaD * t) + (zeta * omega / omegaD) * sin(omegaD * t)) + } + + override fun getInterpolation(input: Float): Float { + if (input <= 0f) return 0f + if (input >= 1f) return 1f + return (raw(input.toDouble()) / endValue).toFloat() + } + } + + companion object { + private const val SNAP_MILLIS = 340L + private const val LEGACY_TOP_DP = 32 + private const val LEGACY_BOTTOM_DP = 56 + private const val SWIPE_OPEN_DP = 28f + private const val CROSS_MIDLINE_FRACTION = 0.32f + private const val MICRO_PILL_DISPLAY_MILLIS = 1_800L + private const val MICRO_PILL_EXIT_MILLIS = 260L + } +} + +private const val IDLE_DIM_DELAY_MILLIS = 3_000L +private const val IDLE_DIM_ALPHA = 0.28f + +/** + * 2026 极细半透明边缘把手 + 新分享入站微胶囊: + * - 平时紧贴左/右屏边缘,仅宽 5dp × 高 52dp 的微信绿微渐变胶囊条(外包 26dp 隐形舒适触控区); + * - 静止 3 秒后平滑半隐至 alpha = 0.28f,触碰或新分享到达时立刻恢复 1.0f; + * - 新分享入站时,从贴边一侧弹簧展开磨砂微胶囊(绿点 + `+1 · 暂存 N 批`),停留约 1.8 秒后回弹收起。 + */ +@Composable +internal fun EdgeHandle( + count: Int, + pulse: Int, + edge: BubbleEdge, + isTouched: Boolean = false, + interactionTick: Int = 0, + microPillVisible: Boolean = false, +) { + var prevCount by remember { mutableIntStateOf(count) } + var prevPulse by remember { mutableIntStateOf(0) } + var arrivalEvent by remember { mutableIntStateOf(0) } + + LaunchedEffect(count, pulse) { + val countIncreased = count > prevCount + val pulsed = pulse > prevPulse + prevCount = count + prevPulse = pulse + if ((countIncreased || pulsed) && count > 0) { + arrivalEvent++ + } + } + + // 入站轻盈呼吸脉动 + val breatheScale = remember { Animatable(1f) } + LaunchedEffect(arrivalEvent) { + if (arrivalEvent > 0) { + breatheScale.animateTo(1.12f, tween(durationMillis = 120)) + breatheScale.animateTo(1f, AppMotion.playfulSpring()) + } + } + + // 静止 3 秒后自动半隐至 0.28f,触碰、交互、微胶囊展开或新分享到达时立刻恢复 1.0f + var isIdle by remember { mutableStateOf(false) } + LaunchedEffect(isTouched, interactionTick, arrivalEvent, microPillVisible) { + isIdle = false + if (!isTouched && !microPillVisible) { + delay(IDLE_DIM_DELAY_MILLIS) + isIdle = true + } + } + + val handleAlpha by animateFloatAsState( + targetValue = if (isIdle) IDLE_DIM_ALPHA else 1f, + animationSpec = tween(durationMillis = if (isIdle) 320 else 120), + label = "edgeHandleIdleAlpha", + ) + + val barWidth by animateDpAsState( + targetValue = if (isTouched || microPillVisible) 6.dp else 4.8.dp, + animationSpec = AppMotion.snappySpring(), + label = "edgeBarWidth", + ) + val barHeight by animateDpAsState( + targetValue = if (isTouched || microPillVisible) 56.dp else 52.dp, + animationSpec = AppMotion.snappySpring(), + label = "edgeBarHeight", + ) + + val pillProgress by animateFloatAsState( + targetValue = if (microPillVisible && count > 0) 1f else 0f, + animationSpec = if (microPillVisible) AppMotion.playfulSpring() else tween(durationMillis = 200), + label = "edgeMicroPillProgress", + ) + + val isRight = edge == BubbleEdge.RIGHT + val handleShape = if (isRight) { + RoundedCornerShape(topStart = 999.dp, bottomStart = 999.dp, topEnd = 3.dp, bottomEnd = 3.dp) + } else { + RoundedCornerShape(topStart = 3.dp, bottomStart = 3.dp, topEnd = 999.dp, bottomEnd = 999.dp) + } + + val barBrush = Brush.verticalGradient( + colors = listOf(Color(0xFF0AD66C), WeChatGreen), + ) + + val handleBar: @Composable () -> Unit = { + Box( + contentAlignment = if (isRight) Alignment.CenterEnd else Alignment.CenterStart, + modifier = Modifier + .width(EDGE_TOUCH_WIDTH_DP.dp) + .fillMaxHeight() + .padding( + end = if (isRight) 2.dp else 0.dp, + start = if (isRight) 0.dp else 2.dp, + ), + ) { + Box( + modifier = Modifier + .width(barWidth) + .height(barHeight) + .graphicsLayer { + val s = breatheScale.value + scaleX = s + scaleY = s + alpha = handleAlpha + } + .shadow( + elevation = if (isIdle) 0.dp else 5.dp, + shape = handleShape, + ambientColor = WeChatGreenDark.copy(alpha = 0.35f), + spotColor = WeChatGreen.copy(alpha = 0.45f), + ) + .clip(handleShape) + .background(barBrush) + .border( + width = 0.75.dp, + color = Color.White.copy(alpha = if (isIdle) 0.22f else 0.42f), + shape = handleShape, + ), + ) { + if (count > 0) { + Box( + modifier = Modifier + .align(Alignment.TopCenter) + .padding(top = 5.dp) + .size(3.5.dp) + .clip(CircleShape) + .background(Color.White.copy(alpha = 0.92f)), + ) + } + } + } + } + + val microPill: @Composable () -> Unit = { + if (pillProgress > 0.01f && count > 0) { + val pillText = pluralStringResource(R.plurals.bubble_micro_pill, count, count) + val slideOffsetPx = (1f - pillProgress) * (if (isRight) 26f else -26f) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier + .padding(horizontal = 4.dp) + .graphicsLayer { + alpha = pillProgress.coerceIn(0f, 1f) + val s = 0.86f + 0.14f * pillProgress + scaleX = s + scaleY = s + translationX = slideOffsetPx + transformOrigin = TransformOrigin(if (isRight) 1f else 0f, 0.5f) + } + .shadow( + elevation = 8.dp, + shape = CircleShape, + ambientColor = Color.Black.copy(alpha = 0.28f), + spotColor = Color.Black.copy(alpha = 0.34f), + ) + .clip(CircleShape) + .background(Color(0xDE141A24)) + .border(0.75.dp, Color.White.copy(alpha = 0.18f), CircleShape) + .padding(horizontal = 11.dp, vertical = 6.dp), + ) { + Box( + modifier = Modifier + .size(7.dp) + .clip(CircleShape) + .background(WeChatGreen), + ) + Text( + text = pillText, + color = Color.White, + style = MaterialTheme.typography.labelMedium.copy( + fontSize = 11.5.sp, + fontWeight = FontWeight.SemiBold, + ), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = if (isRight) Arrangement.End else Arrangement.Start, + modifier = Modifier.fillMaxSize(), + ) { + if (isRight) { + microPill() + handleBar() + } else { + handleBar() + microPill() + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/OverlayOwner.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/OverlayOwner.kt new file mode 100644 index 00000000..d91c4247 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/bubble/OverlayOwner.kt @@ -0,0 +1,48 @@ +package com.xiangming.wechatbridge.bubble + +import android.view.View +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.ViewModelStoreOwner +import androidx.lifecycle.setViewTreeLifecycleOwner +import androidx.lifecycle.setViewTreeViewModelStoreOwner +import androidx.savedstate.SavedStateRegistry +import androidx.savedstate.SavedStateRegistryController +import androidx.savedstate.SavedStateRegistryOwner +import androidx.savedstate.setViewTreeSavedStateRegistryOwner + +/** + * What a ComposeView needs from its host when it lives in a WindowManager + * window instead of an Activity: a lifecycle (the recomposer follows it), a + * saved-state registry and a ViewModel store. Resumed for as long as the + * service runs; nothing is ever restored. + */ +internal class OverlayOwner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner { + private val registry = LifecycleRegistry(this) + private val savedState = SavedStateRegistryController.create(this) + + override val lifecycle: Lifecycle get() = registry + override val savedStateRegistry: SavedStateRegistry get() = savedState.savedStateRegistry + override val viewModelStore: ViewModelStore = ViewModelStore() + + fun create() { + savedState.performAttach() + savedState.performRestore(null) + registry.currentState = Lifecycle.State.RESUMED + } + + fun destroy() { + if (registry.currentState == Lifecycle.State.INITIALIZED) return + registry.currentState = Lifecycle.State.DESTROYED + viewModelStore.clear() + } + + /** Call on the root view of each overlay window before it is added. */ + fun attach(view: View) { + view.setViewTreeLifecycleOwner(this) + view.setViewTreeSavedStateRegistryOwner(this) + view.setViewTreeViewModelStoreOwner(this) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/Preferences.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/Preferences.kt new file mode 100644 index 00000000..1bf2d692 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/Preferences.kt @@ -0,0 +1,162 @@ +package com.xiangming.wechatbridge.data + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.core.stringSetPreferencesKey +import androidx.datastore.preferences.preferencesDataStoreFile +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import java.io.File +import androidx.datastore.preferences.core.Preferences as StoredPreferences + +/** + * What the user chooses, in DataStore Preferences. Port of the target, history + * and onboarding half of iOS `Preferences`; the key names are the iOS + * `UserDefaults` keys, so a future export reads the same on both. Scenes and + * group memory live in their own JSON files (android-plan §3.3), not here. + * + * Every value is a [Flow]; setters suspend until DataStore has written. + */ +class Preferences(private val store: DataStore) { + /** Everything at once, for screens that need a consistent view. */ + data class Snapshot( + val targetOrder: List = emptyList(), + val hiddenTargets: Set = emptySet(), + /** Target id → [DeliveryFormat.rawValue]. */ + val formatOverrides: Map = emptyMap(), + val lastTarget: String? = null, + /** 0 keeps everything (「从不」). */ + val retentionDays: Int = DEFAULT_RETENTION_DAYS, + val onboardingDone: Boolean = false, + ) { + /** The configured targets after order, visibility and format choices, last-used first. */ + fun targets(profiles: List = BuiltInTargets.all): List = + TargetProfile.arranged(profiles, targetOrder, hiddenTargets, formatOverrides, lastTarget) + } + + val snapshot: Flow = store.data.map(::decode).distinctUntilChanged() + + val targetOrder: Flow> = field { it.targetOrder } + val hiddenTargets: Flow> = field { it.hiddenTargets } + val formatOverrides: Flow> = field { it.formatOverrides } + val lastTarget: Flow = field { it.lastTarget } + val retentionDays: Flow = field { it.retentionDays } + val onboardingDone: Flow = field { it.onboardingDone } + + fun targets(profiles: List = BuiltInTargets.all): Flow> = + snapshot.map { it.targets(profiles) }.distinctUntilChanged() + + suspend fun current(): Snapshot = snapshot.first() + + suspend fun setTargetOrder(ids: List) { + store.edit { it[Key.TARGET_ORDER] = encodeList(ids) } + } + + suspend fun setHiddenTargets(ids: Set) { + store.edit { it[Key.HIDDEN_TARGETS] = ids } + } + + suspend fun setHidden(id: String, hidden: Boolean) { + store.edit { + val current = it[Key.HIDDEN_TARGETS].orEmpty() + it[Key.HIDDEN_TARGETS] = if (hidden) current + id else current - id + } + } + + /** `null` drops the override and the target's own default applies again. */ + suspend fun setFormatOverride(id: String, format: DeliveryFormat?) { + store.edit { + val current = decodeMap(it[Key.FORMAT_OVERRIDES]) + val next = if (format == null) current - id else current + (id to format.rawValue) + it[Key.FORMAT_OVERRIDES] = encodeMap(next) + } + } + + suspend fun setLastTarget(id: String?) { + store.edit { if (id == null) it.remove(Key.LAST_TARGET) else it[Key.LAST_TARGET] = id } + } + + /** Negative values are stored as 0 (keep everything). */ + suspend fun setRetentionDays(days: Int) { + store.edit { it[Key.RETENTION_DAYS] = days.coerceAtLeast(0) } + } + + suspend fun setOnboardingDone(done: Boolean) { + store.edit { it[Key.ONBOARDING_DONE] = done } + } + + private fun field(pick: (Snapshot) -> T): Flow = snapshot.map(pick).distinctUntilChanged() + + private fun decode(stored: StoredPreferences) = Snapshot( + targetOrder = decodeList(stored[Key.TARGET_ORDER]), + hiddenTargets = stored[Key.HIDDEN_TARGETS].orEmpty(), + formatOverrides = decodeMap(stored[Key.FORMAT_OVERRIDES]), + lastTarget = stored[Key.LAST_TARGET], + retentionDays = stored[Key.RETENTION_DAYS] ?: DEFAULT_RETENTION_DAYS, + onboardingDone = stored[Key.ONBOARDING_DONE] ?: false, + ) + + /** iOS `Preferences.Key` names. Order and overrides are JSON strings (DataStore has no list/map type). */ + object Key { + val TARGET_ORDER = stringPreferencesKey("com.xiangming.wechatbridge.ios.targetOrder") + val HIDDEN_TARGETS = stringSetPreferencesKey("com.xiangming.wechatbridge.ios.hiddenTargets") + val FORMAT_OVERRIDES = stringPreferencesKey("com.xiangming.wechatbridge.ios.targetFormatOverrides") + val LAST_TARGET = stringPreferencesKey("com.xiangming.wechatbridge.ios.lastTarget") + val RETENTION_DAYS = intPreferencesKey("com.xiangming.wechatbridge.historyRetentionDays") + val ONBOARDING_DONE = booleanPreferencesKey("com.xiangming.wechatbridge.ios.onboardingDone") + } + + companion object { + /** iOS `Preferences.defaultRetentionDays`. */ + const val DEFAULT_RETENTION_DAYS = 7 + const val FILE_NAME = "preferences" + + /** One instance per process: DataStore refuses two stores on the same file. */ + fun create( + context: Context, + scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()), + ): Preferences = create(scope) { context.applicationContext.preferencesDataStoreFile(FILE_NAME) } + + fun create(scope: CoroutineScope, file: () -> File): Preferences = + Preferences(PreferenceDataStoreFactory.create(scope = scope, produceFile = file)) + + // An unreadable value reads as the default rather than failing the whole snapshot. + private fun decodeList(raw: String?): List = raw?.let { + runCatching { Json.parseToJsonElement(it).jsonArray.mapNotNull { e -> e.jsonPrimitive.contentOrNull } } + .getOrNull() + } ?: emptyList() + + private fun decodeMap(raw: String?): Map = raw?.let { + runCatching { + Json.parseToJsonElement(it).jsonObject.mapNotNull { (k, v) -> v.jsonPrimitive.contentOrNull?.let { k to it } } + .toMap() + }.getOrNull() + } ?: emptyMap() + + private fun encodeList(ids: List): String = JsonArray(ids.map(::JsonPrimitive)).toString() + + private fun encodeMap(map: Map): String = + JsonObject(map.mapValues { JsonPrimitive(it.value) }).toString() + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/RelayStore.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/RelayStore.kt new file mode 100644 index 00000000..851dffc9 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/RelayStore.kt @@ -0,0 +1,539 @@ +package com.xiangming.wechatbridge.data + +import com.xiangming.wechatbridge.core.collection.BatchCollection +import com.xiangming.wechatbridge.core.collection.BatchCollectionLedger +import com.xiangming.wechatbridge.core.inbox.BatchOutcome +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.inbox.InboxReader +import com.xiangming.wechatbridge.core.inbox.ReadyBatch +import com.xiangming.wechatbridge.core.summary.RelayFiles +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.receive.CollectMarker +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import java.io.File +import java.nio.file.Files +import java.nio.file.FileVisitResult +import java.nio.file.LinkOption +import java.nio.file.Path +import java.nio.file.SimpleFileVisitor +import java.nio.file.attribute.BasicFileAttributes +import java.time.Clock +import java.time.Instant +import java.util.UUID +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** Where a batch stands with respect to delivery, from its `state.json` outcome. */ +enum class DeliveryStatus { + /** No outcome yet: waiting in the relay. */ + PENDING, + DELIVERED, + COPIED, + FAILED, + EXPIRED, + ; + + companion object { + fun of(outcome: BatchOutcome?): DeliveryStatus = when (outcome?.kind) { + null -> PENDING + BatchOutcome.Kind.DELIVERED -> DELIVERED + BatchOutcome.Kind.COPIED -> COPIED + BatchOutcome.Kind.FAILED -> FAILED + BatchOutcome.Kind.EXPIRED -> EXPIRED + } + } +} + +/** One relay card: the batch, its (possibly not yet computed) summary, and its standing. */ +data class RelayEntry( + val batch: ReadyBatch, + val summary: RelaySummary?, + /** A member of a collection that has not been delivered yet. */ + val isCollecting: Boolean, +) { + val id: UUID get() = batch.id + val delivery: DeliveryStatus get() = DeliveryStatus.of(batch.outcome) + val isDelivered: Boolean get() = delivery == DeliveryStatus.DELIVERED +} + +/** + * The relay's list, and the only writer of `ready/` and the collection ledger + * in the app. The receiver adds batches; everything that removes or annotates + * one goes through here. Port of iOS `RelayStore`. + * + * All disk work runs on [ioDispatcher] behind one [Mutex]; state is published + * through [StateFlow]s. Fire-and-forget calls ([refresh], [delete], [start]) + * run in [scope], which should outlive screens (the app's process scope). + * + * How `:app` keeps the list fresh (there is no App Group observer on Android, + * the receiver runs in the same process): + * - after `UriImporter` returns `ImportOutcome.Saved`, the receiver calls + * `(application as App).container.relayStore.refresh()`; + * - `MainActivity` calls [refresh] on `ON_START` and [flushDeletion] on `ON_STOP` + * (iOS commits on background: a deleted batch must not come back because the + * undo timer never fired); + * - [start] runs once per process (AppContainer does this). + */ +class RelayStore( + val inbox: Inbox, + /** `cacheDir/Relay`: unpacked archives ([RelayFiles.root] is pointed here). */ + private val relayFilesRoot: File, + /** `cacheDir/deliveries`: copies handed out through the FileProvider. */ + private val deliveriesDirectory: File, + private val scope: CoroutineScope, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val clock: Clock = Clock.systemUTC(), + private val summaryCache: SummaryCache = SummaryCache(), + private val undoWindow: Duration = UNDO_WINDOW, + private val deliveryLifetime: java.time.Duration = DELIVERY_LIFETIME, +) { + private val reader = InboxReader(inbox, clock) + private val lock = Mutex() + + /** Guarded by [lock]. */ + private var ledgerValue: BatchCollectionLedger? = null + private val summarizing = mutableSetOf() + private var deletionJob: Job? = null + + private val all = MutableStateFlow>(emptyList()) + private val _entries = MutableStateFlow>(emptyList()) + private val _pendingDeletion = MutableStateFlow>(emptySet()) + private val _ledger = MutableStateFlow(BatchCollectionLedger()) + private val _collections = MutableStateFlow>(emptyList()) + private val _lastError = MutableStateFlow(null) + + /** Visible cards, newest first; batches awaiting deletion are hidden. */ + val entries: StateFlow> = _entries.asStateFlow() + + /** Hidden from [entries] and deleted when the undo window closes. */ + val pendingDeletion: StateFlow> = _pendingDeletion.asStateFlow() + + /** A snapshot copy; mutate only through this store. */ + val ledger: StateFlow = _ledger.asStateFlow() + + /** Collections still in play (not delivered, not empty). */ + val collections: StateFlow> = _collections.asStateFlow() + + /** The last failure, for the UI to map to a message. Cleared by [clearError]. */ + val lastError: StateFlow = _lastError.asStateFlow() + + init { + RelayFiles.root = relayFilesRoot + } + + fun entry(id: UUID): RelayEntry? = all.value.firstOrNull { it.id == id } + + fun entries(ids: List): List = ids.mapNotNull(::entry) + + fun clearError() { + _lastError.value = null + } + + // region Loading + + /** Fire-and-forget [reload]: what the receiver and `ON_START` call. */ + fun refresh() { + scope.launch { reload() } + } + + suspend fun reload() { + withContext(ioDispatcher) { lock.withLock { reloadLocked() } } + summarizeMissing() + } + + /** Once per process: load, then age out history and debris. */ + fun start(retentionDays: suspend () -> Int) { + scope.launch { + reload() + pruneHistory(retentionDays()) + } + } + + private fun reloadLocked() { + runCatching { inbox.prepareDirectories() }.onFailure { _lastError.value = it } + val ledger = ledgerLocked() + val batches = reader.loadBatches() + ingestMarkedLocked(batches, ledger) + val known = all.value.associate { it.id to it.summary } + all.value = batches.map { batch -> + RelayEntry(batch, known[batch.id] ?: summaryCache.cached(batch), isCollecting(batch.id, ledger)) + } + publishLocked() + } + + /** 「分批收集」 batches join the open collection, oldest first. */ + private fun ingestMarkedLocked(batches: List, ledger: BatchCollectionLedger) { + val ids = unseenMarked(batches.map { it.directory }, ledger.seenBatchIDs) + if (ids.isEmpty()) return + for (id in ids) ledger.append(id, clock.instant()) + saveLedgerLocked() + } + + /** + * Parsing reads whole archives, so it runs on [ioDispatcher], one batch at + * a time, and is cached beside the batch for every later launch. + */ + private fun summarizeMissing() { + val missing = synchronized(summarizing) { + all.value.filter { it.summary == null && it.id !in summarizing } + .map { it.batch } + .also { list -> summarizing += list.map { it.id } } + } + if (missing.isEmpty()) return + scope.launch(ioDispatcher) { + for (batch in missing) { + val summary = runCatching { summaryCache.make(batch) }.getOrNull() + lock.withLock { + // A batch deleted meanwhile must not get its directory back. + if (summary != null && batch.directory.isDirectory) { + summaryCache.store(summary, batch) + all.update { list -> list.map { if (it.id == batch.id) it.copy(summary = summary) else it } } + publishLocked() + } + } + synchronized(summarizing) { summarizing -= batch.id } + } + } + } + + /** + * History older than the user's retention goes, except anything a + * collection still needs; then leftovers: staging debris, unpacked copies + * whose batch is gone, and old delivery packages. 0 keeps all history. + */ + suspend fun pruneHistory(retentionDays: Int) { + withContext(ioDispatcher) { + lock.withLock { + val now = clock.instant() + if (retentionDays > 0) { + val ledger = ledgerLocked() + val removed = reader.pruneHistory(retentionDays, now, ledger.protectedBatchIDs) + if (removed > 0) reloadLocked() + } + runCatching { inbox.pruneStaging(now = now) } + cleanCachesLocked() + cleanDeliveries(now) + } + } + } + + /** Unpacked copies whose batch is gone. */ + private fun cleanCachesLocked() { + val live = all.value.map { RelayFiles.directory(it.id).name }.toSet() + for (child in relayFilesRoot.listFiles().orEmpty()) { + if (child.name !in live) child.deleteRecursively() + } + } + + /** A target may still be reading a recent package, so only old ones go. */ + private fun cleanDeliveries(now: Instant) { + for (child in deliveriesDirectory.listFiles().orEmpty()) { + val newest = newestModification(child) ?: Instant.MIN + if (java.time.Duration.between(newest, now) > deliveryLifetime) child.deleteRecursively() + } + } + + // endregion + + // region Deleting, with a short undo window + + fun delete(ids: Set) { + if (ids.isEmpty()) return + _pendingDeletion.update { it + ids } + publish() + deletionJob?.cancel() + deletionJob = scope.launch { + delay(undoWindow) + commitPending() + } + } + + fun undoDeletion() { + deletionJob?.cancel() + deletionJob = null + _pendingDeletion.value = emptySet() + publish() + } + + /** Deletes whatever is pending now, without waiting for the timer. */ + suspend fun commitDeletion() { + deletionJob?.cancel() + deletionJob = null + commitPending() + } + + /** Fire-and-forget [commitDeletion], for `ON_STOP`. */ + fun flushDeletion() { + if (_pendingDeletion.value.isEmpty()) return + scope.launch { commitDeletion() } + } + + private suspend fun commitPending() { + val ids = _pendingDeletion.value + if (ids.isEmpty()) return + withContext(ioDispatcher) { + lock.withLock { + val ledger = ledgerLocked() + for (id in ids) { + try { + // Gone already (a commit cut short and retried): nothing to undo. + if (File(inbox.ready, id.toString().uppercase()).exists()) reader.discard(id) + RelayFiles.remove(id) + for (collection in ledger.collections.filter { id in it.batchIDs }) { + runCatching { ledger.remove(id, collection.id) } + } + } catch (e: Exception) { + _lastError.value = e + } + } + _pendingDeletion.update { it - ids } + saveLedgerLocked() + reloadLocked() + } + } + } + + // endregion + + // region Delivery bookkeeping + + suspend fun markDelivered( + ids: List, + targetName: String, + detail: String?, + chatName: String? = null, + sceneId: String? = null, + sceneName: String? = null, + ) { + recordOutcome(ids, BatchOutcome.Kind.DELIVERED, targetName, detail) { id -> + reader.recordContext(id, chatName, sceneId, sceneName) + } + } + + /** A failure or cancellation the history should show. */ + suspend fun markFailed(ids: List, targetName: String?, detail: String?) { + recordOutcome(ids, BatchOutcome.Kind.FAILED, targetName, detail) {} + } + + private suspend fun recordOutcome( + ids: List, + kind: BatchOutcome.Kind, + targetName: String?, + detail: String?, + extra: (UUID) -> Unit, + ) { + withContext(ioDispatcher) { + lock.withLock { + val outcome = BatchOutcome(kind, detail, clock.instant()) + for (id in ids) { + runCatching { + reader.recordOutcome(outcome, id, targetName) + extra(id) + }.onFailure { _lastError.value = it } + } + reloadLocked() + } + } + } + + // endregion + + // region Collections + + /** Adds to the collection being gathered, starting one if none is. */ + suspend fun addToCollection(id: UUID) = editLedger { it.append(id, clock.instant()) } + + suspend fun removeFromCollection(batchId: UUID, collection: UUID) = editLedger { it.remove(batchId, collection) } + + suspend fun renameCollection(id: UUID, name: String) = editLedger { it.rename(id, name) } + + suspend fun forgetCollection(id: UUID) = editLedger { it.forget(id) } + + /** Makes this the collection 「分批收集」 adds to; a no-op when it already is. */ + suspend fun resumeCollection(id: UUID) = editLedger { if (it.current?.id != id) it.resume(id) } + + /** Freezes the collection and returns its members, or null (see [lastError]). */ + suspend fun beginCollectionDelivery(id: UUID): List? { + var ids: List? = null + editLedger { ids = it.beginDelivery(id) } + return ids + } + + /** [detail] is the caller's localized text (iOS: 已投递 / 已取消). */ + suspend fun finishCollectionDelivery(id: UUID, succeeded: Boolean, target: String, detail: String, scene: String?) { + editLedger { it.finishDelivery(id, succeeded, target, detail, scene) } + } + + /** Time order, the order a merge reads in. */ + fun orderedBatchIds(collection: BatchCollection): List = + entries(collection.batchIDs) + .sortedBy { it.summary?.start ?: it.batch.createdAt } + .map { it.id } + + /** The batch with the latest messages: where the next batch picks up. */ + fun lastBatch(collection: BatchCollection): RelayEntry? = orderedBatchIds(collection).lastOrNull()?.let(::entry) + + fun collectionContaining(batchId: UUID): BatchCollection? = + _ledger.value.collections.firstOrNull { it.status != BatchCollection.Status.DELIVERED && batchId in it.batchIDs } + + /** + * The receipt's 「已收第 N 批」: how many batches the collection holding + * [batchId] has, this one included (iOS `CollectMarker.batchNumber`, read + * after the batch was taken). Null when no live collection holds it, e.g. + * a batch detached earlier, which the ledger never collects again. + */ + fun collectedBatchNumber(batchId: UUID): Int? = collectionContaining(batchId)?.batchIDs?.size + + /** The open collection (the one 「分批收集」 and 「加入收集」 add to), if any. */ + val currentCollection: BatchCollection? get() = _ledger.value.current + + /** + * Receipt 「加入收集」: [addToCollection] (continues the open collection, + * or starts one when none is open), then [collectedBatchNumber]. + */ + suspend fun collect(batchId: UUID): Int? { + addToCollection(batchId) + return collectedBatchNumber(batchId) + } + + /** + * A drop on a collection's page: that collection becomes the open one (as + * copying its keyword does, `resumeCollection`) and takes [batchId]; then + * its [collectedBatchNumber]. Null, with nothing changed, when the + * collection is gone, delivered, being delivered or empty. + */ + suspend fun joinCollection(batchId: UUID, collectionId: UUID): Int? { + val target = _ledger.value.collections.firstOrNull { it.id == collectionId } ?: return null + if (target.status == BatchCollection.Status.DELIVERED || target.status == BatchCollection.Status.DELIVERING) return null + if (target.batchIDs.isEmpty()) return null + resumeCollection(collectionId) + if (currentCollection?.id != collectionId) return null + return collect(batchId) + } + + /** + * The 「分批收集」 entry: the batch was committed with [CollectMarker], so a + * reload adopts it into the open collection (as every reload does); then + * its [collectedBatchNumber]. + */ + suspend fun adoptCollected(batchId: UUID): Int? { + reload() + return collectedBatchNumber(batchId) + } + + /** Applies [edit]; a refusal lands in [lastError]. The ledger is saved either way, as on iOS. */ + private suspend fun editLedger(edit: (BatchCollectionLedger) -> Unit) { + withContext(ioDispatcher) { + lock.withLock { + val ledger = ledgerLocked() + runCatching { edit(ledger) }.onFailure { _lastError.value = it } + saveLedgerLocked() + all.update { list -> list.map { it.copy(isCollecting = isCollecting(it.id, ledger)) } } + publishLocked() + } + } + } + + private val ledgerFile: File get() = File(inbox.root, LEDGER_FILE_NAME) + + private fun ledgerLocked(): BatchCollectionLedger { + ledgerValue?.let { return it } + val loaded = try { + BatchCollectionLedger.load(ledgerFile) + } catch (e: Exception) { + _lastError.value = e + BatchCollectionLedger() + } + loaded.recoverInterruptedDeliveries() + ledgerValue = loaded + saveLedgerLocked() + return loaded + } + + private fun saveLedgerLocked() { + val ledger = ledgerValue ?: return + runCatching { ledger.save(ledgerFile) }.onFailure { _lastError.value = it } + } + + private fun isCollecting(id: UUID, ledger: BatchCollectionLedger): Boolean = + ledger.collections.any { it.status != BatchCollection.Status.DELIVERED && id in it.batchIDs } + + // endregion + + private fun publishLocked() { + ledgerValue?.let { ledger -> + _ledger.value = ledger.copy() + _collections.value = ledger.collections.filter { + it.status != BatchCollection.Status.DELIVERED && it.batchIDs.isNotEmpty() + } + } + publish() + } + + private fun publish() { + val hidden = _pendingDeletion.value + _entries.value = all.value.filter { it.id !in hidden } + } + + companion object { + val UNDO_WINDOW: Duration = 5.seconds + + /** Same as staging: no target is still reading a package this old. */ + val DELIVERY_LIFETIME: java.time.Duration = java.time.Duration.ofMillis(30.minutes.inWholeMilliseconds) + + /** iOS `CollectMarker.ledgerURL(in:)`: `/collections.json`. */ + const val LEDGER_FILE_NAME = "collections.json" + + /** + * iOS `CollectMarker.unseen`: marked batches the ledger has not taken + * yet, in the order they landed (directory creation time, then id). + */ + fun unseenMarked(directories: List, seen: Set): List = + directories.mapNotNull { directory -> + val id = runCatching { UUID.fromString(directory.name) }.getOrNull() ?: return@mapNotNull null + if (id in seen || !CollectMarker.isMarked(directory)) return@mapNotNull null + val created = runCatching { + Files.readAttributes(directory.toPath(), BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS) + .creationTime().toInstant() + }.getOrDefault(Instant.MIN) + Triple(id, created, id.toString().uppercase()) + } + .sortedWith(compareBy> { it.second }.thenBy { it.third }) + .map { it.first } + + private fun newestModification(root: File): Instant? { + var newest: Instant? = null + runCatching { + Files.walkFileTree(root.toPath(), object : SimpleFileVisitor() { + override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult { + consider(attrs.lastModifiedTime().toInstant()) + return FileVisitResult.CONTINUE + } + + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + consider(attrs.lastModifiedTime().toInstant()) + return FileVisitResult.CONTINUE + } + + fun consider(time: Instant) { + if (newest == null || time.isAfter(newest)) newest = time + } + }) + } + return newest + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/SceneStore.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/SceneStore.kt new file mode 100644 index 00000000..8a8292f6 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/SceneStore.kt @@ -0,0 +1,145 @@ +package com.xiangming.wechatbridge.data + +import com.xiangming.wechatbridge.core.scene.GroupMemory +import com.xiangming.wechatbridge.core.scene.GroupName +import com.xiangming.wechatbridge.core.scene.SceneJson +import com.xiangming.wechatbridge.core.scene.SceneSettings +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.io.File +import java.io.IOException +import java.time.Clock +import java.time.Instant + +/** + * Scenes and group memory, in `/scenes.json` and + * `/group-memories.json` (android-plan §3.3). The JSON is what + * [SceneJson] writes, the same as the Swift `Codable` output the Mac and iOS + * apps keep under `scenes.v3` / `groupMemory.v1`, so a file moves between + * platforms unchanged. Port of the scene half of iOS `Preferences`. + * + * Blocking file IO behind one lock: call from a background dispatcher. The + * files are read on first use. A file that does not decode is kept beside the + * original as `.corrupt` and the defaults are used, as iOS falls back to + * `makeDefault()` / `[:]`, but without losing what was there. + */ +class SceneStore( + private val directory: File, + private val clock: Clock = Clock.systemUTC(), +) { + private val lock = Any() + private var loaded = false + private val _settings = MutableStateFlow(SceneSettings.makeDefault().installOfficialScenes()) + private val _memories = MutableStateFlow>(emptyMap()) + private val _lastError = MutableStateFlow(null) + + /** Valid after the first blocking call ([load], [current], any edit). */ + val settings: StateFlow = _settings.asStateFlow() + + /** Normalized group name ([GroupName.normalize]) to memory. */ + val memories: StateFlow> = _memories.asStateFlow() + + /** The last read or write failure, for diagnostics. */ + val lastError: StateFlow = _lastError.asStateFlow() + + val settingsFile: File get() = File(directory, SETTINGS_FILE) + val memoriesFile: File get() = File(directory, MEMORIES_FILE) + + data class Snapshot(val settings: SceneSettings, val memories: Map) + + /** Reads both files once; later calls are no-ops. */ + fun load() { + synchronized(lock) { loadLocked() } + } + + fun current(): Snapshot = synchronized(lock) { + loadLocked() + Snapshot(_settings.value, _memories.value) + } + + fun setSettings(settings: SceneSettings) { + synchronized(lock) { + loadLocked() + _settings.value = settings + write(settingsFile, SceneJson.encodeSettings(settings)) + } + } + + /** iOS `Preferences.rememberGroup`: after a delivery with a scene. A blank name is ignored. */ + fun rememberGroup(displayName: String, sceneID: String, senders: Set, end: Instant?) { + val key = GroupName.normalize(displayName) + if (key.isEmpty()) return + editMemories { memories -> + memories + (key to GroupMemory.advancing(memories[key], displayName, sceneID, senders, end, clock.instant())) + } + } + + /** iOS `Preferences.bind`: the scenes the user bound to a group, plus the speakers seen. */ + fun bind(displayName: String, sceneIDs: List, senders: Set) { + val key = GroupName.normalize(displayName) + if (key.isEmpty()) return + editMemories { memories -> + val existing = memories[key] ?: GroupMemory(displayName = displayName, updatedAt = clock.instant()) + val updated = existing.copy( + boundSceneIDs = sceneIDs, + senders = LinkedHashSet(existing.senders).apply { addAll(senders) }, + updatedAt = clock.instant(), + ) + memories + (key to updated) + } + } + + fun forgetGroup(displayName: String) { + val key = GroupName.normalize(displayName) + editMemories { it - key } + } + + private fun editMemories(edit: (Map) -> Map) { + synchronized(lock) { + loadLocked() + val next = edit(_memories.value) + _memories.value = next + write(memoriesFile, SceneJson.encodeMemories(next)) + } + } + + private fun loadLocked() { + if (loaded) return + loaded = true + read(settingsFile) { SceneJson.decodeSettings(it) }?.let { _settings.value = it } + read(memoriesFile) { SceneJson.decodeMemories(it) }?.let { _memories.value = it } + } + + private fun read(file: File, decode: (String) -> T): T? { + if (!file.isFile) return null + return try { + decode(file.readText(Charsets.UTF_8)) + } catch (e: Exception) { + _lastError.value = e + runCatching { file.copyTo(File(file.path + CORRUPT_SUFFIX), overwrite = true) } + null + } + } + + /** Temp file and rename in the same directory, so a crash never leaves half a file. */ + private fun write(file: File, text: String) { + try { + if (!directory.isDirectory && !directory.mkdirs()) throw IOException("cannot create $directory") + val temp = File(directory, ".${file.name}.tmp") + temp.writeText(text, Charsets.UTF_8) + if (!temp.renameTo(file)) { + file.delete() + if (!temp.renameTo(file)) throw IOException("cannot replace $file") + } + } catch (e: Exception) { + _lastError.value = e + } + } + + companion object { + const val SETTINGS_FILE = "scenes.json" + const val MEMORIES_FILE = "group-memories.json" + const val CORRUPT_SUFFIX = ".corrupt" + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/SummaryCache.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/SummaryCache.kt new file mode 100644 index 00000000..636b26b9 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/data/SummaryCache.kt @@ -0,0 +1,33 @@ +package com.xiangming.wechatbridge.data + +import com.xiangming.wechatbridge.core.inbox.ReadyBatch +import com.xiangming.wechatbridge.core.summary.RelaySummary +import java.io.File + +/** + * Card summaries, cached beside each batch as `relay-cache.json` exactly as on + * iOS (`RelaySummary.cached(in:)` / `store(in:)`), so the file follows the + * batch: deleting or pruning a batch takes its cache with it, and nothing + * under `cacheDir` can go stale. A thin seam over [RelaySummary] so + * [RelayStore] has one place to read, build and write summaries. + */ +class SummaryCache { + /** The stored summary, or null when missing, unreadable or of another schema version. */ + fun cached(batch: ReadyBatch): RelaySummary? = RelaySummary.cached(batch.directory) + + /** Parses the batch (reads whole archives: call off the main thread). Does not store. */ + fun make(batch: ReadyBatch): RelaySummary = RelaySummary.make(batch) + + /** + * Best effort: a refused write only costs a re-parse next launch. Never + * recreates a batch directory that has gone in the meantime. + */ + fun store(summary: RelaySummary, batch: ReadyBatch): Boolean { + if (!batch.directory.isDirectory) return false + return runCatching { summary.store(batch.directory) }.isSuccess + } + + fun invalidate(batch: ReadyBatch) { + File(batch.directory, RelaySummary.CACHE_FILE_NAME).delete() + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/DeliverUiState.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/DeliverUiState.kt new file mode 100644 index 00000000..5cdd819d --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/DeliverUiState.kt @@ -0,0 +1,256 @@ +package com.xiangming.wechatbridge.deliver + +import com.xiangming.wechatbridge.core.deliver.DeliveryFile +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.FormatChoice +import com.xiangming.wechatbridge.core.deliver.SendHint +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import com.xiangming.wechatbridge.core.scene.SceneMatchSource +import com.xiangming.wechatbridge.saf.TreeStatus + +/** One tile of the target grid. */ +data class TargetOption( + /** With the user's saved format override already applied. */ + val profile: TargetProfile, + /** Display name ([DeliverLabels.targetName]). */ + val name: String, + val installation: Installation, +) { + val id: String get() = profile.id + + /** Obsidian / folder: written through SAF, not sent (A4.1). */ + val isWriter: Boolean get() = profile.isWriter + + val isInstalled: Boolean get() = installation != Installation.NOT_INSTALLED +} + +data class SceneOption(val id: String, val name: String) + +/** Why no package could be planned. The UI maps these to text. */ +enum class PlanFailure { + /** A batch has no readable chat text (`DeliveryPlanException.NO_ARCHIVE`, or a parse failure known up front). */ + NO_TRANSCRIPT, + + /** Nothing in the target's chain can be built from these batches, not even the original files. */ + NO_FORMAT, + + /** Copying or unpacking failed (disk full, file gone). */ + IO, +} + +/** The preview section. */ +sealed interface Preview { + /** No target chosen (or the batches are still loading). */ + data object Idle : Preview + + data object Planning : Preview + + data class Ready( + val format: DeliveryFormat, + /** One Intent per group; the transcript, when it goes as a file, is first in the first. */ + val groups: List>, + /** File names this route leaves out (videos, documents…): 「未随附」. */ + val omitted: List, + /** The transcript rides in `EXTRA_TEXT` with the first group ([DeliveryFormat.INLINE_TEXT]). */ + val inlineText: Boolean, + /** Inline text was asked for but was too large, so it goes as a file. */ + val inlineFellBackToFile: Boolean, + ) : Preview { + val fileCount: Int get() = groups.sumOf { it.size } + } + + /** [canSendOriginal]: offer 「改发原始文件」 ([DeliverViewModel.sendOriginal]). */ + data class Failed(val reason: PlanFailure, val canSendOriginal: Boolean) : Preview + + /** + * Obsidian or folder: written through SAF, not sent. Whether a tree is + * picked and still granted is [DeliverUiState.folder]; sending is blocked + * ([SendBlock.NEEDS_FOLDER]) until it is [TreeStatus.GRANTED]. + */ + data class NeedsFolder(val kind: TargetKind) : Preview +} + +/** The SAF root of the selected Obsidian / folder target. */ +data class FolderState( + val kind: TargetKind, + val status: TreeStatus, + /** The picked root's display name (「写入:/」); null when unknown. */ + val folderName: String?, + /** The folder inside the root the note goes to (`微信流` unless set). */ + val subfolder: String, +) + +/** Why writing a note failed. The UI maps these to text. */ +enum class WriteFailure { + /** The grant or the folder is gone: ask to pick it again ([DeliverViewModel.requestFolder]). */ + FOLDER_LOST, + + /** The picker returned a folder the app could not keep access to. */ + NOT_GRANTED, + + /** Nothing readable to write. */ + UNREADABLE, + + /** A write failed and rolling it back left files behind. */ + CLEANUP_FAILED, + + /** Any other provider or disk failure. */ + IO, +} + +/** What the last Obsidian / folder write did; shown once, then [DeliverViewModel.consumeFeedback]. */ +sealed interface WriteFeedback { + /** [notes]: tree-relative paths, e.g. `微信流/项目群的聊天.md`. */ + data class Saved(val notes: List, val folderName: String?) : WriteFeedback + + data class Failed(val reason: WriteFailure, val message: String? = null) : WriteFeedback +} + +/** Groups handed over so far, out of [total]. */ +data class Progress(val sent: Int = 0, val total: Int = 0) { + val started: Boolean get() = sent > 0 + val complete: Boolean get() = total > 0 && sent >= total + + /** 1-based number of the next group: 「继续发送第 [next]/[total] 组」 once [started]. */ + val next: Int get() = sent + 1 + + /** True when the send button should read 「继续发送第 N/M 组」 rather than 「发送」. */ + val isContinuation: Boolean get() = started && !complete +} + +/** How the prompt went out with the first group. */ +enum class PromptRoute { + NONE, + + /** In `EXTRA_TEXT` only (clipboard copy failed or unavailable). */ + EXTRA_TEXT, + + /** Clipboard only: the target drops shared text; tell the user to paste. */ + CLIPBOARD, + + /** `EXTRA_TEXT` and the clipboard as backup. */ + BOTH, +} + +/** What the last send did; shown once, then [DeliverViewModel.consumeFeedback]. */ +sealed interface SendFeedback { + data class Sent( + /** 1-based number of the group that just went. */ + val group: Int, + val total: Int, + val route: Route, + val prompt: PromptRoute, + /** Null when nothing was copied this time (later groups, or no prompt). */ + val clipboard: PromptClipboard.Result?, + /** Pick / paste lines (`TargetProfile.sendHint`). */ + val hint: SendHint, + /** `EXTRA_TEXT` was dropped for size. */ + val textDropped: Boolean, + ) : SendFeedback { + val allSent: Boolean get() = group >= total + } + + data class NotInstalled(val packageNames: List) : SendFeedback + + data class Rejected(val reason: RejectReason) : SendFeedback + + data class LaunchFailed(val message: String?) : SendFeedback + + /** The collection could not be frozen for delivery (already delivered or gone); nothing was sent. */ + data object CollectionUnavailable : SendFeedback +} + +/** Why [DeliverUiState.canSend] is false. */ +enum class SendBlock { + LOADING, + + /** None of the batch ids is in the relay any more. */ + MISSING_BATCHES, + NO_TARGET, + NOT_INSTALLED, + PLANNING, + PLAN_FAILED, + + /** Obsidian / folder: see [Preview.NeedsFolder]. */ + NEEDS_FOLDER, + BUSY, + ALL_SENT, +} + +data class DeliverUiState( + val loading: Boolean = true, + val missingBatches: Boolean = false, + /** > 1: 「合并投递 N 批」. */ + val batchCount: Int = 0, + /** The chat or group name the scenes and group memory work with; often null on Android. */ + val chatName: String? = null, + /** Taken once on open: a delivery must not reorder the grid under the user's finger. */ + val targets: List = emptyList(), + val selectedTargetId: String? = null, + /** Enabled scenes; null [sceneId] is 「不带场景」. */ + val scenes: List = emptyList(), + val sceneId: String? = null, + /** Why the scene was preselected (group binding, keyword…). */ + val sceneSource: SceneMatchSource = SceneMatchSource.NONE, + /** Rendered from the scene; the user may edit it. Blank sends no prompt. */ + val prompt: String = "", + /** The format choice for the selected target, after the one-off override. */ + val formatChoice: FormatChoice? = null, + /** One-off format for this delivery only ([DeliverViewModel.chooseFormat]); never saved. */ + val formatOverride: DeliveryFormat? = null, + val preview: Preview = Preview.Idle, + val progress: Progress = Progress(), + val busy: Boolean = false, + val feedback: SendFeedback? = null, + /** The batches were recorded as 「已交给 X」 in this panel. */ + val delivered: Boolean = false, + /** Which group this is (A4.3); [GroupState.needsChoice] offers picking or creating one. */ + val group: GroupState = GroupState(), + /** Set for Obsidian / folder once the root has been checked; null while checking or for other targets. */ + val folder: FolderState? = null, + /** + * One-shot: launch `ActivityResultContracts.OpenDocumentTree` for this + * kind, then call [DeliverViewModel.onFolderPicked] (null on cancel). + */ + val folderRequest: TargetKind? = null, + val writeFeedback: WriteFeedback? = null, +) { + val selectedTarget: TargetOption? get() = targets.firstOrNull { it.id == selectedTargetId } + + val format: DeliveryFormat? get() = (preview as? Preview.Ready)?.format ?: formatChoice?.format + + /** Intent formats the user can switch to for this delivery. */ + val alternativeFormats: List get() = formatChoice?.alternatives.orEmpty() + + /** + * Offer 「改发原始 ZIP / 改发原始文件」: the plan failed but the originals can + * go, or the plan leaves files out and the ZIP route is available. + */ + val offersOriginal: Boolean + get() = when (val p = preview) { + is Preview.Failed -> p.canSendOriginal + is Preview.Ready -> p.format != DeliveryFormat.ARCHIVE && p.omitted.isNotEmpty() && + formatChoice?.canSwitchToArchive == true && !progress.started + else -> false + } + + val sendBlock: SendBlock? + get() { + val target = selectedTarget + return when { + loading -> SendBlock.LOADING + missingBatches -> SendBlock.MISSING_BATCHES + target == null -> SendBlock.NO_TARGET + !target.isInstalled -> SendBlock.NOT_INSTALLED + preview is Preview.NeedsFolder && folder?.status != TreeStatus.GRANTED -> SendBlock.NEEDS_FOLDER + preview is Preview.Planning || preview is Preview.Idle -> SendBlock.PLANNING + preview is Preview.Failed -> SendBlock.PLAN_FAILED + busy -> SendBlock.BUSY + progress.complete -> SendBlock.ALL_SENT + else -> null + } + } + + val canSend: Boolean get() = sendBlock == null +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/DeliverViewModel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/DeliverViewModel.kt new file mode 100644 index 00000000..d712e0c8 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/DeliverViewModel.kt @@ -0,0 +1,690 @@ +package com.xiangming.wechatbridge.deliver + +import android.content.Context +import android.net.Uri +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.AppContainer +import com.xiangming.wechatbridge.core.deliver.BatchContent +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.ui.settings.TargetsViewModel +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.DeliveryPackage +import com.xiangming.wechatbridge.core.deliver.DeliveryPlanException +import com.xiangming.wechatbridge.core.deliver.DeliveryPlanner +import com.xiangming.wechatbridge.core.deliver.FormatChoice +import com.xiangming.wechatbridge.core.deliver.FormatSelection +import com.xiangming.wechatbridge.core.deliver.PromptChannel +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import com.xiangming.wechatbridge.core.scene.GroupName +import com.xiangming.wechatbridge.core.note.NoteDelivery +import com.xiangming.wechatbridge.core.note.NoteDeliveryException +import com.xiangming.wechatbridge.core.scene.SceneMatchSource +import com.xiangming.wechatbridge.core.scene.SceneResolution +import com.xiangming.wechatbridge.core.scene.ScenePrompt +import com.xiangming.wechatbridge.core.scene.SceneSettings +import com.xiangming.wechatbridge.core.scene.GroupMemory +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.transcript.BatchInsights +import com.xiangming.wechatbridge.data.Preferences +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.data.SceneStore +import com.xiangming.wechatbridge.saf.TreeStatus +import com.xiangming.wechatbridge.saf.TreeStore +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.time.ZoneId +import java.util.UUID +import com.xiangming.wechatbridge.core.deliver.DeliveryRequest as PlanRequest + +/** + * The delivery panel's state machine. Port of the logic half of iOS + * `DeliverySheet`: pick a target, pick a scene, plan a preview, switch format, + * send, continue group by group, record the outcome, update group memory. + * + * Every action runs on the main thread ([viewModelScope]); planning and all + * disk work run on [ioDispatcher]. + * + * Android differences from iOS: + * - 「已交给 X」 is recorded as soon as the first group's `startActivity` + * returns (android-plan §2.3); there is no share-sheet completion to wait for, + * so there is no "cancelled" callback either. A launch that fails is recorded + * as failed instead. + * - Packages already handed out are not deleted on close: the target reads the + * URIs after we return. `RelayStore.pruneHistory` ages them out. + * - The one-off format ([chooseFormat], [sendOriginal]) is dropped when the + * target changes; on iOS `forceArchive` stays on for the whole sheet. + * - TXT + images go as they are; the iOS PDF folding and Photos export have no + * Android counterpart. + * - Obsidian and the folder are written through SAF ([TreeStore], A4.1): the + * panel shows [Preview.NeedsFolder] with [DeliverUiState.folder]; without a + * granted root, sending asks for one ([DeliverUiState.folderRequest]). + * - Which group this is goes through [SceneBinding] (A4.3): by fingerprint + * mostly, or picked / created by hand when not recognized. + */ +class DeliverViewModel( + batchIds: List, + private val relayStore: RelayStore, + private val preferences: Preferences, + private val sceneStore: SceneStore, + private val dispatch: Dispatch, + /** [PromptClipboard.copy]. */ + private val copyPrompt: (String) -> PromptClipboard.Result, + /** Package-manager lookup; runs on [ioDispatcher]. */ + private val installation: (TargetProfile) -> Installation, + /** A fresh, empty directory under `cacheDir/deliveries/` ([ShareFileProvider.newDeliveryDir]). */ + private val newWorkDirectory: () -> File, + private val labels: DeliverLabels = DeliverLabels.Plain, + /** Built-in plus custom profiles, before the user's arrangement. */ + private val profiles: List = BuiltInTargets.all, + /** Custom targets (「添加 App」) found in the saved order; runs on [ioDispatcher]. */ + private val customProfiles: (List) -> List = { emptyList() }, + /** Set when delivering a 分批收集 collection; frozen on the first send. */ + private val collectionId: UUID? = null, + /** Preselect this target (quick delivery) instead of the first in the grid. */ + private val initialTargetId: String? = null, + /** The SAF roots for Obsidian / folder; null leaves them at [SendBlock.NEEDS_FOLDER]. */ + private val trees: TreeStore? = null, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val zone: ZoneId = ZoneId.systemDefault(), +) : ViewModel() { + val batchIds: List = batchIds.distinct() + + private val _state = MutableStateFlow(DeliverUiState(batchCount = this.batchIds.size)) + val state: StateFlow = _state.asStateFlow() + + // Main-thread only. + private var entries: List = emptyList() + private var content = BatchContent(hasArchive = false) + private var allParseFailed = false + private var insights = BatchInsights.EMPTY + private var sceneSettings: SceneSettings = SceneSettings.makeDefault() + private var memories: Map = emptyMap() + /** The name group memory is kept under: the recognized group, else the chat name. */ + private var groupName: String? = null + private var pkg: DeliveryPackage? = null + private var planGeneration = 0 + private var closed = false + private val binding = SceneBinding(sceneStore) + /** The kind [onFolderPicked] applies to. */ + private var pickingKind: TargetKind? = null + + init { + viewModelScope.launch { load() } + } + + // region Loading + + private suspend fun load() { + entries = relayStore.entries(batchIds) + if (entries.size < batchIds.size) { + // Opened before the relay finished loading (a notification, a cold start). + runCatching { relayStore.reload() } + entries = relayStore.entries(batchIds) + } + if (entries.isEmpty()) { + _state.update { it.copy(loading = false, missingBatches = true, batchCount = 0) } + return + } + val summaries = entries.mapNotNull { it.summary } + allParseFailed = summaries.isNotEmpty() && summaries.size == entries.size && summaries.all { it.parseFailed } + val allImageEntries = entries.map { e -> + e.batch.items.isNotEmpty() && e.batch.items.all { DeliveryPlanner.isImage(it.displayName) } + } + val hasAnyReadable = entries.indices.any { idx -> entries[idx].summary?.parseFailed != true } + val allParseableOrImages = entries.indices.all { idx -> + entries[idx].summary?.parseFailed != true || allImageEntries[idx] + } + content = BatchContent( + // The archive route copies the received files as they are: 「原始文件」. + hasArchive = entries.all { e -> e.batch.items.isNotEmpty() && e.batch.items.all { it.file.isFile } }, + hasTranscript = hasAnyReadable && allParseableOrImages, + ) + val batchChatName = entries.firstNotNullOfOrNull { it.batch.chatName } + val title = summaries.firstOrNull { it.kind == RelaySummary.Kind.CHAT }?.title + + val snapshot = runCatching { preferences.current() }.getOrDefault(Preferences.Snapshot()) + val arranged = withContext(ioDispatcher) { + snapshot.targets(profiles + runCatching { customProfiles(snapshot.targetOrder) }.getOrDefault(emptyList())) + } + val batches = entries.map { it.batch } + val loaded = withContext(ioDispatcher) { + val options = arranged.map { TargetOption(it, labels.targetName(it), runCatching { installation(it) }.getOrDefault(Installation.NOT_INSTALLED)) } + val read = runCatching { BatchInsights.read(batches.flatMap { b -> b.items.map { it.file } }, zone) } + .getOrDefault(BatchInsights.EMPTY) + Triple(options, read, sceneStore.current()) + } + val (options, read, scenes) = loaded + insights = read + sceneSettings = scenes.settings + memories = scenes.memories + + val opening = binding.open(batchChatName, title, sceneSettings, memories, insights.senders) + val resolution = opening.resolution + groupName = opening.group.name + val sceneId = resolution.scene?.id + + val initial = options.firstOrNull { it.id == initialTargetId } + ?: options.firstOrNull { it.isInstalled } + ?: options.firstOrNull() + // One update: no observer sees the panel loaded without its first target. + _state.update { + it.copy( + loading = false, + batchCount = entries.size, + chatName = groupName, + group = opening.group, + targets = options, + selectedTargetId = initial?.id, + preview = Preview.Idle, + scenes = sceneSettings.enabledScenes.map { s -> SceneOption(s.id, s.name) }, + sceneId = sceneId, + sceneSource = resolution.source, + prompt = renderPrompt(sceneId), + ) + } + if (initial != null) replan() + } + + private fun renderPrompt(sceneId: String?): String { + val scene = sceneSettings.scene(sceneId) ?: return "" + val memory = groupName?.let { memories[GroupName.normalize(it)] } + return ScenePrompt.render(scene, memory?.lastSummaryAt, insights.end, zone = zone) ?: "" + } + + // endregion + + // region Actions + + fun selectTarget(id: String) { + val current = _state.value + if (current.loading || current.targets.none { it.id == id }) return + if (current.selectedTargetId == id) return + // Idle in the same update, so no observer ever sees the new target with the old plan. + _state.update { + it.copy(selectedTargetId = id, formatOverride = null, feedback = null, writeFeedback = null, folder = null, preview = Preview.Idle) + } + replan() + } + + /** Null is 「不带场景」. Re-renders the prompt, replacing any edit (as iOS). */ + fun selectScene(id: String?) { + val scene = sceneSettings.scene(id) + _state.update { it.copy(sceneId = scene?.id, prompt = renderPrompt(scene?.id)) } + } + + fun editPrompt(text: String) { + _state.update { it.copy(prompt = text) } + } + + /** + * One-off format for this delivery; null returns to the target's own. + * Never written to preferences (that is the settings page's override). + */ + fun chooseFormat(format: DeliveryFormat?) { + val target = _state.value.selectedTarget ?: return + if (_state.value.progress.started) return + if (format != null && (!target.profile.canChangeFormat || !format.usesIntent)) return + if (_state.value.formatOverride == format) return + _state.update { it.copy(formatOverride = format, feedback = null, preview = Preview.Idle) } + replan() + } + + /** 「改发原始 ZIP」 / 「改发原始文件」: the iOS `forceArchive`, for this delivery only. */ + fun sendOriginal() = chooseFormat(DeliveryFormat.ARCHIVE) + + fun consumeFeedback() { + _state.update { it.copy(feedback = null, writeFeedback = null) } + } + + /** + * Hands over the next group. [context] should be the panel's Activity. + * The first group also copies the prompt and records 「已交给 X」. + */ + fun send(context: Context) { + val current = _state.value + if (current.sendBlock == SendBlock.NEEDS_FOLDER && current.folder != null) { + // The same button: no folder yet (or lost) means pick one first. + requestFolder() + return + } + if (!current.canSend) return + // Cleared now, so the last send's feedback is never read as this one's. + _state.update { it.copy(feedback = null, writeFeedback = null) } + val writer = current.selectedTarget?.isWriter == true + viewModelScope.launch { if (writer) writeNote() else sendNext(context) } + } + + /** + * 「选择 Obsidian 库 / 文件夹」 (also 「重新选择」 after [WriteFailure.FOLDER_LOST]): + * raises [DeliverUiState.folderRequest] for the selected writer target. + */ + fun requestFolder() { + val target = _state.value.selectedTarget ?: return + if (!target.isWriter || _state.value.busy) return + pickingKind = target.profile.kind + _state.update { it.copy(folderRequest = target.profile.kind) } + } + + /** The UI has launched the picker for [DeliverUiState.folderRequest]. */ + fun consumeFolderRequest() { + _state.update { it.copy(folderRequest = null) } + } + + /** The `OpenDocumentTree` result; null when the user backed out. */ + fun onFolderPicked(uri: Uri?) { + val kind = pickingKind ?: return + pickingKind = null + _state.update { it.copy(folderRequest = null) } + val store = trees ?: return + if (uri == null) return + viewModelScope.launch { + val status = withContext(ioDispatcher) { runCatching { store.grant(kind, uri) }.getOrDefault(TreeStatus.LOST) } + if (status != TreeStatus.GRANTED) { + _state.update { it.copy(writeFeedback = WriteFeedback.Failed(WriteFailure.NOT_GRANTED)) } + } + if (_state.value.selectedTarget?.profile?.kind == kind) refreshFolder(kind, planGeneration) + } + } + + /** + * 「这是哪个群」: an existing group from [GroupState.known] or any name. + * Preselects that group's bound / last scene when it has one. + */ + fun chooseGroup(displayName: String) { + if (_state.value.loading || _state.value.delivered) return + val opening = binding.choose(displayName, sceneSettings, memories) ?: return + applyGroup(opening) + } + + /** 「新建群」: like [chooseGroup], and the group is remembered with this batch's speakers right away. */ + fun createGroup(displayName: String) { + if (_state.value.loading || _state.value.delivered) return + val opening = binding.choose(displayName, sceneSettings, memories) ?: return + val name = opening.group.name ?: return + applyGroup(opening) + viewModelScope.launch { + val updated = withContext(ioDispatcher) { binding.create(name, insights.senders) } + memories = updated + _state.update { it.copy(group = it.group.copy(known = binding.known(updated))) } + } + } + + /** + * 「以后这个群用这个场景」: binds the selected scene (none unbinds) to the + * group, with this batch's speakers, so the next batch from it is + * preselected by fingerprint. + */ + fun bindSceneToGroup() { + val name = groupName ?: return + val sceneId = _state.value.sceneId + viewModelScope.launch { + val updated = withContext(ioDispatcher) { binding.bind(name, sceneId, insights.senders) } + memories = updated + _state.update { + it.copy( + group = it.group.copy(known = binding.known(updated)), + sceneSource = if (sceneId != null && it.sceneId == sceneId) SceneMatchSource.BINDING else it.sceneSource, + ) + } + } + } + + private fun applyGroup(opening: SceneBinding.Opening) { + groupName = opening.group.name + val resolution: SceneResolution = opening.resolution + val scene = resolution.scene + _state.update { + val sceneId = scene?.id ?: it.sceneId + it.copy( + chatName = groupName, + group = opening.group, + sceneId = sceneId, + sceneSource = if (scene != null) resolution.source else it.sceneSource, + prompt = if (scene != null) renderPrompt(sceneId) else it.prompt, + ) + } + } + + /** Closing the panel: drops a package nothing was sent from. */ + fun close() { + closed = true + discardUnsent() + } + + override fun onCleared() { + discardUnsent() + } + + // endregion + + // region Planning + + private fun effectiveChoice(profile: TargetProfile, override: DeliveryFormat?): FormatChoice? { + val forced = override ?: if (allParseFailed && profile.canChangeFormat) DeliveryFormat.ARCHIVE else null + return FormatSelection.select(profile, content, forced) + } + + private fun canSendOriginal(profile: TargetProfile, format: DeliveryFormat?): Boolean = + profile.canChangeFormat && format != DeliveryFormat.ARCHIVE && FormatSelection.feasible(DeliveryFormat.ARCHIVE, content) + + private fun replan() { + discardUnsent() + pkg = null + val generation = ++planGeneration + val state = _state.value + val target = state.selectedTarget ?: return + val profile = target.profile + val choice = effectiveChoice(profile, state.formatOverride) + if (choice == null) { + val reason = if (!content.hasTranscript) PlanFailure.NO_TRANSCRIPT else PlanFailure.NO_FORMAT + _state.update { + it.copy(formatChoice = null, preview = Preview.Failed(reason, canSendOriginal(profile, null)), progress = Progress()) + } + return + } + if (profile.isWriter || !choice.format.usesIntent) { + _state.update { + it.copy(formatChoice = choice, preview = Preview.NeedsFolder(profile.kind), folder = null, progress = Progress(0, 1)) + } + refreshFolder(profile.kind, generation) + return + } + _state.update { it.copy(formatChoice = choice, preview = Preview.Planning, progress = Progress()) } + val batches = entries.map { it.batch } + viewModelScope.launch { + val result = withContext(ioDispatcher) { + runCatching { + val dir = newWorkDirectory() + DeliveryPlanner.plan(PlanRequest(batches, profile, prompt = null, format = choice.format, zone = zone), dir) + } + } + if (generation != planGeneration || closed) { + result.getOrNull()?.let { stale -> withContext(ioDispatcher) { stale.workDirectory.deleteRecursively() } } + return@launch + } + result.fold( + onSuccess = { planned -> + val total = if (planned.shares.isEmpty() && planned.inlineText != null) 1 else planned.shares.size + if (total == 0) { + withContext(ioDispatcher) { planned.workDirectory.deleteRecursively() } + _state.update { it.copy(preview = Preview.Failed(PlanFailure.NO_FORMAT, canSendOriginal(profile, choice.format))) } + return@fold + } + pkg = planned + _state.update { + it.copy( + preview = Preview.Ready( + format = planned.format, + groups = planned.shares, + omitted = planned.omitted, + inlineText = planned.inlineText != null, + inlineFellBackToFile = planned.inlineFellBackToFile, + ), + progress = Progress(0, total), + ) + } + }, + onFailure = { error -> + val failure = when ((error as? DeliveryPlanException)?.reason) { + DeliveryPlanException.Reason.NO_ARCHIVE -> PlanFailure.NO_TRANSCRIPT + DeliveryPlanException.Reason.UNSUPPORTED_FORMAT -> PlanFailure.NO_FORMAT + null -> PlanFailure.IO + } + val original = failure != PlanFailure.IO && canSendOriginal(profile, choice.format) + _state.update { it.copy(preview = Preview.Failed(failure, original)) } + }, + ) + } + } + + /** Checks the SAF root for [kind] off the main thread; stale results are dropped. */ + private fun refreshFolder(kind: TargetKind, generation: Int) { + if (kind != TargetKind.VAULT && kind != TargetKind.FOLDER) { + _state.update { it.copy(folder = FolderState(kind, TreeStatus.NOT_CHOSEN, null, NoteDelivery.DEFAULT_FOLDER)) } + return + } + viewModelScope.launch { + val folder = withContext(ioDispatcher) { folderState(kind) } + if (generation != planGeneration || _state.value.selectedTarget?.profile?.kind != kind) return@launch + _state.update { it.copy(folder = folder) } + } + } + + /** Blocking. */ + private fun folderState(kind: TargetKind): FolderState { + val store = trees ?: return FolderState(kind, TreeStatus.NOT_CHOSEN, null, NoteDelivery.DEFAULT_FOLDER) + return runCatching { + val status = store.status(kind) + FolderState(kind, status, if (status == TreeStatus.NOT_CHOSEN) null else store.folderName(kind), store.root(kind).effectiveSubfolder) + }.getOrDefault(FolderState(kind, TreeStatus.LOST, null, NoteDelivery.DEFAULT_FOLDER)) + } + + /** A package that has handed out nothing yet can go; one a target may be reading stays. */ + private fun discardUnsent() { + val unsent = pkg?.takeIf { !_state.value.progress.started } ?: return + pkg = null + unsent.workDirectory.deleteRecursively() + } + + // endregion + + // region Sending + + private suspend fun sendNext(context: Context) { + val state = _state.value + if (!state.canSend) return + val target = state.selectedTarget ?: return + val planned = pkg ?: return + val profile = target.profile + val index = state.progress.sent + val total = state.progress.total + _state.update { it.copy(busy = true, feedback = null) } + + if (index == 0 && collectionId != null && relayStore.beginCollectionDelivery(collectionId) == null) { + _state.update { it.copy(busy = false, feedback = SendFeedback.CollectionUnavailable) } + return + } + + val prompt = state.prompt.trim() + val first = index == 0 + val inlineToClipboard = first && planned.inlineText != null && profile.dropsSharedText + val clipboardText = if (first) { + listOfNotNull( + prompt.takeIf { it.isNotEmpty() }, + planned.inlineText?.takeIf { inlineToClipboard }, + ).joinToString("\n\n").ifEmpty { null } + } else { + null + } + val clipboard = clipboardText?.let { copyPrompt(it) } + val promptInExtra = first && prompt.isNotEmpty() && profile.promptChannel != PromptChannel.CLIPBOARD + val text = if (first) { + listOfNotNull(prompt.takeIf { promptInExtra }, planned.inlineText).joinToString("\n\n").ifEmpty { null } + } else { + null + } + val request = DeliveryRequest( + files = planned.shares.getOrNull(index).orEmpty().map { OutgoingFile(it.file, it.mimeType) }, + text = text, + chooserTitle = target.name, + ) + + when (val result = dispatch.dispatch(context, request, profile)) { + is DispatchResult.Sent -> { + val copied = clipboard is PromptClipboard.Result.Copied + val route = when { + !first || prompt.isEmpty() -> PromptRoute.NONE + promptInExtra && result.textAttached -> if (copied) PromptRoute.BOTH else PromptRoute.EXTRA_TEXT + else -> PromptRoute.CLIPBOARD + } + val feedback = SendFeedback.Sent( + group = index + 1, + total = total, + route = result.route, + prompt = route, + clipboard = clipboard, + hint = profile.sendHint(hasPrompt = first && (prompt.isNotEmpty() || inlineToClipboard), viaChooser = result.viaChooser), + textDropped = text != null && !result.textAttached, + ) + _state.update { it.copy(progress = it.progress.copy(sent = index + 1), feedback = feedback) } + if (first) record(target, labels.deliveredDetail(planned.format, result)) + _state.update { it.copy(busy = false, delivered = it.delivered || first) } + } + is DispatchResult.NotInstalled -> failed(target, index, SendFeedback.NotInstalled(result.packageNames), null) + is DispatchResult.Rejected -> failed(target, index, SendFeedback.Rejected(result.reason), null) + is DispatchResult.LaunchFailed -> + failed(target, index, SendFeedback.LaunchFailed(result.message), result.message ?: "launch failed") + } + } + + /** Obsidian / folder: `NoteDelivery.deliver` into the granted root, then 「已交给 X」. */ + private suspend fun writeNote() { + val state = _state.value + if (!state.canSend) return + val target = state.selectedTarget ?: return + val kind = target.profile.kind + val store = trees ?: return + _state.update { it.copy(busy = true, feedback = null, writeFeedback = null) } + + if (collectionId != null && relayStore.beginCollectionDelivery(collectionId) == null) { + _state.update { it.copy(busy = false, feedback = SendFeedback.CollectionUnavailable) } + return + } + val scene = sceneSettings.scene(state.sceneId) + val noteChatName = entries.firstNotNullOfOrNull { it.batch.chatName } ?: state.group.noteChatName + val sources = entries.flatMap { e -> e.batch.items.map { it.file } } + val result = withContext(ioDispatcher) { + runCatching { + val writer = store.writer(kind) ?: throw NoteDeliveryException(NoteDeliveryException.Reason.INVALID_FOLDER) + NoteDelivery.deliver( + sources = sources, + tree = writer, + subfolder = store.root(kind).subfolder, + chatName = noteChatName, + sceneName = scene?.name, + zone = zone, + ) + } + } + result.fold( + onSuccess = { notes -> + val folderName = _state.value.folder?.folderName + _state.update { + it.copy(progress = it.progress.copy(sent = 1, total = 1), writeFeedback = WriteFeedback.Saved(notes, folderName)) + } + val note = notes.firstOrNull { it.endsWith(".md") }?.substringAfterLast('/') + record(target, note ?: target.name) + _state.update { it.copy(busy = false, delivered = true) } + }, + onFailure = { error -> + // A revoked grant can surface as any IO error: ask the store, not the exception. + val folder = withContext(ioDispatcher) { folderState(kind) } + val reason = when { + folder.status != TreeStatus.GRANTED -> WriteFailure.FOLDER_LOST + error is NoteDeliveryException -> when (error.reason) { + NoteDeliveryException.Reason.NOT_CONFIGURED, + NoteDeliveryException.Reason.INVALID_FOLDER -> WriteFailure.FOLDER_LOST + NoteDeliveryException.Reason.UNREADABLE_ARCHIVE, + NoteDeliveryException.Reason.INVALID_SOURCE -> WriteFailure.UNREADABLE + NoteDeliveryException.Reason.CLEANUP_FAILED -> WriteFailure.CLEANUP_FAILED + } + else -> WriteFailure.IO + } + collectionId?.let { + relayStore.finishCollectionDelivery(it, false, target.name, labels.collectionCancelled(), scene?.name) + } + _state.update { + it.copy( + busy = false, + folder = if (it.selectedTarget?.profile?.kind == kind) folder else it.folder, + writeFeedback = WriteFeedback.Failed(reason, error.message), + ) + } + }, + ) + } + + private suspend fun failed(target: TargetOption, index: Int, feedback: SendFeedback, historyDetail: String?) { + _state.update { state -> + val targets = if (feedback is SendFeedback.NotInstalled) { + // Uninstalled since the panel opened: grey the tile out now. + state.targets.map { if (it.id == target.id) it.copy(installation = Installation.NOT_INSTALLED) else it } + } else { + state.targets + } + state.copy(feedback = feedback, targets = targets) + } + if (index == 0) { + collectionId?.let { + relayStore.finishCollectionDelivery(it, false, target.name, labels.collectionCancelled(), sceneName()) + } + // Only a real launch failure goes into history; nothing left the app otherwise. + if (historyDetail != null) relayStore.markFailed(batchIds, target.name, historyDetail) + } + _state.update { it.copy(busy = false) } + } + + private fun sceneName(): String? = sceneSettings.scene(_state.value.sceneId)?.name + + /** iOS `recordDelivery`: history, collection, group memory, last target. */ + private suspend fun record(target: TargetOption, detail: String?) { + val scene = sceneSettings.scene(_state.value.sceneId) + relayStore.markDelivered( + ids = entries.map { it.id }, + targetName = target.name, + detail = detail, + // A summary title is not a chat name: kept out of state.json so it is never read back as one. + chatName = _state.value.group.name.takeUnless { _state.value.group.needsChoice }, + sceneId = scene?.id, + sceneName = scene?.name, + ) + collectionId?.let { + relayStore.finishCollectionDelivery(it, true, target.name, labels.collectionDelivered(), scene?.name) + } + // A4.3: the group's memory advances (last scene, summary boundary, speakers). + val name = groupName + if (scene != null && name != null) { + memories = withContext(ioDispatcher) { binding.advance(name, scene.id, insights.senders, insights.end) } + } + runCatching { preferences.setLastTarget(target.id) } + } + + // endregion + + companion object { + /** For `viewModel { DeliverViewModel.create(container, batchIds) }`; unparsable ids are ignored. */ + fun create( + container: AppContainer, + batchIds: List, + collectionId: UUID? = null, + initialTargetId: String? = null, + ): DeliverViewModel { + val context = container.appContext + return DeliverViewModel( + batchIds = batchIds.mapNotNull { runCatching { UUID.fromString(it) }.getOrNull() }, + relayStore = container.relayStore, + preferences = container.preferences, + sceneStore = container.sceneStore, + dispatch = container.dispatch, + copyPrompt = container.promptClipboard::copy, + installation = { Installation.of(container.targetResolver.resolve(it)) }, + newWorkDirectory = { ShareFileProvider.newDeliveryDir(context, UUID.randomUUID().toString()) }, + labels = ResourceDeliverLabels(context), + collectionId = collectionId, + initialTargetId = initialTargetId, + trees = container.treeStore, + customProfiles = { order -> TargetsViewModel.customProfiles(order, container.targetResolver::customSpec) }, + ) + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/Dispatch.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/Dispatch.kt new file mode 100644 index 00000000..673d13f5 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/Dispatch.kt @@ -0,0 +1,101 @@ +package com.xiangming.wechatbridge.deliver + +import android.annotation.SuppressLint +import android.content.Context +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.TargetProfile + +/** + * The one call [DeliverViewModel] makes to hand a group over. Tests pass a + * fake; production is [IntentDispatch]. [context] should be the Activity the + * panel lives in (no `FLAG_ACTIVITY_NEW_TASK` then). + */ +fun interface Dispatch { + fun dispatch(context: Context, request: DeliveryRequest, profile: TargetProfile): DispatchResult +} + +/** Production [Dispatch]: the explicit Intent → package → chooser chain of [IntentDispatcher]. */ +class IntentDispatch(private val dispatcher: IntentDispatcher) : Dispatch { + override fun dispatch(context: Context, request: DeliveryRequest, profile: TargetProfile): DispatchResult = + dispatcher.dispatch(context, request, profile) +} + +/** Where a target stands on this device, as the grid shows it. */ +enum class Installation { + INSTALLED, + + /** A built-in or custom app that is not installed: the tile is greyed out and cannot send. */ + NOT_INSTALLED, + + /** The chooser or a SAF writer: nothing to install. */ + NOT_AN_APP, + ; + + companion object { + fun of(resolution: Resolution): Installation = when (resolution) { + is Resolution.Installed -> INSTALLED + is Resolution.NotInstalled -> NOT_INSTALLED + Resolution.NotAnApp -> NOT_AN_APP + } + } +} + +/** + * The words the view model has to write into history (`state.json` + * `targetName` and outcome detail). The panel's own wording stays in the UI. + */ +interface DeliverLabels { + /** 「已交给 X」's X: the target's display name. */ + fun targetName(profile: TargetProfile): String + + /** Outcome detail kept with the batch, like iOS 「TXT + 图片 · 去向」. */ + fun deliveredDetail(format: DeliveryFormat, result: DispatchResult.Sent): String? + + /** iOS `finishCollectionDelivery` detail for a collection whose delivery did not go out. */ + fun collectionCancelled(): String = "cancelled" + + /** Same, for one that went out. */ + fun collectionDelivered(): String = "delivered" + + /** Ids and raw values only: for tests, and before strings exist. */ + object Plain : DeliverLabels { + override fun targetName(profile: TargetProfile): String = profile.label ?: profile.id + override fun deliveredDetail(format: DeliveryFormat, result: DispatchResult.Sent): String = + listOfNotNull(format.rawValue, result.packageName ?: "chooser").joinToString(" · ") + } +} + +/** + * Looks names up by resource name: `TargetProfile.displayNameKey` + * (`target_chatgpt`…), `format_` and `deliver_collection_delivered` / + * `deliver_collection_cancelled`, which the panel task (A3.5) adds to + * `strings_deliver.xml`. Falls back to [DeliverLabels.Plain] for any missing one. + */ +class ResourceDeliverLabels(context: Context) : DeliverLabels { + private val appContext = context.applicationContext + + @SuppressLint("DiscouragedApi") + private fun string(name: String?): String? { + if (name.isNullOrEmpty()) return null + val id = appContext.resources.getIdentifier(name, "string", appContext.packageName) + return if (id == 0) null else appContext.getString(id) + } + + override fun targetName(profile: TargetProfile): String = + profile.label ?: string(profile.displayNameKey) ?: DeliverLabels.Plain.targetName(profile) + + override fun deliveredDetail(format: DeliveryFormat, result: DispatchResult.Sent): String? { + val formatName = string("format_${format.rawValue}") ?: format.rawValue + val where = result.packageName?.let { pkg -> + runCatching { + val pm = appContext.packageManager + pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() + }.getOrDefault(pkg) + } ?: string("deliver_via_chooser") + return listOfNotNull(formatName, where).joinToString(" · ") + } + + override fun collectionCancelled(): String = string("deliver_collection_cancelled") ?: super.collectionCancelled() + + override fun collectionDelivered(): String = string("deliver_collection_delivered") ?: super.collectionDelivered() +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/IntentDispatcher.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/IntentDispatcher.kt new file mode 100644 index 00000000..0cdc8e35 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/IntentDispatcher.kt @@ -0,0 +1,263 @@ +package com.xiangming.wechatbridge.deliver + +import android.app.Activity +import android.content.ActivityNotFoundException +import android.content.ClipData +import android.content.ClipDescription +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.Parcelable +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import java.io.File + +/** + * One file to hand over. [file] must already be a copy under + * `/deliveries/` (see [ShareFileProvider]); [displayName] is what + * the receiver sees as `OpenableColumns.DISPLAY_NAME` (defaults to the file name). + */ +data class OutgoingFile(val file: File, val mimeType: String, val displayName: String? = null) + +/** + * Everything one Intent carries. This is the minimal input A3.4 maps a planned + * delivery package to: one request per Intent (a group to send is one request). + */ +data class DeliveryRequest( + val files: List, + /** The prompt or inline transcript, as `EXTRA_TEXT`; dropped (and reported) when over [IntentDispatcher.MAX_INLINE_TEXT_BYTES]. */ + val text: String? = null, + val subject: String? = null, + /** Title of the system chooser, if it comes to that. */ + val chooserTitle: CharSequence? = null, +) + +/** Where a request goes. */ +sealed interface Destination { + /** A named app; [activity] is tried first, then the package alone, then the chooser. */ + data class App(val packageNames: List, val activity: String? = null) : Destination + + /** The system chooser. */ + data object Chooser : Destination + + companion object { + /** Null for the two SAF writers, which are not sent through an Intent. */ + fun of(profile: TargetProfile): Destination? = when { + profile.isWriter -> null + profile.kind == TargetKind.CHOOSER || profile.packageNames.isEmpty() -> Chooser + else -> App(profile.packageNames, profile.sendActivity) + } + } +} + +/** How far down the fallback chain a send went. */ +enum class Route { + /** `setClassName(package, activity)`. */ + EXPLICIT, + + /** `setPackage(package)`: the system picks the package's matching activity. */ + PACKAGE, + + /** `Intent.createChooser`; the user picks (the "pick X on the next screen" hint applies). */ + CHOOSER, +} + +enum class RejectReason { + /** No file and no text. */ + EMPTY, + + /** A file outside `/deliveries/`: never shared. */ + OUTSIDE_DELIVERIES, + + /** A file that does not exist (cleaned up, or never written). */ + MISSING_FILE, + + /** Text only, and too large for a Binder transaction. Send it as a file. */ + TEXT_TOO_LARGE, +} + +/** What [IntentDispatcher.dispatch] did. Never thrown: every case is a value. */ +sealed interface DispatchResult { + data class Sent( + val route: Route, + /** Null for [Route.CHOOSER] (the user picks). */ + val packageName: String?, + /** Set for [Route.EXPLICIT] only. */ + val activity: String?, + val uriCount: Int, + /** False when the request had text and it was dropped for size. */ + val textAttached: Boolean, + ) : DispatchResult { + val viaChooser: Boolean get() = route == Route.CHOOSER + } + + /** None of the target's packages is installed. Nothing was launched. */ + data class NotInstalled(val packageNames: List) : DispatchResult + + /** The request itself is unusable. Nothing was launched. */ + data class Rejected(val reason: RejectReason) : DispatchResult + + /** Every step, the chooser included, failed to start. */ + data class LaunchFailed(val message: String?) : DispatchResult +} + +/** + * Builds and sends share Intents (android-plan §3.5). + * + * - One file: `ACTION_SEND` + `EXTRA_STREAM`, `type` = the file's MIME. + * - Several: `ACTION_SEND_MULTIPLE` + `ArrayList`, `type` = the common + * MIME ("image/" + wildcard for all images, the full wildcard when mixed). + * - Always a `ClipData` holding every URI plus `FLAG_GRANT_READ_URI_PERMISSION`, + * or only the first URI of a multiple send is readable by the target. + * - Text goes in `EXTRA_TEXT` (and the first ClipData item, as the framework + * would do itself) when under ~100 KB. + * - Targeting: explicit activity → `setPackage` → chooser. A step is skipped + * when the package declares nothing that takes this action and MIME, + * because an explicit Intent would bypass the filter and hand the app + * something it never said it reads. + */ +class IntentDispatcher(private val resolver: TargetResolver) { + + /** The send Intent for [request], before any targeting. */ + sealed interface Built { + data class Ready(val intent: Intent, val uris: List, val textAttached: Boolean) : Built + data class Invalid(val reason: RejectReason) : Built + } + + fun build(context: Context, request: DeliveryRequest): Built { + val text = request.text?.takeIf { it.isNotEmpty() } + if (request.files.isEmpty() && text == null) return Built.Invalid(RejectReason.EMPTY) + for (item in request.files) { + if (!ShareFileProvider.isShareable(context, item.file)) return Built.Invalid(RejectReason.OUTSIDE_DELIVERIES) + if (!item.file.isFile) return Built.Invalid(RejectReason.MISSING_FILE) + } + val fits = text != null && fitsInline(text) + if (request.files.isEmpty() && !fits) return Built.Invalid(RejectReason.TEXT_TOO_LARGE) + + val streams = request.files.map { + ShareFileProvider.uriFor(context, it.file, it.displayName ?: it.file.name) to normalizedMime(it.mimeType) + } + val intent = buildSendIntent(streams, text.takeIf { fits }, request.subject) + return Built.Ready(intent, streams.map { it.first }, textAttached = fits) + } + + /** + * Sends [request] to [destination], starting from [context] (an Activity + * where possible; otherwise `FLAG_ACTIVITY_NEW_TASK` is added). + */ + fun dispatch(context: Context, request: DeliveryRequest, destination: Destination): DispatchResult { + val built = when (val b = build(context, request)) { + is Built.Invalid -> return DispatchResult.Rejected(b.reason) + is Built.Ready -> b + } + val base = built.intent + fun sent(route: Route, pkg: String?, activity: String?) = + DispatchResult.Sent(route, pkg, activity, built.uris.size, built.textAttached) + + if (destination is Destination.App) { + val resolution = resolver.resolve(destination.packageNames, destination.activity) + if (resolution is Resolution.NotInstalled) return DispatchResult.NotInstalled(resolution.packageNames) + if (resolution is Resolution.Installed) { + val pkg = resolution.packageName + val matching = resolver.matchingActivities(Intent(base).setPackage(pkg)) + val explicit = destination.activity?.takeIf { it in matching } + if (explicit != null && launch(context, Intent(base).setClassName(pkg, explicit))) { + return sent(Route.EXPLICIT, pkg, explicit) + } + if (matching.isNotEmpty() && launch(context, Intent(base).setPackage(pkg))) { + return sent(Route.PACKAGE, pkg, null) + } + } + } + val chooser = Intent.createChooser(base, request.chooserTitle).apply { + if (Build.VERSION.SDK_INT >= 24) { + putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS, ownReceivers(context)) + } + } + return try { + context.startActivity(chooser.withTaskFlag(context)) + sent(Route.CHOOSER, null, null) + } catch (e: RuntimeException) { + DispatchResult.LaunchFailed(e.javaClass.simpleName) + } + } + + /** Sends to a built-in or custom profile. The two SAF writers are not Intent targets and come back as [DispatchResult.LaunchFailed]. */ + fun dispatch(context: Context, request: DeliveryRequest, profile: TargetProfile): DispatchResult { + val destination = Destination.of(profile) + ?: return DispatchResult.LaunchFailed("target ${profile.id} is written through SAF, not sent") + return dispatch(context, request, destination) + } + + private fun launch(context: Context, intent: Intent): Boolean = try { + context.startActivity(intent.withTaskFlag(context)) + true + } catch (_: ActivityNotFoundException) { + false + } catch (_: SecurityException) { + // Not exported, or guarded by a permission we lack: try the next step. + false + } + + private fun Intent.withTaskFlag(context: Context): Intent = + if (context is Activity) this else addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + + private fun ownReceivers(context: Context): Array = arrayOf( + ComponentName(context.packageName, "${context.packageName}.receive.SaveAlias"), + ComponentName(context.packageName, "${context.packageName}.receive.CollectAlias"), + ) + + companion object { + /** Ceiling for `EXTRA_TEXT`, well under the 1 MB Binder transaction limit (§3.5). */ + const val MAX_INLINE_TEXT_BYTES = 100 * 1024 + + const val FALLBACK_MIME = "application/octet-stream" + + fun fitsInline(text: String): Boolean = text.toByteArray(Charsets.UTF_8).size <= MAX_INLINE_TEXT_BYTES + + fun normalizedMime(mime: String?): String { + val m = mime?.trim()?.lowercase().orEmpty() + val slash = m.indexOf('/') + return if (slash <= 0 || slash == m.length - 1) FALLBACK_MIME else m + } + + // Same MIME → it; same top-level type → "type/*"; otherwise "*/*". + fun commonMime(mimes: List): String { + val normalized = mimes.map(::normalizedMime).distinct() + if (normalized.isEmpty()) return "text/plain" + if (normalized.size == 1) return normalized.first() + val tops = normalized.map { it.substringBefore('/') }.distinct() + return if (tops.size == 1) "${tops.first()}/*" else "*/*" + } + + /** The untargeted send Intent for already-granted-able [streams] (URI to MIME). */ + fun buildSendIntent(streams: List>, text: String?, subject: String? = null): Intent { + val intent = when (streams.size) { + 0 -> Intent(Intent.ACTION_SEND).setType("text/plain") + 1 -> Intent(Intent.ACTION_SEND) + .setType(streams.first().second) + .putExtra(Intent.EXTRA_STREAM, streams.first().first) + else -> Intent(Intent.ACTION_SEND_MULTIPLE) + .setType(commonMime(streams.map { it.second })) + .putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(streams.map { it.first })) + } + if (text != null) intent.putExtra(Intent.EXTRA_TEXT, text) + if (subject != null) intent.putExtra(Intent.EXTRA_SUBJECT, subject) + if (streams.isNotEmpty()) { + val mimes = streams.map { it.second }.distinct().toTypedArray() + val clip = ClipData( + ClipDescription(CLIP_LABEL, mimes), + ClipData.Item(text, null, streams.first().first), + ) + streams.drop(1).forEach { clip.addItem(ClipData.Item(it.first)) } + intent.clipData = clip + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + return intent + } + + private const val CLIP_LABEL = "WeChatBridge delivery" + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/PromptClipboard.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/PromptClipboard.kt new file mode 100644 index 00000000..a2065864 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/PromptClipboard.kt @@ -0,0 +1,47 @@ +package com.xiangming.wechatbridge.deliver + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.os.Build +import androidx.core.content.getSystemService + +/** + * Puts the scene prompt on the clipboard before a send, as the backup for + * targets that drop `EXTRA_TEXT` (android-plan §3.5). + * + * From Android 13 the system shows its own "copied" confirmation; showing a + * Toast as well would say it twice, so callers check [Copied.systemConfirms] + * and only confirm themselves below 33. + */ +class PromptClipboard(context: Context) { + private val appContext = context.applicationContext + + sealed interface Result { + data class Copied(val systemConfirms: Boolean) : Result + + /** Blank prompt: nothing to copy, clipboard left alone. */ + data object NothingToCopy : Result + + /** No clipboard service, or it threw (some ROMs restrict background access). */ + data object Failed : Result + } + + fun copy(prompt: String?): Result { + if (prompt.isNullOrBlank()) return Result.NothingToCopy + val clipboard = appContext.getSystemService() ?: return Result.Failed + return try { + clipboard.setPrimaryClip(ClipData.newPlainText(LABEL, prompt)) + Result.Copied(systemConfirms = systemConfirmsCopy) + } catch (_: RuntimeException) { + Result.Failed + } + } + + companion object { + const val LABEL = "WeChatBridge prompt" + + /** Android 13+ shows a clipboard confirmation of its own. */ + val systemConfirmsCopy: Boolean get() = Build.VERSION.SDK_INT >= 33 + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/SceneBinding.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/SceneBinding.kt new file mode 100644 index 00000000..a49c4eb6 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/SceneBinding.kt @@ -0,0 +1,138 @@ +package com.xiangming.wechatbridge.deliver + +import com.xiangming.wechatbridge.core.scene.GroupMemory +import com.xiangming.wechatbridge.core.scene.GroupName +import com.xiangming.wechatbridge.core.scene.SceneResolution +import com.xiangming.wechatbridge.core.scene.SceneResolver +import com.xiangming.wechatbridge.core.scene.SceneSettings +import com.xiangming.wechatbridge.data.SceneStore +import java.time.Instant + +/** Where the panel's group name came from. */ +enum class GroupSource { + /** The batch itself carries the chat name. */ + CHAT_NAME, + + /** A remembered group, found by name (binding, keyword or last scene). */ + REMEMBERED, + + /** A remembered group, recognized by who speaks in the transcript ([com.xiangming.wechatbridge.core.scene.GroupFingerprint]). */ + FINGERPRINT, + + /** The user picked an existing group or created one in this panel. */ + MANUAL, + + /** Only the summary title ("张三与李四的聊天") is known: not recognized. */ + TITLE, + + /** Nothing at all. */ + NONE, +} + +/** A remembered group the user may pick when the panel cannot tell which group this is. */ +data class GroupOption(val key: String, val displayName: String) + +/** The group half of the panel. */ +data class GroupState( + /** What group memory is kept under; null when nothing is known. */ + val name: String? = null, + val source: GroupSource = GroupSource.NONE, + /** Remembered groups, most recently used first: the choices for [needsChoice]. */ + val known: List = emptyList(), +) { + /** Not recognized: offer 「选择群」 ([DeliverViewModel.chooseGroup]) and 「新建群」 ([DeliverViewModel.createGroup]). */ + val needsChoice: Boolean get() = source == GroupSource.TITLE || source == GroupSource.NONE + + /** + * The chat name to write into an Obsidian note. A summary title is not a + * chat name: [com.xiangming.wechatbridge.core.note.ObsidianNote.title] + * builds the same title from the participants itself. + */ + val noteChatName: String? get() = name.takeUnless { needsChoice } +} + +/** + * Group recognition for the delivery panel (A4.3): which group a batch is, + * which scene to preselect, and what to remember after a delivery. Called by + * [DeliverViewModel]; [SceneStore] keeps the memory. + * + * Android archives carry no group name, so recognition mostly goes by + * fingerprint: the speakers seen in a delivery are remembered with the group + * ([advance], [bind]), and the next batch from the same group is matched on + * them by [SceneResolver]. + */ +class SceneBinding(private val store: SceneStore) { + data class Opening(val resolution: SceneResolution, val group: GroupState) + + /** + * On opening the panel. [chatName] is the batch's own chat name (rarely + * known); [title] the summary title used when it is not. + */ + fun open( + chatName: String?, + title: String?, + settings: SceneSettings, + memories: Map, + senders: Set, + ): Opening { + val given = chatName ?: title + val resolution = SceneResolver.resolve(given, settings, memories, senders) + val name = resolution.groupName ?: given + val source = when { + resolution.usedFingerprint -> GroupSource.FINGERPRINT + name != null && memories.containsKey(GroupName.normalize(name)) -> GroupSource.REMEMBERED + chatName != null -> GroupSource.CHAT_NAME + title != null -> GroupSource.TITLE + else -> GroupSource.NONE + } + return Opening(resolution, GroupState(name, source, known(memories))) + } + + /** + * The user says which group this is: a remembered one, or a new name. + * Re-resolves the scenes for it, without the default scene, so a group + * with nothing bound keeps whatever scene the panel has. + */ + fun choose( + displayName: String, + settings: SceneSettings, + memories: Map, + ): Opening? { + val name = displayName.trim() + if (GroupName.normalize(name).isEmpty()) return null + val remembered = memories[GroupName.normalize(name)] + val resolution = SceneResolver.resolve(remembered?.displayName ?: name, settings, memories, allowDefault = false) + return Opening(resolution, GroupState(remembered?.displayName ?: name, GroupSource.MANUAL, known(memories))) + } + + /** + * Binds [sceneId] (null unbinds) to the group, and remembers [senders] so + * the next batch from it is recognized. Blocking file IO. + */ + fun bind(group: String, sceneId: String?, senders: Set): Map { + store.bind(group, listOfNotNull(sceneId), senders) + return store.memories.value + } + + /** + * After a successful delivery with a scene: `GroupMemory.advancing` + * (last scene, summary boundary, speakers). Without a scene or a group + * name nothing is remembered, as iOS. Blocking file IO. + */ + fun advance(group: String?, sceneId: String?, senders: Set, end: Instant?): Map { + if (group != null && sceneId != null) store.rememberGroup(group, sceneId, senders, end) + return store.memories.value + } + + /** 「新建群」: remembers the group with this batch's speakers, unless it is already known. Blocking file IO. */ + fun create(group: String, senders: Set): Map { + val key = GroupName.normalize(group) + if (key.isNotEmpty() && !store.memories.value.containsKey(key)) store.bind(group.trim(), emptyList(), senders) + return store.memories.value + } + + fun known(memories: Map): List = + memories.entries + .sortedByDescending { it.value.updatedAt } + .map { GroupOption(it.key, it.value.displayName) } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/ShareFileProvider.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/ShareFileProvider.kt new file mode 100644 index 00000000..9d07c4cb --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/ShareFileProvider.kt @@ -0,0 +1,62 @@ +package com.xiangming.wechatbridge.deliver + +import android.content.Context +import android.net.Uri +import androidx.core.content.FileProvider +import com.xiangming.wechatbridge.R +import java.io.File +import java.io.IOException + +/** + * The only provider other apps read from (android-plan §3.5). + * + * Authority `${applicationId}.share`; [R.xml.share_paths] maps nothing but + * `/deliveries/`. What leaves the app is always a copy made there, + * never an original under `inbox/`. A subclass so it cannot collide with a + * library's own `androidx.core.content.FileProvider` entry. + */ +class ShareFileProvider : FileProvider(R.xml.share_paths) { + companion object { + /** Must match `android:authorities` in AndroidManifest.xml. */ + fun authority(context: Context): String = "${context.packageName}$AUTHORITY_SUFFIX" + + const val AUTHORITY_SUFFIX = ".share" + + /** Directory name under `cacheDir`; must match share_paths.xml. */ + const val DELIVERIES = "deliveries" + + /** `/deliveries/`, created on demand. */ + fun deliveriesDir(context: Context): File = + File(context.cacheDir, DELIVERIES).apply { mkdirs() } + + /** Whether [file] lies inside [deliveriesDir] (after resolving `..` and links). */ + fun isShareable(context: Context, file: File): Boolean { + val root = runCatching { deliveriesDir(context).canonicalFile }.getOrNull() ?: return false + val target = runCatching { file.canonicalFile }.getOrNull() ?: return false + return target != root && target.path.startsWith(root.path + File.separator) + } + + /** + * The `content://` URI for a delivery copy. + * @throws IllegalArgumentException when [file] is outside [deliveriesDir]. + */ + fun uriFor(context: Context, file: File, displayName: String? = null): Uri { + require(isShareable(context, file)) { "only files under cacheDir/$DELIVERIES/ may be shared" } + return if (displayName != null) { + getUriForFile(context, authority(context), file, displayName) + } else { + getUriForFile(context, authority(context), file) + } + } + + /** A fresh, empty `/deliveries//` for one send. */ + @Throws(IOException::class) + fun newDeliveryDir(context: Context, name: String): File { + require(name.isNotBlank() && !name.contains('/') && name != "." && name != "..") { "bad directory name" } + val dir = File(deliveriesDir(context), name) + if (dir.exists()) dir.deleteRecursively() + if (!dir.mkdirs()) throw IOException("cannot create delivery directory") + return dir + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/TargetNames.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/TargetNames.kt new file mode 100644 index 00000000..7a2be2bb --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/TargetNames.kt @@ -0,0 +1,13 @@ +package com.xiangming.wechatbridge.deliver + +import android.annotation.SuppressLint +import android.content.Context +import com.xiangming.wechatbridge.core.deliver.TargetProfile + +/** Display name outside Compose (notifications): custom label, else the string resource, else the id. */ +@SuppressLint("DiscouragedApi") +fun TargetProfile.displayName(context: Context): String { + label?.let { return it } + val id = displayNameKey?.let { context.resources.getIdentifier(it, "string", context.packageName) } ?: 0 + return if (id != 0) context.getString(id) else this.id +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/TargetResolver.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/TargetResolver.kt new file mode 100644 index 00000000..cc433b81 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/deliver/TargetResolver.kt @@ -0,0 +1,126 @@ +package com.xiangming.wechatbridge.deliver + +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ResolveInfo +import android.os.Build +import com.xiangming.wechatbridge.core.deliver.CustomTargetSpec +import com.xiangming.wechatbridge.core.deliver.DeclaredReceiver +import com.xiangming.wechatbridge.core.deliver.MimeKind +import com.xiangming.wechatbridge.core.deliver.SendAction +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.deliver.TargetProfile + +/** Where an Intent target stands on this device. */ +sealed interface Resolution { + /** + * Installed. [activity] is the declared [TargetProfile.sendActivity] when the + * package still has it, otherwise the first activity that answers + * `SEND` with the full MIME wildcard in the package, or null when none does (then only + * `setPackage` or the chooser can work). + */ + data class Installed(val packageName: String, val activity: String?, val declaredActivityFound: Boolean) : Resolution + + /** None of [packageNames] is installed (or visible: see `` in the manifest). */ + data class NotInstalled(val packageNames: List) : Resolution + + /** The chooser, or a SAF writer: nothing to resolve. */ + data object NotAnApp : Resolution +} + +/** An installed app that takes shares, for the "add an app" list (A3.6). */ +data class ShareableApp(val packageName: String, val label: String) + +/** + * Package lookups for delivery. Never needs `QUERY_ALL_PACKAGES`: the manifest + * `` names every built-in package and the `SEND` / `SEND_MULTIPLE` + * intents, which is exactly what these queries ask about. + */ +class TargetResolver(context: Context) { + private val appContext = context.applicationContext + private val pm: PackageManager = appContext.packageManager + + fun isInstalled(packageName: String): Boolean = try { + packageInfo(packageName) + true + } catch (_: PackageManager.NameNotFoundException) { + false + } + + /** The first installed package of [profile], with its receiving activity. */ + fun resolve(profile: TargetProfile): Resolution { + if (profile.kind == TargetKind.CHOOSER || profile.isWriter || profile.packageNames.isEmpty()) { + return Resolution.NotAnApp + } + return resolve(profile.packageNames, profile.sendActivity) + } + + fun resolve(packageNames: List, sendActivity: String?): Resolution { + val pkg = packageNames.firstOrNull(::isInstalled) ?: return Resolution.NotInstalled(packageNames) + val receivers = sendReceivers(pkg) + val declared = sendActivity?.takeIf { it in receivers } + return Resolution.Installed(pkg, declared ?: receivers.firstOrNull(), declaredActivityFound = declared != null) + } + + /** Activity class names in [packageName] that answer `SEND` or `SEND_MULTIPLE` with any MIME. */ + fun sendReceivers(packageName: String): List = + SendAction.entries.flatMap { action -> + query(Intent(action.intentAction).setType("*/*").setPackage(packageName)) + }.mapNotNull { it.activityInfo?.name }.distinct() + + /** Class names of the activities that take [intent] (narrow it with `setPackage` first). */ + fun matchingActivities(intent: Intent): List = + query(intent).mapNotNull { it.activityInfo?.name }.distinct() + + /** + * What [packageName] declares for every [SendAction] × [MimeKind]: the + * complete probe [TargetProfile.custom] expects. Null when not installed. + */ + fun customSpec(packageName: String): CustomTargetSpec? { + if (!isInstalled(packageName)) return null + val receivers = SendAction.entries.flatMap { action -> + MimeKind.entries.mapNotNull { mime -> + val hit = query(Intent(action.intentAction).setType(mime.mimeType).setPackage(packageName)).firstOrNull() + hit?.let { DeclaredReceiver(action, mime, it.activityInfo?.name) } + } + } + return CustomTargetSpec(packageName, label(packageName) ?: packageName, receivers) + } + + /** Every other installed app that takes `SEND` or `SEND_MULTIPLE`, sorted by label. */ + fun shareableApps(): List = + SendAction.entries.flatMap { query(Intent(it.intentAction).setType("*/*")) } + .mapNotNull { it.activityInfo?.packageName } + .distinct() + .filter { it != appContext.packageName } + .map { ShareableApp(it, label(it) ?: it) } + .sortedBy { it.label.lowercase() } + + fun label(packageName: String): String? = runCatching { + pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString() + }.getOrNull() + + private fun packageInfo(packageName: String) = + if (Build.VERSION.SDK_INT >= 33) { + pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0)) + } else { + @Suppress("DEPRECATION") + pm.getPackageInfo(packageName, 0) + } + + private fun query(intent: Intent): List = + if (Build.VERSION.SDK_INT >= 33) { + pm.queryIntentActivities(intent, PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong())) + } else { + @Suppress("DEPRECATION") + pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) + } +} + +/** The framework action string for a [SendAction]. */ +val SendAction.intentAction: String + get() = when (this) { + SendAction.SEND -> Intent.ACTION_SEND + SendAction.SEND_MULTIPLE -> Intent.ACTION_SEND_MULTIPLE + } diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillAccess.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillAccess.kt new file mode 100644 index 00000000..ea4b0fe6 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillAccess.kt @@ -0,0 +1,68 @@ +package com.xiangming.wechatbridge.fill + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.provider.Settings +import com.xiangming.wechatbridge.R + +/** Whether 「一键填入」 can run, and the system pages that turn it on. */ +object FillAccess { + enum class State { + /** Turned on and connected: [FillAccessibilityService.running] is there. */ + READY, + + /** Turned on in settings, but the service is not connected (killed, or still starting). */ + NOT_RUNNING, + + OFF, + } + + fun state(context: Context): State = when { + FillAccessibilityService.running != null -> State.READY + isEnabled(context) -> State.NOT_RUNNING + else -> State.OFF + } + + fun isEnabled(context: Context): Boolean { + val setting = runCatching { + Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES) + }.getOrNull() + return FillServiceSetting.contains(setting, context.packageName, FillAccessibilityService::class.java.name) + } + + /** + * Android 13+ blocks turning on accessibility for a sideloaded app until + * 「允许受限设置」 is allowed on its app details page (⋮ menu). + */ + val mayBeRestricted: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU + + fun openAccessibilitySettings(context: Context): Boolean = + tryStart(context, Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)) + + fun openAppDetails(context: Context): Boolean = + tryStart(context, Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName))) + + private fun tryStart(context: Context, intent: Intent): Boolean = try { + context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + true + } catch (_: ActivityNotFoundException) { + false + } catch (_: SecurityException) { + false + } +} + +/** The toast for each [FillOutcome]. */ +object FillMessages { + fun toast(outcome: FillOutcome): Int = when (outcome) { + FillOutcome.FILLED -> R.string.fill_done + FillOutcome.TRUNCATED -> R.string.fill_truncated + FillOutcome.PASTED -> R.string.fill_pasted + FillOutcome.COPIED_ONLY -> R.string.fill_copied_only + FillOutcome.NO_TARGET -> R.string.fill_no_target + FillOutcome.FAILED -> R.string.fill_failed + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillAccessibilityService.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillAccessibilityService.kt new file mode 100644 index 00000000..6f4cca72 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillAccessibilityService.kt @@ -0,0 +1,329 @@ +package com.xiangming.wechatbridge.fill + +import android.accessibilityservice.AccessibilityService +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Intent +import android.graphics.Rect +import android.os.Bundle +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityNodeInfo +import android.view.accessibility.AccessibilityWindowInfo +import androidx.core.content.getSystemService +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import java.lang.ref.WeakReference + +/** + * 「一键填入」: puts a staged batch's text into the input box of the app in + * front (豆包, 千问, 元宝, ChatGPT…) at the cursor, and never sends: no button + * is clicked, no Enter is pressed. + * + * Only acts when the bubble panel's 「填入」 calls [fill]. The one event it + * listens to (a view taking focus) is used to remember which editable box was + * focused last, as a node reference; no node text is read, kept or logged + * outside [fill], and nothing leaves the device. + */ +class FillAccessibilityService : AccessibilityService() { + /** The editable box that last took focus in another app. */ + @Volatile + private var lastFocused: AccessibilityNodeInfo? = null + + override fun onServiceConnected() { + super.onServiceConnected() + current = WeakReference(this) + } + + override fun onAccessibilityEvent(event: AccessibilityEvent?) { + if (event?.eventType != AccessibilityEvent.TYPE_VIEW_FOCUSED) return + if (event.packageName?.toString() == packageName) return + val source = runCatching { event.source }.getOrNull() ?: return + if (isEditableCandidate(source) && !source.isPassword) lastFocused = source + } + + override fun onInterrupt() = Unit + + override fun onUnbind(intent: Intent?): Boolean { + clear() + return super.onUnbind(intent) + } + + override fun onDestroy() { + clear() + super.onDestroy() + } + + private fun clear() { + if (current?.get() === this) current = null + lastFocused = null + } + + /** + * Finds the input box (waiting [settle] ms first for the panel to go and + * focus to come back; expanding a collapsed fake input bar if present, or + * retrying once) and inserts [text]. When the foreground app hides its + * accessibility tree (e.g. WeChat 8.0+), copies [text] to the clipboard so + * the user can paste right away without reopening the panel. + */ + suspend fun fill(text: String, settle: Long = SETTLE_MS): FillOutcome = withContext(Dispatchers.Default) { + delay(settle) + var search = runCatching { searchTarget() }.getOrDefault(TargetSearch.NoWindow) + if (search is TargetSearch.NoEditable) { + val clicked = runCatching { expandPlaceholder(search.root, search.windowBottom) }.getOrDefault(false) + if (clicked) { + delay(EXPAND_MS) + search = runCatching { searchTarget() }.getOrDefault(TargetSearch.NoWindow) + } + } + if (search is TargetSearch.NoWindow || search is TargetSearch.NoEditable) { + delay(RETRY_MS) + search = runCatching { searchTarget() }.getOrDefault(TargetSearch.NoWindow) + } + when (val result = search) { + is TargetSearch.Found -> { + if (result.needsFocus) focusAndSettle(result.node) + runCatching { insert(result.node, text) }.getOrDefault(FillOutcome.FAILED) + } + TargetSearch.Shielded -> { + if (copyToClipboard(text)) FillOutcome.COPIED_ONLY else FillOutcome.FAILED + } + TargetSearch.NoWindow, is TargetSearch.NoEditable -> FillOutcome.NO_TARGET + } + } + + // region Finding the box + + private sealed interface TargetSearch { + data class Found(val node: AccessibilityNodeInfo, val needsFocus: Boolean) : TargetSearch + data class NoEditable(val root: AccessibilityNodeInfo, val windowBottom: Int) : TargetSearch + data object Shielded : TargetSearch + data object NoWindow : TargetSearch + } + + private fun searchTarget(): TargetSearch { + val all = windows.orEmpty() + val roots = all.map { runCatching { it.root }.getOrNull() } + val windowFacts = all.mapIndexed { i, w -> + WindowFacts( + isApplication = w.type == AccessibilityWindowInfo.TYPE_APPLICATION, + packageName = roots[i]?.packageName?.toString(), + layer = w.layer, + focused = w.isFocused, + active = w.isActive, + ) + } + val index = FillWindowRule.pick(windowFacts, packageName) ?: return TargetSearch.NoWindow + val window = all[index] + val root = roots[index] ?: return TargetSearch.NoWindow + + val focused = runCatching { root.findFocus(AccessibilityNodeInfo.FOCUS_INPUT) }.getOrNull() + ?.takeIf { it.windowId == window.id } + val focusedFacts = focused?.let(::facts) + if (FillWindowTree.isShielded(root.childCount, focusedFacts)) { + return TargetSearch.Shielded + } + + val remembered = lastFocused?.takeIf { it.windowId == window.id && runCatching { it.refresh() }.getOrDefault(false) } + val scanned = if (focusedFacts?.editable == true) emptyList() else editables(root) + return when (val target = FillTargetRule.choose(focusedFacts, remembered?.let(::facts), scanned.map(::facts))) { + FillTarget.Focused -> TargetSearch.Found(focused!!, needsFocus = false) + FillTarget.Remembered -> TargetSearch.Found(remembered!!, needsFocus = true) + is FillTarget.Scanned -> TargetSearch.Found(scanned[target.index], needsFocus = true) + FillTarget.None -> { + val bounds = Rect().also(window::getBoundsInScreen) + TargetSearch.NoEditable(root, bounds.bottom) + } + } + } + + /** Editable nodes in the window, breadth first, capped so a huge tree cannot stall us. */ + private fun editables(root: AccessibilityNodeInfo): List { + val found = ArrayList() + val queue = ArrayDeque().apply { add(root) } + var visited = 0 + while (queue.isNotEmpty() && visited < MAX_NODES) { + val node = queue.removeFirst() + visited++ + if (isEditableCandidate(node)) found += node + for (i in 0 until node.childCount) runCatching { node.getChild(i) }.getOrNull()?.let(queue::add) + } + return found + } + + /** + * Some chat apps (e.g. 千问) show a non-editable placeholder bar at the bottom + * and only mount their real `EditText` after the user taps it. Finds and + * taps such a bar if present. + */ + private fun expandPlaceholder(root: AccessibilityNodeInfo, windowBottom: Int): Boolean { + val candidates = ArrayList>() + val queue = ArrayDeque().apply { add(root) } + var visited = 0 + while (queue.isNotEmpty() && visited < MAX_NODES) { + val node = queue.removeFirst() + visited++ + val label = node.text?.toString().orEmpty().ifBlank { node.contentDescription?.toString().orEmpty() } + if (label.isNotBlank() && node.isVisibleToUser && node.isEnabled) { + val clickTarget = findClickableSelfOrAncestor(node) + if (clickTarget != null) { + val r = Rect().also(clickTarget::getBoundsInScreen) + candidates += clickTarget to PlaceholderFacts( + text = label, + clickable = clickTarget.isClickable, + visible = clickTarget.isVisibleToUser, + enabled = clickTarget.isEnabled, + left = r.left, + top = r.top, + right = r.right, + bottom = r.bottom, + ) + } + } + for (i in 0 until node.childCount) runCatching { node.getChild(i) }.getOrNull()?.let(queue::add) + } + val picked = FillPlaceholderRule.pick(candidates.map { it.second }, windowBottom) ?: return false + return candidates[picked].first.performAction(AccessibilityNodeInfo.ACTION_CLICK) + } + + private fun findClickableSelfOrAncestor(node: AccessibilityNodeInfo): AccessibilityNodeInfo? { + var cur: AccessibilityNodeInfo? = node + var depth = 0 + while (cur != null && depth < MAX_ANCESTOR_DEPTH) { + if (cur.isClickable && cur.isEnabled && cur.isVisibleToUser) return cur + cur = runCatching { cur.parent }.getOrNull() + depth++ + } + return null + } + + private fun isEditableCandidate(node: AccessibilityNodeInfo): Boolean = + node.isEditable || node.actionList.any { it.id == AccessibilityNodeInfo.ACTION_SET_TEXT } + + private fun facts(node: AccessibilityNodeInfo): NodeFacts { + val r = Rect().also(node::getBoundsInScreen) + return NodeFacts( + editable = isEditableCandidate(node), + visible = node.isVisibleToUser, + enabled = node.isEnabled, + focused = node.isFocused, + left = r.left, + top = r.top, + right = r.right, + bottom = r.bottom, + password = node.isPassword, + ) + } + + /** Focus (or, if focusing is refused, tap) the box and give it a beat to settle before writing. */ + private suspend fun focusAndSettle(node: AccessibilityNodeInfo) { + runCatching { node.refresh() } + if (node.isFocused) return + val focused = node.performAction(AccessibilityNodeInfo.ACTION_FOCUS) + if (!focused) node.performAction(AccessibilityNodeInfo.ACTION_CLICK) + delay(FOCUS_MS) + runCatching { node.refresh() } + } + + // endregion + + // region Writing + + private suspend fun insert(node: AccessibilityNodeInfo, text: String): FillOutcome { + val before = contentOf(node) + val insertion = FillText.compute( + current = node.text, + showingHint = node.isShowingHintText, + hint = node.hintText, + selectionStart = node.textSelectionStart, + selectionEnd = node.textSelectionEnd, + insert = text, + ) + val set = node.performAction( + AccessibilityNodeInfo.ACTION_SET_TEXT, + Bundle().apply { + putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, insertion.text) + }, + ) + if (set) { + delay(VERIFY_MS) + node.refresh() + when (FillText.verify(before, insertion.text, contentOf(node))) { + FillText.Check.OK -> { + select(node, insertion.cursor) + return FillOutcome.FILLED + } + FillText.Check.TRUNCATED -> { + select(node, contentOf(node).length) + return FillOutcome.TRUNCATED + } + FillText.Check.UNCHANGED -> Unit + } + } + return paste(node, text) + } + + /** The box's real content: empty while only its hint shows. */ + private fun contentOf(node: AccessibilityNodeInfo): String = + if (node.isShowingHintText) "" else node.text?.toString().orEmpty() + + private fun select(node: AccessibilityNodeInfo, cursor: Int) { + node.performAction( + AccessibilityNodeInfo.ACTION_SET_SELECTION, + Bundle().apply { + putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, cursor) + putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, cursor) + }, + ) + } + + /** The box refused `SET_TEXT`: put the text on the clipboard and paste it at the cursor. */ + private suspend fun paste(node: AccessibilityNodeInfo, text: String): FillOutcome { + if (!copyToClipboard(text)) return FillOutcome.FAILED + focusAndSettle(node) + return if (node.performAction(AccessibilityNodeInfo.ACTION_PASTE)) FillOutcome.PASTED else FillOutcome.COPIED_ONLY + } + + private suspend fun copyToClipboard(text: String): Boolean { + val clipboard = getSystemService() ?: return false + return withContext(Dispatchers.Main) { + runCatching { clipboard.setPrimaryClip(ClipData.newPlainText(CLIP_LABEL, text)) }.isSuccess + } + } + + // endregion + + companion object { + private const val SETTLE_MS = 200L + private const val EXPAND_MS = 350L + private const val RETRY_MS = 300L + private const val FOCUS_MS = 120L + private const val VERIFY_MS = 120L + private const val MAX_NODES = 3000 + private const val MAX_ANCESTOR_DEPTH = 4 + private const val CLIP_LABEL = "WeChatBridge" + + @Volatile + private var current: WeakReference? = null + + /** The connected service in this process, if the user turned it on. */ + val running: FillAccessibilityService? get() = current?.get() + } +} + +/** What [FillAccessibilityService.fill] did; the bubble turns it into a toast. */ +enum class FillOutcome { + FILLED, + + /** Written, but the box kept less than it was given (a length limit). */ + TRUNCATED, + + /** `SET_TEXT` refused; pasted from the clipboard instead. */ + PASTED, + + /** Paste refused or the app hides its accessibility tree; text is on the clipboard for a long-press paste. */ + COPIED_ONLY, + + NO_TARGET, + FAILED, +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillLogic.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillLogic.kt new file mode 100644 index 00000000..224111c3 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/fill/FillLogic.kt @@ -0,0 +1,249 @@ +package com.xiangming.wechatbridge.fill + +/** + * The testable half of 「一键填入」: which window and which input box to fill, + * what the box holds afterwards, whether the write took, and whether the + * accessibility service is turned on. No Android types; the service feeds in + * plain facts read from `AccessibilityWindowInfo` / `AccessibilityNodeInfo`. + * None of these keep or log any text they are given. + */ + +/** One window from `AccessibilityService.getWindows()`. */ +data class WindowFacts( + val isApplication: Boolean, + val packageName: String?, + val layer: Int, + val focused: Boolean, + val active: Boolean, +) + +object FillWindowRule { + const val SYSTEM_UI = "com.android.systemui" + + /** + * The window whose input box to fill: an application window that is not + * ours and not System UI. With several (split screen, a dialog over an + * app), the one holding input focus, else the active one, else the + * top-most layer. Returns its index in [windows], or null. + */ + fun pick(windows: List, ownPackage: String): Int? { + val candidates = windows.indices.filter { i -> + val w = windows[i] + w.isApplication && w.packageName != null && w.packageName != ownPackage && w.packageName != SYSTEM_UI + } + if (candidates.isEmpty()) return null + return candidates.firstOrNull { windows[it].focused } + ?: candidates.firstOrNull { windows[it].active } + ?: candidates.maxByOrNull { windows[it].layer } + } +} + +/** One node in the target window, as far as choosing an input box goes. */ +data class NodeFacts( + val editable: Boolean, + val visible: Boolean, + val enabled: Boolean, + val focused: Boolean, + val left: Int, + val top: Int, + val right: Int, + val bottom: Int, + val password: Boolean = false, +) { + val hasArea: Boolean get() = right > left && bottom > top + + /** Something a user could type into right now. Never a password box. */ + val usable: Boolean get() = editable && !password && visible && enabled && hasArea +} + +/** + * A non-editable clickable bar at the bottom of a chat app (e.g. 千问's + * "发消息或按住说话...") that mounts a real `EditText` only after being tapped. + */ +data class PlaceholderFacts( + val text: String, + val clickable: Boolean, + val visible: Boolean, + val enabled: Boolean, + val left: Int, + val top: Int, + val right: Int, + val bottom: Int, +) { + val width: Int get() = right - left + val height: Int get() = bottom - top + val hasArea: Boolean get() = width > 0 && height > 0 +} + +object FillWindowTree { + /** + * Whether the foreground app hides its accessibility hierarchy from + * non-screen-reader services (e.g. WeChat 8.0+ returns a 0-child root and + * a blank, invisible focus node). Retrying will not reveal an input box, + * so the service should fall back to clipboard copy right away. + */ + fun isShielded(rootChildCount: Int, focused: NodeFacts?): Boolean = + rootChildCount <= 0 && (focused == null || (!focused.editable && !focused.visible && !focused.hasArea)) +} + +object FillPlaceholderRule { + private val CUES = listOf( + "发消息", + "按住说话", + "输入", + "问千问", + "问豆包", + "问元宝", + "问我", + "说点什么", + "随便问", + "聊点什么", + "写消息", + "message", + "ask ", + "ask anything", + "type a", + ) + + private val EXCLUDED = setOf( + "发送", + "语音输入", + "扫一扫", + "添加附件", + "send", + ) + + /** + * Picks a bottom fake-input trigger to tap so the app mounts its real + * `EditText`. Requires a wide, visible, clickable node in the lower half + * of the window whose text contains a chat-input prompt cue. + */ + fun pick(candidates: List, windowBottom: Int): Int? { + if (windowBottom <= 0) return null + val minTop = (windowBottom * 0.55f).toInt() + val usable = candidates.indices.filter { i -> + val n = candidates[i] + if (!n.clickable || !n.visible || !n.enabled || !n.hasArea) return@filter false + if (n.top < minTop) return@filter false + if (n.width < n.height * 2) return@filter false + val label = n.text.trim() + if (label.isEmpty()) return@filter false + val lower = label.lowercase() + if (lower in EXCLUDED) return@filter false + CUES.any { lower.contains(it) } + } + if (usable.isEmpty()) return null + return usable.maxWithOrNull(compareBy({ candidates[it].bottom }, { candidates[it].width })) + } +} + +/** Where the text goes, in the order [FillTargetRule.choose] tries. */ +sealed interface FillTarget { + /** `findFocus(FOCUS_INPUT)` in the window, and it is editable. */ + data object Focused : FillTarget + + /** The editable box that last took focus (remembered from a focus event), still in the window. */ + data object Remembered : FillTarget + + /** Found by walking the window; [index] into the scanned list. Focus it before writing. */ + data class Scanned(val index: Int) : FillTarget + + data object None : FillTarget +} + +object FillTargetRule { + fun choose(focused: NodeFacts?, remembered: NodeFacts?, scanned: List): FillTarget { + if (focused != null && focused.editable && !focused.password && focused.visible) return FillTarget.Focused + if (remembered != null && remembered.usable) return FillTarget.Remembered + return pickScanned(scanned)?.let { FillTarget.Scanned(it) } ?: FillTarget.None + } + + /** + * Among the editable boxes found by walking the window: exactly one, that + * one; several, a focused one if any, else the lowest on screen (a chat + * input sits at the bottom), ties to the wider box. + */ + fun pickScanned(scanned: List): Int? { + val usable = scanned.indices.filter { scanned[it].usable } + if (usable.isEmpty()) return null + if (usable.size == 1) return usable.single() + usable.firstOrNull { scanned[it].focused }?.let { return it } + return usable.maxWithOrNull(compareBy({ scanned[it].bottom }, { scanned[it].right - scanned[it].left })) + } +} + +/** The box's new content and where the cursor goes. */ +data class Insertion(val text: String, val cursor: Int, val insertedAt: Int) + +object FillText { + /** + * The box's content after inserting [insert] at the cursor, replacing the + * selection if there is one. A box only showing its hint (or text equal + * to its hint) counts as empty. No cursor (-1) means the end. When the + * box already holds text and the character before the insertion point is + * not whitespace, a line break goes first, so a question typed first stays + * on its own line. + */ + fun compute( + current: CharSequence?, + showingHint: Boolean, + hint: CharSequence?, + selectionStart: Int, + selectionEnd: Int, + insert: String, + ): Insertion { + val existing = when { + current == null || showingHint -> "" + hint != null && hint.isNotEmpty() && current.toString() == hint.toString() -> "" + else -> current.toString() + } + val (start, end) = if (selectionStart < 0 || selectionEnd < 0 || existing.isEmpty()) { + existing.length to existing.length + } else { + val a = selectionStart.coerceIn(0, existing.length) + val b = selectionEnd.coerceIn(0, existing.length) + minOf(a, b) to maxOf(a, b) + } + val prefix = existing.substring(0, start) + val suffix = existing.substring(end) + val separator = if (prefix.isNotEmpty() && !prefix.last().isWhitespace()) "\n" else "" + val at = prefix.length + separator.length + return Insertion(prefix + separator + insert + suffix, at + insert.length, at) + } + + enum class Check { OK, TRUNCATED, UNCHANGED } + + /** + * After `ACTION_SET_TEXT` reported success: did the box take it? Content + * still equal to what was there before means it did not (fall back to + * paste); clearly shorter than expected means a length limit cut it. + * A couple of characters of slack for boxes that trim or normalize. + */ + fun verify(before: String, expected: String, after: CharSequence?): Check { + val now = after?.toString() ?: "" + if (now == expected) return Check.OK + if (now == before && expected != before) return Check.UNCHANGED + return if (now.length + TRUNCATION_SLACK < expected.length) Check.TRUNCATED else Check.OK + } + + const val TRUNCATION_SLACK = 2 +} + +object FillServiceSetting { + /** + * Whether `Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES` ([setting], a + * `:`-separated list of flattened component names, short `.Class` form + * allowed) contains [packageName]/[className]. + */ + fun contains(setting: String?, packageName: String, className: String): Boolean { + if (setting.isNullOrBlank()) return false + return setting.split(':').any { raw -> + val entry = raw.trim() + val slash = entry.indexOf('/') + if (slash <= 0 || slash == entry.length - 1) return@any false + val pkg = entry.substring(0, slash) + val cls = entry.substring(slash + 1).let { if (it.startsWith('.')) pkg + it else it } + pkg.equals(packageName, ignoreCase = true) && cls.equals(className, ignoreCase = true) + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/CollectActionReceiver.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/CollectActionReceiver.kt new file mode 100644 index 00000000..21ac76da --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/CollectActionReceiver.kt @@ -0,0 +1,42 @@ +package com.xiangming.wechatbridge.notify + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import com.xiangming.wechatbridge.App +import kotlinx.coroutines.launch +import java.util.UUID + +/** + * The notification's 「放弃」. Not exported: only our own PendingIntent reaches it. + * The ledger write runs in the app scope; [goAsync] keeps the process up meanwhile. + */ +class CollectActionReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != ACTION_ABANDON) return + val id = intent.getStringExtra(EXTRA_COLLECTION_ID)?.let { runCatching { UUID.fromString(it) }.getOrNull() } + val app = context.applicationContext as App + if (id == null) { + CollectNotification.cancel(app) + return + } + val pending = goAsync() + app.container.appScope.launch { + try { + CollectNotification.abandon(app, app.container.relayStore, id) + } finally { + pending.finish() + } + } + } + + companion object { + const val ACTION_ABANDON = "com.xiangming.wechatbridge.action.COLLECT_ABANDON" + const val EXTRA_COLLECTION_ID = "com.xiangming.wechatbridge.extra.COLLECTION_ID" + + fun abandonIntent(context: Context, collectionId: UUID): Intent = + Intent(context, CollectActionReceiver::class.java) + .setAction(ACTION_ABANDON) + .putExtra(EXTRA_COLLECTION_ID, collectionId.toString()) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/CollectNotification.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/CollectNotification.kt new file mode 100644 index 00000000..488e53e0 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/CollectNotification.kt @@ -0,0 +1,148 @@ +package com.xiangming.wechatbridge.notify + +import android.Manifest +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.NotificationChannelCompat +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.MainActivity +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.collection.BatchCollection +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.receive.DeliverLaunch +import kotlinx.coroutines.launch +import java.util.UUID +import java.util.concurrent.atomic.AtomicBoolean + +/** + * The ongoing 「收集中 · N 批」 notification while a collection is open + * (android-plan A4.4). Actions: 「完成并投递」 opens the delivery panel through + * [DeliverLaunch]; 「放弃」 goes to [CollectActionReceiver]. + * + * Without notification permission (Android 13+) or with notifications off, + * nothing is posted and nothing is asked: the permission request belongs to + * onboarding, and the whole flow still works inside the app. + */ +object CollectNotification { + const val CHANNEL_ID = "collect" + const val NOTIFICATION_ID = 0x0C011EC7 + + private const val REQUEST_DELIVER = 1 + private const val REQUEST_ABANDON = 2 + private const val REQUEST_OPEN = 3 + + private val restored = AtomicBoolean(false) + + /** Mirrors the store's open collection: posts or updates it, or cancels when none is open. */ + fun sync(context: Context, store: RelayStore) { + val current = store.currentCollection + update(context, current, current?.let(store::orderedBatchIds).orEmpty()) + } + + /** [orderedIds] is what 「完成并投递」 hands to the delivery panel, in merge order. */ + fun update(context: Context, collection: BatchCollection?, orderedIds: List) { + if (collection == null || collection.status != BatchCollection.Status.COLLECTING || collection.batchIDs.isEmpty()) { + cancel(context) + return + } + if (!canPost(context)) return + ensureChannel(context) + post(context, build(context, collection, orderedIds.ifEmpty { collection.batchIDs })) + } + + fun cancel(context: Context) { + NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID) + } + + /** 「放弃」 from the notification or the detail page: the group goes, its batches stay in the relay. */ + suspend fun abandon(context: Context, store: RelayStore, collectionId: UUID) { + store.forgetCollection(collectionId) + sync(context, store) + } + + /** + * Interruption recovery: once per process, reload the store and keep the + * notification in step with the ledger from then on (so a delivery that + * ends the collection elsewhere also clears it). Call from `App.onCreate` + * after the container exists. + */ + fun restore(context: Context) { + if (!restored.compareAndSet(false, true)) return + val app = context.applicationContext as App + val container = app.container + container.appScope.launch { + val store = container.relayStore + store.reload() + store.ledger.collect { sync(app, store) } + } + } + + fun canPost(context: Context): Boolean { + if (Build.VERSION.SDK_INT >= 33 && + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED + ) { + return false + } + return NotificationManagerCompat.from(context).areNotificationsEnabled() + } + + private fun ensureChannel(context: Context) { + val channel = NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_LOW) + .setName(context.getString(R.string.collect_channel_name)) + .setDescription(context.getString(R.string.collect_channel_description)) + .setShowBadge(false) + .build() + NotificationManagerCompat.from(context).createNotificationChannel(channel) + } + + private fun build(context: Context, collection: BatchCollection, orderedIds: List) = + NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_stat_wechatbridge) + .setContentTitle(context.getString(R.string.collect_notification_title, collection.batchIDs.size)) + .setContentText(context.getString(R.string.collect_notification_text)) + .setStyle(NotificationCompat.BigTextStyle().bigText(context.getString(R.string.collect_notification_text))) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setSilent(true) + .setShowWhen(false) + .setCategory(NotificationCompat.CATEGORY_PROGRESS) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setContentIntent(openApp(context)) + .addAction(0, context.getString(R.string.collect_notification_deliver), deliver(context, orderedIds)) + .addAction(0, context.getString(R.string.collect_notification_abandon), abandonIntent(context, collection.id)) + .build() + + @SuppressLint("MissingPermission") // checked in canPost + private fun post(context: Context, notification: android.app.Notification) { + runCatching { NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification) } + } + + private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity( + context, + REQUEST_OPEN, + Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + /** Straight to MainActivity, which opens the delivery panel for these batches. */ + internal fun deliver(context: Context, orderedIds: List): PendingIntent = PendingIntent.getActivity( + context, + REQUEST_DELIVER, + DeliverLaunch(orderedIds.map { it.toString().uppercase() }, targetId = null).intent(context), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + internal fun abandonIntent(context: Context, collectionId: UUID): PendingIntent = PendingIntent.getBroadcast( + context, + REQUEST_ABANDON, + CollectActionReceiver.abandonIntent(context, collectionId), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/QuickDeliverNotification.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/QuickDeliverNotification.kt new file mode 100644 index 00000000..9f6dfb8a --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/notify/QuickDeliverNotification.kt @@ -0,0 +1,165 @@ +package com.xiangming.wechatbridge.notify + +import android.Manifest +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.deliver.QuickDeliver +import com.xiangming.wechatbridge.receive.DeliverLaunch +import java.time.Instant +import java.util.UUID + +/** + * 「已存入 · 投给 X」: after a plain save, one notification whose tap opens the + * delivery panel with the last target preselected (android-plan A4.7). + * + * The [PendingIntent] points straight at `MainActivity` via [DeliverLaunch.intent] + * (Android 12+ forbids notification trampolines). The panel only preselects, so + * cancelling the target app's chooser leaves the user on the panel; the + * [QuickDeliver.Ledger] keeps each batch to one notification and one hand-off. + * + * Without notification permission nothing is posted: the save has succeeded anyway. + */ +object QuickDeliverNotification { + const val CHANNEL_ID = "quick_deliver" + + /** Fixed id; the batch string is the tag, so each batch has its own slot. */ + const val NOTIFICATION_ID = 0x51D + + private val lock = Any() + private var ledger = QuickDeliver.Ledger() + + /** + * Posts the notification for [batchId] if [QuickDeliver.decide] allows it and + * notifications are permitted. [others] become action buttons (iOS's + * 「长按换目标」), up to [QuickDeliver.MAX_TARGETS] including the main target. + * Returns whether a notification was posted. + */ + fun post( + context: Context, + batchId: UUID, + targetId: String, + targetName: String, + head: String? = null, + others: List = emptyList(), + collect: Boolean = false, + enabled: Boolean = true, + savedAt: Instant = Instant.now(), + now: Instant = Instant.now(), + ): Boolean { + val target = QuickDeliver.Target(targetId, targetName) + if (!canNotify(context)) return false + synchronized(lock) { + val decision = QuickDeliver.decide(enabled, collect, target, batchId, savedAt, now, ledger) + if (decision !is QuickDeliver.Decision.Post) return false + ledger.markPosted(batchId) + } + val app = context.applicationContext + ensureChannel(app) + val targets = (listOf(target) + others.filter { it.id != targetId && it.id.isNotBlank() }) + .distinctBy { it.id } + .let(QuickDeliver::targets) + val content = QuickDeliver.content(batchId, head.orEmpty(), targets) + val text = when (val body = content.body) { + is QuickDeliver.Body.DeliverTo -> + if (body.head.isBlank()) app.getString(R.string.quick_deliver_body, body.targetName) + else app.getString(R.string.quick_deliver_body_with_head, body.head, body.targetName) + is QuickDeliver.Body.OpenPanel -> body.head + } + val builder = NotificationCompat.Builder(app, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_stat_wechatbridge) + .setContentTitle(app.getString(R.string.quick_deliver_title, targetName)) + .setContentText(text) + .setCategory(NotificationCompat.CATEGORY_RECOMMENDATION) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .setOnlyAlertOnce(true) + .setAutoCancel(true) + .setTimeoutAfter(QuickDeliver.EXPIRY.toMillis()) + .setContentIntent(pendingIntent(app, batchId, targetId)) + // The first target is the body tap; the buttons offer the rest. + content.actions.drop(1).forEach { action -> + builder.addAction( + 0, + app.getString(R.string.quick_deliver_action, action.target.name), + pendingIntent(app, batchId, action.target.id), + ) + } + return try { + NotificationManagerCompat.from(app).notify(tag(batchId), NOTIFICATION_ID, builder.build()) + true + } catch (_: SecurityException) { + // Permission revoked between the check and the post. + false + } + } + + /** Removes [batchId]'s notification, if any; it is not posted again. */ + fun cancel(context: Context, batchId: UUID) { + synchronized(lock) { ledger.dismiss(batchId) } + NotificationManagerCompat.from(context.applicationContext).cancel(tag(batchId), NOTIFICATION_ID) + } + + /** + * Call when a [DeliverLaunch] arrives (notification tap or the receipt's + * 「投给上次目标」). Returns the batches whose quick launch is used for the + * first time; a batch already used (an intent re-delivered from recents) + * is left out, so the caller can open the panel without preselecting again. + * Either way the notification goes away. + */ + fun onLaunched(context: Context, launch: DeliverLaunch): List { + val manager = NotificationManagerCompat.from(context.applicationContext) + return launch.batchIds.filter { raw -> + val id = runCatching { UUID.fromString(raw) }.getOrNull() ?: return@filter false + val first = synchronized(lock) { ledger.consume(id) } + manager.cancel(tag(id), NOTIFICATION_ID) + first + } + } + + /** Runtime permission on 13+, and the user's app-level switch everywhere. */ + fun canNotify(context: Context): Boolean { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != + PackageManager.PERMISSION_GRANTED + ) { + return false + } + return NotificationManagerCompat.from(context).areNotificationsEnabled() + } + + fun tag(batchId: UUID): String = QuickDeliver.batchString(batchId) + + /** Distinct per batch and target: PendingIntents that differ only in extras would be merged. */ + internal fun pendingIntent(context: Context, batchId: UUID, targetId: String): PendingIntent = + PendingIntent.getActivity( + context, + (tag(batchId) + "/" + targetId).hashCode(), + DeliverLaunch.of(batchId, targetId).intent(context), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + private fun ensureChannel(context: Context) { + val manager = context.getSystemService(NotificationManager::class.java) ?: return + if (manager.getNotificationChannel(CHANNEL_ID) != null) return + val channel = NotificationChannel( + CHANNEL_ID, + context.getString(R.string.quick_deliver_channel_name), + NotificationManager.IMPORTANCE_DEFAULT, + ).apply { description = context.getString(R.string.quick_deliver_channel_description) } + manager.createNotificationChannel(channel) + } + + /** Tests only: forget every batch. */ + internal fun resetForTest() { + synchronized(lock) { + ledger = QuickDeliver.Ledger() + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/CollectMarker.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/CollectMarker.kt new file mode 100644 index 00000000..9b4ebcc9 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/CollectMarker.kt @@ -0,0 +1,29 @@ +package com.xiangming.wechatbridge.receive + +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.StandardOpenOption + +/** + * 「分批收集到微信流」: the receiver drops this empty file into the staging + * batch before commit, so it rides inside the atomic rename and a batch is + * never half marked. The collection ledger (A1.7) has one writer, the app, + * which adopts marked batches it has not seen yet. Port of iOS `CollectMarker`. + */ +object CollectMarker { + const val FILE_NAME = "collection-member" + + @Throws(IOException::class) + fun mark(batchDirectory: File) { + Files.write( + File(batchDirectory, FILE_NAME).toPath(), + ByteArray(0), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE, + ) + } + + fun isMarked(batchDirectory: File): Boolean = File(batchDirectory, FILE_NAME).isFile +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DeliverLaunch.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DeliverLaunch.kt new file mode 100644 index 00000000..659469af --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DeliverLaunch.kt @@ -0,0 +1,46 @@ +package com.xiangming.wechatbridge.receive + +import android.content.Context +import android.content.Intent +import com.xiangming.wechatbridge.MainActivity +import java.util.UUID + +/** + * 「投给上次目标」: open the app straight on the delivery panel for these + * batches, with [targetId] preselected. Carried as [MainActivity] intent + * extras; `AppNav` navigates to `Routes.deliver` on arrival. + */ +data class DeliverLaunch( + val batchIds: List, + val targetId: String?, +) { + fun intent(context: Context): Intent = Intent(context, MainActivity::class.java).apply { + action = ACTION + putExtra(EXTRA_BATCH_IDS, batchIds.toTypedArray()) + targetId?.let { putExtra(EXTRA_TARGET_ID, it) } + // MainActivity is singleTask in its own task; the receiver runs in another. + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + + companion object { + const val ACTION = "com.xiangming.wechatbridge.action.DELIVER" + const val EXTRA_BATCH_IDS = "com.xiangming.wechatbridge.extra.BATCH_IDS" + const val EXTRA_TARGET_ID = "com.xiangming.wechatbridge.extra.TARGET_ID" + + fun of(batchId: UUID, targetId: String?) = DeliverLaunch(listOf(batchId.toString().uppercase()), targetId) + + /** + * Null unless the intent is ours and names at least one batch. Only + * UUIDs pass: the ids end up in a route, and MainActivity is exported. + */ + fun parse(intent: Intent?): DeliverLaunch? { + if (intent == null || intent.action != ACTION) return null + val ids = intent.getStringArrayExtra(EXTRA_BATCH_IDS).orEmpty() + .filter { runCatching { UUID.fromString(it) }.isSuccess } + .distinct() + if (ids.isEmpty()) return null + val target = intent.getStringExtra(EXTRA_TARGET_ID)?.trim()?.takeIf { it.isNotEmpty() } + return DeliverLaunch(ids, target) + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DropClips.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DropClips.kt new file mode 100644 index 00000000..f3ead369 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DropClips.kt @@ -0,0 +1,62 @@ +package com.xiangming.wechatbridge.receive + +import android.content.ClipData +import android.content.ClipDescription +import android.content.ContentResolver +import android.content.Context + +/** + * Turns what another app dragged into our window (multi-window / small + * window) into the same [ShareItem]s a system share would give, so a drop + * makes exactly the batch a share makes: `content://` / `file://` items are + * files, a dragged web link or text goes through [ShareOrigins] (the + * `share-origin.json` note, `public.url`). + * + * One drop is one batch, whatever it holds. + */ +object DropClips { + /** MIME families a drop may carry for us to take it at all (ClipDescription is all we see before the drop). */ + private val ACCEPTED_PREFIXES = listOf("text/", "image/", "video/", "audio/", "application/") + + /** + * Decided before the drop, from the description alone: anything with a + * file, text or link type. An `intent`-only clip (a launcher shortcut) is refused. + */ + fun accepts(mimeTypes: Collection): Boolean = mimeTypes.any { raw -> + val type = raw.lowercase() + type != ClipDescription.MIMETYPE_TEXT_INTENT && ACCEPTED_PREFIXES.any { type.startsWith(it) } + } + + fun items(context: Context, clip: ClipData): List { + val resolver = context.contentResolver + val description = clip.description + // The description's type speaks for one item only when the clip holds one and the type is concrete. + val singleType = description?.takeIf { clip.itemCount == 1 && it.mimeTypeCount == 1 } + ?.getMimeType(0) + ?.takeIf { MimeTypes.isConcrete(it) && !it.startsWith("text/") } + val streams = mutableListOf() + val texts = mutableListOf() + val seenUris = mutableSetOf() + for (i in 0 until clip.itemCount) { + val item = clip.getItemAt(i) + val uri = item.uri + val scheme = uri?.scheme?.lowercase() + when { + uri != null && (scheme == ContentResolver.SCHEME_CONTENT || scheme == ContentResolver.SCHEME_FILE) -> { + if (seenUris.add(uri.toString()) && ShareIntents.isAcceptable(context, uri)) { + streams += ContentStreamItem(resolver, uri, singleType) + } + } + // A link dragged out of a browser often arrives as a `text/uri-list` item. + uri != null && ShareOrigins.isWeb(uri.toString()) -> texts += ShareItem.Text(uri.toString()) + else -> textOf(item)?.let { texts += ShareItem.Text(it) } + } + } + return streams + texts + } + + private fun textOf(item: ClipData.Item): String? { + // An HTML item always carries its plain text too (ClipData requires it); that is what a share would send. + return item.text?.toString()?.takeIf { it.isNotBlank() } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DropReceiver.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DropReceiver.kt new file mode 100644 index 00000000..dbfda176 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/DropReceiver.kt @@ -0,0 +1,164 @@ +package com.xiangming.wechatbridge.receive + +import android.app.Activity +import android.view.DragEvent +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import java.util.UUID +import java.util.concurrent.atomic.AtomicBoolean + +/** Where a drop lands: the relay list (a new batch) or a collection's page (a new batch that joins it). */ +sealed interface DropDestination { + data object Relay : DropDestination + + data class Collection(val id: UUID) : DropDestination +} + +/** The read grant a drop came with; released once its items are copied (or given up). */ +fun interface DropGrant { + fun release() +} + +/** Asks for the dragged URIs' read grant. Replaceable so tests need no real drag. */ +fun interface DropPermissions { + /** Null when the system gave none (plain text needs none; a file then fails as unreadable). */ + fun request(event: DragEvent): DropGrant? +} + +/** + * `Activity.requestDragAndDropPermissions`: the grant lives at most as long + * as [activity], so the copy has to finish while it is alive (as for + * [ShareReceiverActivity]). + */ +class ActivityDropPermissions(private val activity: Activity) : DropPermissions { + override fun request(event: DragEvent): DropGrant? = + runCatching { activity.requestDragAndDropPermissions(event) }.getOrNull()?.let { permissions -> + DropGrant { runCatching { permissions.release() } } + } +} + +/** What one drop came to; the screen turns it into a Snackbar. */ +sealed interface DropResult { + val destination: DropDestination + + data class Saved( + override val destination: DropDestination, + val receipt: ReceiptUiState.Saved, + /** 「第 N 批」 once it joined the collection; null for a relay drop or when joining failed. */ + val collectedBatchNumber: Int? = null, + ) : DropResult { + /** Dropped on a collection's page but could not join it (the collection went away or is being delivered). */ + val notJoined: Boolean get() = destination is DropDestination.Collection && collectedBatchNumber == null + } + + data class Failed(override val destination: DropDestination, val failure: ReceiveFailure) : DropResult +} + +/** + * Saves drops one after another, in the order they were dropped: a quick + * second drop waits for the first instead of racing it, and each holds its own + * grant until its copy is done (the grant lives as long as the Activity, so waiting is safe). + * + * [scope] is the Activity's: when it is destroyed the copy is cancelled, + * [UriImporter] discards staging, and the grant is released after that. + */ +class DropReceiver( + private val importer: UriImporter, + private val scope: CoroutineScope, + /** After a save: the relay list picks the batch up (`RelayStore.reload`). */ + private val reload: suspend () -> Unit = {}, + /** + * Joins [batchId] to [collectionId] and returns 「第 N 批」, or null when + * that collection cannot take it (`RelayStore.joinCollection`). + */ + private val joinCollection: suspend (batchId: UUID, collectionId: UUID) -> Int? = { _, _ -> null }, + /** A batch joined the open collection: post or update 「收集中 · N 批」. */ + private val onCollected: () -> Unit = {}, +) { + private class Request( + val items: List, + val grant: DropGrant?, + val destination: DropDestination, + val done: CompletableDeferred, + ) { + val finished = AtomicBoolean(false) + } + + /** Taken in drop order by one worker, so drops can never overtake or overwrite each other. */ + private val requests = Channel(Channel.UNLIMITED) + private val results = Channel(Channel.UNLIMITED) + private val _pending = MutableStateFlow(0) + + /** Drops accepted and not finished yet (queued or copying). */ + val pending: StateFlow = _pending.asStateFlow() + + val events: Flow = results.receiveAsFlow() + + private val worker: Job = scope.launch { + try { + for (request in requests) { + try { + results.trySend(save(request.items, request.destination)) + } finally { + finish(request) + } + } + } finally { + // Cancelled (the Activity is gone): what is still queued is never copied; give its grants back. + requests.close() + while (true) finish(requests.tryReceive().getOrNull() ?: break) + } + } + + /** + * Queues one drop. [items] were read from the clip inside the drop callback. + * The returned job completes once the drop is saved, refused or given up. + */ + fun drop(items: List, grant: DropGrant?, destination: DropDestination): Job { + _pending.update { it + 1 } + val request = Request(items, grant, destination, CompletableDeferred()) + if (!worker.isActive || requests.trySend(request).isFailure) finish(request) + return request.done + } + + /** Only after the copy has finished, or was cancelled and its staging discarded. */ + private fun finish(request: Request) { + if (!request.finished.compareAndSet(false, true)) return + request.grant?.let { runCatching { it.release() } } + _pending.update { it - 1 } + request.done.complete(Unit) + } + + private suspend fun save(items: List, destination: DropDestination): DropResult { + val outcome = try { + importer.import(items, collect = false) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + return DropResult.Failed(destination, ReceiveFailure.StorageFailed) + } + val receipt = when (val state = ReceiptUiState.from(outcome, collect = false)) { + is ReceiptUiState.Saved -> state + is ReceiptUiState.NotSaved -> return DropResult.Failed(destination, state.failure) + is ReceiptUiState.Importing -> return DropResult.Failed(destination, ReceiveFailure.StorageFailed) + } + runCatching { reload() }.onFailure { if (it is CancellationException) throw it } + val number = (destination as? DropDestination.Collection)?.let { target -> + runCatching { joinCollection(receipt.batchId, target.id) } + .onFailure { if (it is CancellationException) throw it } + .getOrNull() + } + if (number != null) runCatching(onCollected) + return DropResult.Saved(destination, receipt, number) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/MimeTypes.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/MimeTypes.kt new file mode 100644 index 00000000..57a9f785 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/MimeTypes.kt @@ -0,0 +1,61 @@ +package com.xiangming.wechatbridge.receive + +/** + * MIME → filename extension, for a shared file whose provider gave no name + * (or a name without an extension). A small fixed table first so the result + * does not depend on the device's `MimeTypeMap`; [platformLookup] fills in the rest. + */ +object MimeTypes { + private val table = mapOf( + "application/zip" to "zip", + "application/x-zip-compressed" to "zip", + "application/x-zip" to "zip", + "text/plain" to "txt", + "application/pdf" to "pdf", + "image/jpeg" to "jpg", + "image/png" to "png", + "image/gif" to "gif", + "image/webp" to "webp", + "image/heic" to "heic", + "image/heif" to "heif", + "video/mp4" to "mp4", + "video/quicktime" to "mov", + "video/3gpp" to "3gp", + "audio/mpeg" to "mp3", + "audio/mp4" to "m4a", + "application/msword" to "doc", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document" to "docx", + "application/vnd.ms-excel" to "xls", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" to "xlsx", + "application/vnd.ms-powerpoint" to "ppt", + "application/vnd.openxmlformats-officedocument.presentationml.presentation" to "pptx", + "text/markdown" to "md", + "text/csv" to "csv", + "application/json" to "json", + ) + + /** `application/octet-stream`, wildcards and unknown types give null: the bytes decide (see [sniff]). */ + fun extension(mimeType: String?, platformLookup: (String) -> String? = { null }): String? { + val type = mimeType?.substringBefore(';')?.trim()?.lowercase() ?: return null + if (type.isEmpty() || '*' in type || type == "application/octet-stream") return null + return table[type] ?: platformLookup(type)?.takeIf { it.isNotEmpty() } + } + + /** A wildcard type (image-any, any-any) from an intent says nothing about one item. */ + fun isConcrete(mimeType: String?): Boolean = + !mimeType.isNullOrBlank() && '*' !in mimeType + + /** + * An extension recognised from the first bytes, for a nameless + * `application/octet-stream` (what WeChat often sends). Only ZIP matters: + * it is what decides whether the batch is read as a chat export. + */ + fun sniff(header: ByteArray, length: Int): String? { + if (length >= 4 && header[0] == 'P'.code.toByte() && header[1] == 'K'.code.toByte() && + header[2] == 3.toByte() && header[3] == 4.toByte() + ) { + return "zip" + } + return null + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiptSheet.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiptSheet.kt new file mode 100644 index 00000000..4b4176c1 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiptSheet.kt @@ -0,0 +1,550 @@ +package com.xiangming.wechatbridge.receive + +import android.os.Build +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Info +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.util.ByteFormat +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface +import com.xiangming.wechatbridge.ui.theme.BridgePrimaryCapsuleButton +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import com.xiangming.wechatbridge.ui.theme.WeChatGreen +import com.xiangming.wechatbridge.ui.theme.pressScale +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import java.time.Instant +import java.util.UUID +import kotlin.math.roundToInt + +/** + * Receipt card (A1.11), the Compose counterpart of iOS `ReceiptView`. + * + * - [ReceiptUiState.Importing]: progress only, not dismissible. + * - [ReceiptUiState.Saved]: summary + buttons; closes itself via [onDone] after + * [AUTO_DISMISS_MILLIS] with a smooth 3dp top countdown bar that pauses while the + * user's finger touches the card, or sooner on scrim tap / 完成. + * - [ReceiptUiState.NotSaved]: the reason stays until the user taps 「好」 (no timer, like iOS). + * + * 「投给上次目标」 shows only when [ReceiptUiState.Saved.lastTargetId] is set; 「加入收集」 only + * while the batch is in no collection ([ReceiptUiState.Saved.collectedBatchNumber] is null). + */ +@Composable +fun ReceiptSheet( + state: ReceiptUiState, + onDone: () -> Unit, + onDeliverToLastTarget: () -> Unit = {}, + onAddToCollection: () -> Unit = {}, +) { + val scope = rememberCoroutineScope() + val colors = MaterialTheme.colorScheme + val ext = LocalAppColors.current + val density = LocalDensity.current + + val isRobolectric = remember { + Build.FINGERPRINT.equals("robolectric", ignoreCase = true) || + Build.PRODUCT.equals("robolectric", ignoreCase = true) + } + var visible by remember { mutableStateOf(isRobolectric) } + var dismissing by remember { mutableStateOf(false) } + if (!isRobolectric) { + LaunchedEffect(Unit) { visible = true } + } + + val dismissWithMotion: () -> Unit = { + if (!dismissing) { + dismissing = true + visible = false + scope.launch { + delay(EXIT_ANIM_MILLIS) + onDone() + } + } + } + + // 顶部倒计时进度(仅 Saved 状态运行,手指触碰卡片时立即暂停,松手继续) + var isPaused by remember(state) { mutableStateOf(false) } + val countdownProgress = remember(state) { Animatable(1f) } + if (state is ReceiptUiState.Saved) { + LaunchedEffect(state, isPaused) { + if (!isPaused && !dismissing) { + val remainingMillis = (AUTO_DISMISS_MILLIS * countdownProgress.value).roundToInt().coerceAtLeast(0) + if (remainingMillis > 0) { + countdownProgress.animateTo( + targetValue = 0f, + animationSpec = tween(durationMillis = remainingMillis, easing = LinearEasing), + ) + } + if (!isPaused && countdownProgress.value <= 0.001f) { + dismissWithMotion() + } + } + } + } + + val slideDistancePx = with(density) { 56.dp.toPx() } + val translationY by animateFloatAsState( + targetValue = if (visible) 0f else slideDistancePx, + animationSpec = if (visible) AppMotion.playfulSpring() else tween(durationMillis = EXIT_ANIM_MILLIS.toInt()), + label = "receiptSlideY", + ) + val cardAlpha by animateFloatAsState( + targetValue = if (visible) 1f else 0f, + animationSpec = tween(durationMillis = if (visible) 180 else EXIT_ANIM_MILLIS.toInt()), + label = "receiptCardAlpha", + ) + val scrimAlpha by animateFloatAsState( + targetValue = if (visible) 0.18f else 0f, + animationSpec = tween(durationMillis = 180), + label = "receiptScrimAlpha", + ) + + Box( + modifier = Modifier + .fillMaxSize() + .background(colors.scrim.copy(alpha = scrimAlpha)) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + enabled = state is ReceiptUiState.Saved, + onClickLabel = stringResource(R.string.a11y_receipt_dismiss), + onClick = dismissWithMotion, + ), + contentAlignment = Alignment.BottomCenter, + ) { + BridgeGlassSurface( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(14.dp) + .graphicsLayer { + this.translationY = translationY + alpha = cardAlpha + } + // 手指触碰卡片任意区域时暂停倒计时(不拦截子按钮点击事件)。 + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + isPaused = event.changes.any { it.pressed } + } + } + } + // Swallow taps on the card itself so only the scrim (and buttons) dismiss. + // A gesture detector (not clickable) so TalkBack doesn't announce the card as a button. + .pointerInput(Unit) { detectTapGestures {} }, + shape = RoundedCornerShape(24.dp), + shadowElevation = 14.dp, + ) { + Column(Modifier.fillMaxWidth()) { + if (state is ReceiptUiState.Saved) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(3.dp) + .background(ext.surfaceSub), + ) { + Box( + modifier = Modifier + .fillMaxHeight() + .fillMaxWidth(countdownProgress.value.coerceIn(0f, 1f)) + .background(colors.primary), + ) + } + } + Column( + modifier = Modifier.padding(horizontal = 20.dp, vertical = 18.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + when (state) { + is ReceiptUiState.Importing -> { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + ReceiptStatusBadge( + icon = AppIcons.NavRelay, + accent = WeChatGreen, + ) + Text( + text = stringResource(R.string.receive_importing), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = colors.onSurface, + ) + } + if (isRobolectric) { + LinearProgressIndicator( + progress = { 0.35f }, + modifier = Modifier + .fillMaxWidth() + .padding(top = 6.dp), + color = colors.primary, + trackColor = ext.surfaceSub, + ) + } else { + LinearProgressIndicator( + modifier = Modifier + .fillMaxWidth() + .padding(top = 6.dp), + color = colors.primary, + trackColor = ext.surfaceSub, + ) + } + } + is ReceiptUiState.Saved -> SavedBody( + state = state, + onDone = dismissWithMotion, + onDeliverToLastTarget = onDeliverToLastTarget, + onAddToCollection = onAddToCollection, + ) + is ReceiptUiState.NotSaved -> NotSavedBody(state, dismissWithMotion) + } + } + } + } + } +} + +@Composable +private fun ReceiptStatusBadge( + icon: ImageVector, + accent: Color, +) { + Box( + modifier = Modifier + .size(40.dp) + .clip(CircleShape) + .background( + Brush.radialGradient( + colors = listOf(accent.copy(alpha = 0.24f), accent.copy(alpha = 0.06f)), + ), + ), + contentAlignment = Alignment.Center, + ) { + Box( + modifier = Modifier + .size(28.dp) + .clip(CircleShape) + .background(accent.copy(alpha = 0.16f)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = accent, + modifier = Modifier.size(16.dp), + ) + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun SavedBody( + state: ReceiptUiState.Saved, + onDone: () -> Unit, + onDeliverToLastTarget: () -> Unit, + onAddToCollection: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val ext = LocalAppColors.current + val title = when { + state.collectedBatchNumber != null -> + stringResource(R.string.receive_collected_batch, state.collectedBatchNumber) + state.collect -> stringResource(R.string.receive_collected) + else -> stringResource(R.string.receive_saved) + } + val countsSeparator = stringResource(R.string.receive_counts_separator) + val counts = buildList { + state.messageCount?.let { add(pluralStringResource(R.plurals.receive_messages, it, it)) } + state.attachmentCount?.let { add(pluralStringResource(R.plurals.receive_attachments, it, it)) } + if (isEmpty()) add(pluralStringResource(R.plurals.receive_files, state.itemCount, state.itemCount)) + } + + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + ReceiptStatusBadge( + icon = Icons.Filled.Check, + accent = WeChatGreen, + ) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + title, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = colors.onSurface, + ) + Text( + text = counts.joinToString(countsSeparator) + countsSeparator + ByteFormat.string(state.byteCount), + style = MaterialTheme.typography.bodyMedium, + color = colors.onSurfaceVariant, + ) + } + } + if (!state.isWeChatFormat) { + Text( + text = state.itemNames.joinToString(stringResource(R.string.receive_names_separator)), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + for (preview in listOfNotNull(state.first, state.last)) { + Text( + text = stringResource(R.string.receive_message_line, preview.sender, preview.text), + style = MaterialTheme.typography.bodySmall, + color = ext.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + if (state.hasNonWeChatArchive) { + Text( + text = stringResource(R.string.receive_not_wechat), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + ) + } + if (state.collect || state.collectedBatchNumber != null) { + Text( + text = stringResource(R.string.receive_collect_next_hint), + style = MaterialTheme.typography.bodySmall, + color = colors.primary, + ) + } + FlowRow( + modifier = Modifier + .fillMaxWidth() + .padding(top = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (!state.collect && state.collectedBatchNumber == null) { + ReceiptSecondaryButton( + label = stringResource(R.string.receive_action_collect), + onClick = onAddToCollection, + ) + } + ReceiptSecondaryButton( + label = stringResource(R.string.receive_action_done), + onClick = onDone, + ) + if (state.lastTargetId != null) { + ReceiptPrimaryButton( + label = stringResource(R.string.receive_action_deliver_last), + onClick = onDeliverToLastTarget, + ) + } + } +} + +@Composable +private fun ReceiptPrimaryButton(label: String, onClick: () -> Unit) { + BridgePrimaryCapsuleButton( + text = label, + onClick = onClick, + height = 42.dp, + ) +} + +@Composable +private fun ReceiptSecondaryButton(label: String, onClick: () -> Unit) { + val interaction = remember { MutableInteractionSource() } + Button( + onClick = onClick, + shape = CircleShape, + colors = ButtonDefaults.buttonColors( + containerColor = LocalAppColors.current.surfaceSub, + contentColor = MaterialTheme.colorScheme.onSurface, + ), + elevation = ButtonDefaults.buttonElevation(0.dp, 0.dp, 0.dp, 0.dp, 0.dp), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 10.dp), + interactionSource = interaction, + modifier = Modifier + .height(42.dp) + .pressScale(interaction), + ) { + Text(label, style = MaterialTheme.typography.labelLarge, maxLines = 1) + } +} + +@Composable +private fun NotSavedBody(state: ReceiptUiState.NotSaved, onDone: () -> Unit) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + ReceiptStatusBadge( + icon = Icons.Filled.Info, + accent = MaterialTheme.colorScheme.error, + ) + Text( + text = stringResource(R.string.receive_not_saved), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.error, + ) + } + Text( + text = failureText(state.failure), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + Text( + text = stringResource(R.string.receive_not_saved_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Row( + modifier = Modifier + .fillMaxWidth() + .padding(top = 8.dp), + horizontalArrangement = Arrangement.End, + ) { + ReceiptPrimaryButton( + label = stringResource(R.string.receive_action_ok), + onClick = onDone, + ) + } +} + +@Composable +private fun failureText(failure: ReceiveFailure): String = when (failure) { + ReceiveFailure.EmptyShare -> stringResource(R.string.receive_failure_empty_share) + is ReceiveFailure.TooManyItems -> stringResource(R.string.receive_failure_too_many, UriImporter.MAX_ITEMS, failure.count) + is ReceiveFailure.EmptyFile -> stringResource(R.string.receive_failure_empty_file, failure.displayName) + ReceiveFailure.Unreadable -> stringResource(R.string.receive_failure_unreadable) + ReceiveFailure.StorageFailed -> stringResource(R.string.receive_failure_storage) +} + +const val AUTO_DISMISS_MILLIS = 2_000L +private const val EXIT_ANIM_MILLIS = 160L + +// ---- Previews (四种状态:单批聊天记录、多文件、收集中、失败) ---- + +private val previewFirst = MessagePreview("小明", "今天下午三点开会,别迟到", Instant.parse("2026-11-20T06:00:00Z")) +private val previewLast = MessagePreview("小红", "收到,我准时到", Instant.parse("2026-11-20T06:12:00Z")) + +private fun previewSaved( + names: List, + collect: Boolean = false, + weChat: Boolean = true, + collectedBatchNumber: Int? = null, +) = ReceiptUiState.Saved( + batchId = UUID(0, 1), + collect = collect, + itemNames = names, + byteCount = 482_000, + messageCount = if (weChat) 128 else null, + attachmentCount = if (weChat) 6 else null, + isWeChatFormat = weChat, + hasNonWeChatArchive = false, + first = if (weChat) previewFirst else null, + last = if (weChat) previewLast else null, + collectedBatchNumber = collectedBatchNumber, + lastTargetId = "chatgpt", +) + +@Preview(name = "单批聊天记录", showBackground = true, heightDp = 420) +@Composable +private fun ReceiptSheetSingleBatchPreview() { + WeChatBridgeTheme { + ReceiptSheet(state = previewSaved(listOf("微信聊天记录.zip")), onDone = {}) + } +} + +@Preview(name = "多文件", showBackground = true, heightDp = 420) +@Composable +private fun ReceiptSheetMultiFilePreview() { + WeChatBridgeTheme { + ReceiptSheet( + state = previewSaved(listOf("会议纪要.pdf", "报价单.xlsx", "现场照片.jpg"), weChat = false), + onDone = {}, + ) + } +} + +@Preview(name = "收集中", showBackground = true, heightDp = 420) +@Composable +private fun ReceiptSheetCollectingPreview() { + WeChatBridgeTheme { + ReceiptSheet( + state = previewSaved(listOf("微信聊天记录.zip"), collect = true, collectedBatchNumber = 3), + onDone = {}, + ) + } +} + +@Preview(name = "失败", showBackground = true, heightDp = 420) +@Composable +private fun ReceiptSheetFailedPreview() { + WeChatBridgeTheme { + ReceiptSheet( + state = ReceiptUiState.NotSaved(ReceiveFailure.EmptyFile("微信聊天记录.zip"), collect = false), + onDone = {}, + ) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiptUiState.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiptUiState.kt new file mode 100644 index 00000000..b89e609a --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiptUiState.kt @@ -0,0 +1,86 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.core.transcript.TranscriptRecord +import java.time.Instant +import java.util.UUID + +/** One message as the receipt shows it: sender, first line of text, time. */ +data class MessagePreview( + val sender: String, + val text: String, + val date: Instant, +) { + companion object { + const val TEXT_LIMIT = 40 + + fun of(record: TranscriptRecord): MessagePreview { + val line = record.text.lineSequence().map { it.trim() }.firstOrNull { it.isNotEmpty() }.orEmpty() + return MessagePreview(record.sender, line.take(TEXT_LIMIT), record.date) + } + } +} + +/** + * What the receipt card shows (consumed by A1.11's `ReceiptSheet`). + * Pure data: wording is mapped from these fields in `:app` resources. + */ +sealed interface ReceiptUiState { + /** 「分批收集到微信流」 entry, as opposed to the plain 「微信流」 save. */ + val collect: Boolean + + data class Importing(override val collect: Boolean) : ReceiptUiState + + /** 已存入中转站. */ + data class Saved( + val batchId: UUID, + override val collect: Boolean, + val itemNames: List, + val byteCount: Long, + /** Sum over the batch's WeChat archives; null when none parsed. */ + val messageCount: Int?, + /** Non-TXT files inside those archives; null when there is no readable archive. */ + val attachmentCount: Int?, + /** At least one ZIP in the batch is a recognisable WeChat export. */ + val isWeChatFormat: Boolean, + /** At least one ZIP was kept but is not a WeChat export (saved anyway, shown as a plain file). */ + val hasNonWeChatArchive: Boolean, + val first: MessagePreview?, + val last: MessagePreview?, + /** + * 「已收第 N 批」: set for the 「分批收集」 entry once the app adopted the + * batch, or after 「加入收集」 (`RelayStore.collectedBatchNumber`). + */ + val collectedBatchNumber: Int? = null, + /** Preferences' last target: 「投给上次目标」 shows only when there is one. */ + val lastTargetId: String? = null, + ) : ReceiptUiState { + val itemCount: Int get() = itemNames.size + } + + /** 没有存入. Nothing was published; the reason is shown until dismissed or timed out. */ + data class NotSaved( + val failure: ReceiveFailure, + override val collect: Boolean, + ) : ReceiptUiState + + companion object { + fun from(outcome: ImportOutcome, collect: Boolean): ReceiptUiState = when (outcome) { + is ImportOutcome.Failed -> NotSaved(outcome.failure, collect) + is ImportOutcome.Saved -> { + val weChat = outcome.archives.filter { it.isWeChatFormat } + Saved( + batchId = outcome.batchId, + collect = outcome.collect, + itemNames = outcome.items.map { it.displayName }, + byteCount = outcome.items.sumOf { it.byteCount }, + messageCount = weChat.mapNotNull { it.messageCount }.takeIf { it.isNotEmpty() }?.sum(), + attachmentCount = weChat.mapNotNull { it.attachmentCount }.takeIf { it.isNotEmpty() }?.sum(), + isWeChatFormat = weChat.isNotEmpty(), + hasNonWeChatArchive = outcome.archives.any { !it.isWeChatFormat }, + first = outcome.records.firstOrNull()?.let(MessagePreview::of), + last = outcome.records.takeIf { it.size > 1 }?.lastOrNull()?.let(MessagePreview::of), + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiveTexts.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiveTexts.kt new file mode 100644 index 00000000..ed276c65 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ReceiveTexts.kt @@ -0,0 +1,33 @@ +package com.xiangming.wechatbridge.receive + +import android.content.res.Resources +import com.xiangming.wechatbridge.R + +/** [ReceiveFailure] in words (strings_receive.xml), for Snackbars outside the receipt card. */ +fun ReceiveFailure.message(resources: Resources): String = when (this) { + ReceiveFailure.EmptyShare -> resources.getString(R.string.receive_failure_empty_share) + is ReceiveFailure.TooManyItems -> resources.getString(R.string.receive_failure_too_many, UriImporter.MAX_ITEMS, count) + is ReceiveFailure.EmptyFile -> resources.getString(R.string.receive_failure_empty_file, displayName) + ReceiveFailure.Unreadable -> resources.getString(R.string.receive_failure_unreadable) + ReceiveFailure.StorageFailed -> resources.getString(R.string.receive_failure_storage) +} + +/** 「N 条消息」 for a chat export, else the first item's name (and how many there are). */ +fun ReceiptUiState.Saved.shortDescription(resources: Resources): String { + messageCount?.let { return resources.getQuantityString(R.plurals.receive_messages, it, it) } + val first = itemNames.firstOrNull() ?: return resources.getQuantityString(R.plurals.receive_files, 0, 0) + return if (itemCount > 1) resources.getQuantityString(R.plurals.drop_names_more, itemCount, first, itemCount) else first +} + +/** The Snackbar line for one drop. */ +fun DropResult.message(resources: Resources): String = when (this) { + is DropResult.Failed -> resources.getString(R.string.drop_failed, failure.message(resources)) + is DropResult.Saved -> { + val what = receipt.shortDescription(resources) + when { + collectedBatchNumber != null -> resources.getString(R.string.drop_collected, collectedBatchNumber, what) + notJoined -> resources.getString(R.string.drop_saved_not_collected, what) + else -> resources.getString(R.string.drop_saved, what) + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareIntents.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareIntents.kt new file mode 100644 index 00000000..ac7404a0 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareIntents.kt @@ -0,0 +1,109 @@ +package com.xiangming.wechatbridge.receive + +import android.content.ContentResolver +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.OpenableColumns +import androidx.core.content.IntentCompat +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import java.io.File +import java.io.FileNotFoundException +import java.io.InputStream + +/** Turns a receiving [Intent] into [ShareItem]s. */ +object ShareIntents { + /** Activity-alias class name of 「分批收集到微信流」 (see AndroidManifest.xml). */ + const val COLLECT_ALIAS = "com.xiangming.wechatbridge.receive.CollectAlias" + + fun isCollectEntry(intent: Intent): Boolean = intent.component?.className == COLLECT_ALIAS + + fun items(context: Context, intent: Intent): List { + val resolver = context.contentResolver + val primary: List = when (intent.action) { + Intent.ACTION_SEND -> + listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)) + Intent.ACTION_SEND_MULTIPLE -> + IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty() + Intent.ACTION_VIEW -> listOfNotNull(intent.data) + else -> emptyList() + } + val clip = intent.clipData + val clipUris = buildList { if (clip != null) for (i in 0 until clip.itemCount) clip.getItemAt(i).uri?.let(::add) } + val uris = merge(primary, clipUris).filter { isAcceptable(context, it) } + // A concrete intent type describes a single item; for several it may be the common parent. + val intentType = intent.type?.takeIf { MimeTypes.isConcrete(it) && uris.size == 1 } + if (uris.isNotEmpty()) { + return uris.map { uri -> ContentStreamItem(resolver, uri, intentType) } + } + + if (intent.action == Intent.ACTION_SEND || intent.action == Intent.ACTION_SEND_MULTIPLE) { + val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString() + ?: clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text?.toString() + if (!text.isNullOrBlank()) { + val subject = intent.getCharSequenceExtra(Intent.EXTRA_SUBJECT)?.toString() + return listOf(ShareItem.Text(text, subject)) + } + } + return emptyList() + } + + /** EXTRA_STREAM first, then ClipData; each URI once, sender's order kept. */ + fun merge(primary: List, clip: List): List = LinkedHashSet().apply { + addAll(primary) + addAll(clip) + }.toList() + + /** + * Only `content://` and `file://`, and never one that points back into this + * app: another app must not be able to make us copy our own private files + * (or our FileProvider's delivery copies) into the inbox and out again. + */ + internal fun isAcceptable(context: Context, uri: Uri): Boolean = when (uri.scheme?.lowercase()) { + ContentResolver.SCHEME_CONTENT -> { + val authority = uri.authority.orEmpty() + authority != context.packageName && !authority.startsWith("${context.packageName}.") + } + ContentResolver.SCHEME_FILE -> { + val path = uri.path + if (path == null) { + false + } else { + val canonical = runCatching { File(path).canonicalPath }.getOrNull() + val ownRoots = listOfNotNull(context.applicationInfo.dataDir, context.filesDir.parent, context.cacheDir.parent) + .mapNotNull { runCatching { File(it).canonicalPath }.getOrNull() } + canonical != null && ownRoots.none { canonical == it || canonical.startsWith("$it/") } + } + } + else -> false + } +} + +/** A [ShareItem.Stream] read through [ContentResolver]. */ +class ContentStreamItem( + private val resolver: ContentResolver, + val uri: Uri, + private val intentType: String?, +) : ShareItem.Stream { + override val mimeType: String? by lazy { + val own = runCatching { resolver.getType(uri) }.getOrNull() + own?.takeIf { MimeTypes.isConcrete(it) } ?: intentType ?: own + } + + override val loadStrategy: LoadStrategy = + if (uri.scheme.equals(ContentResolver.SCHEME_FILE, ignoreCase = true)) LoadStrategy.FILE_URL + else LoadStrategy.FILE_REPRESENTATION + + override fun displayName(): String? { + if (loadStrategy == LoadStrategy.FILE_URL) return uri.lastPathSegment + return runCatching { + resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor -> + val column = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (column >= 0 && cursor.moveToFirst()) cursor.getString(column) else null + } + }.getOrNull() + } + + override fun open(): InputStream = + resolver.openInputStream(uri) ?: throw FileNotFoundException("provider returned no stream") +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareItem.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareItem.kt new file mode 100644 index 00000000..65bba1f5 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareItem.kt @@ -0,0 +1,50 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import java.io.IOException +import java.io.InputStream + +/** + * One thing a share handed us, already lifted out of the [android.content.Intent]. + * + * Kept free of `android.*` types so [UriImporter] runs in plain JVM unit tests; + * the Android-backed [Stream] lives in [ContentStreamItem]. + */ +sealed interface ShareItem { + /** A file-like stream (`content://` from the sender, or a `file://` from an older app). */ + interface Stream : ShareItem { + /** Best MIME type we know: the provider's own, else the intent's when it is concrete. */ + val mimeType: String? + + /** `content` reads through a provider; `file` was handed as a path. */ + val loadStrategy: LoadStrategy + + /** The provider's `OpenableColumns.DISPLAY_NAME` (or a `file://` path's last segment). */ + fun displayName(): String? + + /** Opens the bytes. Called at most once, inside the receiving Activity's lifetime. */ + @Throws(IOException::class) + fun open(): InputStream + } + + /** `EXTRA_TEXT` with no stream: saved as one `.txt` item. */ + data class Text(val text: String, val subject: String? = null) : ShareItem +} + +/** Why a share was not saved. `:app` maps each case to a string (strings_receive.xml). */ +sealed interface ReceiveFailure { + /** Nothing usable in the intent (no stream, no text). */ + data object EmptyShare : ReceiveFailure + + /** More than [UriImporter.MAX_ITEMS] items; the whole share is refused, never truncated. */ + data class TooManyItems(val count: Int) : ReceiveFailure + + /** WeChat never exports an empty file; one arriving means the export failed upstream. */ + data class EmptyFile(val displayName: String) : ReceiveFailure + + /** The sender's URI could not be opened (no grant, revoked, or not a file we may read). */ + data object Unreadable : ReceiveFailure + + /** Our own storage failed (disk full, I/O error while copying or committing). */ + data object StorageFailed : ReceiveFailure +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareOrigins.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareOrigins.kt new file mode 100644 index 00000000..f438e95a --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareOrigins.kt @@ -0,0 +1,71 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.core.summary.PlainLinks +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.core.util.DisplayName +import java.net.URI + +/** + * The iOS share extension's text/link handling (`ShareOrigin.make`, + * `isWeb`, `noteFileName` and `loadOrigin`), for Android's `EXTRA_TEXT` / + * `EXTRA_SUBJECT`. Lives in `:app` because `:core`'s [ShareOrigin] only reads + * and writes the file. + */ +object ShareOrigins { + /** + * iOS `loadOrigin`: an Android share has no URL provider, so a text that + * is nothing but one web link plays that part (Chrome sends the page's + * link as `EXTRA_TEXT` and its title as `EXTRA_SUBJECT`); every other + * text is a text, and the subject is the host's title. + */ + fun from(texts: List): ShareOrigin? { + if (texts.isEmpty()) return null + var url: String? = null + val values = mutableListOf() + for (item in texts) { + val trimmed = item.text.trim() + if (url == null && isSingleWebLink(trimmed)) url = trimmed else values += item.text + } + val title = texts.firstNotNullOfOrNull { it.subject?.takeIf { s -> s.isNotBlank() } } + return make(url, title, values) + } + + /** + * iOS `ShareOrigin.make`: text that is only the link adds nothing; a link + * buried in the text (抖音's 「复制打开抖音」 blurb) becomes the link. + */ + fun make(url: String?, title: String?, texts: List): ShareOrigin? { + var link = url + val parts = mutableListOf() + for (raw in texts) { + val text = raw.trim() + if (text.isEmpty() || text == link || text in parts) continue + parts += text + } + if (link == null) link = parts.firstNotNullOfOrNull(::firstWebUrl) + val trimmedTitle = title?.trim() + // A host that sends the tweet as both the title and the text. + parts.removeAll { it == trimmedTitle } + val origin = ShareOrigin( + url = link, + title = trimmedTitle?.takeIf { it.isNotEmpty() }, + text = if (parts.isEmpty()) null else parts.joinToString("\n\n"), + ) + return if (origin.isEmpty) null else origin + } + + /** iOS `ShareOrigin.noteFileName`. */ + fun noteFileName(origin: ShareOrigin): String = + DisplayName.sanitize("${origin.heading.replace("/", "-")}.txt", "txt") + + fun isWeb(url: String): Boolean { + val scheme = runCatching { URI(url).scheme }.getOrNull() ?: url.substringBefore("://", "") + return scheme.lowercase() in setOf("http", "https") + } + + private fun isSingleWebLink(text: String): Boolean = + text.isNotEmpty() && text.none { it.isWhitespace() } && PlainLinks.extract(text).singleOrNull() == text && isWeb(text) + + /** NSDataDetector's role; [PlainLinks] only finds links that carry their scheme. */ + private fun firstWebUrl(text: String): String? = PlainLinks.extract(text).firstOrNull(::isWeb) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareReceiverActivity.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareReceiverActivity.kt new file mode 100644 index 00000000..53c54a66 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/ShareReceiverActivity.kt @@ -0,0 +1,255 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.AppContainer +import com.xiangming.wechatbridge.core.deliver.QuickDeliver +import com.xiangming.wechatbridge.deliver.displayName +import com.xiangming.wechatbridge.notify.QuickDeliverNotification +import android.os.Bundle +import android.view.WindowManager +import android.widget.Toast +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.bubble.BubbleService +import com.xiangming.wechatbridge.bubble.OverlayPermission +import com.xiangming.wechatbridge.bubble.SilentReceive +import kotlinx.coroutines.delay +import androidx.activity.ComponentActivity +import androidx.activity.OnBackPressedCallback +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.viewModels +import androidx.compose.runtime.getValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.notify.CollectNotification +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import java.util.UUID + +/** + * Entry for 「微信流」 and 「分批收集到微信流」 (two activity-aliases, android-plan §2.1). + * + * Translucent, excluded from recents, in its own task affinity: it copies + * the share into the inbox and gets out of the way. The copy runs here, not in + * a background job, because the sender's URI grant ends with this Activity. + * + * With the bubble on and allowed to show ([SilentReceive]), there is no + * receipt card: the Activity finishes as soon as the batch is in (the + * bubble's count goes up) and only a failure says anything, as a Toast. + * + * Interruptions never leave a half batch: rotation keeps the [ReceiveViewModel] + * (and its import) alive; back while importing cancels it, which discards staging. + */ +class ShareReceiverActivity : ComponentActivity() { + private val viewModel: ReceiveViewModel by viewModels { + viewModelFactory { + initializer { + val container = (application as App).container + ReceiveViewModel( + importer = container.uriImporter, + onSaved = container.relayStore::refresh, + adoptCollected = container.relayStore::adoptCollected, + addToCollection = container.relayStore::collect, + lastTarget = { container.preferences.current().lastTarget }, + onCollected = { CollectNotification.sync(application, container.relayStore) }, + onQuickDeliver = { saved -> postQuickDeliver(container, saved) }, + ) + } + } + } + + /** + * Bubble on (and allowed to show): no receipt card, back to the sender as + * soon as the batch is in; the bubble's count is the receipt. Decided once + * in [onCreate], before the ViewModel exists. + */ + private var silent = false + + /** 「已存入 · 投给 X」: the receipt closes soon, the notification keeps the shortcut. */ + private suspend fun postQuickDeliver(container: AppContainer, saved: ReceiptUiState.Saved) { + // With the bubble the shortcut is one tap on the ball; a notification per share would be noise. + if (silent) return + val lastId = saved.lastTargetId ?: return + val snapshot = container.preferences.current() + val arranged = snapshot.targets() + val last = arranged.firstOrNull { it.id == lastId } ?: return + QuickDeliverNotification.post( + context = application, + batchId = saved.batchId, + targetId = last.id, + targetName = last.displayName(application), + head = saved.itemNames.firstOrNull(), + others = QuickDeliver.targets(arranged) { it.displayName(application) }, + ) + } + + override fun onCreate(savedInstanceState: Bundle?) { + enableEdgeToEdge() + super.onCreate(savedInstanceState) + + val container = (application as App).container + silent = SilentReceive.mode(container.bubbleSettings.isEnabled, OverlayPermission.canDraw(this)) == + SilentReceive.Mode.SILENT + if (silent) { + // Nothing to dim for: the sender stays as it is unless a long copy shows progress. + window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) + BubbleService.sync(this) + } + + val collect = ShareIntents.isCollectEntry(intent) + viewModel.start(collect) { ShareIntents.items(this, intent) } + + onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + viewModel.cancel() + finish() + } + }) + + setContent { + WeChatBridgeTheme { + val state by viewModel.state.collectAsStateWithLifecycle() + if (silent) { + SilentReceipt(state) + } else state?.let { + ReceiptSheet( + state = it, + onDone = ::finish, + onDeliverToLastTarget = ::deliverToLastTarget, + onAddToCollection = viewModel::addToCollection, + ) + } + } + } + } + + /** Bubble mode: progress only for a long copy, finish on save, a Toast on failure. */ + @Composable + private fun SilentReceipt(state: ReceiptUiState?) { + when (SilentReceive.step(state)) { + SilentReceive.Step.WAIT -> { + var showProgress by remember { mutableStateOf(false) } + LaunchedEffect(Unit) { + delay(SilentReceive.PROGRESS_DELAY_MILLIS) + showProgress = true + } + if (showProgress && state != null) ReceiptSheet(state = state, onDone = {}) + } + SilentReceive.Step.FINISH -> LaunchedEffect(Unit) { finish() } + SilentReceive.Step.FAIL -> LaunchedEffect(Unit) { + val failure = (state as ReceiptUiState.NotSaved).failure + Toast.makeText( + applicationContext, + getString(R.string.bubble_receive_failed, failure.message(resources)), + Toast.LENGTH_LONG, + ).show() + finish() + } + } + } + + /** Opens the delivery panel in the main task with the last target preselected, and gets out of the way. */ + private fun deliverToLastTarget() { + val launch = viewModel.deliverLaunch() ?: return + startActivity(launch.intent(this)) + finish() + } + + override fun finish() { + super.finish() + @Suppress("DEPRECATION") + overridePendingTransition(0, android.R.anim.fade_out) + } +} + +class ReceiveViewModel( + private val importer: UriImporter, + /** A plain save: the relay list picks the batch up. */ + private val onSaved: () -> Unit = {}, + /** 「分批收集」 entry: the store adopts the marked batch and returns 「第 N 批」 (`RelayStore.adoptCollected`). */ + private val adoptCollected: suspend (UUID) -> Int? = { null }, + /** Receipt 「加入收集」 (`RelayStore.collect`): continue or start the open collection, return 「第 N 批」. */ + private val addToCollection: suspend (UUID) -> Int? = { null }, + /** Preferences' last target, for 「投给上次目标」. */ + private val lastTarget: suspend () -> String? = { null }, + /** A batch joined the open collection: post or update 「收集中 · N 批」 (`CollectNotification.sync`). */ + private val onCollected: () -> Unit = {}, + /** A plain save with a last target: post 「已存入 · 投给 X」 (`QuickDeliverNotification.post`). */ + private val onQuickDeliver: suspend (ReceiptUiState.Saved) -> Unit = {}, +) : ViewModel() { + private val _state = MutableStateFlow(null) + val state: StateFlow = _state.asStateFlow() + + private var job: Job? = null + private var collecting = false + + /** Idempotent: a recreated Activity (rotation) finds the import already running or done. */ + fun start(collect: Boolean, items: () -> List) { + if (_state.value != null) return + _state.value = ReceiptUiState.Importing(collect) + val parsed = items() + job = viewModelScope.launch { + val outcome = importer.import(parsed, collect) + var receipt = ReceiptUiState.from(outcome, collect) + if (receipt is ReceiptUiState.Saved) { + receipt = if (collect) { + // As on iOS, a collected batch gets no quick delivery: the next batch follows at once. + val number = runCatching { adoptCollected(receipt.batchId) }.getOrNull() + if (number != null) runCatching(onCollected) + receipt.copy(collectedBatchNumber = number) + } else { + onSaved() + receipt.copy(lastTargetId = runCatching { lastTarget() }.getOrNull()) + } + } + _state.value = receipt + if (receipt is ReceiptUiState.Saved && !collect && receipt.lastTargetId != null) { + runCatching { onQuickDeliver(receipt) } + } + } + } + + /** 「加入收集」: once; the receipt then shows 「已收第 N 批」. */ + fun addToCollection() { + val saved = _state.value as? ReceiptUiState.Saved ?: return + if (collecting || saved.collectedBatchNumber != null) return + collecting = true + viewModelScope.launch { + val number = runCatching { addToCollection(saved.batchId) }.getOrNull() + if (number != null) runCatching(onCollected) + _state.update { current -> + if (number != null && current is ReceiptUiState.Saved && current.batchId == saved.batchId) { + current.copy(collectedBatchNumber = number) + } else { + current + } + } + collecting = false + } + } + + /** What 「投给上次目标」 opens; null when there is no last target (the button is hidden then). */ + fun deliverLaunch(): DeliverLaunch? { + val saved = _state.value as? ReceiptUiState.Saved ?: return null + val target = saved.lastTargetId ?: return null + return DeliverLaunch.of(saved.batchId, target) + } + + /** Cancelling mid-copy discards staging inside [UriImporter]; after commit it changes nothing. */ + fun cancel() { + job?.cancel() + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/UriImporter.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/UriImporter.kt new file mode 100644 index 00000000..2785898f --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/receive/UriImporter.kt @@ -0,0 +1,380 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.core.WeChatReadException +import com.xiangming.wechatbridge.core.archive.WeChatArchive +import com.xiangming.wechatbridge.core.inbox.BatchManifest +import com.xiangming.wechatbridge.core.inbox.BatchStaging +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import com.xiangming.wechatbridge.core.inbox.ManifestItem +import com.xiangming.wechatbridge.core.inbox.ShareAction +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.core.transcript.TranscriptRecord +import com.xiangming.wechatbridge.core.util.AttachmentDiagnostic +import com.xiangming.wechatbridge.core.util.DiagnosticsLog +import com.xiangming.wechatbridge.core.util.DisplayName +import com.xiangming.wechatbridge.core.util.ImportDiagnostics +import com.xiangming.wechatbridge.core.util.NameSource +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.StandardOpenOption +import java.time.Clock +import java.time.Instant +import java.time.ZoneId +import java.util.UUID +import java.util.zip.ZipFile +import kotlin.coroutines.coroutineContext + +/** One ZIP in a saved batch, as read after the commit. */ +data class ArchiveCheck( + val displayName: String, + /** [WeChatArchive.messageCount]; null when the archive has no recognisable WeChat TXT or failed to verify. */ + val messageCount: Int?, + /** Non-TXT files inside the archive (images, videos, documents). Null when unreadable. */ + val attachmentCount: Int?, +) { + val isWeChatFormat: Boolean get() = messageCount != null +} + +/** What [UriImporter] did with one share. */ +sealed interface ImportOutcome { + data class Saved( + val batchId: UUID, + val directory: File, + val items: List, + val archives: List, + /** Every parsed record across the batch's WeChat archives, oldest first. */ + val records: List, + val collect: Boolean, + ) : ImportOutcome + + data class Failed(val failure: ReceiveFailure) : ImportOutcome +} + +/** + * Copies a share into `inbox/staging//` and publishes it to `ready/` in + * one atomic rename (port of `AttachmentImporter` + the import half of the iOS + * `ShareViewController`). + * + * - Streams are copied in [BUFFER_SIZE] chunks, never read whole. + * - All items or none: any failure (including cancellation) discards staging. + * - Every share, kept or refused, leaves a redacted record in `inbox/diagnostics/`. + * + * The copy must finish while the receiving Activity is alive: the sender's + * URI grant does not outlive it (android-plan §2.1). + */ +class UriImporter( + private val inbox: Inbox, + /** Recorded as `extensionVersion`; a field report that does not name its build is useless. */ + private val buildVersion: String? = null, + private val clock: Clock = Clock.systemUTC(), + private val zone: ZoneId = ZoneId.systemDefault(), + /** Device MIME table (`MimeTypeMap`) as a last resort; injected so tests stay JVM-only. */ + private val extensionLookup: (String) -> String? = { null }, +) { + /** Runs on [Dispatchers.IO]; cancelling the caller discards the staging batch. */ + suspend fun import(items: List, collect: Boolean): ImportOutcome { + val context = coroutineContext + return withContext(Dispatchers.IO) { + importBlocking(items, collect) { context.ensureActive() } + } + } + + /** + * Blocking form of [import]. [checkCancellation] is called between chunks + * and should throw to stop; the exception is rethrown after cleanup. + */ + fun importBlocking( + items: List, + collect: Boolean, + checkCancellation: () -> Unit = {}, + ): ImportOutcome { + val createdAt = clock.instant() + val diagnostics = mutableListOf() + + fun record(batchId: UUID, succeeded: Boolean) { + DiagnosticsLog.record( + ImportDiagnostics( + action = ACTION.rawValue, + attachments = diagnostics.toList(), + batchID = batchId, + createdAt = createdAt, + extensionVersion = buildVersion, + inputItemCount = items.size, + succeeded = succeeded, + ), + inbox.diagnostics.toPath(), + ) + } + + fun refuse(failure: ReceiveFailure, batchId: UUID = UUID.randomUUID()): ImportOutcome { + record(batchId, succeeded = false) + return ImportOutcome.Failed(failure) + } + + if (items.isEmpty()) return refuse(ReceiveFailure.EmptyShare) + if (items.size > MAX_ITEMS) return refuse(ReceiveFailure.TooManyItems(items.size)) + // Links and text are read as values and merged into one note, as on iOS; everything else is a file. + val streams = items.withIndex().filter { it.value is ShareItem.Stream } + val origin = ShareOrigins.from(items.filterIsInstance()) + if (streams.isEmpty() && origin == null) { + diagnostics += noteDiagnostic(items.size, null, "empty text") + return refuse(ReceiveFailure.EmptyShare) + } + + val staging = try { + BatchStaging.create(inbox) + } catch (_: IOException) { + return refuse(ReceiveFailure.StorageFailed) + } + + val manifestItems = mutableListOf() + val committed: File + try { + for ((index, item) in streams) { + checkCancellation() + val result = copyStream(item as ShareItem.Stream, index, staging, checkCancellation) + diagnostics += result.diagnostic + val failure = result.failure + if (failure != null) { + staging.discard() + return refuse(failure, staging.batchId) + } + manifestItems += result.item!! + } + if (origin != null) { + val result = writeNote(origin, items.size, staging) + diagnostics += result.diagnostic + manifestItems += result.item!! + } + checkCancellation() + + val manifest = BatchManifest( + batchId = staging.batchId, + createdAt = createdAt, + items = manifestItems, + action = ACTION, + ) + val payload = ImportDiagnostics( + action = ACTION.rawValue, + attachments = diagnostics.toList(), + batchID = staging.batchId, + createdAt = createdAt, + extensionVersion = buildVersion, + inputItemCount = items.size, + succeeded = true, + ).encoded()?.toByteArray(StandardCharsets.UTF_8) + if (collect) CollectMarker.mark(staging.directory) + // What RelaySummary reads for the LINK card and the source app (iOS writes it here too). + origin?.write(staging.directory) + committed = staging.commit(manifest, payload, intent = null, inbox = inbox) + } catch (error: Throwable) { + staging.discard() + if (error is IOException) return refuse(ReceiveFailure.StorageFailed, staging.batchId) + // Cancellation (or anything unexpected): nothing was published; let the caller see it. + record(staging.batchId, succeeded = false) + throw error + } + record(staging.batchId, succeeded = true) + runCatching { inbox.pruneStaging(now = clock.instant()) } + + // The files are durable; what follows only describes them and can never unsave them, + // so it is neither cancellable nor allowed to throw. + val archives = mutableListOf() + val records = mutableListOf() + for (manifestItem in manifestItems) { + if (!manifestItem.displayName.endsWith(".zip", ignoreCase = true)) continue + val file = File(committed, manifestItem.relativePath) + val check = runCatching { checkArchive(manifestItem.displayName, file) } + .getOrElse { ArchiveCheck(manifestItem.displayName, null, null) } + archives += check + if (check.isWeChatFormat) records += runCatching { readRecords(file) }.getOrDefault(emptyList()) + } + return ImportOutcome.Saved( + batchId = staging.batchId, + directory = committed, + items = manifestItems.toList(), + archives = archives, + records = records.sortedBy { it.date }, + collect = collect, + ) + } + + private class ItemResult( + val item: ManifestItem?, + val diagnostic: AttachmentDiagnostic, + val failure: ReceiveFailure?, + ) + + private fun copyStream( + source: ShareItem.Stream, + index: Int, + staging: BatchStaging, + checkCancellation: () -> Unit, + ): ItemResult { + val mime = source.mimeType + val suggested = runCatching { source.displayName() }.getOrNull()?.takeIf { it.isNotBlank() } + val suggestedExtension = suggested?.substringAfterLast('.', "")?.takeIf { it.isNotEmpty() && it != suggested } + val nameSource = when { + suggested != null -> NameSource.SUGGESTED + source.loadStrategy == LoadStrategy.FILE_URL -> NameSource.FILE_URL + else -> NameSource.TEMPORARY_FILE + } + + fun diagnostic(byteCount: Long?, failure: String?) = AttachmentDiagnostic( + itemIndex = 0, + attachmentIndex = index, + registeredTypeIdentifiers = listOfNotNull(mime), + hasSuggestedName = suggested != null, + suggestedNameExtension = suggestedExtension, + nameSource = nameSource, + selectedTypeIdentifier = mime, + loadStrategy = source.loadStrategy.rawValue(), + byteCount = byteCount, + failure = failure, + ) + + val input: InputStream = try { + source.open() + } catch (error: Exception) { + // Only the class name: messages from providers can carry paths and chat titles. + return ItemResult(null, diagnostic(null, "open: ${error.javaClass.simpleName}"), ReceiveFailure.Unreadable) + } + + input.use { stream -> + val buffer = ByteArray(BUFFER_SIZE) + val headerLength = readUpTo(stream, buffer, HEADER_SIZE) + val fallbackExtension = MimeTypes.extension(mime, extensionLookup) ?: MimeTypes.sniff(buffer, headerLength) + val displayName = DisplayName.sanitize(suggested, fallbackExtension) + val itemId = UUID.randomUUID() + val destination = staging.destination(itemId, displayName) + var total = 0L + try { + Files.newOutputStream(destination.toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE).use { out -> + if (headerLength > 0) { + out.write(buffer, 0, headerLength) + total += headerLength + } + while (true) { + checkCancellation() + val count = stream.read(buffer) + if (count < 0) break + out.write(buffer, 0, count) + total += count + } + out.flush() + } + } catch (error: IOException) { + // A read failure from the sender's side is theirs; ours would surface on write. + return ItemResult(null, diagnostic(total, "copy: ${error.javaClass.simpleName}"), ReceiveFailure.Unreadable) + } + + if (total == 0L) { + return ItemResult(null, diagnostic(0, "empty file"), ReceiveFailure.EmptyFile(displayName)) + } + val item = ManifestItem( + id = itemId, + displayName = displayName, + relativePath = staging.relativePath(itemId, displayName), + contentType = mime, + byteCount = total, + itemIndex = 0, + attachmentIndex = index, + loadStrategy = source.loadStrategy, + ) + return ItemResult(item, diagnostic(total, null), null) + } + } + + /** iOS `writeNote`: the TXT that carries the link to wherever the batch is delivered. */ + private fun writeNote(origin: ShareOrigin, index: Int, staging: BatchStaging): ItemResult { + val body = origin.note.toByteArray(StandardCharsets.UTF_8) + val name = ShareOrigins.noteFileName(origin) + val id = UUID.randomUUID() + Files.write(staging.destination(id, name).toPath(), body, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) + val item = ManifestItem( + id = id, + displayName = name, + relativePath = staging.relativePath(id, name), + contentType = NOTE_CONTENT_TYPE, + byteCount = body.size.toLong(), + itemIndex = 0, + attachmentIndex = index, + loadStrategy = LoadStrategy.FILE_REPRESENTATION, + ) + return ItemResult(item, noteDiagnostic(index, body.size.toLong(), null), null) + } + + private fun noteDiagnostic(index: Int, byteCount: Long?, failure: String?) = AttachmentDiagnostic( + itemIndex = 0, + attachmentIndex = index, + registeredTypeIdentifiers = listOf(NOTE_CONTENT_TYPE), + hasSuggestedName = false, + selectedTypeIdentifier = NOTE_CONTENT_TYPE, + byteCount = byteCount, + failure = failure, + ) + + private fun checkArchive(displayName: String, file: File): ArchiveCheck { + val count = try { + WeChatArchive.messageCount(file, zone) + } catch (_: WeChatReadException) { + null + } catch (_: IOException) { + null + } + return ArchiveCheck(displayName, count, if (count != null) attachmentCount(file) else null) + } + + private fun readRecords(file: File): List = try { + WeChatArchive.transcript(file, zone)?.records.orEmpty() + } catch (_: WeChatReadException) { + emptyList() + } catch (_: IOException) { + emptyList() + } + + companion object { + /** Same ceiling as the iOS share extension (`NSExtensionActivationSupportsFileWithMaxCount`). */ + const val MAX_ITEMS = 32 + + const val BUFFER_SIZE = 64 * 1024 + private const val HEADER_SIZE = 4 + + /** Every save is recorded as `collect`, as on iOS; the collect entry adds [CollectMarker]. */ + val ACTION = ShareAction.COLLECT + + /** iOS `ShareOrigin.noteContentType` (`public.url`): what RelaySummary and delivery look for. */ + const val NOTE_CONTENT_TYPE = ShareOrigin.NOTE_CONTENT_TYPE + + private fun readUpTo(stream: InputStream, buffer: ByteArray, length: Int): Int { + var read = 0 + while (read < length) { + val count = stream.read(buffer, read, length - read) + if (count < 0) break + read += count + } + return read + } + + /** Non-directory, non-TXT entries. ISO-8859-1 never fails to decode a GBK name, and only the suffix matters. */ + private fun attachmentCount(file: File): Int? = try { + ZipFile(file, StandardCharsets.ISO_8859_1).use { zip -> + zip.entries().asSequence().count { !it.isDirectory && !it.name.lowercase().endsWith(".txt") } + } + } catch (_: IOException) { + null + } + + private fun LoadStrategy.rawValue(): String = when (this) { + LoadStrategy.FILE_REPRESENTATION -> "fileRepresentation" + LoadStrategy.FILE_URL -> "fileURL" + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/DocumentOps.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/DocumentOps.kt new file mode 100644 index 00000000..878dc0af --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/DocumentOps.kt @@ -0,0 +1,155 @@ +package com.xiangming.wechatbridge.saf + +import android.content.ContentResolver +import android.database.Cursor +import android.net.Uri +import android.provider.DocumentsContract +import android.provider.DocumentsContract.Document +import java.io.FileNotFoundException +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream + +/** + * The handful of `DocumentsContract` calls [SafTreeWriter] needs, over one + * picked tree. Documents are addressed by their document id (a String), so the + * writer and its tests never touch `Uri` or a `ContentResolver`; production is + * [ContentDocumentOps], tests use an in-memory fake. + * + * Queries return null when the provider refuses or the document is gone; + * mutations throw [IOException] (a revoked grant's `SecurityException` + * included). + */ +interface DocumentOps { + data class Doc( + val id: String, + /** `COLUMN_DISPLAY_NAME`: the name the provider actually gave it. */ + val name: String, + val isDirectory: Boolean, + /** `FLAG_DIR_SUPPORTS_CREATE` (directories only). */ + val canCreate: Boolean = isDirectory, + ) + + /** The tree's own document id (`getTreeDocumentId`). */ + val rootId: String + + /** The persisted read + write grant for the tree is still held. */ + fun hasPermission(): Boolean + + fun stat(id: String): Doc? + + /** Children of the directory [id]; null when it cannot be listed. */ + fun children(id: String): List? + + /** + * `DocumentsContract.createDocument`. The provider may give the new + * document another name (`name (1).md` on a clash, or a sanitized one); + * the returned [Doc.name] is what it really is called. + */ + @Throws(IOException::class) + fun create(parentId: String, mimeType: String, name: String): Doc + + @Throws(IOException::class) + fun delete(id: String) + + /** [mode] as `ContentResolver.openOutputStream`: "w" or "wt". */ + @Throws(IOException::class) + fun openOutput(id: String, mode: String): OutputStream + + @Throws(IOException::class) + fun openInput(id: String): InputStream + + companion object { + /** Not `text/markdown`: some providers append an extension they derive from the MIME type. */ + const val FILE_MIME = "application/octet-stream" + /** `Document.MIME_TYPE_DIR`. */ + const val DIRECTORY_MIME = "vnd.android.document/directory" + } +} + +/** [DocumentOps] over a tree URI from `ACTION_OPEN_DOCUMENT_TREE`. */ +class ContentDocumentOps( + private val resolver: ContentResolver, + private val tree: Uri, + private val permission: () -> Boolean, +) : DocumentOps { + override val rootId: String = DocumentsContract.getTreeDocumentId(tree) + + override fun hasPermission(): Boolean = permission() + + private fun uri(id: String): Uri = DocumentsContract.buildDocumentUriUsingTree(tree, id) + + override fun stat(id: String): DocumentOps.Doc? = query(uri(id)).firstOrNull() + + override fun children(id: String): List? = + queryOrNull(DocumentsContract.buildChildDocumentsUriUsingTree(tree, id)) + + override fun create(parentId: String, mimeType: String, name: String): DocumentOps.Doc = io { + val created = DocumentsContract.createDocument(resolver, uri(parentId), mimeType, name) + ?: throw IOException("provider refused to create $name") + val id = DocumentsContract.getDocumentId(created) + stat(id) ?: DocumentOps.Doc(id, name, mimeType == DocumentOps.DIRECTORY_MIME) + } + + override fun delete(id: String) { + io { if (!DocumentsContract.deleteDocument(resolver, uri(id))) throw IOException("provider refused to delete $id") } + } + + override fun openOutput(id: String, mode: String): OutputStream = io { + resolver.openOutputStream(uri(id), mode) ?: throw IOException("cannot open $id for writing") + } + + override fun openInput(id: String): InputStream = io { + resolver.openInputStream(uri(id)) ?: throw IOException("cannot open $id") + } + + private fun query(uri: Uri): List = queryOrNull(uri).orEmpty() + + private fun queryOrNull(uri: Uri): List? = try { + resolver.query(uri, PROJECTION, null, null, null)?.use(::read) + } catch (_: SecurityException) { + null + } catch (_: IllegalArgumentException) { + null + } catch (_: IllegalStateException) { + null + } catch (_: UnsupportedOperationException) { + null + } + + private fun read(cursor: Cursor): List { + val docs = ArrayList(cursor.count.coerceAtLeast(0)) + while (cursor.moveToNext()) { + val id = cursor.getString(0) ?: continue + val name = cursor.getString(1) ?: continue + val directory = cursor.getString(2) == Document.MIME_TYPE_DIR + val flags = if (cursor.isNull(3)) 0 else cursor.getInt(3) + docs += DocumentOps.Doc(id, name, directory, directory && flags and Document.FLAG_DIR_SUPPORTS_CREATE != 0) + } + return docs + } + + /** A revoked grant or a vanished document surfaces as [IOException], as [DocumentOps] promises. */ + private inline fun io(block: () -> T): T = try { + block() + } catch (e: IOException) { + throw e + } catch (e: SecurityException) { + throw IOException("permission lost", e) + } catch (e: IllegalArgumentException) { + throw FileNotFoundException(e.message).apply { initCause(e) } + } catch (e: IllegalStateException) { + throw IOException(e.message, e) + } catch (e: UnsupportedOperationException) { + throw IOException(e.message, e) + } + + private companion object { + val PROJECTION = arrayOf( + Document.COLUMN_DOCUMENT_ID, + Document.COLUMN_DISPLAY_NAME, + Document.COLUMN_MIME_TYPE, + Document.COLUMN_FLAGS, + ) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/SafTreeWriter.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/SafTreeWriter.kt new file mode 100644 index 00000000..c97095f1 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/SafTreeWriter.kt @@ -0,0 +1,156 @@ +package com.xiangming.wechatbridge.saf + +import com.xiangming.wechatbridge.core.note.TreeWriter +import java.io.FileNotFoundException +import java.io.IOException +import java.io.OutputStream +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.CodingErrorAction + +/** + * [TreeWriter] over a SAF tree (an Obsidian vault or a folder the user picked), + * through [DocumentOps]. Paths are resolved by walking display names from the + * tree root, one `children` query per level. + * + * The conventions `TreeWriter` leaves to SAF implementations (A1.8): + * - [createNew] looks for the name first; when the provider still gives the + * new document another name (`name (1).md`: someone created the name in + * between), that document is deleted again and null is returned. A name the + * provider changes for any other reason (sanitizing) throws, so + * `createUnique` does not spin through 10 000 numbers. + * - [replaceText] opens with "wt": "w" alone does not truncate on some providers. + * - [remove] deletes only the document this writer created (same document id), + * never a directory. + * - [isWritableRoot] requires the persisted grant, and a root directory that + * still accepts new documents. + * + * Blocking provider IO: call off the main thread. + */ +class SafTreeWriter(private val ops: DocumentOps) : TreeWriter { + override fun isWritableRoot(): Boolean { + if (!ops.hasPermission()) return false + val root = ops.stat(ops.rootId) ?: return false + return root.isDirectory && root.canCreate + } + + override fun exists(path: String): Boolean = resolve(path) != null + + override fun isDirectory(path: String): Boolean = resolve(path)?.isDirectory == true + + override fun list(path: String): List? { + val dir = resolve(path)?.takeIf { it.isDirectory } ?: return null + return ops.children(dir.id)?.map { it.name } + } + + override fun createDirectory(path: String) { + val (parentPath, name) = split(path) + val parent = directory(parentPath) + val existing = child(parent, name) + if (existing != null) { + if (existing.isDirectory) return + throw IOException("a file is in the way: $path") + } + val created = ops.create(parent.id, DocumentOps.DIRECTORY_MIME, name) + if (created.name == name && created.isDirectory) return + // Renamed ("name (1)"): another writer made the directory meanwhile, or the provider rewrote the name. + ops.delete(created.id) + if (child(parent, name)?.isDirectory == true) return + throw IOException("provider renamed directory $name to ${created.name}") + } + + override fun readText(path: String): String? { + val doc = resolve(path)?.takeIf { !it.isDirectory } ?: return null + return try { + val bytes = ops.openInput(doc.id).use { it.readBytes() } + Charsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString() + } catch (_: CharacterCodingException) { + null + } catch (_: IOException) { + null + } + } + + override fun createNew(dir: String, name: String, write: (OutputStream) -> Unit): TreeWriter.Created? { + val parent = directory(dir) + if (child(parent, name) != null) return null + val doc = ops.create(parent.id, DocumentOps.FILE_MIME, name) + if (doc.name != name || doc.isDirectory) { + ops.delete(doc.id) + // Taken in between: the caller numbers on. Otherwise the provider will never take this name. + if (child(parent, name) != null) return null + throw IOException("provider renamed $name to ${doc.name}") + } + val created = TreeWriter.Created(TreeWriter.join(dir, name), doc.id) + try { + ops.openOutput(doc.id, "w").use { output -> + write(output) + output.flush() + } + } catch (e: Throwable) { + try { + remove(created) + } catch (cleanup: IOException) { + e.addSuppressed(cleanup) + } + throw e + } + return created + } + + override fun replaceText(path: String, text: String) { + val doc = resolve(path)?.takeIf { !it.isDirectory } ?: throw FileNotFoundException(path) + ops.openOutput(doc.id, "wt").use { output -> + output.write(text.toByteArray(Charsets.UTF_8)) + output.flush() + } + } + + override fun remove(created: TreeWriter.Created) { + val doc = resolve(created.path) ?: return + if (doc.isDirectory) return + if (created.identity != null && doc.id != created.identity) return + try { + ops.delete(doc.id) + } catch (e: IOException) { + if (resolve(created.path)?.id == doc.id) throw e + } + } + + // region Paths + + private fun split(path: String): Pair { + val parts = components(path) + require(parts.isNotEmpty()) { "the root has no parent" } + return parts.dropLast(1).joinToString("/") to parts.last() + } + + private fun components(path: String): List { + if (path.isEmpty()) return emptyList() + val parts = path.split('/') + require(parts.all { it.isNotEmpty() && it != "." && it != ".." && '\u0000' !in it }) { "invalid tree path: $path" } + return parts + } + + private fun child(parent: DocumentOps.Doc, name: String): DocumentOps.Doc? = + ops.children(parent.id)?.firstOrNull { it.name == name } + + /** The document at [path], or null when any level is missing or unreadable. */ + private fun resolve(path: String): DocumentOps.Doc? { + var at = ops.stat(ops.rootId) ?: return null + for (part in components(path)) { + if (!at.isDirectory) return null + at = child(at, part) ?: return null + } + return at + } + + private fun directory(path: String): DocumentOps.Doc = + resolve(path)?.takeIf { it.isDirectory } ?: throw FileNotFoundException("not a directory: ${path.ifEmpty { "/" }}") + + // endregion +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/TreeStore.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/TreeStore.kt new file mode 100644 index 00000000..c363a776 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/saf/TreeStore.kt @@ -0,0 +1,214 @@ +package com.xiangming.wechatbridge.saf + +import android.content.Context +import android.content.Intent +import android.content.SharedPreferences +import android.net.Uri +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.note.NoteDelivery +import com.xiangming.wechatbridge.core.note.TreeWriter +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** Where one of the two write roots stands. */ +enum class TreeStatus { + /** Never picked (or cleared): ask the user to pick one. */ + NOT_CHOSEN, + + /** Picked, the persisted grant is held and the root is a writable directory. */ + GRANTED, + + /** + * Picked once, but the grant is gone (revoked in system settings, the app + * reinstalled, the provider removed) or the folder itself is gone. Ask the + * user to pick it again; never recreate it. + */ + LOST, +} + +/** + * The platform half of [TreeStore]: persisted URI grants and document access. + * Production is [ContentTreeHost]; tests pass a fake. + */ +interface TreeHost { + /** Trees whose persisted grant includes write. */ + fun persistedWritableTrees(): Set + + /** `takePersistableUriPermission` for read + write; throws `SecurityException` when not offered. */ + fun takePermission(tree: Uri) + + fun releasePermission(tree: Uri) + + fun documents(tree: Uri): DocumentOps +} + +class ContentTreeHost(context: Context) : TreeHost { + private val resolver = context.applicationContext.contentResolver + + override fun persistedWritableTrees(): Set = + resolver.persistedUriPermissions.filter { it.isWritePermission && it.isReadPermission }.map { it.uri }.toSet() + + override fun takePermission(tree: Uri) { + resolver.takePersistableUriPermission(tree, FLAGS) + } + + override fun releasePermission(tree: Uri) { + resolver.releasePersistableUriPermission(tree, FLAGS) + } + + override fun documents(tree: Uri): DocumentOps = + ContentDocumentOps(resolver, tree) { tree in persistedWritableTrees() } + + private companion object { + const val FLAGS = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + } +} + +/** + * The two SAF roots notes are written into: the Obsidian vault + * ([TargetKind.VAULT]) and the default folder ([TargetKind.FOLDER]), each with + * its subfolder name. Android counterpart of iOS `FolderBookmark` plus the + * `obsidianBookmark` / `folderBookmark` / `…Subfolder` preferences. + * + * The tree URIs are kept in their own SharedPreferences file (not DataStore: + * reads happen on the write path, off the main thread, and must be + * synchronous). The grant itself lives in the system; [status] checks both. + * + * [status], [folderName], [grant] and [writer] do provider IO: call them off + * the main thread. + */ +class TreeStore(private val prefs: SharedPreferences, private val host: TreeHost) { + data class Root( + val kind: TargetKind, + /** The picked tree; null when never picked. */ + val uri: Uri?, + /** As the user typed it; empty means [NoteDelivery.DEFAULT_FOLDER]. */ + val subfolder: String, + ) { + /** The folder inside the root that notes go to, for display. */ + val effectiveSubfolder: String get() = subfolder.trim().ifEmpty { NoteDelivery.DEFAULT_FOLDER } + } + + private val lock = Any() + private val _roots = MutableStateFlow(read()) + + /** Both roots as stored; [status] says whether a stored one still works. */ + val roots: StateFlow> = _roots.asStateFlow() + + fun root(kind: TargetKind): Root = _roots.value.getValue(requireSaf(kind)) + + fun status(kind: TargetKind): TreeStatus { + val uri = root(kind).uri ?: return TreeStatus.NOT_CHOSEN + if (uri !in safe { host.persistedWritableTrees() }.orEmpty()) return TreeStatus.LOST + val writable = safe { SafTreeWriter(host.documents(uri)).isWritableRoot() } ?: false + return if (writable) TreeStatus.GRANTED else TreeStatus.LOST + } + + /** The root folder's display name, for 「写入:Vault/微信流」; null when unknown. */ + fun folderName(kind: TargetKind): String? { + val uri = root(kind).uri ?: return null + return safe { host.documents(uri).let { ops -> ops.stat(ops.rootId)?.name } } + } + + /** A writer when [status] is [TreeStatus.GRANTED]; null otherwise. */ + fun writer(kind: TargetKind): TreeWriter? { + if (status(kind) != TreeStatus.GRANTED) return null + val uri = root(kind).uri ?: return null + return SafTreeWriter(host.documents(uri)) + } + + /** + * Keeps [tree] (fresh from `OpenDocumentTree`) as the root for [kind]: + * takes the persisted grant, stores the URI, releases the previous root's + * grant unless the other kind still uses it. Returns the resulting status; + * a refused grant leaves the previous root in place. + */ + fun grant(kind: TargetKind, tree: Uri): TreeStatus { + requireSaf(kind) + try { + host.takePermission(tree) + } catch (_: SecurityException) { + return TreeStatus.LOST + } catch (_: IllegalArgumentException) { + return TreeStatus.LOST + } + val previous = synchronized(lock) { + val old = root(kind).uri + prefs.edit().putString(uriKey(kind), tree.toString()).apply() + update(kind) { it.copy(uri = tree) } + old + } + releaseIfUnused(previous, tree) + return status(kind) + } + + /** Forgets the root for [kind] and gives its grant back. */ + fun clear(kind: TargetKind) { + val previous = synchronized(lock) { + val old = root(kind).uri + prefs.edit().remove(uriKey(kind)).apply() + update(kind) { it.copy(uri = null) } + old + } + releaseIfUnused(previous, null) + } + + fun setSubfolder(kind: TargetKind, subfolder: String) { + synchronized(lock) { + prefs.edit().putString(subfolderKey(requireSaf(kind)), subfolder).apply() + update(kind) { it.copy(subfolder = subfolder) } + } + } + + private fun releaseIfUnused(previous: Uri?, replacement: Uri?) { + if (previous == null || previous == replacement) return + if (_roots.value.values.any { it.uri == previous }) return + safe { host.releasePermission(previous) } + } + + private fun update(kind: TargetKind, edit: (Root) -> Root) { + _roots.value = _roots.value + (kind to edit(_roots.value.getValue(kind))) + } + + private fun read(): Map = KINDS.associateWith { kind -> + Root( + kind = kind, + uri = prefs.getString(uriKey(kind), null)?.let(Uri::parse), + subfolder = prefs.getString(subfolderKey(kind), null).orEmpty(), + ) + } + + private fun requireSaf(kind: TargetKind): TargetKind { + require(kind in KINDS) { "$kind is not written through SAF" } + return kind + } + + /** A provider that crashes or refuses is treated as unavailable, never as a crash. */ + private inline fun safe(block: () -> T): T? = try { + block() + } catch (_: SecurityException) { + null + } catch (_: IllegalArgumentException) { + null + } catch (_: java.io.IOException) { + null + } catch (_: IllegalStateException) { + null + } catch (_: UnsupportedOperationException) { + null + } + + companion object { + const val FILE_NAME = "saf_trees" + val KINDS = listOf(TargetKind.VAULT, TargetKind.FOLDER) + + private fun uriKey(kind: TargetKind) = "${kind.name.lowercase()}.tree" + private fun subfolderKey(kind: TargetKind) = "${kind.name.lowercase()}.subfolder" + + fun create(context: Context): TreeStore = TreeStore( + prefs = context.applicationContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE), + host = ContentTreeHost(context), + ) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/collection/CollectionScreen.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/collection/CollectionScreen.kt new file mode 100644 index 00000000..4be8507a --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/collection/CollectionScreen.kt @@ -0,0 +1,597 @@ +package com.xiangming.wechatbridge.ui.collection + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.res.Resources +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.core.content.getSystemService +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.notify.CollectNotification +import com.xiangming.wechatbridge.receive.DropDestination +import com.xiangming.wechatbridge.ui.drop.DropResultsEffect +import com.xiangming.wechatbridge.ui.drop.DropTargetBox +import com.xiangming.wechatbridge.ui.relay.RelayCardText +import com.xiangming.wechatbridge.ui.theme.BridgeAmbientBackdrop +import com.xiangming.wechatbridge.ui.theme.BridgeBentoCard +import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface +import com.xiangming.wechatbridge.ui.theme.BridgePrimaryCapsuleButton +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale +import java.time.Instant +import java.time.ZoneId + +/** 收集详情:顶部淡绿提示卡 + 16dp 批次白卡列表 + 吸底双按钮栏(「继续收集」+「合并并投递」)。 */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CollectionScreen( + collectionId: String, + onBack: () -> Unit, + onDeliver: (batchIds: List) -> Unit, +) { + val context = LocalContext.current + val app = context.applicationContext as App + val container = app.container + val viewModel: CollectionViewModel = viewModel(key = "collection-$collectionId") { + CollectionViewModel( + collectionId = CollectionViewModel.parseId(collectionId), + store = container.relayStore, + onChanged = { CollectNotification.sync(app, container.relayStore) }, + ) + } + val state by viewModel.state.collectAsStateWithLifecycle(initialValue = viewModel.initial) + var seen by rememberSaveable { mutableStateOf(false) } + var confirmAbandon by rememberSaveable { mutableStateOf(false) } + val resources = context.resources + val text = remember(resources) { RelayCardText(resources, Instant.now(), ZoneId.systemDefault()) } + val appColors = LocalAppColors.current + + // Finished or abandoned elsewhere (the notification, a delivery): leave the page. + LaunchedEffect(state.collection == null) { + if (state.collection != null) seen = true else if (seen) onBack() + } + + val collection = state.collection + val snackbarHostState = remember { SnackbarHostState() } + DropResultsEffect(snackbarHostState) + val dropId = remember(collectionId) { CollectionViewModel.parseId(collectionId) } + + val summaryText = if (collection != null) { + state.messageCount?.let { stringResource(R.string.collect_summary, state.rows.size, it) } + ?: stringResource(R.string.collect_summary_unknown, state.rows.size) + } else { + null + } + + DropTargetBox( + destination = dropId?.let(DropDestination::Collection) ?: DropDestination.Relay, + modifier = Modifier.fillMaxSize(), + ) { + Box(modifier = Modifier.fillMaxSize()) { + BridgeAmbientBackdrop() + Scaffold( + containerColor = Color.Transparent, + snackbarHost = { SnackbarHost(snackbarHostState) }, + topBar = { + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + scrolledContainerColor = MaterialTheme.colorScheme.background.copy(alpha = 0.88f), + ), + title = { + Column(verticalArrangement = Arrangement.spacedBy(1.dp)) { + Text( + collection?.name?.ifEmpty { null } ?: stringResource(R.string.collect_title_untitled), + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (summaryText != null) { + Text( + summaryText, + style = MaterialTheme.typography.labelMedium, + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.action_back), + ) + } + }, + actions = { + if (collection != null) { + TextButton(onClick = { confirmAbandon = true }) { + Text( + stringResource(R.string.collect_abandon), + color = MaterialTheme.colorScheme.error, + ) + } + } + }, + ) + }, + bottomBar = { + if (collection != null) { + CollectionBottomBar( + canDeliver = state.canDeliver, + onContinue = { + viewModel.keywordCopied() + onBack() + }, + onDeliver = { onDeliver(viewModel.deliveryIds(state)) }, + ) + } + }, + ) { padding -> + if (collection == null) { + Box( + Modifier.fillMaxSize().padding(padding).padding(24.dp), + contentAlignment = Alignment.Center, + ) { + Text( + stringResource(R.string.collect_gone), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + return@Scaffold + } + LazyColumn( + modifier = Modifier.fillMaxSize().padding(padding), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + item(key = "tip-card") { + val anchor = state.nextAnchor + if (anchor != null) { + NextBatchCard(anchor, text, onCopied = viewModel::keywordCopied) + } else { + CollectionTintCard(summary = summaryText.orEmpty()) + } + } + if (state.rows.isEmpty()) { + item(key = "empty") { + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + contentPadding = PaddingValues(16.dp), + ) { + Text( + stringResource(R.string.collect_empty), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + items(state.rows, key = { it.id }) { row -> + BatchRowCard(row, text, resources, onRemove = { viewModel.remove(row.id) }) + } + item(key = "footer-hints") { + Column( + modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text( + stringResource(R.string.collect_merge_hint), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + ) + Text( + stringResource(R.string.collect_removed_hint), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + ) + } + } + } + } + } + } + + if (confirmAbandon) { + AlertDialog( + onDismissRequest = { confirmAbandon = false }, + title = { Text(stringResource(R.string.collect_abandon_title)) }, + text = { Text(stringResource(R.string.collect_abandon_body)) }, + confirmButton = { + TextButton(onClick = { + confirmAbandon = false + viewModel.abandon() + onBack() + }) { Text(stringResource(R.string.collect_abandon_confirm), color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { + TextButton(onClick = { confirmAbandon = false }) { Text(stringResource(R.string.action_cancel)) } + }, + ) + } +} + +@Composable +private fun CollectionBottomBar( + canDeliver: Boolean, + onContinue: () -> Unit, + onDeliver: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val continueInteraction = remember { MutableInteractionSource() } + + Row( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(horizontal = 16.dp, vertical = 12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + BridgeGlassSurface( + modifier = Modifier + .weight(1f) + .height(50.dp) + .pressScale(continueInteraction, targetScale = 0.97f), + shape = CircleShape, + shadowElevation = 10.dp, + ) { + Box( + modifier = Modifier + .fillMaxSize() + .clickable( + interactionSource = continueInteraction, + indication = LocalIndication.current, + role = Role.Button, + onClick = onContinue, + ) + .padding(horizontal = 16.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = stringResource(R.string.collect_continue), + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = colors.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + BridgePrimaryCapsuleButton( + text = stringResource(R.string.collect_merge_deliver), + onClick = onDeliver, + icon = Icons.AutoMirrored.Filled.Send, + enabled = canDeliver, + height = 50.dp, + modifier = Modifier.weight(1.4f), + ) + } +} + +@Composable +private fun CollectionTintCard(summary: String) { + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + highlighted = true, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp), + ) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + stringResource(R.string.collect_tip_title), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + if (summary.isNotEmpty()) { + Text( + summary, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.85f), + ) + } + Text( + stringResource(R.string.collect_merge_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.78f), + ) + } + } +} + +@Composable +private fun BatchRowCard( + row: CollectionBatchRow, + text: RelayCardText, + resources: Resources, + onRemove: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val summary = row.summary + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 18.dp, + contentPadding = PaddingValues(start = 16.dp, end = 6.dp, top = 12.dp, bottom = 14.dp), + ) { + Row(verticalAlignment = Alignment.Top) { + Column( + modifier = Modifier.weight(1f).padding(top = 2.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .clip(CircleShape) + .background(appColors.surfaceTint) + .border(0.6.dp, appColors.surfaceTintBorder, CircleShape) + .padding(horizontal = 9.dp, vertical = 2.5.dp), + ) { + Text( + resources.getString(R.string.collect_batch_label, row.number), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = colors.primary, + ) + } + val meta = buildList { + if (summary != null) { + val count = summary.messageCount + add( + if (count != null) resources.getString(R.string.collect_batch_count, count) + else resources.getString(R.string.collect_batch_count_unknown), + ) + } + row.entry?.let { add(text.time(it)) } + }.joinToString(" · ") + if (meta.isNotEmpty()) { + Text( + meta, + style = MaterialTheme.typography.labelMedium, + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + when { + row.entry == null || summary == null -> + Text( + stringResource(R.string.collect_batch_reading), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + ) + summary.kind != RelaySummary.Kind.CHAT || (summary.preview.isEmpty() && summary.last == null) -> + Text( + stringResource(R.string.collect_batch_unreadable), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + ) + else -> { + summary.preview.firstOrNull()?.let { first -> + Text( + stringResource(R.string.collect_batch_first, first), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurface, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + summary.last?.let { last -> + Text( + stringResource(R.string.collect_batch_last, last.sender, last.text), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + IconButton(onClick = onRemove) { + Icon( + Icons.Filled.Close, + contentDescription = stringResource(R.string.collect_remove), + tint = appColors.onSurfaceMuted, + modifier = Modifier.size(18.dp), + ) + } + } + } +} + +/** 绿白定位书签卡:左侧品牌绿竖条 + 浅绿底定位内容 + 一键复制胶囊按钮。 */ +@Composable +private fun NextBatchCard(anchor: NextBatchAnchor, text: RelayCardText, onCopied: () -> Unit) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + var copied by rememberSaveable(anchor.keyword) { mutableStateOf(false) } + val copyInteraction = remember { MutableInteractionSource() } + + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + highlighted = true, + contentPadding = PaddingValues(0.dp), + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .height(IntrinsicSize.Min) + .background(appColors.surfaceTint.copy(alpha = if (appColors.isDark) 0.55f else 0.72f)), + ) { + // 左侧醒目品牌绿竖条书签锚点 + Box( + modifier = Modifier + .width(5.dp) + .fillMaxHeight() + .background(colors.primary), + ) + Column( + modifier = Modifier + .weight(1f) + .padding(horizontal = 15.dp, vertical = 14.dp), + verticalArrangement = Arrangement.spacedBy(9.dp), + ) { + Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text( + text = stringResource(R.string.collect_next_title), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = colors.onPrimaryContainer, + ) + Text( + text = stringResource(R.string.collect_next_body), + style = MaterialTheme.typography.bodySmall, + color = colors.onPrimaryContainer.copy(alpha = 0.82f), + ) + } + + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(colors.surface.copy(alpha = if (appColors.isDark) 0.65f else 0.88f)) + .border(0.75.dp, appColors.surfaceTintBorder, RoundedCornerShape(12.dp)) + .padding(horizontal = 12.dp, vertical = 9.dp), + verticalArrangement = Arrangement.spacedBy(3.dp), + ) { + Text( + text = stringResource(R.string.collect_next_last, anchor.sender, text.range(anchor.date, null)), + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + Text( + text = anchor.text, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + maxLines = 3, + overflow = TextOverflow.Ellipsis, + color = colors.onSurface, + ) + } + + Row( + modifier = Modifier + .pressScale(copyInteraction, targetScale = 0.96f) + .clip(CircleShape) + .background(if (copied) colors.primary else colors.surface) + .border( + width = 0.9.dp, + color = if (copied) colors.primary else appColors.surfaceTintBorder, + shape = CircleShape, + ) + .clickable( + interactionSource = copyInteraction, + indication = LocalIndication.current, + role = Role.Button, + onClick = { + val clipboard = context.getSystemService() + val ok = runCatching { + clipboard?.setPrimaryClip(ClipData.newPlainText(CLIP_LABEL, anchor.keyword)) + }.isSuccess && clipboard != null + if (ok) { + copied = true + onCopied() + } + }, + ) + .padding(horizontal = 14.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Icon( + imageVector = if (copied) Icons.Filled.Check else Icons.Filled.Search, + contentDescription = null, + tint = if (copied) Color.White else colors.primary, + modifier = Modifier.size(16.dp), + ) + Text( + text = if (copied) { + stringResource(R.string.collect_copied_keyword, anchor.keyword) + } else { + stringResource(R.string.collect_copy_keyword) + }, + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = if (copied) Color.White else colors.primary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } +} + +private const val CLIP_LABEL = "WeChatBridge keyword" diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/collection/CollectionViewModel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/collection/CollectionViewModel.kt new file mode 100644 index 00000000..e10323ed --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/collection/CollectionViewModel.kt @@ -0,0 +1,129 @@ +package com.xiangming.wechatbridge.ui.collection + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.core.collection.BatchCollection +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.data.RelayStore +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import java.time.Instant +import java.util.UUID + +/** One row of the batch list: 「第 N 批」 in the order the batches were added. */ +data class CollectionBatchRow( + val id: UUID, + val number: Int, + /** Null while the relay has not loaded the batch (or it went missing). */ + val entry: RelayEntry?, +) { + val summary: RelaySummary? get() = entry?.summary +} + +/** Where the next batch starts when the last one hit WeChat's 100-message limit. */ +data class NextBatchAnchor( + val keyword: String, + val sender: String, + val date: Instant, + val text: String, +) + +data class CollectionUiState( + /** Null: no live collection with this id (finished, abandoned, or never loaded). */ + val collection: BatchCollection?, + val rows: List = emptyList(), + /** Sum of the known counts; null when no batch could be counted. */ + val messageCount: Int? = null, + /** Time order, what 「完成并投递」 hands over (as `RelayStore.orderedBatchIds`). */ + val orderedIds: List = emptyList(), + val nextAnchor: NextBatchAnchor? = null, +) { + val canDeliver: Boolean get() = collection != null && orderedIds.isNotEmpty() + + companion object { + /** + * A pure projection of the ledger and the relay list. The batch with the + * latest messages decides the 100-message hint, as iOS `lastBatch`. + */ + fun build(collectionId: UUID?, collections: List, entries: List): CollectionUiState { + val collection = collections.firstOrNull { + it.id == collectionId && it.status != BatchCollection.Status.DELIVERED + } ?: return CollectionUiState(collection = null) + val byId = entries.associateBy { it.id } + val rows = collection.batchIDs.mapIndexed { index, id -> CollectionBatchRow(id, index + 1, byId[id]) } + val present = rows.mapNotNull { it.entry } + val ordered = present.sortedBy { it.summary?.start ?: it.batch.createdAt } + val counts = present.mapNotNull { it.summary?.messageCount } + val last = ordered.lastOrNull()?.summary + val anchor = last?.takeIf { it.hitsForwardLimit }?.let { summary -> + val keyword = summary.anchor ?: return@let null + val line = summary.last ?: return@let null + NextBatchAnchor(keyword, line.sender, line.date, line.text) + } + return CollectionUiState( + collection = collection, + rows = rows, + messageCount = if (counts.isEmpty()) null else counts.sum(), + orderedIds = ordered.map { it.id }, + nextAnchor = anchor, + ) + } + } +} + +/** + * The collection detail page (iOS `CollectionDetailView`). Every edit goes + * through [RelayStore]; [onChanged] keeps the ongoing notification in step. + */ +class CollectionViewModel( + private val collectionId: UUID?, + private val store: RelayStore, + private val onChanged: () -> Unit = {}, +) : ViewModel() { + val state: Flow = combine(store.ledger, store.entries) { ledger, entries -> + CollectionUiState.build(collectionId, ledger.collections, entries) + } + + val initial: CollectionUiState + get() = CollectionUiState.build(collectionId, store.ledger.value.collections, store.entries.value) + + fun remove(batchId: UUID) { + viewModelScope.launch { removeNow(batchId) } + } + + /** 「移出本次收集」: the batch leaves the group and stays in the relay. */ + suspend fun removeNow(batchId: UUID) { + val id = collectionId ?: return + store.removeFromCollection(batchId, id) + runCatching(onChanged) + } + + fun abandon() { + viewModelScope.launch { abandonNow() } + } + + /** 「放弃」: drops the group record; its batches stay in the relay. */ + suspend fun abandonNow() { + val id = collectionId ?: return + store.forgetCollection(id) + runCatching(onChanged) + } + + /** Copying the keyword means more is coming: into this collection (iOS `willContinue`). */ + fun keywordCopied() { + val id = collectionId ?: return + viewModelScope.launch { + store.resumeCollection(id) + runCatching(onChanged) + } + } + + /** What 「完成并投递」 opens the delivery panel with, in merge (time) order. */ + fun deliveryIds(state: CollectionUiState): List = state.orderedIds.map { it.toString().uppercase() } + + companion object { + fun parseId(raw: String): UUID? = runCatching { UUID.fromString(raw) }.getOrNull() + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverContent.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverContent.kt new file mode 100644 index 00000000..2d5f1e59 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverContent.kt @@ -0,0 +1,466 @@ +package com.xiangming.wechatbridge.ui.deliver + +import androidx.compose.foundation.background +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.scene.SceneMatchSource +import com.xiangming.wechatbridge.deliver.DeliverUiState +import com.xiangming.wechatbridge.deliver.Preview +import com.xiangming.wechatbridge.deliver.SendBlock +import com.xiangming.wechatbridge.deliver.TargetOption +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.BridgeAmbientBackdrop +import com.xiangming.wechatbridge.ui.theme.BridgeBentoCard +import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface +import com.xiangming.wechatbridge.ui.theme.BridgePrimaryCapsuleButton +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale + +/** 投递面板的无状态内容;[DeliverScreen] 接 ViewModel,预览直接喂 [DeliverUiState]。 */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun DeliverContent( + state: DeliverUiState, + snackbarHostState: SnackbarHostState, + onBack: () -> Unit, + onDone: () -> Unit, + onSelectTarget: (TargetOption) -> Unit, + onUnavailableTarget: (TargetOption) -> Unit, + onSelectScene: (String?) -> Unit, + onEditPrompt: (String) -> Unit, + onChooseFormat: (DeliveryFormat?) -> Unit, + onSendOriginal: () -> Unit, + onSend: () -> Unit, + onPickFolder: () -> Unit = {}, + onChooseGroup: (String) -> Unit = {}, + onCreateGroup: (String) -> Unit = {}, + onBindScene: () -> Unit = {}, +) { + Box(modifier = Modifier.fillMaxSize()) { + BridgeAmbientBackdrop() + + Scaffold( + topBar = { + TopAppBar( + title = { + Text( + text = if (state.batchCount > 1) { + stringResource(R.string.deliver_title_merged, state.batchCount) + } else { + stringResource(R.string.nav_deliver) + }, + style = MaterialTheme.typography.titleLarge, + ) + }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.action_back), + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + scrolledContainerColor = Color.Transparent, + ), + ) + }, + bottomBar = { + if (!state.loading && !state.missingBatches) { + SendBar(state = state, onSend = onSend, onDone = onDone) + } + }, + snackbarHost = { SnackbarHost(snackbarHostState) }, + containerColor = Color.Transparent, + ) { padding -> + when { + state.loading -> CenteredBox(padding) { CircularProgressIndicator() } + state.missingBatches -> CenteredBox(padding) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text( + text = stringResource(R.string.deliver_missing_batches), + style = MaterialTheme.typography.bodyMedium, + textAlign = TextAlign.Center, + ) + TextButton(onClick = onBack) { Text(stringResource(R.string.action_back)) } + } + } + else -> Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + // 1. 顶部「待投递内容摘要卡」高亮 Bento 卡 + SummaryStripCard(state = state) + + // 2. 目标宫格 Bento 卡 + SectionCard(title = stringResource(R.string.deliver_section_targets)) { + TargetGrid( + targets = state.targets, + selectedId = state.selectedTargetId, + onSelect = onSelectTarget, + onUnavailable = onUnavailableTarget, + ) + } + + // 3. 场景与提示词 + 将投递的内容(选中目标后呈现决策漏斗下半段) + if (state.selectedTarget != null) { + val autoMatchedByGroup = state.sceneId != null && + state.sceneSource == SceneMatchSource.BINDING + SectionCard( + title = stringResource(R.string.deliver_section_scene), + trailingBadge = if (autoMatchedByGroup) { + { + AutoMatchedBadge(stringResource(R.string.deliver_scene_auto_matched)) + } + } else { + null + }, + ) { + GroupRow(state, onChooseGroup, onCreateGroup, onBindScene) + SceneSection(state, onSelectScene, onEditPrompt) + } + + SectionCard(title = stringResource(R.string.deliver_section_preview)) { + PreviewSection( + state = state, + onChooseFormat = onChooseFormat, + onSendOriginal = onSendOriginal, + onPickFolder = onPickFolder, + ) + } + } + + Spacer(Modifier.height(8.dp)) + } + } + } + } +} + +/** 顶部「待投递内容摘要卡」:高亮绿白 Bento 卡,展示聊天标题/批次数与消息/附件概览胶囊。 */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun SummaryStripCard(state: DeliverUiState) { + val appColors = LocalAppColors.current + val isMerged = state.batchCount > 1 + val title = if (isMerged) { + stringResource(R.string.deliver_title_merged, state.batchCount) + } else { + state.chatName?.takeIf { it.isNotBlank() } + ?: state.group.name?.takeIf { it.isNotBlank() } + ?: stringResource(R.string.deliver_summary_single_default) + } + val readyPreview = state.preview as? Preview.Ready + val subtitle = if (isMerged) { + val chat = state.chatName?.takeIf { it.isNotBlank() } ?: state.group.name?.takeIf { it.isNotBlank() } + chat ?: stringResource(R.string.deliver_summary_merged_sub, state.batchCount) + } else { + state.group.name?.takeIf { it.isNotBlank() && it != title } + ?: stringResource(R.string.deliver_summary_single_sub) + } + + val pills = buildList { + if (isMerged) { + add(stringResource(R.string.deliver_summary_batch_badge, state.batchCount) to true) + } + if (readyPreview != null) { + add(formatName(readyPreview.format) to false) + if (readyPreview.fileCount > 0) { + add(stringResource(R.string.deliver_summary_files_count, readyPreview.fileCount) to true) + } + if (readyPreview.inlineText) { + add(stringResource(R.string.deliver_summary_inline_tag) to false) + } + } + } + + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + highlighted = true, + contentPadding = PaddingValues(16.dp), + ) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(40.dp) + .clip(RoundedCornerShape(12.dp)) + .background(appColors.surfaceTint), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = if (isMerged) AppIcons.NavRelay else AppIcons.ChatBubble, + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = MaterialTheme.colorScheme.primary, + ) + } + Spacer(Modifier.width(12.dp)) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + text = title, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + + if (pills.isNotEmpty()) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + for ((label, accent) in pills) { + Surface( + shape = CircleShape, + color = if (accent) appColors.surfaceTint else appColors.surfaceSub, + ) { + Text( + text = label, + style = MaterialTheme.typography.labelSmall, + color = if (accent) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp), + ) + } + } + } + } + } + } +} + +@Composable +private fun AutoMatchedBadge(text: String) { + val appColors = LocalAppColors.current + Surface( + shape = CircleShape, + color = appColors.surfaceTint, + ) { + Text( + text = text, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(horizontal = 9.dp, vertical = 3.dp), + ) + } +} + +@Composable +private fun CenteredBox(padding: PaddingValues, content: @Composable () -> Unit) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .padding(24.dp), + contentAlignment = Alignment.Center, + ) { + content() + } +} + +/** 干净的 Bento 分区卡片。 */ +@Composable +private fun SectionCard( + title: String, + trailingBadge: (@Composable () -> Unit)? = null, + content: @Composable () -> Unit, +) { + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + contentPadding = PaddingValues(16.dp), + ) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = title, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + ) + trailingBadge?.invoke() + } + content() + } + } +} + +/** 底部悬浮发射胶囊操作栏:带 navigationBarsPadding 与柔和渐隐底衬。 */ +@Composable +private fun SendBar(state: DeliverUiState, onSend: () -> Unit, onDone: () -> Unit) { + val doneInteraction = remember { MutableInteractionSource() } + val backdropFade = Brush.verticalGradient( + colors = listOf( + Color.Transparent, + MaterialTheme.colorScheme.background.copy(alpha = 0.88f), + MaterialTheme.colorScheme.background, + ), + ) + + Box( + modifier = Modifier + .fillMaxWidth() + .background(backdropFade), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (state.sendBlock == SendBlock.NOT_INSTALLED) { + state.selectedTarget?.let { + BridgeGlassSurface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + shadowElevation = 4.dp, + ) { + Text( + text = stringResource(R.string.deliver_block_not_installed, it.name), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp), + ) + } + } + } + + Box( + modifier = Modifier.fillMaxWidth(), + contentAlignment = Alignment.Center, + ) { + BridgePrimaryCapsuleButton( + text = sendTitle(state), + onClick = onSend, + enabled = state.canSend && !state.busy, + height = 52.dp, + modifier = Modifier.fillMaxWidth(), + ) + if (state.busy) { + CircularProgressIndicator( + modifier = Modifier + .align(Alignment.CenterStart) + .padding(start = 22.dp) + .size(16.dp), + strokeWidth = 2.dp, + color = Color.White, + ) + } + } + + if (state.delivered) { + OutlinedButton( + onClick = onDone, + interactionSource = doneInteraction, + shape = CircleShape, + modifier = Modifier + .fillMaxWidth() + .height(44.dp) + .pressScale(doneInteraction), + ) { + Text( + text = stringResource(R.string.deliver_done), + style = MaterialTheme.typography.labelLarge, + ) + } + } + } + } +} + +@Composable +private fun sendTitle(state: DeliverUiState): String { + val target = state.selectedTarget + return when { + state.progress.isContinuation -> + stringResource(R.string.deliver_send_continue, state.progress.next, state.progress.total) + state.progress.complete -> stringResource(R.string.deliver_sent_all) + target != null && target.isWriter -> stringResource(R.string.deliver_save_to, target.name) + target != null -> stringResource(R.string.deliver_send_to, target.name) + else -> stringResource(R.string.deliver_send) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverIcons.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverIcons.kt new file mode 100644 index 00000000..08c2c669 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverIcons.kt @@ -0,0 +1,186 @@ +package com.xiangming.wechatbridge.ui.deliver + +import android.content.Context +import android.graphics.Bitmap +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.dp +import androidx.core.graphics.drawable.toBitmap +import com.xiangming.wechatbridge.R +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.util.concurrent.ConcurrentHashMap +import kotlin.math.abs + +/** 文件夹矢量图标(圆润线框质感,供文件夹目标与保存路径卡共用)。 */ +internal val FolderIcon: ImageVector by lazy { + ImageVector.Builder("Folder", 24.dp, 24.dp, 24f, 24f) + .addPath( + addPathNodes("M3,7 A2,2 0 0 1 5,5 H9.2 L11.2,7.2 H19 A2,2 0 0 1 21,9.2 V17 A2,2 0 0 1 19,19 H5 A2,2 0 0 1 3,17 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.9f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + .build() +} + +/** 「其他应用」干净矢量图标(系统外发分享语义)。 */ +internal val OtherAppIcon: ImageVector by lazy { + ImageVector.Builder("OtherApp", 24.dp, 24.dp, 24f, 24f) + .addPath( + addPathNodes("M12,3 V14 M8,7 L12,3 L16,7"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + .addPath( + addPathNodes("M5,12 V18 A2,2 0 0 0 7,20 H17 A2,2 0 0 0 19,18 V12"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + .build() +} + +/** + * 第一层:内置高清官方 PNG。没有内置 PNG 的目标返回 null,由第二层(系统真实图标)或第三层(首字徽章)兜底。 + */ +internal fun logoResource(logo: String?): Int? = when (logo) { + "logo_chatgpt" -> R.drawable.logo_chatgpt + "logo_claude" -> R.drawable.logo_claude + "logo_doubao" -> R.drawable.logo_doubao + "logo_qwen" -> R.drawable.logo_qwen + "logo_obsidian" -> R.drawable.logo_obsidian + "logo_workbuddy" -> R.drawable.logo_workbuddy + else -> null +} + +/** + * 内存图标缓存:避免滚动/重绘时重复向 PackageManager 解码 Drawable。 + * 用包装类区分「未查过」与「查过但不存在」。 + */ +internal object AppIconCache { + private class Entry(val bitmap: ImageBitmap?) + + private val cache = ConcurrentHashMap() + + fun peek(packageNames: List): ImageBitmap? { + for (pkg in packageNames) { + val entry = cache[pkg] ?: continue + if (entry.bitmap != null) return entry.bitmap + } + return null + } + + fun isResolved(packageNames: List): Boolean = + packageNames.isNotEmpty() && packageNames.all { cache.containsKey(it) } + + fun loadBlocking(context: Context, packageNames: List, sizePx: Int): ImageBitmap? { + val pm = context.applicationContext.packageManager + for (pkg in packageNames) { + cache[pkg]?.let { cached -> + if (cached.bitmap != null) return cached.bitmap + continue + } + val bitmap = runCatching { + val drawable = pm.getApplicationIcon(pkg) + drawable.toBitmap(width = sizePx, height = sizePx, config = Bitmap.Config.ARGB_8888) + .asImageBitmap() + }.getOrNull() + cache[pkg] = Entry(bitmap) + if (bitmap != null) return bitmap + } + return null + } +} + +/** + * 第二层:后台从 PackageManager 加载已安装应用的真实系统图标并内存缓存。 + */ +@Composable +internal fun rememberAppIcon( + packageNames: List, + enabled: Boolean, +): ImageBitmap? { + val context = LocalContext.current + val density = LocalDensity.current + val sizePx = remember(density) { with(density) { 44.dp.roundToPx().coerceAtLeast(96) } } + val key = remember(packageNames) { packageNames.joinToString("|") } + + var icon by remember(key, enabled) { + mutableStateOf(if (enabled) AppIconCache.peek(packageNames) else null) + } + + LaunchedEffect(key, enabled, sizePx) { + if (!enabled || packageNames.isEmpty()) { + icon = null + return@LaunchedEffect + } + if (icon != null || AppIconCache.isResolved(packageNames)) return@LaunchedEffect + icon = withContext(Dispatchers.IO) { + AppIconCache.loadBlocking(context, packageNames, sizePx) + } + } + + return icon +} + +/** 第三层兜底:克制的首字徽章字符(英文取首字母大写,中文取首字)。 */ +internal fun monogramChar(name: String): String { + val trimmed = name.trim() + if (trimmed.isEmpty()) return "?" + val first = trimmed.first() + return if (first in 'a'..'z') first.uppercase() else first.toString() +} + +internal data class MonogramStyle(val background: Color, val foreground: Color) + +private val LightMonogramPalette = listOf( + MonogramStyle(Color(0xFFEBF3FF), Color(0xFF2563EB)), + MonogramStyle(Color(0xFFECFDF3), Color(0xFF059669)), + MonogramStyle(Color(0xFFF3EEFF), Color(0xFF7C3AED)), + MonogramStyle(Color(0xFFFFF4E5), Color(0xFFD97706)), + MonogramStyle(Color(0xFFEEF2F6), Color(0xFF475569)), + MonogramStyle(Color(0xFFFCEEF5), Color(0xFFDB2777)), +) + +private val DarkMonogramPalette = listOf( + MonogramStyle(Color(0xFF1A2840), Color(0xFF93C5FD)), + MonogramStyle(Color(0xFF142F24), Color(0xFF6EE7B7)), + MonogramStyle(Color(0xFF271F3D), Color(0xFFC4B5FD)), + MonogramStyle(Color(0xFF332615), Color(0xFFFCD34D)), + MonogramStyle(Color(0xFF252A30), Color(0xFFCBD5E1)), + MonogramStyle(Color(0xFF351D2B), Color(0xFFF9A8D4)), +) + +/** 按目标 id 稳定映射低饱和度克制徽章配色。 */ +internal fun monogramStyle(id: String, isDark: Boolean): MonogramStyle { + val palette = if (isDark) DarkMonogramPalette else LightMonogramPalette + val index = when (id) { + "gemini" -> 0 + "yuanbao" -> 1 + "deepseek" -> 0 + "lark" -> 1 + "yuque" -> 1 + "minotes" -> 3 + else -> abs(id.hashCode()) % palette.size + } + return palette[index] +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverPreviews.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverPreviews.kt new file mode 100644 index 00000000..a60c2a8a --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverPreviews.kt @@ -0,0 +1,168 @@ +package com.xiangming.wechatbridge.ui.deliver + +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.tooling.preview.Preview +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.core.deliver.DeliveryFile +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.FormatChoice +import com.xiangming.wechatbridge.core.deliver.FormatReason +import com.xiangming.wechatbridge.core.deliver.Omitted +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.scene.SceneMatchSource +import com.xiangming.wechatbridge.deliver.DeliverUiState +import com.xiangming.wechatbridge.deliver.Installation +import com.xiangming.wechatbridge.deliver.PlanFailure +import com.xiangming.wechatbridge.deliver.Preview as DeliverPreview +import com.xiangming.wechatbridge.deliver.Progress +import com.xiangming.wechatbridge.deliver.ResourceDeliverLabels +import com.xiangming.wechatbridge.deliver.SceneOption +import com.xiangming.wechatbridge.deliver.TargetOption +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import java.io.File + +private fun file(name: String, mime: String) = DeliveryFile(File("/preview/$name"), mime) + +private val zip = file("微信聊天记录.zip", "application/zip") +private val txt = file("聊天记录.txt", "text/plain") +private fun jpg(n: Int) = file("IMG_%03d.jpg".format(n), "image/jpeg") + +@Composable +private fun previewTargets(): List { + val context = LocalContext.current + return remember { + val labels = ResourceDeliverLabels(context) + BuiltInTargets.all.map { + val installation = when { + it.kind == TargetKind.CHOOSER -> Installation.NOT_AN_APP + it.id in setOf("gemini", "deepseek", "minotes") -> Installation.NOT_INSTALLED + else -> Installation.INSTALLED + } + TargetOption(it, labels.targetName(it), installation) + } + } +} + +private val scenes = listOf(SceneOption("summary", "群聊总结"), SceneOption("todo", "提取待办")) + +private fun choice(format: DeliveryFormat, omitted: Omitted = Omitted(), vararg alternatives: DeliveryFormat) = + FormatChoice(format, FormatReason.DEFAULT, omitted, alternatives.toList()) + +@Composable +private fun PreviewPanel(state: (List) -> DeliverUiState) { + val targets = previewTargets() + WeChatBridgeTheme { + DeliverContent( + state = state(targets), + snackbarHostState = remember { SnackbarHostState() }, + onBack = {}, + onDone = {}, + onSelectTarget = {}, + onUnavailableTarget = {}, + onSelectScene = {}, + onEditPrompt = {}, + onChooseFormat = {}, + onSendOriginal = {}, + onSend = {}, + ) + } +} + +private fun base(targets: List, selected: String) = DeliverUiState( + loading = false, + batchCount = 1, + targets = targets, + selectedTargetId = selected, + scenes = scenes, + sceneId = "summary", + sceneSource = SceneMatchSource.LAST_USED, + prompt = "请总结这段聊天记录的要点,并列出待办。", +) + +@Preview(name = "单批 ZIP", showBackground = true, heightDp = 900) +@Composable +private fun SingleZipPreview() = PreviewPanel { targets -> + base(targets, "claude").copy( + formatChoice = choice(DeliveryFormat.ARCHIVE, alternatives = arrayOf(DeliveryFormat.TRANSCRIPT_AND_IMAGES, DeliveryFormat.TRANSCRIPT_ONLY)), + preview = DeliverPreview.Ready(DeliveryFormat.ARCHIVE, listOf(listOf(zip)), emptyList(), inlineText = false, inlineFellBackToFile = false), + progress = Progress(0, 1), + ) +} + +@Preview(name = "合并 TXT+图片", showBackground = true, heightDp = 900) +@Composable +private fun MergedPreview() = PreviewPanel { targets -> + base(targets, "chatgpt").copy( + batchCount = 2, + sceneId = null, + sceneSource = SceneMatchSource.NONE, + prompt = "", + formatChoice = choice(DeliveryFormat.TRANSCRIPT_AND_IMAGES, alternatives = arrayOf(DeliveryFormat.TRANSCRIPT_ONLY, DeliveryFormat.INLINE_TEXT)), + preview = DeliverPreview.Ready( + DeliveryFormat.TRANSCRIPT_AND_IMAGES, + listOf(listOf(txt) + (1..4).map(::jpg)), + emptyList(), + inlineText = false, + inlineFellBackToFile = false, + ), + progress = Progress(0, 1), + ) +} + +@Preview(name = "有未随附文件", showBackground = true, heightDp = 900) +@Composable +private fun OmittedPreview() = PreviewPanel { targets -> + base(targets, "doubao").copy( + formatChoice = choice( + DeliveryFormat.TRANSCRIPT_AND_IMAGES, + Omitted(videos = 1, files = 2), + DeliveryFormat.ARCHIVE, + DeliveryFormat.TRANSCRIPT_ONLY, + ), + preview = DeliverPreview.Ready( + DeliveryFormat.TRANSCRIPT_AND_IMAGES, + listOf(listOf(txt, jpg(1), jpg(2))), + listOf("视频_20260101.mp4", "报告.pdf", "预算.xlsx"), + inlineText = false, + inlineFellBackToFile = false, + ), + progress = Progress(0, 1), + ) +} + +@Preview(name = "分组续发", showBackground = true, heightDp = 1000) +@Composable +private fun ContinuationPreview() = PreviewPanel { targets -> + base(targets, "qwen").copy( + delivered = true, + formatChoice = choice(DeliveryFormat.TRANSCRIPT_AND_IMAGES, alternatives = arrayOf(DeliveryFormat.TRANSCRIPT_ONLY)), + preview = DeliverPreview.Ready( + DeliveryFormat.TRANSCRIPT_AND_IMAGES, + listOf(listOf(txt) + (1..9).map(::jpg), (10..14).map(::jpg), (15..16).map(::jpg)), + emptyList(), + inlineText = false, + inlineFellBackToFile = false, + ), + progress = Progress(1, 3), + ) +} + +@Preview(name = "需要文件夹", showBackground = true, heightDp = 700) +@Composable +private fun NeedsFolderPreview() = PreviewPanel { targets -> + base(targets, "obsidian").copy( + formatChoice = choice(DeliveryFormat.KNOWLEDGE_NOTE), + preview = DeliverPreview.NeedsFolder(TargetKind.VAULT), + ) +} + +@Preview(name = "准备失败", showBackground = true, heightDp = 700) +@Composable +private fun FailedPreview() = PreviewPanel { targets -> + base(targets, "yuque").copy( + preview = DeliverPreview.Failed(PlanFailure.NO_TRANSCRIPT, canSendOriginal = true), + ) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverScreen.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverScreen.kt new file mode 100644 index 00000000..4660eb83 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverScreen.kt @@ -0,0 +1,119 @@ +package com.xiangming.wechatbridge.ui.deliver + +import android.content.Context +import android.content.ContextWrapper +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.platform.LocalContext +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.deliver.DeliverViewModel +import com.xiangming.wechatbridge.deliver.SendFeedback +import kotlinx.coroutines.launch +import com.xiangming.wechatbridge.LocalInitialTargetId + +/** 投递面板。参数签名由 AppNav 固定。 */ +@Composable +fun DeliverScreen( + batchIds: List, + onBack: () -> Unit, + onDone: () -> Unit, +) { + val context = LocalContext.current + val container = (context.applicationContext as App).container + // 「投给上次目标」从收据卡进来时预选那个目标(AppNav 经 LocalInitialTargetId 提供)。 + val initialTargetId = LocalInitialTargetId.current + val viewModel = viewModel { + // 投的正好是某个收集的全部批次时,带上它的 id:投完标记为已投递,常驻通知随之消失。 + val ids = batchIds.mapNotNull { runCatching { java.util.UUID.fromString(it) }.getOrNull() } + val collectionId = ids.firstOrNull() + ?.let { container.relayStore.collectionContaining(it) } + ?.takeIf { it.batchIDs.toSet() == ids.toSet() } + ?.id + DeliverViewModel.create(container, batchIds, collectionId = collectionId, initialTargetId = initialTargetId) + } + val state by viewModel.state.collectAsStateWithLifecycle() + val snackbarHostState = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val resources = context.resources + // 发送要 Activity 的上下文:不带 NEW_TASK,对方在同一任务栈里打开。 + val activity = remember(context) { context.findActivity() } + + // 一次性提示:显示完(或被下一次操作顶掉)后清掉,不会重复弹。 + val feedback = state.feedback + val targetName = state.selectedTarget?.name.orEmpty() + LaunchedEffect(feedback) { + if (feedback == null) return@LaunchedEffect + val message = feedbackMessage(resources, feedback, targetName) + val long = feedback !is SendFeedback.Sent || message.contains('\n') + snackbarHostState.showSnackbar(message, duration = if (long) SnackbarDuration.Long else SnackbarDuration.Short) + viewModel.consumeFeedback() + } + + // Obsidian / 文件夹写入的结果,同样一次性提示。 + val writeFeedback = state.writeFeedback + LaunchedEffect(writeFeedback) { + if (writeFeedback == null) return@LaunchedEffect + snackbarHostState.showSnackbar(writeFeedbackMessage(resources, writeFeedback), duration = SnackbarDuration.Long) + viewModel.consumeFeedback() + } + + // 选 Obsidian 库 / 文件夹:ViewModel 发出请求,这里启动系统目录选择器,结果交回去。 + val folderPicker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> + viewModel.onFolderPicked(uri) + } + val folderRequest = state.folderRequest + LaunchedEffect(folderRequest) { + if (folderRequest == null) return@LaunchedEffect + viewModel.consumeFolderRequest() + runCatching { folderPicker.launch(null) }.onFailure { viewModel.onFolderPicked(null) } + } + + val leave = { + viewModel.close() + onBack() + } + BackHandler(onBack = leave) + + DeliverContent( + state = state, + snackbarHostState = snackbarHostState, + onBack = leave, + onDone = { + viewModel.close() + onDone() + }, + onSelectTarget = { viewModel.selectTarget(it.id) }, + onUnavailableTarget = { option -> + scope.launch { + snackbarHostState.currentSnackbarData?.dismiss() + snackbarHostState.showSnackbar(resources.getString(R.string.deliver_target_not_installed, option.name)) + } + }, + onSelectScene = viewModel::selectScene, + onEditPrompt = viewModel::editPrompt, + onChooseFormat = viewModel::chooseFormat, + onSendOriginal = viewModel::sendOriginal, + onSend = { viewModel.send(activity ?: context) }, + onPickFolder = viewModel::requestFolder, + onChooseGroup = viewModel::chooseGroup, + onCreateGroup = viewModel::createGroup, + onBindScene = viewModel::bindSceneToGroup, + ) +} + +private tailrec fun Context.findActivity(): android.app.Activity? = when (this) { + is android.app.Activity -> this + is ContextWrapper -> baseContext.findActivity() + else -> null +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverTexts.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverTexts.kt new file mode 100644 index 00000000..5aacaa32 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/DeliverTexts.kt @@ -0,0 +1,70 @@ +package com.xiangming.wechatbridge.ui.deliver + +import android.content.res.Resources +import androidx.annotation.StringRes +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.PickHint +import com.xiangming.wechatbridge.deliver.PromptClipboard +import com.xiangming.wechatbridge.deliver.RejectReason +import com.xiangming.wechatbridge.deliver.SendFeedback + +@StringRes +internal fun formatNameRes(format: DeliveryFormat): Int = when (format) { + DeliveryFormat.ARCHIVE -> R.string.format_archive + DeliveryFormat.TRANSCRIPT_AND_IMAGES -> R.string.format_transcriptAndImages + DeliveryFormat.TRANSCRIPT_ONLY -> R.string.format_transcriptOnly + DeliveryFormat.INLINE_TEXT -> R.string.format_inlineText + DeliveryFormat.KNOWLEDGE_NOTE -> R.string.format_knowledgeNote + DeliveryFormat.FOLDER -> R.string.format_folder +} + +@Composable +internal fun formatName(format: DeliveryFormat): String = stringResource(formatNameRes(format)) + +/** + * 一次发送结果的提示文字(Snackbar)。[SendFeedback.Sent] 里提示词已复制到剪贴板时, + * 一定要告诉用户可以去对方输入框粘贴。 + */ +internal fun feedbackMessage(resources: Resources, feedback: SendFeedback, targetName: String): String = when (feedback) { + is SendFeedback.Sent -> { + val lines = buildList { + if (feedback.total > 1) { + add( + if (feedback.allSent) { + resources.getString(R.string.deliver_feedback_all_sent, feedback.total) + } else { + resources.getString(R.string.deliver_feedback_group_sent, feedback.group, feedback.total) + }, + ) + } + if (feedback.clipboard is PromptClipboard.Result.Copied) { + add(resources.getString(R.string.deliver_feedback_prompt_copied)) + } else if (feedback.hint.pastePrompt) { + add(resources.getString(R.string.deliver_feedback_paste_manually)) + } + when (feedback.hint.pick) { + PickHint.NAMED_APP -> add(resources.getString(R.string.deliver_feedback_pick_named, targetName)) + PickHint.ANY_APP -> add(resources.getString(R.string.deliver_feedback_pick_any)) + PickHint.NONE -> Unit + } + if (feedback.textDropped) add(resources.getString(R.string.deliver_feedback_text_dropped)) + } + lines.ifEmpty { listOf(resources.getString(R.string.deliver_feedback_sent, targetName)) }.joinToString("\n") + } + is SendFeedback.NotInstalled -> resources.getString(R.string.deliver_feedback_not_installed, targetName) + is SendFeedback.Rejected -> resources.getString( + when (feedback.reason) { + RejectReason.EMPTY -> R.string.deliver_feedback_rejected_empty + RejectReason.OUTSIDE_DELIVERIES -> R.string.deliver_feedback_rejected_outside + RejectReason.MISSING_FILE -> R.string.deliver_feedback_rejected_missing + RejectReason.TEXT_TOO_LARGE -> R.string.deliver_feedback_rejected_too_large + }, + ) + is SendFeedback.LaunchFailed -> + feedback.message?.let { resources.getString(R.string.deliver_feedback_launch_failed, it) } + ?: resources.getString(R.string.deliver_feedback_launch_failed_unknown) + SendFeedback.CollectionUnavailable -> resources.getString(R.string.deliver_feedback_collection_unavailable) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/FolderAndGroup.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/FolderAndGroup.kt new file mode 100644 index 00000000..a608cbea --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/FolderAndGroup.kt @@ -0,0 +1,307 @@ +package com.xiangming.wechatbridge.ui.deliver + +import android.content.res.Resources +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.scene.SceneMatchSource +import com.xiangming.wechatbridge.deliver.DeliverUiState +import com.xiangming.wechatbridge.deliver.FolderState +import com.xiangming.wechatbridge.deliver.WriteFailure +import com.xiangming.wechatbridge.deliver.WriteFeedback +import com.xiangming.wechatbridge.saf.TreeStatus +import com.xiangming.wechatbridge.ui.theme.KindNoteColor +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale + +/** Obsidian / 文件夹:柔和保存路径预览卡,没选或失效时引导「选择 / 重新选择」。 */ +@Composable +internal fun FolderRow(folder: FolderState?, onPickFolder: () -> Unit) { + if (folder == null) return + val appColors = LocalAppColors.current + val interactionSource = remember { MutableInteractionSource() } + + val iconBg = when (folder.status) { + TreeStatus.GRANTED -> appColors.surfaceTint + TreeStatus.NOT_CHOSEN -> KindNoteColor.copy(alpha = 0.12f) + else -> MaterialTheme.colorScheme.error.copy(alpha = 0.12f) + } + val iconTint = when (folder.status) { + TreeStatus.GRANTED -> MaterialTheme.colorScheme.primary + TreeStatus.NOT_CHOSEN -> KindNoteColor + else -> MaterialTheme.colorScheme.error + } + + Surface( + shape = RoundedCornerShape(14.dp), + color = appColors.surfaceSub, + modifier = Modifier.fillMaxWidth(), + ) { + Column( + modifier = Modifier.padding(14.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(38.dp) + .clip(RoundedCornerShape(10.dp)) + .background(iconBg), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = FolderIcon, + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = iconTint, + ) + } + Spacer(Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + text = stringResource(R.string.deliver_folder_save_path), + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + when (folder.status) { + TreeStatus.GRANTED -> Text( + text = stringResource( + R.string.deliver_folder_granted, + folder.folderName.orEmpty(), + folder.subfolder, + ), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + TreeStatus.NOT_CHOSEN -> Text( + text = stringResource( + if (folder.kind == TargetKind.VAULT) R.string.deliver_folder_not_chosen_vault + else R.string.deliver_folder_not_chosen_folder, + folder.subfolder, + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + else -> Text( + text = stringResource(R.string.deliver_folder_lost), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + } + if (folder.status == TreeStatus.GRANTED) { + Spacer(Modifier.width(8.dp)) + TextButton( + onClick = onPickFolder, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 4.dp), + ) { + Text( + text = stringResource(R.string.deliver_folder_rechoose), + style = MaterialTheme.typography.labelMedium, + ) + } + } + } + + if (folder.status != TreeStatus.GRANTED) { + OutlinedButton( + onClick = onPickFolder, + interactionSource = interactionSource, + shape = RoundedCornerShape(11.dp), + modifier = Modifier + .fillMaxWidth() + .height(40.dp) + .pressScale(interactionSource), + ) { + Text( + text = stringResource( + if (folder.status == TreeStatus.NOT_CHOSEN) R.string.deliver_folder_choose + else R.string.deliver_folder_rechoose, + ), + style = MaterialTheme.typography.labelLarge, + ) + } + } + } + } +} + +/** 群识别条:紧贴场景胶囊上方,认出的群名 + 绑定快捷入口;认不出时给紧凑「选择群 / 新建群」。 */ +@Composable +internal fun GroupRow( + state: DeliverUiState, + onChooseGroup: (String) -> Unit, + onCreateGroup: (String) -> Unit, + onBindScene: () -> Unit, +) { + val appColors = LocalAppColors.current + val group = state.group + var menuOpen by remember { mutableStateOf(false) } + var creating by rememberSaveable { mutableStateOf(false) } + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = if (group.needsChoice || group.name == null) { + stringResource(R.string.deliver_group_unknown) + } else { + stringResource(R.string.deliver_group_label, group.name) + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Spacer(Modifier.width(8.dp)) + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (group.needsChoice) { + if (group.known.isNotEmpty()) { + Box { + CompactActionLink( + text = stringResource(R.string.deliver_group_choose), + onClick = { menuOpen = true }, + ) + DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { + group.known.forEach { option -> + DropdownMenuItem( + text = { Text(option.displayName) }, + onClick = { + menuOpen = false + onChooseGroup(option.displayName) + }, + ) + } + } + } + } + CompactActionLink( + text = stringResource(R.string.deliver_group_create), + onClick = { creating = true }, + ) + } else if (group.name != null && state.sceneId != null) { + if (state.sceneSource == SceneMatchSource.BINDING) { + Text( + text = stringResource(R.string.deliver_group_bound), + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + } else { + CompactActionLink( + text = stringResource(R.string.deliver_group_bind), + onClick = onBindScene, + ) + } + } + } + } + + if (creating) { + var name by rememberSaveable { mutableStateOf("") } + AlertDialog( + onDismissRequest = { creating = false }, + title = { Text(stringResource(R.string.deliver_group_create_title)) }, + text = { + OutlinedTextField( + value = name, + onValueChange = { name = it }, + singleLine = true, + shape = RoundedCornerShape(12.dp), + label = { Text(stringResource(R.string.deliver_group_name_hint)) }, + ) + }, + confirmButton = { + TextButton( + enabled = name.isNotBlank(), + onClick = { + creating = false + onCreateGroup(name.trim()) + }, + ) { Text(stringResource(R.string.action_ok)) } + }, + dismissButton = { + TextButton(onClick = { creating = false }) { Text(stringResource(R.string.action_cancel)) } + }, + ) + } +} + +@Composable +private fun CompactActionLink(text: String, onClick: () -> Unit) { + Text( + text = text, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Medium, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable(role = Role.Button, onClick = onClick) + .padding(horizontal = 4.dp, vertical = 2.dp), + ) +} + +internal fun writeFeedbackMessage(resources: Resources, feedback: WriteFeedback): String = when (feedback) { + is WriteFeedback.Saved -> resources.getString( + R.string.deliver_write_saved, + feedback.notes.size, + feedback.notes.joinToString("、"), + ) + is WriteFeedback.Failed -> when (feedback.reason) { + WriteFailure.FOLDER_LOST -> resources.getString(R.string.deliver_write_failed_lost) + WriteFailure.NOT_GRANTED -> resources.getString(R.string.deliver_write_failed_not_granted) + WriteFailure.UNREADABLE -> resources.getString(R.string.deliver_write_failed_unreadable) + WriteFailure.CLEANUP_FAILED -> resources.getString(R.string.deliver_write_failed_cleanup) + WriteFailure.IO -> feedback.message?.let { resources.getString(R.string.deliver_write_failed_io, it) } + ?: resources.getString(R.string.deliver_write_failed_io_unknown) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/PreviewSection.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/PreviewSection.kt new file mode 100644 index 00000000..28431ad0 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/PreviewSection.kt @@ -0,0 +1,476 @@ +package com.xiangming.wechatbridge.ui.deliver + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.SizeTransform +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.deliver.DeliveryFile +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.util.ByteFormat +import com.xiangming.wechatbridge.deliver.DeliverUiState +import com.xiangming.wechatbridge.deliver.PlanFailure +import com.xiangming.wechatbridge.deliver.Preview +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.ErrorRed +import com.xiangming.wechatbridge.ui.theme.KindChatColor +import com.xiangming.wechatbridge.ui.theme.KindFileColor +import com.xiangming.wechatbridge.ui.theme.KindLinkColor +import com.xiangming.wechatbridge.ui.theme.KindNoteColor +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale + +/** 每组最多列出的文件数,更多的折叠成一行(预览放在可滚动页面里,不用 Lazy 列表)。 */ +private const val MAX_FILES_SHOWN = 8 +private const val MAX_OMITTED_SHOWN = 6 + +private enum class PreviewMode { IDLE, PLANNING, READY, FAILED, FOLDER } + +private fun Preview.mode(): PreviewMode = when (this) { + Preview.Idle -> PreviewMode.IDLE + Preview.Planning -> PreviewMode.PLANNING + is Preview.Ready -> PreviewMode.READY + is Preview.Failed -> PreviewMode.FAILED + is Preview.NeedsFolder -> PreviewMode.FOLDER +} + +/** + * 将投递的内容预览: + * - 紧凑分段格式切换; + * - 带文件类型彩色圆角徽章的文件列表; + * - 选中 Obsidian / 文件夹时通过 AnimatedContent 柔和切换为保存路径预览。 + */ +@Composable +internal fun PreviewSection( + state: DeliverUiState, + onChooseFormat: (DeliveryFormat?) -> Unit, + onSendOriginal: () -> Unit, + modifier: Modifier = Modifier, + onPickFolder: () -> Unit = {}, +) { + Column( + modifier = modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + // 紧凑分段格式切换放在上方,方便一眼切换输出形态 + SegmentedFormatSwitcher(state = state, onChooseFormat = onChooseFormat) + + AnimatedContent( + targetState = state.preview.mode(), + transitionSpec = { + (fadeIn(tween(200)) togetherWith fadeOut(tween(140))) + .using(SizeTransform(clip = false) { _, _ -> AppMotion.contentSizeSpring() }) + }, + label = "previewModeTransition", + ) { mode -> + when (mode) { + PreviewMode.IDLE -> MutedText(stringResource(R.string.deliver_preview_idle)) + PreviewMode.PLANNING -> Row( + modifier = Modifier.padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + CircularProgressIndicator( + modifier = Modifier.size(16.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.primary, + ) + Spacer(Modifier.width(10.dp)) + MutedText(stringResource(R.string.deliver_preview_planning)) + } + PreviewMode.READY -> { + val ready = state.preview as? Preview.Ready + if (ready != null) { + ReadyPreview(state = state, preview = ready, onSendOriginal = onSendOriginal) + } + } + PreviewMode.FAILED -> { + val failed = state.preview as? Preview.Failed + if (failed != null) { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + text = stringResource(failureTextRes(failed.reason)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + if (failed.canSendOriginal) { + OutlinedButton( + onClick = onSendOriginal, + shape = RoundedCornerShape(11.dp), + ) { + Text(stringResource(R.string.deliver_send_original_files)) + } + } + } + } + } + PreviewMode.FOLDER -> FolderRow(folder = state.folder, onPickFolder = onPickFolder) + } + } + } +} + +private fun failureTextRes(reason: PlanFailure): Int = when (reason) { + PlanFailure.NO_TRANSCRIPT -> R.string.deliver_failed_no_transcript + PlanFailure.NO_FORMAT -> R.string.deliver_failed_no_format + PlanFailure.IO -> R.string.deliver_failed_io +} + +@Composable +private fun ReadyPreview( + state: DeliverUiState, + preview: Preview.Ready, + onSendOriginal: () -> Unit, +) { + val appColors = LocalAppColors.current + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + if (state.alternativeFormats.isEmpty() && state.formatOverride == null) { + Text( + text = stringResource(R.string.deliver_preview_format, formatName(preview.format)), + style = MaterialTheme.typography.labelMedium, + color = appColors.onSurfaceMuted, + ) + } + if (preview.inlineText) MutedText(stringResource(R.string.deliver_preview_inline_text)) + if (preview.inlineFellBackToFile) MutedText(stringResource(R.string.deliver_preview_inline_fallback)) + + val groupCount = preview.groups.size + if (groupCount > 1) MutedText(stringResource(R.string.deliver_preview_groups, groupCount)) + + preview.groups.forEachIndexed { index, files -> + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + if (groupCount > 1) { + GroupHeader(index + 1, groupCount, files.size, sent = index < state.progress.sent) + } + if (files.isNotEmpty()) { + Surface( + shape = RoundedCornerShape(14.dp), + color = appColors.surfaceSub.copy(alpha = 0.65f), + modifier = Modifier.fillMaxWidth(), + ) { + Column(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) { + val visibleFiles = files.take(MAX_FILES_SHOWN) + visibleFiles.forEachIndexed { fileIdx, file -> + FileRow(file) + if (fileIdx < visibleFiles.lastIndex) { + HorizontalDivider( + thickness = 0.5.dp, + color = appColors.subtleDivider, + ) + } + } + if (files.size > MAX_FILES_SHOWN) { + HorizontalDivider( + thickness = 0.5.dp, + color = appColors.subtleDivider, + ) + Text( + text = stringResource(R.string.deliver_preview_more_files, files.size - MAX_FILES_SHOWN), + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + modifier = Modifier.padding(vertical = 8.dp), + ) + } + } + } + } + } + } + + if (preview.omitted.isNotEmpty()) { + OmittedBox( + omitted = preview.omitted, + showSendOriginal = state.offersOriginal, + onSendOriginal = onSendOriginal, + ) + } + } +} + +@Composable +private fun GroupHeader(number: Int, total: Int, count: Int, sent: Boolean) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = stringResource(R.string.deliver_preview_group_header, number, total, count), + style = MaterialTheme.typography.labelLarge, + color = if (sent) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface, + ) + if (sent) { + Spacer(Modifier.width(6.dp)) + Icon( + imageVector = Icons.Filled.CheckCircle, + contentDescription = stringResource(R.string.a11y_deliver_group_sent), + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.primary, + ) + } + } +} + +@Composable +private fun FileRow(file: DeliveryFile) { + val appColors = LocalAppColors.current + val badge = remember(file.name, file.mimeType) { fileTypeBadge(file) } + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 9.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .width(38.dp) + .height(22.dp) + .clip(RoundedCornerShape(6.dp)) + .background(badge.color.copy(alpha = if (appColors.isDark) 0.22f else 0.12f)), + contentAlignment = Alignment.Center, + ) { + Text( + text = badge.label, + style = MaterialTheme.typography.labelSmall.copy( + fontSize = 10.sp, + lineHeight = 12.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 0.2.sp, + ), + color = badge.color, + maxLines = 1, + ) + } + Spacer(Modifier.width(10.dp)) + Text( + text = file.name, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + ) + // 预览里的文件可能还不在磁盘上;不在就不显示大小。 + val bytes = file.file.takeIf { it.isFile }?.length() + if (bytes != null) { + Spacer(Modifier.width(10.dp)) + Text( + text = ByteFormat.string(bytes), + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + } + } +} + +private data class FileBadge(val label: String, val color: Color) + +private fun fileTypeBadge(file: DeliveryFile): FileBadge { + val ext = file.name.substringAfterLast('.', "").lowercase() + val mime = file.mimeType.lowercase() + return when { + ext == "zip" || mime.contains("zip") -> FileBadge("ZIP", KindFileColor) + ext == "md" || mime.contains("markdown") -> FileBadge("MD", KindChatColor) + ext == "txt" || mime.startsWith("text/") -> FileBadge("TXT", KindChatColor) + mime.startsWith("image/") || ext in setOf("jpg", "jpeg", "png", "webp", "gif", "heic") -> + FileBadge("IMG", KindLinkColor) + ext == "pdf" || mime.contains("pdf") -> FileBadge("PDF", KindNoteColor) + mime.startsWith("video/") || ext in setOf("mp4", "mov", "mkv", "avi") -> + FileBadge("VID", ErrorRed) + ext in setOf("doc", "docx", "xls", "xlsx", "ppt", "pptx") -> + FileBadge(ext.take(3).uppercase(), KindNoteColor) + ext.isNotEmpty() && ext.length <= 4 -> FileBadge(ext.uppercase(), KindFileColor) + else -> FileBadge("FILE", KindLinkColor) + } +} + +/** 「未随附」清单;有改发原始 ZIP 的路时给按钮。 */ +@Composable +private fun OmittedBox( + omitted: List, + showSendOriginal: Boolean, + onSendOriginal: () -> Unit, +) { + val appColors = LocalAppColors.current + Surface( + shape = RoundedCornerShape(12.dp), + color = appColors.surfaceSub, + modifier = Modifier.fillMaxWidth(), + ) { + Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + text = stringResource(R.string.deliver_preview_omitted_title, omitted.size), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurface, + ) + omitted.take(MAX_OMITTED_SHOWN).forEach { + Text( + text = it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + ) + } + if (omitted.size > MAX_OMITTED_SHOWN) { + MutedText(stringResource(R.string.deliver_preview_omitted_more, omitted.size - MAX_OMITTED_SHOWN)) + } + if (showSendOriginal) { + TextButton( + onClick = onSendOriginal, + contentPadding = PaddingValues(horizontal = 4.dp, vertical = 2.dp), + ) { + Text(stringResource(R.string.deliver_send_original_zip)) + } + } + } + } +} + +/** 紧凑分段格式切换;已经开始分组发送后不可再换。 */ +@Composable +private fun SegmentedFormatSwitcher( + state: DeliverUiState, + onChooseFormat: (DeliveryFormat?) -> Unit, +) { + val appColors = LocalAppColors.current + val preview = state.preview + if (preview !is Preview.Ready && preview != Preview.Planning) return + val current = state.format ?: return + val alternatives = state.alternativeFormats + if (alternatives.isEmpty() && state.formatOverride == null) return + val enabled = !state.progress.started && !state.busy && preview is Preview.Ready + + val formats = remember(current, alternatives) { + (listOf(current) + alternatives).distinct() + } + + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = stringResource(R.string.deliver_format_switch), + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + if (state.formatOverride != null && enabled) { + Text( + text = stringResource(R.string.deliver_format_reset), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Medium, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable(role = Role.Button) { onChooseFormat(null) } + .padding(horizontal = 4.dp, vertical = 2.dp), + ) + } + } + + Surface( + shape = RoundedCornerShape(12.dp), + color = appColors.surfaceSub, + modifier = Modifier + .fillMaxWidth() + .alpha(if (enabled) 1f else 0.55f), + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding(3.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + formats.forEach { format -> + val selected = format == current + val interactionSource = remember { MutableInteractionSource() } + val bg by animateColorAsState( + targetValue = if (selected) MaterialTheme.colorScheme.surface else Color.Transparent, + animationSpec = tween(160), + label = "segmentBg", + ) + val textColor by animateColorAsState( + targetValue = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + animationSpec = tween(160), + label = "segmentText", + ) + Surface( + shape = RoundedCornerShape(9.dp), + color = bg, + shadowElevation = if (selected && !appColors.isDark) 0.8.dp else 0.dp, + modifier = Modifier + .pressScale(interactionSource, targetScale = 0.96f) + .clip(RoundedCornerShape(9.dp)) + .clickable( + enabled = enabled && !selected, + interactionSource = interactionSource, + indication = null, + role = Role.Tab, + onClick = { onChooseFormat(format) }, + ), + ) { + Text( + text = formatName(format), + style = MaterialTheme.typography.labelMedium, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, + color = textColor, + maxLines = 1, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp), + ) + } + } + } + } + } +} + +@Composable +private fun MutedText(text: String) { + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/SceneSection.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/SceneSection.kt new file mode 100644 index 00000000..e557d428 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/SceneSection.kt @@ -0,0 +1,262 @@ +package com.xiangming.wechatbridge.ui.deliver + +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.scene.SceneMatchSource +import com.xiangming.wechatbridge.deliver.DeliverUiState +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale + +/** 场景与提示词区块:横向快捷场景胶囊 + 单行当前场景摘要,点击平滑展开/收起 Prompt 编辑框。 */ +@Composable +internal fun SceneSection( + state: DeliverUiState, + onSelectScene: (String?) -> Unit, + onEditPrompt: (String) -> Unit, + modifier: Modifier = Modifier, +) { + val appColors = LocalAppColors.current + val initialSceneId = remember(state.loading) { state.sceneId } + val showAutoMatchSource = state.sceneId != null && state.sceneId == initialSceneId + val nonBindingSourceText = if (showAutoMatchSource && state.sceneSource != SceneMatchSource.BINDING) { + sceneSourceText(state.sceneSource) + } else { + null + } + var promptExpanded by rememberSaveable(state.sceneId) { mutableStateOf(false) } + + Column( + modifier = modifier + .fillMaxWidth() + .animateContentSize(AppMotion.contentSizeSpring()), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + // 横向快捷场景胶囊 + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + SceneCapsule( + label = stringResource(R.string.deliver_scene_none), + selected = state.sceneId == null, + onClick = { onSelectScene(null) }, + ) + state.scenes.forEach { scene -> + SceneCapsule( + label = scene.name, + selected = state.sceneId == scene.id, + onClick = { onSelectScene(scene.id) }, + ) + } + } + + if (nonBindingSourceText != null) { + Text( + text = nonBindingSourceText, + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + } + + // 单行当前场景摘要 + 可展开 Prompt 编辑框 + if (state.sceneId != null) { + val chevronRotation by animateFloatAsState( + targetValue = if (promptExpanded) 90f else 0f, + animationSpec = AppMotion.snappySpring(), + label = "promptChevron", + ) + val summaryText = state.prompt + .lineSequence() + .map { it.trim() } + .firstOrNull { it.isNotEmpty() } + ?: stringResource(R.string.deliver_prompt_empty_hint) + + Column( + modifier = Modifier + .fillMaxWidth() + .animateContentSize(AppMotion.contentSizeSpring()), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Surface( + shape = RoundedCornerShape(12.dp), + color = appColors.surfaceSub, + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable(role = Role.Button) { promptExpanded = !promptExpanded }, + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + imageVector = AppIcons.FillInput, + contentDescription = null, + modifier = Modifier.size(15.dp), + tint = MaterialTheme.colorScheme.primary, + ) + Spacer(Modifier.width(8.dp)) + Text( + text = summaryText, + style = MaterialTheme.typography.bodySmall, + color = if (state.prompt.isBlank()) { + appColors.onSurfaceMuted + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Spacer(Modifier.width(8.dp)) + Text( + text = stringResource( + if (promptExpanded) R.string.deliver_prompt_collapse else R.string.deliver_prompt_edit, + ), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Medium, + ) + Spacer(Modifier.width(2.dp)) + Icon( + imageVector = AppIcons.ChevronRight, + contentDescription = null, + modifier = Modifier + .size(14.dp) + .rotate(chevronRotation), + tint = MaterialTheme.colorScheme.primary, + ) + } + } + + if (promptExpanded) { + OutlinedTextField( + value = state.prompt, + onValueChange = onEditPrompt, + modifier = Modifier.fillMaxWidth(), + label = { Text(stringResource(R.string.deliver_prompt_label)) }, + textStyle = MaterialTheme.typography.bodySmall, + shape = RoundedCornerShape(12.dp), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = MaterialTheme.colorScheme.primary, + unfocusedBorderColor = MaterialTheme.colorScheme.outlineVariant, + focusedContainerColor = MaterialTheme.colorScheme.surface, + unfocusedContainerColor = MaterialTheme.colorScheme.surface, + ), + minLines = 3, + maxLines = 8, + ) + Text( + text = stringResource(R.string.deliver_prompt_note), + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + } + } + } + } +} + +@Composable +private fun SceneCapsule( + label: String, + selected: Boolean, + onClick: () -> Unit, +) { + val appColors = LocalAppColors.current + val interactionSource = remember { MutableInteractionSource() } + val bg by animateColorAsState( + targetValue = if (selected) appColors.surfaceTint else appColors.surfaceSub, + animationSpec = tween(160), + label = "sceneCapsuleBg", + ) + val borderColor by animateColorAsState( + targetValue = if (selected) MaterialTheme.colorScheme.primary else Color.Transparent, + animationSpec = tween(160), + label = "sceneCapsuleBorder", + ) + val textColor by animateColorAsState( + targetValue = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + animationSpec = tween(160), + label = "sceneCapsuleText", + ) + + Surface( + shape = RoundedCornerShape(999.dp), + color = bg, + border = BorderStroke(1.dp, borderColor), + modifier = Modifier + .pressScale(interactionSource, targetScale = 0.96f) + .clip(RoundedCornerShape(999.dp)) + .clickable( + interactionSource = interactionSource, + indication = null, + role = Role.RadioButton, + onClick = onClick, + ), + ) { + Text( + text = label, + style = MaterialTheme.typography.labelMedium, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + color = textColor, + maxLines = 1, + modifier = Modifier.padding(horizontal = 13.dp, vertical = 7.dp), + ) + } +} + +@Composable +private fun sceneSourceText(source: SceneMatchSource): String? = when (source) { + SceneMatchSource.BINDING -> stringResource(R.string.deliver_scene_source_binding) + SceneMatchSource.KEYWORD -> stringResource(R.string.deliver_scene_source_keyword) + SceneMatchSource.FINGERPRINT -> stringResource(R.string.deliver_scene_source_fingerprint) + SceneMatchSource.LAST_USED -> stringResource(R.string.deliver_scene_source_last_used) + SceneMatchSource.DEFAULT_SCENE -> stringResource(R.string.deliver_scene_source_default) + SceneMatchSource.NONE -> null +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/TargetGrid.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/TargetGrid.kt new file mode 100644 index 00000000..fc09ac3b --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/deliver/TargetGrid.kt @@ -0,0 +1,343 @@ +package com.xiangming.wechatbridge.ui.deliver + +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.graphics.ColorMatrix +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.deliver.TargetOption +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.KindNoteColor +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale + +private const val GRID_COLUMNS = 4 +private val IconSize = 44.dp +private val IconShape = RoundedCornerShape(12.dp) +private val RingShape = RoundedCornerShape(15.dp) +private val TileShape = RoundedCornerShape(14.dp) + +/** + * 4 列目标宫格。顺序完全取自 [targets](面板打开时定下的顺序),发送后不会重排。 + * 未安装的目标轻度置灰;点它不会选中,只回调 [onUnavailable] 让外面给提示。 + */ +@Composable +internal fun TargetGrid( + targets: List, + selectedId: String?, + onSelect: (TargetOption) -> Unit, + onUnavailable: (TargetOption) -> Unit, + modifier: Modifier = Modifier, +) { + val haptics = LocalHapticFeedback.current + Column( + modifier = modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + targets.chunked(GRID_COLUMNS).forEach { row -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + row.forEach { option -> + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.TopCenter, + ) { + TargetTile( + option = option, + selected = option.id == selectedId, + onClick = { + if (option.isInstalled) { + if (option.id != selectedId) { + haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove) + } + onSelect(option) + } else { + onUnavailable(option) + } + }, + ) + } + } + repeat(GRID_COLUMNS - row.size) { Spacer(Modifier.weight(1f)) } + } + } + } +} + +@Composable +internal fun TargetTile( + option: TargetOption, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val appColors = LocalAppColors.current + val installed = option.isInstalled + val selectedLabel = stringResource(R.string.deliver_target_selected) + val notInstalledLabel = stringResource(R.string.deliver_target_not_installed_badge) + val interactionSource = remember { MutableInteractionSource() } + + val tileBackground by animateColorAsState( + targetValue = if (selected) appColors.surfaceTint else Color.Transparent, + animationSpec = tween(180), + label = "tileBackground", + ) + val ringColor by animateColorAsState( + targetValue = if (selected) MaterialTheme.colorScheme.primary else Color.Transparent, + animationSpec = tween(180), + label = "ringColor", + ) + val iconScale by animateFloatAsState( + targetValue = if (selected) 1.04f else 1f, + animationSpec = AppMotion.playfulSpring(), + label = "iconScale", + ) + + Column( + modifier = modifier + .fillMaxWidth() + .pressScale(interactionSource, targetScale = 0.94f) + .clip(TileShape) + .background(tileBackground) + .clickable( + interactionSource = interactionSource, + indication = null, + role = Role.Button, + onClick = onClick, + ) + .semantics(mergeDescendants = true) { + this.selected = selected + contentDescription = buildString { + append(option.name) + if (selected) append(", ").append(selectedLabel) + if (!installed) append(", ").append(notInstalledLabel) + } + } + .alpha(if (installed) 1f else 0.45f) + .padding(horizontal = 4.dp, vertical = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(5.dp), + ) { + Box(contentAlignment = Alignment.Center) { + Box( + modifier = Modifier + .graphicsLayer { + scaleX = iconScale + scaleY = iconScale + } + .border(width = 2.dp, color = ringColor, shape = RingShape) + .padding(3.dp), + ) { + TargetIcon(option = option, installed = installed) + } + + // 右上角微信绿勾角标:弹簧弹出 + androidx.compose.animation.AnimatedVisibility( + visible = selected, + modifier = Modifier + .align(Alignment.TopEnd) + .offset(x = 3.dp, y = (-3).dp), + enter = scaleIn( + animationSpec = AppMotion.playfulSpring(), + initialScale = 0.25f, + ) + fadeIn(tween(120)), + exit = scaleOut( + animationSpec = AppMotion.snappySpring(), + targetScale = 0.25f, + ) + fadeOut(tween(100)), + ) { + Box( + modifier = Modifier + .size(18.dp) + .background(MaterialTheme.colorScheme.surface, CircleShape) + .padding(1.5.dp) + .background(MaterialTheme.colorScheme.primary, CircleShape), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Filled.Check, + contentDescription = null, + modifier = Modifier.size(11.dp), + tint = MaterialTheme.colorScheme.onPrimary, + ) + } + } + } + + Text( + text = option.name, + style = MaterialTheme.typography.labelMedium, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, + color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, + ) + + if (!installed) { + Text( + text = notInstalledLabel, + style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp, lineHeight = 12.sp), + color = appColors.onSurfaceMuted, + maxLines = 1, + ) + } + } +} + +/** + * 三层目标图标策略,统一 44dp、12dp 圆角、0.5dp 极淡描边: + * 1. 内置高清官方 PNG; + * 2. 已安装且无内置 PNG 的 App -> PackageManager 真实应用图标; + * 3. 文件夹 / 其他应用用干净矢量图标;其余未安装项用克制的圆角首字徽章兜底。 + */ +@Composable +private fun TargetIcon(option: TargetOption, installed: Boolean) { + val appColors = LocalAppColors.current + val strokeColor = if (appColors.isDark) { + Color.White.copy(alpha = 0.10f) + } else { + Color(0x140F172A) + } + val desaturate = remember { + ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0f) }) + } + val logoRes = logoResource(option.profile.logo) + val isSpecialSystemTarget = option.profile.kind == TargetKind.FOLDER || option.profile.kind == TargetKind.CHOOSER + val appBitmap = if (logoRes == null && !isSpecialSystemTarget) { + rememberAppIcon( + packageNames = option.profile.packageNames, + enabled = installed && option.profile.packageNames.isNotEmpty(), + ) + } else { + null + } + + val containerModifier = Modifier + .size(IconSize) + .clip(IconShape) + .border(width = 0.5.dp, color = strokeColor, shape = IconShape) + + when { + // ① 内置高清官方 PNG + logoRes != null -> { + Image( + painter = painterResource(logoRes), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = containerModifier, + colorFilter = if (installed) null else desaturate, + ) + } + // ② 手机已安装应用的真实系统图标 + appBitmap != null -> { + Image( + bitmap = appBitmap, + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = containerModifier, + colorFilter = if (installed) null else desaturate, + ) + } + // ③-a 文件夹:干净矢量图标 + option.profile.kind == TargetKind.FOLDER -> { + Box( + modifier = containerModifier.background(appColors.surfaceSub), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = FolderIcon, + contentDescription = null, + modifier = Modifier.size(22.dp), + tint = KindNoteColor, + ) + } + } + // ③-b 其他应用:干净矢量图标 + option.profile.kind == TargetKind.CHOOSER -> { + Box( + modifier = containerModifier.background(appColors.surfaceSub), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = OtherAppIcon, + contentDescription = null, + modifier = Modifier.size(21.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + // ③-c 未安装或加载兜底:克制的圆角首字徽章 + else -> { + val style = monogramStyle(option.id, appColors.isDark) + val bg = if (installed) style.background else appColors.surfaceSub + val fg = if (installed) style.foreground else appColors.onSurfaceMuted + Box( + modifier = containerModifier.background(bg), + contentAlignment = Alignment.Center, + ) { + Text( + text = monogramChar(option.name), + style = MaterialTheme.typography.titleMedium.copy( + fontSize = 17.sp, + fontWeight = FontWeight.SemiBold, + ), + color = fg, + maxLines = 1, + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/ChatList.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/ChatList.kt new file mode 100644 index 00000000..cd019251 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/ChatList.kt @@ -0,0 +1,447 @@ +package com.xiangming.wechatbridge.ui.detail + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import coil3.compose.AsyncImage +import coil3.request.ImageRequest +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.KindChatColor +import com.xiangming.wechatbridge.ui.theme.KindFileColor +import com.xiangming.wechatbridge.ui.theme.KindLinkColor +import com.xiangming.wechatbridge.ui.theme.KindNoteColor +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import java.io.File +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle + +/** 气泡式聊天列表。LazyColumn 只组合可见的行,1000 条也不卡;每行的切分与文件查找都在加载时做完。 */ +@Composable +internal fun ChatList( + content: DetailContent.Chat, + onOpenImage: (File) -> Unit, + onOpenFile: (File, String) -> Unit, + onOpenUrl: (String) -> Unit, + modifier: Modifier = Modifier, +) { + val dateFormatter = remember { DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL) } + val timeFormatter = remember { DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) } + LazyColumn( + modifier = modifier, + contentPadding = PaddingValues(horizontal = 14.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + items(content.items, key = { it.key }, contentType = { it::class }) { item -> + when (item) { + is ChatItem.DateDivider -> DateCapsule(text = dateFormatter.format(item.date)) + is ChatItem.Message -> MessageRow( + item = item, + timeText = timeFormatter.format(item.time), + onOpenImage = onOpenImage, + onOpenFile = onOpenFile, + onOpenUrl = onOpenUrl, + ) + } + } + } +} + +@Composable +private fun DateCapsule(text: String) { + val appColors = LocalAppColors.current + Box( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 8.dp), + contentAlignment = Alignment.Center, + ) { + Surface( + shape = RoundedCornerShape(999.dp), + color = appColors.surfaceSub, + ) { + Text( + text = text, + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + } +} + +@Composable +private fun MessageRow( + item: ChatItem.Message, + timeText: String, + onOpenImage: (File) -> Unit, + onOpenFile: (File, String) -> Unit, + onOpenUrl: (String) -> Unit, +) { + val appColors = LocalAppColors.current + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.Top, + ) { + Avatar(item.sender, modifier = Modifier.alpha(if (item.showsSender) 1f else 0f)) + Column( + verticalArrangement = Arrangement.spacedBy(5.dp), + modifier = Modifier.weight(1f, fill = false), + ) { + if (item.showsSender) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + item.sender, + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = senderColor(item.sender), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + timeText, + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + } + } + item.tokens.forEachIndexed { idx, token -> + TokenView( + token = token, + isLeadBubble = item.showsSender && idx == 0, + onOpenImage = onOpenImage, + onOpenFile = onOpenFile, + onOpenUrl = onOpenUrl, + ) + } + } + Spacer(Modifier.width(18.dp)) + } +} + +@Composable +private fun Avatar(name: String, modifier: Modifier = Modifier) { + val bg = senderColor(name) + Box( + modifier = modifier + .size(34.dp) + .clip(RoundedCornerShape(10.dp)) + .background(bg), + contentAlignment = Alignment.Center, + ) { + Text( + avatarInitial(name), + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = Color.White, + ) + } +} + +/** 跳过微信昵称常见的前导点号/空白/标点,提取更有辨识度的首字。 */ +private fun avatarInitial(name: String): String { + val trimmed = name.trim() + val candidate = trimmed.dropWhile { ch -> + ch == '·' || ch == '.' || ch == '_' || ch == '-' || ch == '@' || ch.isWhitespace() + }.ifEmpty { trimmed } + val first = candidate.codePoints().findFirst() + return if (first.isPresent) String(Character.toChars(first.asInt)).uppercase() else "" +} + +/** 8 组低饱和莫兰迪色板:雾蓝、鼠尾草绿、暖杏、浅紫、珊瑚粉、青瓷、暖麦、岩灰蓝。 */ +private val MorandiPalette = listOf( + Color(0xFF5C82A6), // 雾蓝 + Color(0xFF5E947A), // 鼠尾草绿 + Color(0xFFC98C5E), // 暖杏 + Color(0xFF8574A8), // 浅紫 + Color(0xFFC4717A), // 珊瑚粉 + Color(0xFF55949C), // 青瓷蓝 + Color(0xFFB5924C), // 暖麦金 + Color(0xFF6B7A8F), // 岩灰蓝 +) + +/** 同一个名字永远分配同一个低饱和莫兰迪色(稳定 djb2 哈希,头像与发送人名称同色)。 */ +internal fun senderColor(name: String): Color { + var seed = 5381L + name.codePoints().forEach { seed = (seed * 33 + it) and 0xFFFFFFFFL } + return MorandiPalette[(seed % MorandiPalette.size).toInt()] +} + +private val DarkBubbleSurface = Color(0xFF22262B) + +@Composable +private fun TokenView( + token: BubbleToken, + isLeadBubble: Boolean, + onOpenImage: (File) -> Unit, + onOpenFile: (File, String) -> Unit, + onOpenUrl: (String) -> Unit, +) { + val appColors = LocalAppColors.current + val bubbleColor = if (appColors.isDark) DarkBubbleSurface else MaterialTheme.colorScheme.surface + val bubbleElevation = if (appColors.isDark) 0.dp else 1.5.dp + + when (token) { + is BubbleToken.Text -> { + val bubbleShape = RoundedCornerShape( + topStart = if (isLeadBubble) 4.dp else 14.dp, + topEnd = 14.dp, + bottomEnd = 14.dp, + bottomStart = 14.dp, + ) + Surface( + shape = bubbleShape, + color = bubbleColor, + shadowElevation = bubbleElevation, + ) { + SelectionContainer { + Text( + token.text, + style = MaterialTheme.typography.bodyLarge.copy(lineHeight = 21.sp), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), + ) + } + } + } + is BubbleToken.Image -> { + val file = token.file + if (file == null) { + AttachmentCard( + kind = AttachmentKind.IMAGE, + title = token.name, + subtitle = stringResource(R.string.detail_image_missing), + onClick = null, + ) + } else { + ImageTile(token, file, onClick = { onOpenImage(file) }) + } + } + is BubbleToken.Video -> AttachmentCard( + kind = AttachmentKind.VIDEO, + title = token.name, + subtitle = stringResource(R.string.detail_video), + onClick = token.file?.let { file -> { onOpenFile(file, token.name) } }, + ) + is BubbleToken.Attachment -> AttachmentCard( + kind = AttachmentKind.FILE, + title = token.name, + subtitle = stringResource(R.string.detail_file), + onClick = token.file?.let { file -> { onOpenFile(file, token.name) } }, + ) + is BubbleToken.Link -> AttachmentCard( + kind = AttachmentKind.LINK, + title = token.title, + subtitle = token.host, + onClick = { onOpenUrl(token.url) }, + ) + is BubbleToken.Channels -> AttachmentCard( + kind = AttachmentKind.CHANNELS, + title = token.title, + subtitle = stringResource(R.string.detail_channels), + onClick = { onOpenUrl(token.url) }, + ) + } +} + +@Composable +private fun ImageTile(token: BubbleToken.Image, file: File, onClick: () -> Unit) { + val density = LocalDensity.current.density + val (width, height) = displaySizeDp(token.widthPx, token.heightPx, density) + val description = stringResource(R.string.detail_image_cd, token.name) + val context = LocalContext.current + val request = remember(file) { + // 解码时按 600px 下采样:一份转发记录可能带几十张原图。 + ImageRequest.Builder(context).data(file).size(THUMBNAIL_PIXELS).build() + } + val shape = RoundedCornerShape(12.dp) + Box( + modifier = Modifier + .size(width.dp, height.dp) + .clip(shape) + .background(LocalAppColors.current.surfaceSub) + .border(0.5.dp, LocalAppColors.current.subtleDivider, shape) + .semantics { contentDescription = description } + .clickable(onClick = onClick), + ) { + AsyncImage( + model = request, + contentDescription = null, // 外层 Box 已带同一描述,避免读两遍 + contentScale = ContentScale.Crop, + modifier = Modifier.matchParentSize(), + ) + } +} + +private const val THUMBNAIL_PIXELS = 600 + +internal enum class AttachmentKind { + IMAGE, + VIDEO, + FILE, + LINK, + CHANNELS, +} + +/** 视频 / 文件 / 链接 / 视频号 / 缺失图片 的精致纯白圆角卡片,使用 40dp 柔和色块底托 + 矢量图标。 */ +@Composable +internal fun AttachmentCard( + kind: AttachmentKind, + title: String, + subtitle: String, + onClick: (() -> Unit)?, + modifier: Modifier = Modifier, +) { + val appColors = LocalAppColors.current + val cardColor = if (appColors.isDark) DarkBubbleSurface else MaterialTheme.colorScheme.surface + val elevation = if (appColors.isDark) 0.dp else 1.5.dp + val shape = RoundedCornerShape(14.dp) + + val (icon, tint, containerColor) = when (kind) { + AttachmentKind.IMAGE -> Triple(ImageFrameIcon, KindChatColor, KindChatColor.copy(alpha = 0.12f)) + AttachmentKind.VIDEO -> Triple(PlayCircleIcon, KindNoteColor, KindNoteColor.copy(alpha = 0.13f)) + AttachmentKind.FILE -> Triple(AppIcons.FileAttachment, KindFileColor, KindFileColor.copy(alpha = 0.12f)) + AttachmentKind.LINK -> Triple(AppIcons.LinkChain, KindLinkColor, KindLinkColor.copy(alpha = 0.12f)) + AttachmentKind.CHANNELS -> Triple(PlayCircleIcon, KindChatColor, KindChatColor.copy(alpha = 0.12f)) + } + + Surface( + shape = shape, + color = cardColor, + shadowElevation = elevation, + modifier = modifier + .widthIn(max = 288.dp) + .let { if (onClick != null) it.clip(shape).clickable(onClick = onClick) else it }, + ) { + Row( + modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(40.dp) + .clip(RoundedCornerShape(11.dp)) + .background(containerColor), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = tint, + modifier = Modifier.size(20.dp), + ) + } + Column( + modifier = Modifier.weight(1f, fill = false), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + title, + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + Text( + subtitle, + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + if (onClick != null) { + Icon( + imageVector = AppIcons.ChevronRight, + contentDescription = null, + tint = appColors.onSurfaceMuted, + modifier = Modifier.size(16.dp), + ) + } + } + } +} + +/** 精致圆润线框图片图标(用于未随附图片卡片)。 */ +private val ImageFrameIcon: ImageVector by lazy { + ImageVector.Builder("ImageFrame", 24.dp, 24.dp, 24f, 24f) + .addPath( + addPathNodes("M5,3 H19 A2,2 0 0 1 21,5 V19 A2,2 0 0 1 19,21 H5 A2,2 0 0 1 3,19 V5 A2,2 0 0 1 5,3 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.9f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + .addPath( + addPathNodes("M8.5,10 A1.5,1.5 0 1 0 8.5,7 A1.5,1.5 0 1 0 8.5,10 Z"), + fill = SolidColor(Color.Black), + ) + .addPath( + addPathNodes("M21,15 L16,10 L5,21"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.9f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + .build() +} + +/** 精致圆润线框播放图标(用于视频/视频号卡片)。 */ +private val PlayCircleIcon: ImageVector by lazy { + ImageVector.Builder("PlayCircle", 24.dp, 24.dp, 24f, 24f) + .addPath( + addPathNodes("M12,22 A10,10 0 1 0 12,2 A10,10 0 1 0 12,22 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.9f, + ) + .addPath( + addPathNodes("M10,8.5 L16,12 L10,15.5 Z"), + fill = SolidColor(Color.Black), + ) + .build() +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailLinks.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailLinks.kt new file mode 100644 index 00000000..63911c91 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailLinks.kt @@ -0,0 +1,69 @@ +package com.xiangming.wechatbridge.ui.detail + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.webkit.MimeTypeMap +import com.xiangming.wechatbridge.deliver.ShareFileProvider +import java.io.File +import java.net.URI + +/** 链接与外部打开:链接只放行 http/https;文件先复制到投递目录,再经 FileProvider 交出去。 */ +object DetailLinks { + private val URL_PATTERN = Regex("https?://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]") + + /** 只有 http / https(不分大小写)且有主机名的才算可打开的链接。 */ + fun isOpenableUrl(url: String): Boolean { + val uri = runCatching { URI(url.trim()) }.getOrNull() ?: return false + val scheme = uri.scheme?.lowercase() + return (scheme == "http" || scheme == "https") && !uri.host.isNullOrEmpty() + } + + /** 文字里 http(s) 链接的位置(用于让正文里的链接可点)。 */ + fun linkRanges(text: String): List = URL_PATTERN.findAll(text).map { it.range }.toList() + + /** 返回是否成功交给了系统;非 http/https 一律不开。 */ + fun openUrl(context: Context, url: String): Boolean { + if (!isOpenableUrl(url)) return false + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url.trim())).addCategory(Intent.CATEGORY_BROWSABLE) + return start(context, intent) + } + + /** 阻塞 I/O(复制文件),在后台线程调用;返回 null 表示没法交出去。 */ + fun viewIntent(context: Context, file: File, name: String, batchKey: String): Intent? { + if (!file.isFile) return null + return runCatching { + val dir = File(ShareFileProvider.deliveriesDir(context), "view-$batchKey").apply { mkdirs() } + val leaf = File(name).name.ifEmpty { file.name } + val copy = File(dir, leaf) + if (!copy.isFile || copy.length() != file.length()) file.copyTo(copy, overwrite = true) + val extension = leaf.substringAfterLast('.', "").lowercase() + val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "*/*" + Intent(Intent.ACTION_VIEW) + .setDataAndType(ShareFileProvider.uriFor(context, copy, leaf), mime) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + }.getOrNull() + } + + fun start(context: Context, intent: Intent): Boolean { + if (context !is android.app.Activity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + return try { + context.startActivity(intent) + true + } catch (_: ActivityNotFoundException) { + false + } catch (_: SecurityException) { + false + } + } +} + +/** 图片在气泡里的显示尺寸(dp):框在 220×260 内,不放大超过原始像素。读不出尺寸时给 64×64 的占位。 */ +fun displaySizeDp(widthPx: Int, heightPx: Int, density: Float): Pair { + if (widthPx <= 0 || heightPx <= 0 || density <= 0f) return 64f to 64f + val width = widthPx / density + val height = heightPx / density + val scale = minOf(220f / width, 260f / height, 1f) + return (width * scale).coerceAtLeast(64f) to (height * scale).coerceAtLeast(64f) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailLoader.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailLoader.kt new file mode 100644 index 00000000..7a56a324 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailLoader.kt @@ -0,0 +1,124 @@ +package com.xiangming.wechatbridge.ui.detail + +import android.graphics.BitmapFactory +import com.xiangming.wechatbridge.core.inbox.ReadyBatch +import com.xiangming.wechatbridge.core.summary.LoadedTranscript +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.core.transcript.MessageToken +import com.xiangming.wechatbridge.data.RelayEntry +import java.io.File +import java.time.LocalDate +import java.time.ZoneId + +/** + * 把一个批次读成详情页要显示的东西(对应 iOS `RelayDetailView.content` + `LoadedTranscript.load`)。 + * + * 会解压压缩包、读文件,**只能在后台线程调用**。解压目录靠 `RelayFiles.root` + * (`RelayStore` 初始化时已指向 `cacheDir/Relay`),已解压过的批次直接复用。 + */ +class DetailLoader( + private val zone: ZoneId = ZoneId.systemDefault(), + /** 读图片像素宽高(不解码像素);读不出返回 null。 */ + private val imageBounds: (File) -> Pair? = ::decodeImageBounds, +) { + fun load(entry: RelayEntry): DetailContent { + val batch = entry.batch + val origin = ShareOrigin.read(batch.directory) + if (entry.summary?.kind == RelaySummary.Kind.LINK || origin != null) return link(entry, origin) + + val loaded = LoadedTranscript.load(batch) ?: return notesOrFiles(batch) + loaded.exceptionOrNull()?.let { error -> + return DetailContent.Files(files(batch), error = error.message ?: error.toString()) + } + val transcript = loaded.getOrThrow() + transcript.text?.let { return DetailContent.PlainText(it) } + return chat(transcript) + } + + /** + * 没有聊天压缩包:整批都是小文本文件(Android 把分享来的文字存成 .txt)就显示全文, + * 否则列出文件。 + */ + private fun notesOrFiles(batch: ReadyBatch): DetailContent { + val items = batch.items + if (items.isNotEmpty() && items.all { isTextNote(it) }) { + val texts = items.mapNotNull { runCatching { it.file.readText(Charsets.UTF_8) }.getOrNull() } + if (texts.size == items.size) return DetailContent.PlainText(texts.joinToString("\n\n")) + } + return DetailContent.Files(files(batch)) + } + + private fun isTextNote(item: com.xiangming.wechatbridge.core.inbox.ReadyItem): Boolean { + val name = item.displayName.lowercase() + val textual = item.contentType == "text/plain" || name.endsWith(".txt") || name.endsWith(".md") + return textual && item.byteCount <= MAX_NOTE_BYTES + } + + private fun link(entry: RelayEntry, origin: ShareOrigin?): DetailContent.Link { + val summary = entry.summary + val batch = entry.batch + return DetailContent.Link( + title = origin?.title?.takeIf { it.isNotBlank() } ?: if (origin == null) summary?.title else null, + url = origin?.url ?: summary?.url, + text = origin?.text?.takeIf { it.isNotEmpty() }, + source = summary?.source, + files = files(batch) { it.contentType != ShareOrigin.NOTE_CONTENT_TYPE }, + ) + } + + private fun files(batch: ReadyBatch, keep: (com.xiangming.wechatbridge.core.inbox.ReadyItem) -> Boolean = { true }): List = + batch.items.filter(keep).map { DetailFile(it.displayName, it.byteCount, it.file) } + + private fun chat(loaded: LoadedTranscript): DetailContent.Chat { + val records = loaded.records + val items = ArrayList(records.size + 16) + var previousDate: LocalDate? = null + var previousSender: String? = null + records.forEachIndexed { index, record -> + val moment = record.date.atZone(zone) + val date = moment.toLocalDate() + val newDay = date != previousDate + if (newDay) items += ChatItem.DateDivider(date, key = "d$index") + items += ChatItem.Message( + index = index, + sender = record.sender, + time = moment.toLocalTime(), + showsSender = newDay || record.sender != previousSender, + tokens = tokens(record.text, loaded), + ) + previousDate = date + previousSender = record.sender + } + return DetailContent.Chat(items, messageCount = records.size) + } + + private fun tokens(body: String, loaded: LoadedTranscript): List = + MessageToken.tokenize(body).map { token -> + when (token) { + is MessageToken.Text -> BubbleToken.Text(token.text) + is MessageToken.Image -> { + val file = loaded.file(token.name)?.takeIf { it.isFile } + val bounds = file?.let(imageBounds) + BubbleToken.Image(token.name, file, bounds?.first ?: 0, bounds?.second ?: 0) + } + is MessageToken.Video -> BubbleToken.Video(token.name, loaded.file(token.name)?.takeIf { it.isFile }) + is MessageToken.File -> BubbleToken.Attachment(token.name, loaded.file(token.name)?.takeIf { it.isFile }) + is MessageToken.Link -> BubbleToken.Link( + token.title, + token.urlString, + token.url.host?.takeIf { it.isNotEmpty() } ?: token.urlString, + ) + is MessageToken.Channels -> BubbleToken.Channels(token.title, token.urlString) + } + } +} + +/** 只读图片文件头拿到宽高,不分配像素内存。 */ +fun decodeImageBounds(file: File): Pair? = runCatching { + val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeFile(file.path, options) + if (options.outWidth > 0 && options.outHeight > 0) options.outWidth to options.outHeight else null +}.getOrNull() + +private const val MAX_NOTE_BYTES = 1L shl 20 diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailModels.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailModels.kt new file mode 100644 index 00000000..3702e95e --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailModels.kt @@ -0,0 +1,81 @@ +package com.xiangming.wechatbridge.ui.detail + +import java.io.File +import java.time.LocalDate +import java.time.LocalTime + +/** 批次里的一个原始文件(文件批次、链接批次的附件)。 */ +data class DetailFile( + val name: String, + val byteCount: Long, + val file: File, +) + +/** 一条消息正文切出来的一段:文字、图片、视频、文件、链接、视频号。 */ +sealed interface BubbleToken { + /** 普通文字;不认识的占位(如 `[破涕为笑]`)也在这里,原样保留。 */ + data class Text(val text: String) : BubbleToken + + /** [file] 为 null:压缩包里没带这张图。[widthPx]/[heightPx] 为 0:读不出尺寸。 */ + data class Image(val name: String, val file: File?, val widthPx: Int = 0, val heightPx: Int = 0) : BubbleToken + + data class Video(val name: String, val file: File?) : BubbleToken + + data class Attachment(val name: String, val file: File?) : BubbleToken + + data class Link(val title: String, val url: String, val host: String) : BubbleToken + + data class Channels(val title: String, val url: String) : BubbleToken +} + +/** 聊天列表里的一行(LazyColumn 的一项)。 */ +sealed interface ChatItem { + /** 稳定 key:列表滚动与重组都靠它。 */ + val key: String + + data class DateDivider(val date: LocalDate, override val key: String) : ChatItem + + data class Message( + val index: Int, + val sender: String, + val time: LocalTime, + /** 与上一条同一发送者、同一天时不重复显示名字。 */ + val showsSender: Boolean, + val tokens: List, + ) : ChatItem { + override val key: String get() = "m$index" + } +} + +/** 详情页正文的各种形态。 */ +sealed interface DetailContent { + /** 首次进入:正在解压 / 解析。 */ + data object Loading : DetailContent + + /** 这批记录已不存在(被删除)。 */ + data object Missing : DetailContent + + /** 聊天记录:气泡列表。[messageCount] 只数消息,不含日期分隔。 */ + data class Chat(val items: List, val messageCount: Int) : DetailContent + + /** 不是聊天记录格式的文字压缩包:显示全文。 */ + data class PlainText(val text: String) : DetailContent + + /** 分享进来的链接 / 文字。 */ + data class Link( + val title: String?, + val url: String?, + val text: String?, + val source: String?, + val files: List, + ) : DetailContent + + /** 纯文件批次(或读取失败时退化成文件清单)。[error] 非空:读取失败的原因。 */ + data class Files(val files: List, val error: String? = null) : DetailContent +} + +data class DetailUiState( + val title: String? = null, + val source: String? = null, + val content: DetailContent = DetailContent.Loading, +) diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailScreen.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailScreen.kt new file mode 100644 index 00000000..d310c423 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailScreen.kt @@ -0,0 +1,303 @@ +package com.xiangming.wechatbridge.ui.detail + +import android.content.ClipData +import android.content.ClipboardManager +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.core.content.getSystemService +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.ui.theme.BridgeAmbientBackdrop +import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface +import com.xiangming.wechatbridge.ui.theme.BridgePrimaryCapsuleButton +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle + +/** 批次详情:把一批分享读回成它原本的样子(聊天气泡 / 全文 / 文件清单)。 */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DetailScreen( + batchId: String, + onBack: () -> Unit, + onDeliver: (batchId: String) -> Unit, +) { + val context = LocalContext.current + val container = (context.applicationContext as App).container + // relayStore 首次取用时会把 RelayFiles.root 指向 cacheDir/Relay,解压目录因此固定。 + val viewModel: DetailViewModel = viewModel(key = "detail-$batchId") { + DetailViewModel(batchId, container.relayStore.entries) + } + val state by viewModel.state.collectAsStateWithLifecycle() + + val snackbar = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + var viewingPath by rememberSaveable { mutableStateOf(null) } + val openFailed = stringResource(R.string.detail_open_failed) + val copiedMessage = stringResource(R.string.detail_copied) + val copyUnavailable = stringResource(R.string.detail_copy_unavailable) + val appColors = LocalAppColors.current + + val openUrl: (String) -> Unit = { url -> + if (!DetailLinks.openUrl(context, url)) scope.launch { snackbar.showSnackbar(openFailed) } + } + val openFile: (File, String) -> Unit = { file, name -> + scope.launch { + val intent = withContext(Dispatchers.IO) { DetailLinks.viewIntent(context, file, name, batchId) } + if (intent == null || !DetailLinks.start(context, intent)) snackbar.showSnackbar(openFailed) + } + } + val copyFullText: () -> Unit = { + val plain = extractPlainText(state.content) + if (plain.isNullOrBlank()) { + scope.launch { snackbar.showSnackbar(copyUnavailable) } + } else { + val clipboard = context.getSystemService() + val ok = runCatching { + clipboard?.setPrimaryClip(ClipData.newPlainText(CLIP_LABEL_DETAIL, plain)) + }.isSuccess && clipboard != null + scope.launch { snackbar.showSnackbar(if (ok) copiedMessage else copyUnavailable) } + } + } + + val subtitle = detailSubtitle(state.source, state.content) + val showBottomBar = state.content !is DetailContent.Loading && state.content !is DetailContent.Missing + + Box(modifier = Modifier.fillMaxSize()) { + BridgeAmbientBackdrop() + Scaffold( + topBar = { + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + scrolledContainerColor = Color.Transparent, + ), + title = { + Column(verticalArrangement = Arrangement.spacedBy(1.dp)) { + Text( + state.title ?: stringResource(R.string.detail_title_default), + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (subtitle != null) { + Text( + subtitle, + style = MaterialTheme.typography.labelMedium, + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.action_back), + ) + } + }, + ) + }, + bottomBar = { + if (showBottomBar) { + DetailBottomBar( + onCopyAll = copyFullText, + onDeliver = { onDeliver(batchId) }, + ) + } + }, + snackbarHost = { SnackbarHost(snackbar) }, + containerColor = Color.Transparent, + ) { padding -> + val modifier = Modifier.fillMaxSize().padding(padding) + when (val content = state.content) { + DetailContent.Loading -> Column( + modifier = modifier, + verticalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterVertically), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) + Text( + stringResource(R.string.detail_loading), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + DetailContent.Missing -> Box(modifier, contentAlignment = Alignment.Center) { + Text( + stringResource(R.string.detail_missing), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + is DetailContent.Chat -> ChatList( + content = content, + onOpenImage = { viewingPath = it.path }, + onOpenFile = openFile, + onOpenUrl = openUrl, + modifier = modifier, + ) + is DetailContent.PlainText -> PlainTextContent(content.text, openUrl, modifier) + is DetailContent.Link -> LinkContent(content, openUrl, openFile, modifier) + is DetailContent.Files -> FilesContent(content, openFile, modifier) + } + } + } + + viewingPath?.let { path -> ImageViewerDialog(File(path), onDismiss = { viewingPath = null }) } +} + +@Composable +private fun DetailBottomBar( + onCopyAll: () -> Unit, + onDeliver: () -> Unit, +) { + val copyInteraction = remember { MutableInteractionSource() } + + Row( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(horizontal = 16.dp, vertical = 12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + BridgeGlassSurface( + shape = CircleShape, + shadowElevation = 10.dp, + modifier = Modifier + .weight(1f) + .height(50.dp) + .pressScale(copyInteraction, targetScale = 0.97f) + .clickable( + interactionSource = copyInteraction, + indication = null, + role = Role.Button, + onClick = onCopyAll, + ), + ) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = 16.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = stringResource(R.string.detail_action_copy_all), + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + BridgePrimaryCapsuleButton( + text = stringResource(R.string.detail_action_deliver_batch), + icon = Icons.AutoMirrored.Filled.Send, + onClick = onDeliver, + height = 50.dp, + modifier = Modifier.weight(1.35f), + ) + } +} + +@Composable +private fun detailSubtitle(source: String?, content: DetailContent): String? { + val meta = when (content) { + DetailContent.Loading, DetailContent.Missing -> return null + is DetailContent.Chat -> stringResource(R.string.detail_meta_messages, content.messageCount) + is DetailContent.PlainText -> stringResource(R.string.detail_meta_chars, content.text.length) + is DetailContent.Link -> content.source?.takeIf { it.isNotBlank() } ?: stringResource(R.string.detail_meta_link) + is DetailContent.Files -> stringResource(R.string.detail_meta_files, content.files.size) + } + val cleanSource = source?.takeIf { it.isNotBlank() } + return if (cleanSource != null && content !is DetailContent.Link) "$cleanSource · $meta" else meta +} + +private fun extractPlainText(content: DetailContent): String? = when (content) { + DetailContent.Loading, DetailContent.Missing -> null + is DetailContent.PlainText -> content.text + is DetailContent.Link -> buildList { + content.title?.takeIf { it.isNotBlank() }?.let(::add) + content.url?.takeIf { it.isNotBlank() }?.let(::add) + content.text?.takeIf { it.isNotBlank() }?.let(::add) + }.joinToString("\n\n").ifBlank { null } + is DetailContent.Files -> content.files.joinToString("\n") { it.name }.ifBlank { null } + is DetailContent.Chat -> { + val timeFmt = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) + val dateFmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) + val lines = mutableListOf() + for (item in content.items) { + when (item) { + is ChatItem.DateDivider -> lines += "— ${dateFmt.format(item.date)} —" + is ChatItem.Message -> { + val body = item.tokens.joinToString("\n") { token -> + when (token) { + is BubbleToken.Text -> token.text + is BubbleToken.Image -> "[图片: ${token.name}]" + is BubbleToken.Video -> "[视频: ${token.name}]" + is BubbleToken.Attachment -> "[文件: ${token.name}]" + is BubbleToken.Link -> "${token.title} ${token.url}" + is BubbleToken.Channels -> "${token.title} ${token.url}" + } + } + lines += "${item.sender} (${timeFmt.format(item.time)}):\n$body" + } + } + } + lines.joinToString("\n\n").ifBlank { null } + } +} + +private const val CLIP_LABEL_DETAIL = "WeChatBridge detail" diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailViewModel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailViewModel.kt new file mode 100644 index 00000000..ddeadcd8 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/DetailViewModel.kt @@ -0,0 +1,85 @@ +package com.xiangming.wechatbridge.ui.detail + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.data.RelayEntry +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.util.UUID + +/** + * 详情页状态:从 `RelayStore.entries` 里按 [batchId] 找到批次,首次进入在 IO 线程解压并解析。 + * + * - 同一个批次只加载一次(摘要稍后算出来、列表刷新都不会重载); + * - 批次从列表里消失(删除)并且 [missingGraceMillis] 内没有回来,才显示「已删除」, + * 避免 store 尚未加载完时闪一下。 + */ +class DetailViewModel( + batchId: String, + entries: Flow>, + private val loader: DetailLoader = DetailLoader(), + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val missingGraceMillis: Long = MISSING_GRACE_MILLIS, +) : ViewModel() { + private val id: UUID? = runCatching { UUID.fromString(batchId) }.getOrNull() + + private val _state = MutableStateFlow(DetailUiState()) + val state: StateFlow = _state.asStateFlow() + + private var loadedId: UUID? = null + private var loadJob: Job? = null + private var missingJob: Job? = null + + init { + viewModelScope.launch { + entries.map { list -> id?.let { wanted -> list.firstOrNull { it.id == wanted } } } + .collect { entry -> onEntry(entry) } + } + } + + private fun onEntry(entry: RelayEntry?) { + missingJob?.cancel() + if (entry == null) { + loadJob?.cancel() + loadJob = null + loadedId = null + missingJob = viewModelScope.launch { + delay(missingGraceMillis) + _state.value = DetailUiState(title = null, content = DetailContent.Missing) + } + return + } + _state.update { it.copy(title = entry.summary?.title, source = entry.summary?.source) } + if (loadedId == entry.id) return + loadedId = entry.id + _state.update { it.copy(content = DetailContent.Loading) } + loadJob = viewModelScope.launch { + val content = try { + withContext(ioDispatcher) { loader.load(entry) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + DetailContent.Files( + files = entry.batch.items.map { DetailFile(it.displayName, it.byteCount, it.file) }, + error = e.message ?: e.toString(), + ) + } + _state.update { it.copy(content = content) } + } + } + + companion object { + const val MISSING_GRACE_MILLIS = 400L + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/ImageViewerDialog.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/ImageViewerDialog.kt new file mode 100644 index 00000000..bb1f237c --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/ImageViewerDialog.kt @@ -0,0 +1,96 @@ +package com.xiangming.wechatbridge.ui.detail + +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.gestures.detectTransformGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import coil3.compose.AsyncImage +import coil3.compose.AsyncImagePainter +import coil3.request.ImageRequest +import com.xiangming.wechatbridge.R +import java.io.File + +/** 全屏看图:捏合缩放(1×–5×)、双击在 1× 与 2.5× 之间切换;返回键或「完成」关闭。 */ +@Composable +internal fun ImageViewerDialog(file: File, onDismiss: () -> Unit) { + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false), + ) { + var scale by remember { mutableFloatStateOf(1f) } + var offset by remember { mutableStateOf(Offset.Zero) } + var failed by remember { mutableStateOf(false) } + val context = LocalContext.current + val request = remember(file) { ImageRequest.Builder(context).data(file).size(VIEWER_PIXELS).build() } + Box(modifier = Modifier.fillMaxSize().background(Color.Black)) { + AsyncImage( + model = request, + contentDescription = file.name, + contentScale = ContentScale.Fit, + onState = { failed = it is AsyncImagePainter.State.Error }, + modifier = Modifier + .fillMaxSize() + .pointerInput(Unit) { + detectTapGestures(onDoubleTap = { + if (scale > 1f) { + scale = 1f + offset = Offset.Zero + } else { + scale = 2.5f + } + }) + } + .pointerInput(Unit) { + detectTransformGestures { _, pan, zoom, _ -> + scale = (scale * zoom).coerceIn(1f, 5f) + offset = if (scale > 1f) offset + pan else Offset.Zero + } + } + .graphicsLayer { + scaleX = scale + scaleY = scale + translationX = offset.x + translationY = offset.y + }, + ) + if (failed) { + Text( + stringResource(R.string.detail_viewer_unavailable), + color = Color.White, + modifier = Modifier.align(Alignment.Center), + ) + } + TextButton( + onClick = onDismiss, + modifier = Modifier.align(Alignment.TopStart).statusBarsPadding().padding(4.dp), + ) { + Text(stringResource(R.string.detail_viewer_done), color = Color.White) + } + } + } +} + +private const val VIEWER_PIXELS = 2400 diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/TextContents.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/TextContents.kt new file mode 100644 index 00000000..0f329934 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/detail/TextContents.kt @@ -0,0 +1,257 @@ +package com.xiangming.wechatbridge.ui.detail + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.util.ByteFormat +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.KindLinkColor +import com.xiangming.wechatbridge.ui.theme.KindNoteColor +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import java.io.File + +/** 正文里的 http(s) 链接可点;非 http(s) 的不加链接。 */ +internal fun linkified(text: String, linkColor: Color, onOpenUrl: (String) -> Unit): AnnotatedString = + buildAnnotatedString { + append(text) + for (range in DetailLinks.linkRanges(text)) { + val url = text.substring(range.first, range.last + 1) + addLink( + LinkAnnotation.Clickable( + tag = url, + styles = TextLinkStyles(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)), + linkInteractionListener = { onOpenUrl(url) }, + ), + range.first, + range.last + 1, + ) + } + } + +/** 不是聊天记录格式的文字:全文按行分块放进 LazyColumn(长文也不会一次性排版)。 */ +@Composable +internal fun PlainTextContent(text: String, onOpenUrl: (String) -> Unit, modifier: Modifier = Modifier) { + val chunks = remember(text) { text.split("\n").chunked(LINES_PER_CHUNK).map { it.joinToString("\n") } } + val linkColor = MaterialTheme.colorScheme.primary + val appColors = LocalAppColors.current + val elevation = if (appColors.isDark) 0.dp else 1.5.dp + + SelectionContainer(modifier) { + LazyColumn( + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth(), + ) { + items(chunks.size, key = { it }) { index -> + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surface, + shadowElevation = elevation, + modifier = Modifier.fillMaxWidth(), + ) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (index == 0) { + Box( + modifier = Modifier + .size(36.dp) + .clip(RoundedCornerShape(10.dp)) + .background(KindNoteColor.copy(alpha = 0.12f)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = AppIcons.NoteDocument, + contentDescription = null, + tint = KindNoteColor, + modifier = Modifier.size(19.dp), + ) + } + } + Text( + linkified(chunks[index], linkColor, onOpenUrl), + style = MaterialTheme.typography.bodyLarge.copy(lineHeight = 22.sp), + ) + } + } + } + } + } +} + +/** 分享进来的链接 / 文字:标题、可点链接、全文、来源,以及随附文件。 */ +@Composable +internal fun LinkContent( + content: DetailContent.Link, + onOpenUrl: (String) -> Unit, + onOpenFile: (File, String) -> Unit, + modifier: Modifier = Modifier, +) { + val linkColor = MaterialTheme.colorScheme.primary + val appColors = LocalAppColors.current + val elevation = if (appColors.isDark) 0.dp else 1.5.dp + + LazyColumn( + modifier = modifier, + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (content.title != null || content.url != null || content.source != null) { + item(key = "link-header") { + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surface, + shadowElevation = elevation, + modifier = Modifier.fillMaxWidth(), + ) { + Row( + modifier = Modifier.padding(16.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.Top, + ) { + Box( + modifier = Modifier + .size(40.dp) + .clip(RoundedCornerShape(11.dp)) + .background(KindLinkColor.copy(alpha = 0.12f)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = AppIcons.LinkChain, + contentDescription = null, + tint = KindLinkColor, + modifier = Modifier.size(20.dp), + ) + } + SelectionContainer(modifier = Modifier.weight(1f)) { + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + content.title?.let { + Text(it, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + } + content.url?.let { url -> + Text(linkified(url, linkColor, onOpenUrl), style = MaterialTheme.typography.bodyMedium) + } + content.source?.let { source -> + Text( + stringResource(R.string.detail_from, source), + style = MaterialTheme.typography.labelMedium, + color = appColors.onSurfaceMuted, + ) + } + } + } + } + } + } + } + content.text?.let { text -> + val chunks = text.split("\n").chunked(LINES_PER_CHUNK).map { it.joinToString("\n") } + items(chunks.size, key = { "t$it" }) { index -> + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surface, + shadowElevation = elevation, + modifier = Modifier.fillMaxWidth(), + ) { + SelectionContainer { + Text( + linkified(chunks[index], linkColor, onOpenUrl), + style = MaterialTheme.typography.bodyLarge.copy(lineHeight = 22.sp), + modifier = Modifier.padding(16.dp), + ) + } + } + } + } + if (content.files.isNotEmpty()) fileItems(content.files, onOpenFile) + } +} + +/** 纯文件批次:列出文件,点一下交给系统打开。 */ +@Composable +internal fun FilesContent( + content: DetailContent.Files, + onOpenFile: (File, String) -> Unit, + modifier: Modifier = Modifier, +) { + LazyColumn( + modifier = modifier, + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + content.error?.let { error -> + item { + Surface( + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.surface, + modifier = Modifier.fillMaxWidth(), + ) { + Text( + stringResource(R.string.detail_read_failed, error), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(14.dp), + ) + } + } + } + fileItems(content.files, onOpenFile) + } +} + +private fun androidx.compose.foundation.lazy.LazyListScope.fileItems( + files: List, + onOpenFile: (File, String) -> Unit, +) { + item(key = "files-header") { + Text( + stringResource(R.string.detail_files_section), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 4.dp, start = 4.dp), + ) + } + items(files.size, key = { "f$it" }) { index -> + val file = files[index] + AttachmentCard( + kind = AttachmentKind.FILE, + title = file.name, + subtitle = ByteFormat.string(file.byteCount), + onClick = { onOpenFile(file.file, file.name) }, + modifier = Modifier.fillMaxWidth(), + ) + } +} + +private const val LINES_PER_CHUNK = 40 diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/drop/DropTarget.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/drop/DropTarget.kt new file mode 100644 index 00000000..96938250 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/drop/DropTarget.kt @@ -0,0 +1,197 @@ +package com.xiangming.wechatbridge.ui.drop + +import android.content.Context +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.draganddrop.dragAndDropTarget +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AddCircle +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draganddrop.DragAndDropEvent +import androidx.compose.ui.draganddrop.DragAndDropTarget +import androidx.compose.ui.draganddrop.mimeTypes +import androidx.compose.ui.draganddrop.toAndroidDragEvent +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.receive.DropClips +import com.xiangming.wechatbridge.receive.DropDestination +import com.xiangming.wechatbridge.receive.DropPermissions +import com.xiangming.wechatbridge.receive.DropReceiver +import com.xiangming.wechatbridge.receive.DropResult +import com.xiangming.wechatbridge.receive.message +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme + +/** What a screen needs to take drops: the Activity's queue and its permission source. */ +class DropHost( + val receiver: DropReceiver, + val permissions: DropPermissions, + /** The Activity: the clip's URIs are resolved against it. */ + val context: Context, +) + +/** Provided by MainActivity; null in previews (the screen then takes no drops). */ +val LocalDropHost = staticCompositionLocalOf { null } + +/** + * Lets another app's files, images, text and links be dropped on [content] + * (small window, split screen, free-form). While a drag hovers it shows + * 「松手存入中转站」 / 「松手加入这个收集」; a drop is read and queued at once + * (the grant only exists inside the drop callback), then saved in the background. + */ +@Composable +fun DropTargetBox( + destination: DropDestination, + modifier: Modifier = Modifier, + content: @Composable BoxScope.() -> Unit, +) { + val host = LocalDropHost.current + if (host == null) { + Box(modifier, content = content) + return + } + val hovering = remember { mutableStateOf(false) } + val pending by host.receiver.pending.collectAsStateWithLifecycle() + val target = remember(host, destination) { + object : DragAndDropTarget { + override fun onDrop(event: DragAndDropEvent): Boolean { + hovering.value = false + val dragEvent = event.toAndroidDragEvent() + val clip = dragEvent.clipData ?: return false + // Must be asked for here, with this event: afterwards the URIs are no longer ours to read. + val grant = host.permissions.request(dragEvent) + val items = runCatching { DropClips.items(host.context, clip) }.getOrDefault(emptyList()) + host.receiver.drop(items, grant, destination) + return true + } + + override fun onEntered(event: DragAndDropEvent) { + hovering.value = true + } + + override fun onExited(event: DragAndDropEvent) { + hovering.value = false + } + + override fun onEnded(event: DragAndDropEvent) { + hovering.value = false + } + } + } + Box( + modifier = modifier.dragAndDropTarget( + shouldStartDragAndDrop = { event -> DropClips.accepts(event.mimeTypes()) }, + target = target, + ), + ) { + content() + if (pending > 0) { + val saving = stringResource(R.string.drop_saving) + LinearProgressIndicator( + modifier = Modifier + .align(Alignment.TopCenter) + .statusBarsPadding() + .fillMaxWidth() + .semantics { liveRegion = LiveRegionMode.Polite; contentDescription = saving }, + ) + } + AnimatedVisibility(visible = hovering.value, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.fillMaxSize()) { + DropOverlay(destination) + } + } +} + +@Composable +private fun DropOverlay(destination: DropDestination) { + val colors = MaterialTheme.colorScheme + Box( + modifier = Modifier + .fillMaxSize() + .background(colors.surface.copy(alpha = 0.9f)) + .safeDrawingPadding() + .padding(12.dp), + ) { + Column( + modifier = Modifier + .fillMaxSize() + .background(colors.primaryContainer.copy(alpha = 0.55f), RoundedCornerShape(24.dp)) + .border(2.dp, colors.primary, RoundedCornerShape(24.dp)) + .padding(16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically), + ) { + Icon(Icons.Filled.AddCircle, contentDescription = null, tint = colors.primary, modifier = Modifier.size(48.dp)) + Text( + stringResource( + when (destination) { + DropDestination.Relay -> R.string.drop_hint_relay + is DropDestination.Collection -> R.string.drop_hint_collection + }, + ), + style = MaterialTheme.typography.titleMedium, + color = colors.primary, + textAlign = TextAlign.Center, + ) + Text( + stringResource(R.string.drop_hint_more), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } + } +} + +/** Shows each finished drop in [snackbarHostState], in order. */ +@Composable +fun DropResultsEffect(snackbarHostState: SnackbarHostState) { + val host = LocalDropHost.current ?: return + val resources = LocalContext.current.resources + LaunchedEffect(host, snackbarHostState) { + host.receiver.events.collect { result -> + snackbarHostState.showSnackbar( + result.message(resources), + duration = if (result is DropResult.Failed) SnackbarDuration.Long else SnackbarDuration.Short, + ) + } + } +} + +@Preview(name = "拖入覆盖层", showBackground = true, widthDp = 320, heightDp = 360) +@Composable +private fun DropOverlayPreview() = WeChatBridgeTheme { DropOverlay(DropDestination.Relay) } diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingScreen.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingScreen.kt new file mode 100644 index 00000000..bccc8c5c --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingScreen.kt @@ -0,0 +1,731 @@ +package com.xiangming.wechatbridge.ui.onboarding + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.pager.HorizontalPager +import androidx.compose.foundation.pager.rememberPagerState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.List +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Create +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.Notifications +import androidx.compose.material.icons.filled.Share +import androidx.compose.material.icons.filled.Star +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.bubble.BubbleService +import com.xiangming.wechatbridge.bubble.BubbleToggle +import com.xiangming.wechatbridge.bubble.OverlayPermission +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.BridgeAmbientBackdrop +import com.xiangming.wechatbridge.ui.theme.BridgeBentoCard +import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface +import com.xiangming.wechatbridge.ui.theme.BridgePrimaryCapsuleButton +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.pressScale + +/** + * 首次引导:3 步轻盈白卡图文示意引导 + * 第 1 步:微信转发示意 + * 第 2 步:安卓特色悬浮球引导(可一键开启或跳过) + * 第 3 步:通知权限与 Obsidian 库(均为可选) + */ +@Composable +fun OnboardingScreen( + onFinish: () -> Unit, +) { + val context = LocalContext.current + val container = (context.applicationContext as App).container + val viewModel = viewModel { OnboardingViewModel(container.preferences, TreeStoreVault(container.treeStore)) } + val state by viewModel.state.collectAsStateWithLifecycle() + + // 悬浮球状态与权限往返 + val bubbleSettings = container.bubbleSettings + val bubblePrefEnabled by bubbleSettings.enabled.collectAsStateWithLifecycle() + var bubbleAwaiting by rememberSaveable { mutableStateOf(false) } + var bubbleDenied by rememberSaveable { mutableStateOf(false) } + var overlayTick by remember { mutableIntStateOf(0) } + val canDrawOverlay = remember(overlayTick) { OverlayPermission.canDraw(context) } + + fun applyBubble(action: BubbleToggle.Action?, launch: () -> Unit) { + when (action) { + BubbleToggle.Action.ENABLE -> { + bubbleAwaiting = false + bubbleDenied = false + bubbleSettings.setEnabled(true) + BubbleService.sync(context) + } + BubbleToggle.Action.DISABLE -> { + bubbleAwaiting = false + bubbleDenied = false + bubbleSettings.setEnabled(false) + BubbleService.sync(context) + } + BubbleToggle.Action.REQUEST_PERMISSION -> { + bubbleAwaiting = true + launch() + } + null -> Unit + } + } + + val overlayLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { + overlayTick++ + val now = OverlayPermission.canDraw(context) + val action = BubbleToggle.onReturn(bubbleAwaiting, now) + if (action == null && bubbleAwaiting) { + bubbleAwaiting = false + bubbleDenied = true + } + applyBubble(action) {} + } + + LifecycleResumeEffect(Unit) { + overlayTick++ + applyBubble(BubbleToggle.onReturn(bubbleAwaiting, OverlayPermission.canDraw(context))) {} + onPauseOrDispose {} + } + + var notificationsOn by remember { mutableStateOf(notificationsEnabled(context)) } + var notificationsDenied by remember { mutableStateOf(false) } + val notificationLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + notificationsOn = granted + notificationsDenied = !granted + } + val vaultLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> + viewModel.onVaultPicked(uri) + } + + val pager = rememberPagerState(initialPage = state.step) { OnboardingViewModel.STEP_COUNT } + LaunchedEffect(state.step) { + if (pager.currentPage != state.step) pager.animateScrollToPage(state.step) + } + BackHandler(enabled = !state.isFirst) { viewModel.back() } + + OnboardingContent( + state = state, + pager = { modifier -> + // 只靠底部按钮翻页,避免滑动和按钮同时改步骤。 + HorizontalPager(state = pager, modifier = modifier, userScrollEnabled = false) { page -> + when (page) { + 0 -> FindStep() + 1 -> BubbleStep( + enabled = bubblePrefEnabled && canDrawOverlay, + denied = bubbleDenied, + onEnable = { + applyBubble(BubbleToggle.onSwitch(true, OverlayPermission.canDraw(context))) { + runCatching { overlayLauncher.launch(OverlayPermission.settingsIntent(context)) } + } + }, + ) + else -> SetupStep( + notificationsOn = notificationsOn, + notificationsDenied = notificationsDenied, + onEnableNotifications = { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + notificationLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) + } + }, + vaultName = state.vaultName, + vaultFailed = state.vaultFailed, + onPickVault = { runCatching { vaultLauncher.launch(null) } }, + ) + } + } + }, + onSkip = { viewModel.skip(onFinish) }, + onBack = viewModel::back, + onNext = { if (state.isLast) viewModel.finish(onFinish) else viewModel.next() }, + ) +} + +private fun notificationsEnabled(context: Context): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + +@Composable +private fun OnboardingContent( + state: OnboardingUiState, + pager: @Composable (Modifier) -> Unit, + onSkip: () -> Unit, + onBack: () -> Unit, + onNext: () -> Unit, +) { + val backInteraction = remember { MutableInteractionSource() } + + Box(modifier = Modifier.fillMaxSize()) { + BridgeAmbientBackdrop() + Column(modifier = Modifier.fillMaxSize().safeDrawingPadding()) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.End, + verticalAlignment = Alignment.CenterVertically, + ) { + TextButton(onClick = onSkip) { + Text( + stringResource(R.string.onboarding_skip), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { pager(Modifier.fillMaxSize()) } + + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 14.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + val progress = stringResource(R.string.onboarding_progress, state.step + 1, OnboardingViewModel.STEP_COUNT) + CapsuleProgressDots( + step = state.step, + modifier = Modifier.semantics { contentDescription = progress }, + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (!state.isFirst) { + BridgeGlassSurface( + shape = CircleShape, + shadowElevation = 8.dp, + modifier = Modifier + .height(50.dp) + .pressScale(backInteraction, targetScale = 0.97f) + .clickable( + interactionSource = backInteraction, + indication = null, + role = Role.Button, + onClick = onBack, + ), + ) { + Box( + modifier = Modifier + .height(50.dp) + .padding(horizontal = 20.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = stringResource(R.string.onboarding_previous), + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface, + ) + } + } + } + BridgePrimaryCapsuleButton( + text = stringResource(if (state.isLast) R.string.onboarding_start else R.string.onboarding_next), + onClick = onNext, + height = 50.dp, + modifier = Modifier.weight(1f), + ) + } + } + } + } +} + +@Composable +private fun CapsuleProgressDots(step: Int, modifier: Modifier = Modifier) { + Row( + modifier = modifier, + horizontalArrangement = Arrangement.spacedBy(7.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + repeat(OnboardingViewModel.STEP_COUNT) { index -> + val selected = index == step + val width by animateDpAsState( + targetValue = if (selected) 24.dp else 7.dp, + animationSpec = AppMotion.snappySpring(), + label = "onboardingDotWidth", + ) + val color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant + Box( + modifier = Modifier + .width(width) + .height(7.dp) + .clip(CircleShape) + .background(color), + ) + } + } +} + +@Composable +private fun StepPage( + icon: ImageVector, + title: String, + intro: String, + content: @Composable () -> Unit, +) { + val appColors = LocalAppColors.current + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Box( + modifier = Modifier + .size(56.dp) + .clip(RoundedCornerShape(16.dp)) + .background(appColors.surfaceTint), + contentAlignment = Alignment.Center, + ) { + Icon( + icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(28.dp), + ) + } + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text(title, style = MaterialTheme.typography.headlineSmall) + Text(intro, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + content() + } +} + +/** 第 1 步:微信转发示意(轻盈白卡 + 清晰编号流程)。 */ +@Composable +private fun FindStep() { + StepPage( + icon = Icons.Filled.Share, + title = stringResource(R.string.onboarding_find_title), + intro = stringResource(R.string.onboarding_find_intro), + ) { + CaseCard( + title = stringResource(R.string.onboarding_case_a_title), + steps = listOf( + stringResource(R.string.onboarding_case_a_step1) to Icons.AutoMirrored.Filled.List, + stringResource(R.string.onboarding_case_a_step2) to Icons.AutoMirrored.Filled.Send, + stringResource(R.string.onboarding_case_a_step3) to Icons.Filled.MoreVert, + stringResource(R.string.onboarding_case_a_step4) to Icons.Filled.Check, + ), + ) + CaseCard( + title = stringResource(R.string.onboarding_case_b_title), + steps = listOf( + stringResource(R.string.onboarding_case_b_step1) to Icons.Filled.Star, + stringResource(R.string.onboarding_case_b_step2) to Icons.Filled.Share, + stringResource(R.string.onboarding_case_b_step3) to Icons.Filled.Check, + ), + ) + } +} + +/** 第 2 步:安卓特色悬浮球引导(可一键开启,也可跳过)。 */ +@Composable +private fun BubbleStep( + enabled: Boolean, + denied: Boolean, + onEnable: () -> Unit, +) { + val appColors = LocalAppColors.current + + StepPage( + icon = AppIcons.NavRelay, + title = stringResource(R.string.onboarding_bubble_title), + intro = stringResource(R.string.onboarding_bubble_intro), + ) { + // 悬浮球轻盈示意白卡 + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + highlighted = enabled, + contentPadding = PaddingValues(16.dp), + ) { + Column( + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + // 示意横幅:左侧模拟微信卡片 + 右侧悬浮绿球 + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = appColors.surfaceTint, + border = BorderStroke(1.dp, appColors.surfaceTintBorder), + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 14.dp, vertical = 12.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + stringResource(R.string.onboarding_bubble_card_title), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + Text( + stringResource(R.string.bubble_settings_title), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.inverseSurface, + contentColor = MaterialTheme.colorScheme.inverseOnSurface, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + modifier = Modifier.padding(horizontal = 9.dp, vertical = 5.dp), + ) { + Box( + modifier = Modifier + .size(6.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.primary), + ) + Text( + "+1 · 3", + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + ) + } + } + Box( + modifier = Modifier + .width(5.dp) + .height(42.dp) + .clip(RoundedCornerShape(999.dp)) + .background(MaterialTheme.colorScheme.primary), + ) + } + } + } + + Reason(Icons.AutoMirrored.Filled.Send, stringResource(R.string.onboarding_bubble_point_1)) + Reason(AppIcons.FillInput, stringResource(R.string.onboarding_bubble_point_2)) + + if (enabled) { + StatusLine(stringResource(R.string.onboarding_bubble_enabled)) + } else { + BridgePrimaryCapsuleButton( + text = stringResource(R.string.onboarding_bubble_enable), + onClick = onEnable, + height = 46.dp, + modifier = Modifier.fillMaxWidth(), + ) + if (denied) { + Text( + stringResource(R.string.onboarding_bubble_denied), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + } +} + +/** 第 3 步:通知权限与 Obsidian 库(双轻盈白卡,均为可选)。 */ +@Composable +private fun SetupStep( + notificationsOn: Boolean, + notificationsDenied: Boolean, + onEnableNotifications: () -> Unit, + vaultName: String?, + vaultFailed: Boolean, + onPickVault: () -> Unit, +) { + val appColors = LocalAppColors.current + + StepPage( + icon = Icons.Filled.Notifications, + title = stringResource(R.string.onboarding_setup_title), + intro = stringResource(R.string.onboarding_setup_intro), + ) { + // 卡片 1:通知权限 + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + highlighted = notificationsOn, + contentPadding = PaddingValues(16.dp), + ) { + Column( + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(34.dp) + .clip(RoundedCornerShape(10.dp)) + .background(appColors.surfaceTint), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Filled.Notifications, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(18.dp), + ) + } + Text(stringResource(R.string.onboarding_notify_title), style = MaterialTheme.typography.titleMedium) + } + Reason(Icons.AutoMirrored.Filled.List, stringResource(R.string.onboarding_notify_reason_collect)) + Reason(Icons.AutoMirrored.Filled.Send, stringResource(R.string.onboarding_notify_reason_quick)) + if (notificationsOn) { + StatusLine(stringResource(R.string.onboarding_notify_enabled)) + } else { + OutlinedButton( + onClick = onEnableNotifications, + shape = CircleShape, + modifier = Modifier.fillMaxWidth().height(44.dp), + ) { + Text(stringResource(R.string.onboarding_notify_enable)) + } + if (notificationsDenied) { + Text( + stringResource(R.string.onboarding_notify_denied), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + + // 卡片 2:Obsidian 库或本地文件夹 + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + highlighted = vaultName != null, + contentPadding = PaddingValues(16.dp), + ) { + Column( + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(34.dp) + .clip(RoundedCornerShape(10.dp)) + .background(appColors.surfaceTint), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Filled.Create, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(18.dp), + ) + } + Text(stringResource(R.string.onboarding_vault_title), style = MaterialTheme.typography.titleMedium) + } + Text( + stringResource(R.string.onboarding_vault_intro), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (vaultName == null) { + OutlinedButton( + onClick = onPickVault, + shape = CircleShape, + modifier = Modifier.fillMaxWidth().height(44.dp), + ) { + Text(stringResource(R.string.onboarding_vault_pick)) + } + } else { + StatusLine( + if (vaultName.isEmpty()) { + stringResource(R.string.onboarding_vault_chosen_unnamed) + } else { + stringResource(R.string.onboarding_vault_chosen, vaultName) + }, + ) + OutlinedButton( + onClick = onPickVault, + shape = CircleShape, + modifier = Modifier.fillMaxWidth().height(44.dp), + ) { + Text(stringResource(R.string.onboarding_vault_change)) + } + } + if (vaultFailed) { + Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Icon( + Icons.Filled.Info, + contentDescription = null, + tint = MaterialTheme.colorScheme.error, + modifier = Modifier.size(18.dp), + ) + Text( + stringResource(R.string.onboarding_vault_failed), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + } + } + } + } +} + +/** 一条带编号的步骤:编号圆点 + 文案 + 示意图标。 */ +@Composable +private fun NumberedStep(number: Int, text: String, icon: ImageVector) { + val appColors = LocalAppColors.current + Row( + modifier = Modifier.semantics(mergeDescendants = true) {}, + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Box( + modifier = Modifier + .size(26.dp) + .clip(CircleShape) + .background(appColors.surfaceTint), + contentAlignment = Alignment.Center, + ) { + Text( + number.toString(), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + ) + } + Text(text, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) + Icon( + icon, + contentDescription = null, + tint = appColors.onSurfaceMuted, + modifier = Modifier.size(18.dp), + ) + } +} + +@Composable +private fun CaseCard(title: String, steps: List>) { + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + contentPadding = PaddingValues(16.dp), + ) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(title, style = MaterialTheme.typography.titleMedium) + steps.forEachIndexed { index, (text, icon) -> NumberedStep(index + 1, text, icon) } + } + } +} + +@Composable +private fun Reason(icon: ImageVector, text: String) { + Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Icon( + icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(top = 2.dp).size(18.dp), + ) + Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) + } +} + +@Composable +private fun StatusLine(text: String) { + val appColors = LocalAppColors.current + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(appColors.surfaceTint) + .padding(horizontal = 12.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + Icons.Filled.CheckCircle, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(18.dp), + ) + Text(text, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingViewModel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingViewModel.kt new file mode 100644 index 00000000..77527a30 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingViewModel.kt @@ -0,0 +1,116 @@ +package com.xiangming.wechatbridge.ui.onboarding + +import android.net.Uri +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.data.Preferences +import com.xiangming.wechatbridge.saf.TreeStatus +import com.xiangming.wechatbridge.saf.TreeStore +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** The Obsidian vault the guide offers to pick; production is [TreeStoreVault]. */ +interface OnboardingVault { + /** Display name of the vault already chosen; null when none (or it is no longer usable). */ + fun chosenName(): String? + + /** Keeps [tree] as the vault. Returns its display name (empty when unknown) or null when refused. */ + fun grant(tree: Uri): String? +} + +class TreeStoreVault(private val treeStore: TreeStore) : OnboardingVault { + override fun chosenName(): String? = + if (treeStore.status(TargetKind.VAULT) == TreeStatus.GRANTED) { + treeStore.folderName(TargetKind.VAULT).orEmpty() + } else { + null + } + + override fun grant(tree: Uri): String? { + if (treeStore.grant(TargetKind.VAULT, tree) != TreeStatus.GRANTED) return null + return treeStore.folderName(TargetKind.VAULT) ?: tree.lastPathSegment.orEmpty() + } +} + +data class OnboardingUiState( + val step: Int = 0, + /** Chosen vault's display name; empty string = chosen but unnamed; null = none. */ + val vaultName: String? = null, + /** The last pick was refused; cleared by the next pick. */ + val vaultFailed: Boolean = false, +) { + val isFirst: Boolean get() = step == 0 + val isLast: Boolean get() = step == OnboardingViewModel.STEP_COUNT - 1 +} + +/** + * Three steps: how to reach 微信流 from WeChat, notifications, an optional vault. + * Finishing and skipping both record `onboardingDone`, so the guide does not + * return on the next launch; Settings can reopen it on demand. + */ +class OnboardingViewModel( + private val preferences: Preferences, + private val vault: OnboardingVault, + private val io: CoroutineDispatcher = Dispatchers.IO, +) : ViewModel() { + private val _state = MutableStateFlow(OnboardingUiState()) + val state: StateFlow = _state.asStateFlow() + + init { + viewModelScope.launch { + val name = withContext(io) { runCatching { vault.chosenName() }.getOrNull() } + _state.update { it.copy(vaultName = name) } + } + } + + fun next() { + _state.update { it.copy(step = (it.step + 1).coerceAtMost(STEP_COUNT - 1)) } + } + + fun back() { + _state.update { it.copy(step = (it.step - 1).coerceAtLeast(0)) } + } + + fun goTo(step: Int) { + _state.update { it.copy(step = step.coerceIn(0, STEP_COUNT - 1)) } + } + + /** The `OpenDocumentTree` result; null when the user backed out. */ + fun onVaultPicked(tree: Uri?): Job? { + if (tree == null) return null + return viewModelScope.launch { + val name = withContext(io) { runCatching { vault.grant(tree) }.getOrNull() } + _state.update { + if (name != null) it.copy(vaultName = name, vaultFailed = false) else it.copy(vaultFailed = true) + } + } + } + + fun finish(onDone: () -> Unit = {}): Job = markDone(onDone) + + fun skip(onDone: () -> Unit = {}): Job = markDone(onDone) + + // Never trap the user in the guide: if the write fails, still let them out. + private fun markDone(onDone: () -> Unit): Job = viewModelScope.launch { + try { + preferences.setOnboardingDone(true) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + } + onDone() + } + + companion object { + const val STEP_COUNT = 3 + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayCards.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayCards.kt new file mode 100644 index 00000000..94ffb75f --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayCards.kt @@ -0,0 +1,840 @@ +package com.xiangming.wechatbridge.ui.relay + +import android.content.res.Resources +import android.os.Build +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.scale +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.collection.BatchCollection +import com.xiangming.wechatbridge.core.inbox.ReadyBatch +import com.xiangming.wechatbridge.core.inbox.ReadyItem +import com.xiangming.wechatbridge.core.inbox.ShareAction +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareSource +import com.xiangming.wechatbridge.core.util.HistoryLabel +import com.xiangming.wechatbridge.core.util.HistoryStrings +import com.xiangming.wechatbridge.data.DeliveryStatus +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.BridgeBentoCard +import com.xiangming.wechatbridge.ui.theme.BridgePrimaryCapsuleButton +import com.xiangming.wechatbridge.ui.theme.KindChatColor +import com.xiangming.wechatbridge.ui.theme.KindFileColor +import com.xiangming.wechatbridge.ui.theme.KindLinkColor +import com.xiangming.wechatbridge.ui.theme.KindNoteColor +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import com.xiangming.wechatbridge.ui.theme.pressScale +import java.io.File +import java.time.Instant +import java.time.LocalDate +import java.time.LocalTime +import java.time.ZoneId +import java.util.UUID + +/** [HistoryLabel]'s copy and date formats, from string resources. */ +class RelayHistoryStrings(private val resources: Resources) : HistoryStrings { + override fun nameWithMore(firstName: String, count: Int) = + resources.getString(R.string.relay_history_name_more, firstName, count) + + override fun today() = resources.getString(R.string.relay_history_today) + override fun yesterday() = resources.getString(R.string.relay_history_yesterday) + override fun todayAt(time: String) = resources.getString(R.string.relay_history_today_at, time) + override fun oneFile() = resources.getString(R.string.relay_history_one_file) + override fun fileCount(count: Int) = resources.getString(R.string.relay_history_file_count, count) + override fun sentTo(name: String) = resources.getString(R.string.relay_history_sent_to, name) + + override fun monthDay(date: LocalDate, includeYear: Boolean): String = + if (includeYear) { + resources.getString(R.string.relay_history_month_day_year, date.year, date.monthValue, date.dayOfMonth) + } else { + resources.getString(R.string.relay_history_month_day, date.monthValue, date.dayOfMonth) + } + + override fun clockTime(time: LocalTime) = + resources.getString(R.string.relay_history_clock, time.hour, time.minute) +} + +/** Everything the cards need to turn a summary into text. */ +internal class RelayCardText( + private val resources: Resources, + private val now: Instant, + private val zone: ZoneId, +) { + private val strings = RelayHistoryStrings(resources) + + /** `8 条消息 · 3 个附件`; a text reads `文本`, a link `链接` (iOS `RelayCardView.counts`). */ + fun counts(summary: RelaySummary): String = summary.counts.format( + messageFormat = { resources.getString(R.string.relay_count_messages, it) }, + textLabel = resources.getString(R.string.relay_kind_text), + linkLabel = resources.getString(R.string.relay_kind_link), + mediaFormat = { resources.getString(R.string.relay_count_attachments, it) }, + ) + + /** `来源 · 8 条消息 · 3 个附件`: where it came from leads, as on iOS. */ + fun sourceLine(summary: RelaySummary): String = + listOf(summary.source, counts(summary)).filter { it.isNotEmpty() }.joinToString(" · ") + + /** 精简单行元数据:`微信 · 29 条 · 5月26日` 或 `文件 · 2 个附件 · 今天 14:20`。 */ + fun metaLine(entry: RelayEntry, summary: RelaySummary): String { + val countPart = when { + summary.messageCount != null -> + resources.getString(R.string.relay_count_messages_short, summary.messageCount) + summary.kind == RelaySummary.Kind.TEXT -> resources.getString(R.string.relay_kind_text) + summary.kind == RelaySummary.Kind.LINK -> resources.getString(R.string.relay_kind_link) + summary.mediaCount > 0 -> + resources.getString(R.string.relay_count_attachments, summary.mediaCount) + else -> "" + } + return listOf(summary.source, countPart, shortTime(entry)) + .filter { it.isNotEmpty() } + .joinToString(" · ") + } + + /** 精简短时间:`今天 14:20` / `昨天` / `5月26日`。 */ + fun shortTime(entry: RelayEntry): String { + val instant = entry.summary?.start ?: entry.batch.createdAt + return HistoryLabel.timestamp(instant, now, namesToday = true, strings = strings, zone = zone) + } + + /** The chat's own time range when known, else when the batch arrived. */ + fun time(entry: RelayEntry): String { + val summary = entry.summary + val start = summary?.start + if (start != null) return range(start, summary.end) + val received = HistoryLabel.timestamp(entry.batch.createdAt, now, namesToday = true, strings = strings, zone = zone) + return resources.getString(R.string.relay_received_at, received) + } + + /** `10月20日 09:00–09:07`; both ends dated when the range crosses a day. */ + fun range(start: Instant, end: Instant?): String { + val head = HistoryLabel.timestamp(start, now, namesToday = false, strings = strings, zone = zone) + if (end == null || end == start) return head + val sameDay = start.atZone(zone).toLocalDate() == end.atZone(zone).toLocalDate() + val tail = if (sameDay) { + HistoryLabel.clockTime(end, strings, zone) + } else { + HistoryLabel.timestamp(end, now, namesToday = false, strings = strings, zone = zone) + } + return "$head–$tail" + } + + fun title(entry: RelayEntry): String = + entry.summary?.title ?: entry.batch.items.firstOrNull()?.displayName + ?: resources.getString(R.string.relay_untitled) + + fun status(entry: RelayEntry): CardStatus? { + val summary = entry.summary + if (entry.isCollecting) return CardStatus(resources.getString(R.string.relay_status_collecting), StatusTone.Collecting) + // A WeChat export that failed to parse lands as plain files; a lone photo is not a failure. + if (summary?.parseFailed == true && entry.batch.items.any { it.displayName.endsWith(".zip", ignoreCase = true) }) { + return CardStatus(resources.getString(R.string.relay_status_parse_failed), StatusTone.Warning) + } + val target = entry.batch.targetName + return when (entry.delivery) { + DeliveryStatus.PENDING -> null // the normal state needs no tag + DeliveryStatus.DELIVERED -> CardStatus( + if (target.isNullOrEmpty()) { + resources.getString(R.string.relay_status_delivered) + } else { + resources.getString(R.string.relay_status_delivered_to, target) + }, + StatusTone.Quiet, + ) + DeliveryStatus.COPIED -> CardStatus(resources.getString(R.string.relay_status_copied), StatusTone.Quiet) + DeliveryStatus.FAILED -> CardStatus(resources.getString(R.string.relay_status_failed), StatusTone.Warning) + DeliveryStatus.EXPIRED -> CardStatus(resources.getString(R.string.relay_status_expired), StatusTone.Quiet) + } + } + + companion object { + /** A text's lines as written, except that a bare link shows only its domain and at most one link is shown. */ + fun previewLines(summary: RelaySummary): List { + if (summary.kind != RelaySummary.Kind.TEXT) return summary.preview + var sawLink = false + return summary.preview.mapNotNull { line -> + val host = linkHost(line.trim()) ?: return@mapNotNull line + if (sawLink) { + null + } else { + sawLink = true + host + } + } + } + + private fun linkHost(text: String): String? { + val isLink = text.startsWith("http://", ignoreCase = true) || text.startsWith("https://", ignoreCase = true) + if (!isLink || text.any { it.isWhitespace() }) return null + return ShareSource.displayHost(text) + } + } +} + +internal enum class StatusTone { Collecting, Quiet, Warning } + +internal data class CardStatus(val text: String, val tone: StatusTone) + +private val CardCornerRadius = 20.dp +private val CardShape = RoundedCornerShape(CardCornerRadius) + +/** One batch. Taps open it (or toggle it while selecting); a long press starts selecting. */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun RelayCard( + entry: RelayEntry, + text: RelayCardText, + selecting: Boolean, + selected: Boolean, + onClick: () -> Unit, + onLongClick: () -> Unit, + onDeliverSingle: () -> Unit = {}, + modifier: Modifier = Modifier, +) { + val haptic = LocalHapticFeedback.current + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val selectLabel = stringResource(R.string.a11y_relay_card_select) + val interactionSource = remember { MutableInteractionSource() } + + BridgeBentoCard( + modifier = modifier + .fillMaxWidth() + // 多选时卡片整体就是一个勾选项:读屏要能读出「已选中」。 + .semantics { if (selecting) this.selected = selected } + .pressScale(interactionSource, targetScale = 0.985f), + cornerRadius = CardCornerRadius, + highlighted = selected, + contentPadding = PaddingValues(0.dp), + ) { + Box( + modifier = Modifier + .fillMaxWidth() + .clip(CardShape) + .then( + if (selected) { + Modifier.border(1.5.dp, colors.primary, CardShape) + } else { + Modifier + }, + ) + .combinedClickable( + interactionSource = interactionSource, + indication = LocalIndication.current, + onClick = onClick, + onLongClickLabel = selectLabel, + onLongClick = { + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + onLongClick() + }, + ), + ) { + Row( + modifier = Modifier.padding(horizontal = 15.dp, vertical = 14.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.Top, + ) { + if (selecting) { + // The whole card toggles; the box is only the indicator. + Checkbox( + checked = selected, + onCheckedChange = null, + modifier = Modifier.padding(top = 9.dp), + ) + } + KindBadge(entry.summary?.kind) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(5.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = text.title(entry), + style = MaterialTheme.typography.titleMedium.copy( + fontSize = 15.5.sp, + lineHeight = 22.sp, + fontWeight = FontWeight.SemiBold, + ), + color = colors.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + text.status(entry)?.let { StatusTag(it) } + } + + val summary = entry.summary + if (summary == null) { + CircularProgressIndicator( + modifier = Modifier.padding(top = 4.dp).size(16.dp), + strokeWidth = 2.dp, + ) + } else { + val lines = remember(summary) { + RelayCardText.previewLines(summary) + .filter { it.isNotBlank() } + .take(2) + } + if (lines.isNotEmpty()) { + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + for (line in lines) { + PreviewLine(line) + } + } + } + + if (summary.mediaCount > 0 && summary.messageCount != null) { + MediaCountBadge(count = summary.mediaCount) + } + + Row( + modifier = Modifier + .fillMaxWidth() + .padding(top = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = text.metaLine(entry, summary), + style = MaterialTheme.typography.labelSmall.copy(fontSize = 11.5.sp), + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (!selecting) { + Spacer(Modifier.width(8.dp)) + QuickDeliverPill(onClick = onDeliverSingle) + } + } + } + } + } + } + } +} + +@Composable +private fun MediaCountBadge(count: Int) { + val appColors = LocalAppColors.current + val colors = MaterialTheme.colorScheme + Row( + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .background(appColors.surfaceSub) + .padding(horizontal = 7.dp, vertical = 2.5.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Icon( + imageVector = AppIcons.FileAttachment, + contentDescription = null, + tint = colors.onSurfaceVariant, + modifier = Modifier.size(12.dp), + ) + Text( + text = stringResource(R.string.relay_media_badge, count), + style = MaterialTheme.typography.labelSmall.copy(fontSize = 11.sp), + color = colors.onSurfaceVariant, + maxLines = 1, + ) + } +} + +@Composable +private fun QuickDeliverPill(onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val interactionSource = remember { MutableInteractionSource() } + Row( + modifier = Modifier + .pressScale(interactionSource, targetScale = 0.94f) + .clip(CircleShape) + .background(appColors.surfaceTint) + .border(0.75.dp, appColors.surfaceTintBorder, CircleShape) + .clickable( + interactionSource = interactionSource, + indication = LocalIndication.current, + role = Role.Button, + onClick = onClick, + ) + .padding(horizontal = 12.dp, vertical = 5.5.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + ) { + Text( + text = stringResource(R.string.relay_quick_deliver), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = colors.primary, + maxLines = 1, + ) + Icon( + imageVector = AppIcons.ArrowRight, + contentDescription = null, + tint = colors.primary, + modifier = Modifier.size(13.dp), + ) + } +} + +@Composable +private fun PreviewLine(line: String) { + Text( + text = line, + style = MaterialTheme.typography.bodySmall.copy( + fontSize = 13.sp, + lineHeight = 19.sp, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) +} + +/** Which kind of content a card holds, at a glance: 42dp 柔和渐变色块底托 + 矢量图标。 */ +@Composable +private fun KindBadge(kind: RelaySummary.Kind?) { + val (icon: ImageVector, tint: Color, description: Int) = when (kind) { + RelaySummary.Kind.CHAT -> Triple(AppIcons.ChatBubble, KindChatColor, R.string.relay_kind_chat_desc) + RelaySummary.Kind.LINK -> Triple(AppIcons.LinkChain, KindLinkColor, R.string.relay_kind_link_desc) + RelaySummary.Kind.TEXT -> Triple(AppIcons.NoteDocument, KindNoteColor, R.string.relay_kind_text_desc) + RelaySummary.Kind.FILES, null -> Triple(AppIcons.FileAttachment, KindFileColor, R.string.relay_kind_files_desc) + } + val label = stringResource(description) + val badgeShape = RoundedCornerShape(13.dp) + Box( + modifier = Modifier + .size(42.dp) + .clip(badgeShape) + .background( + Brush.linearGradient( + colors = listOf(tint.copy(alpha = 0.16f), tint.copy(alpha = 0.07f)), + ), + ) + .border(0.5.dp, tint.copy(alpha = 0.18f), badgeShape) + .semantics { contentDescription = label }, + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = tint, + modifier = Modifier.size(20.dp), + ) + } +} + +@Composable +private fun StatusTag(status: CardStatus) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + when (status.tone) { + StatusTone.Collecting -> { + // 降噪后的微灰淡青细小角标,避免多条记录同为收集中时满屏抢戏 + Row( + modifier = Modifier + .clip(CircleShape) + .background(appColors.surfaceSub) + .padding(horizontal = 7.dp, vertical = 2.5.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Box( + modifier = Modifier + .size(5.dp) + .clip(CircleShape) + .background(colors.primary.copy(alpha = 0.7f)), + ) + Text( + text = status.text, + style = MaterialTheme.typography.labelSmall.copy(fontSize = 11.sp), + color = colors.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + StatusTone.Quiet -> { + Text( + text = status.text, + style = MaterialTheme.typography.labelSmall.copy(fontSize = 11.sp), + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier + .clip(CircleShape) + .background(appColors.surfaceSub) + .padding(horizontal = 7.dp, vertical = 2.5.dp), + ) + } + StatusTone.Warning -> { + Text( + text = status.text, + style = MaterialTheme.typography.labelSmall.copy(fontSize = 11.sp), + color = colors.error, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier + .clip(CircleShape) + .background(colors.error.copy(alpha = 0.12f)) + .padding(horizontal = 7.dp, vertical = 2.5.dp), + ) + } + } +} + +/** An open collection: its own card above the batches, with a way to finish it. */ +@Composable +internal fun CollectionCard( + model: CollectionCardModel, + text: RelayCardText, + enabled: Boolean, + onOpen: () -> Unit, + onDeliver: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val name = model.collection.name.ifEmpty { stringResource(R.string.relay_collection_untitled) } + val summary = stringResource( + R.string.relay_collection_summary_compact, + model.batchIds.size, + model.messageCount, + ) + + val openInteraction = remember { MutableInteractionSource() } + + BridgeBentoCard( + modifier = modifier.fillMaxWidth(), + cornerRadius = 22.dp, + highlighted = true, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 15.dp), + ) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Column(verticalArrangement = Arrangement.spacedBy(5.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + PinnedBadge() + Text( + text = name, + style = MaterialTheme.typography.titleMedium.copy( + fontSize = 16.sp, + fontWeight = FontWeight.SemiBold, + ), + color = colors.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + CollectingPill() + } + Text( + text = summary, + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth(), + ) { + Box( + modifier = Modifier + .weight(1f) + .height(40.dp) + .alpha(if (enabled) 1f else 0.45f) + .pressScale(openInteraction, targetScale = 0.97f) + .clip(CircleShape) + .background(appColors.primarySoft) + .border(0.9.dp, appColors.surfaceTintBorder, CircleShape) + .clickable( + enabled = enabled, + interactionSource = openInteraction, + indication = LocalIndication.current, + role = Role.Button, + onClick = onOpen, + ) + .padding(horizontal = 14.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = stringResource(R.string.relay_collection_open), + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = colors.primary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + BridgePrimaryCapsuleButton( + text = stringResource(R.string.relay_collection_deliver), + onClick = onDeliver, + enabled = enabled, + height = 40.dp, + modifier = Modifier.weight(1f), + ) + } + } + } +} + +/** 置顶收集卡标题前的「置顶」小胶囊。 */ +@Composable +private fun PinnedBadge() { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + Text( + text = "置顶", + style = MaterialTheme.typography.labelSmall.copy( + fontSize = 10.5.sp, + fontWeight = FontWeight.SemiBold, + ), + color = colors.primary, + maxLines = 1, + modifier = Modifier + .clip(CircleShape) + .background(appColors.primarySoft) + .border(0.6.dp, appColors.surfaceTintBorder, CircleShape) + .padding(horizontal = 7.dp, vertical = 2.dp), + ) +} + +/** 置顶收集卡右上角胶囊:内嵌 1.8s 呼吸绿点。 */ +@Composable +private fun CollectingPill() { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + Row( + modifier = Modifier + .clip(CircleShape) + .background(appColors.primarySoft) + .padding(horizontal = 8.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + BreathingDot(color = colors.primary) + Text( + text = stringResource(R.string.relay_status_collecting), + style = MaterialTheme.typography.labelSmall.copy( + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + ), + color = colors.primary, + maxLines = 1, + ) + } +} + +/** 1.8s 极缓呼吸动效状态点(Robolectric 环境下静态展示,避免虚拟时钟卡顿)。 */ +@Composable +private fun BreathingDot(color: Color) { + val isRobolectric = remember { Build.FINGERPRINT.equals("robolectric", ignoreCase = true) } + val pulse = if (isRobolectric) { + 0.5f + } else { + val transition = rememberInfiniteTransition(label = "collectingBreath") + val animated by transition.animateFloat( + initialValue = 0f, + targetValue = 1f, + animationSpec = infiniteRepeatable( + animation = tween(durationMillis = 900, easing = FastOutSlowInEasing), + repeatMode = RepeatMode.Reverse, + ), + label = "breathPulse", + ) + animated + } + Box( + modifier = Modifier.size(12.dp), + contentAlignment = Alignment.Center, + ) { + Box( + modifier = Modifier + .size(12.dp) + .scale(0.75f + 0.3f * pulse) + .alpha(0.18f + 0.16f * pulse) + .clip(CircleShape) + .background(color), + ) + Box( + modifier = Modifier + .size(6.dp) + .clip(CircleShape) + .background(color), + ) + } +} + +// region Previews + +internal fun previewEntry( + summary: RelaySummary?, + targetName: String? = null, + delivered: Boolean = false, + collecting: Boolean = false, + itemNames: List = listOf("聊天记录.zip"), +): RelayEntry { + val id = UUID.randomUUID() + val created = Instant.parse("2026-11-24T08:30:00Z") + val items = itemNames.map { name -> + ReadyItem(UUID.randomUUID(), id, name, File(name), 1_024, null, created, ShareAction.CLAUDE) + } + val outcome = if (delivered) { + com.xiangming.wechatbridge.core.inbox.BatchOutcome( + kind = com.xiangming.wechatbridge.core.inbox.BatchOutcome.Kind.DELIVERED, + at = created, + ) + } else { + null + } + val batch = ReadyBatch(id, File("."), created, ShareAction.CLAUDE, items, outcome, targetName, isFirstSeen = false) + return RelayEntry(batch, summary, collecting) +} + +internal val previewChat = RelaySummary( + title = "产品讨论群", + messageCount = 86, + senders = listOf("小明", "小红"), + start = Instant.parse("2026-11-24T01:00:00Z"), + end = Instant.parse("2026-11-24T02:07:00Z"), + preview = listOf("小明:周五前把方案定下来", "小红:好的,我今晚补上数据"), + mediaCount = 3, + kind = RelaySummary.Kind.CHAT, + source = ShareSource.WECHAT, + last = RelaySummary.Last("小明", Instant.parse("2026-11-24T02:07:00Z"), "收到,谢谢大家"), +) + +internal val previewLink = RelaySummary( + title = "分享的链接", + preview = listOf("https://github.com/example/project/issues/1"), + kind = RelaySummary.Kind.TEXT, + source = ShareSource.WEB, +) + +internal val previewFiles = RelaySummary( + title = "2 个文件", + preview = listOf("报告.pdf", "截图.png"), + mediaCount = 2, + kind = RelaySummary.Kind.FILES, + source = ShareSource.FILES, +) + +@Composable +private fun PreviewCard(entry: RelayEntry, selecting: Boolean = false, selected: Boolean = false) { + val resources = LocalContext.current.resources + val text = remember { RelayCardText(resources, Instant.parse("2026-11-24T10:00:00Z"), ZoneId.of("Asia/Shanghai")) } + RelayCard( + entry = entry, + text = text, + selecting = selecting, + selected = selected, + onClick = {}, + onLongClick = {}, + onDeliverSingle = {}, + modifier = Modifier.padding(8.dp), + ) +} + +@Preview(name = "聊天记录卡", showBackground = true) +@Composable +private fun ChatCardPreview() = WeChatBridgeTheme { + PreviewCard(previewEntry(previewChat, targetName = "Claude", delivered = true)) +} + +@Preview(name = "文本/链接卡", showBackground = true) +@Composable +private fun LinkCardPreview() = WeChatBridgeTheme { + PreviewCard(previewEntry(previewLink, itemNames = listOf("分享的链接.txt"))) +} + +@Preview(name = "纯文件卡(选中)", showBackground = true) +@Composable +private fun FilesCardPreview() = WeChatBridgeTheme { + PreviewCard(previewEntry(previewFiles, itemNames = listOf("报告.pdf", "截图.png")), selecting = true, selected = true) +} + +@Preview(name = "收集卡", showBackground = true) +@Composable +private fun CollectionCardPreview() = WeChatBridgeTheme { + val resources = LocalContext.current.resources + val text = remember { RelayCardText(resources, Instant.parse("2026-11-24T10:00:00Z"), ZoneId.of("Asia/Shanghai")) } + CollectionCard( + model = CollectionCardModel( + collection = BatchCollection(name = "周会记录"), + batchIds = listOf(UUID.randomUUID(), UUID.randomUUID()), + messageCount = 180, + lastStart = previewChat.start, + lastEnd = previewChat.end, + ), + text = text, + enabled = true, + onOpen = {}, + onDeliver = {}, + modifier = Modifier.padding(8.dp), + ) +} + +// endregion diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayScreen.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayScreen.kt new file mode 100644 index 00000000..b5cf620c --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayScreen.kt @@ -0,0 +1,1479 @@ +package com.xiangming.wechatbridge.ui.relay + +import android.content.ClipboardManager +import android.content.Context +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.bubble.BubbleService +import com.xiangming.wechatbridge.bubble.OverlayPermission +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.receive.ContentStreamItem +import com.xiangming.wechatbridge.receive.DropDestination +import com.xiangming.wechatbridge.receive.message +import com.xiangming.wechatbridge.ui.drop.DropResultsEffect +import com.xiangming.wechatbridge.ui.drop.DropTargetBox +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.AppMotion +import com.xiangming.wechatbridge.ui.theme.BridgeAmbientBackdrop +import com.xiangming.wechatbridge.ui.theme.BridgeBentoCard +import com.xiangming.wechatbridge.ui.theme.BridgeTopBarScrim +import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface +import com.xiangming.wechatbridge.ui.theme.BridgePrimaryCapsuleButton +import com.xiangming.wechatbridge.ui.theme.KindFileColor +import com.xiangming.wechatbridge.ui.theme.KindNoteColor +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import com.xiangming.wechatbridge.ui.theme.pressScale +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch +import java.time.Instant +import java.time.ZoneId +import java.util.UUID + +/** 中转站列表。参数签名由 AppNav 固定。 */ +@Composable +fun RelayScreen( + onOpenBatch: (batchId: String) -> Unit, + onDeliver: (batchIds: List) -> Unit, + onOpenCollection: (collectionId: String) -> Unit, + onOpenScenes: () -> Unit, + onOpenSettings: () -> Unit, +) { + val context = LocalContext.current + val container = (context.applicationContext as App).container + val viewModel = viewModel { RelayViewModel(container.relayStore, container.uriImporter, container.appScope) } + val state by viewModel.state.collectAsStateWithLifecycle() + val allEntries by container.relayStore.entries.collectAsStateWithLifecycle() + val allCollections by container.relayStore.collections.collectAsStateWithLifecycle() + val undeliveredCount = remember(allEntries) { allEntries.count { !it.isDelivered } } + val collectingCount = remember(allCollections, allEntries) { + val entryIds = allEntries.mapTo(mutableSetOf()) { it.id } + allCollections.count { collection -> collection.batchIDs.any { it in entryIds } } + } + + val bubbleEnabled by container.bubbleSettings.enabled.collectAsStateWithLifecycle() + var canDrawOverlay by remember { mutableStateOf(OverlayPermission.canDraw(context)) } + var pendingBubbleEnable by remember { mutableStateOf(false) } + + val snackbarHostState = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val resources = context.resources + + LifecycleResumeEffect(Unit) { + val granted = OverlayPermission.canDraw(context) + canDrawOverlay = granted + if (pendingBubbleEnable && granted) { + pendingBubbleEnable = false + container.bubbleSettings.setEnabled(true) + BubbleService.sync(context) + } else if (pendingBubbleEnable) { + pendingBubbleEnable = false + } + onPauseOrDispose {} + } + + val bubbleActive = bubbleEnabled && canDrawOverlay + + val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> + viewModel.importFiles(uris.map { ContentStreamItem(context.contentResolver, it, null) }) + } + + LaunchedEffect(viewModel) { + viewModel.events.collectLatest { event -> + when (event) { + is RelayEvent.Deleted -> showUndo( + snackbarHostState, + resources.getString(R.string.relay_deleted, event.count), + resources.getString(R.string.relay_undo), + onUndo = viewModel::undoDelete, + ) + is RelayEvent.Imported -> + snackbarHostState.showSnackbar(resources.getString(R.string.relay_imported, event.itemCount)) + is RelayEvent.ImportFailed -> + snackbarHostState.showSnackbar(event.failure.message(resources), duration = SnackbarDuration.Long) + RelayEvent.ClipboardEmpty -> + snackbarHostState.showSnackbar(resources.getString(R.string.relay_clipboard_empty)) + is RelayEvent.Error -> snackbarHostState.showSnackbar( + resources.getString(R.string.relay_error, event.message ?: resources.getString(R.string.relay_error_unknown)), + duration = SnackbarDuration.Long, + ) + } + } + } + + DropResultsEffect(snackbarHostState) + + // Small window / split screen: files, images, text and links dragged in from another app become a batch. + DropTargetBox(destination = DropDestination.Relay, modifier = Modifier.fillMaxSize()) { + RelayContent( + state = state, + snackbarHostState = snackbarHostState, + onFilter = viewModel::setFilter, + onQueryChange = viewModel::setQuery, + onOpenEntry = { id -> onOpenBatch(id.toString()) }, + onToggle = viewModel::toggle, + onSelectAll = viewModel::selectAll, + onClearSelection = viewModel::clearSelection, + onDeliverSelected = { onDeliver(viewModel.takeSelectionForDelivery()) }, + onDeleteSelected = viewModel::deleteSelected, + onOpenCollection = { id -> onOpenCollection(id.toString()) }, + onDeliverCollection = { ids -> onDeliver(ids.map(UUID::toString)) }, + onOpenScenes = onOpenScenes, + onOpenSettings = onOpenSettings, + onImportFiles = { picker.launch(arrayOf("*/*")) }, + onImportClipboard = { viewModel.importText(readClipboardText(context)) }, + undeliveredCount = undeliveredCount, + collectingCount = collectingCount, + bubbleActive = bubbleActive, + onToggleBubble = { + if (bubbleActive) { + container.bubbleSettings.setEnabled(false) + BubbleService.sync(context) + } else if (OverlayPermission.canDraw(context)) { + canDrawOverlay = true + container.bubbleSettings.setEnabled(true) + BubbleService.sync(context) + } else { + pendingBubbleEnable = true + val launched = runCatching { + context.startActivity(OverlayPermission.settingsIntent(context)) + true + }.getOrDefault(false) + if (!launched) { + pendingBubbleEnable = false + scope.launch { + snackbarHostState.showSnackbar(resources.getString(R.string.relay_bubble_permission_hint)) + } + } + } + }, + onDeliverSingle = { id -> onDeliver(listOf(id.toString())) }, + ) + } +} + +/** The undo toast closes with the store's undo window: after that the files are really gone. */ +private suspend fun showUndo(host: SnackbarHostState, message: String, undo: String, onUndo: () -> Unit) { + coroutineScope { + val timer = launch { + delay(RelayStore.UNDO_WINDOW) + host.currentSnackbarData?.dismiss() + } + val result = host.showSnackbar(message, actionLabel = undo, withDismissAction = false, duration = SnackbarDuration.Indefinite) + timer.cancel() + if (result == SnackbarResult.ActionPerformed) onUndo() + } +} + +private fun readClipboardText(context: Context): String? { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return null + val clip = clipboard.primaryClip?.takeIf { it.itemCount > 0 } ?: return null + return clip.getItemAt(0).coerceToText(context)?.toString() +} + +/** Stateless body of the screen, so previews can drive it. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun RelayContent( + state: RelayUiState, + snackbarHostState: SnackbarHostState, + onFilter: (RelayFilter) -> Unit, + onQueryChange: (String) -> Unit = {}, + onOpenEntry: (UUID) -> Unit, + onToggle: (UUID) -> Unit, + onSelectAll: () -> Unit, + onClearSelection: () -> Unit, + onDeliverSelected: () -> Unit, + onDeleteSelected: () -> Unit, + onOpenCollection: (UUID) -> Unit, + onDeliverCollection: (List) -> Unit, + onOpenScenes: () -> Unit = {}, + onOpenSettings: () -> Unit = {}, + onImportFiles: () -> Unit, + onImportClipboard: () -> Unit, + now: Instant = Instant.now(), + undeliveredCount: Int = state.entries.count { !it.isDelivered }, + collectingCount: Int = state.collections.size, + bubbleActive: Boolean = false, + onToggleBubble: () -> Unit = {}, + onDeliverSingle: (UUID) -> Unit = {}, +) { + val resources = LocalContext.current.resources + val zone = remember { ZoneId.systemDefault() } + val cardText = remember(resources, now, zone) { RelayCardText(resources, now, zone) } + + var manualSelecting by remember { mutableStateOf(false) } + var showAddSheet by remember { mutableStateOf(false) } + // Saved, not just remembered: after a rotation the bar must still be there for the keyword + // the view model kept, or the list would stay narrowed with nothing showing why. + var searchActive by rememberSaveable { mutableStateOf(false) } + val listState = rememberLazyListState() + val scrolled by remember { + derivedStateOf { + listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 0 + } + } + + LaunchedEffect(searchActive) { + if (!searchActive) listState.animateScrollToItem(0) + } + + val isSelecting = state.selecting || manualSelecting + val searchOn = searchActive && !isSelecting + + fun exitSelection() { + manualSelecting = false + onClearSelection() + } + + fun collapseSearch() { + searchActive = false + onQueryChange("") + } + + // 多选态优先退出;再按一次才收起搜索(搜索开着时进入多选也成立)。 + BackHandler(enabled = searchOn, onBack = ::collapseSearch) + BackHandler(enabled = isSelecting, onBack = ::exitSelection) + + Box(modifier = Modifier.fillMaxSize()) { + BridgeAmbientBackdrop() + Scaffold( + modifier = Modifier.fillMaxSize(), + containerColor = Color.Transparent, + contentWindowInsets = WindowInsets(0, 0, 0, 0), + topBar = { + AnimatedContent( + targetState = when { + isSelecting -> RelayTopBarMode.Selecting + searchActive -> RelayTopBarMode.Search + else -> RelayTopBarMode.Normal + }, + transitionSpec = { + fadeIn(tween(AppMotion.TAB_FADE_MS)) togetherWith fadeOut(tween(90)) + }, + label = "relayTopBar", + ) { mode -> + when (mode) { + RelayTopBarMode.Selecting -> SelectionTopBar( + selectedCount = state.selection.size, + onCancel = ::exitSelection, + onSelectAll = onSelectAll, + ) + RelayTopBarMode.Search -> RelaySearchBar( + query = state.query, + onQueryChange = onQueryChange, + onCollapse = ::collapseSearch, + ) + RelayTopBarMode.Normal -> RelayHeaderBar( + bubbleActive = bubbleActive, + onToggleBubble = onToggleBubble, + onOpenAdd = { showAddSheet = true }, + onOpenSearch = { searchActive = true }, + ) + } + } + }, + bottomBar = { + AnimatedVisibility( + visible = isSelecting, + enter = slideInVertically(tween(220)) { it } + fadeIn(tween(150)), + exit = slideOutVertically(tween(180)) { it } + fadeOut(tween(120)), + ) { + SelectionBar( + selectedCount = state.selection.size, + hasSelection = state.selection.isNotEmpty(), + onDeliver = { + manualSelecting = false + onDeliverSelected() + }, + onDelete = { + manualSelecting = false + onDeleteSelected() + }, + ) + } + }, + snackbarHost = { + SnackbarHost( + hostState = snackbarHostState, + modifier = Modifier.navigationBarsPadding().padding(bottom = 88.dp), + ) + }, + ) { padding -> + Column(modifier = Modifier.padding(padding).fillMaxSize()) { + if (state.importing) { + LinearProgressIndicator( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + trackColor = LocalAppColors.current.primarySoft, + ) + } + when { + state.isEmpty -> EmptyRelay(modifier = Modifier.weight(1f)) + else -> { + Box(modifier = Modifier.weight(1f)) { + RelayList( + state = state, + isSelecting = isSelecting, + searchActive = searchActive, + listState = listState, + undeliveredCount = undeliveredCount, + collectingCount = collectingCount, + cardText = cardText, + onSelectFilter = { + manualSelecting = false + onFilter(it) + }, + onEnterSelect = { manualSelecting = true }, + onClearQuery = { onQueryChange("") }, + onOpenEntry = onOpenEntry, + onToggle = onToggle, + onDeliverSingle = onDeliverSingle, + onOpenCollection = onOpenCollection, + onDeliverCollection = onDeliverCollection, + modifier = Modifier.fillMaxSize(), + ) + // 顶栏与列表之间有 Scaffold 裁切边界;渐变必须覆盖内容区,而不是画在顶栏里。 + BridgeTopBarScrim( + visible = scrolled, + modifier = Modifier.align(Alignment.TopCenter), + ) + } + } + } + } + } + } + + if (showAddSheet) { + AddImportSheet( + onDismiss = { showAddSheet = false }, + onImportFiles = { + showAddSheet = false + onImportFiles() + }, + onImportClipboard = { + showAddSheet = false + onImportClipboard() + }, + ) + } +} + +/** 顶栏的三种形态:普通(含搜索入口)、关键词搜索、多选。 */ +private enum class RelayTopBarMode { Normal, Search, Selecting } + +@Composable +private fun RelayHeaderBar( + bubbleActive: Boolean, + onToggleBubble: () -> Unit, + onOpenAdd: () -> Unit, + onOpenSearch: () -> Unit, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .statusBarsPadding() + .padding(start = 20.dp, end = 16.dp, top = 14.dp, bottom = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(R.string.nav_relay), + style = MaterialTheme.typography.headlineMedium, + color = MaterialTheme.colorScheme.onBackground, + modifier = Modifier.weight(1f), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + BubbleQuickChip(active = bubbleActive, onClick = onToggleBubble) + Spacer(Modifier.width(10.dp)) + SearchIconButton(onClick = onOpenSearch) + Spacer(Modifier.width(10.dp)) + AddIconButton(onClick = onOpenAdd) + } +} + +/** 顶栏搜索入口:与「+」同款的轻盈白卡小方块。 */ +@Composable +private fun SearchIconButton(onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val interactionSource = remember { MutableInteractionSource() } + val description = stringResource(R.string.relay_search) + val shape = RoundedCornerShape(12.dp) + + Surface( + modifier = Modifier + .size(36.dp) + .pressScale(interactionSource, targetScale = 0.92f) + .clip(shape) + .clickable( + interactionSource = interactionSource, + indication = LocalIndication.current, + role = Role.Button, + onClick = onClick, + ) + .semantics { contentDescription = description }, + shape = shape, + color = colors.surface, + border = BorderStroke(1.dp, appColors.subtleDivider), + shadowElevation = if (appColors.isDark) 0.dp else 1.dp, + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = AppIcons.Search, + contentDescription = null, + tint = colors.onSurface, + modifier = Modifier.size(19.dp), + ) + } + } +} + +/** + * 搜索态顶栏:轻盈圆角输入框 + 一键清空 + 收起。 + * 打开即聚焦并弹起键盘;收起时清空搜索词,列表恢复全部。 + */ +@Composable +internal fun RelaySearchBar( + query: String, + onQueryChange: (String) -> Unit, + onCollapse: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val focusRequester = remember { FocusRequester() } + val clearLabel = stringResource(R.string.relay_search_clear) + + LaunchedEffect(Unit) { focusRequester.requestFocus() } + + Row( + modifier = Modifier + .fillMaxWidth() + .statusBarsPadding() + .padding(start = 12.dp, end = 8.dp, top = 10.dp, bottom = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Surface( + modifier = Modifier.weight(1f).height(40.dp), + shape = RoundedCornerShape(20.dp), + color = colors.surface, + border = BorderStroke(1.dp, appColors.subtleDivider), + shadowElevation = if (appColors.isDark) 0.dp else 1.dp, + ) { + Row( + modifier = Modifier.padding(start = 13.dp, end = 5.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + imageVector = AppIcons.Search, + contentDescription = null, + tint = appColors.onSurfaceMuted, + modifier = Modifier.size(17.dp), + ) + Spacer(Modifier.width(8.dp)) + BasicTextField( + value = query, + onValueChange = onQueryChange, + modifier = Modifier + .weight(1f) + .focusRequester(focusRequester), + singleLine = true, + textStyle = MaterialTheme.typography.bodyMedium.copy(color = colors.onSurface), + cursorBrush = SolidColor(colors.primary), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + decorationBox = { inner -> + Box(contentAlignment = Alignment.CenterStart) { + if (query.isEmpty()) { + Text( + text = stringResource(R.string.relay_search_hint), + style = MaterialTheme.typography.bodyMedium, + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + inner() + } + }, + ) + if (query.isNotEmpty()) { + IconButton( + onClick = { onQueryChange("") }, + modifier = Modifier + .size(30.dp) + .semantics { contentDescription = clearLabel }, + ) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = null, + tint = appColors.onSurfaceMuted, + modifier = Modifier.size(15.dp), + ) + } + } else { + Spacer(Modifier.width(8.dp)) + } + } + } + TextButton( + onClick = onCollapse, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp), + ) { + Text( + text = stringResource(R.string.relay_search_collapse), + style = MaterialTheme.typography.labelLarge, + color = colors.onSurfaceVariant, + maxLines = 1, + ) + } + } +} + +@Composable +private fun BubbleQuickChip(active: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val interactionSource = remember { MutableInteractionSource() } + val bgColor by animateColorAsState( + targetValue = if (active) appColors.surfaceTint else colors.surface, + animationSpec = tween(180), + label = "bubbleChipBg", + ) + val dotColor by animateColorAsState( + targetValue = if (active) colors.primary else appColors.onSurfaceMuted, + animationSpec = tween(180), + label = "bubbleChipDot", + ) + val textColor by animateColorAsState( + targetValue = if (active) colors.primary else colors.onSurfaceVariant, + animationSpec = tween(180), + label = "bubbleChipText", + ) + val borderColor = if (active) appColors.surfaceTintBorder else appColors.subtleDivider + + Surface( + modifier = Modifier + .pressScale(interactionSource, targetScale = 0.94f) + .clip(CircleShape) + .clickable( + interactionSource = interactionSource, + indication = LocalIndication.current, + role = Role.Switch, + onClick = onClick, + ), + shape = CircleShape, + color = bgColor, + border = BorderStroke(1.dp, borderColor), + shadowElevation = if (appColors.isDark || active) 0.dp else 1.dp, + ) { + Row( + modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Box( + modifier = Modifier + .size(7.dp) + .clip(CircleShape) + .background(dotColor), + ) + Text( + text = stringResource(R.string.relay_bubble_chip), + style = MaterialTheme.typography.labelMedium, + fontWeight = if (active) FontWeight.SemiBold else FontWeight.Medium, + color = textColor, + maxLines = 1, + ) + } + } +} + +@Composable +private fun AddIconButton(onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val interactionSource = remember { MutableInteractionSource() } + val description = stringResource(R.string.relay_add) + val shape = RoundedCornerShape(12.dp) + + Surface( + modifier = Modifier + .size(36.dp) + .pressScale(interactionSource, targetScale = 0.92f) + .clip(shape) + .clickable( + interactionSource = interactionSource, + indication = LocalIndication.current, + role = Role.Button, + onClick = onClick, + ) + .semantics { contentDescription = description }, + shape = shape, + color = colors.surface, + border = BorderStroke(1.dp, appColors.subtleDivider), + shadowElevation = if (appColors.isDark) 0.dp else 1.dp, + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Filled.Add, + contentDescription = null, + tint = colors.onSurface, + modifier = Modifier.size(20.dp), + ) + } + } +} + +@Composable +private fun SelectionTopBar( + selectedCount: Int, + onCancel: () -> Unit, + onSelectAll: () -> Unit, +) { + val description = stringResource(R.string.relay_clear_selection) + Row( + modifier = Modifier + .fillMaxWidth() + .statusBarsPadding() + .padding(horizontal = 8.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton( + onClick = onCancel, + modifier = Modifier.semantics { contentDescription = description }, + ) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = null, + tint = MaterialTheme.colorScheme.onBackground, + ) + } + Text( + text = stringResource(R.string.relay_selected_count, selectedCount), + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onBackground, + modifier = Modifier.weight(1f), + maxLines = 1, + ) + TextButton(onClick = onSelectAll) { + Text( + text = stringResource(R.string.relay_select_all), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + ) + } + } +} + +@Composable +private fun RelayBentoOverview( + selectedFilter: RelayFilter, + undeliveredCount: Int, + collectingCount: Int, + totalCount: Int, + onSelectFilter: (RelayFilter) -> Unit, +) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val isUndeliveredActive = selectedFilter == RelayFilter.UNDELIVERED + val isCollectingMode = collectingCount > 0 + val isCollectingActive = selectedFilter == RelayFilter.COLLECTING + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + // 左卡:待投递(品牌绿柔和顶光,点击在「未投递 / 全部」之间切换) + BridgeBentoCard( + modifier = Modifier.weight(1f), + cornerRadius = 20.dp, + highlighted = true, + contentPadding = PaddingValues(14.dp), + onClick = { + onSelectFilter( + if (isUndeliveredActive) RelayFilter.ALL else RelayFilter.UNDELIVERED, + ) + }, + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = "待投递", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = colors.onSurface, + maxLines = 1, + ) + Box( + modifier = Modifier + .size(26.dp) + .clip(CircleShape) + .background(if (isUndeliveredActive) colors.primary else appColors.primarySoft), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = AppIcons.ArrowRight, + contentDescription = null, + tint = if (isUndeliveredActive) Color.White else colors.primary, + modifier = Modifier.size(14.dp), + ) + } + } + Spacer(Modifier.height(8.dp)) + Text( + text = undeliveredCount.toString(), + style = MaterialTheme.typography.headlineMedium.copy( + fontSize = 28.sp, + lineHeight = 32.sp, + fontWeight = FontWeight.Bold, + ), + color = colors.primary, + maxLines = 1, + ) + Spacer(Modifier.height(4.dp)) + Text( + text = if (isUndeliveredActive) "已筛选 · 点此看全部" else "点击只看待投递", + style = MaterialTheme.typography.labelSmall.copy(fontSize = 11.5.sp), + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + + // 右卡:收集中批次数(有收集时)或全部记录总数 + BridgeBentoCard( + modifier = Modifier.weight(1f), + cornerRadius = 20.dp, + highlighted = false, + contentPadding = PaddingValues(14.dp), + onClick = { + if (isCollectingMode) { + onSelectFilter(if (isCollectingActive) RelayFilter.ALL else RelayFilter.COLLECTING) + } else { + onSelectFilter(RelayFilter.ALL) + } + }, + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = if (isCollectingMode) "收集中" else "全部记录", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = colors.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Spacer(Modifier.width(6.dp)) + Row( + modifier = Modifier + .clip(CircleShape) + .background( + if (isCollectingMode && isCollectingActive) { + colors.primary + } else if (isCollectingMode) { + appColors.primarySoft + } else { + appColors.surfaceSub + }, + ) + .padding(horizontal = 7.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + if (isCollectingMode) { + Box( + modifier = Modifier + .size(5.dp) + .clip(CircleShape) + .background(if (isCollectingActive) Color.White else colors.primary), + ) + } + Text( + text = if (isCollectingMode) { + stringResource(R.string.relay_status_collecting) + } else { + stringResource(R.string.relay_filter_all) + }, + style = MaterialTheme.typography.labelSmall.copy( + fontSize = 10.5.sp, + fontWeight = FontWeight.Medium, + ), + color = when { + isCollectingMode && isCollectingActive -> Color.White + isCollectingMode -> colors.primary + else -> colors.onSurfaceVariant + }, + maxLines = 1, + ) + } + } + Spacer(Modifier.height(8.dp)) + Text( + text = (if (isCollectingMode) collectingCount else totalCount).toString(), + style = MaterialTheme.typography.headlineMedium.copy( + fontSize = 28.sp, + lineHeight = 32.sp, + fontWeight = FontWeight.Bold, + ), + color = colors.onSurface, + maxLines = 1, + ) + Spacer(Modifier.height(4.dp)) + Text( + text = if (isCollectingMode) { + if (isCollectingActive) "已筛选 · 点此看全部" else "分批收集进行中" + } else { + "累计中转批次" + }, + style = MaterialTheme.typography.labelSmall.copy(fontSize = 11.5.sp), + color = appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + +@Composable +private fun FilterBar( + selected: RelayFilter, + undeliveredCount: Int, + canSelect: Boolean, + onSelectFilter: (RelayFilter) -> Unit, + onEnterSelect: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + BridgeGlassSurface( + modifier = Modifier.weight(1f), + shape = CircleShape, + shadowElevation = 6.dp, + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(4.dp), + horizontalArrangement = Arrangement.spacedBy(2.dp), + ) { + for (filter in RelayFilter.entries) { + val isSelected = filter == selected + val label = when (filter) { + RelayFilter.ALL -> stringResource(R.string.relay_filter_all) + RelayFilter.UNDELIVERED -> if (undeliveredCount > 0) { + stringResource(R.string.relay_filter_undelivered_count, undeliveredCount) + } else { + stringResource(R.string.relay_filter_undelivered) + } + RelayFilter.COLLECTING -> stringResource(R.string.relay_filter_collecting) + } + val pillColor by animateColorAsState( + targetValue = if (isSelected) colors.primary else Color.Transparent, + animationSpec = tween(160), + label = "segmentPill", + ) + val textColor by animateColorAsState( + targetValue = if (isSelected) Color.White else colors.onSurfaceVariant, + animationSpec = tween(150), + label = "segmentText", + ) + Box( + modifier = Modifier + .weight(1f) + .clip(CircleShape) + .background(pillColor) + .clickable(role = Role.Tab) { onSelectFilter(filter) } + .semantics { this.selected = isSelected } + .padding(horizontal = 6.dp, vertical = 8.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = label, + style = MaterialTheme.typography.labelMedium, + fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium, + color = textColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + TextButton( + onClick = onEnterSelect, + enabled = canSelect, + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp), + ) { + Text( + text = stringResource(R.string.relay_action_select), + style = MaterialTheme.typography.labelLarge, + color = if (canSelect) colors.primary else appColors.onSurfaceMuted, + ) + } + } +} + +@Composable +private fun RelayList( + state: RelayUiState, + isSelecting: Boolean, + searchActive: Boolean, + listState: LazyListState, + undeliveredCount: Int, + collectingCount: Int, + cardText: RelayCardText, + onSelectFilter: (RelayFilter) -> Unit, + onEnterSelect: () -> Unit, + onClearQuery: () -> Unit, + onOpenEntry: (UUID) -> Unit, + onToggle: (UUID) -> Unit, + onDeliverSingle: (UUID) -> Unit, + onOpenCollection: (UUID) -> Unit, + onDeliverCollection: (List) -> Unit, + modifier: Modifier = Modifier, +) { + val navBottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + LazyColumn( + state = listState, + modifier = modifier.fillMaxSize(), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 6.dp, bottom = 116.dp + navBottom), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (!isSelecting) { + // 搜索态连空白关键词也收起统计卡,给键盘上方的结果留出空间。 + if (!searchActive && state.query.isBlank()) { + item(key = "bento-overview") { + RelayBentoOverview( + selectedFilter = state.filter, + undeliveredCount = undeliveredCount, + collectingCount = collectingCount, + totalCount = state.totalCount, + onSelectFilter = onSelectFilter, + ) + } + } + item(key = "filter-bar") { + FilterBar( + selected = state.filter, + undeliveredCount = undeliveredCount, + canSelect = state.entries.isNotEmpty(), + onSelectFilter = onSelectFilter, + onEnterSelect = onEnterSelect, + ) + } + } + if (state.entries.isEmpty() && state.collections.isEmpty()) { + item(key = "empty-result") { + if (state.query.isNotBlank()) { + EmptySearch( + keyword = state.query.trim(), + onClear = onClearQuery, + ) + } else { + EmptyFiltered() + } + } + } else { + items(state.collections, key = { "collection-${it.collection.id}" }) { model -> + CollectionCard( + model = model, + text = cardText, + enabled = !isSelecting, + onOpen = { onOpenCollection(model.collection.id) }, + onDeliver = { onDeliverCollection(model.batchIds) }, + modifier = Modifier.animateItem(), + ) + } + items(state.entries, key = { it.id }) { entry -> + RelayCard( + entry = entry, + text = cardText, + selecting = isSelecting, + selected = entry.id in state.selection, + onClick = { if (isSelecting) onToggle(entry.id) else onOpenEntry(entry.id) }, + onLongClick = { if (!isSelecting) onToggle(entry.id) }, + onDeliverSingle = { onDeliverSingle(entry.id) }, + modifier = Modifier.animateItem(), + ) + } + } + } +} + +/** 多选悬浮玻璃操作胶囊条:删除按钮 + 已选计数 + 品牌绿合并投递胶囊。 */ +@Composable +private fun SelectionBar( + selectedCount: Int, + hasSelection: Boolean, + onDeliver: () -> Unit, + onDelete: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val deleteInteraction = remember { MutableInteractionSource() } + + Box( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(start = 16.dp, end = 16.dp, top = 6.dp, bottom = 92.dp), + ) { + BridgeGlassSurface( + modifier = Modifier.fillMaxWidth(), + shape = CircleShape, + shadowElevation = 14.dp, + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 10.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Row( + modifier = Modifier + .height(42.dp) + .alpha(if (hasSelection) 1f else 0.42f) + .pressScale(deleteInteraction, targetScale = 0.95f) + .clip(CircleShape) + .background(colors.error.copy(alpha = 0.12f)) + .clickable( + enabled = hasSelection, + interactionSource = deleteInteraction, + indication = LocalIndication.current, + role = Role.Button, + onClick = onDelete, + ) + .padding(horizontal = 14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + Icon( + imageVector = Icons.Filled.Delete, + contentDescription = null, + tint = colors.error, + modifier = Modifier.size(16.dp), + ) + Text( + text = stringResource(R.string.relay_action_delete), + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = colors.error, + maxLines = 1, + ) + } + + Spacer(Modifier.weight(1f)) + + BridgePrimaryCapsuleButton( + text = stringResource(R.string.relay_action_merge_deliver), + onClick = onDeliver, + enabled = hasSelection, + height = 42.dp, + ) + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun AddImportSheet( + onDismiss: () -> Unit, + onImportFiles: () -> Unit, + onImportClipboard: () -> Unit, +) { + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = sheetState, + containerColor = MaterialTheme.colorScheme.surface, + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(start = 20.dp, end = 20.dp, bottom = 28.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text( + text = stringResource(R.string.relay_add_sheet_title), + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(bottom = 4.dp), + ) + ImportSheetRow( + icon = AppIcons.FileAttachment, + tint = KindFileColor, + title = stringResource(R.string.relay_import_files), + subtitle = stringResource(R.string.relay_import_files_desc), + onClick = onImportFiles, + ) + ImportSheetRow( + icon = AppIcons.NoteDocument, + tint = KindNoteColor, + title = stringResource(R.string.relay_import_clipboard), + subtitle = stringResource(R.string.relay_import_clipboard_desc), + onClick = onImportClipboard, + ) + } + } +} + +@Composable +private fun ImportSheetRow( + icon: ImageVector, + tint: Color, + title: String, + subtitle: String, + onClick: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + val interactionSource = remember { MutableInteractionSource() } + val shape = RoundedCornerShape(16.dp) + + Row( + modifier = Modifier + .fillMaxWidth() + .pressScale(interactionSource, targetScale = 0.98f) + .clip(shape) + .background(appColors.surfaceSub) + .clickable( + interactionSource = interactionSource, + indication = LocalIndication.current, + role = Role.Button, + onClick = onClick, + ) + .padding(horizontal = 14.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + ) { + Box( + modifier = Modifier + .size(42.dp) + .clip(RoundedCornerShape(12.dp)) + .background(tint.copy(alpha = 0.14f)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = tint, + modifier = Modifier.size(21.dp), + ) + } + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + text = title, + style = MaterialTheme.typography.titleMedium, + color = colors.onSurface, + ) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + ) + } + Icon( + imageVector = AppIcons.ChevronRight, + contentDescription = null, + tint = appColors.onSurfaceMuted, + modifier = Modifier.size(18.dp), + ) + } +} + +/** Nothing at all yet: say how things get here. */ +@Composable +private fun EmptyRelay(modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + Column( + modifier = modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .navigationBarsPadding() + .padding(start = 32.dp, end = 32.dp, top = 24.dp, bottom = 110.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box( + modifier = Modifier + .size(64.dp) + .clip(RoundedCornerShape(20.dp)) + .background(appColors.surfaceTint) + .border(1.dp, appColors.surfaceTintBorder, RoundedCornerShape(20.dp)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = AppIcons.NavRelay, + contentDescription = null, + tint = colors.primary, + modifier = Modifier.size(30.dp), + ) + } + Text( + stringResource(R.string.relay_empty_title), + style = MaterialTheme.typography.titleLarge, + color = colors.onBackground, + modifier = Modifier.padding(top = 16.dp), + ) + Text( + stringResource(R.string.relay_empty_body), + style = MaterialTheme.typography.bodyMedium, + color = colors.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 12.dp), + ) + Text( + stringResource(R.string.relay_empty_body_more), + style = MaterialTheme.typography.bodyMedium, + color = colors.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 8.dp), + ) + } +} + +@Composable +private fun EmptyFiltered(modifier: Modifier = Modifier) { + Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text( + stringResource(R.string.relay_empty_filtered), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/** 搜索进行中但没有命中:提示换词或清空,与整体空状态区分。 */ +/** 搜索无结果:回显关键词,并给一个直接清空的出口。 */ +@Composable +private fun EmptySearch(keyword: String, onClear: () -> Unit, modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + val appColors = LocalAppColors.current + Column( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 32.dp, vertical = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box( + modifier = Modifier + .size(64.dp) + .clip(RoundedCornerShape(20.dp)) + .background(appColors.surfaceTint) + .border(1.dp, appColors.surfaceTintBorder, RoundedCornerShape(20.dp)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = AppIcons.Search, + contentDescription = null, + tint = colors.primary, + modifier = Modifier.size(28.dp), + ) + } + Text( + stringResource(R.string.relay_search_empty_title, keyword), + style = MaterialTheme.typography.titleLarge, + color = colors.onBackground, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 16.dp), + ) + TextButton(onClick = onClear, modifier = Modifier.padding(top = 4.dp)) { + Text( + stringResource(R.string.relay_search_clear), + style = MaterialTheme.typography.labelLarge, + color = colors.primary, + ) + } + } +} + +// region Previews + +@Composable +private fun PreviewContent(state: RelayUiState) { + RelayContent( + state = state, + snackbarHostState = remember { SnackbarHostState() }, + onFilter = {}, + onOpenEntry = {}, + onToggle = {}, + onSelectAll = {}, + onClearSelection = {}, + onDeliverSelected = {}, + onDeleteSelected = {}, + onOpenCollection = {}, + onDeliverCollection = {}, + onOpenScenes = {}, + onOpenSettings = {}, + onImportFiles = {}, + onImportClipboard = {}, + now = Instant.parse("2026-11-24T10:00:00Z"), + undeliveredCount = 2, + bubbleActive = true, + ) +} + +@Preview(name = "空状态", showBackground = true, heightDp = 640) +@Composable +private fun EmptyPreview() = WeChatBridgeTheme { PreviewContent(RelayUiState()) } + +@Preview(name = "三种卡片", showBackground = true, heightDp = 640) +@Composable +private fun ListPreview() = WeChatBridgeTheme { + val chat = previewEntry(previewChat, targetName = "Claude", delivered = true) + PreviewContent( + RelayUiState( + entries = listOf( + chat, + previewEntry(previewLink, itemNames = listOf("分享的链接.txt")), + previewEntry(previewFiles, itemNames = listOf("报告.pdf", "截图.png"), collecting = true), + ), + totalCount = 3, + ), + ) +} + +@Preview(name = "搜索无结果", showBackground = true, heightDp = 640) +@Composable +private fun SearchEmptyPreview() = WeChatBridgeTheme { + PreviewContent(RelayUiState(totalCount = 2, query = "不存在的关键词")) +} + +@Preview(name = "多选", showBackground = true, heightDp = 640) +@Composable +private fun SelectingPreview() = WeChatBridgeTheme { + val chat = previewEntry(previewChat) + PreviewContent( + RelayUiState( + entries = listOf(chat, previewEntry(previewLink, itemNames = listOf("分享的链接.txt"))), + totalCount = 2, + selection = setOf(chat.id), + ), + ) +} + +// endregion diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayViewModel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayViewModel.kt new file mode 100644 index 00000000..ab700925 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/relay/RelayViewModel.kt @@ -0,0 +1,271 @@ +package com.xiangming.wechatbridge.ui.relay + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.core.collection.BatchCollection +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ReceiveFailure +import com.xiangming.wechatbridge.receive.ShareItem +import com.xiangming.wechatbridge.receive.UriImporter +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import java.time.Instant +import java.util.UUID + +/** iOS `RelayFilter`: 全部 / 未投递 / 收集中. */ +enum class RelayFilter { ALL, UNDELIVERED, COLLECTING } + +/** One open collection as the list shows it. */ +data class CollectionCardModel( + val collection: BatchCollection, + /** Batches still in the relay, oldest first. */ + val batchIds: List, + /** iOS: summed from the parsed batches; 「约」 because overlaps are only removed on merge. */ + val messageCount: Int, + val lastStart: Instant?, + val lastEnd: Instant?, +) + +data class RelayUiState( + val filter: RelayFilter = RelayFilter.ALL, + /** 实时搜索词;空白时不过滤。按批次标题、聊天预览文本、来源名匹配。 */ + val query: String = "", + /** Entries that pass [filter] and [query], newest first. */ + val entries: List = emptyList(), + /** Entries in the relay regardless of the filter. */ + val totalCount: Int = 0, + val collections: List = emptyList(), + val selection: Set = emptySet(), + val importing: Boolean = false, +) { + /** Selection mode is on exactly while something is selected. */ + val selecting: Boolean get() = selection.isNotEmpty() + val isEmpty: Boolean get() = totalCount == 0 && collections.isEmpty() +} + +/** One-shot things the screen turns into a Snackbar. */ +sealed interface RelayEvent { + data class Deleted(val count: Int) : RelayEvent + data class Imported(val itemCount: Int) : RelayEvent + data class ImportFailed(val failure: ReceiveFailure) : RelayEvent + data object ClipboardEmpty : RelayEvent + data class Error(val message: String?) : RelayEvent +} + +/** + * State for the relay list. The data lives in [RelayStore]; this adds the + * filter, the multi-selection and the import actions. + * + * [importScope] should outlive the screen (the app scope): an import that is + * cancelled half way would discard the batch. + */ +class RelayViewModel( + private val store: RelayStore, + private val importer: UriImporter, + private val importScope: CoroutineScope, +) : ViewModel() { + private val filter = MutableStateFlow(RelayFilter.ALL) + private val query = MutableStateFlow("") + private val selection = MutableStateFlow>(emptySet()) + private val imports = MutableStateFlow(0) + private val channel = Channel(Channel.BUFFERED) + + val events: Flow = channel.receiveAsFlow() + + /** The store, the filter and the search term, folded into one input. */ + private data class RelayInputs( + val entries: List, + val collections: List, + val filter: RelayFilter, + val selection: Set, + val importing: Boolean, + ) + + val state: StateFlow = combine( + combine( + store.entries, + store.collections, + filter, + selection, + imports, + ) { entries, collections, filter, selection, imports -> + RelayInputs(entries, collections, filter, selection, imports > 0) + }, + query, + ) { inputs, query -> + buildRelayState( + entries = inputs.entries, + collections = inputs.collections, + filter = inputs.filter, + selection = inputs.selection, + importing = inputs.importing, + query = query, + ) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), RelayUiState()) + + init { + viewModelScope.launch { + store.lastError.filterNotNull().collect { error -> + channel.trySend(RelayEvent.Error(error.localizedMessage)) + store.clearError() + } + } + } + + fun setFilter(value: RelayFilter) { + filter.value = value + selection.value = emptySet() + } + + /** 实时搜索:每次输入都会重新过滤,与当前筛选叠加生效。 */ + fun setQuery(value: String) { + query.value = value + } + + fun toggle(id: UUID) { + selection.update { if (id in it) it - id else it + id } + } + + fun selectAll() { + selection.value = state.value.entries.mapTo(mutableSetOf()) { it.id } + } + + fun clearSelection() { + selection.value = emptySet() + } + + /** Hides the selection for the undo window, then the store deletes it. */ + fun deleteSelected() { + val ids = state.value.selection + if (ids.isEmpty()) return + store.delete(ids) + selection.value = emptySet() + channel.trySend(RelayEvent.Deleted(store.pendingDeletion.value.size)) + } + + fun undoDelete() = store.undoDeletion() + + /** The selection as ids for `onDeliver`, oldest batch first (the order a merge reads in); clears the selection. */ + fun takeSelectionForDelivery(): List { + val ids = state.value.selection.toList() + selection.value = emptySet() + return orderedIds(store.entries(ids)) + } + + fun importFiles(items: List) { + if (items.isEmpty()) return + launchImport(items) + } + + /** 「从剪贴板收入」: plain text, saved as one `.txt` like a text share. */ + fun importText(text: String?) { + if (text.isNullOrBlank()) { + channel.trySend(RelayEvent.ClipboardEmpty) + return + } + launchImport(listOf(ShareItem.Text(text))) + } + + private fun launchImport(items: List) { + importScope.launch { + imports.update { it + 1 } + try { + when (val outcome = importer.import(items, collect = false)) { + is ImportOutcome.Saved -> { + store.refresh() + channel.trySend(RelayEvent.Imported(outcome.items.size)) + } + is ImportOutcome.Failed -> channel.trySend(RelayEvent.ImportFailed(outcome.failure)) + } + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + channel.trySend(RelayEvent.ImportFailed(ReceiveFailure.StorageFailed)) + } finally { + imports.update { it - 1 } + } + } + } + + companion object { + /** Oldest first, as a merged delivery reads. */ + internal fun orderedIds(entries: List): List = + entries.sortedBy { it.batch.createdAt }.map { it.id.toString() } + } +} + +/** Pure, so the filter rules are testable without Android. */ +internal fun buildRelayState( + entries: List, + collections: List, + filter: RelayFilter, + selection: Set, + importing: Boolean, + query: String = "", +): RelayUiState { + val visible = when (filter) { + RelayFilter.ALL -> entries + RelayFilter.UNDELIVERED -> entries.filter { !it.isDelivered } + RelayFilter.COLLECTING -> entries.filter { it.isCollecting } + }.filter { it.matchesQuery(query) } + val byId = entries.associateBy { it.id } + // Collections gather batches, not delivered ones: they have no place in 「未投递」. + val cards = if (filter == RelayFilter.UNDELIVERED) { + emptyList() + } else { + collections.mapNotNull { collection -> + val members = collection.batchIDs.mapNotNull(byId::get).sortedBy { it.batch.createdAt } + if (members.isEmpty()) return@mapNotNull null + val last = members.last().summary + CollectionCardModel( + collection = collection, + batchIds = members.map { it.id }, + messageCount = members.sumOf { it.summary?.messageCount ?: 0 }, + lastStart = last?.start, + lastEnd = last?.end, + ) + }.filter { it.collection.name.matchesQuery(query) } + } + return RelayUiState( + filter = filter, + query = query, + entries = visible, + totalCount = entries.size, + collections = cards, + selection = selection.filterTo(mutableSetOf()) { it in byId }, + importing = importing, + ) +} + +/** + * 一条记录是否匹配搜索词:标题(缺省时用首个文件名)、聊天预览文本、来源名, + * 大小写不敏感;空白搜索词一律通过(RelayScreen 的实时搜索)。 + */ +internal fun RelayEntry.matchesQuery(query: String): Boolean { + val text = query.trim() + if (text.isEmpty()) return true + val title = summary?.title ?: batch.items.firstOrNull()?.displayName + if (title?.contains(text, ignoreCase = true) == true) return true + if (summary?.source?.contains(text, ignoreCase = true) == true) return true + return summary?.preview?.any { it.contains(text, ignoreCase = true) } == true +} + +/** 收集卡按名字匹配同一套搜索词;空白搜索词一律通过。 */ +internal fun String.matchesQuery(query: String): Boolean { + val text = query.trim() + if (text.isEmpty()) return true + return contains(text, ignoreCase = true) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneComponents.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneComponents.kt new file mode 100644 index 00000000..87fd3f80 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneComponents.kt @@ -0,0 +1,490 @@ +package com.xiangming.wechatbridge.ui.scenes + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.InputChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.scale +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.scene.AgentId +import com.xiangming.wechatbridge.core.scene.WeChatScene +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.BridgeBentoCard +import com.xiangming.wechatbridge.ui.theme.BridgeGlassSurface +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.WeChatGreen + +@Composable +internal fun GroupedCard( + modifier: Modifier = Modifier, + content: @Composable ColumnScope.() -> Unit, +) { + Surface( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surface, + ) { + Column(content = content) + } +} + +@Composable +internal fun SubtleCardDivider() { + HorizontalDivider( + modifier = Modifier.padding(horizontal = 16.dp), + thickness = 0.75.dp, + color = LocalAppColors.current.subtleDivider, + ) +} + +@Composable +internal fun SectionHeader(title: String, modifier: Modifier = Modifier) { + Text( + title, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = modifier.fillMaxWidth().padding(horizontal = 6.dp), + ) +} + +@Composable +internal fun SectionFooter(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = LocalAppColors.current.onSurfaceMuted, + modifier = Modifier.fillMaxWidth().padding(horizontal = 6.dp), + ) +} + +/** 顶部轻玻璃状态胶囊条:展示「已启用 X / Y 个场景」+ 品牌绿进度小圆点。 */ +@Composable +internal fun ScenesStatusBar( + enabledCount: Int, + totalCount: Int, + modifier: Modifier = Modifier, +) { + val appColors = LocalAppColors.current + BridgeGlassSurface( + modifier = modifier.fillMaxWidth(), + shape = CircleShape, + shadowElevation = 6.dp, + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 11.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Box( + modifier = Modifier + .size(18.dp) + .clip(CircleShape) + .background( + if (enabledCount > 0) WeChatGreen.copy(alpha = 0.16f) + else appColors.surfaceSub, + ), + contentAlignment = Alignment.Center, + ) { + Box( + modifier = Modifier + .size(8.dp) + .clip(CircleShape) + .background( + if (enabledCount > 0) MaterialTheme.colorScheme.primary + else appColors.onSurfaceMuted, + ), + ) + } + Text( + text = "已启用 $enabledCount / $totalCount 个场景", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface, + ) + } + if (totalCount > 0) { + val dotCount = totalCount.coerceAtMost(8) + val litDots = if (totalCount <= 8) { + enabledCount + } else { + ((enabledCount.toFloat() / totalCount) * dotCount).toInt().coerceIn( + if (enabledCount > 0) 1 else 0, + dotCount, + ) + } + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + repeat(dotCount) { index -> + Box( + modifier = Modifier + .size(6.dp) + .clip(CircleShape) + .background( + if (index < litDots) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.outlineVariant, + ), + ) + } + } + } + } + } +} + +/** 官方场景按稳定 ID 映射独立图标;未知官方场景与自定义场景均有安全兜底。 */ +internal fun sceneIcon(scene: WeChatScene): ImageVector = when { + !scene.isOfficial -> AppIcons.FillInput + scene.id.endsWith("customer-review") -> AppIcons.SceneCustomer + scene.id.endsWith("project-sync") -> AppIcons.SceneProject + scene.id.endsWith("daily-summary") -> AppIcons.SceneSummary + scene.id.endsWith("article-extract") -> AppIcons.SceneArticle + scene.id.endsWith("video-reading") -> AppIcons.SceneVideo + else -> AppIcons.NavScenes +} + +/** 2 列 Bento 场景卡片:启用态柔和绿白顶光 + 绿边框;未启用态素雅纯白。 */ +@Composable +internal fun SceneBentoCard( + scene: WeChatScene, + onOpen: () -> Unit, + onToggle: (Boolean) -> Unit, + modifier: Modifier = Modifier, + onDelete: (() -> Unit)? = null, +) { + val appColors = LocalAppColors.current + val enableLabel = stringResource(R.string.a11y_scene_enable, scene.name) + BridgeBentoCard( + modifier = modifier.heightIn(min = 156.dp), + cornerRadius = 20.dp, + highlighted = scene.enabled, + contentPadding = PaddingValues(14.dp), + onClick = onOpen, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 132.dp), + verticalArrangement = Arrangement.SpaceBetween, + ) { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + // 顶部:左侧圆角图标徽章 + 右上角紧凑品牌绿 Switch + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(34.dp) + .clip(RoundedCornerShape(10.dp)) + .background( + if (scene.enabled) appColors.surfaceTint else appColors.surfaceSub, + ), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = sceneIcon(scene), + contentDescription = null, + tint = if (scene.enabled) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + modifier = Modifier.size(17.dp), + ) + } + Switch( + checked = scene.enabled, + onCheckedChange = onToggle, + colors = SwitchDefaults.colors( + checkedThumbColor = Color.White, + checkedTrackColor = MaterialTheme.colorScheme.primary, + checkedBorderColor = MaterialTheme.colorScheme.primary, + uncheckedThumbColor = Color.White, + uncheckedTrackColor = MaterialTheme.colorScheme.surfaceVariant, + uncheckedBorderColor = MaterialTheme.colorScheme.outlineVariant, + ), + modifier = Modifier + .scale(0.82f) + .semantics { contentDescription = enableLabel }, + ) + } + + // 中部:加粗场景名(最多 2 行)+ 摘要说明(最多 3 行) + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + text = scene.name, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + if (scene.summary.isNotEmpty()) { + Text( + text = scene.summary, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 3, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + + Spacer(Modifier.height(10.dp)) + + // 底部推底:官方/自定义小标签 + 已启用/未启用状态 + 自定义场景删除入口 + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.weight(1f), + ) { + Surface( + shape = RoundedCornerShape(6.dp), + color = if (scene.enabled) { + appColors.surfaceTint + } else { + appColors.surfaceSub + }, + ) { + Text( + text = if (scene.isOfficial) "官方" else "自定义", + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Medium, + color = if (scene.enabled) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) + } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Box( + modifier = Modifier + .size(5.dp) + .clip(CircleShape) + .background( + if (scene.enabled) MaterialTheme.colorScheme.primary + else appColors.onSurfaceMuted.copy(alpha = 0.6f), + ), + ) + Text( + text = if (scene.enabled) "已启用" else "未启用", + style = MaterialTheme.typography.labelSmall, + color = if (scene.enabled) { + MaterialTheme.colorScheme.primary + } else { + appColors.onSurfaceMuted + }, + maxLines = 1, + ) + } + } + if (onDelete != null) { + IconButton( + onClick = onDelete, + modifier = Modifier.size(28.dp), + ) { + Icon( + Icons.Filled.Delete, + contentDescription = stringResource(R.string.a11y_scene_delete, scene.name), + tint = appColors.onSurfaceMuted, + modifier = Modifier.size(16.dp), + ) + } + } + } + } + } +} + +/** 场景一行:点行进编辑页,开关绑定的是这个场景自己的启用状态。 */ +@Composable +internal fun SceneRow( + scene: WeChatScene, + onOpen: () -> Unit, + onToggle: (Boolean) -> Unit, + onDelete: (() -> Unit)? = null, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onOpen) + .padding(horizontal = 16.dp, vertical = 13.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(3.dp), + ) { + Text( + scene.name, + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (scene.summary.isNotEmpty()) { + Text( + scene.summary, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (onDelete != null) { + IconButton(onClick = onDelete, modifier = Modifier.size(36.dp)) { + Icon( + Icons.Filled.Delete, + contentDescription = stringResource(R.string.a11y_scene_delete, scene.name), + tint = LocalAppColors.current.onSurfaceMuted, + modifier = Modifier.size(19.dp), + ) + } + } + val enableLabel = stringResource(R.string.a11y_scene_enable, scene.name) + Switch( + checked = scene.enabled, + onCheckedChange = onToggle, + modifier = Modifier.semantics { contentDescription = enableLabel }, + ) + } + } +} + +/** 一个群和它绑定的场景;每个场景可以单独解绑。 */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun GroupBindingRow( + group: GroupBinding, + onUnbind: (sceneId: String) -> Unit, + onUnbindAll: () -> Unit, +) { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + group.displayName, + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (group.scenes.size > 1) { + TextButton(onClick = onUnbindAll) { Text(stringResource(R.string.scenes_unbind_all)) } + } + } + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + for (bound in group.scenes) { + val label = when { + bound.name == null -> stringResource(R.string.scenes_bound_missing) + !bound.enabled -> stringResource(R.string.scenes_bound_disabled, bound.name) + else -> bound.name + } + InputChip( + selected = false, + onClick = { onUnbind(bound.id) }, + label = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + trailingIcon = { + Icon( + Icons.Filled.Close, + contentDescription = stringResource(R.string.scenes_unbind_scene, bound.name ?: label), + modifier = Modifier.size(16.dp), + ) + }, + ) + } + } + } +} + +@Composable +internal fun agentLabel(agent: AgentId): String = stringResource( + when (agent) { + AgentId.CHATGPT_CODEX -> R.string.scenes_agent_chatgpt_codex + AgentId.CLAUDE -> R.string.scenes_agent_claude + AgentId.DOUBAO -> R.string.scenes_agent_doubao + AgentId.QWEN_WORK -> R.string.scenes_agent_qwen_work + AgentId.WORK_BUDDY -> R.string.scenes_agent_work_buddy + AgentId.WE_SIGHT -> R.string.scenes_agent_we_sight + }, +) + +@Composable +internal fun noticeText(notice: ScenesNotice): String = when (notice) { + is ScenesNotice.Imported -> stringResource(R.string.scenes_notice_imported, notice.count) + is ScenesNotice.ImportFailed -> + stringResource(R.string.scenes_notice_import_failed, notice.reason ?: stringResource(R.string.scenes_error_unknown)) + is ScenesNotice.Exported -> stringResource(R.string.scenes_notice_exported, notice.count) + is ScenesNotice.ExportFailed -> + stringResource(R.string.scenes_notice_export_failed, notice.reason ?: stringResource(R.string.scenes_error_unknown)) + ScenesNotice.ExportEmpty -> stringResource(R.string.scenes_notice_export_empty) + is ScenesNotice.Copied -> stringResource(R.string.scenes_notice_copied, notice.name) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneEditor.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneEditor.kt new file mode 100644 index 00000000..1d6ba0c1 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneEditor.kt @@ -0,0 +1,203 @@ +package com.xiangming.wechatbridge.ui.scenes + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.scene.AgentId +import com.xiangming.wechatbridge.ui.theme.LocalAppColors + +/** 编辑 / 新建场景。官方场景只读,只能复制成自己的。 */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +internal fun SceneEditor( + draft: SceneDraft, + onChange: ((SceneDraft) -> SceneDraft) -> Unit, + onSave: () -> Unit, + onCopy: () -> Unit, + onBack: () -> Unit, +) { + BackHandler(onBack = onBack) + val readOnly = draft.isOfficial + val appColors = LocalAppColors.current + Scaffold( + containerColor = MaterialTheme.colorScheme.background, + topBar = { + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.background, + scrolledContainerColor = MaterialTheme.colorScheme.background, + ), + title = { + Text( + if (draft.isNew) stringResource(R.string.scenes_editor_title_new) else draft.name, + style = MaterialTheme.typography.titleLarge, + ) + }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.action_back), + ) + } + }, + actions = { + if (!readOnly) { + TextButton(onClick = onSave, enabled = draft.canSave) { + Text(stringResource(R.string.scenes_editor_save)) + } + } + }, + ) + }, + modifier = Modifier.fillMaxSize(), + ) { padding -> + Column( + modifier = Modifier + .padding(padding) + .imePadding() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + if (readOnly) { + Surface( + shape = RoundedCornerShape(16.dp), + color = appColors.surfaceTint, + border = BorderStroke(1.dp, appColors.surfaceTintBorder), + modifier = Modifier.fillMaxWidth(), + ) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text( + stringResource(R.string.scenes_editor_official_note), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + Button( + onClick = onCopy, + shape = RoundedCornerShape(12.dp), + ) { + Text(stringResource(R.string.scenes_editor_copy)) + } + } + } + } + + GroupedCard { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + OutlinedTextField( + value = draft.name, + onValueChange = { v -> onChange { it.copy(name = v) } }, + label = { Text(stringResource(R.string.scenes_editor_name)) }, + placeholder = { Text(stringResource(R.string.scenes_editor_name_hint)) }, + singleLine = true, + readOnly = readOnly, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = draft.summary, + onValueChange = { v -> onChange { it.copy(summary = v) } }, + label = { Text(stringResource(R.string.scenes_editor_summary)) }, + readOnly = readOnly, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = draft.instruction, + onValueChange = { v -> onChange { it.copy(instruction = v) } }, + label = { Text(stringResource(R.string.scenes_editor_instruction)) }, + readOnly = readOnly, + minLines = 5, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = 120.dp), + ) + OutlinedTextField( + value = draft.outputSpec, + onValueChange = { v -> onChange { it.copy(outputSpec = v) } }, + label = { Text(stringResource(R.string.scenes_editor_output_spec)) }, + readOnly = readOnly, + minLines = 4, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = 100.dp), + ) + OutlinedTextField( + value = draft.keywords, + onValueChange = { v -> onChange { it.copy(keywords = v) } }, + label = { Text(stringResource(R.string.scenes_editor_keywords)) }, + placeholder = { Text(stringResource(R.string.scenes_editor_keywords_hint)) }, + supportingText = { Text(stringResource(R.string.scenes_editor_keywords_footer)) }, + readOnly = readOnly, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth(), + ) + } + } + + GroupedCard { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text(stringResource(R.string.scenes_editor_targets), style = MaterialTheme.typography.titleSmall) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + for (agent in AgentId.allCases) { + val selected = agent in draft.agents + FilterChip( + selected = selected, + onClick = { + if (!readOnly) { + onChange { it.copy(agents = if (selected) it.agents - agent else it.agents + agent) } + } + }, + label = { Text(agentLabel(agent)) }, + ) + } + } + Text( + stringResource(R.string.scenes_editor_targets_footer), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + ) + } + } + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneFiles.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneFiles.kt new file mode 100644 index 00000000..82748ee1 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/SceneFiles.kt @@ -0,0 +1,19 @@ +package com.xiangming.wechatbridge.ui.scenes + +import android.content.ContentResolver +import android.net.Uri +import java.io.FileNotFoundException + +/** 场景 JSON 经 SAF 读写(调用方放在 IO 线程)。 */ +internal object SceneFiles { + fun readText(resolver: ContentResolver, uri: Uri): String { + val bytes = resolver.openInputStream(uri)?.use { it.readBytes() } ?: throw FileNotFoundException(uri.toString()) + return bytes.toString(Charsets.UTF_8) + } + + fun writeText(resolver: ContentResolver, uri: Uri, text: String) { + // "wt":覆盖写入,选了已有文件时不会留下旧内容的尾巴。 + val stream = resolver.openOutputStream(uri, "wt") ?: throw FileNotFoundException(uri.toString()) + stream.use { it.write(text.toByteArray(Charsets.UTF_8)) } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesScreen.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesScreen.kt new file mode 100644 index 00000000..2237a04e --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesScreen.kt @@ -0,0 +1,422 @@ +package com.xiangming.wechatbridge.ui.scenes + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.ui.theme.BridgeAmbientBackdrop +import com.xiangming.wechatbridge.ui.theme.BridgeBentoCard +import com.xiangming.wechatbridge.ui.theme.BridgeTopBarScrim +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** 场景:2 列 Bento 场景卡片墙、顶部状态胶囊、JSON 导入导出和已绑定群聊管理。 */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ScenesScreen( + onBack: () -> Unit, + showBack: Boolean = false, +) { + val context = LocalContext.current + val container = (context.applicationContext as App).container + val viewModel: ScenesViewModel = viewModel { ScenesViewModel(container.sceneStore) } + val state by viewModel.state.collectAsStateWithLifecycle() + val resolver = context.contentResolver + val scope = rememberCoroutineScope() + + val snackbar = remember { SnackbarHostState() } + val notice = state.notice + val noticeMessage = notice?.let { noticeText(it) } + LaunchedEffect(notice) { + if (noticeMessage != null) { + snackbar.showSnackbar(noticeMessage) + viewModel.consumeNotice() + } + } + + // 导出:先把 JSON 定下来,用户选好位置后再写;点击和写入之间场景改了也以点击时为准。 + var pendingExport by remember { mutableStateOf?>(null) } + val exportLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.CreateDocument("application/json"), + ) { uri -> + val export = pendingExport + pendingExport = null + if (uri != null && export != null) { + scope.launch { + try { + withContext(Dispatchers.IO) { SceneFiles.writeText(resolver, uri, export.first) } + viewModel.exportDone(export.second) + } catch (e: Exception) { + viewModel.exportFailed(e.message) + } + } + } + } + val importLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) { + scope.launch { + try { + val text = withContext(Dispatchers.IO) { SceneFiles.readText(resolver, uri) } + viewModel.importJson(listOf(text)) + } catch (e: Exception) { + viewModel.importFailed(e.message) + } + } + } + } + val exportFilename = stringResource(R.string.scenes_export_filename) + + var menuOpen by remember { mutableStateOf(false) } + var deleting by rememberSaveable { mutableStateOf(null) } + + val draft = state.editor + if (draft != null) { + SceneEditor( + draft = draft, + onChange = viewModel::updateDraft, + onSave = viewModel::saveDraft, + onCopy = { draft.sceneId?.let(viewModel::copyOfficial) }, + onBack = viewModel::dismissEditor, + ) + return + } + + val navBarBottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + val totalCount = state.official.size + state.mine.size + val enabledCount = state.official.count { it.enabled } + state.mine.count { it.enabled } + val listState = rememberLazyListState() + val scrolled by remember { + derivedStateOf { + listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 0 + } + } + + Box(modifier = Modifier.fillMaxSize()) { + BridgeAmbientBackdrop() + + Scaffold( + containerColor = Color.Transparent, + topBar = { + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + scrolledContainerColor = Color.Transparent, + ), + title = { + Text( + stringResource(R.string.nav_scenes), + style = if (showBack) MaterialTheme.typography.titleLarge else MaterialTheme.typography.headlineMedium, + ) + }, + navigationIcon = { + if (showBack) { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.action_back), + ) + } + } + }, + actions = { + IconButton(onClick = viewModel::startNew) { + Icon( + Icons.Filled.Add, + contentDescription = stringResource(R.string.scenes_new), + tint = MaterialTheme.colorScheme.primary, + ) + } + Box { + IconButton(onClick = { menuOpen = true }) { + Icon( + Icons.Filled.MoreVert, + contentDescription = stringResource(R.string.scenes_menu_more), + ) + } + DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { + DropdownMenuItem( + text = { Text(stringResource(R.string.scenes_menu_import)) }, + onClick = { + menuOpen = false + importLauncher.launch(arrayOf("*/*")) + }, + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.scenes_menu_export)) }, + enabled = state.mine.isNotEmpty(), + onClick = { + menuOpen = false + val text = viewModel.exportText() + if (text == null) { + viewModel.exportEmpty() + } else { + pendingExport = text to viewModel.exportCount() + exportLauncher.launch(exportFilename) + } + }, + ) + } + } + }, + ) + }, + snackbarHost = { + SnackbarHost( + hostState = snackbar, + modifier = Modifier + .navigationBarsPadding() + .padding(bottom = 84.dp), + ) + }, + ) { padding -> + if (!state.loaded) { + Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { + CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) + } + return@Scaffold + } + val officialRows = remember(state.official) { state.official.chunked(2) } + val mineRows = remember(state.mine) { state.mine.chunked(2) } + + Box( + modifier = Modifier + .fillMaxSize() + .padding(top = padding.calculateTopPadding()), + ) { + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues( + start = 16.dp, + end = 16.dp, + top = 6.dp, + bottom = 116.dp + navBarBottom, + ), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + // 顶部轻玻璃状态胶囊条 + item(key = "status-bar") { + ScenesStatusBar( + enabledCount = enabledCount, + totalCount = totalCount, + ) + } + + // ① 官方场景 2 列 Bento 卡片墙 + item(key = "header-official") { + SectionHeader( + title = stringResource(R.string.scenes_section_official), + modifier = Modifier.padding(top = 6.dp), + ) + } + items( + items = officialRows, + key = { row -> "official-${row.joinToString("-") { it.id }}" }, + ) { row -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + for (scene in row) { + SceneBentoCard( + scene = scene, + onOpen = { viewModel.startEdit(scene.id) }, + onToggle = { viewModel.setEnabled(scene.id, it) }, + // 官方场景为奇数个时,末项撑满整行,不留右侧空白。 + modifier = Modifier.weight(1f, fill = row.size == 1), + ) + } + } + } + + // ② 我的场景 2 列 Bento 卡片墙 + item(key = "header-mine") { + SectionHeader( + title = stringResource(R.string.scenes_section_mine), + modifier = Modifier.padding(top = 8.dp), + ) + } + if (state.mine.isEmpty()) { + item(key = "mine-empty") { + BridgeBentoCard( + cornerRadius = 20.dp, + contentPadding = PaddingValues(0.dp), + ) { + Text( + stringResource(R.string.scenes_mine_empty), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 14.dp), + ) + } + } + } else { + items( + items = mineRows, + key = { row -> "mine-${row.joinToString("-") { it.id }}" }, + ) { row -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + for (scene in row) { + SceneBentoCard( + scene = scene, + onOpen = { viewModel.startEdit(scene.id) }, + onToggle = { viewModel.setEnabled(scene.id, it) }, + onDelete = { deleting = scene.id }, + modifier = Modifier.weight(1f), + ) + } + if (row.size == 1) { + Spacer(Modifier.weight(1f)) + } + } + } + } + item(key = "mine-new") { + BridgeBentoCard( + cornerRadius = 18.dp, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp), + onClick = viewModel::startNew, + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + Icons.Filled.Add, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp), + ) + Text( + stringResource(R.string.scenes_new), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.primary, + ) + } + } + } + + // ③ 已绑定群聊卡片区 + item(key = "group-bindings") { + Column( + modifier = Modifier.padding(top = 8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + SectionHeader(stringResource(R.string.scenes_section_groups)) + BridgeBentoCard( + cornerRadius = 20.dp, + contentPadding = PaddingValues(0.dp), + ) { + if (state.groups.isEmpty()) { + Text( + stringResource(R.string.scenes_groups_empty), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 14.dp), + ) + } else { + state.groups.forEachIndexed { index, group -> + if (index > 0) SubtleCardDivider() + GroupBindingRow( + group = group, + onUnbind = { viewModel.unbind(group.displayName, it) }, + onUnbindAll = { viewModel.unbindAll(group.displayName) }, + ) + } + } + } + if (state.groups.isNotEmpty()) { + SectionFooter(stringResource(R.string.scenes_groups_footer)) + } + } + } + } + // 覆盖内容区顶部边界,滚动时柔和淡出,避免首张卡片被硬裁切。 + BridgeTopBarScrim( + visible = scrolled, + modifier = Modifier.align(Alignment.TopCenter), + ) + } + } + } + + val pendingDelete = deleting?.let { id -> state.mine.firstOrNull { it.id == id } } + if (pendingDelete != null) { + AlertDialog( + onDismissRequest = { deleting = null }, + title = { Text(stringResource(R.string.scenes_delete_title)) }, + text = { Text(stringResource(R.string.scenes_delete_message, pendingDelete.name)) }, + confirmButton = { + TextButton(onClick = { + deleting = null + viewModel.delete(pendingDelete.id) + }) { Text(stringResource(R.string.scenes_delete), color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { + TextButton(onClick = { deleting = null }) { Text(stringResource(R.string.action_cancel)) } + }, + ) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesViewModel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesViewModel.kt new file mode 100644 index 00000000..dc3d1a8c --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesViewModel.kt @@ -0,0 +1,308 @@ +package com.xiangming.wechatbridge.ui.scenes + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.core.scene.AgentId +import com.xiangming.wechatbridge.core.scene.GroupMemory +import com.xiangming.wechatbridge.core.scene.GroupName +import com.xiangming.wechatbridge.core.scene.SceneJson +import com.xiangming.wechatbridge.core.scene.ScenePackage +import com.xiangming.wechatbridge.core.scene.SceneSettings +import com.xiangming.wechatbridge.core.scene.WeChatScene +import com.xiangming.wechatbridge.data.SceneStore +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +/** 一个群绑定的一个场景;[name] 为 null 表示场景已不存在。 */ +data class BoundScene(val id: String, val name: String?, val enabled: Boolean) + +data class GroupBinding(val key: String, val displayName: String, val scenes: List) + +/** 编辑页的草稿。文本框的内容放在这里,旋转屏幕不丢。 */ +data class SceneDraft( + /** 新建时为 null。 */ + val sceneId: String? = null, + val isOfficial: Boolean = false, + val name: String = "", + val summary: String = "", + val instruction: String = "", + val outputSpec: String = SceneSettings.standardOutputSpec, + val keywords: String = "", + val agents: Set = AgentId.allCases.toSet(), +) { + val isNew: Boolean get() = sceneId == null + val canSave: Boolean get() = !isOfficial && name.isNotBlank() && agents.isNotEmpty() +} + +sealed interface ScenesNotice { + data class Imported(val count: Int) : ScenesNotice + data class ImportFailed(val reason: String?) : ScenesNotice + data class Exported(val count: Int) : ScenesNotice + data class ExportFailed(val reason: String?) : ScenesNotice + data object ExportEmpty : ScenesNotice + data class Copied(val name: String) : ScenesNotice +} + +data class ScenesUiState( + val loaded: Boolean = false, + val official: List = emptyList(), + val mine: List = emptyList(), + val groups: List = emptyList(), + val editor: SceneDraft? = null, + val notice: ScenesNotice? = null, +) + +/** + * 场景页状态。开关、编辑、导入导出和群绑定都经 [SceneStore],列表直接来自 + * `store.settings` / `store.memories`,所以投递面板读到的候选场景会同步变化。 + * + * 开关只用 [SceneSettings.scenes] + [SceneSettings.setEnabled](全部场景的启用状态), + * 不用只查已启用场景的 `scene(id:)`,否则关掉之后就再也打不开了(iOS 踩过的坑)。 + */ +class ScenesViewModel( + private val store: SceneStore, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, +) : ViewModel() { + private val loaded = MutableStateFlow(false) + private val editor = MutableStateFlow(null) + private val notice = MutableStateFlow(null) + + /** 读改写串行,连点开关时不会互相覆盖。 */ + private val mutex = Mutex() + + val state: StateFlow = combine( + store.settings, + store.memories, + loaded, + editor, + notice, + ) { settings, memories, isLoaded, draft, note -> + val scenes = settings.scenes + ScenesUiState( + loaded = isLoaded, + official = scenes.filter { it.isOfficial }, + mine = scenes.filter { !it.isOfficial }, + groups = bindings(scenes, memories), + editor = draft, + notice = note, + ) + }.stateIn(viewModelScope, SharingStarted.Eagerly, ScenesUiState()) + + init { + viewModelScope.launch { + withContext(ioDispatcher) { store.load() } + loaded.value = true + } + } + + // MARK: 开关 + + fun setEnabled(id: String, enabled: Boolean) = edit { snapshot -> + val next = snapshot.settings.setEnabled(id, enabled) + if (next !== snapshot.settings) store.setSettings(next) + } + + // MARK: 编辑 + + fun startNew() { + editor.value = SceneDraft() + } + + fun startEdit(id: String) { + val scene = store.settings.value.scenes.firstOrNull { it.id == id } ?: return + editor.value = SceneDraft( + sceneId = scene.id, + isOfficial = scene.isOfficial, + name = scene.name, + summary = scene.summary, + instruction = scene.instruction, + outputSpec = scene.outputSpec, + keywords = scene.keywords.joinToString(","), + agents = scene.compatibleAgents.toSet(), + ) + } + + fun updateDraft(change: (SceneDraft) -> SceneDraft) { + editor.update { draft -> draft?.let(change) } + } + + fun dismissEditor() { + editor.value = null + } + + /** 新建加入并启用;编辑保留原来的开关([SceneSettings.replace])。官方场景不能保存。 */ + fun saveDraft() { + val draft = editor.value ?: return + if (!draft.canSave) return + edit { snapshot -> + val settings = snapshot.settings + val existing = draft.sceneId?.let { id -> settings.scenes.firstOrNull { it.id == id } } + if (draft.sceneId != null && (existing == null || existing.isOfficial)) { + // 场景已被删掉或是官方场景:不凭空再造一个。 + editor.value = null + return@edit + } + val keywords = parseKeywords(draft.keywords) + val agents = AgentId.allCases.filter { it in draft.agents } + val next = if (existing == null) { + settings.add( + WeChatScene( + name = draft.name.trim(), + summary = draft.summary.trim(), + instruction = draft.instruction, + outputSpec = draft.outputSpec, + keywords = keywords, + enabled = true, + compatibleAgents = agents, + ), + ) + } else { + settings.replace( + existing.copy( + name = draft.name.trim(), + summary = draft.summary.trim(), + instruction = draft.instruction, + outputSpec = draft.outputSpec, + keywords = keywords, + compatibleAgents = agents, + ), + ) + } + store.setSettings(next) + editor.value = null + } + } + + /** 官方场景复制成可编辑的「我的场景」(已启用,新 id)。 */ + fun copyOfficial(id: String) = edit { snapshot -> + val settings = snapshot.settings + val source = settings.scenes.firstOrNull { it.id == id } ?: return@edit + val copy = settings.copiedAsUserTask(source) + store.setSettings(settings.add(copy)) + editor.value = null + notice.value = ScenesNotice.Copied(copy.name) + } + + /** 只能删「我的场景」;绑定到它的群一并解绑。 */ + fun delete(id: String) = edit { snapshot -> + val scene = snapshot.settings.scenes.firstOrNull { it.id == id } ?: return@edit + if (scene.isOfficial) return@edit + store.setSettings(snapshot.settings.remove(id)) + for (memory in snapshot.memories.values) { + if (id in memory.boundSceneIDs) { + store.bind(memory.displayName, memory.boundSceneIDs - id, emptySet()) + } + } + } + + // MARK: 导入导出 + + /** + * 每段文本是一个场景包或一组场景包(Mac / iOS 导出的 JSON)。先全部解析,任何一个 + * 失败就整体不导入。导入的场景立刻启用;同 id 的已有场景被覆盖内容、保留位置。 + */ + fun importJson(texts: List) = edit { snapshot -> + try { + val packages = texts.flatMap { SceneJson.decodePackages(it.removePrefix("\uFEFF")) } + var settings = snapshot.settings + for (pack in packages) { + settings = settings.replace(pack.scene).setEnabled(pack.id, true) + } + val installed = packages.count { pack -> settings.scenes.any { it.id == pack.id } } + store.setSettings(settings) + notice.value = ScenesNotice.Imported(installed) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + notice.value = ScenesNotice.ImportFailed(e.message) + } + } + + /** 读文件本身失败(没有权限、文件不存在……)。 */ + fun importFailed(reason: String?) { + notice.value = ScenesNotice.ImportFailed(reason) + } + + /** 导出「我的场景」的 JSON(与 Mac / iOS 的 `ScenePackage` 数组一致);没有则为 null。 */ + fun exportText(): String? { + val mine = state.value.mine + if (mine.isEmpty()) return null + return SceneJson.encodePackages(mine.map { ScenePackage(it) }) + } + + fun exportCount(): Int = state.value.mine.size + + fun exportDone(count: Int) { + notice.value = ScenesNotice.Exported(count) + } + + fun exportFailed(reason: String?) { + notice.value = ScenesNotice.ExportFailed(reason) + } + + fun exportEmpty() { + notice.value = ScenesNotice.ExportEmpty + } + + fun consumeNotice() { + notice.value = null + } + + // MARK: 群绑定 + + fun unbind(groupName: String, sceneId: String) = edit { snapshot -> + val key = GroupName.normalize(groupName) + val memory = snapshot.memories[key] ?: return@edit + if (sceneId !in memory.boundSceneIDs) return@edit + store.bind(memory.displayName, memory.boundSceneIDs - sceneId, emptySet()) + } + + fun unbindAll(groupName: String) = edit { snapshot -> + val key = GroupName.normalize(groupName) + val memory = snapshot.memories[key] ?: return@edit + if (memory.boundSceneIDs.isEmpty()) return@edit + store.bind(memory.displayName, emptyList(), emptySet()) + } + + private fun edit(block: (SceneStore.Snapshot) -> Unit) { + viewModelScope.launch { + mutex.withLock { + withContext(ioDispatcher) { block(store.current()) } + } + } + } + + companion object { + /** iOS 的拆法:逗号、全角逗号、顿号,去掉首尾空白和空项。 */ + fun parseKeywords(text: String): List = + text.split(',', ',', '、').map { it.trim() }.filter { it.isNotEmpty() } + + internal fun bindings(scenes: List, memories: Map): List { + val byId = scenes.associateBy { it.id } + return memories.entries + .filter { it.value.boundSceneIDs.isNotEmpty() } + .sortedBy { it.value.displayName } + .map { (key, memory) -> + GroupBinding( + key = key, + displayName = memory.displayName, + scenes = memory.boundSceneIDs.map { id -> + val scene = byId[id] + BoundScene(id, scene?.name, scene?.enabled ?: false) + }, + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsBubble.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsBubble.kt new file mode 100644 index 00000000..678abe8a --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsBubble.kt @@ -0,0 +1,365 @@ +package com.xiangming.wechatbridge.ui.settings + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.bubble.BubbleService +import com.xiangming.wechatbridge.bubble.BubbleToggle +import com.xiangming.wechatbridge.bubble.OverlayPermission +import com.xiangming.wechatbridge.fill.FillAccess +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.LocalAppColors + +/** + * 「悬浮球」与「一键填入(无障碍)」:作为核心能力分组卡片内的两项,行间用细线分隔。 + */ +@Composable +internal fun BubbleSettingsBlock() { + val context = LocalContext.current + val settings = (context.applicationContext as App).container.bubbleSettings + val enabled by settings.enabled.collectAsStateWithLifecycle() + val autoHideWhenEmpty by settings.autoHideWhenEmpty.collectAsStateWithLifecycle() + val zeroOverlayMode by settings.zeroOverlayMode.collectAsStateWithLifecycle() + var awaiting by rememberSaveable { mutableStateOf(false) } + var denied by rememberSaveable { mutableStateOf(false) } + var tick by remember { mutableIntStateOf(0) } + val canDraw = remember(tick) { OverlayPermission.canDraw(context) } + val appColors = LocalAppColors.current + + fun apply(action: BubbleToggle.Action?, launch: () -> Unit) { + when (action) { + BubbleToggle.Action.ENABLE -> { + awaiting = false + denied = false + settings.setEnabled(true) + BubbleService.sync(context) + } + BubbleToggle.Action.DISABLE -> { + awaiting = false + denied = false + settings.setEnabled(false) + BubbleService.sync(context) + } + BubbleToggle.Action.REQUEST_PERMISSION -> { + awaiting = true + launch() + } + null -> Unit + } + } + + val permissionPage = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { + tick++ + val now = OverlayPermission.canDraw(context) + val action = BubbleToggle.onReturn(awaiting, now) + if (action == null && awaiting) { + awaiting = false + denied = true + } + apply(action) {} + } + val openPermissionPage = { runCatching { permissionPage.launch(OverlayPermission.settingsIntent(context)) } } + + // Some ROMs return without a result; resuming re-checks too. + LifecycleResumeEffect(Unit) { + tick++ + apply(BubbleToggle.onReturn(awaiting, OverlayPermission.canDraw(context))) {} + onPauseOrDispose {} + } + + val checked = enabled && canDraw + Column { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier + .fillMaxWidth() + .toggleable(value = checked, role = Role.Switch) { on -> + apply(BubbleToggle.onSwitch(on, OverlayPermission.canDraw(context))) { openPermissionPage() } + } + .padding(horizontal = 16.dp, vertical = 14.dp), + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(RoundedCornerShape(10.dp)) + .background(if (checked) appColors.surfaceTint else appColors.surfaceSub), + contentAlignment = Alignment.Center, + ) { + Icon( + AppIcons.NavRelay, + contentDescription = null, + tint = if (checked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(19.dp), + ) + } + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text(stringResource(R.string.bubble_settings_title), style = MaterialTheme.typography.titleMedium) + Text( + stringResource(R.string.bubble_settings_summary), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Switch(checked = checked, onCheckedChange = null) + } + val status = when { + enabled && !canDraw -> R.string.bubble_settings_permission_missing + denied -> R.string.bubble_settings_permission_denied + !canDraw -> R.string.bubble_settings_permission_needed + else -> null + } + status?.let { + val problem = it != R.string.bubble_settings_permission_needed + Text( + stringResource(it), + style = MaterialTheme.typography.bodySmall, + color = if (problem) MaterialTheme.colorScheme.error else appColors.onSurfaceMuted, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + ) + if (problem) { + OutlinedButton( + onClick = { + awaiting = true + openPermissionPage() + }, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 10.dp), + ) { Text(stringResource(R.string.bubble_settings_grant)) } + } + } + if (OverlayPermission.isXiaomi) { + Text( + stringResource(R.string.bubble_settings_xiaomi_hint), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + ) + OutlinedButton( + onClick = { OverlayPermission.openXiaomiPermissions(context) }, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 10.dp), + ) { Text(stringResource(R.string.bubble_settings_xiaomi_open)) } + } + if (checked) { + BubbleSubToggleRow( + title = stringResource(R.string.bubble_settings_auto_hide_title), + summary = stringResource(R.string.bubble_settings_auto_hide_summary), + checked = autoHideWhenEmpty, + enabled = !zeroOverlayMode, + onCheckedChange = { settings.setAutoHideWhenEmpty(it) }, + ) + BubbleSubToggleRow( + title = stringResource(R.string.bubble_settings_zero_overlay_title), + summary = stringResource(R.string.bubble_settings_zero_overlay_summary), + checked = zeroOverlayMode, + enabled = true, + onCheckedChange = { settings.setZeroOverlayMode(it) }, + ) + Text( + stringResource(R.string.bubble_settings_notification_hint), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 10.dp), + ) + } + + HorizontalDivider( + modifier = Modifier.padding(horizontal = 16.dp), + thickness = 0.75.dp, + color = appColors.subtleDivider, + ) + + FillSettingsBlock() + } +} + +@Composable +private fun BubbleSubToggleRow( + title: String, + summary: String, + checked: Boolean, + enabled: Boolean, + onCheckedChange: (Boolean) -> Unit, +) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier + .fillMaxWidth() + .alpha(if (enabled) 1f else 0.45f) + .toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onCheckedChange) + .padding(start = 24.dp, end = 16.dp, top = 8.dp, bottom = 8.dp), + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text(title, style = MaterialTheme.typography.bodyMedium) + Text( + summary, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Switch(checked = checked, onCheckedChange = null, enabled = enabled) + } +} + +/** + * 「一键填入(无障碍)」:图标使用 AppIcons.FillInput,状态使用轻盈徽章胶囊。 + */ +@Composable +private fun FillSettingsBlock() { + val context = LocalContext.current + val appColors = LocalAppColors.current + var tick by remember { mutableIntStateOf(0) } + LifecycleResumeEffect(Unit) { + tick++ + onPauseOrDispose {} + } + val state = remember(tick) { FillAccess.state(context) } + val isReady = state == FillAccess.State.READY + val isNotRunning = state == FillAccess.State.NOT_RUNNING + + val badgeBg = when { + isReady -> appColors.surfaceTint + isNotRunning -> MaterialTheme.colorScheme.error.copy(alpha = 0.12f) + else -> appColors.surfaceSub + } + val badgeFg = when { + isReady -> MaterialTheme.colorScheme.primary + isNotRunning -> MaterialTheme.colorScheme.error + else -> MaterialTheme.colorScheme.onSurfaceVariant + } + + Column { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 14.dp), + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(RoundedCornerShape(10.dp)) + .background(if (isReady) appColors.surfaceTint else appColors.surfaceSub), + contentAlignment = Alignment.Center, + ) { + Icon( + AppIcons.FillInput, + contentDescription = null, + tint = if (isReady) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(19.dp), + ) + } + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text(stringResource(R.string.fill_settings_title), style = MaterialTheme.typography.titleMedium) + Text( + stringResource(R.string.fill_settings_summary), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Box( + modifier = Modifier + .clip(RoundedCornerShape(999.dp)) + .background(badgeBg) + .padding(horizontal = 10.dp, vertical = 4.dp), + ) { + Text( + stringResource(if (state == FillAccess.State.OFF) R.string.fill_settings_off else R.string.fill_settings_on), + style = MaterialTheme.typography.labelMedium, + color = badgeFg, + ) + } + } + if (isNotRunning) { + Text( + stringResource(R.string.fill_settings_not_running), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + ) + } + if (!isReady) { + if (FillAccess.mayBeRestricted) { + Text( + stringResource(R.string.fill_guide_restricted), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + ) + } + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 12.dp), + ) { + OutlinedButton( + onClick = { FillAccess.openAccessibilitySettings(context) }, + shape = RoundedCornerShape(12.dp), + ) { + Text(stringResource(R.string.fill_guide_open_settings)) + } + if (FillAccess.mayBeRestricted) { + OutlinedButton( + onClick = { FillAccess.openAppDetails(context) }, + shape = RoundedCornerShape(12.dp), + ) { + Text(stringResource(R.string.fill_guide_open_details)) + } + } + } + } + if (OverlayPermission.isXiaomi) { + Text( + stringResource(R.string.fill_settings_xiaomi_hint), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 12.dp), + ) + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsDiagnostics.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsDiagnostics.kt new file mode 100644 index 00000000..7afe1fc0 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsDiagnostics.kt @@ -0,0 +1,38 @@ +package com.xiangming.wechatbridge.ui.settings + +import com.xiangming.wechatbridge.core.util.DiagnosticsLog +import java.io.File +import java.time.Instant + +/** + * 导出的诊断文本:版本与设置状态,加上最近的脱敏导入记录([DiagnosticsLog] 写的 JSON)。 + * 不含聊天内容、文件夹名与完整文件名。标签用英文,报告是给开发者看、可直接贴进 issue 的。 + */ +object SettingsDiagnostics { + fun report(appInfo: AppInfo, state: SettingsUiState, records: File, now: Instant): String = buildString { + appendLine("WeChatBridge Android diagnostics") + appendLine("generated: $now") + appendLine("version: ${appInfo.versionName ?: "?"} (${appInfo.versionCode})") + appendLine("android: ${appInfo.androidRelease} (sdk ${appInfo.sdkInt})") + appendLine("device: ${appInfo.device}") + appendLine("retentionDays: ${state.retentionDays}") + appendLine("saveEntryEnabled: ${state.saveEntryEnabled}") + appendLine("collectEntryEnabled: ${state.collectEntryEnabled}") + appendLine("vault: ${state.vault.status ?: "UNKNOWN"}") + appendLine("folder: ${state.folder.status ?: "UNKNOWN"}") + + val files = recordFiles(records) + appendLine("records: ${files.size} (newest first, at most ${DiagnosticsLog.RETAINED_RECORDS})") + for (file in files) { + appendLine() + appendLine("--- ${file.name} ---") + appendLine(runCatching { file.readText(Charsets.UTF_8).trimEnd() }.getOrDefault("(unreadable)")) + } + } + + private fun recordFiles(directory: File): List = + directory.listFiles { file -> file.isFile && !file.name.startsWith(".") } + .orEmpty() + .sortedByDescending { it.lastModified() } + .take(DiagnosticsLog.RETAINED_RECORDS) +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsScreen.kt new file mode 100644 index 00000000..845066a4 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsScreen.kt @@ -0,0 +1,938 @@ +package com.xiangming.wechatbridge.ui.settings + +import android.Manifest +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.provider.Settings +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.verticalScroll +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Lock +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.saf.TreeStatus +import com.xiangming.wechatbridge.ui.theme.AppIcons +import com.xiangming.wechatbridge.ui.theme.BridgeAmbientBackdrop +import com.xiangming.wechatbridge.ui.theme.BridgeBentoCard +import com.xiangming.wechatbridge.ui.theme.BridgePrimaryCapsuleButton +import com.xiangming.wechatbridge.ui.theme.LocalAppColors +import com.xiangming.wechatbridge.ui.theme.WeChatGreen + +/** 保留天数的可选项;0 是「从不清理」。 */ +internal val RetentionOptions = listOf(1, 3, 7, 30, 0) + +/** + * 设置页(UI 2.0 Bento 可视化连接面板): + * - 顶部品牌头卡(图标 + 名称 + 版本胶囊 + 本地隐私徽章) + * - 2 列知识库连接 Bento 卡片(Obsidian 库 & 默认文件夹)+ 子目录配置 + * - 投递目标卡片 / 核心能力卡片 / 收集与中转站卡片 / 支持与关于卡片 + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen( + onBack: () -> Unit, + onOpenScenes: () -> Unit, + onOpenOnboarding: () -> Unit, + onOpenTargets: () -> Unit, + showBack: Boolean = false, +) { + val context = LocalContext.current + val container = (context.applicationContext as App).container + val viewModel = viewModel { + SettingsViewModel( + preferences = container.preferences, + treeStore = container.treeStore, + entries = PackageEntryComponents(container.appContext), + diagnosticsDirectory = container.inbox.diagnostics, + appInfo = AppInfo.read(container.appContext), + ) + } + val state by viewModel.state.collectAsStateWithLifecycle() + val snackbar = remember { SnackbarHostState() } + val appColors = LocalAppColors.current + val appInfo = remember(context) { AppInfo.read(context) } + + // 通知状态随前台变化(用户可能刚从系统设置回来)。 + var resumeTick by remember { mutableIntStateOf(0) } + LifecycleResumeEffect(Unit) { + viewModel.refresh() + resumeTick++ + onPauseOrDispose {} + } + + val message = state.message?.let { messageText(it) } + LaunchedEffect(state.message) { + if (message != null) { + snackbar.showSnackbar(message) + viewModel.consumeMessage() + } + } + + val pickVault = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { + viewModel.pickTree(TargetKind.VAULT, it) + } + val pickFolder = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { + viewModel.pickTree(TargetKind.FOLDER, it) + } + val export = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) { uri -> + if (uri != null) { + viewModel.exportDiagnostics { context.contentResolver.openOutputStream(uri, "wt") } + } + } + val exportName = stringResource(R.string.settings_diagnostics_file_name) + + Box(modifier = Modifier.fillMaxSize()) { + BridgeAmbientBackdrop() + Scaffold( + containerColor = Color.Transparent, + topBar = { + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + scrolledContainerColor = Color.Transparent, + ), + title = { + Text( + stringResource(R.string.nav_settings), + style = if (showBack) MaterialTheme.typography.titleLarge else MaterialTheme.typography.headlineMedium, + ) + }, + navigationIcon = { + if (showBack) { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.action_back), + ) + } + } + }, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(18.dp), + ) { + // 顶部品牌头卡 + BrandHeaderCard(appInfo = appInfo) + + // 2 列知识库连接 Bento 卡片 + 子目录配置 + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + SectionLabel(title = stringResource(R.string.settings_group_delivery_storage)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + StorageBentoTile( + modifier = Modifier.weight(1f), + title = stringResource(R.string.settings_vault_title), + folder = state.vault, + chooseDescription = stringResource(R.string.settings_vault_choose_desc), + rechooseDescription = stringResource(R.string.settings_vault_rechoose_desc), + clearDescription = stringResource(R.string.settings_vault_clear_desc), + onPick = { pickVault.launch(null) }, + onClear = { viewModel.clearTree(TargetKind.VAULT) }, + ) + StorageBentoTile( + modifier = Modifier.weight(1f), + title = stringResource(R.string.settings_folder_title), + folder = state.folder, + chooseDescription = stringResource(R.string.settings_folder_choose_desc), + rechooseDescription = stringResource(R.string.settings_folder_rechoose_desc), + clearDescription = stringResource(R.string.settings_folder_clear_desc), + onPick = { pickFolder.launch(null) }, + onClear = { viewModel.clearTree(TargetKind.FOLDER) }, + ) + } + // 2 列紧凑子文件夹输入栏(与上方两张 Bento 卡对齐) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + CompactSubfolderPill( + modifier = Modifier.weight(1f), + value = state.vault.subfolder, + defaultSubfolder = viewModel.defaultSubfolder, + label = stringResource(R.string.settings_vault_subfolder_label), + onValueChange = { viewModel.setSubfolder(TargetKind.VAULT, it) }, + ) + CompactSubfolderPill( + modifier = Modifier.weight(1f), + value = state.folder.subfolder, + defaultSubfolder = viewModel.defaultSubfolder, + label = stringResource(R.string.settings_folder_subfolder_label), + onValueChange = { viewModel.setSubfolder(TargetKind.FOLDER, it) }, + ) + } + Text( + stringResource(R.string.settings_storage_intro), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + modifier = Modifier.padding(horizontal = 4.dp), + ) + // 投递目标入口卡(放在同一存储与投递分组内,避免重复分组标题) + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + contentPadding = PaddingValues(0.dp), + ) { + NavRow( + title = stringResource(R.string.nav_targets), + summary = stringResource(R.string.settings_targets_summary), + trailingText = "调整", + trailingHighlight = true, + onClick = onOpenTargets, + ) + if (showBack) { + SubtleSettingsDivider() + NavRow( + title = stringResource(R.string.nav_scenes), + summary = stringResource(R.string.settings_scenes_summary), + onClick = onOpenScenes, + ) + } + } + } + + // 核心能力(悬浮球 + 一键填入无障碍) + SettingsSection(title = stringResource(R.string.settings_group_core)) { + BubbleSettingsBlock() + } + + // 收集与中转站(系统分享入口开关 + 自动清理周期 + 通知权限) + SettingsSection(title = stringResource(R.string.settings_group_collect_relay)) { + EntrySwitch( + title = stringResource(R.string.settings_entry_save_title), + summary = stringResource(R.string.settings_entry_save_summary), + checked = state.saveEntryEnabled, + locked = state.isLastEntry(ShareEntry.SAVE), + onChange = { viewModel.setEntryEnabled(ShareEntry.SAVE, it) }, + ) + SubtleSettingsDivider() + EntrySwitch( + title = stringResource(R.string.settings_entry_collect_title), + summary = stringResource(R.string.settings_entry_collect_summary), + checked = state.collectEntryEnabled, + locked = state.isLastEntry(ShareEntry.COLLECT), + onChange = { viewModel.setEntryEnabled(ShareEntry.COLLECT, it) }, + ) + if (state.isLastEntry(ShareEntry.SAVE) || state.isLastEntry(ShareEntry.COLLECT)) { + Text( + stringResource(R.string.settings_entries_last_hint), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 10.dp), + ) + } + SubtleSettingsDivider() + RetentionRow(days = state.retentionDays, onSelect = viewModel::setRetentionDays) + SubtleSettingsDivider() + NotificationRow(resumeTick = resumeTick) + } + + // 支持与关于(重新查看新手引导 + 导出诊断日志 + 官网 + 关于版本) + SettingsSection(title = stringResource(R.string.settings_group_support_about)) { + NavRow( + title = stringResource(R.string.settings_onboarding_replay), + onClick = onOpenOnboarding, + ) + SubtleSettingsDivider() + NavRow( + title = stringResource(R.string.settings_diagnostics_export), + summary = stringResource(R.string.settings_diagnostics_summary), + onClick = { export.launch(exportName) }, + ) + SubtleSettingsDivider() + AboutRows() + } + + Spacer(Modifier.navigationBarsPadding().height(116.dp)) + } + } + } +} + +@Composable +private fun BrandHeaderCard(appInfo: AppInfo) { + val appColors = LocalAppColors.current + val versionPill = appInfo.versionName?.let { "v$it" } + ?: stringResource(R.string.settings_version_unknown) + + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 22.dp, + highlighted = true, + contentPadding = PaddingValues(16.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + ) { + Image( + painter = painterResource(R.drawable.logo_wechatbridge), + contentDescription = stringResource(R.string.app_name), + contentScale = ContentScale.Crop, + modifier = Modifier + .size(52.dp) + .clip(RoundedCornerShape(14.dp)) + .border( + width = 0.75.dp, + color = appColors.surfaceTintBorder, + shape = RoundedCornerShape(14.dp), + ), + ) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = stringResource(R.string.app_name), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Box( + modifier = Modifier + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.85f)) + .border(0.75.dp, appColors.surfaceTintBorder, CircleShape) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) { + Text( + text = versionPill, + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.primary, + maxLines = 1, + ) + } + } + Row( + verticalAlignment = Alignment.Top, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + Icon( + imageVector = Icons.Filled.Lock, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier + .padding(top = 2.dp) + .size(12.dp), + ) + Text( + text = stringResource(R.string.settings_privacy_note), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + ) + } + } + } + } +} + +@Composable +private fun StorageBentoTile( + title: String, + folder: FolderState, + chooseDescription: String, + rechooseDescription: String, + clearDescription: String, + onPick: () -> Unit, + onClear: () -> Unit, + modifier: Modifier = Modifier, +) { + val appColors = LocalAppColors.current + val connected = folder.status == TreeStatus.GRANTED + val lost = folder.status == TreeStatus.LOST + val statusText = when (folder.status) { + null -> stringResource(R.string.settings_tree_checking) + TreeStatus.NOT_CHOSEN -> stringResource(R.string.settings_tree_not_chosen) + TreeStatus.LOST -> stringResource(R.string.settings_tree_lost) + TreeStatus.GRANTED -> folder.name ?: stringResource(R.string.settings_tree_unnamed) + } + val dotColor = when { + connected -> WeChatGreen + lost -> MaterialTheme.colorScheme.error + else -> appColors.onSurfaceMuted + } + val badgeBg = when { + connected -> appColors.surfaceTint + lost -> MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.5f) + else -> appColors.surfaceSub + } + val badgeText = when { + connected -> "已连接" + lost -> stringResource(R.string.settings_tree_lost) + folder.status == null -> stringResource(R.string.settings_tree_checking) + else -> stringResource(R.string.settings_tree_not_chosen) + } + + BridgeBentoCard( + modifier = modifier, + cornerRadius = 20.dp, + highlighted = connected, + contentPadding = PaddingValues(14.dp), + ) { + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + // 状态胶囊 + Row( + modifier = Modifier + .clip(CircleShape) + .background(badgeBg) + .padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + Box( + modifier = Modifier + .size(7.dp) + .clip(CircleShape) + .background(dotColor), + ) + Text( + text = badgeText, + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Medium, + color = if (connected) MaterialTheme.colorScheme.primary else if (lost) MaterialTheme.colorScheme.error else appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + + Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = if (connected || lost) statusText else "点下方选择目录", + style = MaterialTheme.typography.bodySmall, + color = if (lost) MaterialTheme.colorScheme.error else appColors.onSurfaceMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + + val picked = folder.chosen + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(34.dp) + .clip(CircleShape) + .background(if (picked) appColors.surfaceSub else appColors.surfaceTint) + .border( + width = 0.75.dp, + color = if (picked) MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f) else appColors.surfaceTintBorder, + shape = CircleShape, + ) + .clickable(role = Role.Button, onClick = onPick) + .semantics { + contentDescription = if (picked) rechooseDescription else chooseDescription + }, + contentAlignment = Alignment.Center, + ) { + Text( + text = stringResource(if (picked) R.string.settings_tree_rechoose else R.string.settings_tree_choose), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = if (picked) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.primary, + maxLines = 1, + ) + } + if (picked) { + Box( + modifier = Modifier + .fillMaxWidth() + .clip(CircleShape) + .clickable(onClick = onClear) + .semantics { contentDescription = clearDescription } + .padding(vertical = 3.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = stringResource(R.string.settings_tree_clear), + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + ) + } + } + } + } + } +} + +@Composable +private fun CompactSubfolderPill( + value: String, + defaultSubfolder: String, + label: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, +) { + val appColors = LocalAppColors.current + val shape = RoundedCornerShape(14.dp) + Row( + modifier = modifier + .height(40.dp) + .clip(shape) + .background(MaterialTheme.colorScheme.surface) + .border(0.75.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.75f), shape) + .padding(horizontal = 11.dp) + .semantics { contentDescription = label }, + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + text = "子目录", + style = MaterialTheme.typography.labelSmall, + color = appColors.onSurfaceMuted, + maxLines = 1, + ) + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.CenterStart, + ) { + if (value.isEmpty()) { + Text( + text = defaultSubfolder, + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted.copy(alpha = 0.75f), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + BasicTextField( + value = value, + onValueChange = onValueChange, + singleLine = true, + textStyle = MaterialTheme.typography.bodySmall.copy( + color = MaterialTheme.colorScheme.onSurface, + ), + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + modifier = Modifier.fillMaxWidth(), + ) + } + } +} + +@Composable +private fun SectionLabel(title: String) { + Text( + title, + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.Medium, + color = LocalAppColors.current.onSurfaceMuted, + modifier = Modifier.padding(horizontal = 6.dp), + ) +} + +@Composable +private fun SettingsSection( + title: String, + content: @Composable ColumnScope.() -> Unit, +) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + SectionLabel(title = title) + BridgeBentoCard( + modifier = Modifier.fillMaxWidth(), + cornerRadius = 20.dp, + contentPadding = PaddingValues(0.dp), + content = content, + ) + } +} + +@Composable +private fun SubtleSettingsDivider() { + HorizontalDivider( + modifier = Modifier.padding(horizontal = 16.dp), + thickness = 0.75.dp, + color = LocalAppColors.current.subtleDivider, + ) +} + +@Composable +private fun messageText(message: SettingsMessage): String = stringResource( + when (message) { + SettingsMessage.LAST_ENTRY -> R.string.settings_entries_last_message + SettingsMessage.FOLDER_REFUSED -> R.string.settings_tree_refused + SettingsMessage.EXPORT_OK -> R.string.settings_diagnostics_ok + SettingsMessage.EXPORT_FAILED -> R.string.settings_diagnostics_failed + }, +) + +@Composable +private fun NavRow( + title: String, + summary: String? = null, + trailingText: String? = null, + trailingHighlight: Boolean = false, + onClick: () -> Unit, +) { + val appColors = LocalAppColors.current + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 14.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(3.dp), + ) { + Text( + title, + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + ) + if (!summary.isNullOrEmpty()) { + Text( + summary, + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + ) + } + } + if (trailingText != null) { + Text( + trailingText, + style = MaterialTheme.typography.labelMedium, + fontWeight = if (trailingHighlight) FontWeight.SemiBold else FontWeight.Normal, + color = if (trailingHighlight) MaterialTheme.colorScheme.primary else appColors.onSurfaceMuted, + ) + } + Icon( + AppIcons.ChevronRight, + contentDescription = null, + tint = if (trailingHighlight) MaterialTheme.colorScheme.primary else appColors.onSurfaceMuted, + modifier = Modifier.size(16.dp), + ) + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun RetentionRow(days: Int, onSelect: (Int) -> Unit) { + val appColors = LocalAppColors.current + // 已存的值不在选项里(别的端写的)时也列出来,免得看起来一个都没选。 + val options = if (days in RetentionOptions) RetentionOptions else listOf(days) + RetentionOptions + + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 14.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(R.string.settings_retention_title), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + ) + Text( + text = retentionLabel(days), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Medium, + ) + } + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + for (option in options) { + val selected = option == days + Surface( + shape = CircleShape, + color = if (selected) MaterialTheme.colorScheme.primary else appColors.surfaceSub, + border = if (selected) null else BorderStroke(0.75.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.65f)), + modifier = Modifier + .clip(CircleShape) + .clickable(role = Role.RadioButton) { onSelect(option) }, + ) { + Text( + text = retentionLabel(option), + style = MaterialTheme.typography.labelMedium, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, + color = if (selected) Color.White else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), + ) + } + } + } + } +} + +@Composable +private fun retentionLabel(days: Int): String = + if (days <= 0) stringResource(R.string.settings_retention_forever) else stringResource(R.string.settings_retention_days, days) + +@Composable +private fun EntrySwitch(title: String, summary: String, checked: Boolean, locked: Boolean, onChange: (Boolean) -> Unit) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier + .fillMaxWidth() + .toggleable(value = checked, enabled = !locked, role = Role.Switch, onValueChange = onChange) + .padding(horizontal = 16.dp, vertical = 12.dp), + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text(title, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium) + Text(summary, style = MaterialTheme.typography.bodySmall, color = LocalAppColors.current.onSurfaceMuted) + } + Switch(checked = checked, onCheckedChange = null, enabled = !locked) + } +} + +@Composable +private fun NotificationRow(resumeTick: Int) { + val context = LocalContext.current + val appColors = LocalAppColors.current + var requestedDenied by rememberSaveable { mutableStateOf(false) } + var tick by remember { mutableIntStateOf(0) } + + val runtimePermission = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU + val permissionGranted = !runtimePermission || ContextCompat.checkSelfPermission( + context, + Manifest.permission.POST_NOTIFICATIONS, + ) == PackageManager.PERMISSION_GRANTED + // 回到前台(resumeTick)或权限结果回来(tick)后重算。 + val enabled = remember(resumeTick, tick) { NotificationManagerCompat.from(context).areNotificationsEnabled() } + val allowed = permissionGranted && enabled + + val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + tick++ + if (!granted) requestedDenied = true + } + + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + stringResource(R.string.settings_notifications_title), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + ) + if (!allowed) { + Text( + stringResource( + if (!permissionGranted) R.string.settings_notifications_denied + else R.string.settings_notifications_disabled, + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + } + if (allowed) { + Box( + modifier = Modifier + .clip(RoundedCornerShape(999.dp)) + .background(appColors.surfaceTint) + .padding(horizontal = 10.dp, vertical = 4.dp), + ) { + Text( + stringResource(R.string.settings_notifications_granted), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + } + } + if (!allowed) { + val rationale = context.findActivity() + ?.shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) ?: false + val permanentlyDenied = requestedDenied && !rationale + val canAsk = runtimePermission && !permissionGranted && !permanentlyDenied + Box( + modifier = Modifier + .padding(top = 10.dp) + .clip(CircleShape) + .background(appColors.surfaceTint) + .border(0.75.dp, appColors.surfaceTintBorder, CircleShape) + .clickable(role = Role.Button) { + if (canAsk) launcher.launch(Manifest.permission.POST_NOTIFICATIONS) else openNotificationSettings(context) + } + .padding(horizontal = 16.dp, vertical = 8.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = stringResource( + if (canAsk) R.string.settings_notifications_request else R.string.settings_notifications_open_settings, + ), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + ) + } + } + } +} + +@Composable +private fun AboutRows() { + val context = LocalContext.current + val info = remember { AppInfo.read(context) } + val websiteUrl = stringResource(R.string.settings_website_url) + val appColors = LocalAppColors.current + + NavRow( + title = stringResource(R.string.settings_website_title), + summary = "访问官网与使用说明", + onClick = { openUrl(context, websiteUrl) }, + ) + SubtleSettingsDivider() + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 14.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stringResource(R.string.settings_version_title), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + ) + Text( + info.versionName?.let { stringResource(R.string.settings_version_value, it, info.versionCode) } + ?: stringResource(R.string.settings_version_unknown), + style = MaterialTheme.typography.bodySmall, + color = appColors.onSurfaceMuted, + ) + } +} + +private fun Context.findActivity(): Activity? { + var current: Context? = this + while (current is ContextWrapper) { + if (current is Activity) return current + current = current.baseContext + } + return null +} + +private fun openNotificationSettings(context: Context) { + val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + runCatching { context.startActivity(intent) } +} + +private fun openUrl(context: Context, url: String) { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + runCatching { context.startActivity(intent) } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsViewModel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsViewModel.kt new file mode 100644 index 00000000..19ffe0ff --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsViewModel.kt @@ -0,0 +1,284 @@ +package com.xiangming.wechatbridge.ui.settings + +import android.content.ComponentName +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.net.Uri +import androidx.core.content.pm.PackageInfoCompat +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.note.NoteDelivery +import com.xiangming.wechatbridge.data.Preferences +import com.xiangming.wechatbridge.saf.TreeStatus +import com.xiangming.wechatbridge.saf.TreeStore +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.io.OutputStream +import java.time.Instant + +/** 系统分享面板里的两个入口,对应 Manifest 里的 activity-alias。 */ +enum class ShareEntry(val className: String) { + /** 「存入微信流」。 */ + SAVE("com.xiangming.wechatbridge.receive.SaveAlias"), + + /** 「分批收集到微信流」。 */ + COLLECT("com.xiangming.wechatbridge.receive.CollectAlias"), + ; + + val other: ShareEntry get() = if (this == SAVE) COLLECT else SAVE +} + +/** 入口别名的启用状态;生产实现是 [PackageEntryComponents]。 */ +interface EntryComponents { + fun isEnabled(entry: ShareEntry): Boolean + fun setEnabled(entry: ShareEntry, enabled: Boolean) +} + +class PackageEntryComponents(context: Context) : EntryComponents { + private val app = context.applicationContext + private val packageManager = app.packageManager + + private fun component(entry: ShareEntry) = ComponentName(app.packageName, entry.className) + + override fun isEnabled(entry: ShareEntry): Boolean { + val component = component(entry) + return when (packageManager.getComponentEnabledSetting(component)) { + PackageManager.COMPONENT_ENABLED_STATE_ENABLED -> true + PackageManager.COMPONENT_ENABLED_STATE_DISABLED, + PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER, + PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, + -> false + // 没有覆盖:按 Manifest 声明(默认启用)。 + else -> runCatching { + @Suppress("DEPRECATION") + packageManager.getActivityInfo(component, PackageManager.GET_DISABLED_COMPONENTS).enabled + }.getOrDefault(true) + } + } + + override fun setEnabled(entry: ShareEntry, enabled: Boolean) { + packageManager.setComponentEnabledSetting( + component(entry), + if (enabled) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED, + PackageManager.DONT_KILL_APP, + ) + } +} + +/** 「关于」与诊断报告用到的应用信息。 */ +data class AppInfo( + /** null:读不到。 */ + val versionName: String?, + val versionCode: Long, + val androidRelease: String, + val sdkInt: Int, + val device: String, +) { + companion object { + fun read(context: Context): AppInfo { + val info = runCatching { + @Suppress("DEPRECATION") + context.packageManager.getPackageInfo(context.packageName, 0) + }.getOrNull() + return AppInfo( + versionName = info?.versionName, + versionCode = info?.let { PackageInfoCompat.getLongVersionCode(it) } ?: 0L, + androidRelease = Build.VERSION.RELEASE.orEmpty(), + sdkInt = Build.VERSION.SDK_INT, + device = listOf(Build.MANUFACTURER, Build.MODEL).filter { !it.isNullOrBlank() }.joinToString(" "), + ) + } + } +} + +/** 一个保存位置(Obsidian 库 / 默认文件夹)现在的样子。 */ +data class FolderState( + val kind: TargetKind, + /** null:正在检查(要读文档提供方)。 */ + val status: TreeStatus? = TreeStatus.NOT_CHOSEN, + /** 已选目录的显示名;未选、失效或读不到时为 null。 */ + val name: String? = null, + /** 用户输入的子文件夹原样;空表示用默认名。 */ + val subfolder: String = "", +) { + val chosen: Boolean get() = status != TreeStatus.NOT_CHOSEN +} + +/** 一次性提示,由页面翻译成文案。 */ +enum class SettingsMessage { LAST_ENTRY, FOLDER_REFUSED, EXPORT_OK, EXPORT_FAILED } + +data class SettingsUiState( + val vault: FolderState = FolderState(TargetKind.VAULT), + val folder: FolderState = FolderState(TargetKind.FOLDER), + /** 0:从不清理。 */ + val retentionDays: Int = Preferences.DEFAULT_RETENTION_DAYS, + val saveEntryEnabled: Boolean = true, + val collectEntryEnabled: Boolean = true, + val message: SettingsMessage? = null, + /** 保留天数等偏好读出来之后为 true;之前显示的是默认值。 */ + val loaded: Boolean = false, +) { + fun entryEnabled(entry: ShareEntry): Boolean = if (entry == ShareEntry.SAVE) saveEntryEnabled else collectEntryEnabled + + /** 只剩这一个入口开着:它的开关要锁住。 */ + fun isLastEntry(entry: ShareEntry): Boolean = entryEnabled(entry) && !entryEnabled(entry.other) + + fun folder(kind: TargetKind): FolderState = if (kind == TargetKind.VAULT) vault else folder +} + +class SettingsViewModel( + private val preferences: Preferences, + private val treeStore: TreeStore, + private val entries: EntryComponents, + /** `/inbox/diagnostics`:脱敏的导入记录。 */ + private val diagnosticsDirectory: File, + private val appInfo: AppInfo, + private val io: CoroutineDispatcher = Dispatchers.IO, + private val now: () -> Instant = { Instant.now() }, +) : ViewModel() { + /** 状态与名称要读文档提供方,查询结果连同当时的 uri 一起存,uri 变了就当作过期。 */ + private data class Detail(val uri: Uri?, val status: TreeStatus, val name: String?) + + private val details = MutableStateFlow>(emptyMap()) + private val entryStates = MutableStateFlow(readEntries()) + private val message = MutableStateFlow(null) + + val state: StateFlow = combine( + treeStore.roots, + details, + preferences.retentionDays, + entryStates, + message, + ) { roots, details, retention, entryStates, message -> + fun folder(kind: TargetKind): FolderState { + val root = roots.getValue(kind) + val detail = details[kind]?.takeIf { it.uri == root.uri } + return FolderState( + kind = kind, + status = if (root.uri == null) TreeStatus.NOT_CHOSEN else detail?.status, + name = detail?.name, + subfolder = root.subfolder, + ) + } + SettingsUiState( + vault = folder(TargetKind.VAULT), + folder = folder(TargetKind.FOLDER), + retentionDays = retention, + saveEntryEnabled = entryStates.getValue(ShareEntry.SAVE), + collectEntryEnabled = entryStates.getValue(ShareEntry.COLLECT), + message = message, + loaded = true, + ) + }.stateIn( + viewModelScope, + SharingStarted.Eagerly, + SettingsUiState( + saveEntryEnabled = entryStates.value.getValue(ShareEntry.SAVE), + collectEntryEnabled = entryStates.value.getValue(ShareEntry.COLLECT), + ), + ) + + init { + refresh() + } + + /** 回到前台时重查:授权可能在系统设置里被撤销,别名状态也可能被改。 */ + fun refresh() { + entryStates.value = readEntries() + viewModelScope.launch { + val next = withContext(io) { + TreeStore.KINDS.associateWith { kind -> + val uri = treeStore.root(kind).uri + val status = treeStore.status(kind) + val name = if (status == TreeStatus.GRANTED) treeStore.folderName(kind) else null + Detail(uri, status, name) + } + } + details.value = next + } + } + + // ---- 保存位置 ---- + + /** `OpenDocumentTree` 的结果;null 是用户取消。 */ + fun pickTree(kind: TargetKind, tree: Uri?) { + if (tree == null) return + viewModelScope.launch { + val status = withContext(io) { treeStore.grant(kind, tree) } + if (status == TreeStatus.LOST) message.value = SettingsMessage.FOLDER_REFUSED + refresh() + } + } + + fun clearTree(kind: TargetKind) { + viewModelScope.launch { + withContext(io) { treeStore.clear(kind) } + refresh() + } + } + + /** 输入框每次变化都存;写入时 [TreeStore.Root.effectiveSubfolder] 会去掉首尾空白。 */ + fun setSubfolder(kind: TargetKind, text: String) { + treeStore.setSubfolder(kind, text) + } + + // ---- 中转站 ---- + + fun setRetentionDays(days: Int) { + viewModelScope.launch { preferences.setRetentionDays(days) } + } + + // ---- 分享入口 ---- + + /** + * 启用 / 禁用 [entry] 的别名。要关掉最后一个开着的入口时拒绝(用户会无处可分享), + * 提示 [SettingsMessage.LAST_ENTRY] 并返回 false。 + */ + fun setEntryEnabled(entry: ShareEntry, enabled: Boolean): Boolean { + if (!enabled && !entries.isEnabled(entry.other)) { + message.value = SettingsMessage.LAST_ENTRY + entryStates.value = readEntries() + return false + } + entries.setEnabled(entry, enabled) + entryStates.value = readEntries() + return true + } + + private fun readEntries(): Map = ShareEntry.entries.associateWith { entries.isEnabled(it) } + + // ---- 诊断 ---- + + /** 把报告写进 [open] 给出的流(`CreateDocument` 的 uri);null 流或写失败都算失败。 */ + fun exportDiagnostics(open: () -> OutputStream?) { + viewModelScope.launch { + val ok = withContext(io) { + runCatching { + val out = open() ?: return@runCatching false + out.use { it.write(diagnosticsReport().toByteArray(Charsets.UTF_8)) } + true + }.getOrDefault(false) + } + message.value = if (ok) SettingsMessage.EXPORT_OK else SettingsMessage.EXPORT_FAILED + } + } + + internal fun diagnosticsReport(): String = + SettingsDiagnostics.report(appInfo, state.value, diagnosticsDirectory, now()) + + fun consumeMessage() { + message.value = null + } + + val defaultSubfolder: String get() = NoteDelivery.DEFAULT_FOLDER +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsScreen.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsScreen.kt new file mode 100644 index 00000000..b8994238 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsScreen.kt @@ -0,0 +1,436 @@ +package com.xiangming.wechatbridge.ui.settings + +import android.annotation.SuppressLint +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material.icons.filled.Create +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Favorite +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Send +import androidx.compose.material.icons.filled.Share +import androidx.compose.material.icons.filled.Star +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExtendedFloatingActionButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.xiangming.wechatbridge.App +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import com.xiangming.wechatbridge.ui.theme.LocalAppColors + +/** 设置 → 目标管理:轻盈白卡列表,支持显示 / 隐藏、上下移动排序、默认格式及自定义 App。 */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun TargetsScreen(onBack: () -> Unit) { + val context = LocalContext.current + val container = (context.applicationContext as App).container + val viewModel = viewModel { TargetsViewModel(container.preferences, ResolverTargetCatalog(container.targetResolver)) } + val state by viewModel.state.collectAsStateWithLifecycle() + + Scaffold( + containerColor = MaterialTheme.colorScheme.background, + topBar = { + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.background, + scrolledContainerColor = MaterialTheme.colorScheme.background, + ), + title = { + Text( + stringResource(R.string.targets_title), + style = MaterialTheme.typography.titleLarge, + ) + }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.action_back), + ) + } + }, + ) + }, + floatingActionButton = { + ExtendedFloatingActionButton( + onClick = { viewModel.openAddApp() }, + shape = RoundedCornerShape(16.dp), + containerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary, + icon = { Icon(Icons.Filled.Add, contentDescription = null) }, + text = { Text(stringResource(R.string.targets_add_app)) }, + ) + }, + ) { padding -> + LazyColumn( + modifier = Modifier.fillMaxSize().padding(padding), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 96.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + item(key = "intro") { + Text( + stringResource(R.string.targets_intro), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp), + ) + } + items(state.rows, key = { it.id }) { row -> + TargetRowItem( + row = row, + onHidden = { viewModel.setHidden(row.id, it) }, + onFormat = { viewModel.setFormat(row.id, it) }, + onUp = { viewModel.moveUp(row.id) }, + onDown = { viewModel.moveDown(row.id) }, + onRemove = { viewModel.removeCustom(row.id) }, + ) + } + } + } + + state.addApp?.let { add -> + AddAppDialog( + state = add, + onToggle = viewModel::toggleApp, + onConfirm = { viewModel.confirmAddApp() }, + onDismiss = viewModel::dismissAddApp, + ) + } +} + +@Composable +private fun TargetRowItem( + row: TargetRow, + onHidden: (Boolean) -> Unit, + onFormat: (DeliveryFormat) -> Unit, + onUp: () -> Unit, + onDown: () -> Unit, + onRemove: () -> Unit, +) { + val name = targetName(row.profile) + val switchLabel = stringResource(R.string.targets_visible_switch, name) + val appColors = LocalAppColors.current + + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surface, + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(start = 14.dp, end = 10.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Box( + modifier = Modifier + .size(42.dp) + .clip(RoundedCornerShape(12.dp)) + .background(appColors.surfaceSub) + .alpha(if (row.hidden) 0.45f else 1f), + contentAlignment = Alignment.Center, + ) { + TargetLogo(row.profile, Modifier.size(30.dp)) + } + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + name, + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.alpha(if (row.hidden) 0.5f else 1f), + ) + if (row.isCustom) { + Box( + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .background(appColors.surfaceTint) + .padding(horizontal = 6.dp, vertical = 1.dp), + ) { + Text( + stringResource(R.string.targets_custom_badge), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + } + } + } + row.installed?.let { installed -> + Text( + stringResource(if (installed) R.string.targets_installed else R.string.targets_not_installed), + style = MaterialTheme.typography.bodySmall, + color = if (installed) appColors.onSurfaceMuted else MaterialTheme.colorScheme.error, + ) + } + if (row.formatOptions.isNotEmpty()) FormatPicker(row, onFormat) + } + Column(horizontalAlignment = Alignment.End) { + Switch( + checked = !row.hidden, + onCheckedChange = { onHidden(!it) }, + modifier = Modifier.semantics { contentDescription = switchLabel }, + ) + Row { + IconButton(onClick = onUp, enabled = row.canMoveUp, modifier = Modifier.size(34.dp)) { + Icon( + Icons.Filled.KeyboardArrowUp, + contentDescription = stringResource(R.string.targets_move_up, name), + modifier = Modifier.size(20.dp), + ) + } + IconButton(onClick = onDown, enabled = row.canMoveDown, modifier = Modifier.size(34.dp)) { + Icon( + Icons.Filled.KeyboardArrowDown, + contentDescription = stringResource(R.string.targets_move_down, name), + modifier = Modifier.size(20.dp), + ) + } + if (row.isCustom) { + IconButton(onClick = onRemove, modifier = Modifier.size(34.dp)) { + Icon( + Icons.Filled.Delete, + contentDescription = stringResource(R.string.targets_remove, name), + tint = appColors.onSurfaceMuted, + modifier = Modifier.size(18.dp), + ) + } + } + } + } + } + } +} + +@Composable +private fun FormatPicker(row: TargetRow, onFormat: (DeliveryFormat) -> Unit) { + var open by remember { mutableStateOf(false) } + Box { + TextButton( + onClick = { open = true }, + contentPadding = PaddingValues(horizontal = 0.dp, vertical = 2.dp), + ) { + Text( + stringResource(R.string.targets_format_label, formatLabel(row.format)), + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Icon( + Icons.Filled.ArrowDropDown, + contentDescription = stringResource(R.string.targets_format_menu_title), + modifier = Modifier.size(18.dp), + ) + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + row.formatOptions.forEach { format -> + val label = formatLabel(format) + DropdownMenuItem( + text = { + Text(if (format == row.defaultFormat) stringResource(R.string.targets_format_default_suffix, label) else label) + }, + onClick = { + open = false + onFormat(format) + }, + ) + } + } + } +} + +@Composable +private fun AddAppDialog( + state: AddAppState, + onToggle: (String) -> Unit, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.targets_add_title)) }, + text = { + Column { + Text(stringResource(R.string.targets_add_message), style = MaterialTheme.typography.bodyMedium) + Spacer(Modifier.size(8.dp)) + when { + state.loading -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + Text(stringResource(R.string.targets_add_loading)) + } + state.apps.isEmpty() -> Text(stringResource(R.string.targets_add_empty)) + else -> LazyColumn(modifier = Modifier.weight(1f, fill = false)) { + items(state.apps, key = { it.packageName }) { app -> + Row( + modifier = Modifier.fillMaxWidth().toggleable( + value = app.packageName in state.selected, + role = Role.Checkbox, + onValueChange = { onToggle(app.packageName) }, + ), + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox(checked = app.packageName in state.selected, onCheckedChange = null) + Column { + Text(app.label, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + app.packageName, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + } + } + }, + confirmButton = { + TextButton(onClick = onConfirm, enabled = state.selected.isNotEmpty()) { + Text( + if (state.selected.isEmpty()) { + stringResource(R.string.targets_add_confirm) + } else { + stringResource(R.string.targets_add_confirm_count, state.selected.size) + }, + ) + } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) } }, + ) +} + +// ---- names and icons (private copies; the delivery panel keeps its own) ---- + +@SuppressLint("DiscouragedApi") +@Composable +private fun targetName(profile: TargetProfile): String { + profile.label?.let { return it } + val context = LocalContext.current + val id = profile.displayNameKey?.let { context.resources.getIdentifier(it, "string", context.packageName) } ?: 0 + return if (id != 0) stringResource(id) else profile.id +} + +@Composable +private fun formatLabel(format: DeliveryFormat): String = stringResource( + when (format) { + DeliveryFormat.ARCHIVE -> R.string.format_archive + DeliveryFormat.TRANSCRIPT_AND_IMAGES -> R.string.format_transcriptAndImages + DeliveryFormat.TRANSCRIPT_ONLY -> R.string.format_transcriptOnly + DeliveryFormat.INLINE_TEXT -> R.string.format_inlineText + DeliveryFormat.KNOWLEDGE_NOTE -> R.string.format_knowledgeNote + DeliveryFormat.FOLDER -> R.string.format_folder + }, +) + +@Composable +private fun TargetLogo(profile: TargetProfile, modifier: Modifier) { + val logo = logoRes(profile.logo) + if (logo != null) { + Image(painterResource(logo), contentDescription = null, modifier = modifier) + } else { + Icon( + genericIcon(profile.id), + contentDescription = null, + modifier = modifier.padding(2.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +private fun logoRes(logo: String?): Int? = when (logo) { + "logo_chatgpt" -> R.drawable.logo_chatgpt + "logo_claude" -> R.drawable.logo_claude + "logo_doubao" -> R.drawable.logo_doubao + "logo_qwen" -> R.drawable.logo_qwen + "logo_obsidian" -> R.drawable.logo_obsidian + "logo_workbuddy" -> R.drawable.logo_workbuddy + else -> null +} + +private val FolderGlyph: ImageVector by lazy { + ImageVector.Builder("Folder", 24.dp, 24.dp, 24f, 24f) + .addPath( + addPathNodes("M10,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V8c0,-1.1 -0.9,-2 -2,-2h-8l-2,-2z"), + fill = SolidColor(Color.Black), + ) + .build() +} + +private fun genericIcon(id: String): ImageVector = when (id) { + "gemini" -> Icons.Filled.Star + "yuanbao" -> Icons.Filled.Favorite + "deepseek" -> Icons.Filled.Search + "lark" -> Icons.Filled.Send + "yuque" -> Icons.Filled.Create + "minotes" -> Icons.Filled.Edit + "folder" -> FolderGlyph + else -> Icons.Filled.Share +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsViewModel.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsViewModel.kt new file mode 100644 index 00000000..77a62981 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsViewModel.kt @@ -0,0 +1,231 @@ +package com.xiangming.wechatbridge.ui.settings + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.core.deliver.CustomTargetSpec +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import com.xiangming.wechatbridge.data.Preferences +import com.xiangming.wechatbridge.deliver.Resolution +import com.xiangming.wechatbridge.deliver.ShareableApp +import com.xiangming.wechatbridge.deliver.TargetResolver +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +/** What the targets page needs from the package manager; a fake in tests. */ +interface TargetCatalog { + /** Where [profile] stands on this device. */ + fun resolution(profile: TargetProfile): Resolution + + /** Installed apps that take shares, for the "add app" list. */ + fun shareableApps(): List + + /** The probe [TargetProfile.custom] needs; null when [packageName] is not installed. */ + fun customSpec(packageName: String): CustomTargetSpec? +} + +class ResolverTargetCatalog(private val resolver: TargetResolver) : TargetCatalog { + override fun resolution(profile: TargetProfile): Resolution = resolver.resolve(profile) + override fun shareableApps(): List = resolver.shareableApps() + override fun customSpec(packageName: String): CustomTargetSpec? = resolver.customSpec(packageName) +} + +/** One line of the list. */ +data class TargetRow( + /** Already carries the user's format override. */ + val profile: TargetProfile, + val hidden: Boolean, + /** null: not an app (chooser, vault, folder), so "installed" does not apply. */ + val installed: Boolean?, + /** The format in force: the override, or [defaultFormat]. */ + val format: DeliveryFormat, + /** What the target uses when the user has not chosen. */ + val defaultFormat: DeliveryFormat, + /** Empty when the target cannot change format. */ + val formatOptions: List, + val isCustom: Boolean, + val canMoveUp: Boolean, + val canMoveDown: Boolean, +) { + val id: String get() = profile.id +} + +data class AddAppState( + val loading: Boolean = true, + val apps: List = emptyList(), + val selected: Set = emptySet(), +) + +data class TargetsUiState( + val loaded: Boolean = false, + val rows: List = emptyList(), + /** Non-null while the "add app" dialog is open. */ + val addApp: AddAppState? = null, +) + +/** + * Order, visibility, per-target default format and user-added apps, all kept in + * [Preferences]. Preferences has no key for custom targets, so a custom target + * lives as its `custom:` id in the stored target order and its + * [CustomTargetSpec] is probed again from the package manager each time; that + * is also why it resolves again after the app is reinstalled. + */ +class TargetsViewModel( + private val preferences: Preferences, + private val catalog: TargetCatalog, + private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, +) : ViewModel() { + private val addApp = MutableStateFlow(null) + private val writes = Mutex() + + val state: StateFlow = combine( + preferences.snapshot.map { TargetsUiState(loaded = true, rows = rows(it)) }.flowOn(workDispatcher), + addApp, + ) { base, add -> base.copy(addApp = add) } + .stateIn(viewModelScope, SharingStarted.Eagerly, TargetsUiState()) + + fun setHidden(id: String, hidden: Boolean): Job = viewModelScope.launch { + preferences.setHidden(id, hidden) + } + + /** [format] equal to the target's own default drops the override. */ + fun setFormat(id: String, format: DeliveryFormat): Job = viewModelScope.launch { + val raw = withContext(workDispatcher) { universe(preferences.current()) }.firstOrNull { it.id == id } + if (raw == null || !raw.canChangeFormat || !format.usesIntent) return@launch + preferences.setFormatOverride(id, format.takeIf { it != raw.format }) + } + + fun moveUp(id: String): Job = move(id, -1) + + fun moveDown(id: String): Job = move(id, 1) + + private fun move(id: String, delta: Int): Job = viewModelScope.launch { + writes.withLock { + val snapshot = preferences.current() + val ids = withContext(workDispatcher) { arrangedIds(snapshot) }.toMutableList() + val from = ids.indexOf(id) + val to = from + delta + if (from < 0 || to !in ids.indices) return@withLock + ids.add(to, ids.removeAt(from)) + preferences.setTargetOrder(ids + snapshot.targetOrder.filter { it !in ids }) + } + } + + /** Drops a user-added app together with its hidden flag and format override. */ + fun removeCustom(id: String): Job = viewModelScope.launch { + if (!id.startsWith(TargetProfile.CUSTOM_PREFIX)) return@launch + writes.withLock { + val snapshot = preferences.current() + preferences.setTargetOrder(snapshot.targetOrder.filter { it != id }) + preferences.setHidden(id, false) + preferences.setFormatOverride(id, null) + } + } + + fun openAddApp(): Job { + addApp.value = AddAppState() + return viewModelScope.launch { + val known = withContext(workDispatcher) { universe(preferences.current()) } + .flatMap { it.packageNames }.toSet() + val apps = withContext(workDispatcher) { catalog.shareableApps() }.filter { it.packageName !in known } + addApp.update { it?.copy(loading = false, apps = apps) } + } + } + + fun toggleApp(packageName: String) { + addApp.update { s -> + s?.copy(selected = if (packageName in s.selected) s.selected - packageName else s.selected + packageName) + } + } + + fun dismissAddApp() { + addApp.value = null + } + + fun confirmAddApp(): Job { + val picked = addApp.value?.selected.orEmpty().toList() + addApp.value = null + return addCustom(picked) + } + + /** Appends the apps as custom targets, last in the list; one that cannot be probed (not installed) is skipped. */ + fun addCustom(packageNames: List): Job = viewModelScope.launch { + writes.withLock { + val snapshot = preferences.current() + val ids = withContext(workDispatcher) { arrangedIds(snapshot) } + val added = withContext(workDispatcher) { + packageNames.distinct() + .filter { TargetProfile.customId(it) !in ids } + .mapNotNull { pkg -> catalog.customSpec(pkg)?.let { TargetProfile.custom(it).id } } + } + if (added.isEmpty()) return@withLock + preferences.setTargetOrder(ids + added + snapshot.targetOrder.filter { it !in ids && it !in added }) + } + } + + // ---- derived state, blocking: call on workDispatcher ---- + + private fun universe(snapshot: Preferences.Snapshot): List = + BuiltInTargets.all + customProfiles(snapshot.targetOrder, catalog::customSpec) + + /** Every target in the user's order, hidden ones included. */ + private fun arrangedIds(snapshot: Preferences.Snapshot): List = + TargetProfile.arranged(universe(snapshot), snapshot.targetOrder, emptySet()).map { it.id } + + private fun rows(snapshot: Preferences.Snapshot): List { + val profiles = universe(snapshot) + val arranged = TargetProfile.arranged(profiles, snapshot.targetOrder, emptySet(), snapshot.formatOverrides) + return arranged.mapIndexed { index, profile -> + val raw = profiles.first { it.id == profile.id } + TargetRow( + profile = profile, + hidden = profile.id in snapshot.hiddenTargets, + installed = when (catalog.resolution(raw)) { + is Resolution.Installed -> true + is Resolution.NotInstalled -> false + Resolution.NotAnApp -> null + }, + format = profile.format, + defaultFormat = raw.format, + formatOptions = if (raw.canChangeFormat) INTENT_FORMATS else emptyList(), + isCustom = raw.kind == TargetKind.CUSTOM_APP, + canMoveUp = index > 0, + canMoveDown = index < arranged.lastIndex, + ) + } + } + + companion object { + /** The formats a target can be switched between: the ones that leave through a share Intent. */ + val INTENT_FORMATS: List = DeliveryFormat.entries.filter { it.usesIntent } + + /** + * The user-added targets named in the stored target order (`custom:`), + * probed through [specOf]; packages that are not installed are left out. + * The delivery panel adds these to [BuiltInTargets.all]. + */ + fun customProfiles(order: List, specOf: (String) -> CustomTargetSpec?): List { + val builtInIds = BuiltInTargets.all.map { it.id }.toSet() + return order.asSequence() + .filter { it.startsWith(TargetProfile.CUSTOM_PREFIX) && it !in builtInIds } + .distinct() + .mapNotNull { id -> specOf(id.removePrefix(TargetProfile.CUSTOM_PREFIX))?.let(TargetProfile::custom) } + .toList() + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/AppIcons.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/AppIcons.kt new file mode 100644 index 00000000..a41bc4fb --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/AppIcons.kt @@ -0,0 +1,306 @@ +package com.xiangming.wechatbridge.ui.theme + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathFillType +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.unit.dp + +/** + * 全站定制矢量图标(不依赖 material-icons-extended,替代 Emoji,保持克制与一致的圆润线框质感)。 + */ +object AppIcons { + + /** 底部 Tab:中转站(层叠流动)。 */ + val NavRelay: ImageVector by lazy { + strokeIcon("NavRelay") { + addPath( + addPathNodes("M12,3 L2,8 L12,13 L22,8 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + addPath( + addPathNodes("M2,13 L12,18 L22,13"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + addPath( + addPathNodes("M2,17.5 L12,22.5 L22,17.5"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 底部 Tab:场景(四宫格卡片)。 */ + val NavScenes: ImageVector by lazy { + strokeIcon("NavScenes") { + val rects = listOf( + "M4.5,3 H9.5 A1.5,1.5 0 0 1 11,4.5 V9.5 A1.5,1.5 0 0 1 9.5,11 H4.5 A1.5,1.5 0 0 1 3,9.5 V4.5 A1.5,1.5 0 0 1 4.5,3 Z", + "M14.5,3 H19.5 A1.5,1.5 0 0 1 21,4.5 V9.5 A1.5,1.5 0 0 1 19.5,11 H14.5 A1.5,1.5 0 0 1 13,9.5 V4.5 A1.5,1.5 0 0 1 14.5,3 Z", + "M4.5,13 H9.5 A1.5,1.5 0 0 1 11,14.5 V19.5 A1.5,1.5 0 0 1 9.5,21 H4.5 A1.5,1.5 0 0 1 3,19.5 V14.5 A1.5,1.5 0 0 1 4.5,13 Z", + "M14.5,13 H19.5 A1.5,1.5 0 0 1 21,14.5 V19.5 A1.5,1.5 0 0 1 19.5,21 H14.5 A1.5,1.5 0 0 1 13,19.5 V14.5 A1.5,1.5 0 0 1 14.5,13 Z", + ) + for (d in rects) { + addPath( + addPathNodes(d), + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.9f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + } + + /** 底部 Tab:设置(极简滑块/齿轮感)。 */ + val NavSettings: ImageVector by lazy { + strokeIcon("NavSettings") { + addPath( + addPathNodes("M12,15 A3,3 0 1 0 12,9 A3,3 0 1 0 12,15 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + ) + addPath( + addPathNodes( + "M19.4,15 A1.65,1.65 0 0 0 19.73,16.82 L19.79,16.88 A2,2 0 1 1 16.96,19.71 L16.9,19.65 A1.65,1.65 0 0 0 15.08,19.32 A1.65,1.65 0 0 0 14.08,20.83 V21 A2,2 0 0 1 10.08,21 V20.91 A1.65,1.65 0 0 0 9,19.4 A1.65,1.65 0 0 0 7.18,19.73 L7.12,19.79 A2,2 0 1 1 4.29,16.96 L4.35,16.9 A1.65,1.65 0 0 0 4.68,15.08 A1.65,1.65 0 0 0 3.17,14.08 H3 A2,2 0 0 1 3,10.08 H3.09 A1.65,1.65 0 0 0 4.6,9 A1.65,1.65 0 0 0 4.27,7.18 L4.21,7.12 A2,2 0 1 1 7.04,4.29 L7.1,4.35 A1.65,1.65 0 0 0 8.92,4.68 H9 A1.65,1.65 0 0 0 10,3.17 V3 A2,2 0 0 1 14,3 V3.09 A1.65,1.65 0 0 0 15,4.6 A1.65,1.65 0 0 0 16.82,4.27 L16.88,4.21 A2,2 0 1 1 19.71,7.04 L19.65,7.1 A1.65,1.65 0 0 0 19.32,8.92 V9 A1.65,1.65 0 0 0 20.83,10 H21 A2,2 0 0 1 21,14 H20.91 A1.65,1.65 0 0 0 19.4,15 Z", + ), + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.85f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 聊天气泡实心图标。 */ + val ChatBubble: ImageVector by lazy { + ImageVector.Builder("ChatBubble", 24.dp, 24.dp, 24f, 24f) + .addPath( + addPathNodes("M20,3 H4 C2.9,3 2,3.9 2,5 V21 L6,17 H20 C21.1,17 22,16.1 22,15 V5 C22,3.9 21.1,3 20,3 Z"), + fill = SolidColor(Color.Black), + pathFillType = PathFillType.NonZero, + ) + .build() + } + + /** 链接图标。 */ + val LinkChain: ImageVector by lazy { + strokeIcon("LinkChain") { + addPath( + addPathNodes("M10,13 A5,5 0 0 0 17.54,13.54 L20.54,10.54 A5,5 0 0 0 13.47,3.47 L11.75,5.18"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2.1f, + strokeLineCap = StrokeCap.Round, + ) + addPath( + addPathNodes("M14,11 A5,5 0 0 0 6.46,10.46 L3.46,13.46 A5,5 0 0 0 10.53,20.53 L12.24,18.82"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2.1f, + strokeLineCap = StrokeCap.Round, + ) + } + } + + /** 文本笔记图标。 */ + val NoteDocument: ImageVector by lazy { + strokeIcon("NoteDocument") { + addPath( + addPathNodes("M14,2 H6 A2,2 0 0 0 4,4 V20 A2,2 0 0 0 6,22 H18 A2,2 0 0 0 20,20 V8 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + addPath( + addPathNodes("M14,2 V8 H20 M8,13 H16 M8,17 H13"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 文件附件图标。 */ + val FileAttachment: ImageVector by lazy { + strokeIcon("FileAttachment") { + addPath( + addPathNodes("M13,2 H6 A2,2 0 0 0 4,4 V20 A2,2 0 0 0 6,22 H18 A2,2 0 0 0 20,20 V9 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + addPath( + addPathNodes("M13,2 V9 H20"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 右向轻箭头(卡片快捷投递按钮用)。 */ + val ArrowRight: ImageVector by lazy { + strokeIcon("ArrowRight") { + addPath( + addPathNodes("M5,12 H19 M13,6 L19,12 L13,18"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2.2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 列表右向尖括号。 */ + val ChevronRight: ImageVector by lazy { + strokeIcon("ChevronRight") { + addPath( + addPathNodes("M9,6 L15,12 L9,18"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2.1f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 搜索放大镜图标(中转站关键词搜索用)。 */ + val Search: ImageVector by lazy { + strokeIcon("Search") { + addPath( + addPathNodes("M18,11 A7,7 0 1 1 4,11 A7,7 0 1 1 18,11 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + addPath( + addPathNodes("M16.2,16.2 L20.5,20.5"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + ) + } + } + + /** 官方场景:客户复盘(人物与反馈)。 */ + val SceneCustomer: ImageVector by lazy { + strokeIcon("SceneCustomer") { + addPath( + addPathNodes("M16,21 V19 A4,4 0 0 0 12,15 H6 A4,4 0 0 0 2,19 V21"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + ) + addPath( + addPathNodes("M9,11 A4,4 0 1 0 9,3 A4,4 0 1 0 9,11 Z M17,4 A3.5,3.5 0 0 1 17,11 M22,21 V19 A4,4 0 0 0 18,15.2"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + ) + } + } + + /** 官方场景:项目周会(清单与进度)。 */ + val SceneProject: ImageVector by lazy { + strokeIcon("SceneProject") { + addPath( + addPathNodes("M9,4 H6 A2,2 0 0 0 4,6 V20 A2,2 0 0 0 6,22 H18 A2,2 0 0 0 20,20 V6 A2,2 0 0 0 18,4 H15"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + addPath( + addPathNodes("M9,2 H15 V6 H9 Z M8,12 L10,14 L14,10 M8,18 H16"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 官方场景:日常摘要(时间线)。 */ + val SceneSummary: ImageVector by lazy { + strokeIcon("SceneSummary") { + addPath( + addPathNodes("M5,3 V21 M5,6 H16 M5,12 H19 M5,18 H14"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + ) + } + } + + /** 官方场景:公众号文章提取(图文文档)。 */ + val SceneArticle: ImageVector by lazy { + strokeIcon("SceneArticle") { + addPath( + addPathNodes("M14,2 H6 A2,2 0 0 0 4,4 V20 A2,2 0 0 0 6,22 H18 A2,2 0 0 0 20,20 V8 Z M14,2 V8 H20"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + addPath( + addPathNodes("M8,13 H10 L11,15 L13,11 L15,15 L16,13 H18 M8,18 H16"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.8f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 官方场景:视频信息读取(播放帧)。 */ + val SceneVideo: ImageVector by lazy { + strokeIcon("SceneVideo") { + addPath( + addPathNodes("M3,5 H21 V19 H3 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + addPath( + addPathNodes("M10,9 L16,12 L10,15 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 1.8f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + /** 填入笔形图标(替代闪电 Emoji)。 */ + val FillInput: ImageVector by lazy { + strokeIcon("FillInput") { + addPath( + addPathNodes("M12,20 H21 M16.5,3.5 A2.12,2.12 0 0 1 19.5,6.5 L7,19 L3,20 L4,16 Z"), + stroke = SolidColor(Color.Black), + strokeLineWidth = 2f, + strokeLineCap = StrokeCap.Round, + strokeLineJoin = StrokeJoin.Round, + ) + } + } + + private inline fun strokeIcon( + name: String, + block: ImageVector.Builder.() -> Unit, + ): ImageVector = ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f).apply(block).build() +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/BridgeGlass.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/BridgeGlass.kt new file mode 100644 index 00000000..c861157d --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/BridgeGlass.kt @@ -0,0 +1,316 @@ +package com.xiangming.wechatbridge.ui.theme + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +/** + * Multi-layered emerald & jade ambient backdrop matching iOS 2.0 Liquid Glass. + * Gives floating glass pills, top controls, and the floating bottom dock soft emerald + * light to sit over instead of flat grey-white. + */ +@Composable +fun BridgeAmbientBackdrop( + modifier: Modifier = Modifier, +) { + val appColors = LocalAppColors.current + val base = MaterialTheme.colorScheme.background + val primaryGlow = if (appColors.isDark) WeChatGreenLight.copy(alpha = 0.20f) else WeChatGreen.copy(alpha = 0.14f) + val secondaryGlow = if (appColors.isDark) WeChatJadeLight.copy(alpha = 0.14f) else WeChatJade.copy(alpha = 0.09f) + + Box( + modifier = modifier + .fillMaxSize() + .background(base) + .drawBehind { + val w = size.width + val h = size.height + drawCircle( + brush = Brush.radialGradient( + colors = listOf(primaryGlow, Color.Transparent), + center = Offset(w * 0.16f, h * 0.02f), + radius = w * 0.92f, + ), + radius = w * 0.92f, + center = Offset(w * 0.16f, h * 0.02f), + ) + drawCircle( + brush = Brush.radialGradient( + colors = listOf(secondaryGlow, Color.Transparent), + center = Offset(w * 0.88f, h * 0.08f), + radius = w * 0.72f, + ), + radius = w * 0.72f, + center = Offset(w * 0.88f, h * 0.08f), + ) + }, + ) +} + +/** + * Floating Liquid Glass control surface for Android (floating TabBar, filter pill bar, + * floating action bars, and receipt cards). Translucent glass fill + specular hairline border. + */ +@Composable +fun BridgeGlassSurface( + modifier: Modifier = Modifier, + shape: Shape = CircleShape, + tint: Color? = null, + shadowElevation: Dp = 12.dp, + content: @Composable BoxScope.() -> Unit, +) { + val appColors = LocalAppColors.current + val fillColor = when { + tint != null -> tint.copy(alpha = if (appColors.isDark) 0.28f else 0.18f) + appColors.isDark -> Color(0xF21A201E) + else -> Color(0xF5FFFFFF) + } + val borderBrush = Brush.verticalGradient( + colors = if (appColors.isDark) { + listOf(Color.White.copy(alpha = 0.22f), Color.White.copy(alpha = 0.06f)) + } else { + listOf(Color.White.copy(alpha = 0.95f), Color.Black.copy(alpha = 0.06f)) + }, + ) + + Box( + modifier = modifier + .shadow( + elevation = shadowElevation, + shape = shape, + ambientColor = Color.Black.copy(alpha = if (appColors.isDark) 0.45f else 0.12f), + spotColor = Color.Black.copy(alpha = if (appColors.isDark) 0.50f else 0.10f), + ) + .clip(shape) + .background(fillColor) + .border(width = 0.9.dp, brush = borderBrush, shape = shape), + content = content, + ) +} + +/** Soft fade beneath a floating top bar so scrolling cards never meet a hard edge. */ +@Composable +fun BridgeTopBarScrim( + visible: Boolean, + modifier: Modifier = Modifier, +) { + val color = MaterialTheme.colorScheme.background + Box( + modifier = modifier + .fillMaxWidth() + .height(32.dp) + .drawBehind { + if (visible) { + drawRect( + brush = Brush.verticalGradient( + colors = listOf( + color, + color.copy(alpha = 0.82f), + Color.Transparent, + ), + ), + ) + } + }, + ) +} + +/** Covers the gap below the floating dock, including the gesture/navigation bar area. */ +@Composable +fun BridgeBottomBarScrim( + modifier: Modifier = Modifier, + height: Dp = 100.dp, +) { + val color = MaterialTheme.colorScheme.background + Box( + modifier = modifier + .fillMaxWidth() + .height(height) + .drawBehind { + drawRect( + brush = Brush.verticalGradient( + colors = listOf(Color.Transparent, color, color), + endY = size.height, + ), + ) + }, + ) +} + +/** + * Crisp opaque Bento card for content layers (never muddy glass on content). + * When [highlighted] is true, adds a soft emerald wash and subtle brand-green border. + */ +@Composable +fun BridgeBentoCard( + modifier: Modifier = Modifier, + cornerRadius: Dp = 20.dp, + highlighted: Boolean = false, + contentPadding: PaddingValues = PaddingValues(16.dp), + onClick: (() -> Unit)? = null, + content: @Composable ColumnScope.() -> Unit, +) { + val appColors = LocalAppColors.current + val shape = RoundedCornerShape(cornerRadius) + val borderColor = if (highlighted) { + appColors.surfaceTintBorder + } else { + MaterialTheme.colorScheme.outlineVariant.copy(alpha = if (appColors.isDark) 0.55f else 0.80f) + } + val interactionSource = remember { MutableInteractionSource() } + val clickMod = if (onClick != null) { + Modifier + .pressScale(interactionSource, targetScale = 0.985f) + .clickable( + interactionSource = interactionSource, + indication = null, + role = Role.Button, + onClick = onClick, + ) + } else { + Modifier + } + + Surface( + modifier = modifier + .shadow( + elevation = if (appColors.isDark) 0.dp else if (highlighted) 6.dp else 4.dp, + shape = shape, + ambientColor = (if (highlighted) WeChatGreen else Color.Black).copy(alpha = 0.08f), + spotColor = (if (highlighted) WeChatGreen else Color.Black).copy(alpha = 0.06f), + ) + .then(clickMod), + shape = shape, + color = MaterialTheme.colorScheme.surface, + border = BorderStroke(if (highlighted) 1.dp else 0.75.dp, borderColor), + tonalElevation = 0.dp, + ) { + Box { + if (highlighted) { + Box( + modifier = Modifier + .matchParentSize() + .background( + Brush.verticalGradient( + colors = listOf( + appColors.surfaceTint.copy(alpha = if (appColors.isDark) 0.75f else 0.85f), + Color.Transparent, + ), + ), + ), + ) + } + Column( + modifier = Modifier.padding(contentPadding), + content = content, + ) + } + } +} + +/** + * Primary brand-green capsule button with specular top highlight border and tactile spring scale. + */ +@Composable +fun BridgePrimaryCapsuleButton( + text: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + icon: ImageVector? = null, + enabled: Boolean = true, + height: Dp = 50.dp, +) { + val interactionSource = remember { MutableInteractionSource() } + val gradient = Brush.verticalGradient( + colors = listOf(MaterialTheme.colorScheme.primary, WeChatGreenDark), + ) + val highlight = Brush.verticalGradient( + colors = listOf(Color.White.copy(alpha = 0.40f), Color.White.copy(alpha = 0.04f)), + ) + + Box( + modifier = modifier + .height(height) + .alpha(if (enabled) 1f else 0.45f) + .shadow( + elevation = if (enabled) 10.dp else 0.dp, + shape = CircleShape, + ambientColor = WeChatGreen.copy(alpha = 0.30f), + spotColor = WeChatGreen.copy(alpha = 0.35f), + ) + .clip(CircleShape) + .background(gradient) + .border(0.8.dp, highlight, CircleShape) + .pressScale(interactionSource, targetScale = 0.97f) + .clickable( + enabled = enabled, + interactionSource = interactionSource, + indication = null, + role = Role.Button, + onClick = onClick, + ) + .padding(horizontal = 20.dp), + contentAlignment = Alignment.Center, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Center, + ) { + if (icon != null) { + Icon( + imageVector = icon, + contentDescription = null, + tint = Color.White, + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(7.dp)) + } + Text( + text = text, + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = Color.White, + maxLines = 1, + ) + } + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Color.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Color.kt new file mode 100644 index 00000000..3cdc59fa --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Color.kt @@ -0,0 +1,47 @@ +package com.xiangming.wechatbridge.ui.theme + +import androidx.compose.ui.graphics.Color + +/** 微信绿,品牌主色。 */ +val WeChatGreen = Color(0xFF07C160) +val WeChatGreenDark = Color(0xFF06AD56) +val WeChatGreenDeep = Color(0xFF058C45) +val WeChatGreenLight = Color(0xFF28CE75) +val WeChatJade = Color(0xFF0D9480) +val WeChatJadeLight = Color(0xFF3DC7AD) + +// Light palette — 清爽绿白画布 + 纯白卡片 +val LightBackground = Color(0xFFF4F7F5) +val LightSurface = Color(0xFFFFFFFF) +val LightSurfaceSub = Color(0xFFF1F6F3) +val LightSurfaceTint = Color(0xFFE9F9F0) +val LightSurfaceTintBorder = Color(0x3D07C160) +val LightOnSurface = Color(0xFF14171A) +val LightSurfaceVariant = Color(0xFFECF2EE) +val LightOnSurfaceVariant = Color(0xFF5A6570) +val LightOnSurfaceMuted = Color(0xFF8A95A0) +val LightOutline = Color(0xFF9AA5B0) +val LightOutlineVariant = Color(0xFFE2E9E4) +val LightSubtleDivider = Color(0x120F172A) + +// Dark palette — 深墨绿灰底 + 层次卡片 +val DarkBackground = Color(0xFF0D100F) +val DarkSurface = Color(0xFF1A1F1D) +val DarkSurfaceSub = Color(0xFF232A27) +val DarkSurfaceTint = Color(0xFF132A1F) +val DarkSurfaceTintBorder = Color(0x4D28CE75) +val DarkOnSurface = Color(0xFFF1F4F2) +val DarkSurfaceVariant = Color(0xFF242B28) +val DarkOnSurfaceVariant = Color(0xFFA0ABA5) +val DarkOnSurfaceMuted = Color(0xFF6E7A74) +val DarkOutline = Color(0xFF6E7873) +val DarkOutlineVariant = Color(0xFF2D3632) +val DarkSubtleDivider = Color(0x14FFFFFF) + +// Kind accents — 收束在绿白和谐语义色系 +val KindChatColor = Color(0xFF07C160) +val KindLinkColor = Color(0xFF0D9480) +val KindNoteColor = Color(0xFF058C45) +val KindFileColor = Color(0xFFD97706) + +val ErrorRed = Color(0xFFFA5151) diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Motion.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Motion.kt new file mode 100644 index 00000000..e5731147 --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Motion.kt @@ -0,0 +1,109 @@ +package com.xiangming.wechatbridge.ui.theme + +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutHorizontally +import androidx.compose.animation.slideOutVertically +import androidx.compose.foundation.interaction.InteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize + +/** + * 全站统一动效规范(Motion Tokens): + * 物理弹簧为主,克制轻快,避免浮夸拖沓。 + */ +object AppMotion { + const val TAB_FADE_MS = 120 + const val PAGE_SLIDE_MS = 250 + const val SHEET_SLIDE_MS = 260 + + /** 按压回弹、角标弹出、开关反馈:利落跟手。 */ + fun snappySpring() = spring( + dampingRatio = 0.85f, + stiffness = Spring.StiffnessMedium, + ) + + /** 容器展开、布局重排:柔和有呼吸感。 */ + fun smoothSpring() = spring( + dampingRatio = 0.88f, + stiffness = Spring.StiffnessMediumLow, + ) + + /** 略带弹性 Q 弹反馈(目标选中角标、入球提示)。 */ + fun playfulSpring() = spring( + dampingRatio = 0.68f, + stiffness = Spring.StiffnessMedium, + ) + + fun contentSizeSpring() = spring( + dampingRatio = 0.88f, + stiffness = Spring.StiffnessMediumLow, + ) + + // --- Navigation Transitions --- + + val tabEnter: EnterTransition = fadeIn(tween(TAB_FADE_MS)) + val tabExit: ExitTransition = fadeOut(tween(TAB_FADE_MS)) + + private val slideSpec = tween(PAGE_SLIDE_MS, easing = FastOutSlowInEasing) + private val fadeSpec = tween(PAGE_SLIDE_MS, easing = FastOutSlowInEasing) + + /** 进入二级页面:从右侧 22% 轻滑入 + 淡入。 */ + val pushEnter: EnterTransition = + slideInHorizontally(slideSpec) { it / 4 } + fadeIn(fadeSpec) + + /** 旧页面退后:向左微移 8% 视差。 */ + val pushExit: ExitTransition = + slideOutHorizontally(slideSpec) { -it / 12 } + fadeOut(tween(180)) + + /** 返回时旧页面还原。 */ + val popEnter: EnterTransition = + slideInHorizontally(slideSpec) { -it / 12 } + fadeIn(tween(200)) + + /** 返回时当前页面轻滑出。 */ + val popExit: ExitTransition = + slideOutHorizontally(slideSpec) { it / 4 } + fadeOut(tween(180)) + + /** 投递面板:从底部轻弹浮现。 */ + val sheetEnter: EnterTransition = + slideInVertically(tween(SHEET_SLIDE_MS, easing = FastOutSlowInEasing)) { it / 5 } + + fadeIn(tween(200)) + + val sheetExit: ExitTransition = + slideOutVertically(tween(220, easing = FastOutSlowInEasing)) { it / 5 } + + fadeOut(tween(180)) +} + +/** + * 旗舰级按压微缩放反馈:按下轻缩,松手弹簧回弹。 + */ +fun Modifier.pressScale( + interactionSource: InteractionSource, + targetScale: Float = 0.975f, +): Modifier = composed { + val pressed by interactionSource.collectIsPressedAsState() + val scale by animateFloatAsState( + targetValue = if (pressed) targetScale else 1f, + animationSpec = AppMotion.snappySpring(), + label = "pressScale", + ) + graphicsLayer { + scaleX = scale + scaleY = scale + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Theme.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Theme.kt new file mode 100644 index 00000000..29b9706c --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Theme.kt @@ -0,0 +1,138 @@ +package com.xiangming.wechatbridge.ui.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Shapes +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp + +private val LightColors = lightColorScheme( + primary = WeChatGreen, + onPrimary = Color.White, + primaryContainer = LightSurfaceTint, + onPrimaryContainer = Color(0xFF00391A), + secondary = WeChatGreenDark, + onSecondary = Color.White, + secondaryContainer = LightSurfaceTint, + onSecondaryContainer = Color(0xFF00391A), + tertiary = WeChatGreenDark, + tertiaryContainer = LightSurfaceTint, + onTertiaryContainer = Color(0xFF00391A), + background = LightBackground, + onBackground = LightOnSurface, + surface = LightSurface, + onSurface = LightOnSurface, + surfaceVariant = LightSurfaceVariant, + onSurfaceVariant = LightOnSurfaceVariant, + surfaceDim = Color(0xFFE2E6EC), + surfaceBright = LightSurface, + surfaceContainerLowest = LightSurface, + surfaceContainerLow = Color(0xFFFAFBFD), + surfaceContainer = LightSurfaceSub, + surfaceContainerHigh = LightSurfaceVariant, + surfaceContainerHighest = Color(0xFFE3E7EE), + inverseSurface = Color(0xFF1E2227), + inverseOnSurface = Color(0xFFF3F5F7), + inversePrimary = WeChatGreenLight, + outline = LightOutline, + outlineVariant = LightOutlineVariant, + error = ErrorRed, +) + +private val DarkColors = darkColorScheme( + primary = WeChatGreenLight, + onPrimary = Color(0xFF00391A), + primaryContainer = DarkSurfaceTint, + onPrimaryContainer = Color(0xFFD5F5E3), + secondary = WeChatGreen, + onSecondary = Color(0xFF00391A), + secondaryContainer = Color(0xFF1A3A28), + onSecondaryContainer = Color(0xFFD5F5E3), + tertiary = WeChatGreen, + tertiaryContainer = Color(0xFF1A3A28), + onTertiaryContainer = Color(0xFFD5F5E3), + background = DarkBackground, + onBackground = DarkOnSurface, + surface = DarkSurface, + onSurface = DarkOnSurface, + surfaceVariant = DarkSurfaceVariant, + onSurfaceVariant = DarkOnSurfaceVariant, + surfaceDim = DarkBackground, + surfaceBright = Color(0xFF31363D), + surfaceContainerLowest = Color(0xFF0A0C0E), + surfaceContainerLow = Color(0xFF16191C), + surfaceContainer = DarkSurface, + surfaceContainerHigh = DarkSurfaceSub, + surfaceContainerHighest = Color(0xFF2F343B), + inverseSurface = DarkOnSurface, + inverseOnSurface = Color(0xFF1B1E21), + inversePrimary = WeChatGreenDark, + outline = DarkOutline, + outlineVariant = DarkOutlineVariant, + error = ErrorRed, +) + +val AppShapes = Shapes( + extraSmall = RoundedCornerShape(8.dp), + small = RoundedCornerShape(12.dp), + medium = RoundedCornerShape(16.dp), + large = RoundedCornerShape(20.dp), + extraLarge = RoundedCornerShape(24.dp), +) + +/** 轻盈白卡微质感扩展色板(互补 Material3 ColorScheme)。 */ +@Immutable +data class AppExtendedColors( + val surfaceSub: Color, + val surfaceTint: Color, + val surfaceTintBorder: Color, + val onSurfaceMuted: Color, + val subtleDivider: Color, + val primarySoft: Color, + val isDark: Boolean, +) + +private val LightExtended = AppExtendedColors( + surfaceSub = LightSurfaceSub, + surfaceTint = LightSurfaceTint, + surfaceTintBorder = LightSurfaceTintBorder, + onSurfaceMuted = LightOnSurfaceMuted, + subtleDivider = LightSubtleDivider, + primarySoft = Color(0x1F07C160), + isDark = false, +) + +private val DarkExtended = AppExtendedColors( + surfaceSub = DarkSurfaceSub, + surfaceTint = DarkSurfaceTint, + surfaceTintBorder = DarkSurfaceTintBorder, + onSurfaceMuted = DarkOnSurfaceMuted, + subtleDivider = DarkSubtleDivider, + primarySoft = Color(0x2925D366), + isDark = true, +) + +val LocalAppColors = staticCompositionLocalOf { LightExtended } + +/** 微信绿主色的轻盈白卡 Material3 主题;跟随系统深色模式,不使用动态取色以保持品牌色。 */ +@Composable +fun WeChatBridgeTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + content: @Composable () -> Unit, +) { + CompositionLocalProvider(LocalAppColors provides if (darkTheme) DarkExtended else LightExtended) { + MaterialTheme( + colorScheme = if (darkTheme) DarkColors else LightColors, + typography = AppTypography, + shapes = AppShapes, + content = content, + ) + } +} diff --git a/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Type.kt b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Type.kt new file mode 100644 index 00000000..9d4f3f6c --- /dev/null +++ b/android/app/src/main/kotlin/com/xiangming/wechatbridge/ui/theme/Type.kt @@ -0,0 +1,68 @@ +package com.xiangming.wechatbridge.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +/** 中英文混排调校字阶:清晰层级 + 舒适行高。 */ +val AppTypography = Typography( + headlineMedium = TextStyle( + fontSize = 26.sp, + lineHeight = 32.sp, + fontWeight = FontWeight.Bold, + letterSpacing = (-0.4).sp, + ), + headlineSmall = TextStyle( + fontSize = 22.sp, + lineHeight = 28.sp, + fontWeight = FontWeight.Bold, + letterSpacing = (-0.2).sp, + ), + titleLarge = TextStyle( + fontSize = 19.sp, + lineHeight = 25.sp, + fontWeight = FontWeight.Bold, + letterSpacing = (-0.1).sp, + ), + titleMedium = TextStyle( + fontSize = 15.5.sp, + lineHeight = 22.sp, + fontWeight = FontWeight.SemiBold, + ), + titleSmall = TextStyle( + fontSize = 13.5.sp, + lineHeight = 19.sp, + fontWeight = FontWeight.SemiBold, + ), + bodyLarge = TextStyle( + fontSize = 15.sp, + lineHeight = 22.sp, + fontWeight = FontWeight.Normal, + ), + bodyMedium = TextStyle( + fontSize = 14.sp, + lineHeight = 20.5.sp, + fontWeight = FontWeight.Normal, + ), + bodySmall = TextStyle( + fontSize = 13.sp, + lineHeight = 18.5.sp, + fontWeight = FontWeight.Normal, + ), + labelLarge = TextStyle( + fontSize = 13.5.sp, + lineHeight = 18.sp, + fontWeight = FontWeight.SemiBold, + ), + labelMedium = TextStyle( + fontSize = 12.sp, + lineHeight = 16.sp, + fontWeight = FontWeight.Medium, + ), + labelSmall = TextStyle( + fontSize = 11.5.sp, + lineHeight = 15.sp, + fontWeight = FontWeight.Medium, + ), +) diff --git a/android/app/src/main/res/drawable-nodpi/logo_chatgpt.png b/android/app/src/main/res/drawable-nodpi/logo_chatgpt.png new file mode 100644 index 00000000..fd0dc3e1 Binary files /dev/null and b/android/app/src/main/res/drawable-nodpi/logo_chatgpt.png differ diff --git a/android/app/src/main/res/drawable-nodpi/logo_claude.png b/android/app/src/main/res/drawable-nodpi/logo_claude.png new file mode 100644 index 00000000..bf35f605 Binary files /dev/null and b/android/app/src/main/res/drawable-nodpi/logo_claude.png differ diff --git a/android/app/src/main/res/drawable-nodpi/logo_doubao.png b/android/app/src/main/res/drawable-nodpi/logo_doubao.png new file mode 100644 index 00000000..db16d884 Binary files /dev/null and b/android/app/src/main/res/drawable-nodpi/logo_doubao.png differ diff --git a/android/app/src/main/res/drawable-nodpi/logo_obsidian.png b/android/app/src/main/res/drawable-nodpi/logo_obsidian.png new file mode 100644 index 00000000..e55f4bc8 Binary files /dev/null and b/android/app/src/main/res/drawable-nodpi/logo_obsidian.png differ diff --git a/android/app/src/main/res/drawable-nodpi/logo_qwen.png b/android/app/src/main/res/drawable-nodpi/logo_qwen.png new file mode 100644 index 00000000..e5947547 Binary files /dev/null and b/android/app/src/main/res/drawable-nodpi/logo_qwen.png differ diff --git a/android/app/src/main/res/drawable-nodpi/logo_wechatbridge.png b/android/app/src/main/res/drawable-nodpi/logo_wechatbridge.png new file mode 100644 index 00000000..19f200e2 Binary files /dev/null and b/android/app/src/main/res/drawable-nodpi/logo_wechatbridge.png differ diff --git a/android/app/src/main/res/drawable-nodpi/logo_workbuddy.png b/android/app/src/main/res/drawable-nodpi/logo_workbuddy.png new file mode 100644 index 00000000..6268cd6f Binary files /dev/null and b/android/app/src/main/res/drawable-nodpi/logo_workbuddy.png differ diff --git a/android/app/src/main/res/drawable/ic_bubble_archive.xml b/android/app/src/main/res/drawable/ic_bubble_archive.xml new file mode 100644 index 00000000..da79345a --- /dev/null +++ b/android/app/src/main/res/drawable/ic_bubble_archive.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_bubble_copy.xml b/android/app/src/main/res/drawable/ic_bubble_copy.xml new file mode 100644 index 00000000..1f903e55 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_bubble_copy.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_bubble_fill.xml b/android/app/src/main/res/drawable/ic_bubble_fill.xml new file mode 100644 index 00000000..d0a5f458 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_bubble_fill.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_bubble_image.xml b/android/app/src/main/res/drawable/ic_bubble_image.xml new file mode 100644 index 00000000..abd5f3d3 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_bubble_image.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_stat_wechatbridge.xml b/android/app/src/main/res/drawable/ic_stat_wechatbridge.xml new file mode 100644 index 00000000..31c6fe40 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_stat_wechatbridge.xml @@ -0,0 +1,17 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..be438580 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000..be438580 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..abf0846a Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..14c021be Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 00000000..7c271921 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..5ca287af Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..e195c63f Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 00000000..0e2cb746 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..e9a8d125 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..feefdf94 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 00000000..ab96e7dd Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..c73c77ce Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..d4459e02 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..48faea1c Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..56db41b9 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..fc89960f Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..62aed9f9 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/values-en/strings_a11y.xml b/android/app/src/main/res/values-en/strings_a11y.xml new file mode 100644 index 00000000..c19d8224 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_a11y.xml @@ -0,0 +1,9 @@ + + + + Enable scene “%1$s” + Delete scene “%1$s” + Select + Close + Sent + diff --git a/android/app/src/main/res/values-en/strings_bubble.xml b/android/app/src/main/res/values-en/strings_bubble.xml new file mode 100644 index 00000000..7225c706 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_bubble.xml @@ -0,0 +1,116 @@ + + + + + WeChatBridge edge handle, %d batch waiting, tap or swipe inward to open + WeChatBridge edge handle, %d batches waiting, tap or swipe inward to open + + + +1 · %d waiting + +1 · %d waiting + + + + + %d batch waiting + %d batches waiting + + Waiting + Nothing in Relay is waiting to be delivered. Share from WeChat (Share → More apps → WeChatBridge) and the count goes up. + Close + Deliver “%1$s” + + %d more batch, open WeChatBridge to see it + %d more batches, open WeChatBridge to see them + + + Deliver %d batch + Merge and deliver all %d batches + + + Fill %d batch + Merge & fill all (%d) + + Fill + Copy + Open WeChatBridge + Turn off edge handle + Edge handle turned off. Re-enable it anytime in Settings. + + + Long-press to drag into another app\'s input box + Drag text out + Dropped in + Not dropped into an input box. Use the copy button instead. + Couldn\'t start dragging. Keep holding, then drag, or use the copy button. + This batch has no text to drag out + Too much text to drag or copy. Tap the batch to deliver it instead. + Couldn\'t read this batch\'s text + Copy the text of “%1$s” + Copied + Couldn\'t copy to the clipboard + + Drag images out + Drag text + Drag images ×%1$d + Drag images + Images ×%1$d + + Drag %d image out + Drag %d images out + + + %d image + %d images + + ZIP + Drag the original ZIP out + Long-press, then drag into another app + At most %1$d images per drag. Took the first %1$d. + This app doesn\'t accept dropped images. Share them from the delivery panel instead. + This app doesn\'t accept dropped files + This batch has no images to drag out + This batch has no text or images to drag out + Couldn\'t prepare the images + Couldn\'t prepare the original ZIP + + + WeChatBridge + + %d waiting + %d waiting + + Tap to open panel + + + Edge handle + Ongoing notification for silent receive and quick access to the staged panel + WeChatBridge ready + + %d batch waiting · tap to open panel + %d batches waiting · tap to open panel + + Silent receive active · tap to open panel + Open panel + Open app + Turn off + + + Not saved to WeChatBridge: %1$s + + + Edge handle + Smart edge handle + Skip the receipt card and stay right in WeChat. A slim translucent edge handle opens the staged panel on tap or inward swipe, with optional zero-overlay Quick Settings tile & notification triggers. + Show edge handle only when staged + Keep the screen completely clean when empty; appear automatically when a share arrives + Zero-overlay mode + Never show the edge handle; open the staged panel via Quick Settings tile or notification + Turning it on asks for the “Display over other apps” permission. + The overlay permission is off, so the edge handle and staged panel cannot show and sharing shows the receipt card again. + The overlay permission was not granted, so the edge handle is off. + Grant permission + Xiaomi / HyperOS: also turn on “Display pop-up windows while running in the background” and “Display pop-up windows” under App permissions → Other permissions, or the edge handle and panel may not show. + Open Xiaomi permissions + The ongoing notification lets you open the staged panel anytime and keeps silent receive active. Without notification permission, the edge handle and Quick Settings tile still work. + diff --git a/android/app/src/main/res/values-en/strings_collect.xml b/android/app/src/main/res/values-en/strings_collect.xml new file mode 100644 index 00000000..5acbe038 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_collect.xml @@ -0,0 +1,39 @@ + + + Untitled collection + Batches: %1$d · about %2$d messages + Batches: %1$d · message count unavailable + Batch %1$d + Messages: %1$d + Message count unknown + First: %1$s + Last: %1$s: %2$s + Couldn\'t read the position reference. The original file is saved. + Reading… + Remove from this collection + Removing only detaches the batch. It stays in Relay. + Batches are merged by time when delivered. Overlapping messages between batches are kept once. + This collection has no batches left. + This collection has ended or no longer exists. + Finish and deliver + Merge & deliver + Keep collecting + Collecting in batches + Abandon + Abandon this collection? + No more batches will be added. Batches already collected stay in Relay. + Abandon collection + + The last batch has exactly 100 messages, so there may be more + WeChat forwards at most 100 messages at a time. In WeChat, search this chat for the keyword below to find that message, select the messages after it, then share to “Collect in batches to WeChatBridge”. + Last message of previous batch · %1$s · %2$s + Copy keyword + Copied “%1$s” + + Batch collection + Stays visible while collecting, so you can finish and deliver or abandon + Collecting · batches: %1$d + Keep sharing from WeChat to “Collect in batches to WeChatBridge”, then finish and deliver when you have everything. + Finish and deliver + Abandon + diff --git a/android/app/src/main/res/values-en/strings_common.xml b/android/app/src/main/res/values-en/strings_common.xml new file mode 100644 index 00000000..27414db4 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_common.xml @@ -0,0 +1,16 @@ + + + WeChatBridge + Coming soon + Back + Done + Cancel + Relay + Batch details + Deliver + Scenes + Delivery targets + Settings + Getting started + Collection + diff --git a/android/app/src/main/res/values-en/strings_deliver.xml b/android/app/src/main/res/values-en/strings_deliver.xml new file mode 100644 index 00000000..070bf309 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_deliver.xml @@ -0,0 +1,124 @@ + + + ChatGPT + Claude + Gemini + Yuanbao + Doubao + Qwen + DeepSeek + Feishu / Lark + Yuque + Mi Notes + Obsidian + Folder + Other app + + Original ZIP + TXT + images + TXT only + Paste as text + Knowledge note + Folder + + System share sheet + Delivered + Delivery not completed + + Deliver %1$d batches together + Close + Done + Loading… + Couldn\'t find these batches. They may have been deleted. + WeChat chat + Single batch · Ready to deliver + %1$d batches merged + %1$d files + Text + %1$d batches + + Deliver to + Not installed + %1$s isn\'t installed, so you can\'t deliver to it. + Selected + + Scene & Prompt + No scene + Auto-matched to group + Chosen from this group\'s bound scene + Chosen by group name keyword + Recognized from group members + Reusing the scene last used for this group + Default scene + Prompt + Edit + Collapse + Tap to edit prompt… + It is copied to the clipboard when you send, so you can paste it into the other app\'s input box. + + Content to deliver + Choose a target to see what will be sent. + Preparing files… + Format: %1$s + Many files, so they will be sent in %1$d rounds + Round %1$d/%2$d · %3$d files + …and %1$d more files + The chat will be sent as text with the message. + The chat is too long to send as text, so a TXT file is used instead. + Not attached (%1$d) + …and %1$d more + Send original ZIP instead + Send original files instead + Switch format + Restore default format + No readable chat in this content. + This content can\'t be sent in the format this target needs. + Couldn\'t prepare the files. Storage may be full or a file may have been deleted. + + Send + Send to %1$s + Save to %1$s + Continue sending: round %1$d/%2$d + Sent + %1$s isn\'t installed + Save path + + Handed to %1$s + Round %1$d/%2$d sent. Tap “Continue sending” for the next one. + All sent (%1$d rounds). + Prompt copied. Paste it into the other app\'s input box. + The other app won\'t receive the prompt. Paste it yourself. + Choose “%1$s” on the next screen. + Choose the app to send to on the next screen. + The text was too long and wasn\'t sent with the message. + %1$s isn\'t installed, so nothing was sent. + Nothing to send. + The file isn\'t in a shareable folder, so it wasn\'t sent. + A file no longer exists. Choose the target again and retry. + The text is too long to send directly. Switch to a file format. + Couldn\'t open the target app: %1$s + Couldn\'t open the target app. + This collection was already delivered or no longer exists. + No Obsidian vault chosen yet. Choose the folder that contains your vault; notes will be written to “%1$s” inside it. + No folder chosen yet. Notes will be written to “%1$s” inside it. + The folder you chose earlier is no longer accessible. Please choose it again. + Writes to: %1$s/%2$s + Choose folder + Choose again + Wrote %1$d notes: %2$s + The folder is no longer accessible. Choose it again, then retry. + Couldn\'t get long-term access to this folder. Please choose another one. + No chat content to write. + Writing failed and some files couldn\'t be cleaned up. Please check the folder. + Writing failed: %1$s + Writing failed. + Group: %1$s + Group not recognized + Choose group + New group + New group + Group name + Use this scene for this group from now on + Bound to this group + OK + diff --git a/android/app/src/main/res/values-en/strings_detail.xml b/android/app/src/main/res/values-en/strings_detail.xml new file mode 100644 index 00000000..065e269b --- /dev/null +++ b/android/app/src/main/res/values-en/strings_detail.xml @@ -0,0 +1,34 @@ + + + Chat + Deliver + Deliver batch + Copy text + Copied full text + No text available to copy + %1$d messages + %1$d files + %1$d chars + Shared link + Reading… + This batch was deleted + Files + Couldn\'t read: %1$s + From %1$s + + Image %1$s + Image not attached + Video + File + Channels + Img + Vid + File + Link + Ch + + Can\'t display this image + Done + + No app can open this + diff --git a/android/app/src/main/res/values-en/strings_drop.xml b/android/app/src/main/res/values-en/strings_drop.xml new file mode 100644 index 00000000..a29a2a6e --- /dev/null +++ b/android/app/src/main/res/values-en/strings_drop.xml @@ -0,0 +1,16 @@ + + + Drop to save to Relay + Drop to add to this collection + Drop again as often as you like; each drop is one batch + Saving what you dropped… + + Saved · %1$s + Added to collection · batch %1$d · %2$s + Saved to Relay, but couldn\'t add it to this collection · %1$s + Not saved: %1$s + + %1$s (%2$d item in all) + %1$s (%2$d items in all) + + diff --git a/android/app/src/main/res/values-en/strings_fill.xml b/android/app/src/main/res/values-en/strings_fill.xml new file mode 100644 index 00000000..d6847ed5 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_fill.xml @@ -0,0 +1,33 @@ + + + WeChatBridge · Quick fill + Only when you tap \"Fill\" in the staging panel, puts the staged text into the current input box. It never sends for you, does not read or keep other apps\' content, and does not go online. + + Fill \"%1$s\" into the current input box + + Fill all (%d batch) + Fill all (%d batches) + + + Filled. Check it, then tap send yourself + Pasted. Check it, then tap send yourself + Could not fill directly; the text is copied, long-press the input box to paste + The input box has a length limit; the text may be cut off + No input box found. Tap the box you want to fill, then try again + Could not fill. Use the copy button and paste instead + + Turn on Quick fill + Quick fill uses an accessibility service: in the system Accessibility settings, find \"WeChatBridge · Quick fill\" and turn it on. It only puts text into the current input box when you tap \"Fill\"; it does not read or keep anything else and does not go online. + The accessibility service is on but not running (the system may have stopped it). In Accessibility settings, turn \"WeChatBridge · Quick fill\" off and on again. + Android 13 and later: if the switch is greyed out as a \"restricted setting\", open App info, tap ⋮ in the top right, choose \"Allow restricted settings\", then come back. + Turn on + App info + Back + + Quick fill (accessibility) + Tap \"Fill\" in the staging panel to put the text at the cursor of an input box in Doubao, Qwen and other apps. It never sends for you. + On + Off + On, but the service is not running; turn it off and on again in system settings + Xiaomi / HyperOS: turn it on under Settings → Additional settings → Accessibility → Downloaded apps. If it turns itself off later, set WeChatBridge\'s battery saver to \"No restrictions\". + diff --git a/android/app/src/main/res/values-en/strings_onboarding.xml b/android/app/src/main/res/values-en/strings_onboarding.xml new file mode 100644 index 00000000..321b4a10 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_onboarding.xml @@ -0,0 +1,48 @@ + + + Skip + Previous + Next + Get started + Step %1$d of %2$d + + Find WeChatBridge in WeChat + WeChat doesn\'t hand content to other apps on its own. You need to send it to WeChatBridge manually from within WeChat. + Chat history (multi-select) + In a chat, press and hold a message, tap “Multi-select”, then pick the messages to save. + Tap “Forward” or “More”. + Choose “Other apps” (or “Open with other app”). + Pick “WeChatBridge” in the list. When you see “Saved to Relay”, you\'re done. + Files, images, links (one at a time) + Press and hold the file, image or link you want to save. + Tap “Open with other app” or “Share”. + Pick “WeChatBridge” in the list. When you see “Saved to Relay”, you\'re done. + + Smart edge handle (recommended) + Keep sharing from WeChat without interrupting your chat. A slim edge handle appears only when batches are waiting, opening delivery or quick fill on tap or inward swipe. + Collect while chatting, deliver anytime + Skips the receipt card so you stay right in WeChat + Auto-hides when empty; also works via Quick Settings tile or notification + Enable smart edge handle + Smart edge handle is on + Overlay permission not granted. You can skip now and turn it on in Settings anytime. + + Notifications & vault (optional) + Turn on notifications or pick an Obsidian vault if you like. Both are optional and can be changed in Settings anytime. + + Turn on notifications (optional) + Notifications only help with these two things, and you can turn them off anytime in system settings. + While collecting in batches, an ongoing notification shows how many you\'ve collected and lets you finish. + After saving, the notification has a “Deliver” button to send it to your usual AI or agent in one step. + Turn on notifications + Notifications are on + Notifications are off. The app still works, and you can turn them on later in system settings. + + Choose an Obsidian vault (optional) + To help your agent remember this content long-term, write it as notes in your Obsidian vault or any folder to use as a knowledge base. You can skip this and choose later in the delivery sheet. + Choose Obsidian vault or folder + Choose again + Chosen: %1$s + Folder chosen + Couldn\'t get write access to this folder. Please try another one. + diff --git a/android/app/src/main/res/values-en/strings_quick_deliver.xml b/android/app/src/main/res/values-en/strings_quick_deliver.xml new file mode 100644 index 00000000..3b8622d9 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_quick_deliver.xml @@ -0,0 +1,9 @@ + + + Quick deliver + After saving to Relay, deliver to your last target in one step + Saved · deliver to %1$s + Tap to open the delivery sheet with “%1$s” preselected + %1$s · tap to deliver to “%2$s” + Deliver to “%1$s” + diff --git a/android/app/src/main/res/values-en/strings_receive.xml b/android/app/src/main/res/values-en/strings_receive.xml new file mode 100644 index 00000000..e04cf083 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_receive.xml @@ -0,0 +1,40 @@ + + + WeChatBridge + Collect in batches to WeChatBridge + + Saving… + Saved to Relay + Added to collection + Not saved + + %d message + %d messages + + + %d attachment + %d attachments + + + %d file + %d files + + Not a WeChat chat export, so it was saved as a regular file + %1$s: %2$s + + No files or text to save were received. + You can save up to %1$d items at a time, but this share has %2$d. Please share in several rounds. + “%1$s” is an empty file and wasn\'t saved. Please export it again from WeChat. + Couldn\'t read the shared file. Please share it again from the source app. + Storage is full or writing failed. Nothing was saved. + Done + Deliver to last target + Add to collection + OK + + " · " + ", " + Batch %1$d collected + Go back to WeChat, select the next part, then choose “Collect in batches to WeChatBridge” + Tap “OK” to close. You can share again from the source app later. + diff --git a/android/app/src/main/res/values-en/strings_relay.xml b/android/app/src/main/res/values-en/strings_relay.xml new file mode 100644 index 00000000..14063d52 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_relay.xml @@ -0,0 +1,80 @@ + + + Edge handle + Enable “Display over other apps” first + All + Undelivered + Undelivered %1$d + Collecting + Select + %1$d selected + Select all + Cancel selection + + Search + Search title, preview, or source + Clear search text + Collapse + No results for “%1$s” + + Merge and deliver + Delete + Deleted: %1$d + Undo + + Add + Add to Relay + Import from files + Import chat archives, documents, or images + Paste clipboard text + Save clipboard text or links as an item + No text on the clipboard + Saved to Relay (items: %1$d) + Couldn\'t complete: %1$s + Unknown error + + Nothing received yet + In WeChat, multi-select chat messages, tap “Forward” or “More”, choose “Other apps”, then “WeChatBridge”. The chat will show up here. For file messages, you can also press and hold and choose “Open with other app”. + Links and text from browsers, X and other apps can also be sent to WeChatBridge with the system “Share”. You can also tap “+” at the top right to import files, or paste clipboard text. + No records match the filter + + Chat + Messages: %1$d + %1$d msgs + Attachments: %1$d + %1$d attachments + Text + Link + Received %1$s + Last: %1$s: %2$s + Collecting + Delivered + Handed to %1$s + Copied + Delivery failed + Expired + Parse failed + Chat + Text + Link + Files + Deliver + + Untitled collection + Batches: %1$d · about %2$d messages + %1$d batches · ~%2$d msgs + Previous batch %1$s + View batches + Merge & deliver + + %1$s and %2$d more + Today + Yesterday + Today %1$s + 1 file + %1$d files + Sent to %1$s + %1$d/%2$d + %2$d/%3$d/%1$d + %1$02d:%2$02d + diff --git a/android/app/src/main/res/values-en/strings_scenes.xml b/android/app/src/main/res/values-en/strings_scenes.xml new file mode 100644 index 00000000..bcecd1e5 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_scenes.xml @@ -0,0 +1,54 @@ + + + Official scenes + My scenes + Group bindings + When you receive chats from these groups, the bound scene is used directly. + No groups have a bound scene yet. After choosing a scene while delivering, you can bind it to the group. + You don\'t have any scenes of your own yet. + New scene + More + Import scene JSON + Export my scenes + Enable “%1$s” + Delete + Delete scene + Delete “%1$s”? Groups bound to it will be unbound too. + WeChatBridge scenes.json + + Unbind + Unbind “%1$s” + Unbind all + Deleted scene + %1$s (off) + + Imported scenes: %1$d + Import failed: %1$s + Exported scenes: %1$d + Export failed: %1$s + No scenes to export + Copied as “%1$s” + Unknown error + + New scene + Save + Official scenes can\'t be edited directly. Copy one as your own scene, then edit it. + Copy as my scene + Name + For example: Project group daily report + One-line description + Prompt + Output spec + Group name keywords + Separate with commas + When a group name contains these words, this scene is chosen automatically. + Applies to targets + This scene is only used for the selected targets. Choose at least one. + + ChatGPT / Codex + Claude + Doubao + Qwen Work + WorkBuddy + WeSight + diff --git a/android/app/src/main/res/values-en/strings_settings.xml b/android/app/src/main/res/values-en/strings_settings.xml new file mode 100644 index 00000000..e101190d --- /dev/null +++ b/android/app/src/main/res/values-en/strings_settings.xml @@ -0,0 +1,74 @@ + + + Core features + Delivery & storage + Collection & relay + Support & about + Delivery + Save location + Relay + Share entries + Notifications + Diagnostics + About + + Choose which targets appear in the delivery sheet, and set their order and default format + Manage the prompt scenes attached when delivering + + Notes are written to “chosen folder/subfolder”. The folder must be visible in the system file picker. + Obsidian vault + Default folder + Not chosen + Checking… + Access expired. Please choose again + Chosen (name unreadable) + Choose + Choose again + Clear + Choose Obsidian vault + Choose Obsidian vault again + Clear Obsidian vault + Choose default folder + Choose default folder again + Clear default folder + Subfolder in Obsidian vault + Subfolder in default folder + Leave blank to use “%1$s” + + Keep records for + %1$s + Keep received records + %1$d days + Never delete + + Choose whether WeChatBridge entries appear in the system share sheet. Turning one off removes it from the share sheet. + Save to WeChatBridge + Save shared content to Relay + Collect in batches to WeChatBridge + Merge several shares into one batch and deliver them together at the end + Keep at least one of the two entries + Both entries can\'t be turned off at once + + Notification permission + Allowed + Not allowed: collection progress and quick deliver reminders won\'t show + Turned off in system settings + Allow notifications + Turn on in system settings + + Export a redacted text report: version, settings status and recent imports. It contains no chat content. + Export diagnostics + wechatbridge-diagnostics.txt + Diagnostics exported + Export failed. Try another location + + Version + %1$s (%2$d) + Unknown + View the guide again + Website + https://render.qmuse.pub/p/muse/2413870555736078 + Chats stay on this device. Nothing is uploaded to a server. + + Can\'t use this folder. Please choose another one + diff --git a/android/app/src/main/res/values-en/strings_settings_targets.xml b/android/app/src/main/res/values-en/strings_settings_targets.xml new file mode 100644 index 00000000..9b2e3726 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_settings_targets.xml @@ -0,0 +1,23 @@ + + + Manage targets + Choose which targets appear in the delivery sheet, and set their order and default format. + Installed + Not installed + Custom + Hidden + Show %1$s + Move %1$s up + Move %1$s down + Default format: %1$s + %1$s (default) + Default format + Remove %1$s + Add app + Add app + Select the apps to add to the delivery sheet. Only installed apps that can receive shares are listed. + Looking for installed apps… + No apps available to add. + Add + Add (%1$d) + diff --git a/android/app/src/main/res/values-night/colors.xml b/android/app/src/main/res/values-night/colors.xml new file mode 100644 index 00000000..2d855738 --- /dev/null +++ b/android/app/src/main/res/values-night/colors.xml @@ -0,0 +1,4 @@ + + + #FF111111 + diff --git a/android/app/src/main/res/values-night/themes.xml b/android/app/src/main/res/values-night/themes.xml new file mode 100644 index 00000000..f6e3c712 --- /dev/null +++ b/android/app/src/main/res/values-night/themes.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..27d8817a --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #FF07C160 + #FFF9FCFB + #FFF7F7F7 + diff --git a/android/app/src/main/res/values/strings_a11y.xml b/android/app/src/main/res/values/strings_a11y.xml new file mode 100644 index 00000000..1f1fefab --- /dev/null +++ b/android/app/src/main/res/values/strings_a11y.xml @@ -0,0 +1,9 @@ + + + + 启用场景「%1$s」 + 删除场景「%1$s」 + 多选 + 关闭 + 已发送 + diff --git a/android/app/src/main/res/values/strings_bubble.xml b/android/app/src/main/res/values/strings_bubble.xml new file mode 100644 index 00000000..dd4b27c3 --- /dev/null +++ b/android/app/src/main/res/values/strings_bubble.xml @@ -0,0 +1,108 @@ + + + + + + 微信流边缘把手,暂存 %d 批,点按或向内轻滑展开 + + + +1 · 暂存 %d 批 + + + + + 暂存 %d 批 + + 暂存 + 中转站里没有待投递的批次。在微信里「分享 → 其他应用 → 微信流」,这里的数字就会加一。 + 收起 + 投递「%1$s」 + + 还有 %d 批,打开微信流查看 + + + 全部合并投递(%d 批) + + + 全部合并填入(%d 批) + + 填入 + 复制 + 打开微信流 + 关闭边缘条 + 边缘把手已关闭,可在「设置 → 悬浮边缘条」里重新打开 + + + 长按可拖到其他应用的输入框 + 拖出文字 + 已拖入 + 没有放进输入框,可点右侧的复制按钮 + 没能开始拖动,请按住不放再拖,或点右侧的复制按钮 + 这一批没有可拖出的文字 + 文字太长,没法拖出或复制,请点这一批去投递 + 读不出这一批的文字 + 复制「%1$s」的文字 + 已复制 + 没能复制到剪贴板 + + + 拖出图片 + 拖拽全文 + 拖拽图片 ×%1$d + 拖拽图片 + 图片 ×%1$d + + 拖出 %d 张图片 + + + 图片 ×%d + + 原包 + 拖出原始压缩包 + 长按后拖到其他应用里 + 一次最多拖出 %1$d 张,已取前 %1$d 张 + 这个应用不接收拖入的图片,可在投递面板里分享 + 这个应用不接收拖入的文件 + 这一批没有可拖出的图片 + 这一批没有可拖出的文字或图片 + 没能准备好要拖出的图片 + 没能准备好原始压缩包 + + + 微信流暂存 + + 暂存 %d 批 + + 点按展开面板 + + + 悬浮边缘条 + 静默接收与暂存面板的常驻通知,可随时点按展开暂存面板 + 微信流已就绪 + + 暂存 %d 批 · 点按展开暂存面板 + + 静默接收中 · 点按展开暂存面板 + 展开面板 + 打开微信流 + 关闭 + + + 没有存入微信流:%1$s + + + 悬浮边缘条 + 智能边缘把手 + 分享到微信流后不弹收据卡,直接回到微信;极细贴边把手不遮挡内容,点按或向内轻滑即可展开暂存面板,也支持零悬浮磁贴/通知栏呼出。 + 有暂存时才显示边缘条 + 平时保持屏幕完全干净,收到微信分享后自动浮现 + 纯零悬浮模式 + 仅通过下拉快捷磁贴与通知栏呼出暂存面板,不显示屏幕边缘条 + 打开时需要授予「显示在其他应用上层」权限。 + 悬浮窗权限已关闭,边缘把手与暂存面板不会显示,分享后仍弹收据卡。 + 没有拿到悬浮窗权限,未能开启。 + 去授权 + 小米 / HyperOS:还要在「应用权限 → 其他权限」里打开「后台弹出界面」和「显示悬浮窗」,否则边缘把手或暂存面板可能不显示。 + 打开小米权限设置 + 常驻通知可随时展开暂存面板并保持静默接收;没有通知权限时通知不显示,边缘把手与快捷磁贴照常工作。 + diff --git a/android/app/src/main/res/values/strings_collect.xml b/android/app/src/main/res/values/strings_collect.xml new file mode 100644 index 00000000..926302b8 --- /dev/null +++ b/android/app/src/main/res/values/strings_collect.xml @@ -0,0 +1,43 @@ + + + + + 未命名收集 + %1$d 批 · 约 %2$d 条 + %1$d 批 · 条数暂不可用 + 第 %1$d 批 + %1$d 条 + 条数未知 + 首条 %1$s + 末条 %1$s:%2$s + 未能读取位置参考,原始文件已保存 + 正在读取… + 移出本次收集 + 移出只解除归属,批次仍留在中转站。 + 投递时按时间合并,前后批重叠的消息只留一份。 + 这个收集里已经没有批次了。 + 这个收集已结束或不存在。 + 完成并投递 + 合并并投递 + 继续收集 + 收集进行中 + 放弃 + 放弃这个收集? + 放弃后不再追加新批次,已收的批次仍留在中转站。 + 放弃收集 + + + 最后一批正好 100 条,可能还没收完 + 微信一次最多转发 100 条。回微信在这个聊天里搜索下面的关键词,定位到这一句,从它后面接着多选,再分享到「分批收集到微信流」。 + 上一批最后一句 · %1$s · %2$s + 复制关键词 + 已复制「%1$s」 + + + 分批收集 + 收集进行中时常驻,可直接完成并投递或放弃 + 收集中 · %1$d 批 + 继续在微信分享到「分批收集到微信流」,收齐后完成并投递。 + 完成并投递 + 放弃 + diff --git a/android/app/src/main/res/values/strings_common.xml b/android/app/src/main/res/values/strings_common.xml new file mode 100644 index 00000000..9c89229e --- /dev/null +++ b/android/app/src/main/res/values/strings_common.xml @@ -0,0 +1,17 @@ + + + + 微信流 + 开发中 + 返回 + 完成 + 取消 + 中转站 + 批次详情 + 投递 + 场景 + 投递目标 + 设置 + 使用引导 + 收集 + diff --git a/android/app/src/main/res/values/strings_deliver.xml b/android/app/src/main/res/values/strings_deliver.xml new file mode 100644 index 00000000..9ed7d8ec --- /dev/null +++ b/android/app/src/main/res/values/strings_deliver.xml @@ -0,0 +1,134 @@ + + + + + ChatGPT + Claude + Gemini + 元宝 + 豆包 + 千问 + DeepSeek + 飞书 + 语雀 + 小米笔记 + Obsidian + 文件夹 + 其他应用 + + + 原始 ZIP + TXT + 图片 + 仅 TXT + 粘贴为文字 + 知识库笔记 + 文件夹 + + + 系统分享面板 + 已投递 + 投递未完成 + + + 合并投递 %1$d 批 + 关闭 + 完成 + 正在加载… + 找不到这些批次,可能已被删除。 + 微信聊天记录 + 单批内容 · 准备投递 + 已合并 %1$d 批内容 + %1$d 个文件 + 纯文字 + %1$d 批 + + + 投递到 + 未安装 + 没有安装%1$s,无法投递到这里。 + 已选中 + + + 场景与提示词 + 不带场景 + 已按群自动匹配 + 已按这个群绑定的场景选择 + 已按群名关键词选择场景 + 已按群成员识别出场景 + 沿用这个群上次用的场景 + 默认场景 + 提示词 + 编辑 + 收起 + 点击编辑提示词… + 发送时会复制到剪贴板,可在对方输入框里粘贴。 + + + 将投递的内容 + 选择一个投递目标,这里会显示将要发送的内容。 + 正在准备文件… + 格式:%1$s + 文件较多,将分 %1$d 次发送 + 第 %1$d/%2$d 组 · %3$d 个文件 + …另有 %1$d 个文件 + 聊天记录将作为文字随消息一起发送。 + 聊天记录太长,没法作为文字发送,已改为 TXT 文件。 + 未随附(%1$d) + …等 %1$d 项 + 改发原始 ZIP + 改发原始文件 + 换一种格式 + 恢复默认格式 + 这些内容里没有能读取的聊天记录。 + 这些内容无法按这个目标需要的格式发送。 + 准备文件时出错,可能是存储空间不足或文件已被删除。 + + + 发送 + 发送到 %1$s + 保存到 %1$s + 继续发送 第 %1$d/%2$d 组 + 已发送 + %1$s 未安装 + 保存路径 + + + 已交给 %1$s + 已发送第 %1$d/%2$d 组,点「继续发送」发出下一组。 + 已全部发送(共 %1$d 组)。 + 提示词已复制,可在对方输入框粘贴 + 对方不会收到提示词,请自行粘贴。 + 请在下一屏选择「%1$s」。 + 请在下一屏选择要发送的应用。 + 文字太长,没有随消息发出。 + 没有安装 %1$s,没能发送。 + 没有可发送的内容。 + 文件不在可分享的目录里,已拒绝发送。 + 有文件已不存在,请重新选择目标再试。 + 文字太长,无法直接发送,请换成文件格式。 + 无法打开目标应用:%1$s + 无法打开目标应用。 + 这个收集已经投递过,或已不存在。 + 还没选择 Obsidian 库。请选择库所在的文件夹,笔记会写进其中的「%1$s」。 + 还没选择保存的文件夹。笔记会写进其中的「%1$s」。 + 之前选择的文件夹已无法访问,请重新选择。 + 写入:%1$s/%2$s + 选择文件夹 + 重新选择 + 已写入 %1$d 篇笔记:%2$s + 文件夹已无法访问,请重新选择后再写入。 + 没能获得这个文件夹的长期访问权限,请换一个文件夹。 + 没有可写入的聊天内容。 + 写入失败,且部分文件没能清理,请到文件夹里检查。 + 写入失败:%1$s + 写入失败。 + 群:%1$s + 没认出是哪个群 + 选择群 + 新建群 + 新建群 + 群名 + 以后这个群用这个场景 + 已绑定到这个群 + 确定 + diff --git a/android/app/src/main/res/values/strings_detail.xml b/android/app/src/main/res/values/strings_detail.xml new file mode 100644 index 00000000..dd0a6b72 --- /dev/null +++ b/android/app/src/main/res/values/strings_detail.xml @@ -0,0 +1,38 @@ + + + + 聊天记录 + 投递 + 投递此批次 + 复制全文 + 已复制全文到剪贴板 + 没有可复制的文字内容 + %1$d 条消息 + %1$d 个文件 + %1$d 字 + 链接分享 + 正在读取… + 这批记录已删除 + 文件 + 读取失败:%1$s + 来自 %1$s + + + 图片 %1$s + 图片未随附 + 视频 + 文件 + 视频号 + 图 + 视 + 文 + 链 + 号 + + + 无法显示这张图片 + 完成 + + + 没有可以打开它的应用 + diff --git a/android/app/src/main/res/values/strings_drop.xml b/android/app/src/main/res/values/strings_drop.xml new file mode 100644 index 00000000..e58600ff --- /dev/null +++ b/android/app/src/main/res/values/strings_drop.xml @@ -0,0 +1,19 @@ + + + + + 松手存入中转站 + 松手加入这个收集 + 可以连续拖入多次,每次存成一批 + 正在存入拖入的内容… + + + 已存入 · %1$s + 已加入收集 · 第 %1$d 批 · %2$s + 已存入中转站,但没能加入这个收集 · %1$s + 没有存入:%1$s + + + %1$s 等 %2$d 项 + + diff --git a/android/app/src/main/res/values/strings_fill.xml b/android/app/src/main/res/values/strings_fill.xml new file mode 100644 index 00000000..dc950b4f --- /dev/null +++ b/android/app/src/main/res/values/strings_fill.xml @@ -0,0 +1,38 @@ + + + + + 微信流 · 一键填入 + 仅在你点击暂存面板里的「填入」时,把暂存内容填入当前输入框,不会替你发送;不读取、不保存其他应用内容,不联网。 + + + 把「%1$s」填入当前输入框 + + 全部填入(%d 批) + + + + 已填入,检查后自己点发送 + 已粘贴,检查后自己点发送 + 没能直接填入,文字已复制,长按输入框粘贴 + 输入框有字数上限,内容可能被截断 + 没找到输入框,先点一下要填入的输入框再试 + 没能填入,可点复制按钮手动粘贴 + + + 开启「一键填入」 + 一键填入要用到无障碍服务:在系统「无障碍」里找到「微信流 · 一键填入」并打开。它只在你点「填入」时把文字放进当前输入框,不读取、不保存其他内容,不联网。 + 无障碍服务已开启,但没有在运行(可能被系统清理了)。请在系统「无障碍」里把「微信流 · 一键填入」关掉再打开。 + Android 13 及以上:如果开关是灰的、提示「受限设置」,先到「应用详情 → 右上角 ⋮ → 允许受限设置」,再回来打开。 + 去开启 + 应用详情 + 返回 + + + 一键填入(无障碍) + 在暂存面板里点「填入」,把文字放进豆包、千问等应用输入框的光标处,不替你发送。 + 已开启 + 未开启 + 已开启,但服务没有在运行;请在系统里关掉再打开 + 小米 / HyperOS:在「设置 → 更多设置 → 无障碍 → 已下载的应用」里打开;如果过一阵自己关掉了,把微信流的省电策略设为「无限制」。 + diff --git a/android/app/src/main/res/values/strings_onboarding.xml b/android/app/src/main/res/values/strings_onboarding.xml new file mode 100644 index 00000000..3a154b41 --- /dev/null +++ b/android/app/src/main/res/values/strings_onboarding.xml @@ -0,0 +1,54 @@ + + + + 跳过 + 上一步 + 下一步 + 开始使用 + 第 %1$d 步,共 %2$d 步 + + + 在微信里找到微信流 + 微信不会主动把内容交给别的 App,需要你在微信里手动把内容「发」到微信流。 + 聊天记录(多选) + 在聊天里长按一条消息,点「多选」,勾选要保存的消息。 + 点「转发」或「更多」。 + 选「其他应用」(或「用其他应用打开」)。 + 在列表里选「微信流」,看到「已存入中转站」就完成了。 + 文件、图片、链接(逐条) + 长按要保存的文件、图片或链接。 + 点「用其他应用打开」或「分享」。 + 在列表里选「微信流」,看到「已存入中转站」就完成了。 + + + 开启智能边缘把手(推荐) + 开启后,在微信里连续转发不会打断聊天;极细贴边把手只在有暂存时浮现,点按或向内轻滑即可一键投递或填入 AI。 + 边聊边收,随时投递 + 分享后不弹收据卡,直接回到微信继续浏览 + 平时自动隐藏不遮挡屏幕,支持边缘把手与快捷磁贴呼出 + 一键开启智能边缘把手 + 智能边缘把手已开启 + 未授予悬浮窗权限,可先跳过,之后在设置里随时开启。 + + + 通知与知识库(可选) + 按需开启通知提醒或绑定 Obsidian 库,跳过也不影响基本使用,随时可在设置里修改。 + + + 开启通知(可选) + 通知只用来帮你更快完成这两件事,随时可以在系统设置里关闭。 + 分批收集时,在通知栏显示常驻通知,随时查看已收集的数量并结束收集。 + 存入之后,通知里直接带有「投递」按钮,一步送给你常用的 AI 或 Agent。 + 开启通知 + 通知已开启 + 通知未开启。不影响使用,之后可以在系统设置里打开。 + + + 选择 Obsidian 库(可选) + 想让 Agent 长期记住这些内容,可以把它们写成笔记,存进你的 Obsidian 库或任意文件夹,当作知识库。不选也可以,之后能在投递面板里再选。 + 选择 Obsidian 库或文件夹 + 重新选择 + 已选择:%1$s + 已选择文件夹 + 没能获得这个文件夹的写入权限,请换一个文件夹再试。 + diff --git a/android/app/src/main/res/values/strings_quick_deliver.xml b/android/app/src/main/res/values/strings_quick_deliver.xml new file mode 100644 index 00000000..d5312553 --- /dev/null +++ b/android/app/src/main/res/values/strings_quick_deliver.xml @@ -0,0 +1,10 @@ + + + + 快速投递 + 存入中转站后,一步投给上次的目标 + 已存入 · 投给 %1$s + 点一下打开投递面板,已选好「%1$s」 + %1$s · 点一下投递到「%2$s」 + 投递到「%1$s」 + diff --git a/android/app/src/main/res/values/strings_receive.xml b/android/app/src/main/res/values/strings_receive.xml new file mode 100644 index 00000000..5622c432 --- /dev/null +++ b/android/app/src/main/res/values/strings_receive.xml @@ -0,0 +1,43 @@ + + + + + 微信流 + 分批收集到微信流 + + + 正在存入… + 已存入中转站 + 已加入收集 + 没有存入 + + %d 条消息 + + + %d 个附件 + + + %d 个文件 + + 不是微信聊天记录格式,已按普通文件存入 + %1$s:%2$s + + + 没有收到可存入的文件或文字。 + 一次最多存入 %1$d 项,这次有 %2$d 项。请分几次分享。 + 「%1$s」是空文件,没有存入。请回到微信重新导出。 + 读不到分享的文件,请从来源 App 重新分享。 + 存储空间不足或写入失败,没有存入。 + + 完成 + 投给上次目标 + 加入收集 + 好 + + + " · " + 、 + 已收第 %1$d 批 + 回微信多选下一段,再选「分批收集到微信流」 + 点「好」关闭,之后可以回到来源 App 重新分享。 + diff --git a/android/app/src/main/res/values/strings_relay.xml b/android/app/src/main/res/values/strings_relay.xml new file mode 100644 index 00000000..37dbfe69 --- /dev/null +++ b/android/app/src/main/res/values/strings_relay.xml @@ -0,0 +1,89 @@ + + + + + 边缘把手 + 请先开启「显示在其他应用上层」权限 + 全部 + 未投递 + 未投递 %1$d + 收集中 + 多选 + 已选 %1$d 条 + 全选 + 取消多选 + + + 搜索 + 搜索标题、预览或来源 + 清空搜索词 + 收起 + 没有找到「%1$s」 + + + 合并投递 + 删除 + 已删除 %1$d 条 + 撤销 + + + 添加 + 收入到中转站 + 从文件导入 + 导入聊天记录压缩包、文档或图片 + 粘贴剪贴板文本 + 将剪贴板里的文字或链接存为一条记录 + 剪贴板里没有文字 + 已存入中转站(%1$d 项) + 操作没有完成:%1$s + 未知错误 + + + 还没有收到内容 + 在微信里多选聊天记录,点「转发」或「更多」,选择「其他应用」,再选「微信流」,聊天记录就会出现在这里。文件消息也可以长按,选「用其他应用打开」。 + 浏览器、X 等应用里的链接和文字,也可以用系统「分享」发到微信流;还可以点右上角「+」导入文件,或粘贴剪贴板文本。 + 没有符合筛选条件的记录 + + + 聊天记录 + %1$d 条消息 + %1$d 条 + %1$d 个附件 + 含 %1$d 个附件 + 文本 + 链接 + 收到于 %1$s + 末条 %1$s:%2$s + 收集中 + 已投递 + 已交给 %1$s + 已复制 + 投递失败 + 已过期 + 解析失败 + 聊天记录 + 文本 + 链接 + 文件 + 投递 + + + 未命名收集 + %1$d 批 · 约 %2$d 条 + 已收集 %1$d 批 · 约 %2$d 条 + 上一批 %1$s + 查看批次 + 合并投递 + + + %1$s 等 %2$d 个 + 今天 + 昨天 + 今天 %1$s + 1 个文件 + %1$d 个文件 + 发给 %1$s + %1$d月%2$d日 + %1$d年%2$d月%3$d日 + %1$02d:%2$02d + diff --git a/android/app/src/main/res/values/strings_scenes.xml b/android/app/src/main/res/values/strings_scenes.xml new file mode 100644 index 00000000..0de0c8f3 --- /dev/null +++ b/android/app/src/main/res/values/strings_scenes.xml @@ -0,0 +1,55 @@ + + + + 官方场景 + 我的场景 + 群绑定 + 收到这些群的聊天记录时,会直接使用绑定的场景。 + 还没有绑定过场景的群。投递时选定场景后,可以把它绑定到群。 + 还没有自己的场景。 + 新建场景 + 更多 + 导入场景 JSON + 导出我的场景 + 启用「%1$s」 + 删除 + 删除场景 + 确定删除「%1$s」吗?绑定到它的群会一并解绑。 + 微信流场景.json + + 解绑 + 解绑「%1$s」 + 全部解绑 + 已删除的场景 + %1$s(已关闭) + + 已导入 %1$d 个场景 + 导入失败:%1$s + 已导出 %1$d 个场景 + 导出失败:%1$s + 没有可导出的场景 + 已复制为「%1$s」 + 未知错误 + + 新建场景 + 保存 + 官方场景不能直接修改,可以复制成我的场景后再改。 + 复制为我的场景 + 名称 + 比如:项目群日报 + 一句话说明 + 提示词 + 输出规范 + 群名关键词 + 用逗号分隔 + 群名含有这些词时,自动选用这个场景。 + 适用目标 + 只在所选的目标里使用这个场景;至少要选一个。 + + ChatGPT / Codex + Claude + 豆包 + 千问办公 + WorkBuddy + WeSight + diff --git a/android/app/src/main/res/values/strings_settings.xml b/android/app/src/main/res/values/strings_settings.xml new file mode 100644 index 00000000..460bd670 --- /dev/null +++ b/android/app/src/main/res/values/strings_settings.xml @@ -0,0 +1,84 @@ + + + + + 核心能力 + 投递与保存位置 + 收集与中转站 + 支持与关于 + 投递 + 保存位置 + 中转站 + 分享入口 + 通知 + 诊断 + 关于 + + + 选择哪些目标出现在投递面板,调整顺序与默认格式 + 管理投递时附带的提示词场景 + + + 笔记写入「所选文件夹/子文件夹」。需要先在系统文件选择器里能看到这个文件夹。 + Obsidian 库 + 默认文件夹 + 未选择 + 正在检查… + 授权已失效,请重新选择 + 已选择(名称不可读) + 选择 + 重新选择 + 清除 + 选择 Obsidian 库 + 重新选择 Obsidian 库 + 清除 Obsidian 库 + 选择默认文件夹 + 重新选择默认文件夹 + 清除默认文件夹 + Obsidian 库的子文件夹 + 默认文件夹的子文件夹 + 留空则使用「%1$s」 + + + 记录保留时间 + %1$s + 保留已收到的记录 + %1$d 天 + 从不清理 + + + 决定系统分享面板里是否出现微信流的入口。关闭后对应入口会从分享面板消失。 + 存入微信流 + 把分享内容存入中转站 + 分批收集到微信流 + 多次分享合并成一个批次,最后一起投递 + 两个入口至少要保留一个 + 两个入口不能同时关闭 + + + 通知权限 + 已允许 + 未允许:收集进度和快速投递提醒不会显示 + 已在系统设置里关闭 + 允许通知 + 去系统设置开启 + + + 导出一份脱敏的文本报告:版本、设置状态和最近的导入记录,不含聊天内容。 + 导出诊断 + wechatbridge-diagnostics.txt + 诊断已导出 + 导出失败,请换个位置再试 + + + 版本 + %1$s(%2$d) + 未知 + 重新查看引导 + 官网 + https://render.qmuse.pub/p/muse/2413870555736078 + 聊天记录仅存本机,不上传服务器。 + + + 无法使用这个文件夹,请换一个 + diff --git a/android/app/src/main/res/values/strings_settings_targets.xml b/android/app/src/main/res/values/strings_settings_targets.xml new file mode 100644 index 00000000..df715f82 --- /dev/null +++ b/android/app/src/main/res/values/strings_settings_targets.xml @@ -0,0 +1,24 @@ + + + + 目标管理 + 选择哪些目标出现在投递面板里,调整它们的顺序和默认格式。 + 已安装 + 未安装 + 自定义 + 已隐藏 + 显示 %1$s + %1$s 上移 + %1$s 下移 + 默认格式:%1$s + %1$s(默认) + 默认格式 + 移除 %1$s + 添加 App + 添加 App + 勾选要加入投递面板的 App。这里只列出已安装且能接收分享的 App。 + 正在查找已安装的 App… + 没有找到可以添加的 App。 + 添加 + 添加(%1$d) + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 00000000..e31fd450 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,6 @@ + + + + diff --git a/android/app/src/main/res/values/themes_receive.xml b/android/app/src/main/res/values/themes_receive.xml new file mode 100644 index 00000000..1ab68205 --- /dev/null +++ b/android/app/src/main/res/values/themes_receive.xml @@ -0,0 +1,16 @@ + + + + + diff --git a/android/app/src/main/res/xml/backup_rules.xml b/android/app/src/main/res/xml/backup_rules.xml new file mode 100644 index 00000000..761e89bb --- /dev/null +++ b/android/app/src/main/res/xml/backup_rules.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 00000000..73be39fa --- /dev/null +++ b/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/xml/fill_accessibility.xml b/android/app/src/main/res/xml/fill_accessibility.xml new file mode 100644 index 00000000..ccb0ece3 --- /dev/null +++ b/android/app/src/main/res/xml/fill_accessibility.xml @@ -0,0 +1,13 @@ + + + diff --git a/android/app/src/main/res/xml/share_paths.xml b/android/app/src/main/res/xml/share_paths.xml new file mode 100644 index 00000000..fd45de01 --- /dev/null +++ b/android/app/src/main/res/xml/share_paths.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragTest.kt new file mode 100644 index 00000000..5106c3a3 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleDragTest.kt @@ -0,0 +1,232 @@ +package com.xiangming.wechatbridge.bubble + +import android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN +import android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE +import android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE +import com.xiangming.wechatbridge.core.archive.WeChatArchive +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.DeliveryPlanner +import com.xiangming.wechatbridge.core.deliver.DeliveryRequest +import com.xiangming.wechatbridge.core.inbox.ReadyBatch +import com.xiangming.wechatbridge.core.inbox.ReadyItem +import com.xiangming.wechatbridge.core.inbox.ShareAction +import com.xiangming.wechatbridge.core.scene.SceneSettings +import com.xiangming.wechatbridge.core.scene.WeChatScene +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.core.transcript.TranscriptMerge +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.data.SceneStore +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.time.Instant +import java.time.ZoneId +import java.util.UUID + +class BubbleDragTest { + @get:Rule + val temp = TemporaryFolder() + + private val zone: ZoneId = ZoneId.of("Asia/Shanghai") + private val base = Instant.parse("2026-11-25T08:00:00Z") + private lateinit var scenes: SceneStore + private val workDirs = mutableListOf() + + @Before + fun setUp() { + scenes = SceneStore(temp.newFolder("files")) + } + + // region Helpers + + private fun fixture(name: String): File { + var dir: File? = File("").absoluteFile + while (dir != null) { + val candidate = File(dir, "ios/Tests/Fixtures/$name") + if (candidate.isFile) return candidate + dir = dir.parentFile + } + error("fixture $name not found above ${File("").absolutePath}") + } + + private fun entry( + files: List>, + kind: RelaySummary.Kind?, + minutes: Long = 0, + chatName: String? = null, + ): RelayEntry { + val id = UUID.randomUUID() + val created = base.plusSeconds(minutes * 60) + val items = files.map { (file, type) -> + ReadyItem(UUID.randomUUID(), id, file.name, file, file.length(), type, created, ShareAction.CLAUDE) + } + val batch = ReadyBatch( + id = id, + directory = temp.root, + createdAt = created, + action = ShareAction.CLAUDE, + items = items, + outcome = null, + chatName = chatName, + isFirstSeen = false, + ) + return RelayEntry(batch, kind?.let { RelaySummary(title = "群聊", kind = it) }, isCollecting = false) + } + + private fun chat(name: String, minutes: Long = 0) = + entry(listOf(fixture(name) to "application/zip"), RelaySummary.Kind.CHAT, minutes) + + private fun note(text: String, minutes: Long = 0): RelayEntry { + val file = File(temp.newFolder(), "链接.txt").apply { writeText(text) } + return entry(listOf(file to ShareOrigin.NOTE_CONTENT_TYPE), RelaySummary.Kind.LINK, minutes) + } + + private fun defaultScene(instruction: String = "请按要点总结。"): WeChatScene { + val scene = WeChatScene(name = "测试场景", instruction = instruction, outputSpec = "", enabled = true) + scenes.setSettings(SceneSettings(listOf(scene), defaultSceneID = scene.id)) + return scene + } + + private fun build(vararg entries: RelayEntry): DragText = + BubbleDragText.build(entries.toList(), scenes, { temp.newFolder().also { workDirs += it } }, zone) + + private fun ready(vararg entries: RelayEntry): String = + (build(*entries) as? DragText.Ready)?.text ?: error("expected text") + + private fun body(name: String): String = WeChatArchive.transcript(fixture(name), zone)!!.body + + // endregion + + // region Text + + @Test + fun chatBatchIsScenePromptThenTranscript() { + defaultScene() + val text = ready(chat("group-a.zip")) + val parts = text.split("\n\n", limit = 2) + assertTrue(parts[0], parts[0].contains("请按要点总结。")) + // The delivery panel's EXTRA_TEXT: prompt, blank line, the inline body. + assertTrue(text.endsWith(body("group-a.zip"))) + assertTrue(text.startsWith(parts[0])) + } + + @Test + fun chatWithoutAnySceneIsJustTheTranscript() { + scenes.setSettings(SceneSettings(emptyList(), defaultSceneID = null)) + assertEquals(body("group-a.zip"), ready(chat("group-a.zip"))) + } + + @Test + fun linkNoteGoesAsItIsWithoutPrompt() { + defaultScene() + val original = "看看这篇\nhttps://example.com/a" + assertEquals(original, ready(note(original))) + } + + @Test + fun mergeInterleavesChatsByTimeWithOnePrompt() { + defaultScene() + val older = chat("group-a.zip", minutes = 0) + val newer = chat("group-a-later.zip", minutes = 5) + val ordered = BubbleDragText.mergeOrder(listOf(newer, older)) + assertEquals(listOf(older, newer), ordered) + val text = ready(*ordered.toTypedArray()) + // Exactly what delivery would put inline for the same batches (merged by time, images renamed). + val planned = DeliveryPlanner.plan( + DeliveryRequest(ordered.map { it.batch }, BubbleDragText.TEXT_ONLY, prompt = null, format = DeliveryFormat.INLINE_TEXT, zone = zone), + temp.newFolder(), + ).inlineText!! + assertTrue(text.endsWith("\n\n" + planned)) + // Interleaved, not one after the other. + assertTrue(planned != body("group-a.zip").trim() + "\n\n" + body("group-a-later.zip").trim()) + assertTrue(planned.contains(TranscriptMerge.merge(listOf(body("group-a.zip")), zone).lines().first())) + assertEquals(1, Regex("请按要点总结。").findAll(text).count()) + } + + @Test + fun mergeSkipsTextlessBatches() { + scenes.setSettings(SceneSettings(emptyList(), defaultSceneID = null)) + val files = entry(listOf(fixture("files-only.zip") to "application/zip"), RelaySummary.Kind.FILES, minutes = 1) + assertEquals(body("group-a.zip"), ready(chat("group-a.zip"), files)) + } + + @Test + fun attachmentsOnlyHasNoText() { + val files = entry(listOf(fixture("files-only.zip") to "application/zip"), RelaySummary.Kind.FILES) + assertTrue(BubbleDragText.isTextless(files)) + assertEquals(DragText.NoText, build(files)) + assertEquals(DragText.NoText, build()) + } + + @Test + fun unsummarizedAttachmentsAreFoundByThePlanner() { + val files = entry(listOf(fixture("files-only.zip") to "application/zip"), kind = null) + assertFalse(BubbleDragText.isTextless(files)) + assertEquals(DragText.NoText, build(files)) + } + + @Test + fun textOverTheInlineLimitIsTooLarge() { + assertEquals(DragText.TooLarge, build(note("字".repeat(DeliveryPlanner.INLINE_TEXT_LIMIT)))) + } + + @Test + fun workDirectoriesAreRemoved() { + defaultScene() + build(chat("group-a.zip")) + assertTrue(workDirs.isNotEmpty()) + assertTrue(workDirs.none { it.exists() }) + } + + @Test + fun textlessJudgement() { + val pdf = File(temp.newFolder(), "a.pdf").apply { writeText("x") } + assertTrue(BubbleDragText.isTextless(entry(listOf(pdf to "application/pdf"), RelaySummary.Kind.FILES))) + assertTrue(BubbleDragText.isTextless(entry(emptyList(), kind = null))) + // A shared link with files is still a link. + val link = File(temp.newFolder(), "链接.txt").apply { writeText("https://example.com") } + assertFalse(BubbleDragText.isTextless(entry(listOf(pdf to "application/pdf", link to ShareOrigin.NOTE_CONTENT_TYPE), RelaySummary.Kind.FILES))) + assertFalse(BubbleDragText.isTextless(entry(listOf(pdf to "application/pdf"), RelaySummary.Kind.CHAT))) + val textless = entry(listOf(pdf to "application/pdf"), RelaySummary.Kind.FILES) + assertTrue(BubbleDragText.allTextless(listOf(textless, textless))) + assertFalse(BubbleDragText.allTextless(listOf(textless, entry(listOf(link to ShareOrigin.NOTE_CONTENT_TYPE), RelaySummary.Kind.LINK)))) + } + + @Test + fun joinMatchesTheDeliveryPanel() { + assertEquals("提示\n\n正文", BubbleDragText.join(" 提示\n", "正文")) + assertEquals("正文", BubbleDragText.join(null, "正文")) + assertEquals("正文", BubbleDragText.join(" ", "正文")) + } + + // endregion + + // region Window flags + + @Test + fun dragMakesThePanelLetDropsThrough() { + val rest = FLAG_LAYOUT_IN_SCREEN + val dragging = DragWindowFlags.flags(rest, dragging = true, focusableAtRest = true) + assertEquals(rest or FLAG_NOT_TOUCHABLE or FLAG_NOT_FOCUSABLE, dragging) + assertEquals(rest, DragWindowFlags.flags(dragging, dragging = false, focusableAtRest = true)) + } + + @Test + fun theBallStaysUnfocusableAfterADrag() { + val rest = FLAG_NOT_FOCUSABLE or FLAG_LAYOUT_IN_SCREEN + val dragging = DragWindowFlags.flags(rest, dragging = true, focusableAtRest = false) + assertEquals(rest or FLAG_NOT_TOUCHABLE, dragging) + assertEquals(rest, DragWindowFlags.flags(dragging, dragging = false, focusableAtRest = false)) + // Idempotent either way. + assertEquals(dragging, DragWindowFlags.flags(dragging, dragging = true, focusableAtRest = false)) + assertEquals(rest, DragWindowFlags.flags(rest, dragging = false, focusableAtRest = false)) + } + + // endregion +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogicTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogicTest.kt new file mode 100644 index 00000000..4b114e90 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleLogicTest.kt @@ -0,0 +1,363 @@ +package com.xiangming.wechatbridge.bubble + +import com.xiangming.wechatbridge.core.inbox.BatchOutcome +import com.xiangming.wechatbridge.core.inbox.ReadyBatch +import com.xiangming.wechatbridge.core.inbox.ShareAction +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.receive.ReceiptUiState +import com.xiangming.wechatbridge.receive.ReceiveFailure +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File +import java.time.Instant +import java.util.UUID + +class BubbleLogicTest { + private val base = Instant.parse("2026-11-25T08:00:00Z") + + private fun entry(minutes: Long, outcome: BatchOutcome.Kind? = null, collecting: Boolean = false): RelayEntry { + val created = base.plusSeconds(minutes * 60) + val batch = ReadyBatch( + id = UUID.randomUUID(), + directory = File("."), + createdAt = created, + action = ShareAction.CLAUDE, + items = emptyList(), + outcome = outcome?.let { BatchOutcome(it, at = created) }, + isFirstSeen = false, + ) + return RelayEntry(batch, null, collecting) + } + + // region Geometry + + @Test + fun releaseSnapsToTheNearerEdge() { + assertEquals(BubbleEdge.LEFT, BubbleGeometry.edgeFor(centerX = 100, screenWidth = 1080)) + assertEquals(BubbleEdge.LEFT, BubbleGeometry.edgeFor(centerX = 539, screenWidth = 1080)) + assertEquals(BubbleEdge.RIGHT, BubbleGeometry.edgeFor(centerX = 540, screenWidth = 1080)) + assertEquals(BubbleEdge.RIGHT, BubbleGeometry.edgeFor(centerX = 1000, screenWidth = 1080)) + } + + @Test + fun edgeXKeepsTheWindowOnScreen() { + assertEquals(0, BubbleGeometry.xFor(BubbleEdge.LEFT, 1080, 150)) + assertEquals(930, BubbleGeometry.xFor(BubbleEdge.RIGHT, 1080, 150)) + assertEquals(0, BubbleGeometry.xFor(BubbleEdge.RIGHT, 100, 150)) + assertEquals(0, BubbleGeometry.clampX(-40, 1080, 150)) + assertEquals(930, BubbleGeometry.clampX(2000, 1080, 150)) + assertEquals(300, BubbleGeometry.clampX(300, 1080, 150)) + } + + @Test + fun yRangeStaysClearOfTheBars() { + assertEquals(80..1950, BubbleGeometry.yRange(screenHeight = 2400, windowSize = 150, topInset = 80, bottomInset = 300)) + // A screen too short collapses to the top, never inverts. + assertEquals(80..80, BubbleGeometry.yRange(screenHeight = 200, windowSize = 150, topInset = 80, bottomInset = 300)) + } + + @Test + fun fractionRoundTripsAndClamps() { + val range = 100..1100 + assertEquals(100, BubbleGeometry.yFor(0f, range)) + assertEquals(600, BubbleGeometry.yFor(0.5f, range)) + assertEquals(1100, BubbleGeometry.yFor(1f, range)) + assertEquals(1100, BubbleGeometry.yFor(3f, range)) + assertEquals(100, BubbleGeometry.yFor(-1f, range)) + assertEquals(BubbleGeometry.yFor(BubblePlacement.DEFAULT.yFraction, range), BubbleGeometry.yFor(Float.NaN, range)) + assertEquals(0.25f, BubbleGeometry.fractionFor(350, range), 0.0001f) + assertEquals(0f, BubbleGeometry.fractionFor(0, range), 0.0001f) + assertEquals(1f, BubbleGeometry.fractionFor(5000, range), 0.0001f) + assertEquals(0.5f, BubbleGeometry.fractionFor(80, 80..80), 0.0001f) + } + + @Test + fun snapRemembersEdgeAndHeightShare() { + val placement = BubbleGeometry.snap(x = 20, y = 600, screenWidth = 1080, windowSize = 150, range = 100..1100) + assertEquals(BubbleEdge.LEFT, placement.edge) + assertEquals(0.5f, placement.yFraction, 0.0001f) + val right = BubbleGeometry.snap(x = 600, y = 100, screenWidth = 1080, windowSize = 150, range = 100..1100) + assertEquals(BubblePlacement(BubbleEdge.RIGHT, 0f), right) + } + + @Test + fun aMoveWithinTheSlopIsATap() { + assertFalse(BubbleGeometry.isDrag(3f, 4f, slop = 5)) + assertTrue(BubbleGeometry.isDrag(3f, 4.1f, slop = 5)) + assertTrue(BubbleGeometry.isDrag(-30f, 0f, slop = 5)) + } + + @Test + fun edgeGestureClassifiesTapInwardSwipeAndReposition() { + val slop = 10 + val swipe = 70f + val cross = 340f + // Within slop -> TAP + assertEquals( + BubbleGeometry.EdgeGesture.TAP, + BubbleGeometry.classifyRelease(BubbleEdge.RIGHT, dx = -4f, dy = 3f, slop = slop, swipeThreshold = swipe, crossThreshold = cross), + ) + // Right edge inward pull (leftward) -> OPEN_PANEL + assertEquals( + BubbleGeometry.EdgeGesture.OPEN_PANEL, + BubbleGeometry.classifyRelease(BubbleEdge.RIGHT, dx = -120f, dy = 12f, slop = slop, swipeThreshold = swipe, crossThreshold = cross), + ) + // Left edge inward pull (rightward) -> OPEN_PANEL + assertEquals( + BubbleGeometry.EdgeGesture.OPEN_PANEL, + BubbleGeometry.classifyRelease(BubbleEdge.LEFT, dx = 110f, dy = -10f, slop = slop, swipeThreshold = swipe, crossThreshold = cross), + ) + // Vertical drag along edge -> REPOSITION + assertEquals( + BubbleGeometry.EdgeGesture.REPOSITION, + BubbleGeometry.classifyRelease(BubbleEdge.RIGHT, dx = -20f, dy = 180f, slop = slop, swipeThreshold = swipe, crossThreshold = cross), + ) + // Cross-midline drag to opposite edge -> REPOSITION + assertEquals( + BubbleGeometry.EdgeGesture.REPOSITION, + BubbleGeometry.classifyRelease(BubbleEdge.RIGHT, dx = -420f, dy = 10f, slop = slop, swipeThreshold = swipe, crossThreshold = cross), + ) + // Outward pull -> REPOSITION (never opens panel) + assertEquals( + BubbleGeometry.EdgeGesture.REPOSITION, + BubbleGeometry.classifyRelease(BubbleEdge.RIGHT, dx = 90f, dy = 0f, slop = slop, swipeThreshold = swipe, crossThreshold = cross), + ) + } + + // endregion + + // region Staging + + @Test + fun stagedIsUndeliveredNewestFirst() { + val old = entry(1) + val delivered = entry(2, BatchOutcome.Kind.DELIVERED) + val failed = entry(3, BatchOutcome.Kind.FAILED) + val newest = entry(4, collecting = true) + val copied = entry(0, BatchOutcome.Kind.COPIED) + val staged = BubbleStaging.staged(listOf(old, delivered, failed, newest, copied)) + // Same rule as the relay's 「未投递」 filter: everything but delivered. + assertEquals(listOf(newest.id, failed.id, old.id, copied.id), staged.map { it.id }) + } + + @Test + fun mergeAllIsOldestFirstInUppercase() { + val a = entry(5) + val b = entry(1) + val c = entry(3) + val ids = BubbleStaging.mergeIds(BubbleStaging.staged(listOf(a, b, c))) + assertEquals(listOf(b, c, a).map { it.id.toString().uppercase() }, ids) + assertEquals(emptyList(), BubbleStaging.mergeIds(emptyList())) + } + + @Test + fun badgeHidesZeroAndCapsAt99() { + assertNull(BubbleStaging.badge(0)) + assertNull(BubbleStaging.badge(-1)) + assertEquals("1", BubbleStaging.badge(1)) + assertEquals("99", BubbleStaging.badge(99)) + assertEquals("99+", BubbleStaging.badge(100)) + } + + @Test + fun pulseOnlyForBatchesThatArriveAfterStart() { + val since = base.plusSeconds(10 * 60) + val existing = entry(1) + val fresh = entry(11) + // Loading the list that was already there: no bounce. + assertFalse(BubbleStaging.shouldPulse(emptySet(), listOf(existing), since)) + // A new batch: bounce. + assertTrue(BubbleStaging.shouldPulse(setOf(existing.id), listOf(fresh, existing), since)) + // Same list again (a summary filled in): no bounce. + assertFalse(BubbleStaging.shouldPulse(setOf(existing.id, fresh.id), listOf(fresh, existing), since)) + // A batch leaving (delivered / deleted): no bounce. + assertFalse(BubbleStaging.shouldPulse(setOf(existing.id, fresh.id), listOf(existing), since)) + } + + // endregion + + // region Decisions + + @Test + fun silentOnlyWithSwitchAndPermission() { + assertEquals(SilentReceive.Mode.SILENT, SilentReceive.mode(bubbleEnabled = true, canDrawOverlays = true)) + assertEquals(SilentReceive.Mode.RECEIPT, SilentReceive.mode(bubbleEnabled = true, canDrawOverlays = false)) + assertEquals(SilentReceive.Mode.RECEIPT, SilentReceive.mode(bubbleEnabled = false, canDrawOverlays = true)) + assertEquals(SilentReceive.Mode.RECEIPT, SilentReceive.mode(bubbleEnabled = false, canDrawOverlays = false)) + assertTrue(BubbleGate.shouldRun(true, true)) + assertFalse(BubbleGate.shouldRun(true, false)) + } + + @Test + fun handleVisibilityRespectsAutoHideZeroOverlayAndPanelState() { + // Auto-hide ON: hidden at 0, visible at >= 1 + assertFalse( + BubbleVisibility.shouldShowHandle( + enabled = true, + canDrawOverlays = true, + stagedCount = 0, + autoHideWhenEmpty = true, + zeroOverlayMode = false, + ), + ) + assertTrue( + BubbleVisibility.shouldShowHandle( + enabled = true, + canDrawOverlays = true, + stagedCount = 1, + autoHideWhenEmpty = true, + zeroOverlayMode = false, + ), + ) + // Auto-hide OFF: visible even at 0 + assertTrue( + BubbleVisibility.shouldShowHandle( + enabled = true, + canDrawOverlays = true, + stagedCount = 0, + autoHideWhenEmpty = false, + zeroOverlayMode = false, + ), + ) + // Zero-overlay mode: always hidden regardless of stagedCount or autoHideWhenEmpty + assertFalse( + BubbleVisibility.shouldShowHandle( + enabled = true, + canDrawOverlays = true, + stagedCount = 5, + autoHideWhenEmpty = false, + zeroOverlayMode = true, + ), + ) + // Panel open: handle hides while panel is shown + assertFalse( + BubbleVisibility.shouldShowHandle( + enabled = true, + canDrawOverlays = true, + stagedCount = 3, + autoHideWhenEmpty = true, + zeroOverlayMode = false, + panelOpen = true, + ), + ) + // Disabled or permission missing: always hidden + assertFalse( + BubbleVisibility.shouldShowHandle( + enabled = false, + canDrawOverlays = true, + stagedCount = 3, + autoHideWhenEmpty = false, + zeroOverlayMode = false, + ), + ) + assertFalse( + BubbleVisibility.shouldShowHandle( + enabled = true, + canDrawOverlays = false, + stagedCount = 3, + autoHideWhenEmpty = false, + zeroOverlayMode = false, + ), + ) + } + + @Test + fun onDemandServiceStaysAliveDuringPanelAndAsyncFill() { + // Closed panel, no fill running, main switch off -> safe to stop + assertTrue( + BubbleVisibility.shouldStopOnDemand( + onDemandOnly = true, + enabled = false, + panelOpen = false, + fillInProgress = false, + ), + ) + // Async fill in progress -> MUST stay alive so scope is not cancelled + assertFalse( + BubbleVisibility.shouldStopOnDemand( + onDemandOnly = true, + enabled = false, + panelOpen = false, + fillInProgress = true, + ), + ) + // Panel open (e.g. reopened on NO_TARGET) -> stay alive + assertFalse( + BubbleVisibility.shouldStopOnDemand( + onDemandOnly = true, + enabled = false, + panelOpen = true, + fillInProgress = false, + ), + ) + // Main switch enabled -> never stop on demand + assertFalse( + BubbleVisibility.shouldStopOnDemand( + onDemandOnly = true, + enabled = true, + panelOpen = false, + fillInProgress = false, + ), + ) + assertFalse( + BubbleVisibility.shouldStopOnDemand( + onDemandOnly = false, + enabled = false, + panelOpen = false, + fillInProgress = false, + ), + ) + } + + @Test + fun silentStepsFollowTheReceipt() { + assertEquals(SilentReceive.Step.WAIT, SilentReceive.step(null)) + assertEquals(SilentReceive.Step.WAIT, SilentReceive.step(ReceiptUiState.Importing(collect = true))) + val saved = ReceiptUiState.Saved( + batchId = UUID.randomUUID(), + collect = false, + itemNames = listOf("a.txt"), + byteCount = 1, + messageCount = null, + attachmentCount = null, + isWeChatFormat = false, + hasNonWeChatArchive = false, + first = null, + last = null, + ) + assertEquals(SilentReceive.Step.FINISH, SilentReceive.step(saved)) + assertEquals(SilentReceive.Step.FINISH, SilentReceive.step(saved.copy(collect = true, collectedBatchNumber = 3))) + assertEquals(SilentReceive.Step.FAIL, SilentReceive.step(ReceiptUiState.NotSaved(ReceiveFailure.EmptyShare, collect = false))) + } + + @Test + fun switchAsksForPermissionOnlyWhenMissing() { + assertEquals(BubbleToggle.Action.ENABLE, BubbleToggle.onSwitch(turnOn = true, canDrawOverlays = true)) + assertEquals(BubbleToggle.Action.REQUEST_PERMISSION, BubbleToggle.onSwitch(turnOn = true, canDrawOverlays = false)) + assertEquals(BubbleToggle.Action.DISABLE, BubbleToggle.onSwitch(turnOn = false, canDrawOverlays = true)) + assertEquals(BubbleToggle.Action.DISABLE, BubbleToggle.onSwitch(turnOn = false, canDrawOverlays = false)) + } + + @Test + fun returningFromThePermissionPage() { + assertEquals(BubbleToggle.Action.ENABLE, BubbleToggle.onReturn(awaitingPermission = true, canDrawOverlays = true)) + assertNull(BubbleToggle.onReturn(awaitingPermission = true, canDrawOverlays = false)) + // Not waiting: an ordinary resume never turns the bubble on. + assertNull(BubbleToggle.onReturn(awaitingPermission = false, canDrawOverlays = true)) + } + + @Test + fun xiaomiFamilyIsRecognised() { + assertTrue(BubbleToggle.isXiaomi("Xiaomi")) + assertTrue(BubbleToggle.isXiaomi("XIAOMI", "Redmi")) + assertTrue(BubbleToggle.isXiaomi("unknown", "redmi")) + assertTrue(BubbleToggle.isXiaomi("POCO")) + assertFalse(BubbleToggle.isXiaomi("samsung", "samsung")) + assertFalse(BubbleToggle.isXiaomi(null, null)) + } + + // endregion +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleMediaTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleMediaTest.kt new file mode 100644 index 00000000..bc9a1248 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleMediaTest.kt @@ -0,0 +1,202 @@ +package com.xiangming.wechatbridge.bubble + +import android.content.ClipDescription +import android.net.Uri +import com.xiangming.wechatbridge.core.archive.WeChatArchive +import com.xiangming.wechatbridge.core.inbox.ReadyBatch +import com.xiangming.wechatbridge.core.inbox.ReadyItem +import com.xiangming.wechatbridge.core.inbox.ShareAction +import com.xiangming.wechatbridge.core.summary.RelayFiles +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.data.RelayEntry +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File +import java.time.Instant +import java.util.UUID + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class BubbleMediaTest { + @get:Rule + val temp = TemporaryFolder() + + private fun fixture(name: String): File { + var dir: File? = File("").absoluteFile + while (dir != null) { + val candidate = File(dir, "ios/Tests/Fixtures/$name") + if (candidate.isFile) return candidate + dir = dir.parentFile + } + error("fixture $name not found") + } + + /** Inbox-style item: the file on disk is `items//file`, the name lives in displayName. */ + private fun item(batchId: UUID, displayName: String, content: ByteArray = displayName.toByteArray(), type: String? = null, source: File? = null): ReadyItem { + val id = UUID.randomUUID() + val file = File(temp.root, "items/$id/file").apply { parentFile!!.mkdirs() } + if (source != null) source.copyTo(file) else file.writeBytes(content) + return ReadyItem(id, batchId, displayName, file, file.length(), type, Instant.EPOCH, ShareAction.CLAUDE) + } + + private fun entry(kind: RelaySummary.Kind?, archiveItem: Boolean = false, items: (UUID) -> List): RelayEntry { + val id = UUID.randomUUID() + val list = items(id) + val batch = ReadyBatch(id, temp.root, Instant.EPOCH, ShareAction.CLAUDE, list, outcome = null, isFirstSeen = false) + val summary = kind?.let { RelaySummary(title = "t", kind = it, archiveItemId = if (archiveItem) list.first().id else null) } + return RelayEntry(batch, summary, isCollecting = false) + } + + private val extractor: (File, UUID) -> RelayFiles.Extracted = { file, id -> + val dir = File(temp.root, "relay/$id").apply { mkdirs() } + RelayFiles.Extracted(dir, WeChatArchive.extract(file, dir)) + } + + // region Names and MIME + + @Test + fun imageNameUsesDisplayNameAndKeepsExtension() { + assertEquals("截图.png", BubbleMedia.imageName("截图.png", "file")) + assertEquals("IMG.JPG", BubbleMedia.imageName("IMG.JPG", "file")) + // No extension on the shown name: take the stored file's. + assertEquals("照片.jpg", BubbleMedia.imageName("照片", "x.jpg")) + assertNull(BubbleMedia.imageName("报告.pdf", "file")) + assertNull(BubbleMedia.imageName("聊天记录.zip", "file")) + assertNull(BubbleMedia.imageName("视频.mp4", "file")) + } + + @Test + fun archiveNameAlwaysEndsInZip() { + assertEquals("群聊_的聊天记录.zip", BubbleMedia.archiveName("群聊_的聊天记录.zip")) + assertEquals("A.ZIP", BubbleMedia.archiveName("A.ZIP")) + assertEquals("聊天记录.zip", BubbleMedia.archiveName("聊天记录")) + assertEquals("聊天记录.zip", BubbleMedia.archiveName("")) + } + + @Test + fun selectCapsAtNine() { + val files = (1..12).map { DragFile(File("$it.png"), "$it.png", "image/png") } + val selection = BubbleMedia.select(files) + assertEquals(9, selection.files.size) + assertEquals(12, selection.total) + assertTrue(selection.truncated) + assertEquals("1.png", selection.files.first().name) + assertFalse(BubbleMedia.select(files.take(9)).truncated) + assertTrue(BubbleMedia.select(emptyList()).files.isEmpty()) + } + + // endregion + + // region Scanning batches + + @Test + fun looseFilesKeepOnlyImagesWithMime() { + val e = entry(RelaySummary.Kind.FILES) { id -> + listOf( + item(id, "a.jpg"), + item(id, "b.PNG"), + item(id, "c.pdf"), + item(id, "d.zip", source = fixture("files-only.zip")), + item(id, "e.webp"), + item(id, "link.txt", type = ShareOrigin.NOTE_CONTENT_TYPE), + ) + } + val media = BubbleMedia.scan(e, extractor) + assertEquals(listOf("a.jpg", "b.PNG", "e.webp"), media.images.map { it.name }) + assertEquals(listOf("image/jpeg", "image/png", "image/webp"), media.images.map { it.mimeType }) + // A ZIP in a files batch is an attachment, not a chat export. + assertNull(media.archive) + } + + @Test + fun chatZipImagesAreUnpackedAndArchiveOffered() { + val e = entry(RelaySummary.Kind.CHAT, archiveItem = true) { id -> + listOf(item(id, "群聊_的聊天记录.zip", source = fixture("group-a.zip"), type = "application/zip")) + } + val media = BubbleMedia.scan(e, extractor) + // group-a.zip holds a png, an mp4 and a pdf: only the png counts. + assertEquals(1, media.images.size) + assertTrue(media.images[0].name.endsWith(".png")) + assertEquals("image/png", media.images[0].mimeType) + assertTrue(media.images[0].file.isFile) + val archive = media.archive!! + assertEquals("群聊_的聊天记录.zip", archive.name) + assertEquals(BubbleMedia.ZIP_MIME, archive.mimeType) + assertEquals(e.batch.items[0].file, archive.file) + } + + @Test + fun chatWithoutSummaryArchiveIdFindsTheZip() { + val e = entry(RelaySummary.Kind.CHAT) { id -> listOf(item(id, "记录.zip", source = fixture("group-a.zip"))) } + assertEquals("记录.zip", BubbleMedia.chatArchive(e)!!.displayName) + assertNull(BubbleMedia.chatArchive(entry(null) { id -> listOf(item(id, "记录.zip", source = fixture("group-a.zip"))) })) + } + + @Test + fun brokenArchiveGivesNoImages() { + val e = entry(RelaySummary.Kind.CHAT, archiveItem = true) { id -> listOf(item(id, "坏.zip", content = byteArrayOf(1, 2, 3))) } + assertTrue(BubbleMedia.scan(e, extractor).images.isEmpty()) + } + + @Test + fun stageCopiesWithUniqueNames() { + val src = temp.newFolder("src") + val a = File(src, "1").apply { writeText("a") } + val b = File(src, "2").apply { writeText("b") } + val out = File(temp.root, "deliveries/bubble-drag-x") + val staged = BubbleMedia.stage(listOf(DragFile(a, "图.png", "image/png"), DragFile(b, "图.png", "image/png")), out) + assertEquals(listOf("图.png", "图 (2).png"), staged.map { it.name }) + assertTrue(staged.all { it.file.parentFile == out && it.file.isFile }) + assertEquals("b", staged[1].file.readText()) + // Originals untouched. + assertTrue(a.isFile && b.isFile) + } + + // endregion + + // region ClipData + + @Test + fun clipPlanCountsItemsAndDistinctTypes() { + assertEquals(ClipPlan(listOf("image/jpeg", "image/png"), 3), DragClip.plan(listOf("image/jpeg", "image/png", "image/jpeg"))) + assertEquals(ClipPlan(listOf("application/zip"), 1), DragClip.plan(listOf("application/zip"))) + assertEquals(ClipPlan(emptyList(), 0), DragClip.plan(emptyList())) + } + + @Test + fun clipHoldsOneUriItemEachAndNoText() { + val uris = listOf( + Uri.parse("content://x.share/deliveries/a.jpg") to "image/jpeg", + Uri.parse("content://x.share/deliveries/b.png") to "image/png", + Uri.parse("content://x.share/deliveries/c.jpg") to "image/jpeg", + ) + val clip = DragClip.build("WeChatBridge", uris)!! + assertEquals(3, clip.itemCount) + assertEquals(uris.map { it.first }, (0 until clip.itemCount).map { clip.getItemAt(it).uri }) + assertTrue((0 until clip.itemCount).all { clip.getItemAt(it).text == null }) + val description: ClipDescription = clip.description + assertArrayEquals(arrayOf("image/jpeg", "image/png"), (0 until description.mimeTypeCount).map { description.getMimeType(it) }.toTypedArray()) + assertFalse(description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) + assertNull(DragClip.build("WeChatBridge", emptyList())) + } + + @Test + fun archiveClipIsASingleZipItem() { + val clip = DragClip.build("WeChatBridge", listOf(Uri.parse("content://x.share/deliveries/a.zip") to BubbleMedia.ZIP_MIME))!! + assertEquals(1, clip.itemCount) + assertEquals(1, clip.description.mimeTypeCount) + assertEquals(BubbleMedia.ZIP_MIME, clip.description.getMimeType(0)) + } + + // endregion +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleSettingsTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleSettingsTest.kt new file mode 100644 index 00000000..8a3b29f0 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/bubble/BubbleSettingsTest.kt @@ -0,0 +1,133 @@ +package com.xiangming.wechatbridge.bubble + +import android.app.Application +import android.content.Context +import android.content.Intent +import android.provider.Settings +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.App +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowSettings + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class BubbleSettingsTest { + private lateinit var app: Application + + @Before + fun setUp() { + app = ApplicationProvider.getApplicationContext() + app.getSharedPreferences(BubbleSettings.FILE_NAME, Context.MODE_PRIVATE).edit().clear().commit() + ShadowSettings.setCanDrawOverlays(false) + } + + @Test + fun offByDefaultWithTheDefaultPlacement() { + val settings = BubbleSettings(app) + assertFalse(settings.isEnabled) + assertFalse(settings.enabled.value) + assertTrue(settings.isAutoHideWhenEmpty) + assertTrue(settings.autoHideWhenEmpty.value) + assertFalse(settings.isZeroOverlayMode) + assertFalse(settings.zeroOverlayMode.value) + assertEquals(BubblePlacement.DEFAULT, settings.placement) + } + + @Test + fun autoHideAndZeroOverlayPersistAcrossInstances() { + val settings = BubbleSettings(app) + settings.setAutoHideWhenEmpty(false) + settings.setZeroOverlayMode(true) + assertFalse(settings.autoHideWhenEmpty.value) + assertTrue(settings.zeroOverlayMode.value) + + val reread = BubbleSettings(app) + assertFalse(reread.isAutoHideWhenEmpty) + assertTrue(reread.isZeroOverlayMode) + } + + @Test + fun switchAndPlacementPersistAcrossInstances() { + val settings = BubbleSettings(app) + settings.setEnabled(true) + settings.placement = BubblePlacement(BubbleEdge.LEFT, 0.25f) + assertTrue(settings.enabled.value) + + val reread = BubbleSettings(app) + assertTrue(reread.isEnabled) + assertEquals(BubblePlacement(BubbleEdge.LEFT, 0.25f), reread.placement) + + reread.setEnabled(false) + assertFalse(BubbleSettings(app).isEnabled) + } + + @Test + fun outOfRangeStoredValuesReadSafely() { + app.getSharedPreferences(BubbleSettings.FILE_NAME, Context.MODE_PRIVATE).edit() + .putString(BubbleSettings.KEY_EDGE, "middle") + .putFloat(BubbleSettings.KEY_Y, 7f) + .commit() + val placement = BubbleSettings(app).placement + assertEquals(BubblePlacement.DEFAULT.edge, placement.edge) + assertEquals(1f, placement.yFraction, 0.0001f) + } + + @Test + fun permissionPageTargetsThisPackage() { + val intent = OverlayPermission.settingsIntent(app) + assertEquals(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, intent.action) + assertEquals("package:" + app.packageName, intent.dataString) + } + + @Test + fun overlayPermissionFeedsTheDecision() { + assertFalse(OverlayPermission.canDraw(app)) + assertEquals(BubbleToggle.Action.REQUEST_PERMISSION, BubbleToggle.onSwitch(true, OverlayPermission.canDraw(app))) + ShadowSettings.setCanDrawOverlays(true) + assertTrue(OverlayPermission.canDraw(app)) + assertEquals(BubbleToggle.Action.ENABLE, BubbleToggle.onSwitch(true, OverlayPermission.canDraw(app))) + } + + @Test + fun syncStartsTheServiceOnlyWhenOnAndPermitted() { + val settings = (app as App).container.bubbleSettings + val shadow = shadowOf(app) + while (shadow.nextStartedService != null) Unit + + settings.setEnabled(true) + assertFalse(BubbleService.sync(app)) + assertEquals(null, shadow.nextStartedService) + + ShadowSettings.setCanDrawOverlays(true) + assertTrue(BubbleService.sync(app)) + val started: Intent? = shadow.nextStartedService + assertEquals(BubbleService::class.java.name, started?.component?.className) + + settings.setEnabled(false) + assertFalse(BubbleService.sync(app)) + assertEquals(BubbleService::class.java.name, shadow.nextStoppedService?.component?.className) + } + + @Test + fun openPanelStartsServiceWithActionOnlyWhenPermitted() { + val shadow = shadowOf(app) + while (shadow.nextStartedService != null) Unit + + assertFalse(BubbleService.openPanel(app)) + assertEquals(null, shadow.nextStartedService) + + ShadowSettings.setCanDrawOverlays(true) + assertTrue(BubbleService.openPanel(app)) + val started: Intent? = shadow.nextStartedService + assertEquals(BubbleService::class.java.name, started?.component?.className) + assertEquals(BubbleService.ACTION_OPEN_PANEL, started?.action) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/PreferencesTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/PreferencesTest.kt new file mode 100644 index 00000000..ddd0a680 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/PreferencesTest.kt @@ -0,0 +1,100 @@ +package com.xiangming.wechatbridge.data + +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.AppContainer +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.summary.RelayFiles +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File + +@RunWith(RobolectricTestRunner::class) +class PreferencesTest { + @get:Rule + val temp = TemporaryFolder() + + private fun withPreferences(file: File, block: suspend (Preferences) -> T): T = runBlocking { + val job = Job() + try { + block(Preferences.create(CoroutineScope(Dispatchers.IO + job)) { file }) + } finally { + job.cancel() + job.join() + } + } + + @Test + fun defaultsMatchIos() { + val file = File(temp.root, "p.preferences_pb") + val snapshot = withPreferences(file) { it.current() } + assertEquals(Preferences.Snapshot(), snapshot) + assertEquals(7, snapshot.retentionDays) + assertFalse(snapshot.onboardingDone) + assertNull(snapshot.lastTarget) + } + + @Test + fun everyValueRoundTripsAcrossInstances() { + val file = File(temp.root, "p.preferences_pb") + val first = BuiltInTargets.all[0].id + val second = BuiltInTargets.all[1].id + withPreferences(file) { prefs -> + prefs.setTargetOrder(listOf(second, first)) + prefs.setHidden(first, true) + prefs.setHidden("custom:x", true) + prefs.setHidden("custom:x", false) + prefs.setFormatOverride(second, DeliveryFormat.TRANSCRIPT_ONLY) + prefs.setFormatOverride(first, DeliveryFormat.ARCHIVE) + prefs.setFormatOverride(first, null) + prefs.setLastTarget(second) + prefs.setRetentionDays(30) + prefs.setOnboardingDone(true) + } + + // A fresh DataStore on the same file: what a new process reads. + withPreferences(file) { prefs -> + assertEquals(listOf(second, first), prefs.targetOrder.first()) + assertEquals(setOf(first), prefs.hiddenTargets.first()) + assertEquals(mapOf(second to "transcriptOnly"), prefs.formatOverrides.first()) + assertEquals(second, prefs.lastTarget.first()) + assertEquals(30, prefs.retentionDays.first()) + assertTrue(prefs.onboardingDone.first()) + + val targets = prefs.targets().first() + assertEquals(second, targets.first().id) + assertTrue(targets.none { it.id == first }) + assertEquals(DeliveryFormat.TRANSCRIPT_ONLY, targets.first().formats.first()) + + prefs.setLastTarget(null) + prefs.setRetentionDays(-3) + assertNull(prefs.lastTarget.first()) + assertEquals(0, prefs.retentionDays.first()) + } + } + + @Test + fun containerWiresTheDataLayer() { + val context = ApplicationProvider.getApplicationContext() + val container = AppContainer(context) + assertEquals(File(context.filesDir, "inbox"), container.relayStore.inbox.root) + assertEquals(container.inbox, container.relayStore.inbox) + assertEquals(File(context.cacheDir, "Relay"), RelayFiles.root) + runBlocking { + container.preferences.setRetentionDays(3) + assertEquals(3, container.preferences.retentionDays.first()) + } + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/RelayStoreCollectionTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/RelayStoreCollectionTest.kt new file mode 100644 index 00000000..5582a1de --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/RelayStoreCollectionTest.kt @@ -0,0 +1,146 @@ +package com.xiangming.wechatbridge.data + +import com.xiangming.wechatbridge.core.collection.BatchCollection +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ShareItem +import com.xiangming.wechatbridge.receive.UriImporter +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import java.util.UUID + +/** Receipt 「加入收集」 and the 「分批收集」 entry's 「已收第 N 批」 (iOS `addToCollection`, `CollectMarker.batchNumber`). */ +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class RelayStoreCollectionTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var inbox: Inbox + private lateinit var importer: UriImporter + private val clock: Clock = Clock.fixed(Instant.now(), ZoneOffset.UTC) + + @Before + fun setUp() { + inbox = Inbox(File(temp.root, "files/inbox")) + importer = UriImporter(inbox, buildVersion = "1") + } + + private fun TestScope.store(): RelayStore = RelayStore( + inbox = inbox, + relayFilesRoot = File(temp.root, "cache/Relay"), + deliveriesDirectory = File(temp.root, "cache/deliveries"), + scope = this, + ioDispatcher = StandardTestDispatcher(testScheduler), + clock = clock, + ) + + private fun save(text: String, collect: Boolean = false): UUID = + (importer.importBlocking(listOf(ShareItem.Text(text)), collect) as ImportOutcome.Saved).batchId + + @Test + fun firstAddStartsACollectionAndLaterAddsContinueIt() = runTest { + val a = save("一") + val b = save("二") + val store = store() + store.reload() + assertNull(store.currentCollection) + assertNull(store.collectedBatchNumber(a)) + + assertEquals(1, store.collect(a)) + val opened = store.currentCollection!! + assertEquals(listOf(a), opened.batchIDs) + + assertEquals(2, store.collect(b)) + assertEquals(opened.id, store.currentCollection!!.id) + assertEquals(listOf(a, b), store.currentCollection!!.batchIDs) + assertEquals(2, store.collectedBatchNumber(a)) + advanceUntilIdle() + } + + @Test + fun addingTheSameBatchTwiceKeepsItOnce() = runTest { + val a = save("一") + val store = store() + store.reload() + assertEquals(1, store.collect(a)) + assertEquals(1, store.collect(a)) + assertEquals(listOf(a), store.currentCollection!!.batchIDs) + advanceUntilIdle() + } + + @Test + fun afterDeliveryTheNextAddStartsANewCollection() = runTest { + val a = save("一") + val b = save("二") + val store = store() + store.reload() + store.collect(a) + val first = store.currentCollection!!.id + store.beginCollectionDelivery(first) + store.finishCollectionDelivery(first, succeeded = true, target = "ChatGPT", detail = "done", scene = null) + assertNull(store.currentCollection) + // A delivered collection no longer counts. + assertNull(store.collectedBatchNumber(a)) + + assertEquals(1, store.collect(b)) + assertNotEquals(first, store.currentCollection!!.id) + advanceUntilIdle() + } + + @Test + fun aCollectionNoLongerOpenIsNotContinued() = runTest { + val a = save("一") + val b = save("二") + val c = save("三") + val store = store() + store.reload() + store.collect(a) + val first = store.currentCollection!!.id + store.collect(b) // joins first + store.removeFromCollection(b, first) + assertEquals(1, store.collectedBatchNumber(a)) + // Detached once, never collected again (iOS seenBatchIDs). + assertEquals(null, store.collect(b)) + + store.beginCollectionDelivery(first) + store.finishCollectionDelivery(first, succeeded = false, target = "ChatGPT", detail = "failed", scene = null) + // A failed delivery leaves it retryable, not open: the next add starts afresh. + assertEquals(BatchCollection.Status.RETRY, store.ledger.value.collections.single().status) + assertEquals(1, store.collect(c)) + assertEquals(2, store.ledger.value.collections.size) + assertEquals(listOf(c), store.currentCollection!!.batchIDs) + advanceUntilIdle() + } + + @Test + fun collectEntryBatchesAreAdoptedAndNumbered() = runTest { + val store = store() + store.reload() + val first = save("一", collect = true) + assertEquals(1, store.adoptCollected(first)) + val second = save("二", collect = true) + assertEquals(2, store.adoptCollected(second)) + assertEquals(listOf(first, second), store.currentCollection!!.batchIDs) + // A receipt 「加入收集」 continues the same collection. + val plain = save("三") + assertEquals(3, store.collect(plain)) + advanceUntilIdle() + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/RelayStoreTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/RelayStoreTest.kt new file mode 100644 index 00000000..b4600443 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/RelayStoreTest.kt @@ -0,0 +1,361 @@ +package com.xiangming.wechatbridge.data + +import com.xiangming.wechatbridge.core.inbox.BatchManifest +import com.xiangming.wechatbridge.core.inbox.BatchStaging +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import com.xiangming.wechatbridge.core.inbox.ManifestItem +import com.xiangming.wechatbridge.core.inbox.ShareAction +import com.xiangming.wechatbridge.core.summary.RelayFiles +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.receive.CollectMarker +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ShareItem +import com.xiangming.wechatbridge.receive.UriImporter +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +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.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.ByteArrayInputStream +import java.io.File +import java.io.InputStream +import java.time.Clock +import java.time.Duration +import java.time.Instant +import java.time.ZoneId +import java.time.ZoneOffset +import java.util.UUID + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class RelayStoreTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var inbox: Inbox + private lateinit var relayRoot: File + private lateinit var deliveries: File + private val now: Instant = Instant.now() + private val clock: Clock = Clock.fixed(now, ZoneOffset.UTC) + + @Before + fun setUp() { + inbox = Inbox(File(temp.root, "files/inbox")) + relayRoot = File(temp.root, "cache/Relay") + deliveries = File(temp.root, "cache/deliveries") + } + + private fun TestScope.store(): RelayStore = RelayStore( + inbox = inbox, + relayFilesRoot = relayRoot, + deliveriesDirectory = deliveries, + // The test scope itself, so advanceUntilIdle drains the store's launches (it skips backgroundScope). + scope = this, + ioDispatcher = StandardTestDispatcher(testScheduler), + clock = clock, + ) + + // MARK: loading + + @Test + fun twoImportsGiveTwoEntriesWithSummaries() = runTest { + val importer = UriImporter(inbox, buildVersion = "1", zone = ZoneId.of("Asia/Shanghai")) + val chat = importer.importBlocking(listOf(ZipStream(fixture("group-a.zip"))), collect = false) as ImportOutcome.Saved + importer.importBlocking(listOf(ShareItem.Text("第一行标题\n第二行")), collect = false) as ImportOutcome.Saved + + val store = store() + store.refresh() + advanceUntilIdle() + + val entries = store.entries.value + assertEquals(2, entries.size) + assertTrue(entries.all { it.summary != null }) + assertTrue(entries.all { it.delivery == DeliveryStatus.PENDING && !it.isCollecting }) + val chatEntry = store.entry(chat.batchId)!! + assertEquals(RelaySummary.Kind.CHAT, chatEntry.summary!!.kind) + assertEquals(chat.records.size, chatEntry.summary!!.messageCount) + // Cached beside the batch, as on iOS; the archive was unpacked under cacheDir/Relay. + assertTrue(File(chatEntry.batch.directory, RelaySummary.CACHE_FILE_NAME).isFile) + assertEquals(relayRoot, RelayFiles.root) + assertTrue(RelayFiles.directory(chat.batchId).isDirectory) + } + + @Test + fun receiverRefreshPicksUpANewBatch() = runTest { + val store = store() + store.refresh() + advanceUntilIdle() + assertEquals(0, store.entries.value.size) + + makeBatch(now) + store.refresh() + advanceUntilIdle() + assertEquals(1, store.entries.value.size) + } + + @Test + fun collectMarkedBatchesJoinTheOpenCollectionOldestFirst() = runTest { + val first = makeBatch(now.minusSeconds(60), collect = true) + val plain = makeBatch(now.minusSeconds(30)) + val store = store() + store.reload() + + assertEquals(listOf(first), store.ledger.value.current!!.batchIDs) + assertTrue(store.entry(first)!!.isCollecting) + assertFalse(store.entry(plain)!!.isCollecting) + assertEquals(1, store.collections.value.size) + } + + // MARK: deleting + + @Test + fun undoRestoresAndTheBatchSurvivesTheWindow() = runTest { + val a = makeBatch(now.minusSeconds(10)) + makeBatch(now) + val store = store() + store.reload() + + store.delete(setOf(a)) + runCurrent() + assertEquals(1, store.entries.value.size) + assertEquals(setOf(a), store.pendingDeletion.value) + + store.undoDeletion() + assertEquals(2, store.entries.value.size) + advanceTimeBy(10_000) + advanceUntilIdle() + assertTrue(batchDirectory(a).isDirectory) + assertEquals(2, store.entries.value.size) + } + + @Test + fun deletionCommitsAfterFiveSeconds() = runTest { + val a = makeBatch(now.minusSeconds(10)) + makeBatch(now) + val store = store() + store.reload() + store.addToCollection(a) + + store.delete(setOf(a)) + advanceTimeBy(4_999) + runCurrent() + assertTrue(batchDirectory(a).isDirectory) + + advanceTimeBy(2) + advanceUntilIdle() + assertFalse(batchDirectory(a).exists()) + assertEquals(1, store.entries.value.size) + assertTrue(store.pendingDeletion.value.isEmpty()) + // Detached from its collection too. + assertTrue(store.ledger.value.collections.none { a in it.batchIDs }) + } + + @Test + fun aSecondDeleteRestartsTheWindowAndCommitsBoth() = runTest { + val a = makeBatch(now.minusSeconds(10)) + val b = makeBatch(now) + val store = store() + store.reload() + + store.delete(setOf(a)) + advanceTimeBy(3_000) + store.delete(setOf(b)) + advanceTimeBy(3_000) + runCurrent() + assertTrue(batchDirectory(a).isDirectory) + advanceUntilIdle() + assertFalse(batchDirectory(a).exists()) + assertFalse(batchDirectory(b).exists()) + } + + // MARK: retention + + @Test + fun pruneRemovesOldHistoryButKeepsCollectingBatchesAndCleansDebris() = runTest { + val old = makeBatch(now.minus(Duration.ofDays(10))) + val oldCollected = makeBatch(now.minus(Duration.ofDays(10))) + val oldMarked = makeBatch(now.minus(Duration.ofDays(10)), collect = true) + val recent = makeBatch(now.minus(Duration.ofDays(1))) + + val store = store() + store.reload() + store.addToCollection(oldCollected) + // Delivered history is what retention ages out; mark all four so only the ledger protects. + store.markDelivered(listOf(old, oldCollected, oldMarked, recent), targetName = "ChatGPT", detail = null) + + val staleStaging = File(inbox.staging, UUID.randomUUID().toString().uppercase()).apply { mkdirs() } + File(staleStaging, "part").apply { writeText("x"); setLastModified(now.minus(Duration.ofHours(2)).toEpochMilli()) } + staleStaging.setLastModified(now.minus(Duration.ofHours(2)).toEpochMilli()) + val orphanCache = File(relayRoot, UUID.randomUUID().toString().uppercase()).apply { mkdirs() } + val oldDelivery = File(deliveries, "old").apply { mkdirs() } + File(oldDelivery, "a.zip").apply { writeText("x"); setLastModified(now.minus(Duration.ofHours(2)).toEpochMilli()) } + oldDelivery.setLastModified(now.minus(Duration.ofHours(2)).toEpochMilli()) + val freshDelivery = File(deliveries, "fresh").apply { mkdirs() } + File(freshDelivery, "a.zip").writeText("x") + + store.pruneHistory(retentionDays = 7) + advanceUntilIdle() + + assertFalse(batchDirectory(old).exists()) + assertTrue(batchDirectory(oldCollected).isDirectory) + assertTrue(batchDirectory(oldMarked).isDirectory) + assertTrue(batchDirectory(recent).isDirectory) + assertEquals(setOf(oldCollected, oldMarked, recent), store.entries.value.map { it.id }.toSet()) + assertFalse(staleStaging.exists()) + assertFalse(orphanCache.exists()) + assertFalse(oldDelivery.exists()) + assertTrue(freshDelivery.exists()) + } + + @Test + fun zeroRetentionKeepsEverything() = runTest { + val old = makeBatch(now.minus(Duration.ofDays(400))) + val store = store() + store.reload() + store.markDelivered(listOf(old), targetName = "Claude", detail = null) + store.pruneHistory(retentionDays = 0) + assertTrue(batchDirectory(old).isDirectory) + } + + @Test + fun startLoadsThenPrunes() = runTest { + val old = makeBatch(now.minus(Duration.ofDays(10)), action = ShareAction.CLIPBOARD) + val store = store() + store.start { 7 } + advanceUntilIdle() + assertFalse(batchDirectory(old).exists()) + assertTrue(store.entries.value.isEmpty()) + } + + // MARK: process death + + @Test + fun stateSurvivesRecreatingTheStore() = runTest { + val delivered = makeBatch(now.minusSeconds(30)) + val collected = makeBatch(now.minusSeconds(20)) + val deleted = makeBatch(now.minusSeconds(10)) + val first = store() + first.reload() + advanceUntilIdle() + first.markDelivered(listOf(delivered), targetName = "Claude", detail = "ok", chatName = "群A", sceneId = "s", sceneName = "场景") + first.addToCollection(collected) + first.delete(setOf(deleted)) + first.commitDeletion() + + // A new process: nothing in memory, only the files. + val second = store() + second.reload() + + val entries = second.entries.value + assertEquals(listOf(collected, delivered), entries.map { it.id }) + assertTrue(entries.all { it.summary != null }) // read from relay-cache.json, not re-parsed + val d = second.entry(delivered)!! + assertEquals(DeliveryStatus.DELIVERED, d.delivery) + assertEquals("Claude", d.batch.targetName) + assertEquals("群A", d.batch.chatName) + assertEquals("场景", d.batch.sceneName) + assertTrue(second.entry(collected)!!.isCollecting) + assertNull(second.entry(deleted)) + } + + @Test + fun uncommittedDeletionIsNotLostSilentlyButNotDoneEither() = runTest { + val a = makeBatch(now) + val first = store() + first.reload() + first.delete(setOf(a)) + runCurrent() + // Killed inside the undo window, before ON_STOP flushed: the batch is still there. + val second = store() + second.reload() + assertNotNull(second.entry(a)) + } + + @Test + fun collectionDeliveryRoundTrip() = runTest { + val a = makeBatch(now.minusSeconds(20)) + val b = makeBatch(now.minusSeconds(10)) + val store = store() + store.reload() + advanceUntilIdle() + store.addToCollection(a) + store.addToCollection(b) + val collection = store.collections.value.single() + assertEquals(listOf(a, b), store.orderedBatchIds(collection)) + assertEquals(b, store.lastBatch(collection)!!.id) + assertEquals(collection.id, store.collectionContaining(a)!!.id) + + assertEquals(listOf(a, b), store.beginCollectionDelivery(collection.id)) + store.finishCollectionDelivery(collection.id, succeeded = true, target = "ChatGPT", detail = "done", scene = null) + assertTrue(store.collections.value.isEmpty()) + assertNull(store.collectionContaining(a)) + assertFalse(store.entry(a)!!.isCollecting) + } + + // MARK: helpers + + private fun batchDirectory(id: UUID) = File(inbox.ready, id.toString().uppercase()) + + private fun makeBatch( + createdAt: Instant, + collect: Boolean = false, + action: ShareAction = ShareAction.COLLECT, + ): UUID { + val staging = BatchStaging.create(inbox) + val itemId = UUID.randomUUID() + val name = "note.txt" + val file = staging.destination(itemId, name) + file.writeText("正文 $createdAt") + if (collect) CollectMarker.mark(staging.directory) + val manifest = BatchManifest( + batchId = staging.batchId, + createdAt = createdAt, + items = listOf( + ManifestItem( + id = itemId, + displayName = name, + relativePath = staging.relativePath(itemId, name), + contentType = "text/plain", + byteCount = file.length(), + itemIndex = 0, + attachmentIndex = 0, + loadStrategy = LoadStrategy.FILE_REPRESENTATION, + ) + ), + action = action, + ) + staging.commit(manifest, diagnostics = null, intent = null, inbox = inbox) + return staging.batchId + } + + private class ZipStream(private val file: File) : ShareItem.Stream { + override val mimeType: String = "application/zip" + override val loadStrategy: LoadStrategy = LoadStrategy.FILE_REPRESENTATION + override fun displayName(): String = "聊天记录.zip" + override fun open(): InputStream = ByteArrayInputStream(file.readBytes()) + } + + private fun fixture(name: String): File { + var dir: File? = File("").absoluteFile + while (dir != null) { + val candidate = File(dir, "ios/Tests/Fixtures/$name") + if (candidate.isFile) return candidate + dir = dir.parentFile + } + error("fixture $name not found above ${File("").absolutePath}") + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/SceneStoreTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/SceneStoreTest.kt new file mode 100644 index 00000000..9e0b32b4 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/data/SceneStoreTest.kt @@ -0,0 +1,68 @@ +package com.xiangming.wechatbridge.data + +import com.xiangming.wechatbridge.core.scene.GroupName +import com.xiangming.wechatbridge.core.scene.SceneSettings +import com.xiangming.wechatbridge.core.scene.WeChatScene +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset + +class SceneStoreTest { + @get:Rule + val temp = TemporaryFolder() + + private val now = Instant.parse("2026-11-25T08:00:00Z") + private fun store() = SceneStore(temp.root, Clock.fixed(now, ZoneOffset.UTC)) + + @Test + fun defaultsWhenNoFiles() { + val snapshot = store().current() + assertEquals(SceneSettings.makeDefault().installOfficialScenes(), snapshot.settings) + assertTrue(snapshot.memories.isEmpty()) + } + + @Test + fun settingsAndMemoriesRoundTripInIosFormat() { + val scene = WeChatScene(name = "周报", instruction = "总结", outputSpec = "", enabled = true) + store().apply { + setSettings(SceneSettings(listOf(scene), defaultSceneID = scene.id)) + rememberGroup(" 产品群 ", scene.id, setOf("alice"), Instant.parse("2026-11-24T10:00:00Z")) + rememberGroup("产品群", scene.id, setOf("bob"), Instant.parse("2026-11-20T10:00:00Z")) + } + val reread = store().current() + assertEquals(scene.id, reread.settings.defaultSceneID) + val memory = reread.memories[GroupName.normalize("产品群")] + assertNotNull(memory) + assertEquals(scene.id, memory!!.lastSceneID) + assertEquals(setOf("alice", "bob"), memory.senders) + // The boundary only moves forward. + assertEquals(Instant.parse("2026-11-24T10:00:00Z"), memory.lastSummaryAt) + + // Swift's default Date coding: seconds since 2001-01-01. + val json = Json.parseToJsonElement(File(temp.root, SceneStore.MEMORIES_FILE).readText()).jsonObject + val stored = json.getValue(GroupName.normalize("产品群")).jsonObject + assertEquals((now.epochSecond - 978_307_200L).toDouble(), stored.getValue("updatedAt").jsonPrimitive.content.toDouble(), 0.001) + } + + @Test + fun bindKeepsSendersAndCorruptFileIsKept() { + store().bind("销售群", listOf("a", "b"), setOf("carol")) + assertEquals(listOf("a", "b"), store().current().memories.values.single().boundSceneIDs) + + File(temp.root, SceneStore.MEMORIES_FILE).writeText("{not json") + val fresh = store() + assertTrue(fresh.current().memories.isEmpty()) + assertNotNull(fresh.lastError.value) + assertTrue(File(temp.root, SceneStore.MEMORIES_FILE + SceneStore.CORRUPT_SUFFIX).isFile) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/DeliverViewModelTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/DeliverViewModelTest.kt new file mode 100644 index 00000000..dbecb8b3 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/DeliverViewModelTest.kt @@ -0,0 +1,697 @@ +package com.xiangming.wechatbridge.deliver + +import android.app.Application +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.Evidence +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import com.xiangming.wechatbridge.core.scene.GroupName +import com.xiangming.wechatbridge.core.scene.SceneMatchSource +import com.xiangming.wechatbridge.core.scene.SceneSettings +import com.xiangming.wechatbridge.core.scene.WeChatScene +import com.xiangming.wechatbridge.data.DeliveryStatus +import com.xiangming.wechatbridge.data.Preferences +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.data.SceneStore +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ShareItem +import com.xiangming.wechatbridge.receive.UriImporter +import com.xiangming.wechatbridge.saf.FakeTreeHost +import com.xiangming.wechatbridge.saf.TreeStatus +import com.xiangming.wechatbridge.saf.TreeStore +import android.net.Uri +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExecutorCoroutineDispatcher +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.asCoroutineDispatcher +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.After +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.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.ByteArrayInputStream +import java.io.File +import java.io.InputStream +import java.time.ZoneId +import java.util.Collections +import java.util.UUID +import java.util.concurrent.Executors + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class DeliverViewModelTest { + @get:Rule + val temp = TemporaryFolder() + + private val zone: ZoneId = ZoneId.of("Asia/Shanghai") + private lateinit var app: Application + private lateinit var main: ExecutorCoroutineDispatcher + private lateinit var job: Job + private lateinit var inbox: Inbox + private lateinit var relay: RelayStore + private lateinit var preferences: Preferences + private lateinit var scenes: SceneStore + private lateinit var deliveries: File + private val viewModels = mutableListOf() + + private val sent: MutableList> = Collections.synchronizedList(mutableListOf()) + private val copied: MutableList = Collections.synchronizedList(mutableListOf()) + private var nextResult: ((DeliveryRequest, TargetProfile) -> DispatchResult)? = null + private val notInstalled = mutableSetOf() + + private val fakeDispatch = Dispatch { _: Context, request, profile -> + sent += request to profile + nextResult?.invoke(request, profile) + ?: DispatchResult.Sent(Route.EXPLICIT, profile.packageName, profile.sendActivity, request.files.size, request.text != null) + } + + @Before + fun setUp() { + app = ApplicationProvider.getApplicationContext() + main = Executors.newSingleThreadExecutor().asCoroutineDispatcher() + Dispatchers.setMain(main) + job = Job() + val scope = CoroutineScope(Dispatchers.IO + job) + inbox = Inbox(File(temp.root, "files/inbox")) + deliveries = File(temp.root, "cache/deliveries") + relay = RelayStore(inbox, File(temp.root, "cache/Relay"), deliveries, scope) + preferences = Preferences.create(scope) { File(temp.root, "files/prefs.preferences_pb") } + scenes = SceneStore(File(temp.root, "files")) + } + + @After + fun tearDown() { + // Clear the view models on main, as the framework would. + runBlocking(main) { viewModels.forEach { clear(it) } } + runBlocking { job.cancel(); job.join() } + Dispatchers.resetMain() + main.close() + } + + // region Helpers + + private class ZipStream(private val file: File, private val name: String = "聊天记录.zip") : ShareItem.Stream { + override val mimeType: String = "application/zip" + override val loadStrategy: LoadStrategy = LoadStrategy.FILE_REPRESENTATION + override fun displayName(): String = name + override fun open(): InputStream = ByteArrayInputStream(file.readBytes()) + } + + private fun fixture(name: String): File { + var dir: File? = File("").absoluteFile + while (dir != null) { + val candidate = File(dir, "ios/Tests/Fixtures/$name") + if (candidate.isFile) return candidate + dir = dir.parentFile + } + error("fixture $name not found above ${File("").absolutePath}") + } + + /** Imports each fixture as its own batch and waits for the relay to summarize them. */ + private fun batches(vararg names: String): List { + val importer = UriImporter(inbox, buildVersion = "1", zone = zone) + val ids = names.map { name -> + (importer.importBlocking(listOf(ZipStream(fixture(name))), collect = false) as ImportOutcome.Saved).batchId + } + runBlocking { + relay.reload() + await(relay.entries) { list -> ids.all { id -> list.any { it.id == id && it.summary != null } } } + } + return ids + } + + private fun viewModel( + ids: List, + profiles: List = BuiltInTargets.all, + trees: TreeStore? = null, + ): DeliverViewModel = DeliverViewModel( + batchIds = ids, + relayStore = relay, + preferences = preferences, + sceneStore = scenes, + dispatch = fakeDispatch, + copyPrompt = { copied += it; PromptClipboard.Result.Copied(systemConfirms = true) }, + installation = { profile -> + when { + profile.isWriter || profile.kind == TargetKind.CHOOSER -> Installation.NOT_AN_APP + profile.id in notInstalled -> Installation.NOT_INSTALLED + else -> Installation.INSTALLED + } + }, + newWorkDirectory = { File(deliveries, UUID.randomUUID().toString()).apply { mkdirs() } }, + profiles = profiles, + trees = trees, + zone = zone, + ).also { viewModels += it } + + private fun await(flow: StateFlow, condition: (T) -> Boolean): T = + runBlocking { withTimeout(15_000) { flow.first(condition) } } + + private fun DeliverViewModel.loaded(): DeliverUiState = await(state) { !it.loading } + + private fun DeliverViewModel.ready(targetId: String): Preview.Ready { + loaded() + runBlocking(main) { selectTarget(targetId) } + val s = await(state) { it.selectedTargetId == targetId && it.preview !is Preview.Planning && it.preview !is Preview.Idle } + return s.preview as? Preview.Ready ?: error("expected a plan, got ${s.preview}") + } + + private fun DeliverViewModel.sendAndWait(): DeliverUiState { + val before = state.value.progress.sent + runBlocking(main) { send(app) } + return await(state) { !it.busy && (it.progress.sent > before || it.feedback != null) } + } + + /** `ViewModel.clear()` is internal to lifecycle; go through the store as the framework does. */ + private fun clear(vm: DeliverViewModel) { + val store = androidx.lifecycle.ViewModelStore() + store.put("vm", vm) + store.clear() + } + + private fun defaultScene(instruction: String = "请按要点总结。"): WeChatScene { + val scene = WeChatScene(name = "测试场景", instruction = instruction, outputSpec = "", enabled = true) + scenes.setSettings(SceneSettings(listOf(scene), defaultSceneID = scene.id)) + return scene + } + + // endregion + + @Test + fun successMarksBatchesDeliveredToTarget() { + val scene = defaultScene() + val ids = batches("group-a.zip") + val vm = viewModel(ids) + val loaded = vm.loaded() + assertEquals(scene.id, loaded.sceneId) + assertEquals(SceneMatchSource.DEFAULT_SCENE, loaded.sceneSource) + assertTrue(loaded.prompt.contains("请按要点总结。")) + + val preview = vm.ready("chatgpt") + assertEquals(DeliveryFormat.ARCHIVE, preview.format) + assertEquals(1, preview.groups.size) + + val after = vm.sendAndWait() + assertTrue(after.progress.complete) + assertEquals(SendBlock.ALL_SENT, after.sendBlock) + val feedback = after.feedback as SendFeedback.Sent + assertEquals(PromptRoute.BOTH, feedback.prompt) + assertTrue(feedback.allSent) + + await(vm.state) { it.delivered } + val entry = relay.entry(ids.single())!! + assertEquals(DeliveryStatus.DELIVERED, entry.delivery) + assertEquals("chatgpt", entry.batch.targetName) + assertEquals(scene.id, entry.batch.sceneId) + assertEquals("chatgpt", runBlocking { preferences.current().lastTarget }) + + // ChatGPT reads EXTRA_TEXT: the prompt goes there and to the clipboard. + val (request, profile) = sent.single() + assertEquals("chatgpt", profile.id) + assertEquals(loaded.prompt.trim(), request.text) + assertEquals(listOf(loaded.prompt.trim()), copied.toList()) + assertTrue(request.files.single().file.name.endsWith(".zip")) + + // Group memory advances under the chat's name. + val chat = after.chatName + if (chat != null) { + val memory = scenes.memories.value[GroupName.normalize(chat)] + assertNotNull(memory) + assertEquals(scene.id, memory!!.lastSceneID) + assertTrue(memory.senders.isNotEmpty()) + } + } + + @Test + fun threeGroupsNeedTwoContinuations() { + val one = TargetProfile( + id = "one-at-a-time", + displayNameKey = null, + label = "单个", + kind = TargetKind.APP, + packageNames = listOf("example.one"), + maxAttachments = 1, + formats = listOf(DeliveryFormat.ARCHIVE, DeliveryFormat.TRANSCRIPT_ONLY), + formatEvidence = Evidence.DECLARED, + ) + defaultScene() + val ids = batches("group-a.zip", "group-a-later.zip", "interleave.zip") + val vm = viewModel(ids, profiles = listOf(one)) + assertEquals(3, vm.loaded().batchCount) + val preview = vm.ready(one.id) + assertEquals(3, preview.groups.size) + assertEquals(Progress(0, 3), vm.state.value.progress) + assertFalse(vm.state.value.progress.isContinuation) + + val first = vm.sendAndWait() + assertEquals(1, first.progress.sent) + assertTrue(first.progress.isContinuation) + assertEquals(2, first.progress.next) + assertTrue(first.canSend) + await(vm.state) { it.delivered } + assertEquals(DeliveryStatus.DELIVERED, relay.entry(ids[0])!!.delivery) + assertTrue(ids.all { relay.entry(it)!!.batch.targetName == "单个" }) + + val second = vm.sendAndWait() + assertEquals(2, second.progress.sent) + assertEquals(3, second.progress.next) + assertTrue(second.canSend) + + val third = vm.sendAndWait() + assertTrue(third.progress.complete) + assertFalse(third.canSend) + assertEquals(SendBlock.ALL_SENT, third.sendBlock) + + assertEquals(3, sent.size) + assertTrue(sent.all { it.first.files.size == 1 }) + // The prompt rides with the first group only, and is copied once. + assertNotNull(sent[0].first.text) + assertNull(sent[1].first.text) + assertNull(sent[2].first.text) + assertEquals(1, copied.size) + + // Nothing more to send: a fourth tap does nothing. + runBlocking(main) { vm.send(app) } + runBlocking(main) { } + assertEquals(3, sent.size) + } + + @Test + fun planFailureOffersSendingOriginalFiles() { + val ids = batches("group-a.zip", "files-only.zip") + val vm = viewModel(ids) + vm.loaded() + runBlocking(main) { vm.selectTarget("doubao") } + val failed = await(vm.state) { it.selectedTargetId == "doubao" && it.preview is Preview.Failed } + val preview = failed.preview as Preview.Failed + assertEquals(PlanFailure.NO_TRANSCRIPT, preview.reason) + assertTrue(preview.canSendOriginal) + assertTrue(failed.offersOriginal) + assertEquals(SendBlock.PLAN_FAILED, failed.sendBlock) + + runBlocking(main) { vm.sendOriginal() } + val ready = await(vm.state) { it.preview is Preview.Ready } + val plan = ready.preview as Preview.Ready + assertEquals(DeliveryFormat.ARCHIVE, plan.format) + assertEquals(2, plan.fileCount) + assertTrue(ready.canSend) + } + + @Test + fun plannerNoArchiveAlsoOffersOriginal() { + // A transcript-only target with no archive fallback, and summaries + // not known yet: the planner itself throws NO_ARCHIVE. + val textOnly = TargetProfile( + id = "text-only", + displayNameKey = null, + label = "TXT", + kind = TargetKind.APP, + packageNames = listOf("example.txt"), + formats = listOf(DeliveryFormat.TRANSCRIPT_ONLY), + formatEvidence = Evidence.DECLARED, + ) + val importer = UriImporter(inbox, buildVersion = "1", zone = zone) + val id = (importer.importBlocking(listOf(ZipStream(fixture("files-only.zip"))), collect = false) as ImportOutcome.Saved).batchId + val vm = viewModel(listOf(id), profiles = listOf(textOnly)) + vm.loaded() + val failed = await(vm.state) { it.preview is Preview.Failed || it.preview is Preview.Ready } + // Either the summary already said "not a chat" (format refused up front) + // or the planner found no transcript: both offer the original file. + if (failed.preview is Preview.Failed) { + assertTrue((failed.preview as Preview.Failed).canSendOriginal) + runBlocking(main) { vm.sendOriginal() } + val ready = await(vm.state) { it.preview is Preview.Ready } + assertEquals(DeliveryFormat.ARCHIVE, (ready.preview as Preview.Ready).format) + } else { + // All batches unparsable: iOS sends the original ZIP straight away. + assertEquals(DeliveryFormat.ARCHIVE, (failed.preview as Preview.Ready).format) + } + } + + @Test + fun archiveOverrideAppliesToThisDeliveryOnly() { + val ids = batches("group-a.zip") + val vm = viewModel(ids) + val txt = vm.ready("doubao") + assertEquals(DeliveryFormat.TRANSCRIPT_AND_IMAGES, txt.format) + assertTrue(txt.omitted.isNotEmpty()) // the video and the PDF + assertTrue(vm.state.value.offersOriginal) + + runBlocking(main) { vm.sendOriginal() } + val zip = await(vm.state) { (it.preview as? Preview.Ready)?.format == DeliveryFormat.ARCHIVE } + assertEquals(DeliveryFormat.ARCHIVE, zip.formatOverride) + assertFalse(zip.offersOriginal) + assertTrue(runBlocking { preferences.current().formatOverrides }.isEmpty()) + + // Another target and back: the one-off is gone. + vm.ready("chatgpt") + assertEquals(DeliveryFormat.TRANSCRIPT_AND_IMAGES, vm.ready("doubao").format) + assertNull(vm.state.value.formatOverride) + + // Sent as ZIP once; the next panel starts from 豆包's own default again. + runBlocking(main) { vm.sendOriginal() } + await(vm.state) { (it.preview as? Preview.Ready)?.format == DeliveryFormat.ARCHIVE } + vm.sendAndWait() + await(vm.state) { it.delivered } + assertTrue(sent.single().first.files.single().file.name.endsWith(".zip")) + assertTrue(runBlocking { preferences.current().formatOverrides }.isEmpty()) + + val next = viewModel(ids) + assertEquals("doubao", next.loaded().targets.first().id) // last used first + assertEquals(DeliveryFormat.TRANSCRIPT_AND_IMAGES, next.ready("doubao").format) + } + + @Test + fun doubaoDefaultsToTxtAndImagesWithPromptOnClipboard() { + defaultScene("帮我整理群里的结论。") + val ids = batches("group-a.zip") + val vm = viewModel(ids) + val preview = vm.ready("doubao") + assertEquals(DeliveryFormat.TRANSCRIPT_AND_IMAGES, preview.format) + val files = preview.groups.single() + assertEquals("聊天记录.txt", files.first().name) + assertTrue(files.drop(1).isNotEmpty() && files.drop(1).all { it.mimeType.startsWith("image/") }) + + val after = vm.sendAndWait() + val (request, _) = sent.single() + assertNull("豆包 drops EXTRA_TEXT: the prompt must not ride there", request.text) + assertEquals(1, copied.size) + assertTrue(copied.single().contains("帮我整理群里的结论。")) + val feedback = after.feedback as SendFeedback.Sent + assertEquals(PromptRoute.CLIPBOARD, feedback.prompt) + assertTrue(feedback.hint.pastePrompt) + assertEquals(files.map { it.file }, request.files.map { it.file }) + } + + @Test + fun notInstalledTargetIsDistinguishable() { + notInstalled += "doubao" + val ids = batches("group-a.zip") + val vm = viewModel(ids) + val loaded = vm.loaded() + val doubao = loaded.targets.first { it.id == "doubao" } + assertEquals(Installation.NOT_INSTALLED, doubao.installation) + assertFalse(doubao.isInstalled) + assertTrue(loaded.targets.first { it.id == "chatgpt" }.isInstalled) + // The panel does not open on a greyed-out tile. + assertTrue(loaded.selectedTarget?.isInstalled == true) + + vm.ready("doubao") + val state = vm.state.value + assertEquals(SendBlock.NOT_INSTALLED, state.sendBlock) + runBlocking(main) { vm.send(app) } + runBlocking(main) { } + assertTrue(sent.isEmpty()) + + // Uninstalled after the panel opened: the dispatcher says so. + nextResult = { _, profile -> DispatchResult.NotInstalled(profile.packageNames) } + vm.ready("chatgpt") + val after = vm.sendAndWait() + assertTrue(after.feedback is SendFeedback.NotInstalled) + assertEquals(Installation.NOT_INSTALLED, after.targets.first { it.id == "chatgpt" }.installation) + assertEquals(0, after.progress.sent) + assertEquals(DeliveryStatus.PENDING, relay.entry(ids.single())!!.delivery) + } + + @Test + fun launchFailureIsRecordedAndCanBeRetried() { + val ids = batches("group-a.zip") + val vm = viewModel(ids) + vm.ready("chatgpt") + nextResult = { _, _ -> DispatchResult.LaunchFailed("ActivityNotFoundException") } + val failed = vm.sendAndWait() + assertTrue(failed.feedback is SendFeedback.LaunchFailed) + assertEquals(0, failed.progress.sent) + assertTrue(failed.canSend) + await(relay.entries) { list -> list.any { it.id == ids.single() && it.delivery == DeliveryStatus.FAILED } } + + nextResult = null + vm.sendAndWait() + await(vm.state) { it.delivered } + assertEquals(DeliveryStatus.DELIVERED, relay.entry(ids.single())!!.delivery) + } + + @Test + fun writersAskForAFolder() { + val ids = batches("group-a.zip") + val vm = viewModel(ids) + vm.loaded() + runBlocking(main) { vm.selectTarget("obsidian") } + val state = await(vm.state) { it.selectedTargetId == "obsidian" && it.preview is Preview.NeedsFolder } + assertEquals(TargetKind.VAULT, (state.preview as Preview.NeedsFolder).kind) + assertTrue(state.selectedTarget!!.isWriter) + assertEquals(SendBlock.NEEDS_FOLDER, state.sendBlock) + + runBlocking(main) { vm.selectTarget("folder") } + val folder = await(vm.state) { it.selectedTargetId == "folder" && it.preview is Preview.NeedsFolder } + assertEquals(TargetKind.FOLDER, (folder.preview as Preview.NeedsFolder).kind) + } + + @Test + fun unsentPackageIsRemovedOnTargetChangeAndClose() { + val ids = batches("group-a.zip") + val vm = viewModel(ids) + vm.ready("chatgpt") + val firstDirs = deliveries.listFiles().orEmpty().toSet() + assertEquals(1, firstDirs.size) + vm.ready("doubao") + val dirs = deliveries.listFiles().orEmpty().toSet() + assertEquals(1, dirs.size) + assertFalse(firstDirs.single().exists()) + runBlocking(main) { vm.close() } + assertTrue(deliveries.listFiles().orEmpty().isEmpty()) + } + + @Test + fun missingBatchesBlockSending() { + val vm = viewModel(listOf(UUID.randomUUID())) + val state = vm.loaded() + assertTrue(state.missingBatches) + assertEquals(SendBlock.MISSING_BATCHES, state.sendBlock) + } + + // region SAF writing (A4.1) + + private val host = FakeTreeHost() + private val vaultUri: Uri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AVault") + + private fun treeStore(): TreeStore = + TreeStore(app.getSharedPreferences("trees-${UUID.randomUUID()}", Context.MODE_PRIVATE), host) + + private fun DeliverViewModel.folder(targetId: String, status: TreeStatus): DeliverUiState { + loaded() + runBlocking(main) { selectTarget(targetId) } + return await(state) { it.selectedTargetId == targetId && it.folder?.status == status } + } + + private fun DeliverViewModel.writeAndWait(): DeliverUiState { + runBlocking(main) { send(app) } + return await(state) { !it.busy && it.writeFeedback != null } + } + + @Test + fun grantedVaultWritesTheNoteAndRecordsDelivery() { + val scene = defaultScene() + val trees = treeStore() + assertEquals(TreeStatus.GRANTED, trees.grant(TargetKind.VAULT, vaultUri)) + val ids = batches("group-a.zip") + val vm = viewModel(ids, trees = trees) + val ready = vm.folder("obsidian", TreeStatus.GRANTED) + assertTrue(ready.preview is Preview.NeedsFolder) + assertEquals("微信流", ready.folder!!.subfolder) + assertEquals("Vault", ready.folder!!.folderName.orEmpty().substringAfterLast(':')) + assertTrue(ready.canSend) + + val after = vm.writeAndWait() + val saved = after.writeFeedback as WriteFeedback.Saved + val note = saved.notes.single() + assertTrue(note, note.startsWith("微信流/") && note.endsWith("的聊天.md")) + val tree = host.tree(vaultUri) + assertNotNull(tree.text(note)) + assertTrue(tree.names("微信流/附件").any { it.endsWith(".zip") }) + assertTrue(after.delivered) + assertEquals(SendBlock.ALL_SENT, after.sendBlock) + assertTrue(sent.isEmpty()) + + val entry = relay.entry(ids.single())!! + assertEquals(DeliveryStatus.DELIVERED, entry.delivery) + assertEquals("obsidian", entry.batch.targetName) + assertEquals(scene.id, entry.batch.sceneId) + assertEquals("obsidian", runBlocking { preferences.current().lastTarget }) + } + + @Test + fun ungrantedFolderAsksForAPickerThenWrites() { + val trees = treeStore() + val ids = batches("group-a.zip") + val vm = viewModel(ids, trees = trees) + val state = vm.folder("folder", TreeStatus.NOT_CHOSEN) + assertEquals(SendBlock.NEEDS_FOLDER, state.sendBlock) + + // The send button asks for a folder instead of sending. + runBlocking(main) { vm.send(app) } + assertEquals(TargetKind.FOLDER, await(vm.state) { it.folderRequest != null }.folderRequest) + runBlocking(main) { vm.consumeFolderRequest() } + + val picked = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3ADocs") + runBlocking(main) { vm.onFolderPicked(picked) } + val granted = await(vm.state) { it.folder?.status == TreeStatus.GRANTED } + assertNull(granted.folderRequest) + assertTrue(granted.canSend) + assertEquals(picked, trees.root(TargetKind.FOLDER).uri) + + val after = vm.writeAndWait() + assertTrue(after.writeFeedback is WriteFeedback.Saved) + assertEquals(DeliveryStatus.DELIVERED, relay.entry(ids.single())!!.delivery) + } + + @Test + fun cancelledOrRefusedPickerLeavesThePanelAsking() { + val trees = treeStore() + val vm = viewModel(batches("group-a.zip"), trees = trees) + vm.folder("obsidian", TreeStatus.NOT_CHOSEN) + runBlocking(main) { vm.requestFolder() } + runBlocking(main) { vm.onFolderPicked(null) } + assertEquals(SendBlock.NEEDS_FOLDER, vm.state.value.sendBlock) + + host.refuse = true + runBlocking(main) { vm.requestFolder() } + runBlocking(main) { vm.onFolderPicked(vaultUri) } + val failed = await(vm.state) { it.writeFeedback != null } + assertEquals(WriteFailure.NOT_GRANTED, (failed.writeFeedback as WriteFeedback.Failed).reason) + assertEquals(SendBlock.NEEDS_FOLDER, failed.sendBlock) + } + + @Test + fun revokedGrantAsksToPickAgainInsteadOfCrashing() { + val trees = treeStore() + trees.grant(TargetKind.VAULT, vaultUri) + val ids = batches("group-a.zip") + + // Revoked before the panel opened. + host.revoke(vaultUri) + val vm = viewModel(ids, trees = trees) + val lost = vm.folder("obsidian", TreeStatus.LOST) + assertEquals(SendBlock.NEEDS_FOLDER, lost.sendBlock) + + // Revoked between opening and sending. + trees.grant(TargetKind.VAULT, vaultUri) + runBlocking(main) { vm.selectTarget("folder") } + val ready = vm.folder("obsidian", TreeStatus.GRANTED) + assertTrue(ready.canSend) + host.revoke(vaultUri) + val after = vm.writeAndWait() + val failure = after.writeFeedback as WriteFeedback.Failed + assertEquals(WriteFailure.FOLDER_LOST, failure.reason) + assertEquals(TreeStatus.LOST, after.folder!!.status) + assertEquals(SendBlock.NEEDS_FOLDER, after.sendBlock) + assertFalse(after.delivered) + assertEquals(DeliveryStatus.PENDING, relay.entry(ids.single())!!.delivery) + + runBlocking(main) { vm.send(app) } + assertEquals(TargetKind.VAULT, await(vm.state) { it.folderRequest != null }.folderRequest) + } + + // endregion + + // region Group binding (A4.3) + + @Test + fun boundGroupIsPreselectedForALaterImportOfTheSameGroup() { + val other = WeChatScene(name = "默认场景", instruction = "默认。", outputSpec = "", enabled = true) + val weekly = WeChatScene(name = "周报场景", instruction = "写周报。", outputSpec = "", enabled = true) + scenes.setSettings(SceneSettings(listOf(other, weekly), defaultSceneID = other.id)) + + val first = viewModel(batches("group-a.zip")) + val opened = first.loaded() + assertEquals(other.id, opened.sceneId) + assertEquals(SceneMatchSource.DEFAULT_SCENE, opened.sceneSource) + assertTrue("an Android archive has no group name", opened.group.needsChoice) + + runBlocking(main) { first.createGroup("项目群") } + await(first.state) { s -> s.group.known.any { it.displayName == "项目群" } } + assertEquals("项目群", first.state.value.group.name) + assertEquals(GroupSource.MANUAL, first.state.value.group.source) + runBlocking(main) { first.selectScene(weekly.id) } + runBlocking(main) { first.bindSceneToGroup() } + await(first.state) { it.sceneSource == SceneMatchSource.BINDING } + assertEquals(listOf(weekly.id), scenes.memories.value[GroupName.normalize("项目群")]!!.boundSceneIDs) + + val later = viewModel(batches("group-a-later.zip")) + val state = later.loaded() + assertEquals(weekly.id, state.sceneId) + assertEquals(SceneMatchSource.FINGERPRINT, state.sceneSource) + assertEquals("项目群", state.group.name) + assertEquals(GroupSource.FINGERPRINT, state.group.source) + assertFalse(state.group.needsChoice) + assertTrue(state.prompt.contains("写周报。")) + } + + @Test + fun deliveryAdvancesGroupMemoryAndAPickedGroupPreselectsItsScene() { + val other = WeChatScene(name = "默认场景", instruction = "默认。", outputSpec = "", enabled = true) + val weekly = WeChatScene(name = "周报场景", instruction = "写周报。", outputSpec = "", enabled = true) + scenes.setSettings(SceneSettings(listOf(other, weekly), defaultSceneID = other.id)) + scenes.bind("项目群", listOf(weekly.id), emptySet()) + + val vm = viewModel(batches("group-a.zip")) + val opened = vm.loaded() + assertTrue(opened.group.needsChoice) + assertTrue(opened.group.known.any { it.displayName == "项目群" }) + runBlocking(main) { vm.chooseGroup("项目群") } + val chosen = await(vm.state) { it.group.source == GroupSource.MANUAL } + assertEquals(weekly.id, chosen.sceneId) + assertEquals(SceneMatchSource.BINDING, chosen.sceneSource) + + vm.ready("chatgpt") + vm.sendAndWait() + await(vm.state) { it.delivered } + val memory = scenes.memories.value[GroupName.normalize("项目群")]!! + assertEquals(weekly.id, memory.lastSceneID) + assertNotNull(memory.lastSummaryAt) + assertTrue(memory.senders.size >= 2) + assertEquals("项目群", relay.entry(vm.batchIds.single())!!.batch.chatName) + } + + @Test + fun qwenInlineTextSendsPureImagesAndCopiesTranscriptToClipboard() { + val vm = viewModel(batches("group-a.zip")) + val preview = vm.ready("qwen") + assertEquals(DeliveryFormat.INLINE_TEXT, preview.format) + assertTrue(preview.inlineText) + assertEquals(listOf(listOf("微信图片_20261020_1.png")), preview.groups.map { g -> g.map { it.name } }) + + val after = vm.sendAndWait() + val feedback = after.feedback as SendFeedback.Sent + assertEquals(1, feedback.total) + assertTrue(feedback.clipboard is PromptClipboard.Result.Copied) + assertTrue(feedback.hint.pastePrompt) + assertEquals(1, copied.size) + assertTrue(copied.single().contains("早上好")) + assertEquals(listOf("微信图片_20261020_1.png"), sent.single().first.files.map { it.file.name }) + } + + // endregion +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/IntentDispatcherTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/IntentDispatcherTest.kt new file mode 100644 index 00000000..d1d42b11 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/IntentDispatcherTest.kt @@ -0,0 +1,293 @@ +package com.xiangming.wechatbridge.deliver + +import android.app.Application +import android.content.ComponentName +import android.content.Intent +import android.content.IntentFilter +import android.net.Uri +import androidx.core.content.IntentCompat +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class IntentDispatcherTest { + private lateinit var app: Application + private lateinit var dispatcher: IntentDispatcher + private lateinit var dir: File + + @Before + fun setUp() { + app = ApplicationProvider.getApplicationContext() + resetFileProviderCache() + dispatcher = IntentDispatcher(TargetResolver(app)) + dir = ShareFileProvider.newDeliveryDir(app, "test") + } + + /** + * FileProvider caches its roots per authority in a static map; Robolectric + * gives every test a new data dir in the same class loader, so drop the + * previous test's roots. + */ + private fun resetFileProviderCache() { + val field = androidx.core.content.FileProvider::class.java.getDeclaredField("sCache") + field.isAccessible = true + (field.get(null) as MutableMap<*, *>).clear() + } + + private fun file(name: String, body: String = "x"): File = File(dir, name).apply { writeText(body) } + + /** Registers [activity] in [pkg] with SEND / SEND_MULTIPLE filters for [mimes]. */ + private fun install(pkg: String, activity: String, vararg mimes: String) { + val spm = shadowOf(app.packageManager) + val component = ComponentName(pkg, activity) + spm.addActivityIfNotPresent(component) + for (action in listOf(Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE)) { + val filter = IntentFilter(action).apply { + addCategory(Intent.CATEGORY_DEFAULT) + mimes.forEach { addDataType(it) } + } + spm.addIntentFilterForActivity(component, filter) + } + } + + private fun started(): Intent = shadowOf(app).nextStartedActivity + + private fun streams(intent: Intent): List = when (intent.action) { + Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)) + else -> IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty() + } + + private fun clipUris(intent: Intent): List { + val clip = intent.clipData ?: return emptyList() + return (0 until clip.itemCount).mapNotNull { clip.getItemAt(it).uri } + } + + private fun assertGranted(intent: Intent) = + assertTrue(intent.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION != 0) + + // MARK: Intent shape + + @Test + fun singleZipIsSendWithStreamClipDataAndGrant() { + install("com.example.chat", "com.example.chat.Share", "application/zip") + val zip = file("聊天记录.zip") + val result = dispatcher.dispatch( + app, + DeliveryRequest(listOf(OutgoingFile(zip, "application/zip")), text = "请总结"), + Destination.App(listOf("com.example.chat"), "com.example.chat.Share"), + ) + + assertEquals(DispatchResult.Sent(Route.EXPLICIT, "com.example.chat", "com.example.chat.Share", 1, true), result) + val intent = started() + assertEquals(Intent.ACTION_SEND, intent.action) + assertEquals("application/zip", intent.type) + assertEquals(ComponentName("com.example.chat", "com.example.chat.Share"), intent.component) + val uris = streams(intent) + assertEquals(1, uris.size) + assertEquals("content", uris[0].scheme) + assertEquals("${app.packageName}.share", uris[0].authority) + assertEquals(uris, clipUris(intent)) + assertEquals("请总结", intent.getStringExtra(Intent.EXTRA_TEXT)) + assertEquals("请总结", intent.clipData!!.getItemAt(0).text) + assertGranted(intent) + } + + @Test + fun severalImagesAreSendMultipleImageWildcardWithEveryUriInClipData() { + install("com.example.gem", "com.example.gem.Entry", "image/*", "text/plain") + val files = listOf(file("1.png"), file("2.jpg"), file("3.png")) + val mimes = listOf("image/png", "image/jpeg", "image/png") + val result = dispatcher.dispatch( + app, + DeliveryRequest(files.zip(mimes) { f, m -> OutgoingFile(f, m) }), + Destination.App(listOf("com.example.gem"), "com.example.gem.Entry"), + ) + + assertTrue(result is DispatchResult.Sent && result.uriCount == 3 && !result.textAttached) + val intent = started() + assertEquals(Intent.ACTION_SEND_MULTIPLE, intent.action) + assertEquals("image/*", intent.type) + val uris = streams(intent) + assertEquals(3, uris.size) + assertEquals(3, uris.toSet().size) + assertEquals(uris, clipUris(intent)) + val description = intent.clipData!!.description + assertEquals(setOf("image/png", "image/jpeg"), (0 until description.mimeTypeCount).map(description::getMimeType).toSet()) + assertNull(intent.getStringExtra(Intent.EXTRA_TEXT)) + assertGranted(intent) + } + + @Test + fun transcriptPlusImagesIsSendMultipleFullWildcard() { + install("com.example.chat", "com.example.chat.Share", "*/*") + val result = dispatcher.dispatch( + app, + DeliveryRequest(listOf(OutgoingFile(file("聊天记录.txt"), "text/plain"), OutgoingFile(file("a.png"), "image/png"))), + Destination.App(listOf("com.example.chat"), "com.example.chat.Share"), + ) + assertTrue(result is DispatchResult.Sent) + val intent = started() + assertEquals("*/*", intent.type) + assertEquals(2, streams(intent).size) + assertEquals(2, clipUris(intent).size) + assertGranted(intent) + } + + @Test + fun textOnlyIsPlainSendWithoutStreamOrGrant() { + install("com.example.notes", "com.example.notes.Share", "text/plain") + val result = dispatcher.dispatch( + app, + DeliveryRequest(emptyList(), text = "内联文本"), + Destination.App(listOf("com.example.notes"), "com.example.notes.Share"), + ) + assertTrue(result is DispatchResult.Sent && result.uriCount == 0 && result.textAttached) + val intent = started() + assertEquals(Intent.ACTION_SEND, intent.action) + assertEquals("text/plain", intent.type) + assertEquals("内联文本", intent.getStringExtra(Intent.EXTRA_TEXT)) + assertTrue(streams(intent).isEmpty()) + assertEquals(0, intent.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + + @Test + fun oversizedTextIsDroppedWhenFilesCarryTheContent() { + install("com.example.chat", "com.example.chat.Share", "text/plain") + val big = "字".repeat(IntentDispatcher.MAX_INLINE_TEXT_BYTES / 3 + 1) + val result = dispatcher.dispatch( + app, + DeliveryRequest(listOf(OutgoingFile(file("t.txt"), "text/plain")), text = big), + Destination.App(listOf("com.example.chat"), "com.example.chat.Share"), + ) + assertTrue(result is DispatchResult.Sent && !result.textAttached) + assertNull(started().getStringExtra(Intent.EXTRA_TEXT)) + } + + // MARK: refusals + + @Test + fun notInstalledTargetIsAValueAndLaunchesNothing() { + val chatgpt = BuiltInTargets.byId("chatgpt")!! + val result = dispatcher.dispatch(app, DeliveryRequest(listOf(OutgoingFile(file("a.zip"), "application/zip"))), chatgpt) + assertEquals(DispatchResult.NotInstalled(listOf("com.openai.chatgpt")), result) + assertNull(shadowOf(app).nextStartedActivity) + } + + @Test + fun badRequestsAreRejectedWithoutLaunching() { + val dest = Destination.Chooser + assertEquals(DispatchResult.Rejected(RejectReason.EMPTY), dispatcher.dispatch(app, DeliveryRequest(emptyList()), dest)) + val outside = File(app.filesDir, "inbox/ready/x.zip").apply { parentFile!!.mkdirs(); writeText("x") } + assertEquals( + DispatchResult.Rejected(RejectReason.OUTSIDE_DELIVERIES), + dispatcher.dispatch(app, DeliveryRequest(listOf(OutgoingFile(outside, "application/zip"))), dest), + ) + val sneaky = File(dir, "../../files/inbox/ready/x.zip") + assertEquals( + DispatchResult.Rejected(RejectReason.OUTSIDE_DELIVERIES), + dispatcher.dispatch(app, DeliveryRequest(listOf(OutgoingFile(sneaky, "application/zip"))), dest), + ) + assertEquals( + DispatchResult.Rejected(RejectReason.MISSING_FILE), + dispatcher.dispatch(app, DeliveryRequest(listOf(OutgoingFile(File(dir, "gone.zip"), "application/zip"))), dest), + ) + val big = "a".repeat(IntentDispatcher.MAX_INLINE_TEXT_BYTES + 1) + assertEquals(DispatchResult.Rejected(RejectReason.TEXT_TOO_LARGE), dispatcher.dispatch(app, DeliveryRequest(emptyList(), text = big), dest)) + assertNull(shadowOf(app).nextStartedActivity) + } + + // MARK: fallback chain + + @Test + fun missingDeclaredActivityFallsBackToSetPackage() { + install("com.example.chat", "com.example.chat.NewShare", "application/zip") + val result = dispatcher.dispatch( + app, + DeliveryRequest(listOf(OutgoingFile(file("a.zip"), "application/zip"))), + Destination.App(listOf("com.example.chat"), "com.example.chat.OldShare"), + ) + assertEquals(DispatchResult.Sent(Route.PACKAGE, "com.example.chat", null, 1, false), result) + val intent = started() + assertNull(intent.component) + assertEquals("com.example.chat", intent.`package`) + assertGranted(intent) + } + + @Test + fun installedAppThatDeclaresNothingForTheMimeGoesToTheChooser() { + install("com.example.gem", "com.example.gem.Entry", "image/*") + val result = dispatcher.dispatch( + app, + DeliveryRequest(listOf(OutgoingFile(file("a.zip"), "application/zip")), chooserTitle = "选择"), + Destination.App(listOf("com.example.gem"), "com.example.gem.Entry"), + ) + assertTrue(result is DispatchResult.Sent && result.viaChooser) + val chooser = started() + assertEquals(Intent.ACTION_CHOOSER, chooser.action) + val inner = IntentCompat.getParcelableExtra(chooser, Intent.EXTRA_INTENT, Intent::class.java)!! + assertEquals(Intent.ACTION_SEND, inner.action) + assertEquals("application/zip", inner.type) + assertEquals(1, streams(inner).size) + assertGranted(chooser) + assertTrue(chooser.clipData != null && chooser.clipData!!.itemCount == 1) + } + + @Test + fun secondPackageNameIsUsedWhenTheFirstIsAbsent() { + install("com.example.intl", "com.example.intl.Share", "*/*") + val result = dispatcher.dispatch( + app, + DeliveryRequest(listOf(OutgoingFile(file("a.zip"), "application/zip"))), + Destination.App(listOf("com.example.cn", "com.example.intl"), "com.example.intl.Share"), + ) + assertEquals(Route.EXPLICIT, (result as DispatchResult.Sent).route) + assertEquals("com.example.intl", result.packageName) + } + + @Test + fun otherTargetUsesTheChooser() { + val other = BuiltInTargets.byId("other")!! + val result = dispatcher.dispatch(app, DeliveryRequest(listOf(OutgoingFile(file("a.zip"), "application/zip"))), other) + assertTrue(result is DispatchResult.Sent && result.viaChooser && result.packageName == null) + assertEquals(Intent.ACTION_CHOOSER, started().action) + } + + @Test + fun writersAreNotIntentDestinations() { + assertNull(Destination.of(BuiltInTargets.byId("obsidian")!!)) + assertNull(Destination.of(BuiltInTargets.byId("folder")!!)) + assertEquals(Destination.Chooser, Destination.of(BuiltInTargets.byId("other")!!)) + } + + // MARK: helpers + + @Test + fun commonMimeRules() { + assertEquals("application/zip", IntentDispatcher.commonMime(listOf("application/zip"))) + assertEquals("image/*", IntentDispatcher.commonMime(listOf("image/png", "image/jpeg"))) + assertEquals("*/*", IntentDispatcher.commonMime(listOf("text/plain", "image/png"))) + assertEquals("image/png", IntentDispatcher.commonMime(listOf("IMAGE/PNG", "image/png"))) + assertEquals("application/octet-stream", IntentDispatcher.normalizedMime("")) + assertEquals("application/octet-stream", IntentDispatcher.normalizedMime("zip")) + } + + @Test + fun providerOnlyServesDeliveries() { + assertTrue(ShareFileProvider.isShareable(app, file("ok.zip"))) + assertFalse(ShareFileProvider.isShareable(app, ShareFileProvider.deliveriesDir(app))) + assertFalse(ShareFileProvider.isShareable(app, File(app.cacheDir, "summaries/x.json"))) + assertFalse(ShareFileProvider.isShareable(app, File(app.cacheDir, "deliveries-evil/x.zip"))) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/TargetResolverTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/TargetResolverTest.kt new file mode 100644 index 00000000..669f4d6a --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/deliver/TargetResolverTest.kt @@ -0,0 +1,120 @@ +package com.xiangming.wechatbridge.deliver + +import android.app.Application +import android.content.ClipboardManager +import android.content.ComponentName +import android.content.Intent +import android.content.IntentFilter +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.MimeKind +import com.xiangming.wechatbridge.core.deliver.SendAction +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class TargetResolverTest { + private lateinit var app: Application + private lateinit var resolver: TargetResolver + + @Before + fun setUp() { + app = ApplicationProvider.getApplicationContext() + resolver = TargetResolver(app) + } + + private fun install(pkg: String, activity: String, action: String, vararg mimes: String) { + val spm = shadowOf(app.packageManager) + val component = ComponentName(pkg, activity) + spm.addActivityIfNotPresent(component) + spm.addIntentFilterForActivity( + component, + IntentFilter(action).apply { + addCategory(Intent.CATEGORY_DEFAULT) + mimes.forEach { addDataType(it) } + }, + ) + } + + @Test + fun builtInTargetResolvesItsDeclaredActivity() { + val chatgpt = BuiltInTargets.byId("chatgpt")!! + assertEquals(Resolution.NotInstalled(listOf("com.openai.chatgpt")), resolver.resolve(chatgpt)) + install("com.openai.chatgpt", "com.openai.chatgpt.MainActivity", Intent.ACTION_SEND, "*/*") + assertEquals( + Resolution.Installed("com.openai.chatgpt", "com.openai.chatgpt.MainActivity", declaredActivityFound = true), + resolver.resolve(chatgpt), + ) + } + + @Test + fun renamedActivityFallsBackToWhateverThePackageDeclares() { + install("com.anthropic.claude", "com.anthropic.claude.share.ShareActivity", Intent.ACTION_SEND, "text/plain") + val result = resolver.resolve(BuiltInTargets.byId("claude")!!) + assertEquals(Resolution.Installed("com.anthropic.claude", "com.anthropic.claude.share.ShareActivity", false), result) + } + + @Test + fun chooserAndWritersAreNotApps() { + assertEquals(Resolution.NotAnApp, resolver.resolve(BuiltInTargets.byId("other")!!)) + assertEquals(Resolution.NotAnApp, resolver.resolve(BuiltInTargets.byId("folder")!!)) + assertEquals(Resolution.NotAnApp, resolver.resolve(BuiltInTargets.byId("obsidian")!!)) + } + + @Test + fun customSpecProbesEveryActionAndMime() { + install("org.localsend", "org.localsend.Share", Intent.ACTION_SEND, "*/*") + install("org.localsend", "org.localsend.Share", Intent.ACTION_SEND_MULTIPLE, "*/*") + val spec = resolver.customSpec("org.localsend")!! + assertEquals(SendAction.entries.size * MimeKind.entries.size, spec.receivers.size) + assertTrue(spec.receivers.all { it.activity == "org.localsend.Share" }) + val profile = TargetProfile.custom(spec) + assertEquals("custom:org.localsend", profile.id) + assertEquals(DeliveryFormat.ARCHIVE, profile.format) + assertEquals("org.localsend.Share", profile.sendActivity) + + install("com.example.pics", "com.example.pics.In", Intent.ACTION_SEND, "image/*") + val pics = resolver.customSpec("com.example.pics")!! + assertEquals(listOf(SendAction.SEND to MimeKind.IMAGE), pics.receivers.map { it.action to it.mime }) + + assertNull(resolver.customSpec("com.example.absent")) + } + + @Test + fun shareableAppsListsEachReceivingPackageOnceAndNotOurselves() { + install("org.localsend", "org.localsend.Share", Intent.ACTION_SEND, "*/*") + install("org.localsend", "org.localsend.Share", Intent.ACTION_SEND_MULTIPLE, "*/*") + install("com.example.pics", "com.example.pics.In", Intent.ACTION_SEND_MULTIPLE, "image/*") + install(app.packageName, "${app.packageName}.receive.SaveAlias", Intent.ACTION_SEND, "*/*") + val packages = resolver.shareableApps().map { it.packageName } + assertEquals(setOf("org.localsend", "com.example.pics"), packages.toSet()) + assertEquals(packages.size, packages.toSet().size) + assertFalse(resolver.isInstalled("com.example.absent")) + } + + @Test + fun promptGoesToTheClipboard() { + val clipboard = PromptClipboard(app) + assertEquals(PromptClipboard.Result.NothingToCopy, clipboard.copy(" ")) + assertEquals(PromptClipboard.Result.Copied(systemConfirms = true), clipboard.copy("请总结这段群聊")) + val manager = app.getSystemService(ClipboardManager::class.java) + assertEquals("请总结这段群聊", manager.primaryClip!!.getItemAt(0).text) + } + + @Test + @Config(sdk = [32]) + fun belowAndroid13WeConfirmTheCopyOurselves() { + assertEquals(PromptClipboard.Result.Copied(systemConfirms = false), PromptClipboard(app).copy("p")) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/fill/FillLogicTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/fill/FillLogicTest.kt new file mode 100644 index 00000000..1c406269 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/fill/FillLogicTest.kt @@ -0,0 +1,281 @@ +package com.xiangming.wechatbridge.fill + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class FillLogicTest { + private val own = "com.xiangming.wechatbridge" + + private fun window(pkg: String?, layer: Int, app: Boolean = true, focused: Boolean = false, active: Boolean = false) = + WindowFacts(isApplication = app, packageName = pkg, layer = layer, focused = focused, active = active) + + private fun node( + top: Int, + bottom: Int, + left: Int = 0, + right: Int = 1000, + editable: Boolean = true, + visible: Boolean = true, + enabled: Boolean = true, + focused: Boolean = false, + ) = NodeFacts(editable, visible, enabled, focused, left, top, right, bottom) + + // region Window + + @Test + fun windowSkipsOwnSystemUiAndNonApplicationWindows() { + val windows = listOf( + window(own, 10), + window(FillWindowRule.SYSTEM_UI, 9), + window("com.example.keyboard", 8, app = false), + window("com.larus.nova", 2), + ) + assertEquals(3, FillWindowRule.pick(windows, own)) + } + + @Test + fun windowPrefersFocusedThenActiveThenTopLayer() { + val a = window("com.a", 1) + val b = window("com.b", 5) + assertEquals(1, FillWindowRule.pick(listOf(a, b), own)) + assertEquals(0, FillWindowRule.pick(listOf(a.copy(active = true), b), own)) + assertEquals(1, FillWindowRule.pick(listOf(a.copy(active = true), b.copy(focused = true)), own)) + } + + @Test + fun noWindowWhenOnlyOursOrUnknown() { + assertNull(FillWindowRule.pick(emptyList(), own)) + assertNull(FillWindowRule.pick(listOf(window(own, 3), window(null, 2)), own)) + } + + // endregion + + // region Target + + @Test + fun focusedEditableWins() { + val target = FillTargetRule.choose(node(0, 10, focused = true), node(20, 30), listOf(node(40, 50))) + assertEquals(FillTarget.Focused, target) + } + + @Test + fun focusedButNotEditableFallsBackToRemembered() { + val target = FillTargetRule.choose(node(0, 10, editable = false, focused = true), node(20, 30), listOf(node(40, 50))) + assertEquals(FillTarget.Remembered, target) + } + + @Test + fun rememberedMustStillBeUsable() { + val target = FillTargetRule.choose(null, node(20, 30, visible = false), listOf(node(40, 50))) + assertEquals(FillTarget.Scanned(0), target) + } + + @Test + fun singleScannedBoxIsUsed() { + assertEquals(FillTarget.Scanned(1), FillTargetRule.choose(null, null, listOf(node(0, 10, editable = false), node(1800, 1900)))) + } + + @Test + fun severalScannedBoxesPickTheLowest() { + // A search box at the top, the chat input at the bottom. + val scanned = listOf(node(100, 180), node(2000, 2150), node(900, 1000)) + assertEquals(1, FillTargetRule.pickScanned(scanned)) + } + + @Test + fun severalScannedBoxesPreferAFocusedOne() { + val scanned = listOf(node(100, 180, focused = true), node(2000, 2150)) + assertEquals(0, FillTargetRule.pickScanned(scanned)) + } + + @Test + fun sameBottomTiesGoToTheWiderBox() { + val scanned = listOf(node(2000, 2150, left = 0, right = 300), node(2000, 2150, left = 0, right = 900)) + assertEquals(1, FillTargetRule.pickScanned(scanned)) + } + + @Test + fun hiddenDisabledOrEmptyBoxesAreSkipped() { + val scanned = listOf( + node(2000, 2150, visible = false), + node(1900, 2000, enabled = false), + node(1800, 1800), + node(100, 200), + ) + assertEquals(3, FillTargetRule.pickScanned(scanned)) + assertEquals(FillTarget.None, FillTargetRule.choose(null, null, scanned.take(3))) + assertEquals(FillTarget.None, FillTargetRule.choose(null, null, emptyList())) + } + + @Test + fun passwordBoxesAreNeverTargets() { + val password = node(2000, 2150, focused = true).copy(password = true) + assertEquals(FillTarget.Scanned(1), FillTargetRule.choose(password, password, listOf(password, node(100, 200)))) + assertNull(FillTargetRule.pickScanned(listOf(password))) + } + + // endregion + + // region Shielded & Placeholder + + private fun placeholder( + text: String, + top: Int = 2092, + bottom: Int = 2206, + left: Int = 33, + right: Int = 1047, + clickable: Boolean = true, + visible: Boolean = true, + enabled: Boolean = true, + ) = PlaceholderFacts(text, clickable, visible, enabled, left, top, right, bottom) + + @Test + fun shieldedWindowMatchesZeroChildRootAndBlankFocus() { + assertTrue(FillWindowTree.isShielded(0, null)) + val wechatBlankFocus = NodeFacts( + editable = false, + visible = false, + enabled = false, + focused = false, + left = 0, + top = 0, + right = 0, + bottom = 0, + ) + assertTrue(FillWindowTree.isShielded(0, wechatBlankFocus)) + assertFalse(FillWindowTree.isShielded(1, null)) + assertFalse(FillWindowTree.isShielded(0, node(1900, 2000, focused = true))) + } + + @Test + fun placeholderPicksQwenCollapsedInputBar() { + val candidates = listOf( + placeholder("语音输入", left = 55, right = 166, top = 2108, bottom = 2206), + placeholder("发消息或按住说话...", left = 33, right = 1047, top = 2092, bottom = 2206), + placeholder("扫一扫", left = 803, right = 914, top = 2108, bottom = 2206), + ) + assertEquals(1, FillPlaceholderRule.pick(candidates, windowBottom = 2340)) + } + + @Test + fun placeholderSkipsTopHalfButtonsAndUnusableNodes() { + val candidates = listOf( + placeholder("发消息", top = 120, bottom = 220), + placeholder("发送", left = 33, right = 1047), + placeholder("发消息", clickable = false), + placeholder("发消息", visible = false), + placeholder("发消息", enabled = false), + placeholder("发消息", left = 100, right = 200, top = 2092, bottom = 2206), + placeholder("AI生图"), + ) + assertNull(FillPlaceholderRule.pick(candidates, windowBottom = 2340)) + } + + @Test + fun placeholderPrefersLowestThenWidest() { + val candidates = listOf( + placeholder("随便问点什么", top = 1600, bottom = 1700), + placeholder("发消息...", top = 2092, bottom = 2206, left = 200, right = 800), + placeholder("发消息或按住说话...", top = 2092, bottom = 2206, left = 33, right = 1047), + ) + assertEquals(2, FillPlaceholderRule.pick(candidates, windowBottom = 2340)) + } + + // endregion + + // region Text + + @Test + fun emptyBoxTakesTheTextAsIs() { + val r = FillText.compute("", false, null, -1, -1, "聊天记录") + assertEquals(Insertion("聊天记录", 4, 0), r) + } + + @Test + fun hintOnlyCountsAsEmpty() { + assertEquals("abc", FillText.compute("发消息…", true, "发消息…", 0, 0, "abc").text) + // Some boxes report the hint as text without saying so. + assertEquals("abc", FillText.compute("发消息…", false, "发消息…", 4, 4, "abc").text) + assertEquals("abc", FillText.compute(null, false, null, 3, 3, "abc").text) + } + + @Test + fun noCursorAppendsAtTheEndOnANewLine() { + val r = FillText.compute("帮我总结", false, null, -1, -1, "记录") + assertEquals("帮我总结\n记录", r.text) + assertEquals(r.text.length, r.cursor) + assertEquals(5, r.insertedAt) + } + + @Test + fun noExtraLineBreakAfterWhitespace() { + assertEquals("问题\n记录", FillText.compute("问题\n", false, null, 3, 3, "记录").text) + assertEquals("问题 记录", FillText.compute("问题 ", false, null, 3, 3, "记录").text) + } + + @Test + fun insertsAtTheCursorKeepingTheRest() { + val r = FillText.compute("前后", false, null, 1, 1, "X") + assertEquals("前\nX后", r.text) + assertEquals(3, r.cursor) + } + + @Test + fun cursorAtStartNeedsNoLineBreak() { + val r = FillText.compute("后面", false, null, 0, 0, "X") + assertEquals("X后面", r.text) + assertEquals(1, r.cursor) + } + + @Test + fun selectionIsReplacedEvenWhenReversed() { + assertEquals("ab\nX", FillText.compute("ab cd", false, null, 5, 2, "X").text) + val r = FillText.compute("abcdef", false, null, 4, 2, "X") + assertEquals("ab\nXef", r.text) + assertEquals(4, r.cursor) + } + + @Test + fun outOfRangeSelectionIsClamped() { + assertEquals("ab\nX", FillText.compute("ab", false, null, 9, 12, "X").text) + } + + @Test + fun verifyDetectsUnchangedTruncatedAndOk() { + assertEquals(FillText.Check.OK, FillText.verify("", "abc", "abc")) + assertEquals(FillText.Check.UNCHANGED, FillText.verify("", "abc", "")) + assertEquals(FillText.Check.UNCHANGED, FillText.verify("q", "q\nabc", "q")) + assertEquals(FillText.Check.TRUNCATED, FillText.verify("", "a".repeat(100), "a".repeat(50))) + // Trimming a trailing line break is not a cut. + assertEquals(FillText.Check.OK, FillText.verify("", "abc\n", "abc")) + assertEquals(FillText.Check.UNCHANGED, FillText.verify("", "abc", null)) + } + + // endregion + + // region Setting + + private val cls = "com.xiangming.wechatbridge.fill.FillAccessibilityService" + + @Test + fun settingContainsTheServiceInFullOrShortForm() { + assertTrue(FillServiceSetting.contains("$own/$cls", own, cls)) + assertTrue(FillServiceSetting.contains("com.other/.A:$own/.fill.FillAccessibilityService", own, cls)) + assertTrue(FillServiceSetting.contains(" com.other/com.other.A : $own/$cls ", own, cls)) + } + + @Test + fun settingWithoutTheServiceIsOff() { + assertFalse(FillServiceSetting.contains(null, own, cls)) + assertFalse(FillServiceSetting.contains("", own, cls)) + assertFalse(FillServiceSetting.contains("com.other/.A", own, cls)) + assertFalse(FillServiceSetting.contains("$own/.bubble.BubbleService", own, cls)) + assertFalse(FillServiceSetting.contains("$own.debug/$cls", own, cls)) + assertFalse(FillServiceSetting.contains("$own/:/$cls", own, cls)) + } + + // endregion +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/fill/FillServiceDeclarationTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/fill/FillServiceDeclarationTest.kt new file mode 100644 index 00000000..930288f3 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/fill/FillServiceDeclarationTest.kt @@ -0,0 +1,76 @@ +package com.xiangming.wechatbridge.fill + +import android.Manifest +import android.accessibilityservice.AccessibilityServiceInfo +import android.app.Application +import android.content.ComponentName +import android.content.Intent +import android.content.pm.PackageManager +import android.view.accessibility.AccessibilityEvent +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.R +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.xmlpull.v1.XmlPullParser +import android.provider.Settings + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class FillServiceDeclarationTest { + private val app: Application = ApplicationProvider.getApplicationContext() + private val component get() = ComponentName(app, FillAccessibilityService::class.java) + + @Test + fun serviceIsProtectedByTheBindPermissionAndPointsAtItsConfig() { + val info = app.packageManager.getServiceInfo(component, PackageManager.GET_META_DATA) + assertEquals(Manifest.permission.BIND_ACCESSIBILITY_SERVICE, info.permission) + assertEquals(R.xml.fill_accessibility, info.metaData.getInt("android.accessibilityservice")) + val found = app.packageManager.queryIntentServices( + Intent("android.accessibilityservice.AccessibilityService").setPackage(app.packageName), + 0, + ) + assertTrue(found.any { it.serviceInfo.name == FillAccessibilityService::class.java.name }) + } + + @Test + fun configRetrievesWindowsListensToFocusOnlyAndAllowsAnyApp() { + val parser = app.resources.getXml(R.xml.fill_accessibility) + while (parser.next() != XmlPullParser.START_TAG) Unit + assertEquals("accessibility-service", parser.name) + assertTrue(parser.getAttributeBooleanValue(NS, "canRetrieveWindowContent", false)) + val flags = parser.getAttributeIntValue(NS, "accessibilityFlags", 0) + assertNotEquals(0, flags and AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS) + assertEquals(AccessibilityEvent.TYPE_VIEW_FOCUSED, parser.getAttributeIntValue(NS, "accessibilityEventTypes", 0)) + assertNull(parser.getAttributeValue(NS, "packageNames")) + val description = parser.getAttributeResourceValue(NS, "description", 0) + assertEquals(R.string.fill_service_description, description) + assertTrue(parser.getAttributeIntValue(NS, "notificationTimeout", 0) in 1..500) + } + + @Test + fun stateFollowsTheSecureSetting() { + Settings.Secure.putString(app.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, null) + assertFalse(FillAccess.isEnabled(app)) + assertEquals(FillAccess.State.OFF, FillAccess.state(app)) + Settings.Secure.putString(app.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, component.flattenToShortString()) + assertTrue(FillAccess.isEnabled(app)) + // Not bound in a unit test: on in settings, but not running. + assertEquals(FillAccess.State.NOT_RUNNING, FillAccess.state(app)) + } + + @Test + fun everyOutcomeHasAToast() { + FillOutcome.entries.forEach { assertTrue(app.getString(FillMessages.toast(it)).isNotBlank()) } + } + + private companion object { + const val NS = "http://schemas.android.com/apk/res/android" + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/notify/CollectNotificationTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/notify/CollectNotificationTest.kt new file mode 100644 index 00000000..18940113 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/notify/CollectNotificationTest.kt @@ -0,0 +1,235 @@ +package com.xiangming.wechatbridge.notify + +import android.Manifest +import android.app.Application +import android.app.Notification +import android.app.NotificationManager +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.receive.DeliverLaunch +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ShareItem +import com.xiangming.wechatbridge.receive.UriImporter +import com.xiangming.wechatbridge.ui.collection.CollectionUiState +import com.xiangming.wechatbridge.ui.collection.CollectionViewModel +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.io.File +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import java.util.UUID + +/** A4.4: 「收集中 · N 批」 follows the open collection; 放弃 and 移出 keep it in step. */ +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class CollectNotificationTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var app: Application + private lateinit var inbox: Inbox + private lateinit var importer: UriImporter + private val clock: Clock = Clock.fixed(Instant.now(), ZoneOffset.UTC) + + @Before + fun setUp() { + app = ApplicationProvider.getApplicationContext() + inbox = Inbox(File(temp.root, "files/inbox")) + importer = UriImporter(inbox, buildVersion = "1") + shadowOf(app).grantPermissions(Manifest.permission.POST_NOTIFICATIONS) + } + + private fun TestScope.store(): RelayStore = RelayStore( + inbox = inbox, + relayFilesRoot = File(temp.root, "cache/Relay"), + deliveriesDirectory = File(temp.root, "cache/deliveries"), + scope = this, + ioDispatcher = StandardTestDispatcher(testScheduler), + clock = clock, + ) + + /** What the 「分批收集到微信流」 entry does: a marked save, then the store adopts it. */ + private suspend fun collectBatch(store: RelayStore, text: String): UUID { + val id = (importer.importBlocking(listOf(ShareItem.Text(text)), collect = true) as ImportOutcome.Saved).batchId + assertNotNull(store.adoptCollected(id)) + CollectNotification.sync(app, store) + return id + } + + private fun posted(): List = + shadowOf(app.getSystemService(NotificationManager::class.java)).allNotifications + + private fun title(notification: Notification): String = + notification.extras.getCharSequence(Notification.EXTRA_TITLE).toString() + + @Test + fun threeCollectedBatchesShowCollectingThreeBatches() = runTest { + val store = store() + store.reload() + collectBatch(store, "一") + assertEquals("收集中 · 1 批", title(posted().single())) + collectBatch(store, "二") + collectBatch(store, "三") + + val notification = posted().single() + assertEquals("收集中 · 3 批", title(notification)) + assertEquals(CollectNotification.CHANNEL_ID, notification.channelId) + assertEquals("collect", notification.channelId) + assertTrue(notification.flags and Notification.FLAG_ONGOING_EVENT != 0) + assertEquals(listOf("完成并投递", "放弃"), notification.actions.map { it.title.toString() }) + advanceUntilIdle() + } + + @Test + fun deliverActionOpensTheDeliveryPanelForTheCollection() = runTest { + val store = store() + store.reload() + val a = collectBatch(store, "一") + val b = collectBatch(store, "二") + val deliver = posted().single().actions.first().actionIntent + val intent = shadowOf(deliver).savedIntent + assertEquals("com.xiangming.wechatbridge.MainActivity", intent.component?.className) + val launch = DeliverLaunch.parse(intent)!! + assertEquals(setOf(a, b).map { it.toString().uppercase() }.toSet(), launch.batchIds.toSet()) + assertNull(launch.targetId) + val abandon = shadowOf(posted().single().actions[1].actionIntent).savedIntent + assertEquals(CollectActionReceiver::class.java.name, abandon.component?.className) + assertEquals(store.currentCollection!!.id.toString(), abandon.getStringExtra(CollectActionReceiver.EXTRA_COLLECTION_ID)) + advanceUntilIdle() + } + + @Test + fun abandoningCancelsTheNotificationAndKeepsTheBatches() = runTest { + val store = store() + store.reload() + val a = collectBatch(store, "一") + collectBatch(store, "二") + val collection = store.currentCollection!!.id + assertEquals(1, posted().size) + + CollectNotification.abandon(app, store, collection) + + assertTrue(posted().isEmpty()) + assertNull(store.currentCollection) + assertNotNull(store.entry(a)) + advanceUntilIdle() + } + + @Test + fun removingABatchUpdatesTheCount() = runTest { + val store = store() + store.reload() + collectBatch(store, "一") + val b = collectBatch(store, "二") + collectBatch(store, "三") + val id = store.currentCollection!!.id + val viewModel = CollectionViewModel(id, store, onChanged = { CollectNotification.sync(app, store) }) + assertEquals(3, viewModel.initial.rows.size) + + viewModel.removeNow(b) + + assertEquals("收集中 · 2 批", title(posted().single())) + val state = viewModel.initial + assertEquals(2, state.rows.size) + assertEquals(listOf(1, 2), state.rows.map { it.number }) + assertTrue(b !in state.rows.map { it.id }) + assertNotNull(store.entry(b)) + advanceUntilIdle() + } + + @Test + fun removingTheLastBatchCancels() = runTest { + val store = store() + store.reload() + val a = collectBatch(store, "一") + val viewModel = CollectionViewModel(store.currentCollection!!.id, store, onChanged = { CollectNotification.sync(app, store) }) + viewModel.removeNow(a) + assertTrue(posted().isEmpty()) + advanceUntilIdle() + } + + @Test + fun withoutPermissionNothingIsPosted() = runTest { + shadowOf(app).denyPermissions(Manifest.permission.POST_NOTIFICATIONS) + val store = store() + store.reload() + collectBatch(store, "一") + assertTrue(posted().isEmpty()) + // The flow itself still works in the app. + assertEquals(1, store.currentCollection!!.batchIDs.size) + advanceUntilIdle() + } + + @Test + fun noOpenCollectionCancels() = runTest { + val store = store() + store.reload() + collectBatch(store, "一") + CollectNotification.update(app, null, emptyList()) + assertTrue(posted().isEmpty()) + advanceUntilIdle() + } + + @Test + fun lastBatchOfExactlyOneHundredOffersTheNextKeyword() = runTest { + val store = store() + store.reload() + val a = collectBatch(store, "一") + val b = collectBatch(store, "二") + val collection = store.currentCollection!! + val t0 = Instant.parse("2026-11-20T10:00:00Z") + fun chat(count: Int, start: Instant, keyword: String) = RelaySummary( + title = "群", + messageCount = count, + start = start, + end = start.plusSeconds(600), + preview = listOf("甲:第一句"), + kind = RelaySummary.Kind.CHAT, + last = RelaySummary.Last("乙", start.plusSeconds(600), "$keyword 的全文"), + anchor = keyword, + ) + val entries = store.entries.value.map { + when (it.id) { + a -> it.copy(summary = chat(100, t0.plusSeconds(3600), "后一批末句")) + b -> it.copy(summary = chat(60, t0, "前一批末句")) + else -> it + } + } + // The batch with the latest messages decides, whatever order they were added in. + val full = CollectionUiState.build(collection.id, listOf(collection), entries) + assertEquals("后一批末句", full.nextAnchor?.keyword) + assertEquals("乙", full.nextAnchor?.sender) + assertEquals(listOf(b, a), full.orderedIds) + assertEquals(160, full.messageCount) + + val short = entries.map { if (it.id == a) it.copy(summary = chat(99, t0.plusSeconds(3600), "x")) else it } + assertNull(CollectionUiState.build(collection.id, listOf(collection), short).nextAnchor) + advanceUntilIdle() + } + + @Test + fun unknownCollectionHasNoState() { + val state = CollectionUiState.build(UUID.randomUUID(), emptyList(), emptyList()) + assertNull(state.collection) + assertTrue(!state.canDeliver) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/notify/QuickDeliverNotificationTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/notify/QuickDeliverNotificationTest.kt new file mode 100644 index 00000000..f33a3df3 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/notify/QuickDeliverNotificationTest.kt @@ -0,0 +1,123 @@ +package com.xiangming.wechatbridge.notify + +import android.Manifest +import android.app.Application +import android.app.NotificationManager +import android.content.Context +import androidx.core.app.NotificationCompat +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.MainActivity +import com.xiangming.wechatbridge.core.deliver.QuickDeliver +import com.xiangming.wechatbridge.receive.DeliverLaunch +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.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.time.Duration +import java.time.Instant +import java.util.UUID + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class QuickDeliverNotificationTest { + private val context: Context = ApplicationProvider.getApplicationContext() + private val manager = context.getSystemService(NotificationManager::class.java) + private val batch = UUID.fromString("0B2E5C3A-1D4F-4E6A-9B7C-8D9E0F1A2B3C") + + @Before + fun setUp() { + QuickDeliverNotification.resetForTest() + shadowOf(context as Application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS) + } + + private fun posted() = shadowOf(manager).getNotification(QuickDeliverNotification.tag(batch), QuickDeliverNotification.NOTIFICATION_ID) + + @Test + fun postsOnTheQuickDeliverChannelWithPermission() { + assertTrue(QuickDeliverNotification.post(context, batch, "doubao", "豆包")) + val notification = posted() + assertNotNull(notification) + assertEquals("quick_deliver", notification.channelId) + assertNotNull(manager.getNotificationChannel("quick_deliver")) + assertEquals("已存入 · 投给 豆包", notification.extras.getString(NotificationCompat.EXTRA_TITLE)) + assertTrue(notification.flags and android.app.Notification.FLAG_AUTO_CANCEL != 0) + } + + @Test + fun tapOpensMainActivityOnTheDeliverPanelWithTheTarget() { + QuickDeliverNotification.post(context, batch, "doubao", "豆包") + val pending = shadowOf(posted()!!.contentIntent) + assertTrue(pending.isActivityIntent) + val intent = pending.savedIntent + assertEquals(MainActivity::class.java.name, intent.component!!.className) + assertEquals(DeliverLaunch.ACTION, intent.action) + assertEquals(DeliverLaunch(listOf(batch.toString().uppercase()), "doubao"), DeliverLaunch.parse(intent)) + } + + @Test + fun otherTargetsBecomeActionsPointingAtMainActivity() { + val others = listOf(QuickDeliver.Target("chatgpt", "ChatGPT"), QuickDeliver.Target("doubao", "重复"), QuickDeliver.Target("qwen", "千问"), QuickDeliver.Target("claude", "Claude")) + QuickDeliverNotification.post(context, batch, "doubao", "豆包", head = "group-a.zip", others = others) + val notification = posted()!! + assertEquals("group-a.zip · 点一下投递到「豆包」", notification.extras.getString(NotificationCompat.EXTRA_TEXT)) + assertEquals(listOf("投递到「ChatGPT」", "投递到「千问」"), notification.actions.map { it.title.toString() }) + val target = DeliverLaunch.parse(shadowOf(notification.actions[0].actionIntent).savedIntent)!!.targetId + assertEquals("chatgpt", target) + } + + @Test + fun withoutPermissionNothingIsPosted() { + shadowOf(context as Application).denyPermissions(Manifest.permission.POST_NOTIFICATIONS) + assertFalse(QuickDeliverNotification.post(context, batch, "doubao", "豆包")) + assertTrue(shadowOf(manager).allNotifications.isEmpty()) + // Granting later still allows this batch: a silent skip is not a post. + shadowOf(context as Application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS) + assertTrue(QuickDeliverNotification.post(context, batch, "doubao", "豆包")) + } + + @Test + fun appLevelSwitchOffPostsNothing() { + shadowOf(manager).setNotificationsEnabled(false) + assertFalse(QuickDeliverNotification.post(context, batch, "doubao", "豆包")) + assertTrue(shadowOf(manager).allNotifications.isEmpty()) + } + + @Test + fun rulesSkipCollectDisabledAndExpired() { + assertFalse(QuickDeliverNotification.post(context, batch, "doubao", "豆包", collect = true)) + assertFalse(QuickDeliverNotification.post(context, batch, "doubao", "豆包", enabled = false)) + val now = Instant.now() + assertFalse(QuickDeliverNotification.post(context, batch, "doubao", "豆包", savedAt = now - Duration.ofHours(2), now = now)) + assertFalse(QuickDeliverNotification.post(context, batch, "", "空")) + assertTrue(shadowOf(manager).allNotifications.isEmpty()) + } + + @Test + fun postsOnceAndNotAfterTheLaunchWasUsed() { + assertTrue(QuickDeliverNotification.post(context, batch, "doubao", "豆包")) + assertFalse(QuickDeliverNotification.post(context, batch, "doubao", "豆包")) + + val launch = DeliverLaunch.of(batch, "doubao") + assertEquals(launch.batchIds, QuickDeliverNotification.onLaunched(context, launch)) + assertNull(posted()) + // Re-delivered intent (recents): not a fresh hand-off; nothing is re-posted. + assertEquals(emptyList(), QuickDeliverNotification.onLaunched(context, launch)) + assertFalse(QuickDeliverNotification.post(context, batch, "doubao", "豆包")) + assertTrue(shadowOf(manager).allNotifications.isEmpty()) + } + + @Test + fun cancelRemovesAndKeepsItHandled() { + QuickDeliverNotification.post(context, batch, "doubao", "豆包") + QuickDeliverNotification.cancel(context, batch) + assertNull(posted()) + assertFalse(QuickDeliverNotification.post(context, batch, "doubao", "豆包")) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DeliverLaunchTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DeliverLaunchTest.kt new file mode 100644 index 00000000..eb308a5e --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DeliverLaunchTest.kt @@ -0,0 +1,62 @@ +package com.xiangming.wechatbridge.receive + +import android.content.Intent +import androidx.test.core.app.ApplicationProvider +import android.content.Context +import com.xiangming.wechatbridge.MainActivity +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.util.UUID + +@RunWith(RobolectricTestRunner::class) +class DeliverLaunchTest { + private val context: Context = ApplicationProvider.getApplicationContext() + private val id = UUID.fromString("0B2E5C3A-1D4F-4E6A-9B7C-8D9E0F1A2B3C") + + @Test + fun roundTripsThroughTheIntent() { + val intent = DeliverLaunch.of(id, "chatgpt").intent(context) + assertEquals(MainActivity::class.java.name, intent.component!!.className) + assertTrue(intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0) + assertEquals(DeliverLaunch(listOf(id.toString().uppercase()), "chatgpt"), DeliverLaunch.parse(intent)) + } + + @Test + fun withoutTargetStillOpensThePanel() { + val parsed = DeliverLaunch.parse(DeliverLaunch.of(id, null).intent(context))!! + assertNull(parsed.targetId) + val blank = DeliverLaunch.parse( + DeliverLaunch.of(id, null).intent(context).putExtra(DeliverLaunch.EXTRA_TARGET_ID, " "), + )!! + assertNull(blank.targetId) + } + + @Test + fun ignoresOtherIntents() { + assertNull(DeliverLaunch.parse(null)) + assertNull(DeliverLaunch.parse(Intent(Intent.ACTION_MAIN))) + // Our action but no batch. + assertNull(DeliverLaunch.parse(Intent(DeliverLaunch.ACTION))) + // A launcher intent carrying the extras is not a request. + assertNull( + DeliverLaunch.parse( + Intent(Intent.ACTION_MAIN).putExtra(DeliverLaunch.EXTRA_BATCH_IDS, arrayOf(id.toString())), + ), + ) + } + + @Test + fun onlyUuidsReachTheRoute() { + val intent = Intent(DeliverLaunch.ACTION).putExtra( + DeliverLaunch.EXTRA_BATCH_IDS, + arrayOf("../settings", id.toString(), "a,b", id.toString()), + ) + assertEquals(listOf(id.toString()), DeliverLaunch.parse(intent)!!.batchIds) + val none = Intent(DeliverLaunch.ACTION).putExtra(DeliverLaunch.EXTRA_BATCH_IDS, arrayOf("x")) + assertNull(DeliverLaunch.parse(none)) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DropClipsTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DropClipsTest.kt new file mode 100644 index 00000000..2dbbe5f1 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DropClipsTest.kt @@ -0,0 +1,137 @@ +package com.xiangming.wechatbridge.receive + +import android.content.ClipData +import android.content.ClipDescription +import android.content.Context +import android.content.Intent +import android.net.Uri +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File + +/** ClipData from a drag → the same [ShareItem]s (and batches) a system share gives. */ +@RunWith(RobolectricTestRunner::class) +class DropClipsTest { + @get:Rule + val temp = TemporaryFolder() + + private val context: Context = ApplicationProvider.getApplicationContext() + + private fun clip(mimeTypes: Array, vararg items: ClipData.Item): ClipData { + val clip = ClipData(ClipDescription("drag", mimeTypes), items.first()) + for (item in items.drop(1)) clip.addItem(item) + return clip + } + + private val photo = Uri.parse("content://media/external/images/media/42") + private val pdf = Uri.parse("content://com.android.providers.downloads.documents/document/7") + + @Test + fun acceptsFilesTextAndLinksButNotIntents() { + assertTrue(DropClips.accepts(setOf("text/plain"))) + assertTrue(DropClips.accepts(setOf("image/jpeg"))) + assertTrue(DropClips.accepts(setOf("video/mp4"))) + assertTrue(DropClips.accepts(setOf("application/pdf"))) + assertTrue(DropClips.accepts(setOf(ClipDescription.MIMETYPE_TEXT_URILIST))) + assertTrue(DropClips.accepts(setOf(ClipDescription.MIMETYPE_TEXT_INTENT, "image/png"))) + assertFalse(DropClips.accepts(setOf(ClipDescription.MIMETYPE_TEXT_INTENT))) + assertFalse(DropClips.accepts(emptySet())) + } + + @Test + fun aUriItemIsAFileWithTheDescriptionsType() { + val items = DropClips.items(context, clip(arrayOf("image/jpeg"), ClipData.Item(photo))) + val stream = items.single() as ContentStreamItem + assertEquals(photo, stream.uri) + } + + @Test + fun plainTextIsAText() { + val items = DropClips.items(context, clip(arrayOf("text/plain"), ClipData.Item("明天下午三点开会"))) + assertEquals(listOf(ShareItem.Text("明天下午三点开会")), items) + } + + @Test + fun htmlItemsUseTheirPlainText() { + val items = DropClips.items(context, clip(arrayOf("text/html"), ClipData.Item("你好 世界", "

你好 世界

"))) + assertEquals(listOf(ShareItem.Text("你好 世界")), items) + } + + @Test + fun aLinkAsTextOrAsUriListIsAText() { + val link = "https://example.com/article?id=1" + assertEquals( + listOf(ShareItem.Text(link)), + DropClips.items(context, clip(arrayOf("text/plain"), ClipData.Item(link))), + ) + assertEquals( + listOf(ShareItem.Text(link)), + DropClips.items(context, clip(arrayOf(ClipDescription.MIMETYPE_TEXT_URILIST), ClipData.Item(Uri.parse(link)))), + ) + } + + @Test + fun mixedFilesAndTextKeepEveryItemFilesFirst() { + val items = DropClips.items( + context, + clip(arrayOf("image/jpeg", "text/plain"), ClipData.Item("说明文字"), ClipData.Item(photo)), + ) + assertEquals(2, items.size) + assertEquals(photo, (items[0] as ContentStreamItem).uri) + assertEquals(ShareItem.Text("说明文字"), items[1]) + } + + @Test + fun severalUrisAreSeveralFilesOnceEachAndNeverOurOwn() { + val own = Uri.parse("content://${context.packageName}.share/deliveries/a.zip") + val items = DropClips.items( + context, + clip( + arrayOf("image/jpeg", "application/pdf"), + ClipData.Item(photo), + ClipData.Item(pdf), + ClipData.Item(photo), + ClipData.Item(own), + ), + ) + assertEquals(listOf(photo, pdf), items.map { (it as ContentStreamItem).uri }) + } + + @Test + fun aClipWithNothingUsableGivesNoItems() { + val items = DropClips.items(context, clip(arrayOf("text/plain"), ClipData.Item(" "))) + assertTrue(items.isEmpty()) + } + + /** A dragged link makes byte-for-byte the batch a 「分享链接」 makes: the note, `public.url`, share-origin.json. */ + @Test + fun aDroppedLinkMakesTheSameBatchAsASharedLink() { + val link = "https://example.com/post/9" + val shared = Intent(Intent.ACTION_SEND).apply { + type = "text/plain" + putExtra(Intent.EXTRA_TEXT, link) + } + val fromShare = UriImporter(Inbox(File(temp.root, "a"))).importBlocking(ShareIntents.items(context, shared), collect = false) + val fromDrop = UriImporter(Inbox(File(temp.root, "b"))) + .importBlocking(DropClips.items(context, clip(arrayOf("text/plain"), ClipData.Item(link))), collect = false) + + val a = fromShare as ImportOutcome.Saved + val b = fromDrop as ImportOutcome.Saved + assertEquals(a.items.map { it.displayName }, b.items.map { it.displayName }) + assertEquals(listOf(ShareOrigin.NOTE_CONTENT_TYPE), b.items.map { it.contentType }) + assertEquals(a.items.map { it.byteCount }, b.items.map { it.byteCount }) + val originA = File(a.directory, ShareOrigin.FILE_NAME) + val originB = File(b.directory, ShareOrigin.FILE_NAME) + assertTrue(originB.isFile) + assertEquals(originA.readText(), originB.readText()) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DropReceiverTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DropReceiverTest.kt new file mode 100644 index 00000000..9812620e --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/DropReceiverTest.kt @@ -0,0 +1,271 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.core.collection.BatchCollection +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import com.xiangming.wechatbridge.data.RelayStore +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File +import java.io.InputStream +import java.util.UUID +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** Drops on the relay and on a collection's page, queued, each grant released after its copy. */ +@RunWith(RobolectricTestRunner::class) +class DropReceiverTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var inbox: Inbox + private lateinit var importer: UriImporter + private lateinit var storeScope: CoroutineScope + private lateinit var dropScope: CoroutineScope + private lateinit var store: RelayStore + private val collected = AtomicInteger() + + @Before + fun setUp() { + inbox = Inbox(File(temp.root, "files/inbox")) + importer = UriImporter(inbox, buildVersion = "1") + storeScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + dropScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + store = RelayStore( + inbox = inbox, + relayFilesRoot = File(temp.root, "cache/Relay"), + deliveriesDirectory = File(temp.root, "cache/deliveries"), + scope = storeScope, + ) + } + + @After + fun tearDown() { + dropScope.cancel() + storeScope.cancel() + } + + private fun receiver() = DropReceiver( + importer = importer, + scope = dropScope, + reload = store::reload, + joinCollection = store::joinCollection, + onCollected = { collected.incrementAndGet() }, + ) + + private fun readyBatches(): List = inbox.ready.listFiles()?.filter { it.isDirectory }.orEmpty() + + private fun saveText(text: String): UUID = + (importer.importBlocking(listOf(ShareItem.Text(text)), collect = false) as ImportOutcome.Saved).batchId + + /** A file stream; [onRead] runs before each chunk so a test can hold or slow the copy. */ + private class FakeStream( + private val name: String, + private val bytes: ByteArray, + private val onRead: () -> Unit = {}, + ) : ShareItem.Stream { + var closed = false + override val mimeType: String = "image/jpeg" + override val loadStrategy: LoadStrategy = LoadStrategy.FILE_REPRESENTATION + override fun displayName(): String = name + override fun open(): InputStream = object : InputStream() { + private var position = 0 + override fun read(): Int { + onRead() + return if (position < bytes.size) bytes[position++].toInt() and 0xFF else -1 + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + onRead() + if (position >= bytes.size) return -1 + val count = minOf(len, bytes.size - position, 1024) + System.arraycopy(bytes, position, b, off, count) + position += count + return count + } + + override fun close() { + closed = true + } + } + } + + @Test + fun aDropOnTheRelayIsANewBatch() = runBlocking { + store.reload() + val receiver = receiver() + val releases = AtomicInteger() + receiver.drop(listOf(ShareItem.Text("拖进来的一段话")), { releases.incrementAndGet() }, DropDestination.Relay).join() + + val result = withTimeout(5_000) { receiver.events.first() } as DropResult.Saved + assertEquals(DropDestination.Relay, result.destination) + assertNull(result.collectedBatchNumber) + assertFalse(result.notJoined) + assertEquals(1, releases.get()) + assertEquals(listOf(result.receipt.batchId), store.entries.value.map { it.id }) + assertTrue(store.ledger.value.collections.isEmpty()) + assertEquals(0, collected.get()) + assertEquals(0, receiver.pending.value) + } + + @Test + fun aDropOnTheOpenCollectionJoinsIt() = runBlocking { + val first = saveText("第一批") + store.reload() + assertEquals(1, store.collect(first)) + val collection = store.currentCollection!!.id + + val receiver = receiver() + receiver.drop(listOf(ShareItem.Text("第二批")), null, DropDestination.Collection(collection)).join() + + val result = withTimeout(5_000) { receiver.events.first() } as DropResult.Saved + assertEquals(2, result.collectedBatchNumber) + assertEquals(listOf(first, result.receipt.batchId), store.currentCollection!!.batchIDs) + assertEquals(1, collected.get()) + assertTrue(store.entry(result.receipt.batchId)!!.isCollecting) + } + + @Test + fun aDropOnAParkedCollectionReopensItAndJoins() = runBlocking { + val a = saveText("甲") + val b = saveText("乙") + store.reload() + store.collect(a) + val parked = store.currentCollection!!.id + // A failed delivery leaves the collection waiting for a retry, with none open. + store.beginCollectionDelivery(parked) + store.finishCollectionDelivery(parked, succeeded = false, target = "ChatGPT", detail = "x", scene = null) + store.collect(b) + val other = store.currentCollection!!.id + assertNotEquals(parked, other) + + val receiver = receiver() + receiver.drop(listOf(ShareItem.Text("丙")), null, DropDestination.Collection(parked)).join() + + val result = withTimeout(5_000) { receiver.events.first() } as DropResult.Saved + assertEquals(2, result.collectedBatchNumber) + assertEquals(parked, store.currentCollection!!.id) + assertEquals(listOf(a, result.receipt.batchId), store.currentCollection!!.batchIDs) + val otherNow = store.ledger.value.collections.first { it.id == other } + assertEquals(BatchCollection.Status.DRAFT, otherNow.status) + assertEquals(listOf(b), otherNow.batchIDs) + } + + @Test + fun aDropOnAGoneCollectionIsStillSavedButNotJoined() = runBlocking { + store.reload() + val receiver = receiver() + receiver.drop(listOf(ShareItem.Text("孤儿")), null, DropDestination.Collection(UUID.randomUUID())).join() + + val result = withTimeout(5_000) { receiver.events.first() } as DropResult.Saved + assertTrue(result.notJoined) + assertEquals(listOf(result.receipt.batchId), store.entries.value.map { it.id }) + assertTrue(store.ledger.value.collections.isEmpty()) + assertNull(store.lastError.value) + assertEquals(0, collected.get()) + } + + @Test + fun twoQuickDropsAreTwoBatchesInDropOrder() = runBlocking { + store.reload() + val receiver = receiver() + val gate = CountDownLatch(1) + val slow = FakeStream("第一张.jpg", ByteArray(8 * 1024) { 1 }) { gate.await(5, TimeUnit.SECONDS) } + val firstJob = receiver.drop(listOf(slow), null, DropDestination.Relay) + val secondJob = receiver.drop(listOf(ShareItem.Text("第二次拖入")), null, DropDestination.Relay) + assertEquals(2, receiver.pending.value) + // The second waits behind the first instead of racing it. + Thread.sleep(100) + assertTrue(readyBatches().isEmpty()) + gate.countDown() + firstJob.join() + secondJob.join() + + val results = withTimeout(5_000) { receiver.events.take(2).toList() }.map { it as DropResult.Saved } + assertEquals(listOf("第一张.jpg"), results[0].receipt.itemNames) + assertTrue(results[1].receipt.itemNames.single().endsWith(".txt")) + assertNotEquals(results[0].receipt.batchId, results[1].receipt.batchId) + assertEquals(2, readyBatches().size) + assertEquals(2, store.entries.value.size) + assertEquals(0, receiver.pending.value) + } + + @Test + fun theGrantIsReleasedOnlyAfterTheCopyIsCommitted() = runBlocking { + store.reload() + val receiver = receiver() + val stream = FakeStream("图.jpg", ByteArray(200 * 1024) { 7 }) + val seenAtRelease = CopyOnWriteArrayList() + var closedAtRelease = false + receiver.drop( + listOf(stream), + { seenAtRelease += readyBatches().size; closedAtRelease = stream.closed }, + DropDestination.Relay, + ).join() + + assertEquals(listOf(1), seenAtRelease.toList()) + assertTrue(closedAtRelease) + val saved = withTimeout(5_000) { receiver.events.first() } as DropResult.Saved + assertEquals(200L * 1024, saved.receipt.byteCount) + } + + @Test + fun destroyingTheActivityCancelsTheCopyDiscardsStagingThenReleases() = runBlocking { + val receiver = receiver() + val copying = CountDownLatch(1) + val stream = FakeStream("大文件.jpg", ByteArray(4 * 1024 * 1024) { 3 }) { + copying.countDown() + Thread.sleep(2) + } + val released = CountDownLatch(1) + var stagingAtRelease = -1 + val job = receiver.drop( + listOf(stream), + { + stagingAtRelease = inbox.staging.listFiles()?.size ?: 0 + released.countDown() + }, + DropDestination.Relay, + ) + assertTrue(copying.await(5, TimeUnit.SECONDS)) + dropScope.cancel() + job.join() + + assertTrue(released.await(5, TimeUnit.SECONDS)) + assertEquals(0, stagingAtRelease) + assertTrue(readyBatches().isEmpty()) + assertTrue(stream.closed) + } + + @Test + fun anEmptyDropIsRefusedAndStillReleased() = runBlocking { + val receiver = receiver() + val releases = AtomicInteger() + receiver.drop(emptyList(), { releases.incrementAndGet() }, DropDestination.Relay).join() + val result = withTimeout(5_000) { receiver.events.first() } as DropResult.Failed + assertEquals(ReceiveFailure.EmptyShare, result.failure) + assertEquals(1, releases.get()) + assertTrue(readyBatches().isEmpty()) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/ReceiveCollectNotifyTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/ReceiveCollectNotifyTest.kt new file mode 100644 index 00000000..409b70e0 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/ReceiveCollectNotifyTest.kt @@ -0,0 +1,79 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.core.inbox.Inbox +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +/** The receiver tells the notification when a batch joined the collection, and only then. */ +@OptIn(ExperimentalCoroutinesApi::class) +class ReceiveCollectNotifyTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var importer: UriImporter + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + importer = UriImporter(Inbox(File(temp.root, "inbox"))) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun ReceiveViewModel.awaitSaved(): ReceiptUiState.Saved = runBlocking { + withTimeout(5_000) { state.first { it is ReceiptUiState.Saved } } as ReceiptUiState.Saved + } + + private fun vm(notified: MutableList, number: Int? = 3) = ReceiveViewModel( + importer = importer, + adoptCollected = { number }, + addToCollection = { number }, + onCollected = { notified += Unit }, + ) + + @Test + fun collectEntryUpdatesTheNotification() { + val notified = mutableListOf() + val vm = vm(notified) + vm.start(collect = true) { listOf(ShareItem.Text("一")) } + assertEquals(3, vm.awaitSaved().collectedBatchNumber) + assertEquals(1, notified.size) + } + + @Test + fun plainSaveDoesNotUntilAddedToTheCollection() { + val notified = mutableListOf() + val vm = vm(notified) + vm.start(collect = false) { listOf(ShareItem.Text("一")) } + vm.awaitSaved() + assertEquals(0, notified.size) + vm.addToCollection() + runBlocking { withTimeout(5_000) { vm.state.first { (it as? ReceiptUiState.Saved)?.collectedBatchNumber != null } } } + assertEquals(1, notified.size) + } + + @Test + fun notAdoptedMeansNoNotification() { + val notified = mutableListOf() + val vm = vm(notified, number = null) + vm.start(collect = true) { listOf(ShareItem.Text("一")) } + vm.awaitSaved() + assertEquals(0, notified.size) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/ReceiveViewModelTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/ReceiveViewModelTest.kt new file mode 100644 index 00000000..e02086df --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/ReceiveViewModelTest.kt @@ -0,0 +1,97 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.core.inbox.Inbox +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.util.UUID + +@OptIn(ExperimentalCoroutinesApi::class) +class ReceiveViewModelTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var importer: UriImporter + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + importer = UriImporter(Inbox(File(temp.root, "inbox"))) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun ReceiveViewModel.saved(): ReceiptUiState.Saved = runBlocking { + withTimeout(5_000) { state.first { it is ReceiptUiState.Saved || it is ReceiptUiState.NotSaved } } as ReceiptUiState.Saved + } + + private fun receiveViewModel( + refreshed: MutableList = mutableListOf(), + added: MutableList = mutableListOf(), + lastTarget: String? = "chatgpt", + ) = ReceiveViewModel( + importer = importer, + onSaved = { refreshed += Unit }, + adoptCollected = { 4 }, + addToCollection = { added += it; 2 }, + lastTarget = { lastTarget }, + ) + + @Test + fun plainSaveOffersTheLastTargetAndCollectsOnRequest() { + val refreshed = mutableListOf() + val added = mutableListOf() + val vm = receiveViewModel(refreshed, added) + vm.start(collect = false) { listOf(ShareItem.Text("一段话")) } + val saved = vm.saved() + assertEquals(1, refreshed.size) + assertEquals("chatgpt", saved.lastTargetId) + assertNull(saved.collectedBatchNumber) + assertEquals(DeliverLaunch(listOf(saved.batchId.toString().uppercase()), "chatgpt"), vm.deliverLaunch()) + + vm.addToCollection() + val collected = runBlocking { withTimeout(5_000) { vm.state.first { (it as ReceiptUiState.Saved).collectedBatchNumber != null } } } + assertEquals(2, (collected as ReceiptUiState.Saved).collectedBatchNumber) + assertEquals(listOf(saved.batchId), added) + // Once only. + vm.addToCollection() + assertEquals(1, added.size) + } + + @Test + fun noLastTargetHidesQuickDelivery() { + val vm = receiveViewModel(lastTarget = null) + vm.start(collect = false) { listOf(ShareItem.Text("一段话")) } + assertNull(vm.saved().lastTargetId) + assertNull(vm.deliverLaunch()) + } + + @Test + fun collectEntryShowsItsBatchNumberAndNoQuickDelivery() { + val refreshed = mutableListOf() + val vm = receiveViewModel(refreshed) + vm.start(collect = true) { listOf(ShareItem.Text("一段话")) } + val saved = vm.saved() + assertEquals(4, saved.collectedBatchNumber) + assertNull(saved.lastTargetId) + assertNull(vm.deliverLaunch()) + // adoptCollected reloads the store itself. + assertEquals(0, refreshed.size) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/UriImporterTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/UriImporterTest.kt new file mode 100644 index 00000000..5edff679 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/receive/UriImporterTest.kt @@ -0,0 +1,499 @@ +package com.xiangming.wechatbridge.receive + +import com.xiangming.wechatbridge.core.inbox.BatchManifest +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.inbox.InboxReader +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import com.xiangming.wechatbridge.core.inbox.ShareAction +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.core.summary.ShareSource +import com.xiangming.wechatbridge.core.util.ImportDiagnostics +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +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.Assert.fail +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.time.ZoneId +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +class UriImporterTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var inbox: Inbox + private lateinit var importer: UriImporter + + @Before + fun setUp() { + inbox = Inbox(File(temp.root, "inbox")) + importer = UriImporter(inbox, buildVersion = "1", zone = ZoneId.of("Asia/Shanghai")) + } + + // MARK: the four acceptance inputs (android-plan §5.3 A1.10) + + @Test + fun singleZipIsCommittedWithItsNameAndChatSummary() { + val outcome = importer.importBlocking(listOf(fixtureItem("group-a.zip", name = "聊天记录.zip")), collect = false) + + val saved = outcome as ImportOutcome.Saved + assertEquals(listOf("聊天记录.zip"), saved.items.map { it.displayName }) + assertEquals(fixture("group-a.zip").length(), saved.items.single().byteCount) + assertEquals(LoadStrategy.FILE_REPRESENTATION, saved.items.single().loadStrategy) + assertEquals("application/zip", saved.items.single().contentType) + assertTrue(saved.directory.parentFile == inbox.ready) + assertTrue(File(saved.directory, saved.items.single().relativePath).isFile) + assertNoStaging() + + val archive = saved.archives.single() + assertTrue(archive.isWeChatFormat) + assertTrue(archive.messageCount!! > 0) + assertEquals(archive.messageCount, saved.records.size) + + val manifest = BatchManifest.decode(File(saved.directory, "manifest.json").readBytes()) + assertEquals(saved.batchId, manifest.batchId) + assertEquals(ShareAction.COLLECT, manifest.action) + assertFalse(CollectMarker.isMarked(saved.directory)) + + val state = ReceiptUiState.from(outcome, collect = false) as ReceiptUiState.Saved + assertEquals(archive.messageCount, state.messageCount) + assertTrue(state.isWeChatFormat) + assertFalse(state.hasNonWeChatArchive) + assertNotNull(state.first) + assertNotNull(state.last) + assertTrue(!state.first!!.date.isAfter(state.last!!.date)) + } + + @Test + fun threeZipsLandInOneBatchInOrder() { + val names = listOf("group-a.zip", "group-a-later.zip", "interleave.zip") + val outcome = importer.importBlocking(names.map { fixtureItem(it, name = it) }, collect = false) + + val saved = outcome as ImportOutcome.Saved + assertEquals(names, saved.items.map { it.displayName }) + assertEquals(listOf(0, 1, 2), saved.items.map { it.attachmentIndex }) + assertEquals(1, inbox.ready.listFiles()!!.size) + assertEquals(3, saved.archives.size) + val state = ReceiptUiState.from(outcome, collect = false) as ReceiptUiState.Saved + assertEquals(saved.archives.sumOf { it.messageCount ?: 0 }, state.messageCount) + assertEquals(saved.records.sortedBy { it.date }, saved.records) + } + + @Test + fun emptyFileRefusesTheWholeShare() { + val outcome = importer.importBlocking( + listOf(fixtureItem("group-a.zip", name = "a.zip"), FakeStream(ByteArray(0), name = "空.zip", mimeType = "application/zip")), + collect = false, + ) + + assertEquals(ReceiveFailure.EmptyFile("空.zip"), (outcome as ImportOutcome.Failed).failure) + assertNoReady() + assertNoStaging() + val record = diagnostics().single() + assertFalse(record.succeeded) + assertEquals(2, record.attachments.size) + assertEquals("empty file", record.attachments.last().failure) + } + + @Test + fun plainTextIsSavedAsATxtItem() { + val outcome = importer.importBlocking(listOf(ShareItem.Text("第一行标题\n第二行内容", subject = null)), collect = false) + + val saved = outcome as ImportOutcome.Saved + val item = saved.items.single() + assertEquals("第一行标题.txt", item.displayName) + assertEquals(ShareOrigin.NOTE_CONTENT_TYPE, item.contentType) + assertEquals("第一行标题\n第二行内容\n", File(saved.directory, item.relativePath).readText()) + assertEquals(ShareOrigin(text = "第一行标题\n第二行内容"), ShareOrigin.read(saved.directory)) + assertTrue(saved.archives.isEmpty()) + val state = ReceiptUiState.from(outcome, collect = false) as ReceiptUiState.Saved + assertNull(state.messageCount) + assertFalse(state.isWeChatFormat) + } + + // MARK: names + + @Test + fun textSubjectBecomesTitleAndName() { + val saved = importer.importBlocking(listOf(ShareItem.Text("正文", subject = "主题/一")), collect = false) as ImportOutcome.Saved + val item = saved.items.single() + assertEquals("主题-一.txt", item.displayName) + assertEquals("主题/一\n\n正文\n", File(saved.directory, item.relativePath).readText()) + } + + // MARK: links (iOS ShareOrigin / share-origin.json) + + @Test + fun linkInTextBecomesALinkCardFromItsApp() { + val saved = importer.importBlocking( + listOf(ShareItem.Text("标题\nhttps://x.com/someone/status/123")), + collect = false, + ) as ImportOutcome.Saved + val origin = ShareOrigin.read(saved.directory)!! + assertEquals("https://x.com/someone/status/123", origin.url) + assertNull(origin.title) + assertEquals("标题\nhttps://x.com/someone/status/123", origin.text) + val item = saved.items.single() + assertEquals("标题.txt", item.displayName) + assertEquals(ShareOrigin.NOTE_CONTENT_TYPE, item.contentType) + assertEquals("https://x.com/someone/status/123\n\n标题\nhttps://x.com/someone/status/123\n", File(saved.directory, item.relativePath).readText()) + + val summary = RelaySummary.make(InboxReader(inbox).loadBatches().single()) + assertEquals(RelaySummary.Kind.LINK, summary.kind) + assertEquals("X", summary.source) + assertEquals("标题", summary.title) + assertEquals("https://x.com/someone/status/123", summary.url) + assertEquals(0, summary.mediaCount) + } + + @Test + fun browserLinkWithSubjectIsTheUrlAndTitle() { + // Chrome: EXTRA_TEXT is the page link, EXTRA_SUBJECT the page title. + val saved = importer.importBlocking( + listOf(ShareItem.Text("https://www.bilibili.com/video/BV1", subject = "一个视频")), + collect = false, + ) as ImportOutcome.Saved + assertEquals(ShareOrigin(url = "https://www.bilibili.com/video/BV1", title = "一个视频"), ShareOrigin.read(saved.directory)) + assertEquals("一个视频.txt", saved.items.single().displayName) + assertEquals("一个视频\nhttps://www.bilibili.com/video/BV1\n", File(saved.directory, saved.items.single().relativePath).readText()) + val summary = RelaySummary.make(InboxReader(inbox).loadBatches().single()) + assertEquals(RelaySummary.Kind.LINK, summary.kind) + assertEquals("哔哩哔哩", summary.source) + } + + @Test + fun plainTextWithoutLinkIsSourcedAsText() { + importer.importBlocking(listOf(ShareItem.Text("只是一段话")), collect = false) as ImportOutcome.Saved + val summary = RelaySummary.make(InboxReader(inbox).loadBatches().single()) + assertEquals(RelaySummary.Kind.LINK, summary.kind) + assertNull(summary.url) + assertEquals(ShareSource.TEXT, summary.source) + } + + @Test + fun shareOriginMakeFollowsIos() { + // Text that is only the link adds nothing. + assertEquals(ShareOrigin(url = "https://a.com/x"), ShareOrigins.make("https://a.com/x", null, listOf(" https://a.com/x "))) + // A title repeated as the text is dropped; duplicates once. + assertEquals( + ShareOrigin(title = "推文", text = "别的"), + ShareOrigins.make(null, " 推文 ", listOf("推文", "别的", "别的")), + ) + // A link buried in a blurb becomes the link. + assertEquals( + "https://v.douyin.com/abc/", + ShareOrigins.make(null, null, listOf("复制打开抖音 https://v.douyin.com/abc/ 看看"))!!.url, + ) + assertNull(ShareOrigins.make(null, " ", listOf(" ", ""))) + assertFalse(ShareOrigins.isWeb("ftp://a.com")) + assertTrue(ShareOrigins.isWeb("HTTPS://a.com")) + } + + @Test + fun blankTextIsAnEmptyShare() { + val outcome = importer.importBlocking(listOf(ShareItem.Text(" \n ")), collect = false) + assertEquals(ReceiveFailure.EmptyShare, (outcome as ImportOutcome.Failed).failure) + assertNoReady() + } + + @Test + fun namelessOctetStreamZipIsRecognisedByItsBytes() { + val saved = importer.importBlocking( + listOf(FakeStream(fixture("group-a.zip").readBytes(), name = null, mimeType = "application/octet-stream")), + collect = false, + ) as ImportOutcome.Saved + assertEquals("共享文件.zip", saved.items.single().displayName) + assertTrue(saved.archives.single().isWeChatFormat) + val diagnostic = diagnostics().single().attachments.single() + assertFalse(diagnostic.hasSuggestedName) + assertEquals(listOf("application/octet-stream"), diagnostic.registeredTypeIdentifiers) + } + + @Test + fun nameWithoutExtensionGetsOneFromMime() { + val saved = importer.importBlocking( + listOf(FakeStream("x".toByteArray(), name = "报告", mimeType = "application/pdf")), + collect = false, + ) as ImportOutcome.Saved + assertEquals("报告.pdf", saved.items.single().displayName) + } + + @Test + fun unsafeNamesAreSanitisedAndDuplicatesCoexist() { + val saved = importer.importBlocking( + listOf( + FakeStream("a".toByteArray(), name = "../../etc/聊天记录.zip", mimeType = "application/zip"), + FakeStream("b".toByteArray(), name = "聊天记录.zip", mimeType = "application/zip"), + ), + collect = false, + ) as ImportOutcome.Saved + assertEquals(listOf("聊天记录.zip", "聊天记录.zip"), saved.items.map { it.displayName }) + assertEquals(2, saved.items.map { it.relativePath }.toSet().size) + // Not a ZIP after all: kept, flagged as not WeChat. + assertTrue(saved.archives.none { it.isWeChatFormat }) + assertTrue((ReceiptUiState.from(saved, false) as ReceiptUiState.Saved).hasNonWeChatArchive) + } + + @Test + fun nonWeChatZipIsKeptButMarked() { + val saved = importer.importBlocking(listOf(fixtureItem("not-wechat.zip", name = "资料.zip")), collect = false) as ImportOutcome.Saved + val check = saved.archives.single() + assertFalse(check.isWeChatFormat) + assertNull(check.messageCount) + assertTrue(File(saved.directory, saved.items.single().relativePath).isFile) + } + + @Test + fun fileUrlStrategyIsRecorded() { + val saved = importer.importBlocking( + listOf(FakeStream("hi".toByteArray(), name = "a.txt", mimeType = "text/plain", loadStrategy = LoadStrategy.FILE_URL)), + collect = false, + ) as ImportOutcome.Saved + assertEquals(LoadStrategy.FILE_URL, saved.items.single().loadStrategy) + assertEquals("fileURL", diagnostics().single().attachments.single().loadStrategy) + } + + // MARK: limits and failures + + @Test + fun emptyShareIsRefused() { + assertEquals(ReceiveFailure.EmptyShare, (importer.importBlocking(emptyList(), false) as ImportOutcome.Failed).failure) + assertNoReady() + assertFalse(diagnostics().single().succeeded) + } + + @Test + fun moreThan32ItemsIsRefusedWhole() { + val items = (0..UriImporter.MAX_ITEMS).map { FakeStream("x".toByteArray(), name = "$it.txt", mimeType = "text/plain") } + val outcome = importer.importBlocking(items, collect = false) + assertEquals(ReceiveFailure.TooManyItems(33), (outcome as ImportOutcome.Failed).failure) + assertTrue(items.none { it.opened }) + assertNoReady() + } + + @Test + fun exactly32ItemsAreAccepted() { + val items = (0 until UriImporter.MAX_ITEMS).map { FakeStream("x".toByteArray(), name = "$it.txt", mimeType = "text/plain") } + val saved = importer.importBlocking(items, collect = false) as ImportOutcome.Saved + assertEquals(32, saved.items.size) + } + + @Test + fun unopenableUriRefusesTheShare() { + val outcome = importer.importBlocking( + listOf(fixtureItem("group-a.zip", name = "a.zip"), FakeStream(null, name = "b.zip", mimeType = "application/zip")), + collect = false, + ) + assertEquals(ReceiveFailure.Unreadable, (outcome as ImportOutcome.Failed).failure) + assertNoReady() + assertNoStaging() + val failure = diagnostics().single().attachments.last().failure!! + // Redacted: the exception class, never its message (which may hold a path or chat title). + assertEquals("open: FileNotFoundException", failure) + } + + @Test + fun readErrorMidCopyLeavesNothingBehind() { + val broken = object : ShareItem.Stream { + override val mimeType = "application/zip" + override val loadStrategy = LoadStrategy.FILE_REPRESENTATION + override fun displayName() = "秘密群聊.zip" + override fun open(): InputStream = object : InputStream() { + var sent = 0 + override fun read(): Int = if (sent++ < 10_000) 1 else throw IOException("/secret/path") + } + } + val outcome = importer.importBlocking(listOf(broken), collect = false) + assertEquals(ReceiveFailure.Unreadable, (outcome as ImportOutcome.Failed).failure) + assertNoReady() + assertNoStaging() + val json = inbox.diagnostics.listFiles()!!.single().readText() + assertFalse(json.contains("秘密群聊")) + assertFalse(json.contains("secret")) + } + + @Test + fun cancellationMidCopyDiscardsStaging() { + var calls = 0 + val big = GeneratedStream(8L * UriImporter.BUFFER_SIZE) + try { + importer.importBlocking(listOf(big), collect = false) { + if (++calls > 3) throw CancellationException("back pressed") + } + fail("expected cancellation") + } catch (_: CancellationException) { + } + assertNoReady() + assertNoStaging() + } + + @Test + fun cancellingTheCoroutineDiscardsStaging() = runBlocking { + val started = CountDownLatch(1) + val endless = object : ShareItem.Stream { + override val mimeType = "application/zip" + override val loadStrategy = LoadStrategy.FILE_REPRESENTATION + override fun displayName() = "big.zip" + override fun open(): InputStream = object : InputStream() { + override fun read(): Int = 1 + override fun read(b: ByteArray, off: Int, len: Int): Int { + started.countDown() + Thread.sleep(1) + b.fill(1, off, off + len) + return len + } + } + } + val job = async(Dispatchers.Default) { importer.import(listOf(endless), collect = false) } + assertTrue(started.await(5, TimeUnit.SECONDS)) + job.cancel() + withTimeout(5_000) { runCatching { job.await() } } + assertNoReady() + assertNoStaging() + } + + @Test + fun largeStreamIsCopiedInChunks() { + val size = 40L * 1024 * 1024 + val stream = GeneratedStream(size) + val saved = importer.importBlocking(listOf(stream), collect = false) as ImportOutcome.Saved + assertEquals(size, saved.items.single().byteCount) + assertEquals(size, File(saved.directory, saved.items.single().relativePath).length()) + // Never asked for more than one buffer at a time. + assertTrue(stream.largestRead <= UriImporter.BUFFER_SIZE) + } + + // MARK: collect entry, diagnostics, reader interop + + @Test + fun collectEntryMarksTheBatchInsideTheCommit() { + val outcome = importer.importBlocking(listOf(fixtureItem("group-a.zip", name = "a.zip")), collect = true) + val saved = outcome as ImportOutcome.Saved + assertTrue(CollectMarker.isMarked(saved.directory)) + assertTrue((ReceiptUiState.from(outcome, collect = true) as ReceiptUiState.Saved).collect) + } + + @Test + fun successWritesBatchAndRingDiagnostics() { + val saved = importer.importBlocking(listOf(fixtureItem("group-a.zip", name = "a.zip")), collect = false) as ImportOutcome.Saved + val inBatch = ImportDiagnostics.decode(File(saved.directory, "diagnostics.json").readText())!! + assertTrue(inBatch.succeeded) + assertEquals("collect", inBatch.action) + assertEquals("1", inBatch.extensionVersion) + assertEquals(saved.batchId, inBatch.batchID) + val ring = diagnostics().single() + assertEquals(saved.batchId, ring.batchID) + assertTrue(inbox.diagnostics.listFiles()!!.single().name.startsWith("ok-")) + } + + @Test + fun committedBatchIsReadableByInboxReader() { + val saved = importer.importBlocking(listOf(fixtureItem("group-a.zip", name = "聊天记录.zip")), collect = false) as ImportOutcome.Saved + val batch = InboxReader(inbox).loadBatches().single() + assertEquals(saved.batchId, batch.id) + assertEquals("聊天记录.zip", batch.items.single().displayName) + assertTrue(batch.isFirstSeen) + } + + // MARK: pure helpers + + @Test + fun mimeExtensions() { + assertEquals("zip", MimeTypes.extension("application/zip")) + assertEquals("zip", MimeTypes.extension("application/x-zip-compressed")) + assertEquals("txt", MimeTypes.extension("text/plain; charset=utf-8")) + assertNull(MimeTypes.extension("application/octet-stream")) + assertNull(MimeTypes.extension("*/*")) + assertNull(MimeTypes.extension("image/*")) + assertEquals("abc", MimeTypes.extension("application/x-abc") { "abc" }) + assertFalse(MimeTypes.isConcrete("*/*")) + assertTrue(MimeTypes.isConcrete("image/png")) + assertEquals("zip", MimeTypes.sniff(byteArrayOf(0x50, 0x4B, 3, 4), 4)) + assertNull(MimeTypes.sniff(byteArrayOf(0x50, 0x4B), 2)) + } + + @Test + fun mergeKeepsOrderAndDropsDuplicates() { + assertEquals(listOf("a", "b", "c"), ShareIntents.merge(listOf("a", "b"), listOf("b", "c", "a"))) + } + + @Test + fun failureStateCarriesTheReason() { + val state = ReceiptUiState.from(ImportOutcome.Failed(ReceiveFailure.Unreadable), collect = true) + assertEquals(ReceiptUiState.NotSaved(ReceiveFailure.Unreadable, collect = true), state) + } + + // MARK: helpers + + private fun assertNoReady() { + assertTrue(inbox.ready.listFiles().orEmpty().isEmpty()) + } + + private fun assertNoStaging() { + assertTrue(inbox.staging.listFiles().orEmpty().isEmpty()) + } + + private fun diagnostics(): List = + inbox.diagnostics.listFiles().orEmpty().map { ImportDiagnostics.decode(it.readText())!! } + + private fun fixtureItem(fixtureName: String, name: String?) = + FakeStream(fixture(fixtureName).readBytes(), name = name, mimeType = "application/zip") + + private class FakeStream( + private val bytes: ByteArray?, + private val name: String?, + override val mimeType: String?, + override val loadStrategy: LoadStrategy = LoadStrategy.FILE_REPRESENTATION, + ) : ShareItem.Stream { + var opened = false + override fun displayName(): String? = name + override fun open(): InputStream { + opened = true + return ByteArrayInputStream(bytes ?: throw java.io.FileNotFoundException("/private/path/$name")) + } + } + + /** Produces [size] bytes without holding them, and records the largest read request. */ + private class GeneratedStream(private val size: Long) : ShareItem.Stream { + override val mimeType = "video/mp4" + override val loadStrategy = LoadStrategy.FILE_REPRESENTATION + var largestRead = 0 + override fun displayName() = "big.mp4" + override fun open(): InputStream = object : InputStream() { + var remaining = size + override fun read(): Int = if (remaining-- > 0) 7 else -1 + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (remaining <= 0) return -1 + largestRead = maxOf(largestRead, len) + val n = minOf(len.toLong(), remaining).toInt() + remaining -= n + return n + } + } + } + + private fun fixture(name: String): File { + var dir: File? = File("").absoluteFile + while (dir != null) { + val candidate = File(dir, "ios/Tests/Fixtures/$name") + if (candidate.isFile) return candidate + dir = dir.parentFile + } + error("fixture $name not found above ${File("").absolutePath}") + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/FakeDocumentOps.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/FakeDocumentOps.kt new file mode 100644 index 00000000..6cdca0fc --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/FakeDocumentOps.kt @@ -0,0 +1,165 @@ +package com.xiangming.wechatbridge.saf + +import android.net.Uri +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream + +/** + * In-memory SAF provider. Like `ExternalStorageProvider`, `create` on a taken + * name gives `name (1).ext`; [renameOnCreate] forces another name, [beforeCreate] + * runs first (a concurrent writer), and "w" without "t" overwrites in place + * without truncating, as some providers do. Without [granted] queries return + * null and mutations throw, as a revoked grant does. + */ +class FakeDocumentOps(rootName: String = "Vault") : DocumentOps { + class Node(val id: String, var name: String, val isDirectory: Boolean, val parent: String?) { + var bytes: ByteArray = ByteArray(0) + } + + val nodes = LinkedHashMap() + var granted = true + var renameOnCreate: ((name: String) -> String?)? = null + var beforeCreate: ((parentId: String, name: String) -> Unit)? = null + var failWritesAfter: Int? = null + val created = mutableListOf() + val deleted = mutableListOf() + val outputModes = mutableListOf() + private var nextId = 0 + + override val rootId: String = "root" + + init { + nodes[rootId] = Node(rootId, rootName, isDirectory = true, parent = null) + } + + override fun hasPermission(): Boolean = granted + + override fun stat(id: String): DocumentOps.Doc? = if (!granted) null else nodes[id]?.doc() + + override fun children(id: String): List? { + if (!granted) return null + val node = nodes[id]?.takeIf { it.isDirectory } ?: return null + return nodes.values.filter { it.parent == node.id }.map { it.doc() } + } + + override fun create(parentId: String, mimeType: String, name: String): DocumentOps.Doc { + guard() + beforeCreate?.invoke(parentId, name) + val parent = nodes[parentId]?.takeIf { it.isDirectory } ?: throw IOException("no parent $parentId") + var actual = renameOnCreate?.invoke(name) ?: name + val siblings = nodes.values.filter { it.parent == parent.id }.map { it.name }.toSet() + if (actual in siblings) { + val dot = actual.lastIndexOf('.').takeIf { it > 0 && mimeType != DocumentOps.DIRECTORY_MIME } + val base = if (dot == null) actual else actual.substring(0, dot) + val ext = if (dot == null) "" else actual.substring(dot) + var n = 1 + while ("$base ($n)$ext" in siblings) n++ + actual = "$base ($n)$ext" + } + val node = add(parent.id, actual, mimeType == DocumentOps.DIRECTORY_MIME) + created += node.id + return node.doc() + } + + override fun delete(id: String) { + guard() + val node = nodes[id] ?: throw IOException("no such document $id") + nodes.values.filter { it.parent == node.id }.map { it.id }.forEach { delete(it) } + nodes.remove(id) + deleted += id + } + + override fun openOutput(id: String, mode: String): OutputStream { + guard() + val node = nodes[id]?.takeIf { !it.isDirectory } ?: throw IOException("cannot write $id") + outputModes += mode + val limit = failWritesAfter + return object : ByteArrayOutputStream() { + override fun write(b: ByteArray, off: Int, len: Int) { + if (limit != null && size() + len > limit) throw IOException("disk full") + super.write(b, off, len) + } + + override fun close() { + val written = toByteArray() + node.bytes = if ('t' in mode || written.size >= node.bytes.size) { + written + } else { + written + node.bytes.copyOfRange(written.size, node.bytes.size) + } + } + } + } + + override fun openInput(id: String): InputStream { + guard() + val node = nodes[id]?.takeIf { !it.isDirectory } ?: throw IOException("cannot read $id") + return ByteArrayInputStream(node.bytes) + } + + // region Test helpers + + fun add(parentId: String, name: String, directory: Boolean, text: String? = null): Node { + val node = Node("doc${nextId++}", name, directory, parentId) + if (text != null) node.bytes = text.toByteArray() + nodes[node.id] = node + return node + } + + fun find(path: String): Node? { + var at = nodes.getValue(rootId) + if (path.isEmpty()) return at + for (part in path.split('/')) { + at = nodes.values.firstOrNull { it.parent == at.id && it.name == part } ?: return null + } + return at + } + + fun text(path: String): String? = find(path)?.takeIf { !it.isDirectory }?.bytes?.toString(Charsets.UTF_8) + + fun names(path: String): List { + val dir = find(path) ?: return emptyList() + return nodes.values.filter { it.parent == dir.id }.map { it.name }.sorted() + } + + // endregion + + private fun guard() { + if (!granted) throw IOException("permission lost", SecurityException("revoked")) + } + + private fun Node.doc() = DocumentOps.Doc(id, name, isDirectory) +} + +/** Persisted grants and one [FakeDocumentOps] per tree. */ +class FakeTreeHost : TreeHost { + val persisted = LinkedHashSet() + val released = mutableListOf() + val trees = LinkedHashMap() + var refuse = false + + fun tree(uri: Uri): FakeDocumentOps = trees.getOrPut(uri) { FakeDocumentOps(uri.lastPathSegment ?: "Tree") } + + fun revoke(uri: Uri) { + persisted -= uri + trees[uri]?.granted = false + } + + override fun persistedWritableTrees(): Set = persisted.toSet() + + override fun takePermission(tree: Uri) { + if (refuse) throw SecurityException("no persistable grant offered") + persisted += tree + tree(tree).granted = true + } + + override fun releasePermission(tree: Uri) { + persisted -= tree + released += tree + } + + override fun documents(tree: Uri): DocumentOps = tree(tree) +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/SafTreeWriterTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/SafTreeWriterTest.kt new file mode 100644 index 00000000..d046257d --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/SafTreeWriterTest.kt @@ -0,0 +1,153 @@ +package com.xiangming.wechatbridge.saf + +import com.xiangming.wechatbridge.core.note.NoteDelivery +import com.xiangming.wechatbridge.core.note.NoteDeliveryException +import com.xiangming.wechatbridge.core.note.TreeWriter +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File +import java.io.IOException +import java.time.ZoneId + +class SafTreeWriterTest { + private val ops = FakeDocumentOps() + private val writer = SafTreeWriter(ops) + private val zone: ZoneId = ZoneId.of("Asia/Shanghai") + + private fun fixture(name: String): File { + var dir: File? = File("").absoluteFile + while (dir != null) { + val candidate = File(dir, "ios/Tests/Fixtures/$name") + if (candidate.isFile) return candidate + dir = dir.parentFile + } + error("fixture $name not found above ${File("").absolutePath}") + } + + private fun numbered(name: String, n: Int): String = + if (n == 1) name else name.substringBeforeLast('.') + " $n." + name.substringAfterLast('.') + + @Test + fun createNewRefusesTakenNameWithoutCreatingAnything() { + ops.add(ops.rootId, "a.md", directory = false, text = "old") + assertNull(writer.createNew("", "a.md") { it.write("new".toByteArray()) }) + assertTrue(ops.created.isEmpty()) + assertEquals("old", ops.text("a.md")) + } + + @Test + fun providerRenameIsDeletedAndReportedAsTaken() { + // Someone creates the name between our check and createDocument: SAF answers "a (1).md". + ops.beforeCreate = { parent, name -> if (name == "a.md") ops.add(parent, "a.md", directory = false, text = "theirs") } + assertNull(writer.createNew("", "a.md") { it.write("ours".toByteArray()) }) + assertEquals(listOf("a.md"), ops.names("")) + assertEquals("theirs", ops.text("a.md")) + assertEquals(1, ops.deleted.size) + } + + @Test + fun createUniqueFallsBackToTheNextNumberAfterARename() { + ops.add(ops.rootId, "a.md", directory = false, text = "1") + var raced = false + ops.beforeCreate = { parent, name -> + if (name == "a 2.md" && !raced) { + raced = true + ops.add(parent, "a 2.md", directory = false, text = "2") + } + } + val created = writer.createUnique("", "a.md", ::numbered) { it.write("3".toByteArray()) } + assertEquals("a 3.md", created.path) + assertEquals(listOf("a 2.md", "a 3.md", "a.md"), ops.names("")) + assertEquals("3", ops.text("a 3.md")) + } + + @Test + fun aNameTheProviderAlwaysRewritesFailsInsteadOfLooping() { + ops.renameOnCreate = { it.replace(':', '_') } + assertThrows(IOException::class.java) { writer.createNew("", "a:b.md") { } } + assertTrue(ops.names("").isEmpty()) + } + + @Test + fun replaceTextTruncatesWithWt() { + ops.add(ops.rootId, "note.md", directory = false, text = "a much longer original text") + writer.replaceText("note.md", "short") + assertEquals("short", ops.text("note.md")) + assertEquals(listOf("wt"), ops.outputModes) + } + + @Test + fun removeDeletesOnlyTheFileThisWriterCreated() { + writer.createDirectory("dir") + val mine = writer.createNew("dir", "x.zip") { it.write(1) }!! + // Replaced by another writer under the same name: a different document. + ops.delete(ops.find("dir/x.zip")!!.id) + ops.add(ops.find("dir")!!.id, "x.zip", directory = false, text = "theirs") + writer.remove(mine) + assertEquals("theirs", ops.text("dir/x.zip")) + + // Never a directory, even one at a path it was told about. + writer.remove(TreeWriter.Created("dir", ops.find("dir")!!.id)) + assertNotNull(ops.find("dir")) + + val own = writer.createNew("dir", "y.zip") { it.write(1) }!! + writer.remove(own) + assertNull(ops.find("dir/y.zip")) + writer.remove(own) // already gone: nothing + } + + @Test + fun failedWriteRemovesThePartialFile() { + ops.failWritesAfter = 2 + assertThrows(IOException::class.java) { writer.createNew("", "big.bin") { it.write(ByteArray(10)) } } + assertNull(ops.find("big.bin")) + } + + @Test + fun createDirectoryToleratesExistingAndRejectsAFileInTheWay() { + writer.createDirectories("a/b") + writer.createDirectories("a/b") + assertTrue(writer.isDirectory("a/b")) + assertEquals(listOf("b"), writer.list("a")) + ops.add(ops.find("a")!!.id, "f", directory = false, text = "") + assertThrows(IOException::class.java) { writer.createDirectory("a/f") } + assertThrows(IOException::class.java) { writer.createDirectory("missing/x") } + // A concurrent mkdir: SAF names ours "c (1)"; it is removed and the existing one used. + ops.beforeCreate = { parent, name -> if (name == "c") ops.add(parent, "c", directory = true) } + writer.createDirectory("a/c") + assertEquals(listOf("b", "c", "f"), ops.names("a")) + } + + @Test + fun revokedGrantIsAnInvalidFolder() { + assertTrue(writer.isWritableRoot()) + ops.granted = false + assertFalse(writer.isWritableRoot()) + assertFalse(writer.exists("")) + val error = assertThrows(NoteDeliveryException::class.java) { + NoteDelivery.deliver(listOf(fixture("group-a.zip")), writer, "", "项目群", null, zone = zone) + } + assertEquals(NoteDeliveryException.Reason.INVALID_FOLDER, error.reason) + } + + @Test + fun deliverWritesNoteAndAttachmentsAndMergesTheSecondTime() { + val first = NoteDelivery.deliver(listOf(fixture("group-a.zip")), writer, "", "项目群", "测试场景", zone = zone) + assertEquals(listOf("微信流/项目群的聊天.md"), first) + assertTrue(writer.isDirectory("微信流/附件")) + assertTrue(ops.names("微信流/附件").any { it.endsWith(".zip") }) + val note = ops.text("微信流/项目群的聊天.md")!! + assertTrue(note.contains("项目群")) + + val second = NoteDelivery.deliver(listOf(fixture("group-a-later.zip")), writer, "", "项目群", "测试场景", zone = zone) + assertEquals(listOf("微信流/项目群的聊天.md"), second) + assertEquals(1, ops.names("微信流").count { it.endsWith(".md") }) + assertTrue(ops.text("微信流/项目群的聊天.md")!!.length > note.length) + assertTrue("wt" in ops.outputModes) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/TreeStoreTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/TreeStoreTest.kt new file mode 100644 index 00000000..9537d06d --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/saf/TreeStoreTest.kt @@ -0,0 +1,103 @@ +package com.xiangming.wechatbridge.saf + +import android.app.Application +import android.content.Context +import android.net.Uri +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.core.deliver.TargetKind +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class TreeStoreTest { + private lateinit var app: Application + private val host = FakeTreeHost() + private val vault = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AVault") + private val folder = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3ADocs") + + @Before + fun setUp() { + app = ApplicationProvider.getApplicationContext() + } + + private fun store() = TreeStore(app.getSharedPreferences("trees-test", Context.MODE_PRIVATE), host) + + @Test + fun notChosenUntilGrantedThenPersisted() { + val store = store() + assertEquals(TreeStatus.NOT_CHOSEN, store.status(TargetKind.VAULT)) + assertNull(store.writer(TargetKind.VAULT)) + assertEquals("微信流", store.root(TargetKind.VAULT).effectiveSubfolder) + + assertEquals(TreeStatus.GRANTED, store.grant(TargetKind.VAULT, vault)) + assertTrue(vault in host.persisted) + assertNotNull(store.writer(TargetKind.VAULT)) + assertEquals(TreeStatus.NOT_CHOSEN, store.status(TargetKind.FOLDER)) + + // A new process reads the same root back. + val again = store() + assertEquals(vault, again.root(TargetKind.VAULT).uri) + assertEquals(TreeStatus.GRANTED, again.status(TargetKind.VAULT)) + } + + @Test + fun revokedGrantOrVanishedRootIsLost() { + val store = store() + store.grant(TargetKind.FOLDER, folder) + host.revoke(folder) + assertEquals(TreeStatus.LOST, store.status(TargetKind.FOLDER)) + assertNull(store.writer(TargetKind.FOLDER)) + + // Grant still listed but the provider no longer lets us in. + store.grant(TargetKind.FOLDER, folder) + host.tree(folder).granted = false + assertEquals(TreeStatus.LOST, store.status(TargetKind.FOLDER)) + + // Picking it again recovers. + assertEquals(TreeStatus.GRANTED, store.grant(TargetKind.FOLDER, folder)) + } + + @Test + fun replacingARootReleasesTheOldGrantUnlessStillUsed() { + val store = store() + store.grant(TargetKind.VAULT, vault) + store.grant(TargetKind.FOLDER, vault) + store.grant(TargetKind.FOLDER, folder) + assertTrue(host.released.isEmpty()) // the vault still uses it + store.grant(TargetKind.VAULT, folder) + assertEquals(listOf(vault), host.released) + store.clear(TargetKind.VAULT) + assertEquals(listOf(vault), host.released) // folder still uses it + assertEquals(TreeStatus.NOT_CHOSEN, store.status(TargetKind.VAULT)) + } + + @Test + fun refusedGrantKeepsThePreviousRoot() { + val store = store() + store.grant(TargetKind.VAULT, vault) + host.refuse = true + assertEquals(TreeStatus.LOST, store.grant(TargetKind.VAULT, folder)) + assertEquals(vault, store.root(TargetKind.VAULT).uri) + assertEquals(TreeStatus.GRANTED, store.status(TargetKind.VAULT)) + } + + @Test + fun subfolderAndNameAndKindCheck() { + val store = store() + store.setSubfolder(TargetKind.VAULT, "收件箱/微信") + assertEquals("收件箱/微信", store.root(TargetKind.VAULT).effectiveSubfolder) + assertEquals("收件箱/微信", store().root(TargetKind.VAULT).subfolder) + store.grant(TargetKind.VAULT, vault) + assertEquals(host.tree(vault).nodes.getValue("root").name, store.folderName(TargetKind.VAULT)) + assertThrows(IllegalArgumentException::class.java) { store.status(TargetKind.APP) } + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/detail/DetailViewModelTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/detail/DetailViewModelTest.kt new file mode 100644 index 00000000..16d512e0 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/detail/DetailViewModelTest.kt @@ -0,0 +1,362 @@ +package com.xiangming.wechatbridge.ui.detail + +import com.xiangming.wechatbridge.core.archive.WeChatArchive +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.inbox.LoadStrategy +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareOrigin +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ShareItem +import com.xiangming.wechatbridge.receive.UriImporter +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.InputStream +import java.time.ZoneId +import java.util.UUID +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class DetailViewModelTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var inbox: Inbox + private val shanghai = ZoneId.of("Asia/Shanghai") + + // 不碰真实图片解码:固定回一个尺寸,测试只关心图片挂在哪条消息下。 + // 时区用系统默认:解析聊天时间和显示分组本来就是同一个时区。 + private val loader = DetailLoader(imageBounds = { 400 to 300 }) + + @Before + fun setUp() { + inbox = Inbox(File(temp.root, "files/inbox")) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + // MARK: 聊天记录(group-a.zip) + + @Test + fun groupAMessageCountMatchesFixture() = runTest { + val expected = WeChatArchive.transcript(fixture("group-a.zip"), shanghai)!!.records!!.size + val chat = loadChat(importZip(fixture("group-a.zip"))) + assertEquals(expected, chat.messageCount) + assertEquals(8, chat.messageCount) + assertEquals(expected, chat.items.filterIsInstance().size) + } + + @Test + fun imageSitsUnderItsOwnMessage() = runTest { + val chat = loadChat(importZip(fixture("group-a.zip"))) + val messages = chat.items.filterIsInstance() + + val withImage = messages.filter { m -> m.tokens.any { it is BubbleToken.Image } } + assertEquals(listOf(1), withImage.map { it.index }) + val message = withImage.single() + assertEquals("乙", message.sender) + val image = message.tokens.single() as BubbleToken.Image + assertEquals("微信图片_20261020_1.png", image.name) + val file = image.file!! + assertTrue(file.isFile) + assertEquals(0x89.toByte(), file.readBytes()[0]) + assertEquals(400, image.widthPx) + assertEquals(300, image.heightPx) + } + + @Test + fun otherPlaceholdersBecomeTheirOwnCards() = runTest { + val chat = loadChat(importZip(fixture("group-a.zip"))) + val messages = chat.items.filterIsInstance() + + assertEquals(listOf(BubbleToken.Text("早上好,今天讨论发布计划")), messages[0].tokens) + assertEquals( + BubbleToken.Link("发布清单模板", "https://mp.weixin.qq.com/s/abc123", "mp.weixin.qq.com"), + messages[2].tokens.single(), + ) + assertEquals( + BubbleToken.Channels("产品演示", "https://weixin.qq.com/sph/xyz789"), + messages[3].tokens.single(), + ) + val video = messages[4].tokens.single() as BubbleToken.Video + assertEquals("录屏_1.mp4", video.name) + assertTrue(video.file!!.isFile) + val attachment = messages[5].tokens.single() as BubbleToken.Attachment + assertEquals("需求文档.pdf", attachment.name) + assertEquals("%PDF-1.4\n%%EOF\n", attachment.file!!.readText()) + assertEquals(listOf(BubbleToken.Text("第一行\n第二行")), messages[6].tokens) + } + + @Test + fun unknownPlaceholderIsShownAsWritten() = runTest { + val chat = loadChat(importZip(fixture("group-a.zip"))) + val last = chat.items.filterIsInstance().last() + assertEquals(listOf(BubbleToken.Text("[破涕为笑]")), last.tokens) + } + + @Test + fun dateDividerOpensTheDayAndSenderRepeatsOnlyWhenItChanges() = runTest { + val chat = loadChat(importZip(fixture("group-a.zip"))) + assertTrue(chat.items.first() is ChatItem.DateDivider) + assertEquals(1, chat.items.count { it is ChatItem.DateDivider }) + val messages = chat.items.filterIsInstance() + // 甲 乙 丙 甲 乙 丙 甲 乙:相邻发送者都不同,每条都显示名字。 + assertTrue(messages.all { it.showsSender }) + assertEquals("09:00", messages[0].time.toString()) + assertEquals(chat.items.map { it.key }.toSet().size, chat.items.size) + } + + @Test + fun consecutiveMessagesFromOneSenderShareTheirHeader() = runTest { + val body = buildString { + append("·甲\n2026年10月20日 09:00\n一\n\n·甲\n2026年10月20日 09:01\n二\n\n") + append("·甲\n2026年10月21日 09:02\n三\n") + } + val chat = loadChat(importZip(zipBytes("聊天记录.txt" to body.toByteArray()))) + val shown = chat.items.filterIsInstance().map { it.showsSender } + // 同一天同一发送者:第二条不重复;换了一天要重新显示。 + assertEquals(listOf(true, false, true), shown) + assertEquals(2, chat.items.count { it is ChatItem.DateDivider }) + } + + @Test + fun thousandMessagesAreFlatItemsWithUniqueKeys() = runTest { + val body = buildString { + for (i in 0 until 1000) { + val minute = i % 60 + val hour = 8 + (i / 60) % 10 + append("·${if (i % 2 == 0) "甲" else "乙"}\n2026年10月20日 %02d:%02d\n第 %d 条\n\n".format(hour, minute, i)) + } + } + val chat = loadChat(importZip(zipBytes("聊天记录.txt" to body.toByteArray()))) + assertEquals(1000, chat.messageCount) + assertEquals(chat.items.size, chat.items.map { it.key }.toSet().size) + } + + // MARK: 其它形态 + + @Test + fun nonChatTextArchiveShowsFullText() = runTest { + val expected = WeChatArchive.transcript(fixture("not-wechat.zip"))!!.body + val content = loadContent(importZip(fixture("not-wechat.zip"))) + assertEquals(DetailContent.PlainText(expected), content) + } + + @Test + fun filesOnlyBatchListsItsFiles() = runTest { + val content = loadContent(importZip(fixture("files-only.zip"))) + content as DetailContent.Files + assertEquals(1, content.files.size) + assertEquals("聊天记录.zip", content.files.single().name) + assertNull(content.error) + } + + @Test + fun sharedLinkShowsUrlAndFullText() = runTest { + val importer = UriImporter(inbox, buildVersion = "1", zone = shanghai) + val saved = importer.importBlocking( + listOf(ShareItem.Text("https://example.com/a?b=1\n这是一段分享时附带的完整文字\n第二行", subject = "示例标题")), + collect = false, + ) as ImportOutcome.Saved + // UriImporter 和 iOS 分享扩展一样写 share-origin.json,批次因此是链接批次。 + val entry = entry(saved.batchId) + assertEquals(RelaySummary.Kind.LINK, entry.summary!!.kind) + + val content = loader.load(entry) as DetailContent.Link + assertEquals("https://example.com/a?b=1", content.url) + assertTrue(content.text!!.contains("这是一段分享时附带的完整文字")) + assertTrue(content.text.contains("第二行")) + assertEquals("示例标题", content.title) + // 便签是 public.url,照 iOS RelayDetailView 不算附件。 + assertEquals(0, content.files.size) + } + + @Test + fun sharedTextNoteShowsFullText() = runTest { + val importer = UriImporter(inbox, buildVersion = "1", zone = shanghai) + val saved = importer.importBlocking( + listOf(ShareItem.Text("第一行标题\n第二行 https://example.com")), + collect = false, + ) as ImportOutcome.Saved + // 正文里带 http(s) 链接,按 iOS ShareOrigin.make 记为链接批次,全文仍在。 + val content = loader.load(entry(saved.batchId)) as DetailContent.Link + assertEquals("https://example.com", content.url) + val shown = listOfNotNull(content.title, content.text).joinToString("\n") + assertTrue(shown.contains("第一行标题")) + assertTrue(shown.contains("第二行")) + } + + // MARK: ViewModel + + @Test + fun viewModelLoadsTheBatchOnceAndPublishesItsTitle() = runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + Dispatchers.setMain(dispatcher) + val id = importZip(fixture("group-a.zip")) + val store = store() + store.reload() + advanceUntilIdle() + + val viewModel = DetailViewModel(id.toString(), store.entries, loader, ioDispatcher = dispatcher) + assertTrue(viewModel.state.value.content is DetailContent.Loading) + advanceUntilIdle() + + val state = viewModel.state.value + assertEquals(store.entry(id)!!.summary!!.title, state.title) + val chat = state.content as DetailContent.Chat + assertEquals(8, chat.messageCount) + + // 摘要等后续刷新不会让详情重新加载。 + store.reload() + advanceUntilIdle() + assertTrue(viewModel.state.value.content === chat) + } + + @Test + fun missingBatchShowsDeletedAfterAGraceDelay() = runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + Dispatchers.setMain(dispatcher) + val store = store() + store.reload() + advanceUntilIdle() + + val viewModel = DetailViewModel(UUID.randomUUID().toString(), store.entries, loader, ioDispatcher = dispatcher) + advanceTimeBy(DetailViewModel.MISSING_GRACE_MILLIS - 1) + assertTrue(viewModel.state.value.content is DetailContent.Loading) + advanceUntilIdle() + assertEquals(DetailContent.Missing, viewModel.state.value.content) + } + + @Test + fun malformedBatchIdIsMissingNotACrash() = runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + Dispatchers.setMain(dispatcher) + val store = store() + store.reload() + val viewModel = DetailViewModel("not-a-uuid", store.entries, loader, ioDispatcher = dispatcher) + advanceUntilIdle() + assertEquals(DetailContent.Missing, viewModel.state.value.content) + } + + // MARK: 链接与尺寸 + + @Test + fun onlyHttpAndHttpsLinksAreOpenable() { + assertTrue(DetailLinks.isOpenableUrl("https://example.com/a")) + assertTrue(DetailLinks.isOpenableUrl("http://example.com")) + assertTrue(DetailLinks.isOpenableUrl("HTTPS://example.com")) + assertFalse(DetailLinks.isOpenableUrl("javascript:alert(1)")) + assertFalse(DetailLinks.isOpenableUrl("file:///etc/passwd")) + assertFalse(DetailLinks.isOpenableUrl("intent://scan/#Intent;scheme=zxing;end")) + assertFalse(DetailLinks.isOpenableUrl("content://com.example/x")) + assertFalse(DetailLinks.isOpenableUrl("weixin://dl/chat")) + assertFalse(DetailLinks.isOpenableUrl("https://")) + assertFalse(DetailLinks.isOpenableUrl("example.com")) + assertFalse(DetailLinks.isOpenableUrl("")) + } + + @Test + fun linkRangesFindOnlyHttpLinksInText() { + val text = "看 https://a.com/x?y=1,和 http://b.org。还有 weixin://x" + val found = DetailLinks.linkRanges(text).map { text.substring(it.first, it.last + 1) } + assertEquals(listOf("https://a.com/x?y=1", "http://b.org"), found) + } + + @Test + fun displaySizeFitsTheBoxAndNeverUpscales() { + // density 1:像素即 dp。 + assertEquals(64f to 64f, displaySizeDp(0, 0, 1f)) + assertEquals(100f to 100f, displaySizeDp(100, 100, 1f)) + val (w, h) = displaySizeDp(1100, 1300, 1f) + assertEquals(220f, w, 0.01f) + assertEquals(260f, h, 0.01f) + // 高密度屏:320px 宽在 2× 下是 160dp。 + assertEquals(160f, displaySizeDp(320, 160, 2f).first, 0.01f) + // 细长图至少保留 64dp 的可点击底。 + assertTrue(displaySizeDp(1000, 10, 1f).second >= 64f) + } + + // MARK: helpers + + private fun TestScope.store(): RelayStore = RelayStore( + inbox = inbox, + relayFilesRoot = File(temp.root, "cache/Relay"), + deliveriesDirectory = File(temp.root, "cache/deliveries"), + scope = this, + ioDispatcher = StandardTestDispatcher(testScheduler), + ) + + private fun importZip(file: File): UUID = importZip(file.readBytes()) + + private fun importZip(bytes: ByteArray): UUID { + val importer = UriImporter(inbox, buildVersion = "1", zone = shanghai) + val outcome = importer.importBlocking(listOf(ZipStream(bytes)), collect = false) as ImportOutcome.Saved + return outcome.batchId + } + + private suspend fun TestScope.entry(id: UUID): com.xiangming.wechatbridge.data.RelayEntry { + val store = store() + store.reload() + advanceUntilIdle() + return store.entry(id)!! + } + + private suspend fun TestScope.loadContent(id: UUID): DetailContent = loader.load(entry(id)) + + private suspend fun TestScope.loadChat(id: UUID): DetailContent.Chat = loadContent(id) as DetailContent.Chat + + private fun zipBytes(vararg entries: Pair): ByteArray { + val out = ByteArrayOutputStream() + ZipOutputStream(out, Charsets.UTF_8).use { zip -> + for ((name, bytes) in entries) { + zip.putNextEntry(ZipEntry(name)) + zip.write(bytes) + zip.closeEntry() + } + } + return out.toByteArray() + } + + private class ZipStream(private val bytes: ByteArray) : ShareItem.Stream { + override val mimeType: String = "application/zip" + override val loadStrategy: LoadStrategy = LoadStrategy.FILE_REPRESENTATION + override fun displayName(): String = "聊天记录.zip" + override fun open(): InputStream = ByteArrayInputStream(bytes) + } + + private fun fixture(name: String): File { + var dir: File? = File("").absoluteFile + while (dir != null) { + val candidate = File(dir, "ios/Tests/Fixtures/$name") + if (candidate.isFile) return candidate + dir = dir.parentFile + } + error("fixture $name not found above ${File("").absolutePath}") + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingViewModelTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingViewModelTest.kt new file mode 100644 index 00000000..5d0c0eb5 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/onboarding/OnboardingViewModelTest.kt @@ -0,0 +1,160 @@ +package com.xiangming.wechatbridge.ui.onboarding + +import android.net.Uri +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.data.Preferences +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class OnboardingViewModelTest { + @get:Rule + val temp = TemporaryFolder() + + private class FakeVault(var chosen: String? = null, var refuse: Boolean = false) : OnboardingVault { + override fun chosenName(): String? = chosen + + override fun grant(tree: Uri): String? { + if (refuse) return null + chosen = tree.lastPathSegment.orEmpty() + return chosen + } + } + + @Before + fun setUp() { + Dispatchers.setMain(Dispatchers.Unconfined) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun withVm( + vault: FakeVault = FakeVault(), + block: suspend (OnboardingViewModel, Preferences) -> T, + ): T = runBlocking { + val job = Job() + var vm: OnboardingViewModel? = null + try { + val prefs = Preferences.create(CoroutineScope(Dispatchers.IO + job)) { File(temp.root, "p.preferences_pb") } + vm = OnboardingViewModel(prefs, vault, Dispatchers.Unconfined) + withTimeout(20_000) { block(vm, prefs) } + } finally { + vm?.viewModelScope?.coroutineContext?.get(Job)?.cancelAndJoin() + job.cancel() + job.join() + } + } + + @Test + fun finishMarksOnboardingDoneThenCallsBack() { + withVm { vm, prefs -> + assertFalse(prefs.current().onboardingDone) + var doneWhenCalled: Boolean? = null + vm.finish { doneWhenCalled = runBlocking { prefs.current().onboardingDone } }.join() + assertTrue(prefs.current().onboardingDone) + assertEquals(true, doneWhenCalled) + } + } + + @Test + fun skipAlsoMarksOnboardingDone() { + withVm { vm, prefs -> + var called = false + vm.skip { called = true }.join() + assertTrue(prefs.current().onboardingDone) + assertTrue(called) + } + } + + @Test + fun stepsStartAtFirstAndStopAtBothEnds() { + withVm { vm, _ -> + assertEquals(0, vm.state.value.step) + assertTrue(vm.state.value.isFirst) + vm.back() + assertEquals(0, vm.state.value.step) + + vm.next() + assertEquals(1, vm.state.value.step) + vm.next() + assertEquals(2, vm.state.value.step) + assertTrue(vm.state.value.isLast) + vm.next() + assertEquals(2, vm.state.value.step) + + vm.back() + assertEquals(1, vm.state.value.step) + assertFalse(vm.state.value.isFirst) + assertFalse(vm.state.value.isLast) + } + } + + @Test + fun goToIsClampedIntoRange() { + withVm { vm, _ -> + vm.goTo(99) + assertEquals(OnboardingViewModel.STEP_COUNT - 1, vm.state.value.step) + vm.goTo(-5) + assertEquals(0, vm.state.value.step) + } + } + + @Test + fun existingVaultShowsAsChosen() { + withVm(FakeVault(chosen = "Notes")) { vm, _ -> + assertEquals("Notes", vm.state.value.vaultName) + } + } + + @Test + fun pickingVaultShowsItsNameAndBackingOutChangesNothing() { + withVm { vm, _ -> + assertNull(vm.state.value.vaultName) + assertNull(vm.onVaultPicked(null)) + assertNull(vm.state.value.vaultName) + + vm.onVaultPicked(Uri.parse("content://tree/Vault"))?.join() + assertEquals("Vault", vm.state.value.vaultName) + assertFalse(vm.state.value.vaultFailed) + } + } + + @Test + fun refusedVaultKeepsPreviousChoiceAndFlagsFailure() { + val vault = FakeVault(chosen = "Old") + withVm(vault) { vm, _ -> + vault.refuse = true + vm.onVaultPicked(Uri.parse("content://tree/New"))?.join() + assertEquals("Old", vm.state.value.vaultName) + assertTrue(vm.state.value.vaultFailed) + + vault.refuse = false + vm.onVaultPicked(Uri.parse("content://tree/New"))?.join() + assertEquals("New", vm.state.value.vaultName) + assertFalse(vm.state.value.vaultFailed) + } + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelaySearchBarTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelaySearchBarTest.kt new file mode 100644 index 00000000..a6a2e989 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelaySearchBarTest.kt @@ -0,0 +1,200 @@ +package com.xiangming.wechatbridge.ui.relay + +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.longClick +import androidx.compose.ui.test.onAllNodesWithContentDescription +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTouchInput +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.UUID + +/** + * The search bar as it behaves on screen: the icon opens it, typing narrows the list at once, the + * cross clears, 「收起」 folds it back, and the selection bar borrows the top only while it lasts. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class RelaySearchBarTest { + @get:Rule + val compose = createComposeRule() + + private val chat = previewEntry(previewChat) + private val files = previewEntry(previewFiles, itemNames = listOf("报告.pdf", "截图.png"), collecting = true) + private val entries = listOf(chat, files) + + private var typed = mutableListOf() + + /** + * The screen with the keyword and the selection hoisted, as [RelayViewModel] holds them, + * driven only through the callbacks the screen calls. + */ + private fun show(searchLabel: String = "搜索") { + compose.setContent { + // Hoisted, as the view model holds them: remembered, so typing is not reset by the + // recomposition it causes. + var query by remember { mutableStateOf("") } + var selection by remember { mutableStateOf(emptySet()) } + val shown = entries.filter { it.matchesQuery(query) } + WeChatBridgeTheme { + RelayContent( + state = RelayUiState( + query = query, + entries = shown, + totalCount = entries.size, + selection = selection, + ), + snackbarHostState = SnackbarHostState(), + onFilter = {}, + onQueryChange = { + query = it + typed += it + }, + onOpenEntry = {}, + onToggle = { selection = if (it in selection) selection - it else selection + it }, + onSelectAll = {}, + onClearSelection = { selection = emptySet() }, + onDeliverSelected = {}, + onDeleteSelected = {}, + onOpenCollection = {}, + onDeliverCollection = {}, + onImportFiles = {}, + onImportClipboard = {}, + ) + } + } + compose.onNodeWithContentDescription(searchLabel).performClick() + compose.waitForIdle() + } + + private fun type(text: String) { + compose.onNode(hasSetTextAction()).performTextInput(text) + compose.waitForIdle() + } + + @Test + fun theIconSwapsTheTitleForTheSearchBar() { + show() + + compose.onNodeWithText("中转站").assertDoesNotExist() + compose.onNodeWithText("搜索标题、预览或来源").assertIsDisplayed() + compose.onNodeWithText("收起").assertIsDisplayed() + compose.onNodeWithText("产品讨论群").assertIsDisplayed() + // 搜索入口一打开就收起统计卡,即使关键词还是空的。 + compose.onNodeWithText("待投递").assertDoesNotExist() + compose.onNodeWithText("全部记录").assertDoesNotExist() + } + + @Test + fun typingNarrowsTheListAsYouGo() { + show() + + type("报告") + + assertEquals(listOf("报告"), typed) + compose.onNodeWithText("搜索标题、预览或来源").assertDoesNotExist() + compose.onNodeWithText("产品讨论群").assertDoesNotExist() + compose.onNodeWithText("2 个文件").assertIsDisplayed() + // The filter tabs sit beside the keyword, not instead of it. + compose.onNodeWithText("全部").assertIsDisplayed() + compose.onNodeWithText("多选").assertIsDisplayed() + } + + @Test + fun theCrossClearsTheKeywordAndTheListIsWholeAgain() { + show() + type("报告") + compose.onNodeWithText("产品讨论群").assertDoesNotExist() + + compose.onNodeWithContentDescription("清空搜索词").performClick() + compose.waitForIdle() + + assertEquals(listOf("报告", ""), typed) + compose.onNodeWithText("搜索标题、预览或来源").assertIsDisplayed() + compose.onNodeWithText("产品讨论群").assertIsDisplayed() + compose.onNodeWithText("2 个文件").assertIsDisplayed() + // 清空词仍停留在搜索态,统计卡保持收起;退出搜索后才恢复。 + compose.onNodeWithText("待投递").assertDoesNotExist() + // Nothing left to clear. + compose.onAllNodesWithContentDescription("清空搜索词").assertCountEquals(0) + } + + @Test + fun noMatchNamesTheKeywordAndOffersToClearIt() { + show() + type("季度预算") + + compose.onNodeWithText("没有找到「季度预算」").assertIsDisplayed() + // The filter's empty state, not the search's. + compose.onNodeWithText("没有符合筛选条件的记录").assertDoesNotExist() + + compose.onNodeWithText("清空搜索词").performClick() + compose.waitForIdle() + + compose.onNodeWithText("没有找到「季度预算」").assertDoesNotExist() + compose.onNodeWithText("产品讨论群").assertIsDisplayed() + } + + @Test + fun collapseDropsTheKeywordAndPutsTheTitleBack() { + show() + type("报告") + + compose.onNodeWithText("收起").performClick() + compose.waitForIdle() + + assertEquals(listOf("报告", ""), typed) + compose.onNodeWithText("中转站").assertIsDisplayed() + compose.onNodeWithText("待投递").assertIsDisplayed() + compose.onAllNodesWithText("收起").assertCountEquals(0) + } + + @Test + fun theSelectionBorrowsTheBarAndTheSearchIsBackAfterIt() { + show() + type("报告") + + // A long press on the one match starts selecting: the count bar takes the top. + compose.onNodeWithText("2 个文件").performTouchInput { longClick() } + compose.waitForIdle() + compose.onNodeWithText("已选 1 条").assertIsDisplayed() + compose.onAllNodesWithText("收起").assertCountEquals(0) + + compose.onNodeWithContentDescription("取消多选").performClick() + compose.waitForIdle() + + // Same keyword, same matches, the search bar again. + compose.onNodeWithText("收起").assertIsDisplayed() + compose.onNodeWithText("2 个文件").assertIsDisplayed() + compose.onNodeWithText("产品讨论群").assertDoesNotExist() + } + + @Test + @Config(sdk = [34], qualifiers = "night") + fun searchBarAndItsEmptyStateComposeInDark() { + // The night qualifier brings the default locale with it: these are the values-en strings. + show(searchLabel = "Search") + type("季度预算") + + compose.onNodeWithText("No results for “季度预算”").assertIsDisplayed() + compose.onNodeWithContentDescription("Clear search text").assertIsDisplayed() + compose.onNodeWithText("Collapse").assertIsDisplayed() + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelaySearchTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelaySearchTest.kt new file mode 100644 index 00000000..217cf245 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelaySearchTest.kt @@ -0,0 +1,276 @@ +package com.xiangming.wechatbridge.ui.relay + +import android.os.Looper +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import com.xiangming.wechatbridge.R +import com.xiangming.wechatbridge.core.collection.BatchCollection +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.core.summary.RelaySummary +import com.xiangming.wechatbridge.core.summary.ShareSource +import com.xiangming.wechatbridge.data.RelayEntry +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ShareItem +import com.xiangming.wechatbridge.receive.UriImporter +import com.xiangming.wechatbridge.ui.theme.WeChatBridgeTheme +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import java.io.File +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import java.util.UUID + +/** 中转站关键词实时搜索:纯过滤规则 + RelayViewModel 接线 + 搜索界面组合。 */ +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class RelaySearchTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var inbox: Inbox + private lateinit var importer: UriImporter + private val clock: Clock = Clock.fixed(Instant.parse("2026-11-24T10:00:00Z"), ZoneOffset.UTC) + + @Before + fun setUp() { + inbox = Inbox(File(temp.root, "files/inbox")) + importer = UriImporter(inbox, buildVersion = "1") + } + + private fun entry( + title: String, + preview: List = emptyList(), + source: String = ShareSource.WECHAT, + delivered: Boolean = false, + collecting: Boolean = false, + ): RelayEntry = previewEntry( + summary = RelaySummary( + title = title, + preview = preview, + kind = RelaySummary.Kind.TEXT, + source = source, + ), + targetName = "Claude", + delivered = delivered, + collecting = collecting, + ) + + private fun state( + entries: List, + collections: List = emptyList(), + filter: RelayFilter = RelayFilter.ALL, + query: String = "", + selection: Set = emptySet(), + ) = buildRelayState(entries, collections, filter, selection, importing = false, query = query) + + // region 纯过滤规则 + + @Test + fun blankQueryKeepsEverything() { + val entries = listOf(entry("周报汇总"), entry("购物清单")) + for (q in listOf("", " ")) { + val result = state(entries, query = q) + assertEquals(2, result.entries.size) + assertEquals(q, result.query) + } + } + + @Test + fun titleMatchIgnoresCase() { + val entries = listOf(entry("Project Notes"), entry("购物清单")) + assertEquals(1, state(entries, query = "project").entries.size) + assertEquals("Project Notes", state(entries, query = "PROJECT").entries.single().summary?.title) + } + + @Test + fun previewMatch() { + val entries = listOf(entry("周报汇总", preview = listOf("下周五上线发布")), entry("购物清单")) + assertEquals(1, state(entries, query = "上线").entries.size) + } + + @Test + fun sourceMatch() { + val entries = listOf(entry("甲", source = "GitHub"), entry("乙", source = ShareSource.WECHAT)) + val hits = state(entries, query = "github").entries + assertEquals(1, hits.size) + assertEquals("甲", hits.single().summary?.title) + } + + @Test + fun queryIsTrimmedAndNoMatchHidesEverything() { + val entries = listOf(entry("周报汇总")) + assertEquals(1, state(entries, query = " 周报 ").entries.size) + val miss = state(entries, query = "不存在的关键词") + assertTrue(miss.entries.isEmpty()) + assertTrue(miss.collections.isEmpty()) + // 库里确实有内容,只是被搜索词挡掉:空状态文案由此区分。 + assertEquals(1, miss.totalCount) + assertFalse(miss.isEmpty) + } + + @Test + fun searchStacksWithUndeliveredFilter() { + val entries = listOf( + entry("周报汇总", delivered = true), + entry("周报复盘", delivered = false), + ) + val result = state(entries, filter = RelayFilter.UNDELIVERED, query = "周报") + assertEquals(listOf("周报复盘"), result.entries.map { it.summary?.title }) + assertTrue(result.collections.isEmpty()) + } + + @Test + fun searchStacksWithCollectingFilter() { + val entries = listOf( + entry("周报第一批", collecting = true), + entry("周报第二批", collecting = false), + ) + val result = state(entries, filter = RelayFilter.COLLECTING, query = "周报") + assertEquals(listOf("周报第一批"), result.entries.map { it.summary?.title }) + } + + @Test + fun collectionsMatchByName() { + val weekly = entry("批次一") + val shopping = entry("批次二") + val collections = listOf( + BatchCollection(id = UUID.randomUUID(), name = "周会记录", batchIDs = listOf(weekly.id)), + BatchCollection(id = UUID.randomUUID(), name = "购物清单", batchIDs = listOf(shopping.id)), + ) + val all = state(listOf(weekly, shopping), collections) + assertEquals(2, all.collections.size) + + val hit = state(listOf(weekly, shopping), collections, query = "周会") + assertEquals(listOf("周会记录"), hit.collections.map { it.collection.name }) + // 收集卡按名字匹配;批次卡仍按各自的标题/预览/来源匹配,「批次一/二」不含「周会」故收起。 + assertTrue(hit.entries.isEmpty()) + + val miss = state(listOf(weekly, shopping), collections, query = "投影") + assertTrue(miss.collections.isEmpty()) + assertTrue(miss.entries.isEmpty()) + } + + @Test + fun selectionOfVisibleEntrySurvivesSearch() { + val chat = entry("产品讨论群") + val link = entry("分享的链接") + val result = state(listOf(chat, link), query = "产品", selection = setOf(chat.id, link.id)) + // 选择集按全量条目保留:被搜索词挡掉的已选项仍计入多选底栏。 + assertEquals(setOf(chat.id, link.id), result.selection) + } + + // endregion + + // region RelayViewModel 实时搜索 + + @Test + fun viewModelQueryFiltersLiveEntries() = runTest { + save("周报汇总\n下周五上线") + save("购物清单\n牛奶和鸡蛋") + val store = store() + store.reload() + advanceUntilIdle() + shadowOf(Looper.getMainLooper()).idle() + + val viewModel = RelayViewModel(store, importer, this) + val seen = mutableListOf() + val job = launch { viewModel.state.collect { seen += it } } + shadowOf(Looper.getMainLooper()).idle() + runCurrent() + assertEquals(2, viewModel.state.value.entries.size) + + viewModel.setQuery("周报") + shadowOf(Looper.getMainLooper()).idle() + runCurrent() + assertEquals(listOf("周报汇总"), viewModel.state.value.entries.map { it.summary?.title }) + assertTrue(seen.any { it.query == "周报" && it.entries.size == 1 }) + + viewModel.setQuery("") + shadowOf(Looper.getMainLooper()).idle() + runCurrent() + assertEquals(2, viewModel.state.value.entries.size) + job.cancel() + } + + private fun TestScope.store(): RelayStore = RelayStore( + inbox = inbox, + relayFilesRoot = File(temp.root, "cache/Relay"), + deliveriesDirectory = File(temp.root, "cache/deliveries"), + scope = this, + ioDispatcher = StandardTestDispatcher(testScheduler), + clock = clock, + ) + + private fun save(text: String): UUID = + (importer.importBlocking(listOf(ShareItem.Text(text)), collect = false) as ImportOutcome.Saved).batchId + + // endregion + + // region 界面组合 + + @Test + fun searchEmptyStateComposes() { + val activity = compose { + RelayContent( + state = RelayUiState(totalCount = 2, query = "不存在的关键词"), + snackbarHostState = remember { SnackbarHostState() }, + onFilter = {}, + onQueryChange = {}, + onOpenEntry = {}, + onToggle = {}, + onSelectAll = {}, + onClearSelection = {}, + onDeliverSelected = {}, + onDeleteSelected = {}, + onOpenCollection = {}, + onDeliverCollection = {}, + onOpenScenes = {}, + onOpenSettings = {}, + onImportFiles = {}, + onImportClipboard = {}, + ) + } + // 组合不崩溃即通过;空状态文案由 MissingTranslation 与字符串资源保证。 + assertTrue(activity.resources.getString(R.string.relay_search_empty_title).isNotEmpty()) + } + + @Test + fun searchBarComposesWithQueryAndClearAction() { + compose { + WeChatBridgeTheme { + RelaySearchBar(query = "周报", onQueryChange = {}, onCollapse = {}) + } + } + } + + private fun compose(content: @Composable () -> Unit): ComponentActivity { + val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup() + val activity = controller.get() + activity.setContent { WeChatBridgeTheme { content() } } + shadowOf(Looper.getMainLooper()).idle() + return activity + } + + // endregion +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelayViewModelSearchTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelayViewModelSearchTest.kt new file mode 100644 index 00000000..7d445dfb --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/relay/RelayViewModelSearchTest.kt @@ -0,0 +1,208 @@ +package com.xiangming.wechatbridge.ui.relay + +import android.os.Looper +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.core.inbox.Inbox +import com.xiangming.wechatbridge.data.RelayStore +import com.xiangming.wechatbridge.receive.ImportOutcome +import com.xiangming.wechatbridge.receive.ShareItem +import com.xiangming.wechatbridge.receive.UriImporter +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.io.File +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import java.util.UUID + +/** + * The keyword against the real relay: what [RelayViewModel.setQuery] does to the state the list + * shows, on its own and together with the filter tabs and the multi-selection. + */ +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class RelayViewModelSearchTest { + @get:Rule + val temp = TemporaryFolder() + + private val clock: Clock = Clock.fixed(Instant.parse("2026-11-24T10:00:00Z"), ZoneOffset.UTC) + private val viewModels = mutableListOf() + private lateinit var inbox: Inbox + private lateinit var importer: UriImporter + + @Before + fun setUp() { + inbox = Inbox(File(temp.root, "files/inbox")) + importer = UriImporter(inbox, buildVersion = "1") + } + + @After + fun tearDown() { + viewModels.forEach { it.viewModelScope.cancel() } + } + + @Test + fun keywordNarrowsByTitleOrPreviewInEitherCase() = runTest { + val rig = relay("周报汇总\n下周五上线发布", "Project Notes\nAction items", "旅行清单\n护照") + val state = rig.viewModel.state + assertEquals(3, state.value.totalCount) + assertEquals("", state.value.query) + + type(rig, "notes") + assertEquals(listOf("Project Notes"), titles(rig)) + assertEquals("notes", state.value.query) + + type(rig, "NOTES") + assertEquals(listOf("Project Notes"), titles(rig)) + + // A preview line, not a title. + type(rig, "上线") + assertEquals(listOf("周报汇总"), titles(rig)) + + type(rig, "不存在的关键词") + assertTrue(titles(rig).isEmpty()) + // The relay still holds everything: this is the search's empty state, not the relay's. + assertEquals(3, state.value.totalCount) + assertFalse(state.value.isEmpty) + + type(rig, " ") + assertEquals(3, titles(rig).size) + } + + @Test + fun aBatchArrivingUnderAKeywordShowsOnlyIfItMatches() = runTest { + val rig = relay("周报汇总\n第一批") + type(rig, "周报") + assertEquals(listOf("周报汇总"), titles(rig)) + + val unrelated = save("会议纪要\n不相关") + val matching = save("周报复盘\n第二批") + rig.store.reload() + drain() + withTimeout(15_000) { + rig.store.entries.first { list -> listOf(unrelated, matching).all { id -> list.any { it.id == id && it.summary != null } } } + } + drain() + + assertEquals(3, rig.viewModel.state.value.totalCount) + assertEquals(setOf("周报复盘", "周报汇总"), titles(rig).toSet()) + } + + @Test + fun keywordStacksWithTheFilterTabs() = runTest { + val rig = relay("周报汇总", "周报复盘", "会议纪要") + type(rig, "周报") + assertEquals(2, titles(rig).size) + + // 「收集中」 has nothing here; the keyword waits unchanged behind it. + tab(rig, RelayFilter.COLLECTING) + assertTrue(titles(rig).isEmpty()) + assertEquals(RelayFilter.COLLECTING, rig.viewModel.state.value.filter) + assertEquals("周报", rig.viewModel.state.value.query) + + tab(rig, RelayFilter.ALL) + assertEquals(2, titles(rig).size) + } + + @Test + fun selectAllTakesTheMatchesAndTheSelectionOutlivesTheKeyword() = runTest { + val rig = relay("周报汇总", "周报复盘", "会议纪要") + type(rig, "周报") + val matches = rig.viewModel.state.value.entries.map { it.id }.toSet() + assertEquals(2, matches.size) + rig.viewModel.selectAll() + assertEquals(matches, rig.viewModel.state.value.selection) + assertTrue(rig.viewModel.state.value.selecting) + + // Another keyword hides the picked cards; they stay picked, as the bar's count says. + type(rig, "会议") + assertEquals(listOf("会议纪要"), titles(rig)) + assertEquals(matches, rig.viewModel.state.value.selection) + + // 「全选」 replaces the selection with what is on screen: under a keyword, the matches only. + val visible = rig.viewModel.state.value.entries.map { it.id }.toSet() + rig.viewModel.selectAll() + drain() + assertEquals(visible, rig.viewModel.state.value.selection) + + // Switching tabs is still the one thing that drops a selection, keyword or not. + tab(rig, RelayFilter.UNDELIVERED) + assertTrue(rig.viewModel.state.value.selection.isEmpty()) + } + + // region Helpers + + private class Rig(val store: RelayStore, val viewModel: RelayViewModel) + + /** Imports each text as its own batch (first line: title, rest: preview) and starts showing the list. */ + private suspend fun TestScope.relay(vararg texts: String): Rig { + val ids = texts.map { save(it) } + val store = RelayStore( + inbox = inbox, + relayFilesRoot = File(temp.root, "cache/Relay"), + deliveriesDirectory = File(temp.root, "cache/deliveries"), + scope = this, + ioDispatcher = StandardTestDispatcher(testScheduler), + clock = clock, + ) + store.reload() + drain() + withTimeout(15_000) { + store.entries.first { list -> ids.all { id -> list.any { it.id == id && it.summary != null } } } + } + drain() + + val viewModel = RelayViewModel(store, importer, this).also { viewModels += it } + // The list is only built while someone is looking. + backgroundScope.launch { viewModel.state.collect { } } + drain() + return Rig(store, viewModel) + } + + /** The view model folds on the main dispatcher: type, then let the main looper deliver. */ + private fun TestScope.type(rig: Rig, keyword: String) { + rig.viewModel.setQuery(keyword) + drain() + } + + private fun TestScope.tab(rig: Rig, filter: RelayFilter) { + rig.viewModel.setFilter(filter) + drain() + } + + private fun save(text: String): UUID = + (importer.importBlocking(listOf(ShareItem.Text(text)), collect = false) as ImportOutcome.Saved).batchId + + /** The store's work on the test scheduler, then what it published, on main. */ + private fun TestScope.drain() { + advanceUntilIdle() + shadowOf(Looper.getMainLooper()).idle() + runCurrent() + shadowOf(Looper.getMainLooper()).idle() + } + + private fun titles(rig: Rig): List = rig.viewModel.state.value.entries.mapNotNull { it.summary?.title } + + // endregion +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesViewModelTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesViewModelTest.kt new file mode 100644 index 00000000..ce0f8c27 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/scenes/ScenesViewModelTest.kt @@ -0,0 +1,392 @@ +package com.xiangming.wechatbridge.ui.scenes + +import com.xiangming.wechatbridge.core.scene.AgentId +import com.xiangming.wechatbridge.core.scene.GroupName +import com.xiangming.wechatbridge.core.scene.SceneJson +import com.xiangming.wechatbridge.core.scene.SceneSettings +import com.xiangming.wechatbridge.core.scene.WeChatScene +import com.xiangming.wechatbridge.data.SceneStore +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.After +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.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class ScenesViewModelTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var dir: File + private lateinit var store: SceneStore + private lateinit var vm: ScenesViewModel + + @Before + fun setUp() { + val dispatcher = UnconfinedTestDispatcher() + Dispatchers.setMain(dispatcher) + dir = File(temp.root, "files") + store = SceneStore(dir) + vm = ScenesViewModel(store, dispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun scene(id: String) = vm.state.value.let { s -> (s.official + s.mine).first { it.id == id } } + private fun reloaded() = SceneStore(dir).current() + + // MARK: 开关(iOS 的坑:关掉之后必须还能再打开) + + @Test + fun loadsOfficialAndMineGroups() { + val state = vm.state.value + assertTrue(state.loaded) + assertTrue(state.official.isNotEmpty()) + assertTrue(state.official.all { it.isOfficial }) + assertTrue(state.mine.isEmpty()) + } + + @Test + fun turningAnOfficialSceneOffThenOnAgainWorks() { + val id = vm.state.value.official.first().id + vm.setEnabled(id, true) + assertTrue(scene(id).enabled) + + vm.setEnabled(id, false) + assertFalse(scene(id).enabled) + // 关掉的场景仍在列表里,才有得开。 + assertTrue(vm.state.value.official.any { it.id == id }) + assertFalse(reloaded().settings.scenes.first { it.id == id }.enabled) + assertNull(store.settings.value.scene(id)) + + vm.setEnabled(id, true) + assertTrue(scene(id).enabled) + assertTrue(reloaded().settings.scenes.first { it.id == id }.enabled) + assertNotNull(store.settings.value.scene(id)) + } + + @Test + fun turningMySceneOffThenOnAgainWorks() { + vm.startNew() + vm.updateDraft { it.copy(name = "周报", instruction = "总结") } + vm.saveDraft() + val id = vm.state.value.mine.single().id + assertTrue(scene(id).enabled) + + vm.setEnabled(id, false) + assertFalse(scene(id).enabled) + vm.setEnabled(id, true) + assertTrue(scene(id).enabled) + assertEquals(listOf(id), store.settings.value.enabledScenes.map { it.id }.filter { it == id }) + } + + // MARK: 编辑 + + @Test + fun newSceneIsAddedEnabledWithParsedKeywordsAndTargets() { + vm.startNew() + assertTrue(vm.state.value.editor!!.isNew) + assertFalse(vm.state.value.editor!!.canSave) + vm.updateDraft { + it.copy( + name = " 项目群日报 ", + instruction = "整理成日报", + keywords = "项目,日报, 周会、 ,", + agents = setOf(AgentId.CLAUDE, AgentId.DOUBAO), + ) + } + assertTrue(vm.state.value.editor!!.canSave) + vm.saveDraft() + + assertNull(vm.state.value.editor) + val saved = vm.state.value.mine.single() + assertEquals("项目群日报", saved.name) + assertTrue(saved.enabled) + assertFalse(saved.isOfficial) + assertEquals(listOf("项目", "日报", "周会"), saved.keywords) + assertEquals(listOf(AgentId.CLAUDE, AgentId.DOUBAO), saved.compatibleAgents) + assertEquals(saved, reloaded().settings.scenes.first { it.id == saved.id }) + } + + @Test + fun blankNameOrNoTargetCannotBeSaved() { + vm.startNew() + vm.updateDraft { it.copy(name = " ") } + vm.saveDraft() + assertTrue(vm.state.value.mine.isEmpty()) + assertNotNull(vm.state.value.editor) + + vm.updateDraft { it.copy(name = "x", agents = emptySet()) } + vm.saveDraft() + assertTrue(vm.state.value.mine.isEmpty()) + } + + @Test + fun editingKeepsTheSwitchAndOtherFields() { + val original = WeChatScene( + name = "旧名", instruction = "旧", outputSpec = "格式", enabled = true, + author = "我", requiredSkillIDs = listOf("skill.a"), + ) + store.setSettings(store.current().settings.add(original)) + vm = ScenesViewModel(store, Dispatchers.Main) + vm.setEnabled(original.id, false) + + vm.startEdit(original.id) + vm.updateDraft { it.copy(name = "新名", instruction = "新") } + vm.saveDraft() + + val saved = vm.state.value.mine.single() + assertEquals("新名", saved.name) + assertEquals("新", saved.instruction) + assertFalse(saved.enabled) + assertEquals("我", saved.author) + assertEquals(listOf("skill.a"), saved.requiredSkillIDs) + } + + @Test + fun officialSceneIsReadOnlyButCanBeCopied() { + val official = vm.state.value.official.first() + vm.startEdit(official.id) + val draft = vm.state.value.editor!! + assertTrue(draft.isOfficial) + assertFalse(draft.canSave) + vm.saveDraft() + vm.delete(official.id) + assertEquals(official, scene(official.id)) + + vm.copyOfficial(official.id) + assertNull(vm.state.value.editor) + val copy = vm.state.value.mine.single() + assertNotEquals(official.id, copy.id) + assertTrue(copy.enabled) + assertFalse(copy.isOfficial) + assertEquals(official.instruction, copy.instruction) + assertEquals(ScenesNotice.Copied(copy.name), vm.state.value.notice) + } + + private fun assertNotEquals(a: Any, b: Any) = assertTrue("$a == $b", a != b) + + @Test + fun deleteRemovesMySceneAndItsGroupBindings() { + vm.startNew() + vm.updateDraft { it.copy(name = "要删的", instruction = "x") } + vm.saveDraft() + val doomed = vm.state.value.mine.single().id + val official = vm.state.value.official.first().id + store.bind("产品群", listOf(doomed, official), setOf("甲")) + + vm.delete(doomed) + + assertTrue(vm.state.value.mine.isEmpty()) + assertEquals(listOf(official), vm.state.value.groups.single().scenes.map { it.id }) + assertTrue(reloaded().settings.scenes.none { it.id == doomed }) + } + + // MARK: 导入导出 + + @Test + fun importsV1AndV2PackagesFromMacTests() { + val v1 = """ + { + "schemaVersion": 1, + "id": "example.v1", + "name": "旧任务", + "version": "1.0.0", + "instruction": "整理", + "outputSpec": "输出" + } + """.trimIndent() + val v2 = """ + { + "schemaVersion": 2, + "id": "example.v2", + "name": "新任务", + "version": "1.0.0", + "instruction": "整理", + "outputSpec": "输出", + "requiredSkillIDs": ["wechatbridge.wechat-article-extract"], + "compatibleAgents": ["chatGPTCodex"], + "isOfficial": true + } + """.trimIndent() + + vm.importJson(listOf(v1, v2)) + + assertEquals(ScenesNotice.Imported(2), vm.state.value.notice) + val v1Scene = scene("example.v1") + assertEquals("旧任务", v1Scene.name) + assertTrue(v1Scene.enabled) + assertEquals(AgentId.allCases, v1Scene.compatibleAgents) + val v2Scene = scene("example.v2") + assertEquals(listOf(AgentId.CHATGPT_CODEX), v2Scene.compatibleAgents) + assertTrue(v2Scene.enabled) + assertTrue(reloaded().settings.scenes.any { it.id == "example.v1" && it.enabled }) + } + + @Test + fun importsMacExportedArrayWithEscapedSlashesAndSortedKeys() { + // Mac / iOS 的 ScenePackage.encoder():美化、键排序、"/" 转义。 + val export = """ + [ + { + "applicability" : "站会纪要", + "author" : "小明", + "compatibleAgents" : [ + "claude", + "weSight" + ], + "id" : "6C0B3F44-2D3E-4C4B-9E64-3E5E3F6E7A10", + "instruction" : "按 2026\/11\/25 的格式整理", + "isOfficial" : false, + "keywords" : [ + "站会" + ], + "name" : "站会", + "outputSpec" : "列表", + "requiredSkillIDs" : [], + "schemaVersion" : 3, + "version" : "1.2.0" + }, + { + "id" : "B", + "instruction" : "i", + "name" : "第二个", + "schemaVersion" : 3, + "version" : "1.0.0" + } + ] + """.trimIndent() + + vm.importJson(listOf(export)) + + assertEquals(ScenesNotice.Imported(2), vm.state.value.notice) + val first = scene("6C0B3F44-2D3E-4C4B-9E64-3E5E3F6E7A10") + assertEquals("站会", first.name) + assertEquals("站会纪要", first.summary) + assertEquals("1.2.0", first.packageVersion) + assertEquals("按 2026/11/25 的格式整理", first.instruction) + assertEquals(listOf(AgentId.CLAUDE, AgentId.WE_SIGHT), first.compatibleAgents) + assertTrue(first.enabled) + assertEquals("", scene("B").outputSpec) + assertEquals(2, vm.state.value.mine.size) + } + + @Test + fun importingAgainOverwritesContentAndTurnsTheSceneOn() { + val json = { name: String -> + """{"schemaVersion":3,"id":"dup","name":"$name","version":"1.0.0","instruction":"i","outputSpec":"o"}""" + } + vm.importJson(listOf(json("第一版"))) + vm.setEnabled("dup", false) + + vm.importJson(listOf(json("第二版"))) + + assertEquals(1, vm.state.value.mine.size) + assertEquals("第二版", scene("dup").name) + assertTrue(scene("dup").enabled) + } + + @Test + fun badImportChangesNothing() { + val good = """{"schemaVersion":3,"id":"ok","name":"好","version":"1","instruction":"i","outputSpec":"o"}""" + val before = store.settings.value + + vm.importJson(listOf("not json")) + assertTrue(vm.state.value.notice is ScenesNotice.ImportFailed) + assertEquals(before, store.settings.value) + + // 一个坏、一个好:整体失败,好的那个也不进来。 + vm.importJson(listOf(good, """{"schemaVersion":3,"id":"bad"}""")) + assertTrue(vm.state.value.notice is ScenesNotice.ImportFailed) + assertEquals(before, store.settings.value) + assertFalse(File(dir, SceneStore.SETTINGS_FILE).exists()) + } + + @Test + fun exportThenImportRoundTripsMyScenes() { + assertNull(vm.exportText()) + vm.startNew() + vm.updateDraft { + it.copy(name = "往返", summary = "说明", instruction = "整理 {{skill:wechatbridge.wechat-article-extract}}", keywords = "a,b") + } + vm.saveDraft() + val mine = vm.state.value.mine.single() + + val text = vm.exportText()!! + assertEquals(1, vm.exportCount()) + assertEquals(listOf(mine.id), SceneJson.decodePackages(text).map { it.id }) + // 官方场景不导出。 + assertTrue(SceneJson.decodePackages(text).none { it.isOfficial }) + + val other = ScenesViewModel(SceneStore(File(temp.root, "other")), Dispatchers.Main) + other.importJson(listOf(text)) + val imported = other.state.value.mine.single() + assertEquals(mine.id, imported.id) + assertEquals("往返", imported.name) + assertEquals(listOf("a", "b"), imported.keywords) + assertEquals(mine.instruction, imported.instruction) + assertEquals(mine.compatibleAgents, imported.compatibleAgents) + assertTrue(imported.enabled) + } + + // MARK: 群绑定 + + @Test + fun groupsListBoundScenesAndCanBeUnbound() { + val ids = vm.state.value.official.take(2).map { it.id } + store.bind("产品群", ids, setOf("甲", "乙")) + store.bind("空绑定群", emptyList(), setOf("丙")) + store.rememberGroup("只记住的群", ids[0], setOf("丁"), null) + + val groups = vm.state.value.groups + assertEquals(listOf("产品群"), groups.map { it.displayName }) + assertEquals(ids, groups.single().scenes.map { it.id }) + assertTrue(groups.single().scenes.all { it.name != null }) + + vm.unbind("产品群", ids[0]) + assertEquals(listOf(ids[1]), vm.state.value.groups.single().scenes.map { it.id }) + assertEquals(listOf(ids[1]), reloaded().memories[GroupName.normalize("产品群")]!!.boundSceneIDs) + // 群的发言人记忆不受影响。 + assertEquals(setOf("甲", "乙"), reloaded().memories[GroupName.normalize("产品群")]!!.senders) + + vm.unbindAll("产品群") + assertTrue(vm.state.value.groups.isEmpty()) + } + + @Test + fun boundDisabledAndMissingScenesAreMarked() { + val official = vm.state.value.official.first() + vm.setEnabled(official.id, false) + store.bind("群", listOf(official.id, "gone"), emptySet()) + + val scenes = vm.state.value.groups.single().scenes + assertEquals(BoundScene(official.id, official.name, false), scenes[0]) + assertEquals(BoundScene("gone", null, false), scenes[1]) + } + + @Test + fun parseKeywordsSplitsOnAllThreeSeparators() { + assertEquals(listOf("a", "b", "c", "d"), ScenesViewModel.parseKeywords(" a,b,c、 d ,, ")) + assertTrue(ScenesViewModel.parseKeywords(" ").isEmpty()) + assertEquals(SceneSettings.standardOutputSpec, SceneDraft().outputSpec) + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsViewModelTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsViewModelTest.kt new file mode 100644 index 00000000..f58142d4 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/settings/SettingsViewModelTest.kt @@ -0,0 +1,224 @@ +package com.xiangming.wechatbridge.ui.settings + +import android.app.Application +import android.content.ComponentName +import android.content.Context +import android.content.pm.PackageManager +import android.net.Uri +import androidx.lifecycle.viewModelScope +import androidx.test.core.app.ApplicationProvider +import com.xiangming.wechatbridge.core.deliver.TargetKind +import com.xiangming.wechatbridge.data.Preferences +import com.xiangming.wechatbridge.saf.FakeTreeHost +import com.xiangming.wechatbridge.saf.TreeStatus +import com.xiangming.wechatbridge.saf.TreeStore +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.ByteArrayOutputStream +import java.io.File +import java.time.Instant + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class SettingsViewModelTest { + @get:Rule + val temp = TemporaryFolder() + + private lateinit var app: Application + private val host = FakeTreeHost() + private val vaultUri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AVault") + + /** 内存里的入口别名状态,用来在不依赖 Robolectric 包管理器时测「最后一个不能关」。 */ + private class FakeEntries(var save: Boolean = true, var collect: Boolean = true) : EntryComponents { + override fun isEnabled(entry: ShareEntry) = if (entry == ShareEntry.SAVE) save else collect + override fun setEnabled(entry: ShareEntry, enabled: Boolean) { + if (entry == ShareEntry.SAVE) save = enabled else collect = enabled + } + } + + private val info = AppInfo("1.2.3", 45, "14", 34, "Test Device") + + @Before + fun setUp() { + Dispatchers.setMain(Dispatchers.Unconfined) + app = ApplicationProvider.getApplicationContext() + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun withVm( + entries: EntryComponents = PackageEntryComponents(app), + records: File = File(temp.root, "diagnostics"), + block: suspend (SettingsViewModel, Preferences, TreeStore) -> T, + ): T = runBlocking { + val job = Job() + var vm: SettingsViewModel? = null + try { + val prefs = Preferences.create(CoroutineScope(Dispatchers.IO + job)) { File(temp.root, "p.preferences_pb") } + val trees = TreeStore(app.getSharedPreferences("settings-test-${System.nanoTime()}", Context.MODE_PRIVATE), host) + vm = SettingsViewModel(prefs, trees, entries, records, info, Dispatchers.IO, { Instant.parse("2026-01-01T00:00:00Z") }) + withTimeout(20_000) { + vm.state.first { it.loaded } + block(vm, prefs, trees) + } + } finally { + vm?.viewModelScope?.coroutineContext?.get(Job)?.cancelAndJoin() + job.cancel() + job.join() + } + } + + private fun state(alias: ShareEntry): Int = + app.packageManager.getComponentEnabledSetting(ComponentName(app.packageName, alias.className)) + + @Test + fun retentionDaysPersists() { + withVm { vm, prefs, _ -> + assertEquals(Preferences.DEFAULT_RETENTION_DAYS, vm.state.first().retentionDays) + vm.setRetentionDays(30) + assertEquals(30, vm.state.first { it.retentionDays == 30 }.retentionDays) + assertEquals(30, prefs.retentionDays.first()) + + vm.setRetentionDays(0) // 从不 + vm.state.first { it.retentionDays == 0 } + assertEquals(0, prefs.current().retentionDays) + } + } + + @Test + fun disablingSaveEntryDisablesTheAlias() { + withVm { vm, _, _ -> + assertTrue(vm.state.value.saveEntryEnabled) + assertTrue(vm.setEntryEnabled(ShareEntry.SAVE, false)) + assertEquals(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, state(ShareEntry.SAVE)) + assertFalse(vm.state.value.saveEntryEnabled) + assertTrue(vm.state.value.collectEntryEnabled) + + assertTrue(vm.setEntryEnabled(ShareEntry.SAVE, true)) + assertEquals(PackageManager.COMPONENT_ENABLED_STATE_ENABLED, state(ShareEntry.SAVE)) + assertTrue(vm.state.value.saveEntryEnabled) + } + } + + @Test + fun theTwoEntriesCannotBothBeOff() { + withVm { vm, _, _ -> + assertTrue(vm.setEntryEnabled(ShareEntry.SAVE, false)) + assertTrue(vm.state.value.isLastEntry(ShareEntry.COLLECT)) + + assertFalse(vm.setEntryEnabled(ShareEntry.COLLECT, false)) + assertEquals(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, state(ShareEntry.SAVE)) + assertTrue(vm.state.value.collectEntryEnabled) + assertEquals(SettingsMessage.LAST_ENTRY, vm.state.value.message) + assertNotDisabled(ShareEntry.COLLECT) + + vm.consumeMessage() + assertEquals(null, vm.state.value.message) + } + } + + private fun assertNotDisabled(entry: ShareEntry) { + assertFalse(state(entry) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) + } + + @Test + fun lastEntryGuardAlsoHoldsForTheOtherDirection() { + val entries = FakeEntries(save = true, collect = false) + withVm(entries = entries) { vm, _, _ -> + assertTrue(vm.state.value.isLastEntry(ShareEntry.SAVE)) + assertFalse(vm.setEntryEnabled(ShareEntry.SAVE, false)) + assertTrue(entries.save) + } + } + + @Test + fun grantingAFolderShowsItsNameAndClearingForgetsIt() { + withVm { vm, _, trees -> + assertEquals(TreeStatus.NOT_CHOSEN, vm.state.value.vault.status) + + vm.pickTree(TargetKind.VAULT, vaultUri) + val granted = vm.state.first { it.vault.status == TreeStatus.GRANTED && it.vault.name != null }.vault + assertEquals(TreeStatus.GRANTED, granted.status) + assertEquals(vaultUri, trees.root(TargetKind.VAULT).uri) + assertEquals(TreeStatus.NOT_CHOSEN, vm.state.value.folder.status) + + vm.setSubfolder(TargetKind.VAULT, "笔记") + assertEquals("笔记", vm.state.value.vault.subfolder) + + vm.clearTree(TargetKind.VAULT) + vm.state.first { it.vault.status == TreeStatus.NOT_CHOSEN } + assertTrue(vaultUri in host.released) + } + } + + @Test + fun refusedGrantReportsAMessage() { + host.refuse = true + withVm { vm, _, _ -> + vm.pickTree(TargetKind.FOLDER, vaultUri) + assertEquals(SettingsMessage.FOLDER_REFUSED, vm.state.first { it.message != null }.message) + assertEquals(TreeStatus.NOT_CHOSEN, vm.state.value.folder.status) + } + } + + @Test + fun revokedGrantShowsAsLostAfterRefresh() { + withVm { vm, _, trees -> + trees.grant(TargetKind.FOLDER, vaultUri) + vm.refresh() + vm.state.first { it.folder.status == TreeStatus.GRANTED } + host.revoke(vaultUri) + vm.refresh() + vm.state.first { it.folder.status == TreeStatus.LOST } + } + } + + @Test + fun diagnosticsReportHasHeaderAndRecords() { + val records = File(temp.root, "diagnostics").also { it.mkdirs() } + File(records, "ok-AAA.json").writeText("{\"succeeded\":true}") + File(records, ".hidden.tmp").writeText("skip me") + withVm(records = records) { vm, _, _ -> + val out = ByteArrayOutputStream() + vm.exportDiagnostics { out } + assertEquals(SettingsMessage.EXPORT_OK, vm.state.first { it.message != null }.message) + val text = out.toString(Charsets.UTF_8) + assertTrue(text.contains("version: 1.2.3 (45)")) + assertTrue(text.contains("retentionDays: 7")) + assertTrue(text.contains("--- ok-AAA.json ---")) + assertTrue(text.contains("{\"succeeded\":true}")) + assertFalse(text.contains("skip me")) + } + } + + @Test + fun exportFailureWhenNoStream() { + withVm { vm, _, _ -> + vm.exportDiagnostics { null } + assertEquals(SettingsMessage.EXPORT_FAILED, vm.state.first { it.message != null }.message) + } + } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsViewModelTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsViewModelTest.kt new file mode 100644 index 00000000..4eba0bae --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/settings/TargetsViewModelTest.kt @@ -0,0 +1,247 @@ +package com.xiangming.wechatbridge.ui.settings + +import androidx.lifecycle.viewModelScope +import com.xiangming.wechatbridge.core.deliver.BuiltInTargets +import com.xiangming.wechatbridge.core.deliver.CustomTargetSpec +import com.xiangming.wechatbridge.core.deliver.DeclaredReceiver +import com.xiangming.wechatbridge.core.deliver.DeliveryFormat +import com.xiangming.wechatbridge.core.deliver.MimeKind +import com.xiangming.wechatbridge.core.deliver.SendAction +import com.xiangming.wechatbridge.core.deliver.TargetProfile +import com.xiangming.wechatbridge.data.Preferences +import com.xiangming.wechatbridge.deliver.Resolution +import com.xiangming.wechatbridge.deliver.ShareableApp +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.After +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.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class TargetsViewModelTest { + @get:Rule + val temp = TemporaryFolder() + + private val localSend = "org.localsend.localsend_app" + + private class FakeCatalog(private val installed: Set) : TargetCatalog { + override fun resolution(profile: TargetProfile): Resolution = when { + profile.packageNames.isEmpty() -> Resolution.NotAnApp + profile.packageNames.any { it in installed } -> Resolution.Installed(profile.packageNames.first(), null, false) + else -> Resolution.NotInstalled(profile.packageNames) + } + + override fun shareableApps(): List = + listOf(ShareableApp("com.anthropic.claude", "Claude"), ShareableApp("org.localsend.localsend_app", "LocalSend")) + + override fun customSpec(packageName: String): CustomTargetSpec? = + if (packageName !in installed) { + null + } else { + CustomTargetSpec( + packageName, + "LocalSend", + listOf(DeclaredReceiver(SendAction.SEND, MimeKind.TEXT, "$packageName.Share")), + ) + } + } + + @Before + fun setUp() { + Dispatchers.setMain(Dispatchers.Unconfined) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun withVm( + installed: Set = setOf(localSend), + file: File = File(temp.root, "p.preferences_pb"), + block: suspend (TargetsViewModel, Preferences) -> T, + ): T = runBlocking { + val job = Job() + var vm: TargetsViewModel? = null + try { + val prefs = Preferences.create(CoroutineScope(Dispatchers.IO + job)) { file } + vm = TargetsViewModel(prefs, FakeCatalog(installed), Dispatchers.IO) + withTimeout(20_000) { block(vm, prefs) } + } finally { + // Stop the view model's own collectors before Main is reset. + vm?.viewModelScope?.coroutineContext?.get(Job)?.cancelAndJoin() + job.cancel() + job.join() + } + } + + private suspend fun TargetsViewModel.rows(until: (List) -> Boolean = { true }): List = + state.first { it.loaded && until(it.rows) }.rows + + private val firstId = BuiltInTargets.all[0].id + private val secondId = BuiltInTargets.all[1].id + + @Test + fun listsEveryBuiltInTargetWithInstalledState() { + withVm(installed = setOf("com.anthropic.claude")) { vm, _ -> + val rows = vm.rows() + assertEquals(BuiltInTargets.all.map { it.id }, rows.map { it.id }) + assertEquals(true, rows.first { it.id == "claude" }.installed) + assertEquals(false, rows.first { it.id == "chatgpt" }.installed) + assertNull(rows.first { it.id == "folder" }.installed) + assertFalse(rows.first().canMoveUp) + assertFalse(rows.last().canMoveDown) + } + } + + @Test + fun hiddenTargetLeavesArrangedResult() { + withVm { vm, prefs -> + vm.setHidden(firstId, true).join() + val arranged = prefs.current().targets() + assertTrue(arranged.none { it.id == firstId }) + assertEquals(BuiltInTargets.all.size - 1, arranged.size) + // The page still lists it, switched off. + assertTrue(vm.rows { r -> r.first { it.id == firstId }.hidden }.any { it.id == firstId }) + + vm.setHidden(firstId, false).join() + assertTrue(prefs.current().targets().any { it.id == firstId }) + } + } + + @Test + fun moveUpChangesOrder() { + withVm { vm, prefs -> + vm.moveUp(secondId).join() + val ids = prefs.current().targets().map { it.id } + assertEquals(secondId, ids[0]) + assertEquals(firstId, ids[1]) + assertEquals(BuiltInTargets.all.size, ids.size) + + vm.moveDown(secondId).join() + assertEquals(BuiltInTargets.all.map { it.id }, prefs.current().targets().map { it.id }) + } + } + + @Test + fun movingTheEdgesDoesNothing() { + withVm { vm, prefs -> + vm.moveUp(firstId).join() + vm.moveDown(BuiltInTargets.all.last().id).join() + assertEquals(BuiltInTargets.all.map { it.id }, prefs.current().targets().map { it.id }) + } + } + + @Test + fun formatOverridePersistsAcrossInstances() { + val file = File(temp.root, "p.preferences_pb") + val target = BuiltInTargets.all.first { it.canChangeFormat } + val chosen = TargetsViewModel.INTENT_FORMATS.first { it != target.format } + withVm(file = file) { vm, prefs -> + vm.setFormat(target.id, chosen).join() + assertEquals(chosen.rawValue, prefs.current().formatOverrides[target.id]) + } + withVm(file = file) { vm, prefs -> + val row = vm.rows().first { it.id == target.id } + assertEquals(chosen, row.format) + assertEquals(target.format, row.defaultFormat) + assertEquals(chosen, prefs.current().targets().first { it.id == target.id }.format) + } + } + + @Test + fun choosingTheDefaultFormatDropsTheOverrideAndWritersCannotChange() { + withVm { vm, prefs -> + val target = BuiltInTargets.all.first { it.canChangeFormat } + val other = TargetsViewModel.INTENT_FORMATS.first { it != target.format } + vm.setFormat(target.id, other).join() + vm.setFormat(target.id, target.format).join() + assertNull(prefs.current().formatOverrides[target.id]) + + val writer = BuiltInTargets.all.first { it.isWriter } + vm.setFormat(writer.id, DeliveryFormat.ARCHIVE).join() + assertNull(prefs.current().formatOverrides[writer.id]) + assertTrue(vm.rows().first { it.id == writer.id }.formatOptions.isEmpty()) + assertEquals(TargetsViewModel.INTENT_FORMATS, vm.rows().first { it.id == target.id }.formatOptions) + } + } + + @Test + fun addedAppBecomesLastCustomTargetAndSurvivesRestart() { + val file = File(temp.root, "p.preferences_pb") + val id = TargetProfile.customId(localSend) + withVm(file = file) { vm, prefs -> + vm.addCustom(listOf(localSend, "not.installed.app")).join() + val rows = vm.rows { r -> r.any { it.id == id } } + assertEquals(id, rows.last().id) + assertTrue(rows.last().isCustom) + assertEquals("LocalSend", rows.last().profile.label) + assertTrue(id in prefs.current().targetOrder) + assertTrue(prefs.current().targets(BuiltInTargets.all + customProfile()).any { it.id == id }) + assertEquals(BuiltInTargets.all.size + 1, rows.size) + } + withVm(file = file) { vm, _ -> + assertEquals(id, vm.rows { r -> r.any { it.id == id } }.last().id) + } + } + + @Test + fun removingCustomTargetClearsItsSettings() { + val id = TargetProfile.customId(localSend) + withVm { vm, prefs -> + vm.addCustom(listOf(localSend)).join() + vm.setHidden(id, true).join() + vm.setFormat(id, DeliveryFormat.INLINE_TEXT).join() + vm.removeCustom(id).join() + val snapshot = prefs.current() + assertFalse(id in snapshot.targetOrder) + assertFalse(id in snapshot.hiddenTargets) + assertNull(snapshot.formatOverrides[id]) + assertTrue(vm.rows { r -> r.none { it.id == id } }.none { it.id == id }) + // Built-ins cannot be removed. + vm.removeCustom(firstId).join() + assertNotNull(vm.rows().firstOrNull { it.id == firstId }) + } + } + + @Test + fun addAppDialogListsOnlyAppsNotYetTargets() { + withVm { vm, prefs -> + vm.openAddApp().join() + var add = vm.state.first { it.addApp?.loading == false }.addApp!! + assertEquals(listOf(localSend), add.apps.map { it.packageName }) + vm.toggleApp(localSend) + assertEquals(setOf(localSend), vm.state.first { it.addApp?.selected?.isNotEmpty() == true }.addApp!!.selected) + vm.confirmAddApp().join() + assertNull(vm.state.first { it.addApp == null }.addApp) + assertTrue(TargetProfile.customId(localSend) in prefs.current().targetOrder) + + vm.openAddApp().join() + add = vm.state.first { it.addApp?.loading == false }.addApp!! + assertTrue(add.apps.isEmpty()) + vm.dismissAddApp() + } + } + + private fun customProfile(): List = + TargetsViewModel.customProfiles(listOf(TargetProfile.customId(localSend))) { FakeCatalog(setOf(localSend)).customSpec(it) } +} diff --git a/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/theme/DarkModeSmokeTest.kt b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/theme/DarkModeSmokeTest.kt new file mode 100644 index 00000000..5fb22f51 --- /dev/null +++ b/android/app/src/test/kotlin/com/xiangming/wechatbridge/ui/theme/DarkModeSmokeTest.kt @@ -0,0 +1,98 @@ +package com.xiangming.wechatbridge.ui.theme + +import android.content.res.Configuration +import android.os.Looper +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.remember +import com.xiangming.wechatbridge.receive.ReceiptSheet +import com.xiangming.wechatbridge.receive.ReceiptUiState +import com.xiangming.wechatbridge.ui.relay.RelayContent +import com.xiangming.wechatbridge.ui.relay.RelayUiState +import com.xiangming.wechatbridge.ui.relay.previewChat +import com.xiangming.wechatbridge.ui.relay.previewEntry +import com.xiangming.wechatbridge.ui.relay.previewFiles +import com.xiangming.wechatbridge.ui.settings.SettingsScreen +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +/** 深色模式冒烟:主要界面在 night 配置下能组合、不崩溃,且主题确实切到深色配色。 */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "night") +class DarkModeSmokeTest { + + private fun compose(content: @Composable () -> Unit): ComponentActivity { + val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup() + val activity = controller.get() + activity.setContent { WeChatBridgeTheme { content() } } + shadowOf(Looper.getMainLooper()).idle() + return activity + } + + @Test + fun nightQualifierSelectsDarkScheme() { + var dark = false + var background = 0L + val activity = compose { + val isDark = isSystemInDarkTheme() + val bg = MaterialTheme.colorScheme.background + SideEffect { + dark = isDark + background = bg.value.toLong() + } + } + val night = activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK + assertEquals(Configuration.UI_MODE_NIGHT_YES, night) + assertTrue(dark) + assertEquals(DarkBackground.value.toLong(), background) + } + + @Test + fun relayListComposesInDark() { + val chat = previewEntry(previewChat, targetName = "Claude", delivered = true) + compose { + RelayContent( + state = RelayUiState( + entries = listOf(chat, previewEntry(previewFiles, itemNames = listOf("报告.pdf", "截图.png"))), + totalCount = 2, + selection = setOf(chat.id), + ), + snackbarHostState = remember { SnackbarHostState() }, + onFilter = {}, + onOpenEntry = {}, + onToggle = {}, + onSelectAll = {}, + onClearSelection = {}, + onDeliverSelected = {}, + onDeleteSelected = {}, + onOpenCollection = {}, + onDeliverCollection = {}, + onOpenScenes = {}, + onOpenSettings = {}, + onImportFiles = {}, + onImportClipboard = {}, + ) + } + } + + @Test + fun receiptSheetComposesInDark() { + compose { ReceiptSheet(state = ReceiptUiState.Importing(collect = false), onDone = {}) } + } + + @Test + fun settingsScreenComposesInDark() { + compose { SettingsScreen(onBack = {}, onOpenScenes = {}, onOpenOnboarding = {}, onOpenTargets = {}) } + } +} diff --git a/android/app/src/test/resources/robolectric.properties b/android/app/src/test/resources/robolectric.properties new file mode 100644 index 00000000..8febb24b --- /dev/null +++ b/android/app/src/test/resources/robolectric.properties @@ -0,0 +1 @@ +qualifiers=zh diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 00000000..db4f8c38 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { + alias(libs.plugins.android.application) apply false + alias(libs.plugins.kotlin.jvm) apply false + alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.kotlin.serialization) apply false +} diff --git a/android/core/build.gradle.kts b/android/core/build.gradle.kts new file mode 100644 index 00000000..7b46aa05 --- /dev/null +++ b/android/core/build.gradle.kts @@ -0,0 +1,32 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +// :core —— 纯 Kotlin/JVM,不依赖 android.*,全部可单测。 +plugins { + alias(libs.plugins.kotlin.jvm) + alias(libs.plugins.kotlin.serialization) +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } +} + +dependencies { + implementation(libs.kotlinx.serialization.json) + implementation(libs.kotlinx.coroutines.core) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.platform.launcher) + testImplementation(libs.kotlinx.coroutines.test) +} + +tasks.test { + useJUnitPlatform() +} diff --git a/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/CoreInfo.kt b/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/CoreInfo.kt new file mode 100644 index 00000000..c47621aa --- /dev/null +++ b/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/CoreInfo.kt @@ -0,0 +1,9 @@ +package com.xiangming.wechatbridge.core + +/** :core 模块占位:后续任务在各子包(archive/、transcript/、inbox/ …)里添加真正的逻辑。 */ +object CoreInfo { + /** 批次清单的 schema 版本,与 Mac / iOS 的 BatchManifest 保持一致。 */ + const val MANIFEST_SCHEMA_VERSION: Int = 1 + + const val MODULE_NAME: String = "core" +} diff --git a/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/WeChatReadException.kt b/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/WeChatReadException.kt new file mode 100644 index 00000000..0c7ad01a --- /dev/null +++ b/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/WeChatReadException.kt @@ -0,0 +1,20 @@ +package com.xiangming.wechatbridge.core + +/** + * Mirrors `WeChatReadError` on macOS / iOS. Every malformed, truncated or + * suspicious export fails closed with [Kind.INVALID_TRANSCRIPT]; callers keep + * the original file and show the localized message from `:app`. + */ +class WeChatReadException( + val kind: Kind = Kind.INVALID_TRANSCRIPT, + message: String? = null, + cause: Throwable? = null, +) : Exception(message ?: kind.name, cause) { + enum class Kind { INVALID_TRANSCRIPT, TRANSCRIPT_MISMATCH } + + companion object { + /** Shorthand used by the parsers: `throw invalid("why")`. */ + fun invalid(reason: String? = null, cause: Throwable? = null) = + WeChatReadException(Kind.INVALID_TRANSCRIPT, reason, cause) + } +} diff --git a/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/archive/ArchiveSource.kt b/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/archive/ArchiveSource.kt new file mode 100644 index 00000000..bf19eb05 --- /dev/null +++ b/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/archive/ArchiveSource.kt @@ -0,0 +1,53 @@ +package com.xiangming.wechatbridge.core.archive + +import com.xiangming.wechatbridge.core.WeChatReadException +import java.io.Closeable +import java.io.File +import java.nio.ByteBuffer +import java.nio.channels.FileChannel +import java.nio.file.StandardOpenOption + +/** + * Random-access bytes of one ZIP. Android heaps are far smaller than a Mac's + * `Data(mappedIfSafe)`, so the parser never loads the whole archive: it reads + * the tail, the central directory, and then streams each entry. + */ +interface ArchiveSource : Closeable { + val size: Long + + /** Fills `dest[off, off+len)` from absolute `position`, or throws. */ + fun readFully(position: Long, dest: ByteArray, off: Int = 0, len: Int = dest.size - off) + + override fun close() {} + + companion object { + fun of(bytes: ByteArray): ArchiveSource = ByteArraySource(bytes) + fun open(file: File): ArchiveSource = FileChannelSource(file) + } +} + +private class ByteArraySource(private val bytes: ByteArray) : ArchiveSource { + override val size: Long get() = bytes.size.toLong() + override fun readFully(position: Long, dest: ByteArray, off: Int, len: Int) { + if (position < 0 || len < 0 || position > size - len) throw WeChatReadException.invalid("read past end") + System.arraycopy(bytes, position.toInt(), dest, off, len) + } +} + +private class FileChannelSource(file: File) : ArchiveSource { + private val channel: FileChannel = FileChannel.open(file.toPath(), StandardOpenOption.READ) + override val size: Long = channel.size() + + override fun readFully(position: Long, dest: ByteArray, off: Int, len: Int) { + if (position < 0 || len < 0 || position > size - len) throw WeChatReadException.invalid("read past end") + val buffer = ByteBuffer.wrap(dest, off, len) + var at = position + while (buffer.hasRemaining()) { + val n = channel.read(buffer, at) + if (n < 0) throw WeChatReadException.invalid("file shrank while reading") + at += n + } + } + + override fun close() = channel.close() +} diff --git a/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/archive/WeChatArchive.kt b/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/archive/WeChatArchive.kt new file mode 100644 index 00000000..24747bd7 --- /dev/null +++ b/android/core/src/main/kotlin/com/xiangming/wechatbridge/core/archive/WeChatArchive.kt @@ -0,0 +1,167 @@ +package com.xiangming.wechatbridge.core.archive + +import com.xiangming.wechatbridge.core.WeChatReadException +import com.xiangming.wechatbridge.core.transcript.TranscriptRecord +import java.io.File +import java.nio.file.Files +import java.nio.file.LinkOption +import java.nio.file.Path +import java.nio.file.StandardOpenOption +import java.text.Normalizer +import java.time.Instant +import java.time.ZoneId + +/** + * Reads WeChat's own "聊天记录__