豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows
一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、 不需要另外装 Termux。 安卓端 - 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的 - 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹 - 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端; pty 不可用的 ROM 上自动降级成命令控制台 - APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上 - 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板 - 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎 AI 能力 - 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义 - 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发), 认不出来的一律不发,避免给不支持的厂商发字段直接 400 - MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式 跨端 - 安卓走原生 Compose,Web / Windows 走 Lynx - Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本 自检脚本(都不需要真 Key) - verify-phone.mjs 设备端 24 项验收 - verify-speech.mjs 语音链路 31 项,两份内核各跑一遍 - parity-thinking.mjs 思考强度映射对拍 - probe-settings-wipe.mjs 设置防清空攻击测试 - mock-llm.mjs 假的 OpenAI + 火山语音服务 许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron) 的授权见 LICENSE。
22
.gitattributes
vendored
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# 统一换行符为 LF。
|
||||||
|
#
|
||||||
|
# 为什么必须显式规定:开发机是 Windows,git 默认会把文本文件转成 CRLF;
|
||||||
|
# 而 kernel/ 里的 .py 和 scripts/ 里的 shell 片段是要在安卓/Linux 上跑的,
|
||||||
|
# 带上 \r 会出各种"看起来一样但就是跑不起来"的怪问题
|
||||||
|
# (比如 shebang 变成 #!/bin/sh\r 直接报 bad interpreter)。
|
||||||
|
* text=auto eol=lf
|
||||||
|
|
||||||
|
# 二进制文件别做任何转换
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.jpeg binary
|
||||||
|
*.webp binary
|
||||||
|
*.gif binary
|
||||||
|
*.ico binary
|
||||||
|
*.so binary
|
||||||
|
*.jar binary
|
||||||
|
*.keystore binary
|
||||||
|
*.zip binary
|
||||||
|
|
||||||
|
# 锁文件按二进制处理:合并冲突时人工处理没意义
|
||||||
|
package-lock.json -diff linguist-generated
|
||||||
89
.gitignore
vendored
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
# 依赖(几百 MB,clone 后 `npm run install:all` 自己装)
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
node_modules/
|
||||||
|
.npm-cache/
|
||||||
|
desktop/node_modules/
|
||||||
|
desktop/dist-staging/
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
# 构建产物
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
dist-android/
|
||||||
|
dist-win/
|
||||||
|
app/dist/
|
||||||
|
web/dist/
|
||||||
|
android/app/build/
|
||||||
|
android/build/
|
||||||
|
android/.gradle/
|
||||||
|
android/local.properties
|
||||||
|
build/
|
||||||
|
.gradle/
|
||||||
|
*.tsbuildinfo
|
||||||
|
*.apk
|
||||||
|
*.aab
|
||||||
|
*.exe
|
||||||
|
*_boot.zip
|
||||||
|
|
||||||
|
# 打包中间产物(electron 二进制与暂存目录都很大)
|
||||||
|
android/app/src/main/assets/main.lynx.bundle
|
||||||
|
.rasterize-*
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
# 密钥 / 个人配置 —— 这些**绝不能**提交
|
||||||
|
#
|
||||||
|
# settings.json 里有 apiKey 字段(现在是占位值,但随时可能填真 Key);
|
||||||
|
# mcp.servers.json 里有本机绝对路径。
|
||||||
|
# 示例文件(*.example.*)是给别人做模板用的,要提交。
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
server/.env
|
||||||
|
server/.env.*
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
*.local
|
||||||
|
server/config/settings.json
|
||||||
|
tools/mcp.servers.json
|
||||||
|
app/config/settings.json
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
# 运行时数据
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
server/data/
|
||||||
|
data/
|
||||||
|
phone-verify-result.json
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
# Termux 的两个 bootstrap(各 28 MB,共 56 MB)
|
||||||
|
#
|
||||||
|
# 这两个 .so 是**手动**从 Termux 的 APK 里取出来放进 jniLibs 的,
|
||||||
|
# 仓库里没有脚本能重新生成(fetch-termux.mjs 只把 APK 下到缓存)。
|
||||||
|
# 56 MB 的二进制不适合跟着代码走,所以单独排除;
|
||||||
|
# 要构建 APK 见 README「4.2 APK 里到底装了什么」。
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
android/app/src/main/jniLibs/*/libtermux-bootstrap.so
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
# Python
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
# 编辑器 / 系统
|
||||||
|
# ─────────────────────────────────────────────────────────────
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.iml
|
||||||
|
*.swp
|
||||||
|
Thumbs.db
|
||||||
|
Desktop.ini
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# 调试时生成的临时探针
|
||||||
|
.tmp/
|
||||||
|
.tmp-*
|
||||||
62
LICENSE
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 doubao-clone contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
|
||||||
|
===============================================================================
|
||||||
|
第三方组件(Third-Party Notices)
|
||||||
|
===============================================================================
|
||||||
|
|
||||||
|
本项目**包含或依赖**以下第三方作品。它们各自的授权条款独立于上面的 MIT,
|
||||||
|
使用时请一并遵守:
|
||||||
|
|
||||||
|
1. Termux(终端模拟器与 Linux 用户态)—— Apache License 2.0
|
||||||
|
https://github.com/termux/termux-app
|
||||||
|
- `android/app/src/main/java/com/termux/**` 是 Termux 的终端模拟器源码
|
||||||
|
(vendored,只改了 R 类的包名引用)
|
||||||
|
- `android/app/src/main/jniLibs/*/libtermux.so` 是 Termux 编译出的 JNI 库
|
||||||
|
- 构建 APK 时还需要 Termux 的 bootstrap(`libtermux-bootstrap.so`),
|
||||||
|
该文件未收录在本仓库中
|
||||||
|
- 完整许可见 `android/app/src/main/assets/TERMUX_LICENSE.txt`
|
||||||
|
与 `android/app/src/main/assets/APACHE-2.0.txt`
|
||||||
|
|
||||||
|
2. Chaquopy —— MIT License(社区版)
|
||||||
|
https://chaquo.com/chaquopy/
|
||||||
|
用于在 APK 内嵌 CPython。
|
||||||
|
|
||||||
|
3. Jetpack Compose / AndroidX —— Apache License 2.0
|
||||||
|
https://developer.android.com/jetpack
|
||||||
|
|
||||||
|
4. LynxJS —— Apache License 2.0
|
||||||
|
https://github.com/lynx-family/lynx
|
||||||
|
Web / Windows 桌面版的界面用的就是它。
|
||||||
|
|
||||||
|
5. Electron —— MIT License
|
||||||
|
https://github.com/electron/electron
|
||||||
|
仅 Windows 桌面版打包使用。
|
||||||
|
|
||||||
|
===============================================================================
|
||||||
|
关于商标与素材
|
||||||
|
===============================================================================
|
||||||
|
|
||||||
|
- 「豆包」是字节跳动的商标,本项目**与字节跳动没有任何关系**,
|
||||||
|
是出于学习目的的界面复刻,不包含任何来自豆包 App 的代码或素材。
|
||||||
|
- 界面配色与布局是照着公开截图量出来的,图标用的是 Material Icons。
|
||||||
|
- 仓库里的界面截图由项目作者在自己的设备上截取。
|
||||||
638
README.md
Normal file
@@ -0,0 +1,638 @@
|
|||||||
|
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||||
|
|
||||||
|
[](LICENSE)
|
||||||
|
|
||||||
|
**主力是安卓端**:一个**完全离线自主**的原生 Android App ——
|
||||||
|
界面是 Kotlin + Jetpack Compose,AI 内核是内嵌的 CPython,**Termux 也是内置的**(不用另外装、不用连电脑)。
|
||||||
|
|
||||||
|
> ⚠️ 学习目的的界面复刻,**与字节跳动没有任何关系**,不含任何来自豆包 App 的代码或素材。
|
||||||
|
> 「豆包」是字节跳动的商标。
|
||||||
|
|
||||||
|
| 平台 | 产物 | 界面 | 内核 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **Android(主力)** | `dist-android/doubao-debug.apk`(88.4 MB) | **原生 Compose** | **APK 内嵌 CPython 3.13 + 内置 Termux** |
|
||||||
|
| Windows | `…\DoubaoClone\Doubao-win32-x64\豆包.exe` | Lynx(旧版,仍在) | Node(随 Electron 启动) |
|
||||||
|
| 浏览器 | `http://127.0.0.1:5199/` | Lynx(旧版,仍在) | Node |
|
||||||
|
|
||||||
|
> 安卓端**不依赖电脑、不依赖外装 Termux**:Python 运行时、Linux 用户态(bash/apt/pkg)、
|
||||||
|
> MCP 客户端、终端全在 APK 里。装完填个 API Key 就能用。
|
||||||
|
|
||||||
|
| 对话(原生) | 真实回复(含操作栏) | 抽屉(含「模型」栏) |
|
||||||
|
|---|---|---|
|
||||||
|
|  |  |  |
|
||||||
|
|
||||||
|
| 模型与思考强度 | 设置(10 家提供商) | 内置 Termux 终端 |
|
||||||
|
|---|---|---|
|
||||||
|
|  |  |  |
|
||||||
|
|
||||||
|
| 早期 Lynx 版(真机实拍) | 浏览器版设置(10 家提供商) | Windows 桌面版 |
|
||||||
|
|---|---|---|
|
||||||
|
|  |  |  |
|
||||||
|
|
||||||
|
> 最左边那张是**旧的 Lynx 版**在真机上跑的(原生 Compose 版见上面两组)。
|
||||||
|
> 两个版本现在都在仓库里:安卓走原生 Compose,Web / exe 走 Lynx。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 快速开始
|
||||||
|
|
||||||
|
### 浏览器 / 桌面版
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run install:all # app(Lynx 客户端)+ server(Node 内核)
|
||||||
|
npm run build
|
||||||
|
npm start # 打开 http://127.0.0.1:5199/
|
||||||
|
```
|
||||||
|
|
||||||
|
Windows 桌面版直接双击 `豆包.exe`(**exe 必须放纯英文路径**,见 §7.1)。
|
||||||
|
|
||||||
|
### Android(推荐,不需要电脑)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run apk # 产出 dist-android/doubao-debug.apk(约 88 MB)
|
||||||
|
adb install -r dist-android/doubao-debug.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
装完打开 App → 抽屉 →「设置」→ 选提供商、填 API Key → 保存。
|
||||||
|
第一次启动会解压内置 Termux(约 95 MB、3226 个文件),**约 10~30 秒**,界面上有进度。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ Android App(原生 Kotlin + Compose,主力) │
|
||||||
|
│ │
|
||||||
|
│ ui/ ChatScreen Drawer Settings Skills Agents Profile │
|
||||||
|
│ ModelPickerSheet TerminalScreen ← 7 个页面 │
|
||||||
|
│ │ │
|
||||||
|
│ │ KernelClient(OkHttp + 轮询流式) │
|
||||||
|
│ ▼ │
|
||||||
|
│ ┌──────────────────────────────────────────────┐ │
|
||||||
|
│ │ Python 内核(Chaquopy 内嵌 CPython 3.13) │ │
|
||||||
|
│ │ android/kernel/ —— 监听 127.0.0.1:5199 │ │
|
||||||
|
│ │ · providers 10 家兼容厂商 + 思考强度映射 │ │
|
||||||
|
│ │ · agent_loop 多轮工具循环 │ │
|
||||||
|
│ │ · tools import 加载 tools/*.py │ │
|
||||||
|
│ │ · mcp_client 手写 JSON-RPC(http/stdio/inproc)│ │
|
||||||
|
│ └──────────────────────────────────────────────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ▼ 进程内直调(Chaquopy 桥) │
|
||||||
|
│ ┌──────────────────────────────────────────────┐ │
|
||||||
|
│ │ 内置 Termux($PREFIX = /data/user/0/<pkg>/files/usr) │
|
||||||
|
│ │ · bash 5.x / apt / pkg / 388 个命令 │ │
|
||||||
|
│ │ · libtermux.so → forkpty(真 tty) │ │
|
||||||
|
│ │ · TerminalView → ANSI 渲染(Termux 源码 vendored)│ │
|
||||||
|
│ └──────────────────────────────────────────────┘ │
|
||||||
|
│ ┌──────────────────────────────────────────────┐ │
|
||||||
|
│ │ 设备能力 NativeBridge:定位 / 陀螺仪 / 加速度计 │ │
|
||||||
|
│ │ 磁性 / 光线 / 气压 / 电量 / 剪贴板 / 选文件 │ │
|
||||||
|
│ └──────────────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
电脑上的 Web/exe 版仍然用 **Node 内核 + Lynx 界面**。两个内核**接口逐字段一致**,
|
||||||
|
所以安卓端把界面换成 Compose 之后,后端一行都不用改。
|
||||||
|
|
||||||
|
怎么做到一致的:`android/kernel/` 是照 `server/src/` 的契约重写的纯标准库实现
|
||||||
|
(`http.server` + `urllib` + 手写 JSON-RPC),不依赖任何第三方包 —— 因为安卓上装不进来。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 功能
|
||||||
|
|
||||||
|
### 3.1 智能体
|
||||||
|
抽屉 →「智能体」。每个智能体有独立头像(9 种)和系统提示词,聊天时覆盖全局提示词,顶部显示当前智能体。
|
||||||
|
内置 4 个(豆包 / 代码搭子 / 文案师 / 数据分析),可自建。存 `<数据目录>/agents.json`。
|
||||||
|
|
||||||
|
### 3.2 模型、提供商与思考强度(抽屉里的「模型」那一栏)
|
||||||
|
|
||||||
|
**支持 10 家,而且它们全都是同一个协议**(`POST {baseUrl}/chat/completions`),
|
||||||
|
所以内核里只有一份实现,差别只在三件事:地址、模型名、**思考强度用哪个字段传**。
|
||||||
|
|
||||||
|
| key | 提供商 | Base URL | 思考强度怎么传 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `ark` | 火山方舟(豆包) | `https://ark.cn-beijing.volces.com/api/v3` | 顶层 `thinking: {type}` |
|
||||||
|
| `openai` | OpenAI 官方 | `https://api.openai.com/v1` | `reasoning_effort` |
|
||||||
|
| `deepseek` | DeepSeek | `https://api.deepseek.com/v1` | 不发(模型自己决定) |
|
||||||
|
| `kimi` | Kimi(月之暗面) | `https://api.moonshot.cn/v1` | 不发 |
|
||||||
|
| `zhipu` | 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` | 顶层 `thinking: {type}` |
|
||||||
|
| `dashscope` | 通义千问(阿里云) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | 不发 |
|
||||||
|
| `siliconflow` | 硅基流动 | `https://api.siliconflow.cn/v1` | 不发 |
|
||||||
|
| `openrouter` | OpenRouter(聚合) | `https://openrouter.ai/api/v1` | `reasoning_effort` |
|
||||||
|
| `ollama` | 本地 Ollama | `http://127.0.0.1:11434/v1` | 不发 |
|
||||||
|
| `custom` | 自定义兼容网关 | 自己填 | 不发 |
|
||||||
|
|
||||||
|
**为什么不是"非 ark 即 openai"**:这个判断以前写死成两家名字。
|
||||||
|
现在厂商多了,各自认的字段不一样,而**给不认 `reasoning_effort` 的服务发这个字段,有些会直接 400**。
|
||||||
|
所以改成每个预设自己声明 `thinkingMode`(`ark` / `effort` / `none`),**认不出来的一律 `none`**(什么都不发,最安全)。
|
||||||
|
|
||||||
|
| 强度 | `thinkingMode: ark` | `thinkingMode: effort` | `thinkingMode: none` |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 快速 | `thinking={type:"disabled"}` | 推理模型 `reasoning_effort=minimal` | 不发 |
|
||||||
|
| 自动 | 不传,交给模型 | 不传 | 不传 |
|
||||||
|
| 低 / 中 / 高 | `thinking={type:"enabled"}` | `reasoning_effort=low/medium/high` | 不传 |
|
||||||
|
|
||||||
|
另外:`thinkingMode: effort` 且模型名匹配 `o1|o3|o4|gpt-5|gpt-6` 时,
|
||||||
|
会自动剥掉 `temperature`/`top_p` 等采样参数,并把 `max_tokens` 换成 `max_completion_tokens`
|
||||||
|
(这些模型"传默认值"也算传,会 400)。
|
||||||
|
|
||||||
|
两份内核(Node / Python)在这件事上**逐字段对拍 50/50 一致**(10 家 × 5 档),
|
||||||
|
脚本:`node scripts/parity-thinking.mjs`。
|
||||||
|
|
||||||
|
### 3.3 思考过程怎么显示
|
||||||
|
1. **正文里**:回答上方一个 `✨ 深度思考 ›` 入口,思考中显示跳动小点
|
||||||
|
(这里不再拼思考强度 —— 强度本身就叫"深度思考",拼出来会变成"深度思考 · 深度思考")
|
||||||
|
2. **点开**:底部升起「**思考过程**」弹层(左上角 X),先列这轮调了哪些工具,再是完整思维链
|
||||||
|
3. 思维链**已落库**,刷新/切会话都不丢
|
||||||
|
|
||||||
|
### 3.4 界面:照着豆包抠的,带完整动效
|
||||||
|
|
||||||
|
安卓端是原生 Compose 重写的,视觉对着豆包真机截图一项项抠:
|
||||||
|
|
||||||
|
- **纯白底**(不是浅灰)——豆包的层级靠"白底 + 浅灰卡片"表达,用灰底会一股系统设置味
|
||||||
|
- 顶部三段式:左边 ☰ / ✎,中间「头像 + 智能体名 + ›」(点开就是模型面板),右边 📞 / 🔊
|
||||||
|
- 空会话时:168dp 蓝色圆环大头像 + 灰色问候气泡 + 白底描边快捷胶囊(对话 / AI创作 / 出行用豆包 / 豆包)
|
||||||
|
- 用户气泡:`#2B7BFF` 蓝底、右下角收窄成 4dp(气泡"尾巴")
|
||||||
|
- 助手气泡:`#F2F3F5` 灰底、左下角收窄;下面一排 5 个圆形小按钮(复制/朗读/赞/踩/分享)+ 右侧重新生成
|
||||||
|
- 输入框:52dp 高的大圆角描边胶囊,左边相机、右边麦克风;**有内容时右侧才变成蓝色圆形发送键**
|
||||||
|
- 出错的回复是浅红底 + 红字,不是普通气泡
|
||||||
|
- 设置 / 我的 / 技能 / 智能体各页共用同一套小部件(`ScreenHeader` / `SettingsCard` / `FormField` …),
|
||||||
|
所以在主题层改一次颜色,7 个页面一起变
|
||||||
|
|
||||||
|
动效(都是 Compose 原生动画,没引第三方库):
|
||||||
|
|
||||||
|
| 位置 | 动效 |
|
||||||
|
|---|---|
|
||||||
|
| 抽屉 | 从左滑入 + 遮罩淡入,关闭反向 |
|
||||||
|
| 页面切换 | 淡入 + 轻微横向位移(`AnimatedContent`) |
|
||||||
|
| 消息气泡 | 出现时淡入 + 上移 10dp(`AppearOnce`) |
|
||||||
|
| 思考 / 模型面板 | 从底部升起,收起时降下去 |
|
||||||
|
| "正在输入" | 三个小点依次跳动(`TypingDots`,错开 130ms) |
|
||||||
|
| 按钮 | 按下缩到 0.86~0.94 回弹(`collectIsPressedAsState` + spring) |
|
||||||
|
| 抽屉列表项 | 按下时背景色渐变 |
|
||||||
|
|
||||||
|
> 顺带一个坑:底部面板的**滚动区会吃掉点击**。如果面板顶到状态栏,
|
||||||
|
> "点遮罩关闭"就只剩状态栏那条能点,等于失效。所以面板限高 85%、并且都带明确的 X 按钮。
|
||||||
|
|
||||||
|
### 3.5 设置不会被保存清空(三道防线)
|
||||||
|
|
||||||
|
之前有个真 bug:**一保存设置,整份配置被清空**。根因是首屏 `state` 还在路上时,
|
||||||
|
设置页草稿还是"全空"的,而保存按钮把草稿**全量**下发;`/api/settings` 是浅合并,
|
||||||
|
空字符串就等于把它清掉。现在三道防线:
|
||||||
|
|
||||||
|
1. **界面只发改动过的字段**(`SettingsDraft.changesAgainst`)——没动过的键根本不出现
|
||||||
|
2. **草稿只在服务端设置真的变了时重建**(存一份 `snapshot` 对比),
|
||||||
|
不会再被无关的 state 刷新冲掉正在输入的内容
|
||||||
|
3. **内核拒收空的关键字段**(`provider` / `baseUrl` / `model` / `apiKey` / `nickname` / `thinkingLevel`)——
|
||||||
|
前端再出 bug 也清不掉配置。`systemPrompt` / `toolsDir` 故意不在此列:它们"留空"是合理需求
|
||||||
|
|
||||||
|
验证脚本(都会先正常保存一次验证不掉字段,再按"旧版 bug 的形状"下发一堆空值验证被忽略):
|
||||||
|
|
||||||
|
- `node scripts/probe-settings-wipe.mjs http://127.0.0.1:5199`(电脑 / Node 内核)
|
||||||
|
- `node scripts/device-settings-attack.mjs emulator-5556 5199`(设备 / Python 内核)
|
||||||
|
|
||||||
|
### 3.6 工具
|
||||||
|
|
||||||
|
| 工具 | 说明 | 安卓 |
|
||||||
|
|---|---|---|
|
||||||
|
| `shell` | 终端执行命令,带超时与黑名单 | ✅ 优先走内置 Termux |
|
||||||
|
| `python_run` | 执行 Python 代码 / .py 文件,`action=libs` 列可用库 | ✅ 进程内 exec(CPython 3.13.9) |
|
||||||
|
| `device` | **手机能力**:设备信息、定位、传感器、剪贴板 | ✅ 安卓专属 |
|
||||||
|
| `calc` `now` `get_weather` `notes` `web_fetch` | `tools/*.py`,自己写的 | ✅ 同一份代码 |
|
||||||
|
| `mcp__*` | MCP 服务暴露的工具 | ✅ 见 3.8 |
|
||||||
|
|
||||||
|
**`device` 工具**(安卓)实测能力:
|
||||||
|
- `info`:型号/厂商/系统/SDK/ABI/存储/屏幕/电量
|
||||||
|
- `location`:GPS 经纬度(真机实测 `纬度, 经度 ±35m`)
|
||||||
|
- `sensors` / `sensor`:列出并采样(真机 46 个传感器,加速度计 z≈9.7 m/s² 就是重力)
|
||||||
|
- `clipboard_get` / `clipboard_set`
|
||||||
|
- `termux_available` / `termux_run`:走内置 Termux
|
||||||
|
|
||||||
|
### 3.7 自己写工具
|
||||||
|
往工具目录丢一个 `.py`(`_` 开头跳过):
|
||||||
|
|
||||||
|
```python
|
||||||
|
TOOL = {
|
||||||
|
"name": "word_count",
|
||||||
|
"description": "统计一段文字的字数",
|
||||||
|
"parameters": {"type": "object", "properties": {"text": {"type": "string"}},
|
||||||
|
"required": ["text"]},
|
||||||
|
}
|
||||||
|
def run(args): # 同步或 async 都行
|
||||||
|
return {"count": len(args["text"])}
|
||||||
|
```
|
||||||
|
|
||||||
|
工具目录:安卓在 `files/tools/`(可通过设置里的 `toolsDir` 改),电脑在 `tools/`。
|
||||||
|
内置工具在首次启动时会**播种**到可写目录,改坏了删掉重启就恢复。
|
||||||
|
|
||||||
|
> 为什么安卓上要播种、还要把源码 base64 打进 APK:Chaquopy 打的是 `.pyc`,
|
||||||
|
> 运行时 `loader.get_source()` 拿不到源码,所以构建脚本额外生成了 `bundled_tool_sources.py`。
|
||||||
|
|
||||||
|
### 3.8 MCP:三种传输,安卓也能跑
|
||||||
|
抽屉 →「技能·连接器」→「MCP 服务」,图形化和原始 JSON 两个 Tab,保存时校验并自动重连。
|
||||||
|
|
||||||
|
| 传输 | 说明 | 安卓 |
|
||||||
|
|---|---|---|
|
||||||
|
| `http` | 标准 Streamable HTTP / SSE | ✅ |
|
||||||
|
| `stdio` | 起一个子进程用管道通信 | ✅ 用内置 Termux 的 python/node |
|
||||||
|
| `inproc` | 同进程内直接调用(自己写的 Python 服务) | ✅ 安卓推荐,最省事 |
|
||||||
|
|
||||||
|
实测:filesystem 服务 14 个工具、memory 9 个工具、自己写的 Python 服务 3 个工具,全部连接并调用成功。
|
||||||
|
|
||||||
|
> 为什么手写 JSON-RPC 而不用官方 `mcp` SDK:它依赖 pydantic v2,Chaquopy 装不进来。
|
||||||
|
|
||||||
|
### 3.9 文件上传 / 权限模式
|
||||||
|
- **上传**:输入框左侧相机/加号 → 选文件 → 上传到内核 → 挂到输入框 → 随消息发送 → 气泡里显示
|
||||||
|
- **权限模式**:`open` 全放行 / `restricted` 只放 `allow` 白名单。限制模式下未授权工具
|
||||||
|
**列都不列出来**,执行时再拦一道
|
||||||
|
|
||||||
|
### 3.10 语音:朗读 + 语音输入
|
||||||
|
|
||||||
|
**引擎放在内核里,音频采集/播放在端上。** 这么分的好处:API Key 只存一份,
|
||||||
|
浏览器 / 安卓 / exe 三端白捡同一个能力,厂商鉴权差异全在一个文件里。
|
||||||
|
|
||||||
|
| | 引擎 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| **朗读** | `system` | 设备自带 TTS(安卓 `TextToSpeech`)。**不联网、不要 Key**,默认就是它 |
|
||||||
|
| | `volc` | **火山语音合成 —— 豆包同款音色** |
|
||||||
|
| | `openai` | OpenAI 兼容的 `/audio/speech`(`tts-1` + alloy/nova/…) |
|
||||||
|
| **语音输入** | `system` | 设备自带识别(安卓 `SpeechRecognizer`) |
|
||||||
|
| | `openai` | OpenAI 兼容的 `/audio/transcriptions`(`whisper-1` 等) |
|
||||||
|
|
||||||
|
**火山那个接口有两个坑**(对着[官方文档](https://docs.volcengine.com/docs/DoubaoVoice/HTTPone-timecompositenon-streaminginterface-V1notrecommended?lang=zh)
|
||||||
|
和两个第三方实现核对过,并且用 mock 抓了实际发出的请求):
|
||||||
|
|
||||||
|
1. 鉴权头是 `Authorization: Bearer;{token}` —— **分号,不是空格**。写成空格会判鉴权失败。
|
||||||
|
实测抓到的请求:`Authorization="Bearer;tok-abc"`
|
||||||
|
2. 成功判定看 body 里的 `code === 3000`,**HTTP 200 也可能带错误码**;
|
||||||
|
返回的 `data` 是**纯 base64**(不是 data URL),解出来就是音频字节
|
||||||
|
|
||||||
|
接口:
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /api/tts {"text": "..."}
|
||||||
|
→ {"ok":true, "engine":"system"} 用设备自带,界面自己念
|
||||||
|
→ {"ok":true, "engine":"volc", "mime":"audio/mpeg", "audio":"<base64>"}
|
||||||
|
→ {"ok":false, "error":"..."} 失败原因给人话
|
||||||
|
|
||||||
|
POST /api/stt <body 就是音频原始字节,不套 JSON/base64>
|
||||||
|
头: X-Audio-Filename / X-Audio-Type
|
||||||
|
→ {"ok":true, "engine":"openai", "text":"..."}
|
||||||
|
|
||||||
|
GET /api/speech → 当前配置 + 可选音色
|
||||||
|
```
|
||||||
|
|
||||||
|
> 两个接口**失败也返回 HTTP 200 + `ok:false`**:缺 Key、厂商报错都是预期内的失败,
|
||||||
|
> 界面要的是把原因显示出来,而不是让 fetch 抛网络异常(那样错误信息就丢了)。
|
||||||
|
|
||||||
|
安卓端(`speech/AudioIo.kt` + `speech/SpeechController.kt`):
|
||||||
|
|
||||||
|
- **录音**用 `AudioRecord` 直接拿 PCM,套 44 字节 WAV 头(16kHz 单声道 16bit ——
|
||||||
|
Whisper 最常见的输入格式,30 秒才 1 MB)。不用 `MediaRecorder` 是因为它只吐 m4a/aac,还得再解码
|
||||||
|
- **播放**云端音频走 `MediaPlayer`(`setDataSource` 只认路径/FD,所以 base64 落盘成临时文件再播)
|
||||||
|
- **系统 TTS** 会**按句切分**再排队 —— `speak()` 单次上限约 4000 字符,整段塞进去会被截断
|
||||||
|
- 念之前**剥掉 markdown**(`**加粗**`、代码块、链接),否则会念出一堆星号
|
||||||
|
- **云端失败自动退回系统 TTS**:用户点了朗读却一点动静都没有是最差的体验
|
||||||
|
- 录音时**先停朗读**,否则会把自己的声音录进去(自我循环)
|
||||||
|
- 录音权限**第一次点麦克风才申请**,不在启动时要
|
||||||
|
- 录音时输入框整条换成「正在听…」+ 实时音量画的小波形
|
||||||
|
|
||||||
|
验证:`node scripts/verify-speech.mjs py|node` —— **21 项断言,两份内核都跑**
|
||||||
|
(语音在 Node 和 Python 里是分别实现的,只验一份不算数)。
|
||||||
|
mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权头。
|
||||||
|
|
||||||
|
### 3.11 通话模式(设计好了,还没做)
|
||||||
|
|
||||||
|
顶部那个 📞 现在是提示。真要做的话按这个来(**不要一上来就上全双工**):
|
||||||
|
|
||||||
|
| 阶段 | 做法 | 为什么 |
|
||||||
|
|---|---|---|
|
||||||
|
| A(推荐先做) | **半双工**:按一次开始录 → 静音自动断句 → STT → 内核 → TTS 播 → 循环 | 复用现有的 STT/TTS,1 天能出可用版本 |
|
||||||
|
| B | 全双工实时(OpenAI Realtime / 火山实时对话,WebSocket) | 延迟 300ms 级、能自然打断,但强依赖网络,改造量 3~5 天 |
|
||||||
|
|
||||||
|
阶段 A 要处理的四件事(都会真实咬人):
|
||||||
|
|
||||||
|
1. **自我循环**:TTS 在播时开麦会把 AI 自己的声音录进去 → 播之前必须先停麦,
|
||||||
|
或者做回声消除(`AudioSource.VOICE_COMMUNICATION` + AEC)
|
||||||
|
2. **音频焦点**:`TextToSpeech` 和 `AudioRecord` 不能同时持有 → 用 `AudioManager` 协调
|
||||||
|
3. **VAD 断句**:靠静音时长判断"说完了"。阈值调不好要么打断用户、要么一直不响应;
|
||||||
|
建议"连续 800ms 低于阈值算说完",并且**开口就打断 TTS**(barge-in)——这是"像通话"的关键手感
|
||||||
|
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||||
|
息屏后要有前台服务,否则一锁屏就断
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 安卓端:内置 Termux 是怎么塞进去的
|
||||||
|
|
||||||
|
### 4.1 一条硬限制决定了整个方案
|
||||||
|
|
||||||
|
**Android 10(API 29)起有 W^X 限制:`targetSdk ≥ 29` 的应用不允许执行自己数据目录里的二进制。**
|
||||||
|
而 Termux 把 bash/python/node 全解压在自己的私有目录再 exec —— 它能这么干,**唯一原因是它 `targetSdk = 28`**
|
||||||
|
(实测核对:`dumpsys package com.termux` → `targetSdk=28`)。
|
||||||
|
|
||||||
|
所以这个 APK 也锁 **`targetSdk = 28`**。代价是上不了应用商店(个人工具无所谓);
|
||||||
|
换来的是完整 Linux 用户态:`bash`、`apt`、`pkg`、以及 `pkg install python nodejs-lts`。
|
||||||
|
|
||||||
|
### 4.2 APK 里到底装了什么
|
||||||
|
|
||||||
|
```
|
||||||
|
APK 88.4 MB
|
||||||
|
├─ lib/arm64-v8a/libtermux-bootstrap.so 28.0 MB ← Termux 根文件系统(其实是 zip)
|
||||||
|
├─ lib/x86_64/libtermux-bootstrap.so 28.1 MB ← 同上,模拟器用
|
||||||
|
├─ lib/<abi>/libtermux.so ← pty 的 JNI(createSubprocess 等 5 个符号)
|
||||||
|
├─ lib/<abi>/libpython3.13.so ← Chaquopy 的 CPython
|
||||||
|
├─ assets/chaquopy/** ← 内核 + 9 个 Python 工具
|
||||||
|
└─ java/com/termux/{terminal,view}/** ← Termux 的终端模拟器源码(vendored)
|
||||||
|
```
|
||||||
|
|
||||||
|
Termux 的终端库**没有发布到任何 Maven 仓库**(Maven Central 没有,JitPack 也不通),
|
||||||
|
所以是 vendored 源码 + 改了两处 `import com.termux.view.R` 指向我们自己的 R 类。
|
||||||
|
Apache-2.0 声明见 `android/app/src/main/assets/TERMUX_LICENSE.txt`。
|
||||||
|
|
||||||
|
### 4.3 安装流程(移植自 Termux 的 `TermuxInstaller.java`)
|
||||||
|
|
||||||
|
1. 从 APK 里取出 `libtermux-bootstrap.so`
|
||||||
|
2. **切掉 ELF 头**得到纯 zip(见 4.4 ①)
|
||||||
|
3. 解压到 `files/usr`(3226 个文件),给 `bin/ lib/ libexec/` 下的文件补可执行位
|
||||||
|
4. 读 `SYMLINKS.txt`(1146 行,格式 `目标←链接路径`),**用 `/system/bin/sh` 批量 `ln -sf`**
|
||||||
|
—— Java 的 File API 建不了符号链接
|
||||||
|
5. **改写脚本 shebang**(见 4.4 ④)
|
||||||
|
6. 写一份自己的 `etc/doubao.bashrc`
|
||||||
|
|
||||||
|
进度会写进 `files/termux-install.log`(见 §7.6,为什么不用 Logcat)。
|
||||||
|
|
||||||
|
### 4.4 踩过的四个坑(都和你想象的不一样)
|
||||||
|
|
||||||
|
**① `libtermux-bootstrap.so` 不是纯 zip,是「ELF 头 + zip」**
|
||||||
|
文件前 1328 字节是 ELF 头(Android 要求 `lib/` 下的东西得像 ELF,Termux 就把 zip 接在后面)。
|
||||||
|
- `ZipInputStream` 按本地文件头顺序扫,**实测一个条目都读不出来**;
|
||||||
|
- `ZipFile` 走中央目录,但它**不会**像桌面 JVM 那样自动跳过前缀 ——
|
||||||
|
真机 Android 16 上直接报 `Entry at offset zero has invalid LFH signature 464c457f`
|
||||||
|
(`464c457f` 就是 `\x7FELF` 的小端十六进制)。模拟器上碰巧宽松能过,真机不行。
|
||||||
|
|
||||||
|
所以现在的做法:**自己扫第一个 `PK\x03\x04`、把前缀切掉**,再交给 `ZipFile`。
|
||||||
|
|
||||||
|
**② `bin/su` 写不进去(ENOENT)**
|
||||||
|
父目录存在、权限也对,就是 `open` 失败。安卓对这个文件名有额外限制。
|
||||||
|
处理方式:**单个文件失败就跳过并记日志**,不让一个怪文件毁掉整次安装(其余 3226 个照常)。
|
||||||
|
|
||||||
|
**③ 必须设 `LD_PRELOAD` + `TERMUX__PREFIX`(双下划线)**
|
||||||
|
Termux 的二进制里写死了 `/data/data/com.termux/files/usr`。`libtermux-exec.so` 负责把这些路径
|
||||||
|
重写到真实 prefix,但它认的环境变量是:
|
||||||
|
`TERMUX__PREFIX`(**不是** `TERMUX_PREFIX`)、`TERMUX_APP__DATA_DIR`。
|
||||||
|
少一个,bash 就会去读**别的包**的 `/etc/profile`,报 `Permission denied`。
|
||||||
|
|
||||||
|
**④ 脚本的 shebang 也得改**
|
||||||
|
`bin/getprop`、`bin/pkg` 这些是 shell 脚本,第一行写死 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||||
|
内核解析 shebang 时不会经过 termux-exec,照样 EACCES("bad interpreter")。
|
||||||
|
安装时统一把 `bin/ libexec/` 下 79 个脚本的 shebang 前缀改成我们的 prefix 就好了。
|
||||||
|
|
||||||
|
### 4.5 终端界面(真终端 + 控制台退路)
|
||||||
|
|
||||||
|
用 Termux 自己的 `TerminalView` + `libtermux.so` 的 `forkpty` —— 真 pty、真 ANSI,
|
||||||
|
所以 `vim`/`top` 这类全屏程序都能跑。Compose 里用 `AndroidView` 包一层,底下加了手机必备的功能键排:
|
||||||
|
`ESC / TAB / CTRL+C / CTRL+D / ↑↓←→ / HOME / END / | / / / - / ENTER`(没这排连 vim 都退不出来)。
|
||||||
|
|
||||||
|
**但 pty 不是每台机器都给用**。实测 realme(Android 16)上:
|
||||||
|
|
||||||
|
```
|
||||||
|
/dev/pts → Permission denied
|
||||||
|
mount → devpts on /dev/pts type devpts (mode=600,ptmxmode=000)
|
||||||
|
python openpty → OSError: out of pty devices
|
||||||
|
```
|
||||||
|
|
||||||
|
`/dev/pts` 被挂成 `mode=600` 且 `ptmxmode=000`,应用**分配不到从设备 pty**,
|
||||||
|
于是 TerminalSession 一起来就退出(界面上只留一句 `[Process completed]`)。
|
||||||
|
这不是 SELinux 拒绝(logcat 里没有任何 avc),是挂载参数定的,应用侧绕不过去。
|
||||||
|
|
||||||
|
所以做成两条路,**自动切换**:
|
||||||
|
|
||||||
|
| 情况 | 走哪条 |
|
||||||
|
|---|---|
|
||||||
|
| pty 可用(多数设备 / 模拟器) | Termux 的 TerminalView,真终端 |
|
||||||
|
| 会话建起来 2 秒内就退出(判定 pty 不可用) | 自动切「控制台模式」:命令框 + 输出区,跑的是**同一条 Termux bash**,只是没有 tty |
|
||||||
|
|
||||||
|
代价只是没有全屏 TUI 和交互式提示符,跑命令、装包(`pkg install python`)都正常。
|
||||||
|
|
||||||
|
### 4.6 和内核怎么接
|
||||||
|
|
||||||
|
内核里的 `shell` 工具优先走内置 Termux(返回里带 `via: "termux"`),
|
||||||
|
`device` 工具的 `termux_run` / `termux_available` 也走同一条路。
|
||||||
|
因为 Termux 现在就在本进程里,不需要跨进程 intent、也不需要用户去开 `allow-external-apps`。
|
||||||
|
|
||||||
|
### 4.7 安卓端其余细节(Chaquopy / 界面)
|
||||||
|
|
||||||
|
- **Chaquopy 17.0.0** 内嵌 CPython 3.13.9:没有 `python` 可执行文件(所以 `python_run` 是**进程内 exec**,
|
||||||
|
不能起子进程);运行时 pip 只能装纯 Python 轮子;`mcp` 官方 SDK 用不了(要 pydantic v2)
|
||||||
|
- **刻意不装任何第三方包**:Chaquopy 每次构建都要连云 pip,网络一抖整个 APK 就构建不出来
|
||||||
|
(实测 `Could not find a version that satisfies the requirement requests`)。
|
||||||
|
内核只用标准库(`urllib`/`http.server`/`json`),所以留零依赖换来"离线也能构建"。
|
||||||
|
要 requests/numpy 就走内置 Termux:`pkg install python && pip install requests`
|
||||||
|
- **界面**:状态栏不遮挡顶栏(`windowInsetsPadding(WindowInsets.safeDrawing)`)、
|
||||||
|
输入框跟随输入法(`imePadding`)、深色模式自动适配
|
||||||
|
- **流式**:Lynx 那边用 SSE;安卓原生 Compose 走的是**轮询通道**
|
||||||
|
(`transport: "poll"` + `GET /api/chat/poll?runId=&cursor=`),
|
||||||
|
两条件事件类型完全一致,客户端 200ms 取一次增量
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 我实际验证了什么
|
||||||
|
|
||||||
|
### 5.1 安卓端(原生 Compose + 内置 Termux)
|
||||||
|
|
||||||
|
真机(RMX5090 / Android 16 / arm64-v8a):`node scripts/verify-phone.mjs <serial>` → **17/18**。
|
||||||
|
模拟器(Android 14 / x86_64):17/18(唯一失败的是"定位",模拟器没有 GPS)。
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
|---|---|
|
||||||
|
| 构建 | ✅ `assembleDebug` 成功,APK 88.4 MB |
|
||||||
|
| 内核启动 | ✅ `GET /api/health` → `{"ok":true,…}` |
|
||||||
|
| 智能体 / 工具 | ✅ 4 个智能体;8 个内置工具 + MCP 工具 |
|
||||||
|
| 内置 Termux | ✅ 首次解压 3226 个文件 / 388 个命令 / 1146 个符号链接 |
|
||||||
|
| shell | ✅ 真机 `Linux localhost 6.6.118-android15 … aarch64 Android`,`via: termux`,stderr 干净 |
|
||||||
|
| pkg / apt | ✅ 可执行(79 个脚本的 shebang 已修正) |
|
||||||
|
| python_run | ✅ CPython 3.13.9 aarch64(进程内) |
|
||||||
|
| 联网 | ✅ urllib 与 requests 都 200 |
|
||||||
|
| device 信息 | ✅ 型号 / 厂商 / 系统 / SDK / 存储 / 电量 |
|
||||||
|
| 传感器 | ✅ 真机 46 个;加速度计 z≈9.7 m/s²、陀螺仪有数据 |
|
||||||
|
| 定位 | ✅ 真机 `纬度, 经度 ±35m` |
|
||||||
|
| MCP(Python 写的服务) | ✅ 连接 + 列工具 + 调用成功 |
|
||||||
|
| 设置保存 | ✅ 保存前后逐字段一致(含 API Key / 系统提示词),空值攻击被忽略 |
|
||||||
|
| 思考强度映射 | ✅ 两份内核对拍 50/50 一致 |
|
||||||
|
| 界面 | ✅ 对话 / 抽屉 / 终端 / 设置 / 模型面板 截图见文首 |
|
||||||
|
|
||||||
|
### 5.2 其他平台
|
||||||
|
| 项 | 结果 |
|
||||||
|
|---|---|
|
||||||
|
| 浏览器渲染 | ✅ 无头 Edge + CDP,5 个页面全部渲染,控制台无异常 |
|
||||||
|
| 端到端工具调用 | ✅ mock 模型 → 请求 `calc` → Python 返回 → 第二轮流式回答 → 落库 |
|
||||||
|
| Python 工具 | ✅ `calc` `now` `get_weather`(实时数据) `notes` `web_fetch` 全部通过 |
|
||||||
|
| MCP | ✅ filesystem 14 工具、memory 9 工具连接成功;6 类校验错误全部拦截 |
|
||||||
|
| Windows exe | ✅ 冷启动、界面渲染、内置内核、MCP 自动连接 |
|
||||||
|
|
||||||
|
### 5.3 没有 API Key 也能把链路跑通
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node scripts/mock-llm.mjs & # 假的 OpenAI 兼容服务,监听 5299
|
||||||
|
node scripts/verify-phone.mjs emulator-5556 # 或对真机跑
|
||||||
|
```
|
||||||
|
|
||||||
|
mock 会按"第一轮返回 tool_call(calc)、第二轮根据工具结果流式回答"来演,
|
||||||
|
所以能验证完整的 界面 → 内核 → 工具调用 → 流式返回 链路,**不消耗任何额度**。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 给 Lynx 界面(Web / exe)的注意事项
|
||||||
|
|
||||||
|
安卓端已经不用 Lynx 了,这一节只对 Web/exe 有效:
|
||||||
|
|
||||||
|
- **Fresco 必须先初始化**,否则图片不显示;**Fresco 不能解码 SVG**,图标要预先栅格化成 PNG
|
||||||
|
- Lynx 的 `fetch` 没有 `response.body`,所以流式走轮询通道
|
||||||
|
- 状态栏/布局用 `safe-area` 相关变量,别写死 px
|
||||||
|
- 动画(`breathe` 那种)在某些模拟器上会破坏图片绘制,已改成不影响绘制的写法
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 打包踩坑记录
|
||||||
|
|
||||||
|
### 7.1 Windows exe
|
||||||
|
- **exe 必须放纯英文路径**:中文路径下 Electron 的资源加载会失败
|
||||||
|
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 384 MB)
|
||||||
|
- 桌面窗口的验证方式:设 `DOUBAO_CDP_PORT=9444` 启动,
|
||||||
|
再用 `CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着上去截图
|
||||||
|
(Electron 界面只有真窗口渲染得出来,光 curl 验不了)
|
||||||
|
|
||||||
|
### 7.2 Android APK
|
||||||
|
- **`extractNativeLibs` 必须是 true**(Gradle:`packaging.jniLibs.useLegacyPackaging = true`)。
|
||||||
|
否则 `nativeLibraryDir` 是空的,`.so` 全在 APK 里,取 bootstrap 时得从 `applicationInfo.sourceDir` 读
|
||||||
|
- **`targetSdk = 28`**(见 4.1),`abiFilters = ["arm64-v8a", "x86_64"]`
|
||||||
|
- 构建脚本会把 `tools/*.py` 拷进 `app/src/main/python/` 并生成 `bundled_tool_sources.py`
|
||||||
|
- 构建暂存目录用 ASCII 路径(`C:\DoubaoAndroid`),中文路径会让 Gradle/Chaquopy 出问题
|
||||||
|
- **别并发跑两次 Gradle**:会互相踩坏 Chaquopy 的 venv(`Scripts/python.exe does not exist`)
|
||||||
|
|
||||||
|
### 7.3 Chaquopy / 内嵌 Python
|
||||||
|
- `.pyc`-only 打包导致 `loader.get_source()` 失败 → 工具源码用 base64 内嵌
|
||||||
|
- 每次构建都会连云 pip → 已改为零第三方依赖(见 4.7)
|
||||||
|
|
||||||
|
### 7.4 Android 15+ 的 edge-to-edge
|
||||||
|
强制 edge-to-edge 后,状态栏会压住顶栏、输入法会盖住输入框。
|
||||||
|
Compose 里统一在根布局吃 `WindowInsets.safeDrawing`,滚动页再叠 `imePadding()`。
|
||||||
|
|
||||||
|
### 7.5 工具链(Windows)
|
||||||
|
- **Node 20+ 不能直接 `spawn` `.bat`/`.cmd`**(`status=null`),必须 `shell: true`
|
||||||
|
- **PowerShell 会把命令行里的 JSON 引号搅坏**:所有内联 node/python 脚本都写成文件再跑
|
||||||
|
- **PowerShell 的 `Get-Content` / `Set-Content` 会按 GBK 读写 UTF-8 文件**,
|
||||||
|
一读一写就把中文文档转成乱码(本文档就被这么毁过一次)。
|
||||||
|
改文本一律用编辑器工具,别用这两个 cmdlet 做"读进来再写回去"
|
||||||
|
- **Kotlin 的块注释会嵌套**:在 KDoc 里写 `lib/*.so` 里的 `/*` 会开一个嵌套注释,
|
||||||
|
把后面的代码全吞掉,报错却指向文件末尾之外的行
|
||||||
|
|
||||||
|
### 7.6 安卓 `org.json` 不会把 `Map` 转成 JSON 对象(踩过一次大的)
|
||||||
|
|
||||||
|
`json.put("speech", mapOf("autoRead" to true))` **不会**产生 `{"speech":{"autoRead":true}}`,
|
||||||
|
而是把 Map 原样存进去,序列化出来是 `{"speech":"{autoRead=true}"}` —— **值是字符串**。
|
||||||
|
|
||||||
|
这一个坑连锁出四件事:
|
||||||
|
|
||||||
|
1. 内核把字符串写进了 `settings.json`(`speech` 本来是对象,被字符串顶掉了)
|
||||||
|
2. 之后**每一次**读配置(`{**默认, **字符串}`)都抛 `TypeError`
|
||||||
|
3. `/api/state` 从此永远返回 `{"error":"'str' object is not a mapping"}`
|
||||||
|
4. App 把这个错误 JSON 解析成了「全默认状态」,而且**不抛异常**,所以还弹了"已保存"
|
||||||
|
|
||||||
|
用户看到的就是:**点一下语音按钮,模型变「未设置」、昵称变回「我」、会话列表全空**。
|
||||||
|
|
||||||
|
修了三处(缺一不可):
|
||||||
|
- **安卓**:`patchToJson()` 显式递归把 Map/List 转成 `JSONObject`/`JSONArray`(见 `AppViewModel.kt`)
|
||||||
|
- **内核写**:`tools`/`security`/`speech` 这几个子对象,补丁里不是字典就**直接忽略**,
|
||||||
|
宁可这次改动不生效,也不写出读不回来的配置
|
||||||
|
- **内核读**:发现子对象不是字典就**回落默认值**(自愈)——
|
||||||
|
一个坏字段不该让 `/api/state` 永久 500,更不该把用户其它数据一起拖没
|
||||||
|
|
||||||
|
> 为什么之前没暴露:只有**嵌套对象**才触发,而在此之前 App 从没发过嵌套补丁
|
||||||
|
> (`tools` 那两个开关从来没在设置页点过)。教训是——
|
||||||
|
> **跨语言边界传结构化数据时,别信任何一侧的隐式转换**,两端都要有"形状不对就拒绝"的防线。
|
||||||
|
|
||||||
|
### 7.7 部分 ROM 会吞掉应用日志
|
||||||
|
realme / ColorOS 实测:应用自己打的 `Log.i` 在 `adb logcat` 里**一条都看不到**。
|
||||||
|
所以安装进度、终端会话退出原因等关键信息都**落盘**到 `files/termux-install.log`,
|
||||||
|
用 `adb shell run-as com.doubao.lynxclone cat files/termux-install.log` 读。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 已知限制
|
||||||
|
|
||||||
|
- **`targetSdk = 28` 上不了应用商店**(个人侧载没问题)。要上架就得回到"外装 Termux + 桥接"那条路
|
||||||
|
- **pty 在部分 ROM 上不可用**(4.5),自动降级成控制台模式,没有全屏 TUI
|
||||||
|
- **内嵌 CPython 没有 `python` 可执行文件**,`python_run` 是进程内 exec,不能起子进程
|
||||||
|
- **内嵌 Python 没有第三方库**(为了离线可构建),要装就走内置 Termux
|
||||||
|
- **语音通话 / 朗读 / 分享**目前只弹提示,没做
|
||||||
|
- **方舟模型 ID 带日期版本**,默认值取自官方 SDK 常量,是否对你这账号可用请看控制台
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 命令速查
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 开发
|
||||||
|
npm run dev # 起 Node 内核 + Lynx 热更
|
||||||
|
npm run build # 构建 Lynx bundle
|
||||||
|
npm run apk # 构建 APK(--clean 可彻底重建)
|
||||||
|
npm run exe # 打包 Windows exe
|
||||||
|
|
||||||
|
# 验证
|
||||||
|
node scripts/verify-phone.mjs <serial> # 设备端 18 项验收
|
||||||
|
node scripts/parity-thinking.mjs # 两份内核的思考强度对拍
|
||||||
|
node scripts/probe-settings-wipe.mjs <baseUrl> # 设置保存不掉字段(电脑)
|
||||||
|
node scripts/device-settings-attack.mjs <serial> # 设置保存不掉字段(设备)
|
||||||
|
node scripts/test-shell-tool.mjs <serial> [port] # 试内置 Termux 的 shell
|
||||||
|
node scripts/device-state.mjs <serial> # 看设备内核当前设置
|
||||||
|
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||||
|
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||||
|
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||||
|
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||||
|
|
||||||
|
# mock(不消耗额度)
|
||||||
|
node scripts/mock-llm.mjs # 监听 5299
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 参考
|
||||||
|
|
||||||
|
- 火山方舟:<https://www.volcengine.com/docs/82379/1298454>
|
||||||
|
- OpenAI Chat Completions:<https://platform.openai.com/docs/api-reference/chat>
|
||||||
|
- Termux(Apache-2.0):<https://github.com/termux/termux-app>
|
||||||
|
- Chaquopy:<https://chaquo.com/chaquopy/doc/current/>
|
||||||
|
- 调研笔记(`docs/`):
|
||||||
|
- `ai-chat-backend-api-research.md`(Ark/OpenAI/MCP 接口细节与证据强度)
|
||||||
|
- `lynx-ui-research.md`(豆包界面还原的调研)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 许可
|
||||||
|
|
||||||
|
本项目采用 **MIT License**,见 [LICENSE](LICENSE)。
|
||||||
|
|
||||||
|
它**包含或依赖**第三方作品,各自的授权独立于 MIT,使用时请一并遵守:
|
||||||
|
|
||||||
|
| 组件 | 授权 | 用在哪 |
|
||||||
|
|---|---|---|
|
||||||
|
| [Termux](https://github.com/termux/termux-app) | **Apache-2.0** | 终端模拟器源码(vendored)+ pty 的 JNI 库 |
|
||||||
|
| [Chaquopy](https://chaquo.com/chaquopy/) | MIT | APK 内嵌 CPython |
|
||||||
|
| [Jetpack Compose / AndroidX](https://developer.android.com/jetpack) | Apache-2.0 | 安卓界面 |
|
||||||
|
| [LynxJS](https://github.com/lynx-family/lynx) | Apache-2.0 | Web / 桌面版界面 |
|
||||||
|
| [Electron](https://github.com/electron/electron) | MIT | Windows 桌面版打包 |
|
||||||
|
|
||||||
|
Termux 的完整许可在 `android/app/src/main/assets/TERMUX_LICENSE.txt` 与 `APACHE-2.0.txt`。
|
||||||
|
|
||||||
|
> **商标声明**:「豆包」是字节跳动的商标。本项目是出于学习目的的界面复刻,
|
||||||
|
> 与字节跳动无任何关联,不含任何来自豆包 App 的代码或素材。
|
||||||
|
> 界面配色与布局照着公开截图量出,图标使用 Material Icons。
|
||||||
|
|
||||||
|
> **注意**:本仓库**不包含** Termux 的 bootstrap(`libtermux-bootstrap.so`,两个 ABI 共 56 MB),
|
||||||
|
> 因此直接 clone 下来构建 APK 会缺这个文件。补法见 §4.2 与 §4.3。
|
||||||
|
|
||||||
130
android/app/build.gradle.kts
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application")
|
||||||
|
id("org.jetbrains.kotlin.android")
|
||||||
|
id("org.jetbrains.kotlin.plugin.compose")
|
||||||
|
id("com.chaquo.python")
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "com.doubao.lynxclone"
|
||||||
|
compileSdk = 35
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "com.doubao.lynxclone"
|
||||||
|
minSdk = 24
|
||||||
|
/**
|
||||||
|
* ★ 为什么锁死在 28:
|
||||||
|
* Android 10(API 29) 起有 W^X 限制 —— targetSdk >= 29 的应用**不能执行自己数据目录里的二进制**。
|
||||||
|
* Termux(targetSdk=28)正是靠这个豁免,才能把 bash/python/node 解压到
|
||||||
|
* /data/data/<pkg>/files/usr 再 exec。我们要把 Termux 原生内置进来,就必须跟它一样。
|
||||||
|
* 代价:上不了应用商店;部分新系统行为按旧版走(对我们这种本地工具无所谓)。
|
||||||
|
*/
|
||||||
|
targetSdk = 28
|
||||||
|
versionCode = 3
|
||||||
|
versionName = "0.3.0"
|
||||||
|
|
||||||
|
ndk {
|
||||||
|
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||||
|
abiFilters += listOf("arm64-v8a", "x86_64")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = false
|
||||||
|
proguardFiles(
|
||||||
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
|
"proguard-rules.pro",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = "1.8"
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
}
|
||||||
|
|
||||||
|
packaging {
|
||||||
|
jniLibs {
|
||||||
|
/**
|
||||||
|
* ★ 必须为 true(等价于 manifest 里的 extractNativeLibs="true")。
|
||||||
|
* AGP 8.5+ 默认 useLegacyPackaging=false,此时原生库**不会解压到文件系统**,
|
||||||
|
* applicationInfo.nativeLibraryDir 里可能是个空目录 ——
|
||||||
|
* 而 Termux 的 bootstrap 正是以 .so 的形式放在那里被读出来的(Termux 自己也开这个开关)。
|
||||||
|
* 实测不开的话解压出来是 0 个文件。
|
||||||
|
*/
|
||||||
|
useLegacyPackaging = true
|
||||||
|
pickFirsts += listOf(
|
||||||
|
"lib/*/libc++_shared.so",
|
||||||
|
"**/libnapi.so",
|
||||||
|
"**/libnapi_adapter.so",
|
||||||
|
"META-INF/*.kotlin_module",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
resources {
|
||||||
|
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// bootstrap 是数据不是代码,压缩它没意义还拖慢解压
|
||||||
|
androidResources {
|
||||||
|
noCompress += listOf("bundle")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
chaquopy {
|
||||||
|
defaultConfig {
|
||||||
|
version = "3.13"
|
||||||
|
buildPython(
|
||||||
|
providers.environmentVariable("DOUBAO_PYTHON313").getOrElse("C:\\Python313\\python.exe"),
|
||||||
|
)
|
||||||
|
/**
|
||||||
|
* ★ 这里刻意**不装任何第三方包**。
|
||||||
|
*
|
||||||
|
* 原因:Chaquopy 每次构建都要去 PyPI 拉包,网络一抖整个 APK 就构建不出来
|
||||||
|
* (实测 "Could not find a version that satisfies the requirement requests")。
|
||||||
|
* 而内核只用标准库(urllib/http.server/json),根本不需要 requests。
|
||||||
|
*
|
||||||
|
* 用户确实要 requests/httpx/numpy 这些时,走内置 Termux 更合适 —— 真 pip、真轮子:
|
||||||
|
* 在终端里执行 pkg install python && pip install requests
|
||||||
|
* 所以这里保持零依赖,换来"离线也能构建"。
|
||||||
|
*/
|
||||||
|
// pip { install("requests") }
|
||||||
|
}
|
||||||
|
sourceSets {
|
||||||
|
getByName("main") {
|
||||||
|
// Python 内核 + 内置工具(构建脚本会把 tools/*.py 也拷进来)
|
||||||
|
srcDir("../kernel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// 原生 UI 用 Compose
|
||||||
|
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||||
|
implementation("androidx.compose.ui:ui")
|
||||||
|
implementation("androidx.compose.ui:ui-graphics")
|
||||||
|
implementation("androidx.compose.material3:material3")
|
||||||
|
implementation("androidx.compose.material:material-icons-extended")
|
||||||
|
implementation("androidx.activity:activity-compose:1.9.3")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
|
||||||
|
// viewModel() 和 viewModelScope 都在这两个里
|
||||||
|
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
|
||||||
|
implementation("androidx.core:core-ktx:1.13.1")
|
||||||
|
|
||||||
|
// 跟本地内核通信 + 处理系统栏/输入法内边距
|
||||||
|
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||||
|
|
||||||
|
// 注意:Termux 的终端模拟器**没有发布到任何 Maven 仓库**(Maven Central 没有、JitPack 也不通),
|
||||||
|
// 所以它的源码是直接 vendor 进工程的:android/app/src/main/java/com/termux/**
|
||||||
|
// (Apache-2.0,见 assets/TERMUX_LICENSE.txt)
|
||||||
|
}
|
||||||
4
android/app/proguard-rules.pro
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# Lynx 依赖较多反射,保守起见先不混淆
|
||||||
|
-keep class com.lynx.** { *; }
|
||||||
|
-keep class org.lynxsdk.** { *; }
|
||||||
|
-dontwarn com.lynx.**
|
||||||
59
android/app/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
|
<!-- 内核默认跑在手机本地(APK 内嵌 CPython),远程模式才需要联网;两种情况都要 INTERNET -->
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
|
||||||
|
<!-- device 工具的定位能力(用户拒绝也不影响其它功能) -->
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||||
|
|
||||||
|
<!-- 把命令交给 Termux 执行(对方需要在 termux.properties 里开 allow-external-apps) -->
|
||||||
|
<uses-permission android:name="com.termux.permission.RUN_COMMAND" />
|
||||||
|
|
||||||
|
<!-- 语音输入 / 通话要录音。朗读不需要(播音频不要权限) -->
|
||||||
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
|
<!-- 通话时想在被叫/接听场景抢音频焦点用得上;多数机型不加也行 -->
|
||||||
|
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||||
|
|
||||||
|
<!-- Android 11+ 用于判断 Termux 是否安装 -->
|
||||||
|
<queries>
|
||||||
|
<package android:name="com.termux" />
|
||||||
|
<!-- 系统语音识别服务:不声明的话 Android 11+ 查不到可用引擎 -->
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.speech.RecognitionService" />
|
||||||
|
</intent>
|
||||||
|
<!-- 系统 TTS 引擎:同上,用来判断"这台机器到底有没有 TTS" -->
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.intent.action.TTS_SERVICE" />
|
||||||
|
</intent>
|
||||||
|
</queries>
|
||||||
|
|
||||||
|
<!-- 加速度计/陀螺仪等传感器不需要权限 -->
|
||||||
|
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="false" />
|
||||||
|
<uses-feature android:name="android.hardware.sensor.gyroscope" android:required="false" />
|
||||||
|
<uses-feature android:name="android.hardware.location" android:required="false" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:name=".DoubaoApplication"
|
||||||
|
android:allowBackup="false"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:roundIcon="@mipmap/ic_launcher"
|
||||||
|
android:supportsRtl="false"
|
||||||
|
android:usesCleartextTraffic="true"
|
||||||
|
android:theme="@style/AppTheme">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:configChanges="orientation|screenSize|keyboardHidden|uiMode"
|
||||||
|
android:exported="true"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
202
android/app/src/main/assets/APACHE-2.0.txt
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
22
android/app/src/main/assets/TERMUX_LICENSE.txt
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
本 App 内置了 Termux 的组件,均来自开源项目 https://github.com/termux/termux-app (Apache License 2.0)。
|
||||||
|
|
||||||
|
具体包含:
|
||||||
|
|
||||||
|
1. 终端模拟器源码
|
||||||
|
- android/app/src/main/java/com/termux/terminal/**
|
||||||
|
- android/app/src/main/java/com/termux/view/**
|
||||||
|
(来自 termux-app 的 terminal-emulator 与 terminal-view 模块,v0.118.3)
|
||||||
|
|
||||||
|
2. 原生库
|
||||||
|
- android/app/src/main/jniLibs/<abi>/libtermux.so
|
||||||
|
pty 支持(forkpty 等 JNI 实现),TerminalSession 依赖它
|
||||||
|
- android/app/src/main/jniLibs/<abi>/libtermux-bootstrap.so
|
||||||
|
根文件系统(其实是个 zip,含 bash / apt / pkg 等 250+ 个可执行文件与 1146 条符号链接)
|
||||||
|
|
||||||
|
3. 安装逻辑
|
||||||
|
- android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt
|
||||||
|
(按 Termux 的 TermuxInstaller.java 移植:解压 + 用 sh 建符号链接)
|
||||||
|
|
||||||
|
Apache License 2.0 全文见 https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Copyright (c) 2013-2024 Termux contributors
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.doubao.lynxclone
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import com.chaquo.python.Python
|
||||||
|
import com.chaquo.python.android.AndroidPlatform
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 现在只需要两件事:
|
||||||
|
* 1) 启动 Chaquopy(内嵌 CPython,跑 AI 内核)
|
||||||
|
* 2) 别的都不用了 —— 界面改成原生 Compose,Lynx 和 Fresco 都删了
|
||||||
|
*/
|
||||||
|
class DoubaoApplication : Application() {
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
|
||||||
|
// ★ Chaquopy 必须显式启动,否则第一次 Python.getInstance() 会抛:
|
||||||
|
// "Cannot use GenericPlatform on Android. Call Python.start(new AndroidPlatform(context))..."
|
||||||
|
if (!Python.isStarted()) {
|
||||||
|
Python.start(AndroidPlatform(this))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.doubao.lynxclone
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.chaquo.python.Python
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机端的本地 AI 内核(Chaquopy 内嵌 CPython)。
|
||||||
|
*
|
||||||
|
* 为什么要它:手机上装不了 Node,而用户要的是"脱离电脑也能用"。
|
||||||
|
* 内核用 Python 重写了一份(android/kernel),接口和电脑上的 Node 版一模一样,
|
||||||
|
* 所以 Lynx 界面完全不用改,只是把 apiBase 指到 127.0.0.1。
|
||||||
|
*
|
||||||
|
* 注意 Chaquopy 的两个硬约束(都踩过):
|
||||||
|
* 1. 它把 Python 嵌在主进程里,**没有独立 python 可执行文件** → 不能用 subprocess 起 py 脚本
|
||||||
|
* 2. 只有 arm64-v8a / x86_64 两个 ABI
|
||||||
|
*/
|
||||||
|
object LocalKernel {
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var port = 0
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var failure: String? = null
|
||||||
|
|
||||||
|
/** 已启动则直接返回端口;否则同步启动(要在子线程调) */
|
||||||
|
@Synchronized
|
||||||
|
fun ensureStarted(context: Context, preferredPort: Int = 5199): Int {
|
||||||
|
if (port > 0) return port
|
||||||
|
failure = null
|
||||||
|
try {
|
||||||
|
val py = Python.getInstance()
|
||||||
|
val entry = py.getModule("doubao_entry")
|
||||||
|
|
||||||
|
val dataDir = File(context.filesDir, "kernel-data").apply { mkdirs() }.absolutePath
|
||||||
|
// 外部私有目录:不用申请存储权限,用户能通过文件管理器/USB 往里放自己的 py 工具
|
||||||
|
val workDir = (context.getExternalFilesDir(null) ?: File(context.filesDir, "external"))
|
||||||
|
.apply { mkdirs() }.absolutePath
|
||||||
|
|
||||||
|
val actual = entry.callAttr("start", dataDir, workDir, preferredPort).toInt()
|
||||||
|
port = actual
|
||||||
|
android.util.Log.i("DoubaoKernel", "本地内核已就绪 127.0.0.1:$actual data=$dataDir work=$workDir")
|
||||||
|
return actual
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
failure = t.message ?: t.toString()
|
||||||
|
android.util.Log.e("DoubaoKernel", "本地内核启动失败", t)
|
||||||
|
throw t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun baseUrl(): String? = if (port > 0) "http://127.0.0.1:$port" else null
|
||||||
|
|
||||||
|
fun lastFailure(): String? = failure
|
||||||
|
|
||||||
|
/** 工具目录(给界面显示用) */
|
||||||
|
fun workDir(context: Context): String =
|
||||||
|
(context.getExternalFilesDir(null) ?: File(context.filesDir, "external")).absolutePath
|
||||||
|
}
|
||||||
121
android/app/src/main/java/com/doubao/lynxclone/MainActivity.kt
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
package com.doubao.lynxclone
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import com.doubao.lynxclone.data.KernelClient
|
||||||
|
import com.doubao.lynxclone.termux.TermuxInstaller
|
||||||
|
import com.doubao.lynxclone.ui.AppRoot
|
||||||
|
import com.doubao.lynxclone.ui.theme.DoubaoTheme
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 原生 Compose 宿主。
|
||||||
|
*
|
||||||
|
* 启动顺序(都很关键):
|
||||||
|
* 1. 起本地 Python 内核(Chaquopy,跑在进程里,监听 127.0.0.1)
|
||||||
|
* 2. 后台解压内置 Termux 环境(95MB,首次十几秒;之后秒过)
|
||||||
|
* 3. 进主界面 —— 前两步都不阻塞 UI,装到哪一步界面上都看得见
|
||||||
|
*/
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
|
||||||
|
private val client = KernelClient()
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
enableEdgeToEdge()
|
||||||
|
|
||||||
|
var kernelUrl by mutableStateOf("")
|
||||||
|
var status by mutableStateOf("正在启动本地内核…")
|
||||||
|
var termuxReady by mutableStateOf(false)
|
||||||
|
var termuxStatus by mutableStateOf("")
|
||||||
|
|
||||||
|
setContent {
|
||||||
|
DoubaoTheme {
|
||||||
|
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
|
||||||
|
if (kernelUrl.isBlank()) {
|
||||||
|
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
|
Text(status, style = MaterialTheme.typography.bodyLarge)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
AppRoot(
|
||||||
|
client = client,
|
||||||
|
termuxReady = termuxReady,
|
||||||
|
termuxStatus = termuxStatus,
|
||||||
|
onInstallTermux = { installTermux { msg -> termuxStatus = msg } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ① 内核
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val port = withContext(Dispatchers.IO) {
|
||||||
|
runCatching { LocalKernel.ensureStarted(this@MainActivity) }.getOrNull()
|
||||||
|
}
|
||||||
|
if (port != null && port > 0) {
|
||||||
|
client.baseUrl = "http://127.0.0.1:$port"
|
||||||
|
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
||||||
|
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
runCatching { NativeBridge.register(NativeBridge(this@MainActivity)) }
|
||||||
|
}
|
||||||
|
withContext(Dispatchers.IO) { awaitHealthy(port) }
|
||||||
|
kernelUrl = client.baseUrl
|
||||||
|
} else {
|
||||||
|
status = "本地内核启动失败:${LocalKernel.lastFailure() ?: "未知原因"}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ② Termux 环境(不阻塞界面)
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val ready = withContext(Dispatchers.IO) {
|
||||||
|
TermuxInstaller.install(this@MainActivity) { msg -> termuxStatus = msg }
|
||||||
|
}
|
||||||
|
termuxReady = ready
|
||||||
|
termuxStatus = if (ready) "Termux 环境就绪" else "Termux 环境未就绪"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun installTermux(onProgress: (String) -> Unit) {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val ready = withContext(Dispatchers.IO) {
|
||||||
|
TermuxInstaller.install(this@MainActivity, onProgress)
|
||||||
|
}
|
||||||
|
onProgress(if (ready) "已就绪" else "安装失败")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun awaitHealthy(port: Int): Boolean {
|
||||||
|
val deadline = System.currentTimeMillis() + 20_000
|
||||||
|
while (System.currentTimeMillis() < deadline) {
|
||||||
|
try {
|
||||||
|
val conn = java.net.URL("http://127.0.0.1:$port/api/health").openConnection() as java.net.HttpURLConnection
|
||||||
|
conn.connectTimeout = 1200
|
||||||
|
conn.readTimeout = 1200
|
||||||
|
val code = conn.responseCode
|
||||||
|
conn.disconnect()
|
||||||
|
if (code == 200) return true
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// 还没起来,继续等
|
||||||
|
}
|
||||||
|
Thread.sleep(300)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
371
android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt
Normal file
@@ -0,0 +1,371 @@
|
|||||||
|
package com.doubao.lynxclone
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.hardware.Sensor
|
||||||
|
import android.hardware.SensorEvent
|
||||||
|
import android.hardware.SensorEventListener
|
||||||
|
import android.hardware.SensorManager
|
||||||
|
import android.location.Location
|
||||||
|
import android.location.LocationManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.BatteryManager
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Environment
|
||||||
|
import android.os.StatFs
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import com.chaquo.python.Python
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import com.doubao.lynxclone.termux.TermuxShell
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.CountDownLatch
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 暴露给 Python 内核的原生能力。
|
||||||
|
*
|
||||||
|
* Chaquopy 允许 Python 直接调这个类的方法(`from java import jclass` 那套),
|
||||||
|
* 所以内核里的 `device` 工具、剪贴板钩子、选文件钩子都落到这里。
|
||||||
|
*
|
||||||
|
* 线程约定:device() 可能阻塞几秒(采传感器、等定位),
|
||||||
|
* 它只会在内核的 HTTP 工作线程上被调用,**不会**卡住 UI 线程。
|
||||||
|
*/
|
||||||
|
class NativeBridge(private val activity: Activity) {
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 设备能力
|
||||||
|
|
||||||
|
/** 统一入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||||
|
@Suppress("unused")
|
||||||
|
fun device(payloadJson: String): String {
|
||||||
|
val req = try {
|
||||||
|
JSONObject(payloadJson)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
JSONObject()
|
||||||
|
}
|
||||||
|
val action = req.optString("action", "info")
|
||||||
|
return try {
|
||||||
|
when (action) {
|
||||||
|
"info" -> deviceInfo()
|
||||||
|
"battery" -> batteryInfo()
|
||||||
|
"location" -> locationInfo()
|
||||||
|
"sensors" -> sensorList()
|
||||||
|
"sensor" -> sensorSample(req.optString("sensor"), req.optDouble("duration", 1.5))
|
||||||
|
"clipboard_get" -> JSONObject().put("text", readClipboard())
|
||||||
|
"clipboard_set" -> {
|
||||||
|
setClipboard(req.optString("text"))
|
||||||
|
JSONObject().put("ok", true)
|
||||||
|
}
|
||||||
|
// 内置 Termux:完整 Linux 用户态(真 bash / 真 pkg / 真子进程)
|
||||||
|
"termux_available" -> JSONObject().put("installed", TermuxShell.isReady(activity))
|
||||||
|
"termux_run" -> TermuxShell.run(
|
||||||
|
activity,
|
||||||
|
req.optString("command"),
|
||||||
|
req.optString("cwd"),
|
||||||
|
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||||
|
)
|
||||||
|
else -> JSONObject().put("error", "未知 action:$action")
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||||
|
}.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun deviceInfo(): JSONObject {
|
||||||
|
val stat = StatFs(Environment.getDataDirectory().path)
|
||||||
|
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||||
|
val totalGb = stat.totalBytes / 1024.0 / 1024.0 / 1024.0
|
||||||
|
return JSONObject()
|
||||||
|
.put("platform", "Android")
|
||||||
|
.put("model", Build.MODEL)
|
||||||
|
.put("manufacturer", Build.MANUFACTURER)
|
||||||
|
.put("brand", Build.BRAND)
|
||||||
|
.put("device", Build.DEVICE)
|
||||||
|
.put("android", Build.VERSION.RELEASE)
|
||||||
|
.put("sdk", Build.VERSION.SDK_INT)
|
||||||
|
.put("abis", JSONArray(Build.SUPPORTED_ABIS.toList()))
|
||||||
|
.put("storage_free_gb", String.format("%.1f", freeGb))
|
||||||
|
.put("storage_total_gb", String.format("%.1f", totalGb))
|
||||||
|
.put("screen", screenInfo())
|
||||||
|
.put("battery", batteryInfo())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun screenInfo(): String {
|
||||||
|
val metrics = activity.resources.displayMetrics
|
||||||
|
return "${metrics.widthPixels}x${metrics.heightPixels} @${metrics.density}x"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun batteryInfo(): JSONObject {
|
||||||
|
val bm = activity.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager
|
||||||
|
return JSONObject()
|
||||||
|
.put("level_percent", bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: -1)
|
||||||
|
.put("charging", bm?.isCharging ?: false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 定位:先拿最后已知位置,拿不到就等一次单次更新(最多 8 秒) */
|
||||||
|
private fun locationInfo(): JSONObject {
|
||||||
|
val lm = activity.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
|
||||||
|
?: return JSONObject().put("error", "没有 LocationManager")
|
||||||
|
val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
|
||||||
|
var best: Location? = null
|
||||||
|
for (p in providers) {
|
||||||
|
try {
|
||||||
|
if (!lm.isProviderEnabled(p)) continue
|
||||||
|
val loc = lm.getLastKnownLocation(p) ?: continue
|
||||||
|
if (best == null || loc.time > best!!.time) best = loc
|
||||||
|
} catch (t: SecurityException) {
|
||||||
|
return JSONObject().put("error", "缺少定位权限(ACCESS_FINE_LOCATION)")
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// 某些机型会抛 IllegalArgumentException,忽略继续
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (best == null) {
|
||||||
|
val latch = CountDownLatch(1)
|
||||||
|
var fresh: Location? = null
|
||||||
|
val listener = object : android.location.LocationListener {
|
||||||
|
override fun onLocationChanged(location: Location) {
|
||||||
|
fresh = location
|
||||||
|
latch.countDown()
|
||||||
|
}
|
||||||
|
// 老 API 要求实现,留着空实现
|
||||||
|
override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}
|
||||||
|
override fun onProviderEnabled(provider: String) {}
|
||||||
|
override fun onProviderDisabled(provider: String) {}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
activity.runOnUiThread {
|
||||||
|
try {
|
||||||
|
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, listener)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
latch.countDown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
latch.await(8, TimeUnit.SECONDS)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// 忽略
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
lm.removeUpdates(listener)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
}
|
||||||
|
best = fresh
|
||||||
|
}
|
||||||
|
if (best == null) {
|
||||||
|
return JSONObject()
|
||||||
|
.put("available", false)
|
||||||
|
.put("hint", "没拿到定位:确认已开定位开关、已授予权限、或在室内 GPS 信号差时稍后再试")
|
||||||
|
}
|
||||||
|
return JSONObject()
|
||||||
|
.put("available", true)
|
||||||
|
.put("latitude", best!!.latitude)
|
||||||
|
.put("longitude", best!!.longitude)
|
||||||
|
.put("accuracy_m", best!!.accuracy.toDouble())
|
||||||
|
.put("provider", best!!.provider)
|
||||||
|
.put("age_seconds", (System.currentTimeMillis() - best!!.time) / 1000.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val keywordToType = mapOf(
|
||||||
|
"accelerometer" to Sensor.TYPE_ACCELEROMETER,
|
||||||
|
"gyroscope" to Sensor.TYPE_GYROSCOPE,
|
||||||
|
"magnetic" to Sensor.TYPE_MAGNETIC_FIELD,
|
||||||
|
"light" to Sensor.TYPE_LIGHT,
|
||||||
|
"pressure" to Sensor.TYPE_PRESSURE,
|
||||||
|
"proximity" to Sensor.TYPE_PROXIMITY,
|
||||||
|
"gravity" to Sensor.TYPE_GRAVITY,
|
||||||
|
"linear_acceleration" to Sensor.TYPE_LINEAR_ACCELERATION,
|
||||||
|
"rotation_vector" to Sensor.TYPE_ROTATION_VECTOR,
|
||||||
|
"step_counter" to Sensor.TYPE_STEP_COUNTER,
|
||||||
|
"humidity" to Sensor.TYPE_RELATIVE_HUMIDITY,
|
||||||
|
"temperature" to Sensor.TYPE_AMBIENT_TEMPERATURE,
|
||||||
|
"game_rotation_vector" to Sensor.TYPE_GAME_ROTATION_VECTOR,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun sensorManager(): SensorManager? =
|
||||||
|
activity.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
|
||||||
|
|
||||||
|
private fun sensorList(): JSONObject {
|
||||||
|
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||||
|
val arr = JSONArray()
|
||||||
|
for (s in sm.getSensorList(Sensor.TYPE_ALL)) {
|
||||||
|
val key = keywordToType.entries.firstOrNull { it.value == s.type }?.key
|
||||||
|
arr.put(
|
||||||
|
JSONObject()
|
||||||
|
.put("key", key ?: "type_${s.type}")
|
||||||
|
.put("name", s.name)
|
||||||
|
.put("vendor", s.vendor)
|
||||||
|
.put("type", s.type)
|
||||||
|
.put("power_ma", s.power.toDouble()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return JSONObject().put("count", arr.length()).put("sensors", arr)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 采样:注册监听 duration 秒,返回样本序列与统计 */
|
||||||
|
private fun sensorSample(key: String, duration: Double): JSONObject {
|
||||||
|
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||||
|
val name = key.ifBlank { "accelerometer" }
|
||||||
|
val type = keywordToType[name] ?: return JSONObject()
|
||||||
|
.put("error", "不认识的传感器:$name(可用:${keywordToType.keys.joinToString(", ")})")
|
||||||
|
val sensor = sm.getDefaultSensor(type)
|
||||||
|
?: return JSONObject().put("error", "这台设备没有 $name 传感器")
|
||||||
|
|
||||||
|
val seconds = duration.coerceIn(0.2, 10.0)
|
||||||
|
val samples = mutableListOf<FloatArray>()
|
||||||
|
val latch = CountDownLatch(1)
|
||||||
|
val listener = object : SensorEventListener {
|
||||||
|
override fun onSensorChanged(event: SensorEvent) {
|
||||||
|
if (samples.size < 500) samples.add(event.values.copyOf())
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
|
||||||
|
}
|
||||||
|
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME)
|
||||||
|
try {
|
||||||
|
// 用 latch 等不到就超时,靠 await 的返回值判断即可
|
||||||
|
latch.await((seconds * 1000).toLong(), TimeUnit.MILLISECONDS)
|
||||||
|
} finally {
|
||||||
|
sm.unregisterListener(listener)
|
||||||
|
}
|
||||||
|
if (samples.isEmpty()) return JSONObject().put("error", "$name 在采样期内没出数据")
|
||||||
|
|
||||||
|
val dims = samples.first().size
|
||||||
|
val stats = JSONArray()
|
||||||
|
for (d in 0 until dims) {
|
||||||
|
val values = samples.map { it[d].toDouble() }
|
||||||
|
stats.put(
|
||||||
|
JSONObject()
|
||||||
|
.put("avg", values.average())
|
||||||
|
.put("min", values.min())
|
||||||
|
.put("max", values.max())
|
||||||
|
.put("last", values.last()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val last = JSONArray()
|
||||||
|
samples.last().forEach { last.put(it.toDouble()) }
|
||||||
|
return JSONObject()
|
||||||
|
.put("sensor", name)
|
||||||
|
.put("unit", unitOf(name))
|
||||||
|
.put("sample_count", samples.size)
|
||||||
|
.put("seconds", seconds)
|
||||||
|
.put("axes", axisNames(dims))
|
||||||
|
.put("last", last)
|
||||||
|
.put("stats", stats)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun axisNames(dims: Int): JSONArray {
|
||||||
|
val names = listOf("x", "y", "z", "w")
|
||||||
|
val arr = JSONArray()
|
||||||
|
for (i in 0 until dims) arr.put(names.getOrElse(i) { "v$i" })
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun unitOf(name: String): String = when (name) {
|
||||||
|
"accelerometer", "gravity", "linear_acceleration" -> "m/s^2"
|
||||||
|
"gyroscope" -> "rad/s"
|
||||||
|
"magnetic" -> "uT"
|
||||||
|
"light" -> "lx"
|
||||||
|
"pressure" -> "hPa"
|
||||||
|
"proximity" -> "cm"
|
||||||
|
"humidity" -> "%"
|
||||||
|
"temperature" -> "°C"
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 剪贴板 / 选文件
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun setClipboard(text: String) {
|
||||||
|
activity.runOnUiThread {
|
||||||
|
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
cm.setPrimaryClip(ClipData.newPlainText("doubao", text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readClipboard(): String {
|
||||||
|
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
val clip = cm.primaryClip ?: return ""
|
||||||
|
if (clip.itemCount == 0) return ""
|
||||||
|
return clip.getItemAt(0).coerceToText(activity).toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 内核请求"用户选个文件"时调用;把选中的文件复制到 App 私有目录再返回路径 */
|
||||||
|
@Volatile
|
||||||
|
private var pickLatch: CountDownLatch? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var pickedUris: List<Uri> = emptyList()
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun pickFile(): Array<String> {
|
||||||
|
val latch = CountDownLatch(1)
|
||||||
|
pickLatch = latch
|
||||||
|
pickedUris = emptyList()
|
||||||
|
activity.runOnUiThread {
|
||||||
|
try {
|
||||||
|
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||||
|
addCategory(Intent.CATEGORY_OPENABLE)
|
||||||
|
type = "*/*"
|
||||||
|
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
|
||||||
|
}
|
||||||
|
activity.startActivityForResult(intent, REQ_PICK)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
latch.countDown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
latch.await(PICK_TIMEOUT_S, TimeUnit.SECONDS)
|
||||||
|
pickLatch = null
|
||||||
|
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** MainActivity 的 onActivityResult 转进来 */
|
||||||
|
fun onPicked(data: Intent?) {
|
||||||
|
val uris = mutableListOf<Uri>()
|
||||||
|
data?.clipData?.let { clip ->
|
||||||
|
for (i in 0 until clip.itemCount) uris.add(clip.getItemAt(i).uri)
|
||||||
|
}
|
||||||
|
data?.data?.let { uris.add(it) }
|
||||||
|
pickedUris = uris
|
||||||
|
pickLatch?.countDown()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copyIntoCache(uri: Uri): String? = try {
|
||||||
|
val name = displayName(uri) ?: "upload_${System.currentTimeMillis()}"
|
||||||
|
val dir = File(activity.cacheDir, "picked").apply { mkdirs() }
|
||||||
|
val dest = File(dir, name)
|
||||||
|
activity.contentResolver.openInputStream(uri)?.use { input ->
|
||||||
|
dest.outputStream().use { output -> input.copyTo(output) }
|
||||||
|
}
|
||||||
|
dest.absolutePath
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun displayName(uri: Uri): String? = try {
|
||||||
|
activity.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||||
|
val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||||
|
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 安卓上没有"打开文件夹",直接返回提示(设置页会显示不可用) */
|
||||||
|
@Suppress("unused")
|
||||||
|
fun reveal(path: String): String? = null
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val REQ_PICK = 0x4D31
|
||||||
|
private const val PICK_TIMEOUT_S = 120L
|
||||||
|
|
||||||
|
/** 内核起来后把 bridge 注册给 Python */
|
||||||
|
fun register(bridge: NativeBridge) {
|
||||||
|
val entry = Python.getInstance().getModule("doubao_entry")
|
||||||
|
entry.callAttr("set_android_bridge", bridge)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
457
android/app/src/main/java/com/doubao/lynxclone/speech/AudioIo.kt
Normal file
@@ -0,0 +1,457 @@
|
|||||||
|
package com.doubao.lynxclone.speech
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.media.AudioAttributes
|
||||||
|
import android.media.AudioFormat
|
||||||
|
import android.media.AudioRecord
|
||||||
|
import android.media.MediaPlayer
|
||||||
|
import android.media.MediaRecorder
|
||||||
|
import android.media.AudioTrack
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.speech.tts.TextToSpeech
|
||||||
|
import android.speech.tts.UtteranceProgressListener
|
||||||
|
import android.util.Base64
|
||||||
|
import android.util.Log
|
||||||
|
import java.io.File
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 朗读。
|
||||||
|
*
|
||||||
|
* 两条路走同一个入口:
|
||||||
|
* - 云端音色(火山 / OpenAI):内核把音频合成好,以 base64 回来,这里写临时文件用 MediaPlayer 播;
|
||||||
|
* - 系统引擎:直接用 TextToSpeech,不联网、不要 Key。
|
||||||
|
*
|
||||||
|
* 为什么云端音频要落盘再播而不是喂内存:
|
||||||
|
* MediaPlayer 的 setDataSource 只认路径 / FileDescriptor / AssetFileDescriptor,
|
||||||
|
* 内存里的字节要么落盘、要么自己写个 MediaDataSource —— 落盘简单可靠,
|
||||||
|
* 而且能立刻知道"这段音频到底是不是有效文件"(大小、时长)。
|
||||||
|
*/
|
||||||
|
class Speaker(private val context: Context) {
|
||||||
|
|
||||||
|
private var player: MediaPlayer? = null
|
||||||
|
private var tts: TextToSpeech? = null
|
||||||
|
private var ttsReady = false
|
||||||
|
/** TTS 初始化是异步的:没就绪前先攒着,就绪后自动开口 */
|
||||||
|
private val pending = ArrayDeque<String>()
|
||||||
|
|
||||||
|
/** 播完(或被停掉)回调一次,界面用它复位"正在朗读"的状态 */
|
||||||
|
var onFinished: (() -> Unit)? = null
|
||||||
|
|
||||||
|
/** 出错回调:把原因交给界面显示,别静默失败 */
|
||||||
|
var onError: (String) -> Unit = {}
|
||||||
|
|
||||||
|
private var tempFile: File? = null
|
||||||
|
|
||||||
|
val isPlaying: Boolean
|
||||||
|
get() = player?.isPlaying == true
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 云端音频
|
||||||
|
|
||||||
|
/** 播一段云端合成的音频(base64) */
|
||||||
|
fun playBase64(audioBase64: String, mime: String) {
|
||||||
|
stop()
|
||||||
|
val bytes = try {
|
||||||
|
Base64.decode(audioBase64, Base64.DEFAULT)
|
||||||
|
} catch (e: IllegalArgumentException) {
|
||||||
|
onError("音频解码失败:${e.message}")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (bytes.isEmpty()) {
|
||||||
|
onError("内核返回了空音频")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用 mime 猜后缀:MediaPlayer 对未知扩展名会比较挑
|
||||||
|
val ext = when {
|
||||||
|
mime.contains("wav") -> "wav"
|
||||||
|
mime.contains("ogg") -> "ogg"
|
||||||
|
mime.contains("mp4") || mime.contains("aac") -> "m4a"
|
||||||
|
else -> "mp3"
|
||||||
|
}
|
||||||
|
val file = File(context.cacheDir, "tts-${UUID.randomUUID()}.$ext")
|
||||||
|
try {
|
||||||
|
file.writeBytes(bytes)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
onError("写临时音频失败:${e.message}")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tempFile = file
|
||||||
|
|
||||||
|
try {
|
||||||
|
player = MediaPlayer().apply {
|
||||||
|
setAudioAttributes(
|
||||||
|
AudioAttributes.Builder()
|
||||||
|
.setUsage(AudioAttributes.USAGE_ASSISTANT)
|
||||||
|
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
setDataSource(file.absolutePath)
|
||||||
|
setOnCompletionListener { finish() }
|
||||||
|
setOnErrorListener { _, what, extra ->
|
||||||
|
onError("播放失败(what=$what extra=$extra)")
|
||||||
|
finish()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
prepare()
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
onError("播放失败:${e.message}")
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 系统 TTS
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用系统 TTS 念。会按句切分后再排队 ——
|
||||||
|
* TextToSpeech.speak 单次有长度上限(约 4000 字符),长回复整段塞进去会被截断。
|
||||||
|
*/
|
||||||
|
fun speakSystem(text: String) {
|
||||||
|
val chunks = splitSentences(text)
|
||||||
|
if (chunks.isEmpty()) return
|
||||||
|
ensureTts()
|
||||||
|
if (!ttsReady) {
|
||||||
|
pending.addAll(chunks)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
enqueue(chunks)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ensureTts() {
|
||||||
|
if (tts != null) return
|
||||||
|
tts = TextToSpeech(context) { status ->
|
||||||
|
if (status == TextToSpeech.SUCCESS) {
|
||||||
|
ttsReady = true
|
||||||
|
tts?.language = Locale.SIMPLIFIED_CHINESE
|
||||||
|
// 没有这个监听,队列念完了我们不会知道,"正在朗读"的状态就会一直卡着
|
||||||
|
tts?.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
|
||||||
|
override fun onStart(utteranceId: String?) {}
|
||||||
|
|
||||||
|
override fun onDone(utteranceId: String?) {
|
||||||
|
// 只有最后一句念完才算真的结束
|
||||||
|
if (utteranceId == LAST_ID) finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated("基类要求实现", ReplaceWith(""))
|
||||||
|
override fun onError(utteranceId: String?) {
|
||||||
|
onError("系统朗读出错")
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onError(utteranceId: String?, errorCode: Int) {
|
||||||
|
onError("系统朗读出错(code=$errorCode)")
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// 初始化是异步的,就绪后把之前攒下的补上
|
||||||
|
val queued = pending.toList()
|
||||||
|
pending.clear()
|
||||||
|
if (queued.isNotEmpty()) enqueue(queued)
|
||||||
|
} else {
|
||||||
|
onError("系统语音引擎初始化失败(这台机器可能没装 TTS 引擎)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun enqueue(chunks: List<String>) {
|
||||||
|
chunks.forEachIndexed { index, chunk ->
|
||||||
|
val isLast = index == chunks.lastIndex
|
||||||
|
// 全部用 QUEUE_ADD 排队,靠 utteranceId 分辨"最后一句"来收尾
|
||||||
|
tts?.speak(chunk, TextToSpeech.QUEUE_ADD, Bundle(), if (isLast) LAST_ID else "part$index")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 公共
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
try {
|
||||||
|
player?.let {
|
||||||
|
if (it.isPlaying) it.stop()
|
||||||
|
it.release()
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// 释放失败无所谓,下面会把引用清掉
|
||||||
|
}
|
||||||
|
player = null
|
||||||
|
try {
|
||||||
|
tts?.stop()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// 同上
|
||||||
|
}
|
||||||
|
pending.clear()
|
||||||
|
cleanup()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun release() {
|
||||||
|
stop()
|
||||||
|
tts?.shutdown()
|
||||||
|
tts = null
|
||||||
|
ttsReady = false
|
||||||
|
onFinished = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun finish() {
|
||||||
|
cleanup()
|
||||||
|
onFinished?.invoke()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cleanup() {
|
||||||
|
tempFile?.delete()
|
||||||
|
tempFile = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val LAST_ID = "__doubao_last__"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 录音 → WAV。
|
||||||
|
*
|
||||||
|
* 采样率固定 16000 / 单声道 / 16bit:
|
||||||
|
* - 这是 Whisper 等识别服务最常见的输入格式,不用服务端再转;
|
||||||
|
* - 16k 单声道 30 秒也就 1 MB 左右,走手机流量没压力。
|
||||||
|
*
|
||||||
|
* 为什么不直接用 MediaRecorder:它只会吐 m4a/aac,还要额外解码;
|
||||||
|
* AudioRecord 直接给 PCM,套个 44 字节 WAV 头就能发。
|
||||||
|
*/
|
||||||
|
class Recorder(private val context: Context) {
|
||||||
|
|
||||||
|
private var record: AudioRecord? = null
|
||||||
|
private var thread: Thread? = null
|
||||||
|
private val pcm = ArrayList<ByteArray>()
|
||||||
|
private var total = 0
|
||||||
|
private var recording = false
|
||||||
|
private var peakLevel = 0
|
||||||
|
|
||||||
|
/** 录音中的音量(0~100),界面拿它画波形 */
|
||||||
|
val level: Int get() = peakLevel
|
||||||
|
|
||||||
|
val isRecording: Boolean get() = recording
|
||||||
|
|
||||||
|
/** 开始录音。返回 false 表示麦克风不可用(权限或占用) */
|
||||||
|
fun start(): Boolean {
|
||||||
|
if (recording) return false
|
||||||
|
val rate = SAMPLE_RATE
|
||||||
|
val minBuf = AudioRecord.getMinBufferSize(
|
||||||
|
rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
|
||||||
|
)
|
||||||
|
if (minBuf <= 0) return false
|
||||||
|
val bufSize = minBuf * 2
|
||||||
|
val rec = try {
|
||||||
|
AudioRecord(
|
||||||
|
MediaRecorder.AudioSource.VOICE_RECOGNITION,
|
||||||
|
rate,
|
||||||
|
AudioFormat.CHANNEL_IN_MONO,
|
||||||
|
AudioFormat.ENCODING_PCM_16BIT,
|
||||||
|
bufSize,
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "AudioRecord 创建失败", e)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (rec.state != AudioRecord.STATE_INITIALIZED) {
|
||||||
|
rec.release()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
pcm.clear()
|
||||||
|
total = 0
|
||||||
|
peakLevel = 0
|
||||||
|
record = rec
|
||||||
|
recording = true
|
||||||
|
rec.startRecording()
|
||||||
|
|
||||||
|
thread = Thread {
|
||||||
|
val buf = ByteArray(bufSize)
|
||||||
|
while (recording) {
|
||||||
|
val n = rec.read(buf, 0, buf.size)
|
||||||
|
if (n <= 0) continue
|
||||||
|
pcm.add(buf.copyOf(n))
|
||||||
|
total += n
|
||||||
|
peakLevel = peakOf(buf, n)
|
||||||
|
}
|
||||||
|
}.also { it.start() }
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 结束录音并返回 WAV 字节;没录到东西返回 null */
|
||||||
|
fun stop(): ByteArray? {
|
||||||
|
if (!recording) return null
|
||||||
|
recording = false
|
||||||
|
try {
|
||||||
|
thread?.join(800)
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
// 超时就算了,下面的数据照样能用
|
||||||
|
}
|
||||||
|
thread = null
|
||||||
|
try {
|
||||||
|
record?.stop()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// 没 start 成功时 stop 会抛,忽略
|
||||||
|
}
|
||||||
|
record?.release()
|
||||||
|
record = null
|
||||||
|
peakLevel = 0
|
||||||
|
|
||||||
|
if (total < SAMPLE_RATE / 4) return null // 不到 0.25 秒当没说话
|
||||||
|
val body = ByteArray(total)
|
||||||
|
var off = 0
|
||||||
|
for (chunk in pcm) {
|
||||||
|
System.arraycopy(chunk, 0, body, off, chunk.size)
|
||||||
|
off += chunk.size
|
||||||
|
}
|
||||||
|
pcm.clear()
|
||||||
|
return wavHeader(body.size) + body
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancel() {
|
||||||
|
recording = false
|
||||||
|
try {
|
||||||
|
thread?.join(300)
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
thread = null
|
||||||
|
try {
|
||||||
|
record?.stop()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
record?.release()
|
||||||
|
record = null
|
||||||
|
pcm.clear()
|
||||||
|
total = 0
|
||||||
|
peakLevel = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取一小段里最大的振幅,映射成 0~100 */
|
||||||
|
private fun peakOf(buf: ByteArray, len: Int): Int {
|
||||||
|
var peak = 0
|
||||||
|
var i = 0
|
||||||
|
while (i + 1 < len) {
|
||||||
|
// 小端 16bit
|
||||||
|
val v = (buf[i].toInt() and 0xFF) or (buf[i + 1].toInt() shl 8)
|
||||||
|
val abs = if (v < 0) -v else v
|
||||||
|
if (abs > peak) peak = abs
|
||||||
|
i += 2
|
||||||
|
}
|
||||||
|
return (peak * 100 / 32768).coerceIn(0, 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 44 字节标准 WAV 头(PCM 16bit 单声道) */
|
||||||
|
private fun wavHeader(dataLen: Int): ByteArray {
|
||||||
|
val header = ByteArray(44)
|
||||||
|
fun putStr(offset: Int, s: String) {
|
||||||
|
for (i in s.indices) header[offset + i] = s[i].code.toByte()
|
||||||
|
}
|
||||||
|
fun putInt(offset: Int, v: Int) {
|
||||||
|
header[offset] = (v and 0xFF).toByte()
|
||||||
|
header[offset + 1] = ((v shr 8) and 0xFF).toByte()
|
||||||
|
header[offset + 2] = ((v shr 16) and 0xFF).toByte()
|
||||||
|
header[offset + 3] = ((v shr 24) and 0xFF).toByte()
|
||||||
|
}
|
||||||
|
fun putShort(offset: Int, v: Int) {
|
||||||
|
header[offset] = (v and 0xFF).toByte()
|
||||||
|
header[offset + 1] = ((v shr 8) and 0xFF).toByte()
|
||||||
|
}
|
||||||
|
putStr(0, "RIFF")
|
||||||
|
putInt(4, 36 + dataLen)
|
||||||
|
putStr(8, "WAVE")
|
||||||
|
putStr(12, "fmt ")
|
||||||
|
putInt(16, 16)
|
||||||
|
putShort(20, 1) // PCM
|
||||||
|
putShort(22, 1) // 单声道
|
||||||
|
putInt(24, SAMPLE_RATE)
|
||||||
|
putInt(28, SAMPLE_RATE * 2) // 字节率 = 采样率 * 声道 * 位深/8
|
||||||
|
putShort(32, 2) // 块对齐
|
||||||
|
putShort(34, 16) // 位深
|
||||||
|
putStr(36, "data")
|
||||||
|
putInt(40, dataLen)
|
||||||
|
return header
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val SAMPLE_RATE = 16000
|
||||||
|
private const val TAG = "DoubaoRecorder"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 播放本地 PCM(暂时没用到,留着给"边合成边播"的流式方案) */
|
||||||
|
@Suppress("unused")
|
||||||
|
class PcmPlayer {
|
||||||
|
private var track: AudioTrack? = null
|
||||||
|
|
||||||
|
fun play(pcm: ByteArray) {
|
||||||
|
stop()
|
||||||
|
val t = AudioTrack.Builder()
|
||||||
|
.setAudioAttributes(
|
||||||
|
AudioAttributes.Builder()
|
||||||
|
.setUsage(AudioAttributes.USAGE_ASSISTANT)
|
||||||
|
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.setAudioFormat(
|
||||||
|
AudioFormat.Builder()
|
||||||
|
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
|
||||||
|
.setSampleRate(Recorder.SAMPLE_RATE)
|
||||||
|
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.setBufferSizeInBytes(pcm.size.coerceAtLeast(4096))
|
||||||
|
.setTransferMode(AudioTrack.MODE_STATIC)
|
||||||
|
.build()
|
||||||
|
t.write(pcm, 0, pcm.size)
|
||||||
|
t.play()
|
||||||
|
track = t
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
try {
|
||||||
|
track?.stop()
|
||||||
|
track?.release()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
track = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把回复里的 markdown 剥掉再念 —— 否则会念出一堆星号和反引号 */
|
||||||
|
fun stripForSpeech(text: String): String {
|
||||||
|
var s = text
|
||||||
|
s = s.replace(Regex("```[\\s\\S]*?```"), "(代码块)")
|
||||||
|
s = s.replace(Regex("`([^`]*)`"), "$1")
|
||||||
|
s = s.replace(Regex("!\\[[^\\]]*\\]\\([^)]*\\)"), "")
|
||||||
|
s = s.replace(Regex("\\[([^\\]]*)\\]\\([^)]*\\)"), "$1")
|
||||||
|
s = s.replace(Regex("(?m)^#{1,6}\\s*"), "")
|
||||||
|
s = s.replace(Regex("\\*\\*([^*]*)\\*\\*"), "$1")
|
||||||
|
s = s.replace(Regex("(?m)^\\s*[-*+]\\s+"), "")
|
||||||
|
s = s.replace(Regex("\\*"), "")
|
||||||
|
s = s.replace(Regex("~~([^~]*)~~"), "$1")
|
||||||
|
return s.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按句切:中英文句末标点 + 换行,另外照顾超长无标点的段落 */
|
||||||
|
fun splitSentences(text: String, maxLen: Int = 180): List<String> {
|
||||||
|
val clean = stripForSpeech(text)
|
||||||
|
if (clean.isEmpty()) return emptyList()
|
||||||
|
val out = ArrayList<String>()
|
||||||
|
val sb = StringBuilder()
|
||||||
|
for (ch in clean) {
|
||||||
|
sb.append(ch)
|
||||||
|
val boundary = ch in "。!?!?;;\n"
|
||||||
|
if (boundary && sb.length >= 4) {
|
||||||
|
out.add(sb.toString().trim())
|
||||||
|
sb.setLength(0)
|
||||||
|
} else if (sb.length >= maxLen) {
|
||||||
|
out.add(sb.toString().trim())
|
||||||
|
sb.setLength(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sb.isNotBlank()) out.add(sb.toString().trim())
|
||||||
|
return out.filter { it.isNotBlank() }
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
package com.doubao.lynxclone.speech
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.doubao.lynxclone.data.KernelClient
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 语音编排:把「朗读」和「语音输入」串起来,界面只管调方法、看状态。
|
||||||
|
*
|
||||||
|
* 为什么单独抽一层而不是写在 Composable 里:
|
||||||
|
* 1. 录音 / 合成 / 播放都是异步且互斥的(录音时不能播、播的时候不能录),
|
||||||
|
* 这些状态机逻辑放界面里会散得到处都是;
|
||||||
|
* 2. 录音对象持有麦克风,必须跟着界面生命周期释放,集中管理不容易漏。
|
||||||
|
*/
|
||||||
|
class SpeechController(
|
||||||
|
private val context: Context,
|
||||||
|
private val client: KernelClient,
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
) {
|
||||||
|
private val speaker = Speaker(context)
|
||||||
|
private val recorder = Recorder(context)
|
||||||
|
|
||||||
|
/** 正在朗读第几条消息;-1 = 没在念 */
|
||||||
|
var speakingIndex by mutableStateOf(-1)
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** 正在录音(界面画波形、把麦克风图标变红) */
|
||||||
|
var recording by mutableStateOf(false)
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** 正在识别(录音已结束,等内核返回文字) */
|
||||||
|
var transcribing by mutableStateOf(false)
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** 录音时的实时音量 0~100 */
|
||||||
|
var level by mutableStateOf(0)
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** 自动朗读新回复 */
|
||||||
|
var autoRead by mutableStateOf(false)
|
||||||
|
|
||||||
|
/** 一句话的提示,界面用它弹 Snackbar */
|
||||||
|
var notice by mutableStateOf("")
|
||||||
|
|
||||||
|
private var levelJob: Job? = null
|
||||||
|
|
||||||
|
init {
|
||||||
|
speaker.onFinished = { speakingIndex = -1 }
|
||||||
|
speaker.onError = { notice = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 朗读 ------------------------------ */
|
||||||
|
|
||||||
|
/** 念第 index 条消息 */
|
||||||
|
fun speak(text: String, index: Int) {
|
||||||
|
if (text.isBlank()) return
|
||||||
|
// 正在念同一条 → 再点一次就是停
|
||||||
|
if (speakingIndex == index && speaker.isPlaying) {
|
||||||
|
stopSpeaking()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stopSpeaking()
|
||||||
|
// 要开口念了,麦克风必须让出来:一边录一边放会把 AI 自己的声音录进去(自我循环)。
|
||||||
|
// 这里用 cancelRecording 而不是 stopRecording —— 用户点的是"朗读",
|
||||||
|
// 不是"说完了",把半截录音发去识别纯属浪费。
|
||||||
|
cancelRecording()
|
||||||
|
|
||||||
|
speakingIndex = index
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
val result = client.speak(text)
|
||||||
|
if (!result.optBoolean("ok")) {
|
||||||
|
// 云端失败就退回系统 TTS —— 用户点了朗读却一点动静都没有是最差的体验
|
||||||
|
val reason = result.optString("error").ifBlank { "云端合成失败" }
|
||||||
|
Log.w(TAG, "云端朗读失败,改用系统引擎:$reason")
|
||||||
|
notice = "云端失败,改用系统朗读:$reason"
|
||||||
|
speaker.speakSystem(text)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val engine = result.optString("engine")
|
||||||
|
if (engine == "system" || result.isNull("audio")) {
|
||||||
|
speaker.speakSystem(text)
|
||||||
|
} else {
|
||||||
|
speaker.playBase64(result.optString("audio"), result.optString("mime", "audio/mpeg"))
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
notice = "朗读失败:${e.message}"
|
||||||
|
speakingIndex = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopSpeaking() {
|
||||||
|
speaker.stop()
|
||||||
|
speakingIndex = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 自动朗读:新回复刚落地时调它 */
|
||||||
|
fun maybeAutoRead(text: String, index: Int) {
|
||||||
|
if (!autoRead || text.isBlank()) return
|
||||||
|
if (recording) return
|
||||||
|
speak(text, index)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 录音 ------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开始录音。返回 false 表示麦克风起不来(没权限 / 被别的应用占用)。
|
||||||
|
* 界面负责在返回 false 时去申请权限或提示。
|
||||||
|
*/
|
||||||
|
fun startRecording(): Boolean {
|
||||||
|
if (recording) return false
|
||||||
|
stopSpeaking()
|
||||||
|
if (!recorder.start()) {
|
||||||
|
notice = "麦克风起不来(检查录音权限,或有没有别的应用在占用)"
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
recording = true
|
||||||
|
// 波形:每 80ms 采一次音量,够顺滑又不费电
|
||||||
|
levelJob = scope.launch {
|
||||||
|
while (recording) {
|
||||||
|
level = recorder.level
|
||||||
|
delay(80)
|
||||||
|
}
|
||||||
|
level = 0
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 结束录音并发去识别;识别结果通过 onText 回给界面 */
|
||||||
|
fun stopRecording(onText: (String) -> Unit) {
|
||||||
|
if (!recording) return
|
||||||
|
recording = false
|
||||||
|
levelJob?.cancel()
|
||||||
|
levelJob = null
|
||||||
|
level = 0
|
||||||
|
|
||||||
|
val wav = recorder.stop()
|
||||||
|
if (wav == null) {
|
||||||
|
notice = "没录到声音(太短了)"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
transcribing = true
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
val result = client.transcribe(wav)
|
||||||
|
if (result.optBoolean("ok")) {
|
||||||
|
val engine = result.optString("engine")
|
||||||
|
if (engine == "system") {
|
||||||
|
notice = "当前是「系统识别」引擎,请在设置里选 OpenAI 兼容并填 Key"
|
||||||
|
} else {
|
||||||
|
val text = result.optString("text")
|
||||||
|
if (text.isNotBlank()) onText(text) else notice = "没听清"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
notice = result.optString("error").ifBlank { "识别失败" }
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
notice = "识别失败:${e.message}"
|
||||||
|
} finally {
|
||||||
|
transcribing = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取消录音(用户划走、按返回) */
|
||||||
|
fun cancelRecording() {
|
||||||
|
if (!recording) return
|
||||||
|
recording = false
|
||||||
|
levelJob?.cancel()
|
||||||
|
levelJob = null
|
||||||
|
level = 0
|
||||||
|
recorder.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun release() {
|
||||||
|
levelJob?.cancel()
|
||||||
|
levelJob = null
|
||||||
|
recorder.cancel()
|
||||||
|
speaker.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "DoubaoSpeech"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
package com.doubao.lynxclone.termux
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileInputStream
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import java.util.zip.ZipInputStream
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 Termux 的根文件系统(bootstrap)装进应用私有目录。
|
||||||
|
*
|
||||||
|
* 这套逻辑是从 Termux 自己的 `TermuxInstaller.java` 移植过来的(Apache-2.0),
|
||||||
|
* 关键就三步:
|
||||||
|
* 1. 从 `lib/<abi>/libtermux-bootstrap.so` 读 zip(它其实就是个改了名的 zip,
|
||||||
|
* 放在 lib 目录是为了让系统在安装时原样解出来、不被压缩)
|
||||||
|
* 2. 逐条解压到 files/usr,并给 bin/ lib/ 下的文件加可执行位
|
||||||
|
* 3. 读 SYMLINKS.txt(格式 `目标←链接路径`),**用 /system/bin/sh 建符号链接**
|
||||||
|
* —— Java 的 File API 建不了符号链接,只能借 shell
|
||||||
|
*
|
||||||
|
* 为什么必须 targetSdk=28:Android 10 起 targetSdk>=29 的应用不允许执行自己数据目录里的二进制,
|
||||||
|
* 而 bash/python 全在这个目录里。Termux 自己也是锁 28 才活下来的。
|
||||||
|
*/
|
||||||
|
object TermuxInstaller {
|
||||||
|
|
||||||
|
private const val TAG = "DoubaoTermux"
|
||||||
|
private const val BOOTSTRAP_LIB = "libtermux-bootstrap.so"
|
||||||
|
private const val ARROW = "\u2190" // SYMLINKS.txt 里的分隔符
|
||||||
|
|
||||||
|
fun prefix(context: Context): File = File(context.filesDir, "usr")
|
||||||
|
fun home(context: Context): File = File(context.filesDir, "home")
|
||||||
|
fun bashPath(context: Context): String = File(prefix(context), "bin/bash").absolutePath
|
||||||
|
|
||||||
|
/** 装没装:看 bash 在不在(Termux 的 bootstrap 一定带 bash) */
|
||||||
|
fun isInstalled(context: Context): Boolean =
|
||||||
|
File(prefix(context), "bin/bash").exists() && File(prefix(context), "bin/login").exists()
|
||||||
|
|
||||||
|
/** 剩余没装的标记文件,避免半途失败后反复重来 */
|
||||||
|
private fun stampFile(context: Context) = File(context.filesDir, ".termux-bootstrap-ok")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安装日志。
|
||||||
|
*
|
||||||
|
* 为什么要写文件而不是只打 Logcat:部分国产 ROM(实测 realme/ColorOS)会把应用自己打的
|
||||||
|
* log 全过滤掉,出问题时 adb logcat 里一条都看不到,只能靠落盘来诊断。
|
||||||
|
* 位置:files/termux-install.log,可以直接 `adb shell run-as <包名> cat files/termux-install.log`
|
||||||
|
*/
|
||||||
|
private fun logFile(context: Context) = File(context.filesDir, "termux-install.log")
|
||||||
|
|
||||||
|
fun trace(context: Context, message: String) { Log.i(TAG, message)
|
||||||
|
try {
|
||||||
|
logFile(context).appendText("${System.currentTimeMillis()} $message\n")
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// 落盘失败不影响主流程
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安装(幂等)。要在后台线程调用。progress 会报告阶段,给界面显示。
|
||||||
|
* @return true 表示装好(或本来就装好了)
|
||||||
|
*/
|
||||||
|
fun install(context: Context, progress: (String) -> Unit): Boolean {
|
||||||
|
trace(context, "install() 开始;isInstalled=${isInstalled(context)} stamp=${stampFile(context).exists()}")
|
||||||
|
if (stampFile(context).exists() && isInstalled(context)) {
|
||||||
|
// 已经装过也别直接返回:rc 文件是 App 生成的,升级 App 后要跟着更新
|
||||||
|
writeBashRc(context)
|
||||||
|
progress("Termux 环境已就绪")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
val prefix = prefix(context)
|
||||||
|
if (prefix.exists()) prefix.deleteRecursively()
|
||||||
|
prefix.mkdirs()
|
||||||
|
trace(context, "prefix 准备完成:$prefix")
|
||||||
|
|
||||||
|
return try {
|
||||||
|
progress("正在解压运行环境(约 95 MB,首次会慢一点)…")
|
||||||
|
trace(context, "开始解压 bootstrap")
|
||||||
|
val count = extractBootstrap(context, prefix)
|
||||||
|
trace(context, "解压结束,文件数=$count")
|
||||||
|
if (count < 50) {
|
||||||
|
progress("解压结果不对:只出来 $count 个文件")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
progress("正在建立符号链接…")
|
||||||
|
createSymlinks(prefix)
|
||||||
|
trace(context, "符号链接完成")
|
||||||
|
|
||||||
|
progress("正在准备目录…")
|
||||||
|
File(prefix, "tmp").mkdirs()
|
||||||
|
File(prefix, "var").mkdirs()
|
||||||
|
home(context).mkdirs()
|
||||||
|
writeBashRc(context)
|
||||||
|
|
||||||
|
progress("正在修正脚本的解释器路径…")
|
||||||
|
val fixed = fixShebangs(context)
|
||||||
|
trace(context, "改写了 $fixed 个脚本的 shebang")
|
||||||
|
|
||||||
|
val binCount = File(prefix, "bin").list()?.size ?: 0
|
||||||
|
stampFile(context).writeText("ok")
|
||||||
|
progress("Termux 环境安装完成($binCount 个命令)")
|
||||||
|
trace(context, "安装完成:files=$count bin=$binCount")
|
||||||
|
true
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
trace(context, "安装失败:${t.javaClass.simpleName}: ${t.message}")
|
||||||
|
progress("安装失败:${t.message}")
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解压 bootstrap。
|
||||||
|
*
|
||||||
|
* ★ 这里有个坑:`libtermux-bootstrap.so` **不是纯 zip**,而是
|
||||||
|
* 「1328 字节的 ELF 头 + 一个完整 zip」(Android 要求 lib 下的 so 得像 ELF,
|
||||||
|
* Termux 就把 zip 接在 ELF 头后面)。
|
||||||
|
* `ZipInputStream` 是按本地文件头顺序扫的,在安卓上实测一个条目都读不出来;
|
||||||
|
* 而 `ZipFile` 走的是文件尾的中央目录,能直接跳过前面的 ELF 头 —— 所以先落盘再用 ZipFile。
|
||||||
|
*
|
||||||
|
* 注意注释里千万别写 "lib" 加斜杠星号那种通配(Kotlin 块注释会嵌套,会把后面代码全注释掉)。
|
||||||
|
*/
|
||||||
|
private fun extractBootstrap(context: Context, targetDir: File): Int {
|
||||||
|
val cacheZip = File(context.cacheDir, "termux-bootstrap.zip")
|
||||||
|
try {
|
||||||
|
// ① 从 APK 里把那份 .so 原样拷出来
|
||||||
|
val apk = File(context.applicationInfo.sourceDir)
|
||||||
|
val abi = android.os.Build.SUPPORTED_ABIS.firstOrNull() ?: "arm64-v8a"
|
||||||
|
val candidates = listOf(abi, "arm64-v8a", "x86_64")
|
||||||
|
var copied = false
|
||||||
|
java.util.zip.ZipFile(apk).use { apkZip ->
|
||||||
|
for (candidate in candidates) {
|
||||||
|
val entry = apkZip.getEntry("lib/$candidate/$BOOTSTRAP_LIB") ?: continue
|
||||||
|
Log.i(TAG, "bootstrap 来自 APK: lib/$candidate/$BOOTSTRAP_LIB (${entry.size} 字节)")
|
||||||
|
apkZip.getInputStream(entry).use { input ->
|
||||||
|
cacheZip.outputStream().use { out -> input.copyTo(out, 256 * 1024) }
|
||||||
|
}
|
||||||
|
copied = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!copied) {
|
||||||
|
// 退路:有些打包方式会把 .so 解到 nativeLibraryDir
|
||||||
|
val fromLib = File(context.applicationInfo.nativeLibraryDir, BOOTSTRAP_LIB)
|
||||||
|
if (!fromLib.exists()) throw IllegalStateException("APK 里找不到 $BOOTSTRAP_LIB")
|
||||||
|
fromLib.copyTo(cacheZip, overwrite = true)
|
||||||
|
Log.i(TAG, "bootstrap 来自 nativeLibraryDir")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ② 把 ELF 头切掉,得到纯 zip
|
||||||
|
//
|
||||||
|
// ★ 为什么必须切:安卓的 ZipFile **不会**像桌面 JVM 那样自动跳过前缀,
|
||||||
|
// 它按中央目录里记的偏移去读,读到文件开头是 ELF 就报
|
||||||
|
// "Entry at offset zero has invalid LFH signature 464c457f"
|
||||||
|
// (464c457f 就是 \x7FELF 的小端十六进制)。
|
||||||
|
// 模拟器上碰巧宽松能过,真机 Android 16 直接失败 —— 所以自己切最稳。
|
||||||
|
val pureZip = File(context.cacheDir, "termux-bootstrap-pure.zip")
|
||||||
|
val zipOffset = stripPrefix(cacheZip, pureZip)
|
||||||
|
trace(context, "ELF 前缀 ${zipOffset} 字节,已切掉")
|
||||||
|
|
||||||
|
// ③ 用 ZipFile 读纯 zip
|
||||||
|
var count = 0
|
||||||
|
var skipped = 0
|
||||||
|
java.util.zip.ZipFile(pureZip).use { zip ->
|
||||||
|
val entries = zip.entries()
|
||||||
|
while (entries.hasMoreElements()) {
|
||||||
|
val entry = entries.nextElement()
|
||||||
|
val name = entry.name
|
||||||
|
if (name.startsWith("..") || name.contains("../")) continue
|
||||||
|
val outFile = File(targetDir, name)
|
||||||
|
if (entry.isDirectory) {
|
||||||
|
outFile.mkdirs()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val parent = outFile.parentFile
|
||||||
|
if (parent != null && !parent.exists()) parent.mkdirs()
|
||||||
|
|
||||||
|
// ★ 单个文件失败不能把整次安装毁掉:安卓上有个别人为拦的怪名字
|
||||||
|
// (比如 bin/su 会 ENOENT),跳过去照样能用。
|
||||||
|
try {
|
||||||
|
zip.getInputStream(entry).use { input ->
|
||||||
|
FileOutputStream(outFile).use { out -> input.copyTo(out, 256 * 1024) }
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
skipped += 1
|
||||||
|
if (skipped <= 5) {
|
||||||
|
Log.w(
|
||||||
|
TAG,
|
||||||
|
"跳过 $name(${t.javaClass.simpleName}: ${t.message})" +
|
||||||
|
" parent=${parent?.absolutePath} exists=${parent?.exists()}" +
|
||||||
|
" isDir=${parent?.isDirectory}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// bin/ lib/ libexec/ 和根目录下的东西要可执行
|
||||||
|
val rel = name.replace('\\', '/')
|
||||||
|
if (rel.startsWith("bin/") || rel.startsWith("lib/") ||
|
||||||
|
rel.startsWith("libexec/") || !rel.contains('/')
|
||||||
|
) {
|
||||||
|
outFile.setExecutable(true, false)
|
||||||
|
}
|
||||||
|
count += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log.i(TAG, "解压完成,$count 个文件(跳过 $skipped 个)")
|
||||||
|
pureZip.delete()
|
||||||
|
return count
|
||||||
|
} finally {
|
||||||
|
cacheZip.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 `ELF 头 + zip` 切成纯 zip,返回被切掉的前缀长度。
|
||||||
|
* ZIP 的第一个本地文件头签名是 `PK\x03\x04`;ELF 头只有一千多字节,扫前 64KB 足够。
|
||||||
|
*/
|
||||||
|
private fun stripPrefix(src: File, dst: File): Long {
|
||||||
|
FileInputStream(src).use { input ->
|
||||||
|
val head = ByteArray(64 * 1024)
|
||||||
|
val n = input.read(head)
|
||||||
|
if (n <= 4) throw IllegalStateException("bootstrap 文件太小($n 字节)")
|
||||||
|
|
||||||
|
var offset = -1
|
||||||
|
for (i in 0 until n - 3) {
|
||||||
|
if (head[i] == 0x50.toByte() && head[i + 1] == 0x4b.toByte() &&
|
||||||
|
head[i + 2] == 0x03.toByte() && head[i + 3] == 0x04.toByte()
|
||||||
|
) {
|
||||||
|
offset = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (offset < 0) throw IllegalStateException("在文件头 64KB 里找不到 ZIP 签名(PK\\x03\\x04)")
|
||||||
|
|
||||||
|
FileOutputStream(dst).use { out ->
|
||||||
|
out.write(head, offset, n - offset)
|
||||||
|
input.copyTo(out, 256 * 1024)
|
||||||
|
}
|
||||||
|
return offset.toLong()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 建符号链接。Java 建不了 symlink,只能把上千条 ln -s 拼成脚本交给 /system/bin/sh 执行。
|
||||||
|
* SYMLINKS.txt 里的相对路径是相对 prefix 的,所以 cwd 必须设成 prefix。
|
||||||
|
*/
|
||||||
|
private fun createSymlinks(prefix: File) {
|
||||||
|
val symlinksFile = File(prefix, "SYMLINKS.txt")
|
||||||
|
if (!symlinksFile.exists()) {
|
||||||
|
Log.w(TAG, "没有 SYMLINKS.txt,跳过")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val commands = symlinksFile.readLines()
|
||||||
|
.filter { it.contains(ARROW) }
|
||||||
|
.map { line ->
|
||||||
|
val idx = line.indexOf(ARROW)
|
||||||
|
val target = line.substring(0, idx)
|
||||||
|
val link = line.substring(idx + ARROW.length)
|
||||||
|
"ln -sf '$target' '$link'"
|
||||||
|
}
|
||||||
|
symlinksFile.delete()
|
||||||
|
|
||||||
|
if (commands.isEmpty()) return
|
||||||
|
|
||||||
|
// 一次别塞太多,命令行有长度上限
|
||||||
|
commands.chunked(200).forEach { chunk ->
|
||||||
|
val script = chunk.joinToString(" ; ")
|
||||||
|
val proc = ProcessBuilder("/system/bin/sh", "-c", script)
|
||||||
|
.directory(prefix)
|
||||||
|
.redirectErrorStream(true)
|
||||||
|
.start()
|
||||||
|
val output = proc.inputStream.bufferedReader().readText()
|
||||||
|
val code = proc.waitFor()
|
||||||
|
if (code != 0) {
|
||||||
|
Log.w(TAG, "建链接返回 $code:${output.take(400)}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写一份我们自己的 bash rc。
|
||||||
|
*
|
||||||
|
* 为什么需要:Termux 的 bash 是带着编译期路径 `/data/data/com.termux/files/usr/etc/profile`
|
||||||
|
* 构建的,而我们的 prefix 是 `/data/user/0/<我们的包名>/files/usr`。
|
||||||
|
* termux-exec 只重写 **exec 的路径**,管不到 bash 自己 open("/etc/profile"),
|
||||||
|
* 所以登录式 bash 一启动就会报 "Permission denied"。
|
||||||
|
*
|
||||||
|
* ★ 这里**故意不去 source Termux 自带的 etc/profile**:
|
||||||
|
* 真机实测 source 之后 bash 会立刻退出,终端上只留一句 "[Process completed]"
|
||||||
|
* (那份 profile 里有一堆 dpkg/init 的假设,在别人的 prefix 下不成立)。
|
||||||
|
* 交互式终端真正需要的变量这里手工设全就够了。
|
||||||
|
*/
|
||||||
|
private fun writeBashRc(context: Context) {
|
||||||
|
val prefix = prefix(context).absolutePath
|
||||||
|
val home = home(context).absolutePath
|
||||||
|
val rc = File(prefix, "etc/doubao.bashrc")
|
||||||
|
rc.parentFile?.mkdirs()
|
||||||
|
rc.writeText(
|
||||||
|
"""
|
||||||
|
# 由豆包 App 生成:内置 Termux 的交互式 bash 配置(保持最小)
|
||||||
|
export PREFIX="$prefix"
|
||||||
|
export HOME="$home"
|
||||||
|
export TMPDIR="$prefix/tmp"
|
||||||
|
export PATH="$prefix/bin:$prefix/bin/applets:/system/bin:/system/xbin"
|
||||||
|
export LD_LIBRARY_PATH="$prefix/lib"
|
||||||
|
export LD_PRELOAD="$prefix/lib/libtermux-exec.so"
|
||||||
|
export TERM=xterm-256color
|
||||||
|
export LANG=en_US.UTF-8
|
||||||
|
export COLORTERM=truecolor
|
||||||
|
cd "${'$'}HOME" 2>/dev/null || cd /
|
||||||
|
export PS1='\[\e[32m\]\u@termux\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '
|
||||||
|
echo "豆包内置 Termux —— 试试 pkg install python"
|
||||||
|
""".trimIndent() + "\n",
|
||||||
|
Charsets.UTF_8,
|
||||||
|
)
|
||||||
|
trace(context, "已写入 bash rc: ${rc.absolutePath}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把脚本里 shebang 的硬编码前缀改成我们自己的。
|
||||||
|
*
|
||||||
|
* 为什么必须做:Termux 的 bin 下不少命令(getprop、pkg 之类)是 shell 脚本,
|
||||||
|
* 第一行写死了 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||||
|
* 那个路径属于**另一个包**,我们 exec 它会 EACCES ——
|
||||||
|
* 表现是 "bad interpreter: Permission denied"。
|
||||||
|
* termux-exec 只重写 execve 的参数,管不到内核解析 shebang 这一步,所以直接改文件最省事。
|
||||||
|
*/
|
||||||
|
private fun fixShebangs(context: Context): Int {
|
||||||
|
val prefix = prefix(context)
|
||||||
|
val oldPrefix = "/data/data/com.termux/files/usr"
|
||||||
|
val newPrefix = prefix.absolutePath
|
||||||
|
var fixed = 0
|
||||||
|
|
||||||
|
val dirs = listOf(File(prefix, "bin"), File(prefix, "libexec"), File(prefix, "libexec/termux-am"))
|
||||||
|
for (dir in dirs) {
|
||||||
|
val files = dir.listFiles() ?: continue
|
||||||
|
for (file in files) {
|
||||||
|
if (!file.isFile || file.length() > 512 * 1024) continue
|
||||||
|
val head = try {
|
||||||
|
file.inputStream().use { input ->
|
||||||
|
val buf = ByteArray(256)
|
||||||
|
val n = input.read(buf)
|
||||||
|
if (n <= 0) return@use "" else String(buf, 0, n, Charsets.UTF_8)
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!head.startsWith("#!$oldPrefix")) continue
|
||||||
|
|
||||||
|
try {
|
||||||
|
val text = file.readText(Charsets.UTF_8)
|
||||||
|
file.writeText(text.replaceFirst(oldPrefix, newPrefix), Charsets.UTF_8)
|
||||||
|
file.setExecutable(true, false)
|
||||||
|
fixed += 1
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Log.w(TAG, "改 shebang 失败:${file.name}", t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fixed
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 交互式终端应该跑的 shell(配我们自己的 rc) */
|
||||||
|
fun interactiveShellArgs(context: Context): Array<String> =
|
||||||
|
arrayOf("--rcfile", File(prefix(context), "etc/doubao.bashrc").absolutePath, "-i")
|
||||||
|
|
||||||
|
/** 装完之后给内核/工具用的环境变量(Termux 的标准一套) */
|
||||||
|
fun environment(context: Context): Map<String, String> {
|
||||||
|
val prefix = prefix(context).absolutePath
|
||||||
|
val home = home(context).absolutePath
|
||||||
|
val filesDir = context.filesDir.absolutePath
|
||||||
|
val legacy = "/data/data/${context.packageName}/files"
|
||||||
|
return mapOf(
|
||||||
|
"PREFIX" to prefix,
|
||||||
|
"HOME" to home,
|
||||||
|
"TMPDIR" to "$prefix/tmp",
|
||||||
|
"PATH" to "$prefix/bin:$prefix/bin/applets:/system/bin:/system/xbin",
|
||||||
|
"LD_LIBRARY_PATH" to "$prefix/lib",
|
||||||
|
// ★ 这个 LD_PRELOAD 是 Termux 能在 Android 上正常跑命令的关键:
|
||||||
|
// 它把二进制里写死的 /data/data/com.termux/files/usr 重写到我们自己的 prefix。
|
||||||
|
// 不开的话 bash 会去找别的 App 的 profile,报 Permission denied。
|
||||||
|
"LD_PRELOAD" to "$prefix/lib/libtermux-exec.so",
|
||||||
|
/**
|
||||||
|
* ★ 下面这两个是 termux-exec 用来确定"真实 prefix"的变量(从它的 .so 里扫出来的符号名):
|
||||||
|
* TERMUX__PREFIX —— 注意是**双下划线**,写成 TERMUX_PREFIX 它不认
|
||||||
|
* TERMUX_APP__DATA_DIR —— 应用数据目录
|
||||||
|
* 少一个路径重写就不生效,表现是 bash 去读 /data/data/com.termux/... 然后权限拒绝。
|
||||||
|
*/
|
||||||
|
"TERMUX__PREFIX" to prefix,
|
||||||
|
"TERMUX__ROOTFS" to "/",
|
||||||
|
"TERMUX_APP__DATA_DIR" to filesDir,
|
||||||
|
"TERMUX_APP__LEGACY_DATA_DIR" to legacy,
|
||||||
|
"TERMUX_APP__PACKAGE_NAME" to context.packageName,
|
||||||
|
"TERMUX_APP__APP_VERSION_NAME" to "0.3.0",
|
||||||
|
"TERMUX_IS_DEBUGGABLE_BUILD" to "1",
|
||||||
|
"LANG" to "en_US.UTF-8",
|
||||||
|
"LC_ALL" to "en_US.UTF-8",
|
||||||
|
"TERM" to "xterm-256color",
|
||||||
|
"TZ" to "Asia/Shanghai",
|
||||||
|
"ANDROID_ROOT" to "/system",
|
||||||
|
"ANDROID_DATA" to "/data",
|
||||||
|
"EXTERNAL_STORAGE" to "/sdcard",
|
||||||
|
"TERMUX_VERSION" to "0.118.3",
|
||||||
|
"TERMUX_MAIN_PACKAGE_FORMAT" to "debian",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.doubao.lynxclone.termux
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用内置的 Termux 跑命令。
|
||||||
|
*
|
||||||
|
* 和上一版(借外部 Termux 的 RUN_COMMAND intent)的区别:
|
||||||
|
* 现在 Termux 就在本 App 里,直接 ProcessBuilder 起 `$PREFIX/bin/bash -lc` 就行 ——
|
||||||
|
* 不用跨进程、不用用户去开 allow-external-apps、也不需要 Termux 装着。
|
||||||
|
*
|
||||||
|
* 能这么干的前提是 **targetSdk = 28**:Android 10 起 targetSdk>=29 的应用
|
||||||
|
* 不允许执行自己数据目录里的二进制,而 bash 就在那。
|
||||||
|
*/
|
||||||
|
object TermuxShell {
|
||||||
|
|
||||||
|
private const val TAG = "DoubaoTermux"
|
||||||
|
|
||||||
|
fun isReady(context: Context): Boolean = TermuxInstaller.isInstalled(context)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 跑一条命令并等结果。会阻塞,请在后台线程调用。
|
||||||
|
* @return {available, exit_code, stdout, stderr} 或 {available:false, error}
|
||||||
|
*/
|
||||||
|
fun run(context: Context, command: String, cwd: String, timeoutMs: Long): JSONObject {
|
||||||
|
if (!isReady(context)) {
|
||||||
|
return JSONObject()
|
||||||
|
.put("available", false)
|
||||||
|
.put("error", "内置 Termux 环境还没装好")
|
||||||
|
}
|
||||||
|
val prefix = TermuxInstaller.prefix(context)
|
||||||
|
val workdir = File(cwd.ifBlank { TermuxInstaller.home(context).absolutePath })
|
||||||
|
if (!workdir.isDirectory) workdir.mkdirs()
|
||||||
|
|
||||||
|
return try {
|
||||||
|
// 用 -c 而不是 -lc:登录式会去 source 编译期写死的 /etc/profile(那是别的包的路径),
|
||||||
|
// 每次都在 stderr 里冒一条 Permission denied。rc 该设的东西我们在环境变量里都设好了。
|
||||||
|
val proc = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||||
|
.directory(workdir)
|
||||||
|
.apply { environment().putAll(TermuxInstaller.environment(context)) }
|
||||||
|
.start()
|
||||||
|
|
||||||
|
// 读流要放到线程里,否则大输出会把管道塞满导致死锁
|
||||||
|
val outBuf = StringBuilder()
|
||||||
|
val errBuf = StringBuilder()
|
||||||
|
val outThread = Thread { proc.inputStream.bufferedReader().forEachLine { outBuf.appendLine(it) } }
|
||||||
|
val errThread = Thread { proc.errorStream.bufferedReader().forEachLine { errBuf.appendLine(it) } }
|
||||||
|
outThread.start()
|
||||||
|
errThread.start()
|
||||||
|
|
||||||
|
val finished = proc.waitFor(timeoutMs, TimeUnit.MILLISECONDS)
|
||||||
|
if (!finished) {
|
||||||
|
proc.destroyForcibly()
|
||||||
|
return JSONObject()
|
||||||
|
.put("available", true)
|
||||||
|
.put("error", "命令超时(${timeoutMs / 1000}s)")
|
||||||
|
}
|
||||||
|
outThread.join(2000)
|
||||||
|
errThread.join(2000)
|
||||||
|
|
||||||
|
JSONObject()
|
||||||
|
.put("available", true)
|
||||||
|
.put("exit_code", proc.exitValue())
|
||||||
|
.put("stdout", outBuf.toString().takeLast(8000))
|
||||||
|
.put("stderr", errBuf.toString().takeLast(4000))
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Log.e(TAG, "执行失败: $command", t)
|
||||||
|
JSONObject()
|
||||||
|
.put("available", true)
|
||||||
|
.put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
package com.doubao.lynxclone.termux
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import com.termux.terminal.TerminalSession
|
||||||
|
import com.termux.terminal.TerminalSessionClient
|
||||||
|
import com.termux.view.TerminalView
|
||||||
|
import com.termux.view.TerminalViewClient
|
||||||
|
import android.view.KeyEvent
|
||||||
|
import android.view.MotionEvent
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 真·终端会话:用 Termux 自己的 pty(libtermux.so 的 JNI)+ 它的终端模拟器。
|
||||||
|
*
|
||||||
|
* 为什么不用 `Runtime.exec` 拼一个假终端:那样跑不了 vim/top、没有颜色、没有方向键,
|
||||||
|
* 也不是 tty,很多命令行为会不一样。Termux 这套是完整 pty + ANSI 渲染。
|
||||||
|
*/
|
||||||
|
class TermuxTerminal(private val context: Context) {
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var session: TerminalSession? = null
|
||||||
|
private set
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开一个登录 shell。Termux 的标准做法就是跑 `$PREFIX/bin/login`,
|
||||||
|
* 它会按 /etc/profile 把 PATH、PS1、动态库路径都准备好。
|
||||||
|
*/
|
||||||
|
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||||
|
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||||
|
val home = TermuxInstaller.home(context).absolutePath
|
||||||
|
val env = TermuxInstaller.environment(context).map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||||
|
|
||||||
|
val client = object : TerminalSessionClient {
|
||||||
|
override fun onTextChanged(changedSession: TerminalSession) {}
|
||||||
|
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||||
|
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||||
|
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||||
|
TermuxInstaller.trace(context, "终端会话结束,退出码=${finishedSession.exitStatus}")
|
||||||
|
onExit()
|
||||||
|
}
|
||||||
|
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||||
|
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||||
|
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||||
|
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||||
|
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBell(session: TerminalSession) {}
|
||||||
|
override fun onColorsChanged(session: TerminalSession) {}
|
||||||
|
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||||
|
/** 光标样式:0=块 1=竖线 2=下划线,用 Termux 的默认值 */
|
||||||
|
override fun getTerminalCursorStyle(): Int = 1
|
||||||
|
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||||
|
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||||
|
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||||
|
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||||
|
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||||
|
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||||
|
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||||
|
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||||
|
}
|
||||||
|
|
||||||
|
val created = TerminalSession(
|
||||||
|
"$prefix/bin/bash",
|
||||||
|
home,
|
||||||
|
// 用我们自己的 rc:Termux 的 bash 带的是编译期路径 /data/data/com.termux/...,
|
||||||
|
// 直接当登录 shell 跑会去读别的包的 profile,报权限拒绝
|
||||||
|
TermuxInstaller.interactiveShellArgs(context),
|
||||||
|
env,
|
||||||
|
2000,
|
||||||
|
client,
|
||||||
|
)
|
||||||
|
session = created
|
||||||
|
return created
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 给 TerminalView 用的客户端:把按键/手势接上,其余保持默认行为 */
|
||||||
|
fun viewClient(): TerminalViewClient = object : TerminalViewClient {
|
||||||
|
override fun onScale(scale: Float): Float = scale
|
||||||
|
override fun onSingleTapUp(e: MotionEvent) {
|
||||||
|
// 点一下就把软键盘叫出来,手机上最常用
|
||||||
|
(e.source)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun shouldBackButtonBeMappedToEscape(): Boolean = false
|
||||||
|
override fun shouldEnforceCharBasedInput(): Boolean = true
|
||||||
|
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
|
||||||
|
override fun isTerminalViewSelected(): Boolean = true
|
||||||
|
override fun copyModeChanged(copyMode: Boolean) {}
|
||||||
|
override fun onKeyDown(keyCode: Int, e: KeyEvent, session: TerminalSession): Boolean = false
|
||||||
|
override fun onKeyUp(keyCode: Int, e: KeyEvent): Boolean = false
|
||||||
|
override fun onLongPress(event: MotionEvent): Boolean = false
|
||||||
|
override fun readControlKey(): Boolean = false
|
||||||
|
override fun readAltKey(): Boolean = false
|
||||||
|
override fun readShiftKey(): Boolean = false
|
||||||
|
override fun readFnKey(): Boolean = false
|
||||||
|
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession): Boolean = false
|
||||||
|
override fun onEmulatorSet() {}
|
||||||
|
// TerminalViewClient 也继承了 Logger,这 7 个必须实现
|
||||||
|
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||||
|
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||||
|
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||||
|
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||||
|
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||||
|
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||||
|
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun destroy() {
|
||||||
|
try {
|
||||||
|
session?.finishIfRunning()
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Log.w("DoubaoTermux", "关闭会话失败", t)
|
||||||
|
}
|
||||||
|
session = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 给 Compose 的 AndroidView 用:把 view 绑上会话 */
|
||||||
|
fun bindSession(view: TerminalView, terminal: TermuxTerminal, onTitle: (String) -> Unit, onExit: () -> Unit) {
|
||||||
|
val s = terminal.session ?: terminal.createSession(onTitle, onExit)
|
||||||
|
if (view.currentSession !== s) {
|
||||||
|
view.attachSession(s)
|
||||||
|
}
|
||||||
|
view.requestFocus()
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.BorderStroke
|
||||||
|
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.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.imePadding
|
||||||
|
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.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Add
|
||||||
|
import androidx.compose.material.icons.filled.Check
|
||||||
|
import androidx.compose.material.icons.filled.DeleteOutline
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
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.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.doubao.lynxclone.data.Agent
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 智能体页(对应旧版 Lynx 的 Agents.tsx)。
|
||||||
|
*
|
||||||
|
* 几个取舍:
|
||||||
|
*
|
||||||
|
* 1. **列表点一下就"使用"**(照旧版)。编辑要按右边的笔,避免手滑把当前人设换掉。
|
||||||
|
* 当前使用中的那一项有「使用中」标记 —— 没有标记的话用户不知道现在到底是谁在回答。
|
||||||
|
*
|
||||||
|
* 2. **删除只给"自建"的智能体**。内核里 4 个内置智能体(豆包/代码搭子/文案师/数据分析)
|
||||||
|
* 删掉之后内核会重建默认列表,界面上会出现"删了又回来"的诡异现象;
|
||||||
|
* 旧版也是这么藏的(`!builtin` 才显示删除)。自建的才给删,删前再确认一次。
|
||||||
|
*
|
||||||
|
* 3. **「一句话介绍」实际上是内核的 tagline 字段**,而 AppViewModel.saveAgent 的形参叫
|
||||||
|
* greeting、KernelClient 又是透传 —— 现在这份内核(store.create_agent)只认 tagline,
|
||||||
|
* 所以这个输入框的内容**目前存不进去**。这是别人的文件里的契约不一致,
|
||||||
|
* 我按 UI 契约传参,同时在提示文案里写清楚,免得用户以为是自己没保存上。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun AgentsScreen(vm: AppViewModel) {
|
||||||
|
var editing by remember { mutableStateOf<Agent?>(null) }
|
||||||
|
var creating by remember { mutableStateOf(false) }
|
||||||
|
var confirmDelete by remember { mutableStateOf<Agent?>(null) }
|
||||||
|
|
||||||
|
val activeId = vm.state.activeAgent?.id.orEmpty()
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxSize()) {
|
||||||
|
ScreenHeader("智能体", onBack = { vm.screen = Screen.Chat }) {
|
||||||
|
TextButton(onClick = { creating = true }) { Text("新建", fontSize = 13.sp) }
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.fillMaxWidth()
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.imePadding()
|
||||||
|
.padding(horizontal = 14.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||||
|
) {
|
||||||
|
Spacer(Modifier.height(2.dp))
|
||||||
|
|
||||||
|
SettingsCard {
|
||||||
|
FormHint("点一项就切换人设,之后所有新消息都按它回答;点右边的笔可以改。")
|
||||||
|
}
|
||||||
|
|
||||||
|
vm.state.agents.forEach { agent ->
|
||||||
|
AgentRow(
|
||||||
|
agent = agent,
|
||||||
|
active = agent.id == activeId,
|
||||||
|
onUse = { vm.useAgent(agent.id) },
|
||||||
|
onEdit = { editing = agent },
|
||||||
|
onDelete = { confirmDelete = agent },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vm.state.agents.isEmpty()) {
|
||||||
|
SettingsCard { FormHint("还没有智能体,点右上角「新建」加一个。") }
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = { creating = true },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(24.dp),
|
||||||
|
contentPadding = PaddingValues(vertical = 12.dp),
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Add, null, modifier = Modifier.size(18.dp))
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text("新建智能体", fontSize = 15.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
FormHint("每个智能体的系统提示词互相独立;聊天页顶部会显示当前用的是谁。")
|
||||||
|
Spacer(Modifier.height(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 新建 / 编辑 ---------------- */
|
||||||
|
if (creating || editing != null) {
|
||||||
|
val target = editing
|
||||||
|
AgentEditDialog(
|
||||||
|
agent = target,
|
||||||
|
onDismiss = { creating = false; editing = null },
|
||||||
|
onSave = { name, avatar, prompt, tagline ->
|
||||||
|
vm.saveAgent(target?.id, name, avatar, prompt, tagline) {
|
||||||
|
creating = false
|
||||||
|
editing = null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onDelete = if (target != null && !target.builtin) {
|
||||||
|
{ confirmDelete = target }
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 删除确认 ---------------- */
|
||||||
|
confirmDelete?.let { agent ->
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { confirmDelete = null },
|
||||||
|
title = { Text("删除智能体", fontSize = 16.sp) },
|
||||||
|
text = { Text("确定删除「${agent.name}」吗?它的系统提示词也会一起删掉,不能撤销。", fontSize = 13.sp) },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
vm.deleteAgent(agent.id)
|
||||||
|
confirmDelete = null
|
||||||
|
// 正在编辑的就是被删的那个的话,把编辑框一起关掉,否则保存会 404
|
||||||
|
if (editing?.id == agent.id) editing = null
|
||||||
|
}) { Text("删除") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { confirmDelete = null }) { Text("取消") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 一行智能体 ------------------------------ */
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun AgentRow(
|
||||||
|
agent: Agent,
|
||||||
|
active: Boolean,
|
||||||
|
onUse: () -> Unit,
|
||||||
|
onEdit: () -> Unit,
|
||||||
|
onDelete: () -> Unit,
|
||||||
|
) {
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.fillMaxWidth().clickable(onClick = onUse),
|
||||||
|
shape = RoundedCornerShape(14.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surface,
|
||||||
|
border = BorderStroke(
|
||||||
|
1.dp,
|
||||||
|
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.6f),
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(12.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
AvatarCircle(name = agent.name, avatar = agent.avatar, size = 44)
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(agent.name, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||||
|
if (active) {
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
ActiveBadge()
|
||||||
|
}
|
||||||
|
if (agent.builtin) {
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text("内置", fontSize = 10.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
// 摘要:优先用一句话介绍,其次取系统提示词首行,都没有就说通用助手
|
||||||
|
agentSummary(agent),
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
TextButton(onClick = onEdit) { Text("编辑", fontSize = 12.sp) }
|
||||||
|
if (!agent.builtin) {
|
||||||
|
TextButton(onClick = onDelete) { Text("删除", fontSize = 12.sp) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ActiveBadge() {
|
||||||
|
Surface(shape = RoundedCornerShape(6.dp), color = MaterialTheme.colorScheme.primaryContainer) {
|
||||||
|
Row(
|
||||||
|
Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Check,
|
||||||
|
null,
|
||||||
|
modifier = Modifier.size(11.dp),
|
||||||
|
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(2.dp))
|
||||||
|
Text("使用中", fontSize = 10.sp, color = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 编辑弹窗 ------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 编辑/新建弹窗。
|
||||||
|
*
|
||||||
|
* 为什么用"弹窗 + 本地草稿"而不是像旧版那样整页切换成编辑态:
|
||||||
|
* 手机屏幕小,整页切换会丢掉列表的上下文(改什么、改的是哪一个),
|
||||||
|
* 弹窗能一直看到背后列表;而且这几个页面都有返回箭头统一回聊天页的约定,
|
||||||
|
* 页面内再套一层编辑态会让"返回"语义变得含糊。
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalLayoutApi::class)
|
||||||
|
@Composable
|
||||||
|
private fun AgentEditDialog(
|
||||||
|
agent: Agent?,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onSave: (name: String, avatar: String, systemPrompt: String, greeting: String) -> Unit,
|
||||||
|
onDelete: (() -> Unit)?,
|
||||||
|
) {
|
||||||
|
var name by remember { mutableStateOf(agent?.name.orEmpty()) }
|
||||||
|
var avatar by remember { mutableStateOf(agent?.avatar ?: "doubao") }
|
||||||
|
var prompt by remember { mutableStateOf(agent?.systemPrompt.orEmpty()) }
|
||||||
|
var greeting by remember { mutableStateOf(agent?.greeting.orEmpty()) }
|
||||||
|
var error by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(if (agent == null) "新建智能体" else "编辑智能体", fontSize = 16.sp) },
|
||||||
|
text = {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||||
|
FormLabel("头像")
|
||||||
|
FlowRow(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
AvatarKeys.forEach { key ->
|
||||||
|
Box(Modifier.clickable { avatar = key }) {
|
||||||
|
// 选中态画在 AvatarCircle 的外圈上,不改变尺寸
|
||||||
|
AvatarCircle(name = "", avatar = key, size = 34, selected = avatar == key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
FormLabel("名称")
|
||||||
|
OutlinedTextField(
|
||||||
|
value = name,
|
||||||
|
onValueChange = { name = it },
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||||
|
placeholder = { Text("例如:翻译官", fontSize = 13.sp) },
|
||||||
|
singleLine = true,
|
||||||
|
textStyle = TextStyle(fontSize = 14.sp),
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
FormLabel("问候语 / 一句话介绍")
|
||||||
|
OutlinedTextField(
|
||||||
|
value = greeting,
|
||||||
|
onValueChange = { greeting = it },
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||||
|
placeholder = { Text("显示在列表里,也用作首屏问候", fontSize = 13.sp) },
|
||||||
|
singleLine = true,
|
||||||
|
textStyle = TextStyle(fontSize = 14.sp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"列表摘要会显示这句;新会话首屏也用它打招呼。",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
FormLabel("系统提示词")
|
||||||
|
OutlinedTextField(
|
||||||
|
value = prompt,
|
||||||
|
onValueChange = { prompt = it },
|
||||||
|
modifier = Modifier.fillMaxWidth().height(150.dp).padding(top = 6.dp),
|
||||||
|
placeholder = { Text("这个人设、规则、说话风格…", fontSize = 13.sp) },
|
||||||
|
textStyle = TextStyle(fontSize = 13.sp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"和它聊天时,这段提示词会覆盖全局系统提示词。",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (error.isNotBlank()) {
|
||||||
|
Text(error, fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
if (name.isBlank()) {
|
||||||
|
error = "名称不能为空"
|
||||||
|
} else {
|
||||||
|
onSave(name.trim(), avatar, prompt, greeting.trim())
|
||||||
|
}
|
||||||
|
}) { Text("保存") }
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
Row {
|
||||||
|
if (onDelete != null) {
|
||||||
|
TextButton(onClick = onDelete) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.DeleteOutline,
|
||||||
|
null,
|
||||||
|
modifier = Modifier.size(16.dp),
|
||||||
|
tint = MaterialTheme.colorScheme.error,
|
||||||
|
)
|
||||||
|
Text("删除", color = MaterialTheme.colorScheme.error, fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TextButton(onClick = onDismiss) { Text("取消") }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 列表里那一行摘要文案 */
|
||||||
|
private fun agentSummary(agent: Agent): String = when {
|
||||||
|
agent.greeting.isNotBlank() -> agent.greeting
|
||||||
|
agent.systemPrompt.isNotBlank() -> agent.systemPrompt.lineSequence().firstOrNull { it.isNotBlank() } ?: "通用助手"
|
||||||
|
else -> "通用助手"
|
||||||
|
}
|
||||||
301
android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt
Normal file
@@ -0,0 +1,301 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
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.slideInHorizontally
|
||||||
|
import androidx.compose.animation.slideOutHorizontally
|
||||||
|
import androidx.compose.animation.togetherWith
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.*
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
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.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.ViewModelProvider
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import com.doubao.lynxclone.data.Conversation
|
||||||
|
import com.doubao.lynxclone.data.KernelClient
|
||||||
|
|
||||||
|
/** 建 ViewModel 并把 client 注入进去(没上 DI 框架,手写个工厂就够) */
|
||||||
|
@Composable
|
||||||
|
fun rememberAppViewModel(client: KernelClient): AppViewModel =
|
||||||
|
viewModel(factory = object : ViewModelProvider.Factory {
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
override fun <T : ViewModel> create(modelClass: Class<T>): T = AppViewModel(client) as T
|
||||||
|
})
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AppRoot(
|
||||||
|
client: KernelClient,
|
||||||
|
termuxReady: Boolean,
|
||||||
|
termuxStatus: String,
|
||||||
|
onInstallTermux: () -> Unit,
|
||||||
|
) {
|
||||||
|
val vm = rememberAppViewModel(client)
|
||||||
|
LaunchedEffect(Unit) { vm.refresh() }
|
||||||
|
|
||||||
|
// 提示条 2.5 秒后自动消失
|
||||||
|
LaunchedEffect(vm.hint) {
|
||||||
|
if (vm.hint.isNotBlank()) {
|
||||||
|
kotlinx.coroutines.delay(2500)
|
||||||
|
vm.hint = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(doubaoBg())
|
||||||
|
// edge-to-edge 下得自己吃系统栏/输入法内边距
|
||||||
|
.windowInsetsPadding(WindowInsets.safeDrawing),
|
||||||
|
) {
|
||||||
|
// 页面切换带淡入 + 轻微位移,不然是"啪"一下就换了
|
||||||
|
AnimatedContent(
|
||||||
|
targetState = vm.screen,
|
||||||
|
transitionSpec = {
|
||||||
|
val forward = targetState != Screen.Chat
|
||||||
|
val dir = if (forward) 1 else -1
|
||||||
|
(slideInHorizontally(tween(240)) { it / 14 * dir } + fadeIn(tween(200))) togetherWith
|
||||||
|
(slideOutHorizontally(tween(200)) { -it / 14 * dir } + fadeOut(tween(150)))
|
||||||
|
},
|
||||||
|
label = "screen",
|
||||||
|
) { screen ->
|
||||||
|
when (screen) {
|
||||||
|
Screen.Chat -> ChatScreen(vm)
|
||||||
|
Screen.Profile -> ProfileScreen(vm)
|
||||||
|
Screen.Settings -> SettingsScreen(vm)
|
||||||
|
Screen.Skills -> SkillsScreen(vm)
|
||||||
|
Screen.Agents -> AgentsScreen(vm)
|
||||||
|
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 抽屉:左边滑进来 + 遮罩淡入
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = vm.drawerOpen,
|
||||||
|
enter = slideInHorizontally(tween(260)) { -it } + fadeIn(tween(180)),
|
||||||
|
exit = slideOutHorizontally(tween(220)) { -it } + fadeOut(tween(150)),
|
||||||
|
) {
|
||||||
|
DrawerOverlay(vm)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vm.hint.isNotBlank()) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.align(Alignment.BottomCenter)
|
||||||
|
.padding(24.dp)
|
||||||
|
.clip(RoundedCornerShape(18.dp))
|
||||||
|
.background(Color(0xE61F2329))
|
||||||
|
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||||
|
) {
|
||||||
|
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 抽屉 ------------------------------ */
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DrawerOverlay(vm: AppViewModel) {
|
||||||
|
Row(Modifier.fillMaxSize()) {
|
||||||
|
Column(
|
||||||
|
Modifier
|
||||||
|
.fillMaxHeight()
|
||||||
|
.width(300.dp)
|
||||||
|
.background(doubaoSurface()),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(start = 20.dp, end = 16.dp, top = 18.dp, bottom = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text("豆包", fontSize = 26.sp, fontWeight = FontWeight.Bold, color = doubaoText())
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Search, "搜索", tint = doubaoText(),
|
||||||
|
modifier = Modifier.size(22.dp).clickable { vm.showHint("搜索还没做") },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||||
|
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||||
|
vm.screen = Screen.Agents; vm.drawerOpen = false
|
||||||
|
}
|
||||||
|
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
|
||||||
|
vm.screen = Screen.Skills; vm.drawerOpen = false
|
||||||
|
}
|
||||||
|
DrawerItem(Icons.Filled.Terminal, "终端") {
|
||||||
|
vm.screen = Screen.Terminal; vm.drawerOpen = false
|
||||||
|
}
|
||||||
|
DrawerItem(Icons.Filled.Settings, "设置") {
|
||||||
|
vm.screen = Screen.Settings; vm.drawerOpen = false
|
||||||
|
}
|
||||||
|
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||||
|
DrawerItem(
|
||||||
|
Icons.Filled.Memory, "模型",
|
||||||
|
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
|
||||||
|
) {
|
||||||
|
vm.modelPickerOpen = true
|
||||||
|
vm.drawerOpen = false
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
SectionLabel("置顶", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||||
|
|
||||||
|
LazyColumn(Modifier.weight(1f)) {
|
||||||
|
items(vm.state.conversations.size) { i ->
|
||||||
|
ConversationRow(vm, vm.state.conversations[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { vm.screen = Screen.Profile; vm.drawerOpen = false }
|
||||||
|
.padding(horizontal = 20.dp, vertical = 16.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier.size(34.dp).clip(CircleShape).background(Doubao.Blue),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Text(vm.settings.nickname.take(1), color = Color.White, fontSize = 14.sp)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Text(vm.settings.nickname, fontSize = 15.sp, color = doubaoText())
|
||||||
|
Spacer(Modifier.width(4.dp))
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.ChevronRight, null,
|
||||||
|
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.fillMaxHeight()
|
||||||
|
.background(Doubao.Scrim)
|
||||||
|
.clickable { vm.drawerOpen = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DrawerItem(
|
||||||
|
icon: ImageVector,
|
||||||
|
label: String,
|
||||||
|
trailing: String = "",
|
||||||
|
onClick: () -> Unit,
|
||||||
|
) {
|
||||||
|
val source = remember { MutableInteractionSource() }
|
||||||
|
val pressed by source.collectIsPressedAsState()
|
||||||
|
val bg by animateColorAsState(
|
||||||
|
targetValue = if (pressed) doubaoCard() else Color.Transparent,
|
||||||
|
animationSpec = tween(120),
|
||||||
|
label = "itemBg",
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||||
|
.clip(RoundedCornerShape(12.dp))
|
||||||
|
.background(bg)
|
||||||
|
.clickable(interactionSource = source, indication = null, onClick = onClick)
|
||||||
|
.padding(horizontal = 10.dp, vertical = 13.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||||
|
Spacer(Modifier.width(14.dp))
|
||||||
|
Text(label, fontSize = 16.sp, color = doubaoText())
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
if (trailing.isNotBlank()) {
|
||||||
|
Text(trailing, fontSize = 13.sp, color = doubaoTextSecondary())
|
||||||
|
Spacer(Modifier.width(4.dp))
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.KeyboardArrowDown, null,
|
||||||
|
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ConversationRow(vm: AppViewModel, conv: Conversation) {
|
||||||
|
val active = conv.id == vm.activeConversationId
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||||
|
.clip(RoundedCornerShape(14.dp))
|
||||||
|
.background(if (active) doubaoCard() else Color.Transparent)
|
||||||
|
.clickable { vm.openConversation(conv.id) }
|
||||||
|
.padding(horizontal = 10.dp, vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier.size(38.dp).clip(RoundedCornerShape(19.dp)).background(doubaoHeroRing()),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Text(conv.title.take(1), color = Doubao.Blue, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(conv.title, fontSize = 15.sp, color = doubaoText(), maxLines = 1)
|
||||||
|
Text(
|
||||||
|
conv.preview.ifBlank { "还没有消息" },
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
|
||||||
|
modifier = Modifier.size(18.dp).clickable { vm.deleteConversation(conv) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 文案小工具 ------------------------------ */
|
||||||
|
|
||||||
|
fun shortModel(model: String): String = when {
|
||||||
|
model.isBlank() -> "未设置"
|
||||||
|
model.startsWith("ep-") -> "接入点 ${model.take(8)}"
|
||||||
|
model.startsWith("doubao-seed-2-1-pro") -> "豆包 Pro"
|
||||||
|
model.startsWith("doubao-seed-1-8") -> "豆包 1.8"
|
||||||
|
model.startsWith("doubao-seed-1-6") -> "豆包 1.6"
|
||||||
|
model.startsWith("doubao") -> "豆包"
|
||||||
|
model.startsWith("deepseek-r1") -> "DeepSeek R1"
|
||||||
|
model.startsWith("deepseek") -> "DeepSeek"
|
||||||
|
model.startsWith("gpt-5") -> if (model.contains("mini")) "GPT-5 mini" else "GPT-5"
|
||||||
|
model.startsWith("gpt-4o") -> if (model.contains("mini")) "GPT-4o mini" else "GPT-4o"
|
||||||
|
else -> if (model.length > 16) model.take(14) + "…" else model
|
||||||
|
}
|
||||||
|
|
||||||
|
fun thinkingLabel(level: String): String = when (level) {
|
||||||
|
"off" -> "快速"
|
||||||
|
"low" -> "低"
|
||||||
|
"medium" -> "中"
|
||||||
|
"high" -> "深度思考"
|
||||||
|
else -> "自动"
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateListOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.doubao.lynxclone.data.Agent
|
||||||
|
import com.doubao.lynxclone.data.AppState
|
||||||
|
import com.doubao.lynxclone.data.Attachment
|
||||||
|
import com.doubao.lynxclone.data.ChatMessage
|
||||||
|
import com.doubao.lynxclone.data.Conversation
|
||||||
|
import com.doubao.lynxclone.data.KernelClient
|
||||||
|
import com.doubao.lynxclone.data.StreamEvent
|
||||||
|
import com.doubao.lynxclone.data.ToolTrace
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应) */
|
||||||
|
enum class Screen { Chat, Profile, Settings, Skills, Agents, Terminal }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全局状态。界面只读这里的状态、只调这里的方法,网络全在 KernelClient 里。
|
||||||
|
*/
|
||||||
|
class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||||
|
|
||||||
|
var state by mutableStateOf(AppState())
|
||||||
|
private set
|
||||||
|
var screen by mutableStateOf(Screen.Chat)
|
||||||
|
var drawerOpen by mutableStateOf(false)
|
||||||
|
var loading by mutableStateOf(true)
|
||||||
|
var bootError by mutableStateOf("")
|
||||||
|
var hint by mutableStateOf("")
|
||||||
|
|
||||||
|
val messages = mutableStateListOf<ChatMessage>()
|
||||||
|
var activeConversationId by mutableStateOf("c_main")
|
||||||
|
var streaming by mutableStateOf(false)
|
||||||
|
private set
|
||||||
|
var draft by mutableStateOf("")
|
||||||
|
val attachments = mutableStateListOf<Attachment>()
|
||||||
|
/** 正在看「思考过程」的消息下标;-1 表示没开 */
|
||||||
|
var thinkingIndex by mutableStateOf(-1)
|
||||||
|
/** 模型 / 思考强度面板(底部升起) */
|
||||||
|
var modelPickerOpen by mutableStateOf(false)
|
||||||
|
|
||||||
|
private var chatJob: AtomicBoolean? = null
|
||||||
|
|
||||||
|
val settings get() = state.settings
|
||||||
|
val agents: List<Agent> get() = state.agents
|
||||||
|
val activeAgent: Agent? get() = state.activeAgent
|
||||||
|
|
||||||
|
fun refresh(onDone: (() -> Unit)? = null) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
state = withContext(Dispatchers.IO) { client.state() }
|
||||||
|
bootError = ""
|
||||||
|
} catch (e: Exception) {
|
||||||
|
bootError = e.message ?: "连不上内核"
|
||||||
|
} finally {
|
||||||
|
loading = false
|
||||||
|
onDone?.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun showHint(text: String) {
|
||||||
|
hint = text
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 点赞/点踩:只改本地状态(没接后端反馈接口),点同一个再点一次就取消 */
|
||||||
|
fun onFeedback(index: Int, kind: String) {
|
||||||
|
if (index !in messages.indices) return
|
||||||
|
val current = messages[index]
|
||||||
|
messages[index] = current.copy(feedback = if (current.feedback == kind) null else kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动朗读开关。
|
||||||
|
*
|
||||||
|
* 声音那边由 SpeechController 立即生效;这里负责**落盘**,
|
||||||
|
* 否则退出 App 再进来又变回关的,用户会以为没保存上。
|
||||||
|
*/
|
||||||
|
fun setAutoRead(on: Boolean) {
|
||||||
|
saveSettings(mapOf("speech" to mapOf("autoRead" to on)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 会话 ------------------------------ */
|
||||||
|
|
||||||
|
fun openConversation(id: String) {
|
||||||
|
activeConversationId = id
|
||||||
|
drawerOpen = false
|
||||||
|
screen = Screen.Chat
|
||||||
|
viewModelScope.launch {
|
||||||
|
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
||||||
|
messages.clear()
|
||||||
|
messages.addAll(list)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun newTopic() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
||||||
|
refresh()
|
||||||
|
if (conv != null) openConversation(conv.id) else {
|
||||||
|
messages.clear()
|
||||||
|
activeConversationId = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteConversation(conv: Conversation) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
runCatching { withContext(Dispatchers.IO) { client.deleteConversation(conv.id) } }
|
||||||
|
refresh()
|
||||||
|
showHint("已删除「${conv.title}」")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 发消息 ------------------------------ */
|
||||||
|
|
||||||
|
fun send() {
|
||||||
|
val text = draft.trim()
|
||||||
|
if (text.isEmpty() && attachments.isEmpty()) return
|
||||||
|
if (streaming) return
|
||||||
|
|
||||||
|
val files = attachments.toList()
|
||||||
|
draft = ""
|
||||||
|
attachments.clear()
|
||||||
|
runChat(text, files)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun regenerate() {
|
||||||
|
if (streaming) return
|
||||||
|
val lastUser = messages.lastOrNull { it.role == "user" } ?: return
|
||||||
|
// 去掉最后一条助手回复再重来
|
||||||
|
while (messages.isNotEmpty() && messages.last().role != "user") messages.removeAt(messages.size - 1)
|
||||||
|
runChat(lastUser.content, emptyList())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runChat(text: String, files: List<Attachment>) {
|
||||||
|
messages.add(ChatMessage(role = "user", content = text, attachments = files))
|
||||||
|
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
|
||||||
|
streaming = true
|
||||||
|
|
||||||
|
val cancel = AtomicBoolean(false)
|
||||||
|
chatJob = cancel
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
client.chat(
|
||||||
|
conversationId = activeConversationId.ifBlank { "c_main" },
|
||||||
|
message = text,
|
||||||
|
attachments = files,
|
||||||
|
agentId = activeAgent?.id,
|
||||||
|
cancelled = cancel,
|
||||||
|
) { event -> onStreamEvent(event) }
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { "出错了:${e.message}" }) }
|
||||||
|
showHint("出错了:${e.message}")
|
||||||
|
} finally {
|
||||||
|
streaming = false
|
||||||
|
chatJob = null
|
||||||
|
patchLast { it.copy(pending = false) }
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 事件回调可能在 IO 线程,统一切回主线程改状态 */
|
||||||
|
private fun onStreamEvent(event: StreamEvent) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
when (event) {
|
||||||
|
is StreamEvent.Delta -> patchLast { it.copy(content = it.content + event.text) }
|
||||||
|
is StreamEvent.Reasoning -> patchLast { it.copy(reasoning = it.reasoning + event.text) }
|
||||||
|
is StreamEvent.ToolCall -> patchLast {
|
||||||
|
it.copy(toolTrace = it.toolTrace + ToolTrace(id = event.id, name = event.name))
|
||||||
|
}
|
||||||
|
is StreamEvent.ToolResult -> patchLast { msg ->
|
||||||
|
msg.copy(toolTrace = msg.toolTrace.map {
|
||||||
|
if (it.id == event.id) it.copy(ok = event.ok, result = event.result) else it
|
||||||
|
})
|
||||||
|
}
|
||||||
|
is StreamEvent.Failure -> {
|
||||||
|
val text = if (event.hint.isNotBlank()) "出错了:${event.message}|${event.hint}" else "出错了:${event.message}"
|
||||||
|
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { text }) }
|
||||||
|
showHint(text)
|
||||||
|
}
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun patchLast(fn: (ChatMessage) -> ChatMessage) {
|
||||||
|
for (i in messages.indices.reversed()) {
|
||||||
|
if (messages[i].role == "assistant") {
|
||||||
|
messages[i] = fn(messages[i])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 设置 / 工具 ------------------------------ */
|
||||||
|
|
||||||
|
fun saveSettings(patch: Map<String, Any?>, onDone: (() -> Unit)? = null) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val json = patchToJson(patch)
|
||||||
|
state = withContext(Dispatchers.IO) { client.saveSettings(json) }
|
||||||
|
showHint("已保存")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
showHint("保存失败:${e.message}")
|
||||||
|
} finally {
|
||||||
|
onDone?.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setThinkingLevel(level: String) = saveSettings(mapOf("thinkingLevel" to level))
|
||||||
|
fun setModel(model: String) = saveSettings(mapOf("model" to model))
|
||||||
|
fun runTool(name: String, args: JSONObject, onResult: (Boolean, String) -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val res = withContext(Dispatchers.IO) { client.runTool(name, args) }
|
||||||
|
onResult(res.ok, if (res.ok) res.result.toString() else res.error)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
onResult(false, e.message ?: "执行失败")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveMcpConfig(text: String, onResult: (Boolean, String) -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val json = withContext(Dispatchers.IO) { client.saveMcpConfig(text) }
|
||||||
|
refresh()
|
||||||
|
val results = json.optJSONArray("results")
|
||||||
|
val summary = if (results != null) {
|
||||||
|
(0 until results.length()).joinToString(",") { i ->
|
||||||
|
val item = results.optJSONObject(i) ?: return@joinToString ""
|
||||||
|
val ok = item.optBoolean("ok")
|
||||||
|
"${item.optString("name")}${if (ok) "✓" else "✗" + item.optString("error")}"
|
||||||
|
}
|
||||||
|
} else ""
|
||||||
|
onResult(json.optBoolean("ok"), if (json.optBoolean("ok")) "已重连:$summary" else json.optString("error"))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
onResult(false, e.message ?: "保存失败")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveAgent(id: String?, name: String, avatar: String, systemPrompt: String, greeting: String, onDone: () -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val body = JSONObject()
|
||||||
|
.put("name", name)
|
||||||
|
.put("avatar", avatar)
|
||||||
|
.put("systemPrompt", systemPrompt)
|
||||||
|
// 内核字段叫 tagline;UI 上叫"一句话介绍"
|
||||||
|
.put("tagline", greeting)
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
if (id.isNullOrBlank()) client.createAgent(body) else client.updateAgent(id, body)
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
onDone()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
showHint("保存失败:${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteAgent(id: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
runCatching { withContext(Dispatchers.IO) { client.deleteAgent(id) } }
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun useAgent(id: String) {
|
||||||
|
saveSettings(mapOf("activeAgentId" to id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 附件 ------------------------------ */
|
||||||
|
|
||||||
|
fun addAttachment(file: Attachment) {
|
||||||
|
if (attachments.none { it.id == file.id }) attachments.add(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeAttachment(id: String) {
|
||||||
|
attachments.removeAll { it.id == id }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun uploadAndAttach(name: String, mime: String, bytes: ByteArray) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val file = withContext(Dispatchers.IO) { client.uploadFile(name, mime, bytes, false) }
|
||||||
|
if (file != null) {
|
||||||
|
addAttachment(file)
|
||||||
|
showHint("已添加 ${file.name}")
|
||||||
|
} else {
|
||||||
|
showHint("上传失败")
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
showHint("上传失败:${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从内核拉待处理附件(比如 Termux 里刚生成的文件) */
|
||||||
|
fun syncPendingUploads() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val json = withContext(Dispatchers.IO) { client.state() }
|
||||||
|
state = json
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 工具权限:切模式 / 勾白名单 */
|
||||||
|
fun saveSecurity(mode: String, allow: List<String>) {
|
||||||
|
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
|
||||||
|
saveSettings(mapOf("security" to json))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把补丁 Map 转成 JSONObject。
|
||||||
|
*
|
||||||
|
* ★ 为什么必须显式递归转换,不能直接 `json.put(k, mapOf(...))`:
|
||||||
|
*
|
||||||
|
* Android 的 org.json **不会**把 `Map` 自动当成 JSON 对象 —— `put(String, Object)`
|
||||||
|
* 只是把 Map 原样塞进内部表,`toString()` 时按普通对象处理,
|
||||||
|
* 于是发出去的是 `{"speech":"{autoRead=true}"}`:值是**字符串**而不是对象。
|
||||||
|
*
|
||||||
|
* 内核那边 `speech` 本来是个 dict,被字符串覆盖之后,之后**每一次**读配置
|
||||||
|
* (`{**默认, **字符串}`)都会抛 TypeError,`/api/state` 从此一直返回
|
||||||
|
* `{"error":"'str' object is not a mapping"}`;而 App 把这个错误 JSON 解析成了
|
||||||
|
* 「全默认状态」且不抛异常 —— 表现就是:
|
||||||
|
* **点一下语音按钮,模型变"未设置"、昵称变"我"、会话列表全空,还弹"已保存"。**
|
||||||
|
*
|
||||||
|
* 这个坑很隐蔽:只有"嵌套对象"才会触发,而在此之前 App 从没发过嵌套补丁。
|
||||||
|
*/
|
||||||
|
fun patchToJson(patch: Map<String, Any?>): JSONObject {
|
||||||
|
val json = JSONObject()
|
||||||
|
for ((key, value) in patch) {
|
||||||
|
json.put(key, toJsonValue(value))
|
||||||
|
}
|
||||||
|
return json
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun toJsonValue(value: Any?): Any = when (value) {
|
||||||
|
null -> JSONObject.NULL
|
||||||
|
is JSONObject, is JSONArray -> value
|
||||||
|
is Map<*, *> -> {
|
||||||
|
val obj = JSONObject()
|
||||||
|
for ((k, v) in value) obj.put(k.toString(), toJsonValue(v))
|
||||||
|
obj
|
||||||
|
}
|
||||||
|
is List<*> -> {
|
||||||
|
val arr = JSONArray()
|
||||||
|
for (item in value) arr.put(toJsonValue(item))
|
||||||
|
arr
|
||||||
|
}
|
||||||
|
else -> value
|
||||||
|
}
|
||||||
719
android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt
Normal file
@@ -0,0 +1,719 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
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.slideInVertically
|
||||||
|
import androidx.compose.animation.slideOutVertically
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.horizontalScroll
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
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.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.*
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
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.SolidColor
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.platform.LocalClipboardManager
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.AnnotatedString
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
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.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.doubao.lynxclone.data.ChatMessage
|
||||||
|
import com.doubao.lynxclone.speech.SpeechController
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对话页。
|
||||||
|
*
|
||||||
|
* 视觉对着豆包真机截图抠的:纯白底、顶部三段式(左右图标 + 居中智能体名)、
|
||||||
|
* 大头像 + 灰色问候气泡、白底描边快捷胶囊、输入框是大圆角描边胶囊、发送键是蓝色圆钮。
|
||||||
|
* 动效:气泡淡入上移、思考面板从底部升起、typing 三点跳动、按钮按下回弹。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun ChatScreen(vm: AppViewModel) {
|
||||||
|
val agent = vm.activeAgent
|
||||||
|
val listState = rememberLazyListState()
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||||
|
if (uri == null) return@rememberLauncherForActivityResult
|
||||||
|
try {
|
||||||
|
val name = uri.lastPathSegment?.substringAfterLast('/') ?: "upload"
|
||||||
|
val mime = context.contentResolver.getType(uri) ?: "application/octet-stream"
|
||||||
|
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||||
|
if (bytes != null) vm.uploadAndAttach(name, mime, bytes)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
vm.showHint("读取文件失败:${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val onPickFile: () -> Unit = { picker.launch("*/*") }
|
||||||
|
|
||||||
|
// ---------------- 语音 ----------------
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val speech = remember { SpeechController(context, vm.client, scope) }
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
onDispose { speech.release() }
|
||||||
|
}
|
||||||
|
// 设置里的开关同步到控制器
|
||||||
|
LaunchedEffect(vm.state.speech.autoRead) { speech.autoRead = vm.state.speech.autoRead }
|
||||||
|
// 控制器自己产生的提示(云端失败、没听清…)也走统一的提示条
|
||||||
|
LaunchedEffect(speech.notice) {
|
||||||
|
if (speech.notice.isNotBlank()) {
|
||||||
|
vm.showHint(speech.notice)
|
||||||
|
speech.notice = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 录音权限:用户第一次点麦克风时才要,不在启动时要
|
||||||
|
val micPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||||
|
if (granted) speech.startRecording() else vm.showHint("没有录音权限,去系统设置里给一下")
|
||||||
|
}
|
||||||
|
val onMic: () -> Unit = {
|
||||||
|
when {
|
||||||
|
speech.recording -> speech.stopRecording { text -> vm.draft = text }
|
||||||
|
speech.transcribing -> vm.showHint("还在识别上一段…")
|
||||||
|
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)
|
||||||
|
== PackageManager.PERMISSION_GRANTED -> speech.startRecording()
|
||||||
|
else -> micPermission.launch(Manifest.permission.RECORD_AUDIO)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自动朗读:最后一条回复从「进行中」变成「已落地」时念出来
|
||||||
|
val lastMsg = vm.messages.lastOrNull()
|
||||||
|
val lastDoneKey = lastMsg?.let { "${vm.messages.size}:${it.pending}:${it.content.length}" }
|
||||||
|
LaunchedEffect(lastDoneKey) {
|
||||||
|
val msg = vm.messages.lastOrNull() ?: return@LaunchedEffect
|
||||||
|
if (msg.role == "assistant" && !msg.pending && !msg.error && msg.content.isNotBlank()) {
|
||||||
|
// 内容还在变(流式)时别念,等它稳定一下
|
||||||
|
delay(600)
|
||||||
|
val now = vm.messages.lastOrNull()
|
||||||
|
if (now === msg && !now.pending && now.content == msg.content) {
|
||||||
|
speech.maybeAutoRead(now.content, vm.messages.size - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 新消息 / 流式增量都滚到底
|
||||||
|
LaunchedEffect(vm.messages.size, vm.messages.lastOrNull()?.content?.length) {
|
||||||
|
if (vm.messages.isNotEmpty()) listState.animateScrollToItem(vm.messages.size - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||||
|
ChatHeader(vm, agent?.name ?: "豆包", speech)
|
||||||
|
|
||||||
|
LazyColumn(
|
||||||
|
state = listState,
|
||||||
|
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||||
|
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 10.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
if (vm.messages.isEmpty()) {
|
||||||
|
val tagline = agent?.greeting.orEmpty().trim()
|
||||||
|
val looksLikeSentence = tagline.length >= 12 &&
|
||||||
|
(tagline.endsWith("。") || tagline.endsWith("!") ||
|
||||||
|
tagline.endsWith("?") || tagline.contains(","))
|
||||||
|
val greeting =
|
||||||
|
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
|
||||||
|
item { AppearOnce { HeroSection(greeting) } }
|
||||||
|
}
|
||||||
|
items(vm.messages.size) { index ->
|
||||||
|
AppearOnce(offsetY = 10.dp) {
|
||||||
|
MessageItem(vm, index, vm.messages[index], speech)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vm.messages.isEmpty()) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())
|
||||||
|
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
listOf("对话", "AI创作", "出行用豆包", "豆包").forEach { label ->
|
||||||
|
DoubaoPill(text = label, onClick = { vm.draft = label })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||||
|
|
||||||
|
InputBar(vm, onPickFile, onMic, speech)
|
||||||
|
}
|
||||||
|
|
||||||
|
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = thinkingVisible,
|
||||||
|
enter = slideInVertically(initialOffsetY = { it }) + fadeIn(tween(160)),
|
||||||
|
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(tween(160)),
|
||||||
|
) {
|
||||||
|
val index = vm.thinkingIndex
|
||||||
|
if (index in vm.messages.indices) ThinkingSheet(vm.messages[index]) { vm.thinkingIndex = -1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = vm.modelPickerOpen,
|
||||||
|
enter = slideInVertically(initialOffsetY = { it }) + fadeIn(tween(160)),
|
||||||
|
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(tween(160)),
|
||||||
|
) {
|
||||||
|
ModelPickerSheet(vm) { vm.modelPickerOpen = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 顶部栏 ------------------------------ */
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechController) {
|
||||||
|
Column(Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp)) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
HeaderIcon(Icons.Filled.Menu, "菜单") { vm.drawerOpen = true }
|
||||||
|
HeaderIcon(Icons.Filled.Edit, "新话题") { vm.newTopic() }
|
||||||
|
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
// 中间这块点开就是「模型」,和豆包一样(豆包点的是 Agent 名)
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.clip(RoundedCornerShape(16.dp))
|
||||||
|
.clickable { vm.modelPickerOpen = true }
|
||||||
|
.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier.size(24.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(agentName, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||||
|
Icon(Icons.Filled.ChevronRight, null, tint = doubaoText(), modifier = Modifier.size(18.dp))
|
||||||
|
}
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
|
||||||
|
HeaderIcon(Icons.Filled.Call, "通话") { vm.showHint("通话模式还没做(方案在 README 里)") }
|
||||||
|
// 这个喇叭是「自动朗读」开关:开了之后每条新回复自动念
|
||||||
|
HeaderIcon(
|
||||||
|
if (speech.autoRead) Icons.Filled.VolumeUp else Icons.Filled.VolumeOff,
|
||||||
|
if (speech.autoRead) "自动朗读已开" else "自动朗读已关",
|
||||||
|
tint = if (speech.autoRead) Doubao.Blue else null,
|
||||||
|
) {
|
||||||
|
val next = !speech.autoRead
|
||||||
|
speech.autoRead = next
|
||||||
|
vm.setAutoRead(next)
|
||||||
|
vm.showHint(if (next) "新回复会自动朗读" else "已关闭自动朗读")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
"AI 生成可能有误 注意核实",
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
fontSize = 10.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun HeaderIcon(
|
||||||
|
icon: ImageVector,
|
||||||
|
desc: String,
|
||||||
|
tint: androidx.compose.ui.graphics.Color? = null,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
) {
|
||||||
|
val source = remember { MutableInteractionSource() }
|
||||||
|
val pressed by source.collectIsPressedAsState()
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.86f else 1f, tween(110), label = "hdr")
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(44.dp)
|
||||||
|
.scale(scale)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.clickable(interactionSource = source, indication = null, onClick = onClick),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(icon, desc, tint = tint ?: doubaoText(), modifier = Modifier.size(22.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 空态大头像 ------------------------------ */
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun HeroSection(greeting: String) {
|
||||||
|
Column(
|
||||||
|
Modifier.fillMaxWidth().padding(top = 34.dp, bottom = 18.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(20.dp))
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.clip(RoundedCornerShape(16.dp))
|
||||||
|
.background(doubaoBubble())
|
||||||
|
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||||
|
) {
|
||||||
|
Text(greeting, fontSize = 16.sp, lineHeight = 26.sp, color = doubaoText())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 消息 ------------------------------ */
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: SpeechController) {
|
||||||
|
val clipboard = LocalClipboardManager.current
|
||||||
|
val speaking = speech.speakingIndex == index
|
||||||
|
|
||||||
|
if (msg.role == "user") {
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||||
|
Column(horizontalAlignment = Alignment.End) {
|
||||||
|
msg.attachments.forEach { file ->
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.clip(RoundedCornerShape(12.dp))
|
||||||
|
.background(doubaoBubble())
|
||||||
|
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Image, null,
|
||||||
|
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(file.name, fontSize = 13.sp, color = doubaoText(), maxLines = 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
}
|
||||||
|
if (msg.content.isNotBlank()) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.widthIn(max = 288.dp)
|
||||||
|
.clip(RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp))
|
||||||
|
.background(Doubao.Blue)
|
||||||
|
.padding(horizontal = 14.dp, vertical = 11.dp),
|
||||||
|
) {
|
||||||
|
Text(msg.content, color = Color.White, fontSize = 16.sp, lineHeight = 25.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
|
||||||
|
val hasReasoning = msg.reasoning.isNotBlank()
|
||||||
|
val hasTrace = msg.toolTrace.isNotEmpty()
|
||||||
|
|
||||||
|
if (hasReasoning || hasTrace || msg.pending) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.clip(RoundedCornerShape(14.dp))
|
||||||
|
.background(doubaoCard())
|
||||||
|
.clickable { vm.thinkingIndex = index }
|
||||||
|
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Icon(Icons.Filled.AutoAwesome, null, tint = Doubao.Blue, modifier = Modifier.size(15.dp))
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(
|
||||||
|
when {
|
||||||
|
// 强度本身就叫"深度思考",拼上去会变成"深度思考 · 深度思考"
|
||||||
|
hasReasoning -> "深度思考"
|
||||||
|
hasTrace -> "执行过程"
|
||||||
|
else -> "深度思考中"
|
||||||
|
},
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
if (hasReasoning || hasTrace) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.ChevronRight, null,
|
||||||
|
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
TypingDots(dot = 4.dp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
msg.toolTrace.forEach { trace ->
|
||||||
|
var open by remember(trace.id) { mutableStateOf(false) }
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(bottom = 6.dp)
|
||||||
|
.clip(RoundedCornerShape(12.dp))
|
||||||
|
.background(doubaoCard())
|
||||||
|
.clickable { open = !open }
|
||||||
|
.padding(horizontal = 12.dp, vertical = 9.dp),
|
||||||
|
) {
|
||||||
|
Column {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Icon(Icons.Filled.Build, null, tint = doubaoTextSecondary(), modifier = Modifier.size(14.dp))
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(trace.name, fontSize = 13.sp, color = doubaoText())
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
Text(
|
||||||
|
when (trace.ok) {
|
||||||
|
true -> "完成"
|
||||||
|
false -> "失败"
|
||||||
|
null -> "进行中"
|
||||||
|
},
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = if (trace.ok == false) Doubao.Error else Doubao.Blue,
|
||||||
|
)
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.ChevronRight, null,
|
||||||
|
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (open && trace.result.isNotBlank()) {
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
Text(
|
||||||
|
trace.result.take(800),
|
||||||
|
fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.widthIn(max = 300.dp)
|
||||||
|
.clip(RoundedCornerShape(4.dp, 18.dp, 18.dp, 18.dp))
|
||||||
|
.background(if (msg.error) Doubao.ErrorBg else doubaoBubble())
|
||||||
|
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||||
|
) {
|
||||||
|
when {
|
||||||
|
msg.content.isNotBlank() -> Text(
|
||||||
|
msg.content,
|
||||||
|
fontSize = 16.sp,
|
||||||
|
lineHeight = 26.sp,
|
||||||
|
color = if (msg.error) Doubao.Error else doubaoText(),
|
||||||
|
)
|
||||||
|
msg.pending -> TypingDots()
|
||||||
|
else -> Text("…", color = doubaoTextSecondary(), fontSize = 16.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!msg.pending && msg.content.isNotBlank() && !msg.error) {
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
RoundIconButton(Icons.Filled.ContentCopy, "复制") {
|
||||||
|
clipboard.setText(AnnotatedString(msg.content))
|
||||||
|
vm.showHint("已复制")
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
if (speaking) {
|
||||||
|
// 正在念这条:按钮变蓝 + 图标换成停止,一眼看出"再点就是停"
|
||||||
|
RoundIconButton(
|
||||||
|
Icons.Filled.Stop, "停止朗读",
|
||||||
|
tint = Doubao.Blue,
|
||||||
|
bg = doubaoHeroRing(),
|
||||||
|
) { speech.stopSpeaking() }
|
||||||
|
} else {
|
||||||
|
RoundIconButton(Icons.Filled.VolumeUp, "朗读") { speech.speak(msg.content, index) }
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
RoundIconButton(
|
||||||
|
Icons.Filled.ThumbUp, "赞",
|
||||||
|
tint = if (msg.feedback == "up") Doubao.Blue else null,
|
||||||
|
) { vm.onFeedback(index, "up") }
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
RoundIconButton(
|
||||||
|
Icons.Filled.ThumbDown, "踩",
|
||||||
|
tint = if (msg.feedback == "down") Doubao.Blue else null,
|
||||||
|
) { vm.onFeedback(index, "down") }
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
RoundIconButton(Icons.Filled.Share, "分享") { vm.showHint("分享还没做") }
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
RoundIconButton(Icons.Filled.Refresh, "重新生成") { vm.regenerate() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 附件 / 输入栏 ------------------------------ */
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun AttachmentStrip(vm: AppViewModel) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())
|
||||||
|
.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
vm.attachments.forEach { file ->
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.clip(RoundedCornerShape(10.dp))
|
||||||
|
.background(doubaoCard())
|
||||||
|
.padding(horizontal = 10.dp, vertical = 7.dp),
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.AttachFile, null,
|
||||||
|
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(5.dp))
|
||||||
|
Text(file.name, fontSize = 12.sp, color = doubaoText(), maxLines = 1)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Close, "移除", tint = doubaoTextSecondary(),
|
||||||
|
modifier = Modifier.size(14.dp).clickable { vm.removeAttachment(file.id) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun InputBar(
|
||||||
|
vm: AppViewModel,
|
||||||
|
onPickFile: () -> Unit,
|
||||||
|
onMic: () -> Unit,
|
||||||
|
speech: SpeechController,
|
||||||
|
) {
|
||||||
|
val canSend = vm.draft.isNotBlank() || vm.attachments.isNotEmpty()
|
||||||
|
val sendSource = remember { MutableInteractionSource() }
|
||||||
|
val sendPressed by sendSource.collectIsPressedAsState()
|
||||||
|
val sendScale by animateFloatAsState(if (sendPressed) 0.88f else 1f, tween(110), label = "send")
|
||||||
|
|
||||||
|
// 录音时把输入框整条换成"正在听…",跟豆包按住说话一个观感
|
||||||
|
if (speech.recording || speech.transcribing) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.height(52.dp)
|
||||||
|
.clip(RoundedCornerShape(26.dp))
|
||||||
|
.background(Doubao.Blue.copy(alpha = 0.08f))
|
||||||
|
.border(1.dp, Doubao.Blue, RoundedCornerShape(26.dp))
|
||||||
|
.padding(horizontal = 16.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
if (speech.transcribing) Icons.Filled.HourglassTop else Icons.Filled.Mic,
|
||||||
|
null, tint = Doubao.Blue, modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Text(
|
||||||
|
if (speech.transcribing) "识别中…" else "正在听…",
|
||||||
|
fontSize = 15.sp,
|
||||||
|
color = Doubao.Blue,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
// 简易波形:用实时音量画几根高低不同的柱子,能看出"在收音"
|
||||||
|
Row(
|
||||||
|
Modifier.weight(1f).height(24.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(3.dp),
|
||||||
|
) {
|
||||||
|
val amp = if (speech.transcribing) 8 else speech.level
|
||||||
|
repeat(18) { i ->
|
||||||
|
// 中间高两边低,再叠加实时音量,看着像声波
|
||||||
|
val shape = 1f - kotlin.math.abs(i - 8.5f) / 10f
|
||||||
|
val h = (6 + amp * shape * 0.16f).coerceIn(4f, 24f)
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.width(3.dp)
|
||||||
|
.height(h.dp)
|
||||||
|
.clip(RoundedCornerShape(2.dp))
|
||||||
|
.background(Doubao.Blue.copy(alpha = 0.35f + 0.5f * shape)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(40.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(Doubao.Blue)
|
||||||
|
.clickable { onMic() },
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Check, "完成", tint = Color.White, modifier = Modifier.size(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.height(52.dp)
|
||||||
|
.clip(RoundedCornerShape(26.dp))
|
||||||
|
.background(doubaoSurface())
|
||||||
|
.border(1.dp, doubaoBorder(), RoundedCornerShape(26.dp))
|
||||||
|
.padding(horizontal = 12.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
if (vm.attachments.isEmpty()) Icons.Filled.PhotoCamera else Icons.Filled.Add,
|
||||||
|
"附件",
|
||||||
|
tint = doubaoText(),
|
||||||
|
modifier = Modifier.size(22.dp).clickable(onClick = onPickFile),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
|
||||||
|
if (vm.draft.isEmpty()) {
|
||||||
|
Text("发消息或按住说话…", fontSize = 15.sp, color = Doubao.TextTertiary)
|
||||||
|
}
|
||||||
|
BasicTextField(
|
||||||
|
value = vm.draft,
|
||||||
|
onValueChange = { vm.draft = it },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
textStyle = TextStyle(fontSize = 15.sp, color = doubaoText()),
|
||||||
|
cursorBrush = SolidColor(Doubao.Blue),
|
||||||
|
maxLines = 3,
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
|
||||||
|
keyboardActions = KeyboardActions(onSend = { vm.send() }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!canSend) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Mic, "语音输入", tint = doubaoText(),
|
||||||
|
modifier = Modifier.size(22.dp).clickable(onClick = onMic),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
|
||||||
|
if (canSend) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(40.dp)
|
||||||
|
.scale(sendScale)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(Doubao.Blue)
|
||||||
|
.clickable(interactionSource = sendSource, indication = null) { vm.send() },
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.ArrowUpward, "发送", tint = Color.White, modifier = Modifier.size(20.dp))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(40.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(doubaoSurface())
|
||||||
|
.border(1.dp, doubaoBorder(), CircleShape)
|
||||||
|
.clickable(onClick = onPickFile),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Add, "更多", tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 思考过程弹层 ------------------------------ */
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||||
|
Box(
|
||||||
|
Modifier.fillMaxSize().background(Doubao.Scrim).clickable(onClick = onClose),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
Modifier
|
||||||
|
.align(Alignment.BottomCenter)
|
||||||
|
.fillMaxWidth()
|
||||||
|
.heightIn(max = 560.dp)
|
||||||
|
.clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp))
|
||||||
|
.background(doubaoSurface())
|
||||||
|
.clickable(enabled = false) {}
|
||||||
|
.padding(horizontal = 18.dp, vertical = 16.dp),
|
||||||
|
) {
|
||||||
|
// 顶上那条小横杠:一眼看出是从底部拉起来的
|
||||||
|
Box(
|
||||||
|
Modifier.align(Alignment.CenterHorizontally).width(36.dp).height(4.dp)
|
||||||
|
.clip(RoundedCornerShape(2.dp)).background(doubaoBorder()),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(14.dp))
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
RoundIconButton(Icons.Filled.Close, "关闭", size = 30.dp, iconSize = 15.dp, onClick = onClose)
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
Text("思考过程", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
Spacer(Modifier.width(30.dp))
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(14.dp))
|
||||||
|
|
||||||
|
LazyColumn(Modifier.fillMaxWidth()) {
|
||||||
|
if (msg.toolTrace.isNotEmpty()) {
|
||||||
|
items(msg.toolTrace.size) { i ->
|
||||||
|
val trace = msg.toolTrace[i]
|
||||||
|
Row(Modifier.padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Build, null,
|
||||||
|
tint = doubaoTextSecondary(), modifier = Modifier.size(14.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(
|
||||||
|
"${if (trace.ok == false) "失败" else "已调用"} ${trace.name}",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Text(
|
||||||
|
msg.reasoning.ifBlank { "这次没有返回思维链(模型不支持,或思考强度被关掉了)。" },
|
||||||
|
fontSize = 13.sp,
|
||||||
|
lineHeight = 21.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.ArrowUpward
|
||||||
|
import androidx.compose.material.icons.filled.DeleteSweep
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 命令控制台 —— 真 pty 用不了时的退路。
|
||||||
|
*
|
||||||
|
* 为什么需要:有些 ROM(实测 realme / Android 16)把 `/dev/pts` 挂成
|
||||||
|
* `mode=600,ptmxmode=000`,应用**分配不到从设备 pty**,
|
||||||
|
* 于是 Termux 的 TerminalSession 一起来就退出(终端上只剩一句 "[Process completed]")。
|
||||||
|
* 这不是 SELinux 拒绝,是挂载参数决定的,应用侧绕不过去。
|
||||||
|
*
|
||||||
|
* 但"跑命令"这件事本身不需要 pty:直接 ProcessBuilder 起 Termux 的 bash 就行。
|
||||||
|
* 所以这里给一个控制台:能敲命令、能看到输出、退出码和通道都显示出来,
|
||||||
|
* 只是没有全屏 TUI(vim/top)和交互式提示符。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun CommandConsole(
|
||||||
|
onRun: (String, (Boolean, String) -> Unit) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
data class Line(val text: String, val kind: String)
|
||||||
|
|
||||||
|
val lines = remember { mutableStateListOf<Line>() }
|
||||||
|
var draft by remember { mutableStateOf("") }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
val listState = rememberLazyListState()
|
||||||
|
|
||||||
|
LaunchedEffect(lines.size) {
|
||||||
|
if (lines.isNotEmpty()) listState.animateScrollToItem(lines.size - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun run(command: String) {
|
||||||
|
val cmd = command.trim()
|
||||||
|
if (cmd.isEmpty() || busy) return
|
||||||
|
lines.add(Line("$ $cmd", "cmd"))
|
||||||
|
draft = ""
|
||||||
|
busy = true
|
||||||
|
onRun(cmd) { ok, text ->
|
||||||
|
busy = false
|
||||||
|
if (ok) {
|
||||||
|
// 内核把 shell 的返回做成了 JSON 字符串,这里拆出来好看的排版
|
||||||
|
val rendered = try {
|
||||||
|
val json = JSONObject(text)
|
||||||
|
buildString {
|
||||||
|
append(json.optString("stdout"))
|
||||||
|
val err = json.optString("stderr")
|
||||||
|
if (err.isNotBlank()) append("\n[stderr] ").append(err)
|
||||||
|
append("\n[退出码 ${json.optInt("exit_code")}|通道 ${json.optString("via", "?")}]")
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
text
|
||||||
|
}
|
||||||
|
lines.add(Line(rendered.trimEnd(), "out"))
|
||||||
|
} else {
|
||||||
|
lines.add(Line(text, "err"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(modifier.fillMaxSize()) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text("控制台模式", color = Color(0xFF8A93A0), fontSize = 12.sp)
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
IconButton(onClick = { lines.clear() }) {
|
||||||
|
Icon(Icons.Filled.DeleteSweep, "清屏", tint = Color.White, modifier = Modifier.size(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LazyColumn(state = listState, modifier = Modifier.weight(1f).fillMaxWidth()) {
|
||||||
|
items(lines) { line ->
|
||||||
|
Text(
|
||||||
|
line.text,
|
||||||
|
color = when (line.kind) {
|
||||||
|
"cmd" -> Color(0xFF7FD1A0)
|
||||||
|
"err" -> Color(0xFFFF8F8F)
|
||||||
|
else -> Color(0xFFD7DAE0)
|
||||||
|
},
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (busy) {
|
||||||
|
item { Text("执行中…", color = Color(0xFF8A93A0), fontSize = 12.sp, modifier = Modifier.padding(12.dp)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 常用命令,手机上打字麻烦
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp),
|
||||||
|
) {
|
||||||
|
listOf(
|
||||||
|
"ls -la" to "pwd; ls -la",
|
||||||
|
"Python" to "python --version 2>/dev/null || echo 'pkg install python 后可装'",
|
||||||
|
"系统" to "uname -a",
|
||||||
|
"装东西" to "pkg install -y python",
|
||||||
|
).forEach { (label, cmd) ->
|
||||||
|
AssistChip(
|
||||||
|
onClick = { run(cmd) },
|
||||||
|
label = { Text(label, fontSize = 12.sp, color = Color(0xFFD7DAE0)) },
|
||||||
|
modifier = Modifier.padding(end = 6.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = draft,
|
||||||
|
onValueChange = { draft = it },
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
placeholder = { Text("输入命令…", fontSize = 13.sp) },
|
||||||
|
shape = RoundedCornerShape(20.dp),
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
|
||||||
|
keyboardActions = KeyboardActions(onSend = { run(draft) }),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
FilledIconButton(onClick = { run(draft) }, enabled = !busy) {
|
||||||
|
Icon(Icons.Filled.ArrowUpward, "执行")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
214
android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
import androidx.compose.animation.core.*
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
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.graphicsLayer
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 豆包的视觉规范。
|
||||||
|
*
|
||||||
|
* 颜色和尺寸都是照着真机截图抠的 —— 之前直接用 Material3 默认值,
|
||||||
|
* 出来一股"原生 Android 模板"味,跟豆包一点都不像。
|
||||||
|
*/
|
||||||
|
object Doubao {
|
||||||
|
// ---- 主色与中性色 ----
|
||||||
|
val Blue = Color(0xFF2B7BFF)
|
||||||
|
val BluePressed = Color(0xFF1E63D6)
|
||||||
|
val TextPrimary = Color(0xFF1F2329)
|
||||||
|
val TextSecondary = Color(0xFF5A6472)
|
||||||
|
val TextTertiary = Color(0xFF9AA0A8)
|
||||||
|
val BubbleBot = Color(0xFFF2F3F5) // 助手气泡
|
||||||
|
val ChipBg = Color(0xFFFFFFFF) // 快捷入口
|
||||||
|
val CardBg = Color(0xFFF7F8FA)
|
||||||
|
val Divider = Color(0xFFEFF1F4)
|
||||||
|
val Border = Color(0xFFE5E7EB)
|
||||||
|
val HeroRing = Color(0xFFDCE9FF)
|
||||||
|
val Error = Color(0xFFE5484D)
|
||||||
|
val ErrorBg = Color(0xFFFDECEC)
|
||||||
|
/** 弹层背后的遮罩 */
|
||||||
|
val Scrim = Color(0x66000000)
|
||||||
|
|
||||||
|
// ---- 深色(真机深色模式下看截图对着调)----
|
||||||
|
val DarkBg = Color(0xFF101216)
|
||||||
|
val DarkSurface = Color(0xFF1A1D23)
|
||||||
|
val DarkBubble = Color(0xFF262A31)
|
||||||
|
val DarkText = Color(0xFFE8EAED)
|
||||||
|
val DarkTextSecondary = Color(0xFFA8AFBA)
|
||||||
|
val DarkBorder = Color(0xFF2E333B)
|
||||||
|
val DarkHeroRing = Color(0xFF1E355C)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 当前是不是深色主题(跟随系统) */
|
||||||
|
@Composable
|
||||||
|
fun isDark(): Boolean = androidx.compose.foundation.isSystemInDarkTheme()
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun doubaoBg() = if (isDark()) Doubao.DarkBg else Color.White
|
||||||
|
@Composable
|
||||||
|
fun doubaoSurface() = if (isDark()) Doubao.DarkSurface else Color.White
|
||||||
|
@Composable
|
||||||
|
fun doubaoText() = if (isDark()) Doubao.DarkText else Doubao.TextPrimary
|
||||||
|
@Composable
|
||||||
|
fun doubaoTextSecondary() = if (isDark()) Doubao.DarkTextSecondary else Doubao.TextSecondary
|
||||||
|
@Composable
|
||||||
|
fun doubaoBubble() = if (isDark()) Doubao.DarkBubble else Doubao.BubbleBot
|
||||||
|
@Composable
|
||||||
|
fun doubaoBorder() = if (isDark()) Doubao.DarkBorder else Doubao.Border
|
||||||
|
@Composable
|
||||||
|
fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg
|
||||||
|
@Composable
|
||||||
|
fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing
|
||||||
|
|
||||||
|
/* ------------------------------ 动画 ------------------------------ */
|
||||||
|
|
||||||
|
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
||||||
|
@Composable
|
||||||
|
fun AppearOnce(
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
offsetY: Dp = 14.dp,
|
||||||
|
durationMs: Int = 260,
|
||||||
|
content: @Composable () -> Unit,
|
||||||
|
) {
|
||||||
|
var shown by remember { mutableStateOf(false) }
|
||||||
|
LaunchedEffect(Unit) { shown = true }
|
||||||
|
val progress by animateFloatAsState(
|
||||||
|
targetValue = if (shown) 1f else 0f,
|
||||||
|
animationSpec = tween(durationMs, easing = FastOutSlowInEasing),
|
||||||
|
label = "appear",
|
||||||
|
)
|
||||||
|
Box(
|
||||||
|
modifier.graphicsLayer {
|
||||||
|
alpha = progress
|
||||||
|
translationY = (1f - progress) * offsetY.toPx()
|
||||||
|
},
|
||||||
|
) { content() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按下去缩一下(按钮用) */
|
||||||
|
@Composable
|
||||||
|
fun pressScale(pressed: Boolean, to: Float = 0.94f): Float {
|
||||||
|
val scale by animateFloatAsState(
|
||||||
|
targetValue = if (pressed) to else 1f,
|
||||||
|
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
|
||||||
|
label = "press",
|
||||||
|
)
|
||||||
|
return scale
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 「正在输入」的三个跳动小点 */
|
||||||
|
@Composable
|
||||||
|
fun TypingDots(color: Color = Doubao.TextTertiary, dot: Dp = 6.dp) {
|
||||||
|
val transition = rememberInfiniteTransition(label = "typing")
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
repeat(3) { index ->
|
||||||
|
val alpha by transition.animateFloat(
|
||||||
|
initialValue = 0.25f,
|
||||||
|
targetValue = 1f,
|
||||||
|
animationSpec = infiniteRepeatable(
|
||||||
|
animation = tween(520, easing = LinearEasing),
|
||||||
|
repeatMode = RepeatMode.Reverse,
|
||||||
|
// 依次错开,看着像波浪
|
||||||
|
initialStartOffset = StartOffset(index * 130),
|
||||||
|
),
|
||||||
|
label = "dot$index",
|
||||||
|
)
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.padding(end = 4.dp)
|
||||||
|
.size(dot)
|
||||||
|
.graphicsLayer { this.alpha = alpha }
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(color),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 小部件 ------------------------------ */
|
||||||
|
|
||||||
|
/** 顶部/输入框上方的白底描边胶囊按钮(快捷入口、功能键) */
|
||||||
|
@Composable
|
||||||
|
fun DoubaoPill(
|
||||||
|
text: String? = null,
|
||||||
|
icon: ImageVector? = null,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
height: Dp = 40.dp,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier
|
||||||
|
.height(height)
|
||||||
|
.clip(RoundedCornerShape(height / 2))
|
||||||
|
.background(doubaoSurface())
|
||||||
|
.border(1.dp, doubaoBorder(), RoundedCornerShape(height / 2))
|
||||||
|
.clickable(onClick = onClick)
|
||||||
|
.padding(horizontal = 16.dp),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
if (icon != null) {
|
||||||
|
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(16.dp))
|
||||||
|
if (text != null) Spacer(Modifier.width(5.dp))
|
||||||
|
}
|
||||||
|
if (text != null) {
|
||||||
|
Text(text, fontSize = 14.sp, color = doubaoText())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 圆形小图标按钮(消息下方的操作栏)。
|
||||||
|
* 注意 onClick 放最后一个参数:这样 `RoundIconButton(icon, "desc") { ... }` 的尾随 lambda 才落对地方。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun RoundIconButton(
|
||||||
|
icon: ImageVector,
|
||||||
|
contentDescription: String,
|
||||||
|
size: Dp = 34.dp,
|
||||||
|
iconSize: Dp = 16.dp,
|
||||||
|
tint: Color? = null,
|
||||||
|
bg: Color? = null,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(size)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(bg ?: doubaoCard())
|
||||||
|
.clickable(onClick = onClick),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(icon, contentDescription, tint = tint ?: doubaoTextSecondary(), modifier = Modifier.size(iconSize))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 分区标题(抽屉里的"置顶/最近") */
|
||||||
|
@Composable
|
||||||
|
fun SectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||||
|
Text(
|
||||||
|
text,
|
||||||
|
modifier = modifier,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
fontWeight = FontWeight.Normal,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
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.filled.Check
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
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.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 模型 / 思考强度面板(从底部升起,跟豆包点标题那个面板一个意思)。
|
||||||
|
*
|
||||||
|
* 点选即生效:内核里换模型和思考强度是热生效的,下一轮对话就用新的,
|
||||||
|
* 所以不放"确定"按钮 —— 多一个确定反而让人以为没保存。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun ModelPickerSheet(vm: AppViewModel, onDismiss: () -> Unit) {
|
||||||
|
val s = vm.settings
|
||||||
|
val preset = vm.state.providers[s.provider]
|
||||||
|
// 当前模型可能不在候选里(手填的 ep-xxx),插到最前面,否则会出现"一个都没勾"
|
||||||
|
val models = remember(preset?.models, s.model) {
|
||||||
|
val list = preset?.models.orEmpty().toMutableList()
|
||||||
|
if (s.model.isNotBlank() && s.model !in list) list.add(0, s.model)
|
||||||
|
list
|
||||||
|
}
|
||||||
|
val level = s.thinkingLevel.ifBlank { "auto" }
|
||||||
|
|
||||||
|
Box(
|
||||||
|
Modifier.fillMaxSize().background(Doubao.Scrim).clickable(onClick = onDismiss),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
Modifier
|
||||||
|
.align(Alignment.BottomCenter)
|
||||||
|
.fillMaxWidth()
|
||||||
|
// 留出上面 15% 当遮罩:面板自己的滚动区会把点击吃掉,
|
||||||
|
// 如果面板顶到状态栏,就只剩状态栏那条能点,"点外面关闭"等于失效
|
||||||
|
.fillMaxHeight(0.85f)
|
||||||
|
.clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp))
|
||||||
|
.background(doubaoSurface())
|
||||||
|
.clickable(enabled = false) {}
|
||||||
|
.padding(horizontal = 18.dp, vertical = 14.dp),
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier.align(Alignment.CenterHorizontally).width(36.dp).height(4.dp)
|
||||||
|
.clip(RoundedCornerShape(2.dp)).background(doubaoBorder()),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(14.dp))
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text("模型", fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = doubaoText())
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
"${preset?.label ?: s.provider} · 换模型和思考强度立即生效,不用重启",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// 明确的关闭按钮:不能只指望"点遮罩",实测面板滚动区会吃掉点击
|
||||||
|
RoundIconButton(Icons.Filled.Close, "关闭", size = 32.dp, iconSize = 16.dp, onClick = onDismiss)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
|
||||||
|
Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) {
|
||||||
|
Text("选模型", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
|
||||||
|
if (models.isEmpty()) {
|
||||||
|
Text("这个提供商还没有候选模型,去「设置」里手填模型 ID。", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||||
|
}
|
||||||
|
models.forEach { model ->
|
||||||
|
val active = model == s.model
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(bottom = 8.dp)
|
||||||
|
.clip(RoundedCornerShape(14.dp))
|
||||||
|
.background(if (active) doubaoHeroRing() else doubaoSurface())
|
||||||
|
.border(
|
||||||
|
1.dp,
|
||||||
|
if (active) Doubao.Blue else doubaoBorder(),
|
||||||
|
RoundedCornerShape(14.dp),
|
||||||
|
)
|
||||||
|
.clickable { vm.setModel(model) }
|
||||||
|
.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
shortModel(model),
|
||||||
|
fontSize = 15.sp,
|
||||||
|
color = doubaoText(),
|
||||||
|
fontWeight = if (active) FontWeight.Medium else FontWeight.Normal,
|
||||||
|
)
|
||||||
|
// 简称可能撞车,真 ID 得露出来,不然分不清 1.6 / 1.8
|
||||||
|
Text(model, fontSize = 11.sp, color = doubaoTextSecondary(), maxLines = 1)
|
||||||
|
}
|
||||||
|
if (active) {
|
||||||
|
Box(
|
||||||
|
Modifier.size(22.dp).clip(CircleShape).background(Doubao.Blue),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Check, "当前", tint = androidx.compose.ui.graphics.Color.White, modifier = Modifier.size(14.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
Text("思考强度", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
listOf("off", "auto", "low", "medium", "high").forEach { key ->
|
||||||
|
val active = key == level
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.clip(RoundedCornerShape(12.dp))
|
||||||
|
.background(if (active) Doubao.Blue else doubaoCard())
|
||||||
|
.clickable { vm.setThinkingLevel(key) }
|
||||||
|
.padding(vertical = 9.dp),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
thinkingLabel(key),
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = if (active) androidx.compose.ui.graphics.Color.White else doubaoText(),
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Text(
|
||||||
|
when (level) {
|
||||||
|
"off" -> "不思考,直接答。"
|
||||||
|
"low" -> "方舟:thinking=enabled;OpenAI:reasoning_effort=low。"
|
||||||
|
"medium" -> "方舟:thinking=enabled;OpenAI:reasoning_effort=medium。"
|
||||||
|
"high" -> "想得最久、最慢,难题用。"
|
||||||
|
else -> "交给模型决定。"
|
||||||
|
},
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
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.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
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.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Check
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
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.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.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「我的」页(对应旧版 Lynx 的 Profile.tsx)。
|
||||||
|
*
|
||||||
|
* 两个取舍:
|
||||||
|
*
|
||||||
|
* 1. **昵称就地改**:输入框 + 右边的勾,保存走 settings 的 nickname 补丁。
|
||||||
|
* 旧版这里是跳去设置页改,但昵称是这一页最主要的可编辑内容,
|
||||||
|
* 为了改两个字跳一整页不划算;落盘还是 vm.saveSettings(...),没有绕开契约。
|
||||||
|
* 没改动时勾是灰的 —— 不然用户点了没反应会以为坏了。
|
||||||
|
*
|
||||||
|
* 2. 下面那几行既是"当前状态"也是入口:模型/思考强度/智能体点进去就能换。
|
||||||
|
* 不然这一页只是摆设,用户还得猜哪个页面能改模型。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun ProfileScreen(vm: AppViewModel) {
|
||||||
|
val s = vm.settings
|
||||||
|
val agent = vm.state.activeAgent
|
||||||
|
// key = s.nickname:保存成功后会刷新 state,输入框跟真实值重新对齐
|
||||||
|
var nickname by remember(s.nickname) { mutableStateOf(s.nickname) }
|
||||||
|
val dirty = nickname.trim() != s.nickname
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxSize()) {
|
||||||
|
ScreenHeader("我的", onBack = { vm.screen = Screen.Chat })
|
||||||
|
|
||||||
|
Column(
|
||||||
|
Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.fillMaxWidth()
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.imePadding()
|
||||||
|
.padding(horizontal = 14.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
) {
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
|
||||||
|
/* ---------------- 大头像 ---------------- */
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.size(84.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(MaterialTheme.colorScheme.primary),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
s.nickname.take(1).ifBlank { "我" },
|
||||||
|
color = Color.White,
|
||||||
|
fontSize = 34.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = nickname,
|
||||||
|
onValueChange = { nickname = it },
|
||||||
|
modifier = Modifier.width(190.dp),
|
||||||
|
singleLine = true,
|
||||||
|
placeholder = { Text("起个名字", fontSize = 14.sp) },
|
||||||
|
textStyle = TextStyle(fontSize = 16.sp),
|
||||||
|
)
|
||||||
|
IconButton(
|
||||||
|
onClick = { vm.saveSettings(mapOf("nickname" to nickname.trim().ifBlank { "我" })) },
|
||||||
|
enabled = dirty,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Check,
|
||||||
|
"保存昵称",
|
||||||
|
tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Text(
|
||||||
|
"本地账号 · 数据都在你自己的设备上",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(14.dp))
|
||||||
|
|
||||||
|
/* ---------------- 当前状态 ---------------- */
|
||||||
|
SettingsCard("当前状态") {
|
||||||
|
NavRow("模型", shortModel(s.model)) { vm.screen = Screen.Settings }
|
||||||
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f))
|
||||||
|
NavRow("思考强度", thinkingLabel(s.thinkingLevel)) { vm.screen = Screen.Settings }
|
||||||
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f))
|
||||||
|
NavRow("当前智能体", agent?.name ?: "未选择") { vm.screen = Screen.Agents }
|
||||||
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f))
|
||||||
|
// 内核平台是内核自报的运行环境,改了没意义,所以这行不带箭头
|
||||||
|
ProfileInfoRow(
|
||||||
|
"内核平台",
|
||||||
|
buildString {
|
||||||
|
append(vm.state.platform)
|
||||||
|
if (vm.state.shellKind.isNotBlank()) append(" · ${vm.state.shellKind}")
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
|
||||||
|
/* ---------------- 设置入口 ---------------- */
|
||||||
|
SettingsCard("设置") {
|
||||||
|
NavRow("AI 内核设置", providerLabel(vm, s.provider)) { vm.screen = Screen.Settings }
|
||||||
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f))
|
||||||
|
NavRow("技能 · 连接器", "${vm.state.toolNames.size} 个工具") { vm.screen = Screen.Skills }
|
||||||
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f))
|
||||||
|
NavRow("智能体", "${vm.state.agents.size} 个") { vm.screen = Screen.Agents }
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
|
||||||
|
SettingsCard("关于") {
|
||||||
|
FormHint("豆包客户端复刻版:原生 Compose 界面 + 跑在同一进程里的本地 Python 内核,请求不经过任何中转服务器。")
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
TextButton(onClick = { vm.refresh() }) { Text("重新连接内核", fontSize = 13.sp) }
|
||||||
|
TextButton(onClick = { vm.newTopic() }) { Text("开启新话题", fontSize = 13.sp) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 只读状态行:没有箭头,因为点它什么也不会发生 */
|
||||||
|
@Composable
|
||||||
|
private fun ProfileInfoRow(label: String, value: String) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(vertical = 12.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(label, fontSize = 14.sp)
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
Text(value, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 提供商显示名:优先用内核给的预设 label,缺了退回 key */
|
||||||
|
private fun providerLabel(vm: AppViewModel, key: String): String =
|
||||||
|
vm.state.providers[key]?.label ?: key
|
||||||
1030
android/app/src/main/java/com/doubao/lynxclone/ui/SettingsScreen.kt
Normal file
@@ -0,0 +1,413 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
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.height
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
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.filled.PlayArrow
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Checkbox
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
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.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.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.doubao.lynxclone.data.PythonTool
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/** 成功色的绿:主题色板里没有 success 槽位,单独定一个,别硬套 primary */
|
||||||
|
private val SuccessGreen = Color(0xFF3AA76D)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 技能 · 连接器页(对应旧版 Lynx 的 Skills.tsx)。三块:工具权限 / Python 工具 / MCP 服务。
|
||||||
|
*
|
||||||
|
* 几个刻意的做法:
|
||||||
|
*
|
||||||
|
* 1. **安全模式先存本地再点「应用」**。勾选白名单是个多步操作,每次点一下都发请求
|
||||||
|
* 等于把内核的 security 改了 N 次(中间态还可能是"限制模式 + 空白名单",
|
||||||
|
* 那一瞬间模型什么工具都用不了)。所以照旧版:本地改 draft,点应用才落盘。
|
||||||
|
*
|
||||||
|
* 2. **试运行参数走弹窗**而不是每行内嵌一个输入框。手机上内嵌输入框会把列表撑得很高,
|
||||||
|
* 还容易误触;弹窗一次只服务一个工具,焦点清楚。
|
||||||
|
*
|
||||||
|
* 3. **「重新连接」= 拿当前编辑器里的文本再存一次**。KernelClient 有 reconnectMcp(),
|
||||||
|
* 但 AppViewModel 没把它暴露出来(那是别人的文件,不动);而内核的
|
||||||
|
* PUT /api/mcp/config 本身就是"写盘 → disconnect_all → connect_all_enabled",
|
||||||
|
* 所以存一次当前文本 = 重连一次。副作用只是把同一份配置重写了一遍,没有风险。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun SkillsScreen(vm: AppViewModel) {
|
||||||
|
val saved = vm.settings.security
|
||||||
|
var mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) }
|
||||||
|
var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) }
|
||||||
|
|
||||||
|
var runTarget by remember { mutableStateOf<PythonTool?>(null) }
|
||||||
|
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||||
|
val toolResults = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||||
|
var running by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
val savedMcpText = vm.state.mcpConfigText
|
||||||
|
val mcpText = remember { mutableStateOf(savedMcpText) }
|
||||||
|
var busy by remember { mutableStateOf("") }
|
||||||
|
var mcpMessage by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
// 内核那边配置变了(保存成功会刷新 state、或者别人改了文件后点刷新),
|
||||||
|
// 编辑器跟着走一遍;否则界面会一直显示旧文本,用户以为没保存上。
|
||||||
|
LaunchedEffect(savedMcpText) {
|
||||||
|
if (savedMcpText.isNotBlank()) mcpText.value = savedMcpText
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxSize()) {
|
||||||
|
ScreenHeader("技能 · 连接器", onBack = { vm.screen = Screen.Chat }) {
|
||||||
|
// 右上角的刷新:内核里刚放进去的 *.py / MCP 状态,点一下就能重新发现
|
||||||
|
TextButton(onClick = { vm.refresh() }) { Text("刷新", fontSize = 13.sp) }
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.fillMaxWidth()
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.imePadding()
|
||||||
|
.padding(horizontal = 14.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Spacer(Modifier.height(2.dp))
|
||||||
|
|
||||||
|
/* ==================== ① 工具权限 ==================== */
|
||||||
|
SettingsCard("工具权限") {
|
||||||
|
SegmentedOptions(
|
||||||
|
options = listOf("open" to "完全开放", "restricted" to "限制模式"),
|
||||||
|
selected = mode,
|
||||||
|
onSelect = { mode = it },
|
||||||
|
)
|
||||||
|
FormHint(
|
||||||
|
if (mode == "open") {
|
||||||
|
"完全开放:${vm.state.toolNames.size} 个工具都交给模型自由调用。"
|
||||||
|
} else {
|
||||||
|
"限制模式:只有勾选的工具可用,其余即使模型点名也会被拦下。已选 ${allow.size} 个。"
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if (mode == "restricted") {
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
TextButton(onClick = { allow = vm.state.suggestedAllow.toSet() }) {
|
||||||
|
Text("只勾只读工具", fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
TextButton(onClick = { allow = emptySet() }) {
|
||||||
|
Text("全部取消", fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vm.state.toolNames.isEmpty()) {
|
||||||
|
FormHint("内核还没上报工具名。先去「设置」确认工具目录,或者放一个 *.py 进 tools 目录。")
|
||||||
|
}
|
||||||
|
vm.state.toolNames.forEach { name ->
|
||||||
|
ToolAllowRow(
|
||||||
|
name = name,
|
||||||
|
checked = name in allow,
|
||||||
|
readOnly = name in vm.state.suggestedAllow,
|
||||||
|
onToggle = { on ->
|
||||||
|
allow = if (on) allow + name else allow - name
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Button(
|
||||||
|
onClick = { vm.saveSecurity(mode, allow.toList()) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(24.dp),
|
||||||
|
contentPadding = PaddingValues(vertical = 12.dp),
|
||||||
|
) {
|
||||||
|
Text("应用权限设置", fontSize = 15.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ==================== ② Python 工具 ==================== */
|
||||||
|
SettingsCard("Python 工具 · ${vm.state.tools.size} 个") {
|
||||||
|
if (vm.state.tools.isEmpty()) {
|
||||||
|
FormHint("没有发现工具。往 tools 目录里放一个 *.py,用 _protocol 暴露即可。")
|
||||||
|
}
|
||||||
|
vm.state.tools.forEach { tool ->
|
||||||
|
ToolItem(
|
||||||
|
tool = tool,
|
||||||
|
running = running == tool.name,
|
||||||
|
result = toolResults.value[tool.name].orEmpty(),
|
||||||
|
onRun = { runTarget = tool },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
FormHint("试运行会真的执行这个工具(不受安全模式限制,因为是你手点的)。")
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ==================== ③ MCP 服务 ==================== */
|
||||||
|
SettingsCard("MCP 服务") {
|
||||||
|
if (vm.state.mcp.isEmpty()) {
|
||||||
|
FormHint("还没有配置 MCP 服务。在下面的原始 JSON 里加一条就能接上。")
|
||||||
|
}
|
||||||
|
vm.state.mcp.forEach { server ->
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(server.name, fontSize = 14.sp, fontWeight = FontWeight.Medium)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
StatusBadge(server.connected)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
buildString {
|
||||||
|
append(server.transport)
|
||||||
|
if (server.target.isNotBlank()) append(" · ${server.target}")
|
||||||
|
append(" · ${server.toolCount} 个工具")
|
||||||
|
},
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
if (server.error.isNotBlank()) {
|
||||||
|
Text(server.error, fontSize = 11.sp, color = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
SectionTitle("原始 JSON")
|
||||||
|
FormField(
|
||||||
|
value = mcpText.value,
|
||||||
|
onValue = { mcpText.value = it },
|
||||||
|
placeholder = """{"servers":[]}""",
|
||||||
|
singleLine = false,
|
||||||
|
minLines = 6,
|
||||||
|
)
|
||||||
|
FormHint("支持 stdio / http / sse;路径里可以写 \${DOUBAO_DATA} 之类的占位符。")
|
||||||
|
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
busy = "save"
|
||||||
|
vm.saveMcpConfig(mcpText.value) { ok, msg ->
|
||||||
|
busy = ""
|
||||||
|
mcpMessage = if (ok) msg else "保存失败:$msg"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(24.dp),
|
||||||
|
contentPadding = PaddingValues(vertical = 12.dp),
|
||||||
|
enabled = busy == "",
|
||||||
|
) {
|
||||||
|
Text(if (busy == "save") "保存中…" else "保存并重连", fontSize = 15.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
TextButton(
|
||||||
|
onClick = {
|
||||||
|
busy = "reconnect"
|
||||||
|
vm.saveMcpConfig(mcpText.value) { ok, msg ->
|
||||||
|
busy = ""
|
||||||
|
mcpMessage = if (ok) "已重连:$msg" else "重连失败:$msg"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled = busy == "",
|
||||||
|
) {
|
||||||
|
Text(if (busy == "reconnect") "重连中…" else "重新连接", fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
TextButton(onClick = { mcpText.value = vm.state.mcpConfigText }) {
|
||||||
|
Text("重新读取", fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mcpMessage.isNotBlank()) {
|
||||||
|
ResultBox(mcpMessage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 试运行参数的输入弹窗 */
|
||||||
|
runTarget?.let { tool ->
|
||||||
|
ToolRunDialog(
|
||||||
|
tool = tool,
|
||||||
|
initialArgs = toolArgs.value[tool.name].orEmpty(),
|
||||||
|
onDismiss = { runTarget = null },
|
||||||
|
onRun = { json ->
|
||||||
|
toolArgs.value = toolArgs.value + (tool.name to json)
|
||||||
|
runTarget = null
|
||||||
|
running = tool.name
|
||||||
|
val args = runCatching { JSONObject(json.ifBlank { "{}" }) }.getOrNull()
|
||||||
|
if (args == null) {
|
||||||
|
running = ""
|
||||||
|
toolResults.value = toolResults.value + (tool.name to "参数不是合法 JSON,请检查括号和引号。")
|
||||||
|
return@ToolRunDialog
|
||||||
|
}
|
||||||
|
vm.runTool(tool.name, args) { ok, text ->
|
||||||
|
running = ""
|
||||||
|
toolResults.value = toolResults.value + (
|
||||||
|
tool.name to if (ok) "返回:${preview(text)}" else "调用失败:$text"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ 零件 ------------------------------ */
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ToolAllowRow(name: String, checked: Boolean, readOnly: Boolean, onToggle: (Boolean) -> Unit) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Checkbox(checked = checked, onCheckedChange = onToggle)
|
||||||
|
Text(name, fontSize = 13.sp, modifier = Modifier.weight(1f))
|
||||||
|
// 「只读」标签来自内核对工具名/描述的判断(suggestedAllow),点它等价于点行本身
|
||||||
|
if (readOnly) {
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(6.dp),
|
||||||
|
color = MaterialTheme.colorScheme.primaryContainer,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
"只读",
|
||||||
|
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||||
|
fontSize = 10.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ToolItem(tool: PythonTool, running: Boolean, result: String, onRun: () -> Unit) {
|
||||||
|
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
|
||||||
|
Text(tool.name, fontSize = 14.sp, fontWeight = FontWeight.Medium)
|
||||||
|
if (tool.description.isNotBlank()) {
|
||||||
|
Text(tool.description, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
Text(tool.file, fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
|
||||||
|
TextButton(onClick = onRun, enabled = !running) {
|
||||||
|
Icon(Icons.Filled.PlayArrow, null, modifier = Modifier.size(16.dp))
|
||||||
|
Spacer(Modifier.width(4.dp))
|
||||||
|
Text(if (running) "执行中…" else "试运行", fontSize = 13.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.isNotBlank()) ResultBox(result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun StatusBadge(connected: Boolean) {
|
||||||
|
val color = if (connected) SuccessGreen else MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(color.copy(alpha = 0.14f))
|
||||||
|
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
if (connected) "已连接" else "未连接",
|
||||||
|
fontSize = 10.sp,
|
||||||
|
color = color,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ResultBox(text: String) {
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||||
|
shape = RoundedCornerShape(10.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text,
|
||||||
|
modifier = Modifier.padding(10.dp),
|
||||||
|
fontSize = 12.sp,
|
||||||
|
lineHeight = 18.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 试运行参数弹窗。
|
||||||
|
* 空输入按 {} 处理 —— 很多工具没有必填参数,逼用户手打一对大括号很烦。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun ToolRunDialog(
|
||||||
|
tool: PythonTool,
|
||||||
|
initialArgs: String,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onRun: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
var json by remember { mutableStateOf(initialArgs) }
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text("试运行 ${tool.name}", fontSize = 16.sp) },
|
||||||
|
text = {
|
||||||
|
Column {
|
||||||
|
if (tool.description.isNotBlank()) {
|
||||||
|
Text(tool.description, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
}
|
||||||
|
OutlinedTextField(
|
||||||
|
value = json,
|
||||||
|
onValueChange = { json = it },
|
||||||
|
modifier = Modifier.fillMaxWidth().height(130.dp),
|
||||||
|
placeholder = { Text("""参数 JSON,例如 {"expression":"1+1"}""", fontSize = 12.sp) },
|
||||||
|
textStyle = TextStyle(fontSize = 13.sp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
"留空 = 不带参数执行",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(onClick = { onRun(json) }) { Text("试运行") } },
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 工具返回可能很长(比如抓了一整页网页),列表里只给预览 */
|
||||||
|
private fun preview(value: String): String =
|
||||||
|
if (value.length > 600) value.take(600) + "…" else value
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.horizontalScroll
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
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.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
|
import com.doubao.lynxclone.termux.TermuxInstaller
|
||||||
|
import com.doubao.lynxclone.termux.TermuxTerminal
|
||||||
|
import com.termux.view.TerminalView
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 内置 Termux 终端。
|
||||||
|
*
|
||||||
|
* 这里是**真的终端**,不是"命令框":
|
||||||
|
* - 进程侧用 Termux 的 pty(libtermux.so 的 JNI 直接调 forkpty),所以是 tty,能跑 vim/top
|
||||||
|
* - 渲染侧用 Termux 的 TerminalView,ANSI 颜色、光标、选区都是现成的
|
||||||
|
*
|
||||||
|
* 手机上没有 Esc/Tab/方向键,所以额外加了一排功能键 —— 没有它连 vim 都退不出来。
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun TerminalScreen(
|
||||||
|
vm: AppViewModel,
|
||||||
|
termuxReady: Boolean,
|
||||||
|
termuxStatus: String,
|
||||||
|
onInstallTermux: () -> Unit,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val terminal = remember { TermuxTerminal(context) }
|
||||||
|
var title by remember { mutableStateOf("termux") }
|
||||||
|
/** pty 起不来(有些 ROM 的 /dev/pts 不给应用用)时切成命令控制台 */
|
||||||
|
var ptyFailed by remember { mutableStateOf(false) }
|
||||||
|
var startedAt by remember { mutableStateOf(0L) }
|
||||||
|
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
onDispose { terminal.destroy() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// pty 不可用的判定:会话建起来后 2 秒内就结束,说明 bash 拿不到 tty(stdin 直接 EOF)
|
||||||
|
val onSessionExit = {
|
||||||
|
if (startedAt > 0 && System.currentTimeMillis() - startedAt < 2000) {
|
||||||
|
ptyFailed = true
|
||||||
|
TermuxInstaller.trace(context, "pty 不可用(会话秒退),切换到命令控制台")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxSize().background(Color(0xFF14161A))) {
|
||||||
|
// ---------------- 顶部栏 ----------------
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().background(Color(0xFF1C1F24)).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
IconButton(onClick = { vm.screen = Screen.Chat }) {
|
||||||
|
Icon(Icons.Filled.ArrowBack, "返回", tint = Color.White)
|
||||||
|
}
|
||||||
|
Text(title, color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
IconButton(onClick = {
|
||||||
|
// 发一个 Ctrl+C,终止前台进程(手机上没键盘,这是最常用的逃生键)
|
||||||
|
terminal.session?.write("\u0003".toByteArray(), 0, 1)
|
||||||
|
}) { Icon(Icons.Filled.Stop, "Ctrl+C", tint = Color.White) }
|
||||||
|
IconButton(onClick = {
|
||||||
|
terminal.session?.write("clear\n".toByteArray(), 0, 6)
|
||||||
|
}) { Icon(Icons.Filled.DeleteSweep, "清屏", tint = Color.White) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- 环境状态 / 安装入口 ----------------
|
||||||
|
if (!termuxReady) {
|
||||||
|
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Column(Modifier.padding(12.dp)) {
|
||||||
|
Text(
|
||||||
|
if (termuxStatus.isBlank()) "正在准备内置 Termux 环境…" else termuxStatus,
|
||||||
|
color = Color(0xFFFFD08A),
|
||||||
|
fontSize = 12.sp,
|
||||||
|
lineHeight = 18.sp,
|
||||||
|
)
|
||||||
|
if (termuxStatus.contains("失败")) {
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
TextButton(onClick = onInstallTermux) { Text("重试安装") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Surface(color = Color(0xFF16301F), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Text(
|
||||||
|
"Termux 已内置 · ${TermuxInstaller.prefix(context).absolutePath}\n" +
|
||||||
|
"试试点上面的 + 装东西:pkg install python nodejs-lts",
|
||||||
|
color = Color(0xFF9BE7B4),
|
||||||
|
fontSize = 11.sp,
|
||||||
|
lineHeight = 16.sp,
|
||||||
|
modifier = Modifier.padding(10.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- 终端本体 ----------------
|
||||||
|
if (termuxReady && ptyFailed) {
|
||||||
|
// pty 用不了 → 命令控制台(跑的是同一条 Termux bash,只是没有 tty)
|
||||||
|
Box(Modifier.weight(1f).fillMaxWidth().background(Color(0xFF14161A))) {
|
||||||
|
CommandConsole(
|
||||||
|
onRun = { command, done ->
|
||||||
|
vm.runTool("shell", org.json.JSONObject().put("command", command)) { ok, text ->
|
||||||
|
done(ok, text)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else if (termuxReady) {
|
||||||
|
AndroidView(
|
||||||
|
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||||
|
factory = { ctx ->
|
||||||
|
TerminalView(ctx, null).apply {
|
||||||
|
setTerminalViewClient(terminal.viewClient())
|
||||||
|
setTextSize(28)
|
||||||
|
isFocusable = true
|
||||||
|
isFocusableInTouchMode = true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
update = { view ->
|
||||||
|
try {
|
||||||
|
val session = terminal.session ?: run {
|
||||||
|
startedAt = System.currentTimeMillis()
|
||||||
|
terminal.createSession(onTitle = { title = it }, onExit = onSessionExit)
|
||||||
|
}
|
||||||
|
if (view.currentSession !== session) {
|
||||||
|
view.attachSession(session)
|
||||||
|
view.requestFocus()
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
title = "会话启动失败:${t.message}"
|
||||||
|
ptyFailed = true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// 没就绪时给一块占位区,别留空白让人以为卡死了
|
||||||
|
Box(
|
||||||
|
Modifier.weight(1f).fillMaxWidth(),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
"内置 Termux 环境还没装好,装好后这里就是真终端。",
|
||||||
|
color = Color(0xFF8A93A0),
|
||||||
|
fontSize = 13.sp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- 功能键(手机没键盘,必须有这一排) ----------------
|
||||||
|
if (termuxReady) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().background(Color(0xFF1C1F24))
|
||||||
|
.horizontalScroll(rememberScrollState()).padding(6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
data class Key(val label: String, val bytes: String)
|
||||||
|
val keys = listOf(
|
||||||
|
Key("ESC", "\u001b"),
|
||||||
|
Key("TAB", "\t"),
|
||||||
|
Key("CTRL+C", "\u0003"),
|
||||||
|
Key("CTRL+D", "\u0004"),
|
||||||
|
Key("↑", "\u001b[A"),
|
||||||
|
Key("↓", "\u001b[B"),
|
||||||
|
Key("←", "\u001b[D"),
|
||||||
|
Key("→", "\u001b[C"),
|
||||||
|
Key("HOME", "\u001b[H"),
|
||||||
|
Key("END", "\u001b[F"),
|
||||||
|
Key("|", "|"),
|
||||||
|
Key("/", "/"),
|
||||||
|
Key("-", "-"),
|
||||||
|
Key("ENTER", "\n"),
|
||||||
|
)
|
||||||
|
keys.forEach { key ->
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(6.dp),
|
||||||
|
color = Color(0xFF2A2F37),
|
||||||
|
modifier = Modifier.padding(end = 6.dp).clickable {
|
||||||
|
val s = terminal.session ?: return@clickable
|
||||||
|
val bytes = key.bytes.toByteArray()
|
||||||
|
s.write(bytes, 0, bytes.size)
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
key.label,
|
||||||
|
color = Color(0xFFD7DAE0),
|
||||||
|
fontSize = 12.sp,
|
||||||
|
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.doubao.lynxclone.ui.theme
|
||||||
|
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.darkColorScheme
|
||||||
|
import androidx.compose.material3.lightColorScheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 照着豆包的观感取的色:主色 #2B7BFF。
|
||||||
|
*
|
||||||
|
* 关键一点:**背景是纯白**,不是浅灰。
|
||||||
|
* 豆包的层级靠"白底 + 浅灰卡片"表达,之前用 #F7F8FA 当背景,
|
||||||
|
* 整页看上去就是一股系统设置的灰味。
|
||||||
|
*/
|
||||||
|
private val DoubaoBlue = Color(0xFF2B7BFF)
|
||||||
|
|
||||||
|
private val LightColors = lightColorScheme(
|
||||||
|
primary = DoubaoBlue,
|
||||||
|
onPrimary = Color.White,
|
||||||
|
primaryContainer = Color(0xFFDCE9FF),
|
||||||
|
onPrimaryContainer = Color(0xFF0B2E66),
|
||||||
|
secondary = Color(0xFF5A6472),
|
||||||
|
background = Color.White,
|
||||||
|
onBackground = Color(0xFF1F2329),
|
||||||
|
surface = Color.White,
|
||||||
|
onSurface = Color(0xFF1F2329),
|
||||||
|
surfaceVariant = Color(0xFFF7F8FA),
|
||||||
|
onSurfaceVariant = Color(0xFF5A6472),
|
||||||
|
outline = Color(0xFFE5E7EB),
|
||||||
|
outlineVariant = Color(0xFFEFF1F4),
|
||||||
|
error = Color(0xFFE5484D),
|
||||||
|
)
|
||||||
|
|
||||||
|
private val DarkColors = darkColorScheme(
|
||||||
|
primary = Color(0xFF5B9BFF),
|
||||||
|
onPrimary = Color.White,
|
||||||
|
primaryContainer = Color(0xFF1E355C),
|
||||||
|
onPrimaryContainer = Color(0xFFD6E6FF),
|
||||||
|
secondary = Color(0xFFA8AFBA),
|
||||||
|
background = Color(0xFF101216),
|
||||||
|
onBackground = Color(0xFFE8EAED),
|
||||||
|
surface = Color(0xFF101216),
|
||||||
|
onSurface = Color(0xFFE8EAED),
|
||||||
|
surfaceVariant = Color(0xFF1F232A),
|
||||||
|
onSurfaceVariant = Color(0xFFA8AFBA),
|
||||||
|
outline = Color(0xFF2E333B),
|
||||||
|
outlineVariant = Color(0xFF262A31),
|
||||||
|
error = Color(0xFFFF8F8F),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun DoubaoTheme(
|
||||||
|
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||||
|
content: @Composable () -> Unit,
|
||||||
|
) {
|
||||||
|
MaterialTheme(
|
||||||
|
colorScheme = if (darkTheme) DarkColors else LightColors,
|
||||||
|
content = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
108
android/app/src/main/java/com/termux/terminal/ByteQueue.java
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
/** A circular byte buffer allowing one producer and one consumer thread. */
|
||||||
|
final class ByteQueue {
|
||||||
|
|
||||||
|
private final byte[] mBuffer;
|
||||||
|
private int mHead;
|
||||||
|
private int mStoredBytes;
|
||||||
|
private boolean mOpen = true;
|
||||||
|
|
||||||
|
public ByteQueue(int size) {
|
||||||
|
mBuffer = new byte[size];
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void close() {
|
||||||
|
mOpen = false;
|
||||||
|
notify();
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized int read(byte[] buffer, boolean block) {
|
||||||
|
while (mStoredBytes == 0 && mOpen) {
|
||||||
|
if (block) {
|
||||||
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// Ignore.
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!mOpen) return -1;
|
||||||
|
|
||||||
|
int totalRead = 0;
|
||||||
|
int bufferLength = mBuffer.length;
|
||||||
|
boolean wasFull = bufferLength == mStoredBytes;
|
||||||
|
int length = buffer.length;
|
||||||
|
int offset = 0;
|
||||||
|
while (length > 0 && mStoredBytes > 0) {
|
||||||
|
int oneRun = Math.min(bufferLength - mHead, mStoredBytes);
|
||||||
|
int bytesToCopy = Math.min(length, oneRun);
|
||||||
|
System.arraycopy(mBuffer, mHead, buffer, offset, bytesToCopy);
|
||||||
|
mHead += bytesToCopy;
|
||||||
|
if (mHead >= bufferLength) mHead = 0;
|
||||||
|
mStoredBytes -= bytesToCopy;
|
||||||
|
length -= bytesToCopy;
|
||||||
|
offset += bytesToCopy;
|
||||||
|
totalRead += bytesToCopy;
|
||||||
|
}
|
||||||
|
if (wasFull) notify();
|
||||||
|
return totalRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attempt to write the specified portion of the provided buffer to the queue.
|
||||||
|
* <p/>
|
||||||
|
* Returns whether the output was totally written, false if it was closed before.
|
||||||
|
*/
|
||||||
|
public boolean write(byte[] buffer, int offset, int lengthToWrite) {
|
||||||
|
if (lengthToWrite + offset > buffer.length) {
|
||||||
|
throw new IllegalArgumentException("length + offset > buffer.length");
|
||||||
|
} else if (lengthToWrite <= 0) {
|
||||||
|
throw new IllegalArgumentException("length <= 0");
|
||||||
|
}
|
||||||
|
|
||||||
|
final int bufferLength = mBuffer.length;
|
||||||
|
|
||||||
|
synchronized (this) {
|
||||||
|
while (lengthToWrite > 0) {
|
||||||
|
while (bufferLength == mStoredBytes && mOpen) {
|
||||||
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// Ignore.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!mOpen) return false;
|
||||||
|
final boolean wasEmpty = mStoredBytes == 0;
|
||||||
|
int bytesToWriteBeforeWaiting = Math.min(lengthToWrite, bufferLength - mStoredBytes);
|
||||||
|
lengthToWrite -= bytesToWriteBeforeWaiting;
|
||||||
|
|
||||||
|
while (bytesToWriteBeforeWaiting > 0) {
|
||||||
|
int tail = mHead + mStoredBytes;
|
||||||
|
int oneRun;
|
||||||
|
if (tail >= bufferLength) {
|
||||||
|
// Buffer: [.............]
|
||||||
|
// ________________H_______T
|
||||||
|
// =>
|
||||||
|
// Buffer: [.............]
|
||||||
|
// ___________T____H
|
||||||
|
// onRun= _____----_
|
||||||
|
tail = tail - bufferLength;
|
||||||
|
oneRun = mHead - tail;
|
||||||
|
} else {
|
||||||
|
oneRun = bufferLength - tail;
|
||||||
|
}
|
||||||
|
int bytesToCopy = Math.min(oneRun, bytesToWriteBeforeWaiting);
|
||||||
|
System.arraycopy(buffer, offset, mBuffer, tail, bytesToCopy);
|
||||||
|
offset += bytesToCopy;
|
||||||
|
bytesToWriteBeforeWaiting -= bytesToCopy;
|
||||||
|
mStoredBytes += bytesToCopy;
|
||||||
|
}
|
||||||
|
if (wasEmpty) notify();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
41
android/app/src/main/java/com/termux/terminal/JNI.java
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Native methods for creating and managing pseudoterminal subprocesses. C code is in jni/termux.c.
|
||||||
|
*/
|
||||||
|
final class JNI {
|
||||||
|
|
||||||
|
static {
|
||||||
|
System.loadLibrary("termux");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a subprocess. Differs from {@link ProcessBuilder} in that a pseudoterminal is used to communicate with the
|
||||||
|
* subprocess.
|
||||||
|
* <p/>
|
||||||
|
* Callers are responsible for calling {@link #close(int)} on the returned file descriptor.
|
||||||
|
*
|
||||||
|
* @param cmd The command to execute
|
||||||
|
* @param cwd The current working directory for the executed command
|
||||||
|
* @param args An array of arguments to the command
|
||||||
|
* @param envVars An array of strings of the form "VAR=value" to be added to the environment of the process
|
||||||
|
* @param processId A one-element array to which the process ID of the started process will be written.
|
||||||
|
* @return the file descriptor resulting from opening /dev/ptmx master device. The sub process will have opened the
|
||||||
|
* slave device counterpart (/dev/pts/$N) and have it as stdint, stdout and stderr.
|
||||||
|
*/
|
||||||
|
public static native int createSubprocess(String cmd, String cwd, String[] args, String[] envVars, int[] processId, int rows, int columns, int cellWidth, int cellHeight);
|
||||||
|
|
||||||
|
/** Set the window size for a given pty, which allows connected programs to learn how large their screen is. */
|
||||||
|
public static native void setPtyWindowSize(int fd, int rows, int cols, int cellWidth, int cellHeight);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Causes the calling thread to wait for the process associated with the receiver to finish executing.
|
||||||
|
*
|
||||||
|
* @return if >= 0, the exit status of the process. If < 0, the signal causing the process to stop negated.
|
||||||
|
*/
|
||||||
|
public static native int waitFor(int processId);
|
||||||
|
|
||||||
|
/** Close a file descriptor through the close(2) system call. */
|
||||||
|
public static native void close(int fileDescriptor);
|
||||||
|
|
||||||
|
}
|
||||||
373
android/app/src/main/java/com/termux/terminal/KeyHandler.java
Normal file
@@ -0,0 +1,373 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static android.view.KeyEvent.KEYCODE_BACK;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_BREAK;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_DEL;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_DPAD_CENTER;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_DPAD_DOWN;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_DPAD_LEFT;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_DPAD_RIGHT;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_DPAD_UP;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_ENTER;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_ESCAPE;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F1;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F10;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F11;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F12;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F2;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F3;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F4;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F5;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F6;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F7;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F8;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_F9;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_FORWARD_DEL;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_INSERT;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_MOVE_END;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_MOVE_HOME;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_0;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_1;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_2;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_3;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_4;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_5;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_6;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_7;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_8;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_9;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_ADD;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_COMMA;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_DIVIDE;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_DOT;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_ENTER;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_EQUALS;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_MULTIPLY;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUMPAD_SUBTRACT;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_NUM_LOCK;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_PAGE_DOWN;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_PAGE_UP;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_SPACE;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_SYSRQ;
|
||||||
|
import static android.view.KeyEvent.KEYCODE_TAB;
|
||||||
|
|
||||||
|
public final class KeyHandler {
|
||||||
|
|
||||||
|
public static final int KEYMOD_ALT = 0x80000000;
|
||||||
|
public static final int KEYMOD_CTRL = 0x40000000;
|
||||||
|
public static final int KEYMOD_SHIFT = 0x20000000;
|
||||||
|
public static final int KEYMOD_NUM_LOCK = 0x10000000;
|
||||||
|
|
||||||
|
private static final Map<String, Integer> TERMCAP_TO_KEYCODE = new HashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
// terminfo: http://pubs.opengroup.org/onlinepubs/7990989799/xcurses/terminfo.html
|
||||||
|
// termcap: http://man7.org/linux/man-pages/man5/termcap.5.html
|
||||||
|
TERMCAP_TO_KEYCODE.put("%i", KEYMOD_SHIFT | KEYCODE_DPAD_RIGHT);
|
||||||
|
TERMCAP_TO_KEYCODE.put("#2", KEYMOD_SHIFT | KEYCODE_MOVE_HOME); // Shifted home
|
||||||
|
TERMCAP_TO_KEYCODE.put("#4", KEYMOD_SHIFT | KEYCODE_DPAD_LEFT);
|
||||||
|
TERMCAP_TO_KEYCODE.put("*7", KEYMOD_SHIFT | KEYCODE_MOVE_END); // Shifted end key
|
||||||
|
|
||||||
|
TERMCAP_TO_KEYCODE.put("k1", KEYCODE_F1);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k2", KEYCODE_F2);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k3", KEYCODE_F3);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k4", KEYCODE_F4);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k5", KEYCODE_F5);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k6", KEYCODE_F6);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k7", KEYCODE_F7);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k8", KEYCODE_F8);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k9", KEYCODE_F9);
|
||||||
|
TERMCAP_TO_KEYCODE.put("k;", KEYCODE_F10);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F1", KEYCODE_F11);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F2", KEYCODE_F12);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F3", KEYMOD_SHIFT | KEYCODE_F1);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F4", KEYMOD_SHIFT | KEYCODE_F2);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F5", KEYMOD_SHIFT | KEYCODE_F3);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F6", KEYMOD_SHIFT | KEYCODE_F4);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F7", KEYMOD_SHIFT | KEYCODE_F5);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F8", KEYMOD_SHIFT | KEYCODE_F6);
|
||||||
|
TERMCAP_TO_KEYCODE.put("F9", KEYMOD_SHIFT | KEYCODE_F7);
|
||||||
|
TERMCAP_TO_KEYCODE.put("FA", KEYMOD_SHIFT | KEYCODE_F8);
|
||||||
|
TERMCAP_TO_KEYCODE.put("FB", KEYMOD_SHIFT | KEYCODE_F9);
|
||||||
|
TERMCAP_TO_KEYCODE.put("FC", KEYMOD_SHIFT | KEYCODE_F10);
|
||||||
|
TERMCAP_TO_KEYCODE.put("FD", KEYMOD_SHIFT | KEYCODE_F11);
|
||||||
|
TERMCAP_TO_KEYCODE.put("FE", KEYMOD_SHIFT | KEYCODE_F12);
|
||||||
|
|
||||||
|
TERMCAP_TO_KEYCODE.put("kb", KEYCODE_DEL); // backspace key
|
||||||
|
|
||||||
|
TERMCAP_TO_KEYCODE.put("kd", KEYCODE_DPAD_DOWN); // terminfo=kcud1, down-arrow key
|
||||||
|
TERMCAP_TO_KEYCODE.put("kh", KEYCODE_MOVE_HOME);
|
||||||
|
TERMCAP_TO_KEYCODE.put("kl", KEYCODE_DPAD_LEFT);
|
||||||
|
TERMCAP_TO_KEYCODE.put("kr", KEYCODE_DPAD_RIGHT);
|
||||||
|
|
||||||
|
// K1=Upper left of keypad:
|
||||||
|
// t_K1 <kHome> keypad home key
|
||||||
|
// t_K3 <kPageUp> keypad page-up key
|
||||||
|
// t_K4 <kEnd> keypad end key
|
||||||
|
// t_K5 <kPageDown> keypad page-down key
|
||||||
|
TERMCAP_TO_KEYCODE.put("K1", KEYCODE_MOVE_HOME);
|
||||||
|
TERMCAP_TO_KEYCODE.put("K3", KEYCODE_PAGE_UP);
|
||||||
|
TERMCAP_TO_KEYCODE.put("K4", KEYCODE_MOVE_END);
|
||||||
|
TERMCAP_TO_KEYCODE.put("K5", KEYCODE_PAGE_DOWN);
|
||||||
|
|
||||||
|
TERMCAP_TO_KEYCODE.put("ku", KEYCODE_DPAD_UP);
|
||||||
|
|
||||||
|
TERMCAP_TO_KEYCODE.put("kB", KEYMOD_SHIFT | KEYCODE_TAB); // termcap=kB, terminfo=kcbt: Back-tab
|
||||||
|
TERMCAP_TO_KEYCODE.put("kD", KEYCODE_FORWARD_DEL); // terminfo=kdch1, delete-character key
|
||||||
|
TERMCAP_TO_KEYCODE.put("kDN", KEYMOD_SHIFT | KEYCODE_DPAD_DOWN); // non-standard shifted arrow down
|
||||||
|
TERMCAP_TO_KEYCODE.put("kF", KEYMOD_SHIFT | KEYCODE_DPAD_DOWN); // terminfo=kind, scroll-forward key
|
||||||
|
TERMCAP_TO_KEYCODE.put("kI", KEYCODE_INSERT);
|
||||||
|
TERMCAP_TO_KEYCODE.put("kN", KEYCODE_PAGE_UP);
|
||||||
|
TERMCAP_TO_KEYCODE.put("kP", KEYCODE_PAGE_DOWN);
|
||||||
|
TERMCAP_TO_KEYCODE.put("kR", KEYMOD_SHIFT | KEYCODE_DPAD_UP); // terminfo=kri, scroll-backward key
|
||||||
|
TERMCAP_TO_KEYCODE.put("kUP", KEYMOD_SHIFT | KEYCODE_DPAD_UP); // non-standard shifted up
|
||||||
|
|
||||||
|
TERMCAP_TO_KEYCODE.put("@7", KEYCODE_MOVE_END);
|
||||||
|
TERMCAP_TO_KEYCODE.put("@8", KEYCODE_NUMPAD_ENTER);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String getCodeFromTermcap(String termcap, boolean cursorKeysApplication, boolean keypadApplication) {
|
||||||
|
Integer keyCodeAndMod = TERMCAP_TO_KEYCODE.get(termcap);
|
||||||
|
if (keyCodeAndMod == null) return null;
|
||||||
|
int keyCode = keyCodeAndMod;
|
||||||
|
int keyMod = 0;
|
||||||
|
if ((keyCode & KEYMOD_SHIFT) != 0) {
|
||||||
|
keyMod |= KEYMOD_SHIFT;
|
||||||
|
keyCode &= ~KEYMOD_SHIFT;
|
||||||
|
}
|
||||||
|
if ((keyCode & KEYMOD_CTRL) != 0) {
|
||||||
|
keyMod |= KEYMOD_CTRL;
|
||||||
|
keyCode &= ~KEYMOD_CTRL;
|
||||||
|
}
|
||||||
|
if ((keyCode & KEYMOD_ALT) != 0) {
|
||||||
|
keyMod |= KEYMOD_ALT;
|
||||||
|
keyCode &= ~KEYMOD_ALT;
|
||||||
|
}
|
||||||
|
if ((keyCode & KEYMOD_NUM_LOCK) != 0) {
|
||||||
|
keyMod |= KEYMOD_NUM_LOCK;
|
||||||
|
keyCode &= ~KEYMOD_NUM_LOCK;
|
||||||
|
}
|
||||||
|
return getCode(keyCode, keyMod, cursorKeysApplication, keypadApplication);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getCode(int keyCode, int keyMode, boolean cursorApp, boolean keypadApplication) {
|
||||||
|
boolean numLockOn = (keyMode & KEYMOD_NUM_LOCK) != 0;
|
||||||
|
keyMode &= ~KEYMOD_NUM_LOCK;
|
||||||
|
switch (keyCode) {
|
||||||
|
case KEYCODE_DPAD_CENTER:
|
||||||
|
return "\015";
|
||||||
|
|
||||||
|
case KEYCODE_DPAD_UP:
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OA" : "\033[A") : transformForModifiers("\033[1", keyMode, 'A');
|
||||||
|
case KEYCODE_DPAD_DOWN:
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OB" : "\033[B") : transformForModifiers("\033[1", keyMode, 'B');
|
||||||
|
case KEYCODE_DPAD_RIGHT:
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OC" : "\033[C") : transformForModifiers("\033[1", keyMode, 'C');
|
||||||
|
case KEYCODE_DPAD_LEFT:
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OD" : "\033[D") : transformForModifiers("\033[1", keyMode, 'D');
|
||||||
|
|
||||||
|
case KEYCODE_MOVE_HOME:
|
||||||
|
// Note that KEYCODE_HOME is handled by the system and never delivered to applications.
|
||||||
|
// On a Logitech k810 keyboard KEYCODE_MOVE_HOME is sent by FN+LeftArrow.
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OH" : "\033[H") : transformForModifiers("\033[1", keyMode, 'H');
|
||||||
|
case KEYCODE_MOVE_END:
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OF" : "\033[F") : transformForModifiers("\033[1", keyMode, 'F');
|
||||||
|
|
||||||
|
// An xterm can send function keys F1 to F4 in two modes: vt100 compatible or
|
||||||
|
// not. Because Vim may not know what the xterm is sending, both types of keys
|
||||||
|
// are recognized. The same happens for the <Home> and <End> keys.
|
||||||
|
// normal vt100 ~
|
||||||
|
// <F1> t_k1 <Esc>[11~ <xF1> <Esc>OP *<xF1>-xterm*
|
||||||
|
// <F2> t_k2 <Esc>[12~ <xF2> <Esc>OQ *<xF2>-xterm*
|
||||||
|
// <F3> t_k3 <Esc>[13~ <xF3> <Esc>OR *<xF3>-xterm*
|
||||||
|
// <F4> t_k4 <Esc>[14~ <xF4> <Esc>OS *<xF4>-xterm*
|
||||||
|
// <Home> t_kh <Esc>[7~ <xHome> <Esc>OH *<xHome>-xterm*
|
||||||
|
// <End> t_@7 <Esc>[4~ <xEnd> <Esc>OF *<xEnd>-xterm*
|
||||||
|
case KEYCODE_F1:
|
||||||
|
return (keyMode == 0) ? "\033OP" : transformForModifiers("\033[1", keyMode, 'P');
|
||||||
|
case KEYCODE_F2:
|
||||||
|
return (keyMode == 0) ? "\033OQ" : transformForModifiers("\033[1", keyMode, 'Q');
|
||||||
|
case KEYCODE_F3:
|
||||||
|
return (keyMode == 0) ? "\033OR" : transformForModifiers("\033[1", keyMode, 'R');
|
||||||
|
case KEYCODE_F4:
|
||||||
|
return (keyMode == 0) ? "\033OS" : transformForModifiers("\033[1", keyMode, 'S');
|
||||||
|
case KEYCODE_F5:
|
||||||
|
return transformForModifiers("\033[15", keyMode, '~');
|
||||||
|
case KEYCODE_F6:
|
||||||
|
return transformForModifiers("\033[17", keyMode, '~');
|
||||||
|
case KEYCODE_F7:
|
||||||
|
return transformForModifiers("\033[18", keyMode, '~');
|
||||||
|
case KEYCODE_F8:
|
||||||
|
return transformForModifiers("\033[19", keyMode, '~');
|
||||||
|
case KEYCODE_F9:
|
||||||
|
return transformForModifiers("\033[20", keyMode, '~');
|
||||||
|
case KEYCODE_F10:
|
||||||
|
return transformForModifiers("\033[21", keyMode, '~');
|
||||||
|
case KEYCODE_F11:
|
||||||
|
return transformForModifiers("\033[23", keyMode, '~');
|
||||||
|
case KEYCODE_F12:
|
||||||
|
return transformForModifiers("\033[24", keyMode, '~');
|
||||||
|
|
||||||
|
case KEYCODE_SYSRQ:
|
||||||
|
return "\033[32~"; // Sys Request / Print
|
||||||
|
// Is this Scroll lock? case Cancel: return "\033[33~";
|
||||||
|
case KEYCODE_BREAK:
|
||||||
|
return "\033[34~"; // Pause/Break
|
||||||
|
|
||||||
|
case KEYCODE_ESCAPE:
|
||||||
|
case KEYCODE_BACK:
|
||||||
|
return "\033";
|
||||||
|
|
||||||
|
case KEYCODE_INSERT:
|
||||||
|
return transformForModifiers("\033[2", keyMode, '~');
|
||||||
|
case KEYCODE_FORWARD_DEL:
|
||||||
|
return transformForModifiers("\033[3", keyMode, '~');
|
||||||
|
|
||||||
|
case KEYCODE_PAGE_UP:
|
||||||
|
return "\033[5~";
|
||||||
|
case KEYCODE_PAGE_DOWN:
|
||||||
|
return "\033[6~";
|
||||||
|
case KEYCODE_DEL:
|
||||||
|
String prefix = ((keyMode & KEYMOD_ALT) == 0) ? "" : "\033";
|
||||||
|
// Just do what xterm and gnome-terminal does:
|
||||||
|
return prefix + (((keyMode & KEYMOD_CTRL) == 0) ? "\u007F" : "\u0008");
|
||||||
|
case KEYCODE_NUM_LOCK:
|
||||||
|
if (keypadApplication) {
|
||||||
|
return "\033OP";
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
case KEYCODE_SPACE:
|
||||||
|
// If ctrl is not down, return null so that it goes through normal input processing (which may e.g. cause a
|
||||||
|
// combining accent to be written):
|
||||||
|
return ((keyMode & KEYMOD_CTRL) == 0) ? null : "\0";
|
||||||
|
case KEYCODE_TAB:
|
||||||
|
// This is back-tab when shifted:
|
||||||
|
return (keyMode & KEYMOD_SHIFT) == 0 ? "\011" : "\033[Z";
|
||||||
|
case KEYCODE_ENTER:
|
||||||
|
return ((keyMode & KEYMOD_ALT) == 0) ? "\r" : "\033\r";
|
||||||
|
|
||||||
|
case KEYCODE_NUMPAD_ENTER:
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'M') : "\n";
|
||||||
|
case KEYCODE_NUMPAD_MULTIPLY:
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'j') : "*";
|
||||||
|
case KEYCODE_NUMPAD_ADD:
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'k') : "+";
|
||||||
|
case KEYCODE_NUMPAD_COMMA:
|
||||||
|
return ",";
|
||||||
|
case KEYCODE_NUMPAD_DOT:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? "\033On" : ".";
|
||||||
|
} else {
|
||||||
|
// DELETE
|
||||||
|
return transformForModifiers("\033[3", keyMode, '~');
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_SUBTRACT:
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'm') : "-";
|
||||||
|
case KEYCODE_NUMPAD_DIVIDE:
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'o') : "/";
|
||||||
|
case KEYCODE_NUMPAD_0:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'p') : "0";
|
||||||
|
} else {
|
||||||
|
// INSERT
|
||||||
|
return transformForModifiers("\033[2", keyMode, '~');
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_1:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'q') : "1";
|
||||||
|
} else {
|
||||||
|
// END
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OF" : "\033[F") : transformForModifiers("\033[1", keyMode, 'F');
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_2:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'r') : "2";
|
||||||
|
} else {
|
||||||
|
// DOWN
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OB" : "\033[B") : transformForModifiers("\033[1", keyMode, 'B');
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_3:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 's') : "3";
|
||||||
|
} else {
|
||||||
|
// PGDN
|
||||||
|
return "\033[6~";
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_4:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 't') : "4";
|
||||||
|
} else {
|
||||||
|
// LEFT
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OD" : "\033[D") : transformForModifiers("\033[1", keyMode, 'D');
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_5:
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'u') : "5";
|
||||||
|
case KEYCODE_NUMPAD_6:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'v') : "6";
|
||||||
|
} else {
|
||||||
|
// RIGHT
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OC" : "\033[C") : transformForModifiers("\033[1", keyMode, 'C');
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_7:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'w') : "7";
|
||||||
|
} else {
|
||||||
|
// HOME
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OH" : "\033[H") : transformForModifiers("\033[1", keyMode, 'H');
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_8:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'x') : "8";
|
||||||
|
} else {
|
||||||
|
// UP
|
||||||
|
return (keyMode == 0) ? (cursorApp ? "\033OA" : "\033[A") : transformForModifiers("\033[1", keyMode, 'A');
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_9:
|
||||||
|
if (numLockOn) {
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'y') : "9";
|
||||||
|
} else {
|
||||||
|
// PGUP
|
||||||
|
return "\033[5~";
|
||||||
|
}
|
||||||
|
case KEYCODE_NUMPAD_EQUALS:
|
||||||
|
return keypadApplication ? transformForModifiers("\033O", keyMode, 'X') : "=";
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String transformForModifiers(String start, int keymod, char lastChar) {
|
||||||
|
int modifier;
|
||||||
|
switch (keymod) {
|
||||||
|
case KEYMOD_SHIFT:
|
||||||
|
modifier = 2;
|
||||||
|
break;
|
||||||
|
case KEYMOD_ALT:
|
||||||
|
modifier = 3;
|
||||||
|
break;
|
||||||
|
case (KEYMOD_SHIFT | KEYMOD_ALT):
|
||||||
|
modifier = 4;
|
||||||
|
break;
|
||||||
|
case KEYMOD_CTRL:
|
||||||
|
modifier = 5;
|
||||||
|
break;
|
||||||
|
case KEYMOD_SHIFT | KEYMOD_CTRL:
|
||||||
|
modifier = 6;
|
||||||
|
break;
|
||||||
|
case KEYMOD_ALT | KEYMOD_CTRL:
|
||||||
|
modifier = 7;
|
||||||
|
break;
|
||||||
|
case KEYMOD_SHIFT | KEYMOD_ALT | KEYMOD_CTRL:
|
||||||
|
modifier = 8;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return start + lastChar;
|
||||||
|
}
|
||||||
|
return start + (";" + modifier) + lastChar;
|
||||||
|
}
|
||||||
|
}
|
||||||
80
android/app/src/main/java/com/termux/terminal/Logger.java
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
|
||||||
|
public class Logger {
|
||||||
|
|
||||||
|
public static void logError(TerminalSessionClient client, String logTag, String message) {
|
||||||
|
if (client != null)
|
||||||
|
client.logError(logTag, message);
|
||||||
|
else
|
||||||
|
Log.e(logTag, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void logWarn(TerminalSessionClient client, String logTag, String message) {
|
||||||
|
if (client != null)
|
||||||
|
client.logWarn(logTag, message);
|
||||||
|
else
|
||||||
|
Log.w(logTag, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void logInfo(TerminalSessionClient client, String logTag, String message) {
|
||||||
|
if (client != null)
|
||||||
|
client.logInfo(logTag, message);
|
||||||
|
else
|
||||||
|
Log.i(logTag, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void logDebug(TerminalSessionClient client, String logTag, String message) {
|
||||||
|
if (client != null)
|
||||||
|
client.logDebug(logTag, message);
|
||||||
|
else
|
||||||
|
Log.d(logTag, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void logVerbose(TerminalSessionClient client, String logTag, String message) {
|
||||||
|
if (client != null)
|
||||||
|
client.logVerbose(logTag, message);
|
||||||
|
else
|
||||||
|
Log.v(logTag, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void logStackTraceWithMessage(TerminalSessionClient client, String tag, String message, Throwable throwable) {
|
||||||
|
logError(client, tag, getMessageAndStackTraceString(message, throwable));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getMessageAndStackTraceString(String message, Throwable throwable) {
|
||||||
|
if (message == null && throwable == null)
|
||||||
|
return null;
|
||||||
|
else if (message != null && throwable != null)
|
||||||
|
return message + ":\n" + getStackTraceString(throwable);
|
||||||
|
else if (throwable == null)
|
||||||
|
return message;
|
||||||
|
else
|
||||||
|
return getStackTraceString(throwable);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getStackTraceString(Throwable throwable) {
|
||||||
|
if (throwable == null) return null;
|
||||||
|
|
||||||
|
String stackTraceString = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
StringWriter errors = new StringWriter();
|
||||||
|
PrintWriter pw = new PrintWriter(errors);
|
||||||
|
throwable.printStackTrace(pw);
|
||||||
|
pw.close();
|
||||||
|
stackTraceString = errors.toString();
|
||||||
|
errors.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return stackTraceString;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,497 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A circular buffer of {@link TerminalRow}:s which keeps notes about what is visible on a logical screen and the scroll
|
||||||
|
* history.
|
||||||
|
* <p>
|
||||||
|
* See {@link #externalToInternalRow(int)} for how to map from logical screen rows to array indices.
|
||||||
|
*/
|
||||||
|
public final class TerminalBuffer {
|
||||||
|
|
||||||
|
TerminalRow[] mLines;
|
||||||
|
/** The length of {@link #mLines}. */
|
||||||
|
int mTotalRows;
|
||||||
|
/** The number of rows and columns visible on the screen. */
|
||||||
|
int mScreenRows, mColumns;
|
||||||
|
/** The number of rows kept in history. */
|
||||||
|
private int mActiveTranscriptRows = 0;
|
||||||
|
/** The index in the circular buffer where the visible screen starts. */
|
||||||
|
private int mScreenFirstRow = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a transcript screen.
|
||||||
|
*
|
||||||
|
* @param columns the width of the screen in characters.
|
||||||
|
* @param totalRows the height of the entire text area, in rows of text.
|
||||||
|
* @param screenRows the height of just the screen, not including the transcript that holds lines that have scrolled off
|
||||||
|
* the top of the screen.
|
||||||
|
*/
|
||||||
|
public TerminalBuffer(int columns, int totalRows, int screenRows) {
|
||||||
|
mColumns = columns;
|
||||||
|
mTotalRows = totalRows;
|
||||||
|
mScreenRows = screenRows;
|
||||||
|
mLines = new TerminalRow[totalRows];
|
||||||
|
|
||||||
|
blockSet(0, 0, columns, screenRows, ' ', TextStyle.NORMAL);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTranscriptText() {
|
||||||
|
return getSelectedText(0, -getActiveTranscriptRows(), mColumns, mScreenRows).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTranscriptTextWithoutJoinedLines() {
|
||||||
|
return getSelectedText(0, -getActiveTranscriptRows(), mColumns, mScreenRows, false).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTranscriptTextWithFullLinesJoined() {
|
||||||
|
return getSelectedText(0, -getActiveTranscriptRows(), mColumns, mScreenRows, true, true).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSelectedText(int selX1, int selY1, int selX2, int selY2) {
|
||||||
|
return getSelectedText(selX1, selY1, selX2, selY2, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSelectedText(int selX1, int selY1, int selX2, int selY2, boolean joinBackLines) {
|
||||||
|
return getSelectedText(selX1, selY1, selX2, selY2, joinBackLines, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSelectedText(int selX1, int selY1, int selX2, int selY2, boolean joinBackLines, boolean joinFullLines) {
|
||||||
|
final StringBuilder builder = new StringBuilder();
|
||||||
|
final int columns = mColumns;
|
||||||
|
|
||||||
|
if (selY1 < -getActiveTranscriptRows()) selY1 = -getActiveTranscriptRows();
|
||||||
|
if (selY2 >= mScreenRows) selY2 = mScreenRows - 1;
|
||||||
|
|
||||||
|
for (int row = selY1; row <= selY2; row++) {
|
||||||
|
int x1 = (row == selY1) ? selX1 : 0;
|
||||||
|
int x2;
|
||||||
|
if (row == selY2) {
|
||||||
|
x2 = selX2 + 1;
|
||||||
|
if (x2 > columns) x2 = columns;
|
||||||
|
} else {
|
||||||
|
x2 = columns;
|
||||||
|
}
|
||||||
|
TerminalRow lineObject = mLines[externalToInternalRow(row)];
|
||||||
|
int x1Index = lineObject.findStartOfColumn(x1);
|
||||||
|
int x2Index = (x2 < mColumns) ? lineObject.findStartOfColumn(x2) : lineObject.getSpaceUsed();
|
||||||
|
if (x2Index == x1Index) {
|
||||||
|
// Selected the start of a wide character.
|
||||||
|
x2Index = lineObject.findStartOfColumn(x2 + 1);
|
||||||
|
}
|
||||||
|
char[] line = lineObject.mText;
|
||||||
|
int lastPrintingCharIndex = -1;
|
||||||
|
int i;
|
||||||
|
boolean rowLineWrap = getLineWrap(row);
|
||||||
|
if (rowLineWrap && x2 == columns) {
|
||||||
|
// If the line was wrapped, we shouldn't lose trailing space:
|
||||||
|
lastPrintingCharIndex = x2Index - 1;
|
||||||
|
} else {
|
||||||
|
for (i = x1Index; i < x2Index; ++i) {
|
||||||
|
char c = line[i];
|
||||||
|
if (c != ' ') lastPrintingCharIndex = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int len = lastPrintingCharIndex - x1Index + 1;
|
||||||
|
if (lastPrintingCharIndex != -1 && len > 0)
|
||||||
|
builder.append(line, x1Index, len);
|
||||||
|
|
||||||
|
boolean lineFillsWidth = lastPrintingCharIndex == x2Index - 1;
|
||||||
|
if ((!joinBackLines || !rowLineWrap) && (!joinFullLines || !lineFillsWidth)
|
||||||
|
&& row < selY2 && row < mScreenRows - 1) builder.append('\n');
|
||||||
|
}
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getWordAtLocation(int x, int y) {
|
||||||
|
// Set y1 and y2 to the lines where the wrapped line starts and ends.
|
||||||
|
// I.e. if a line that is wrapped to 3 lines starts at line 4, and this
|
||||||
|
// is called with y=5, then y1 would be set to 4 and y2 would be set to 6.
|
||||||
|
int y1 = y;
|
||||||
|
int y2 = y;
|
||||||
|
while (y1 > 0 && !getSelectedText(0, y1 - 1, mColumns, y, true, true).contains("\n")) {
|
||||||
|
y1--;
|
||||||
|
}
|
||||||
|
while (y2 < mScreenRows && !getSelectedText(0, y, mColumns, y2 + 1, true, true).contains("\n")) {
|
||||||
|
y2++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the text for the whole wrapped line
|
||||||
|
String text = getSelectedText(0, y1, mColumns, y2, true, true);
|
||||||
|
// The index of x in text
|
||||||
|
int textOffset = (y - y1) * mColumns + x;
|
||||||
|
|
||||||
|
if (textOffset >= text.length()) {
|
||||||
|
// The click was to the right of the last word on the line, so
|
||||||
|
// there's no word to return
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set x1 and x2 to the indices of the last space before x and the
|
||||||
|
// first space after x in text respectively
|
||||||
|
int x1 = text.lastIndexOf(' ', textOffset);
|
||||||
|
int x2 = text.indexOf(' ', textOffset);
|
||||||
|
if (x2 == -1) {
|
||||||
|
x2 = text.length();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (x1 == x2) {
|
||||||
|
// The click was on a space, so there's no word to return
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return text.substring(x1 + 1, x2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getActiveTranscriptRows() {
|
||||||
|
return mActiveTranscriptRows;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getActiveRows() {
|
||||||
|
return mActiveTranscriptRows + mScreenRows;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a row value from the public external coordinate system to our internal private coordinate system.
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* - External coordinate system: -mActiveTranscriptRows to mScreenRows-1, with the screen being 0..mScreenRows-1.
|
||||||
|
* - Internal coordinate system: the mScreenRows lines starting at mScreenFirstRow comprise the screen, while the
|
||||||
|
* mActiveTranscriptRows lines ending at mScreenFirstRow-1 form the transcript (as a circular buffer).
|
||||||
|
*
|
||||||
|
* External ↔ Internal:
|
||||||
|
*
|
||||||
|
* [ ... ] [ ... ]
|
||||||
|
* [ -mActiveTranscriptRows ] [ mScreenFirstRow - mActiveTranscriptRows ]
|
||||||
|
* [ ... ] [ ... ]
|
||||||
|
* [ 0 (visible screen starts here) ] ↔ [ mScreenFirstRow ]
|
||||||
|
* [ ... ] [ ... ]
|
||||||
|
* [ mScreenRows-1 ] [ mScreenFirstRow + mScreenRows-1 ]
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @param externalRow a row in the external coordinate system.
|
||||||
|
* @return The row corresponding to the input argument in the private coordinate system.
|
||||||
|
*/
|
||||||
|
public int externalToInternalRow(int externalRow) {
|
||||||
|
if (externalRow < -mActiveTranscriptRows || externalRow > mScreenRows)
|
||||||
|
throw new IllegalArgumentException("extRow=" + externalRow + ", mScreenRows=" + mScreenRows + ", mActiveTranscriptRows=" + mActiveTranscriptRows);
|
||||||
|
final int internalRow = mScreenFirstRow + externalRow;
|
||||||
|
return (internalRow < 0) ? (mTotalRows + internalRow) : (internalRow % mTotalRows);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLineWrap(int row) {
|
||||||
|
mLines[externalToInternalRow(row)].mLineWrap = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean getLineWrap(int row) {
|
||||||
|
return mLines[externalToInternalRow(row)].mLineWrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clearLineWrap(int row) {
|
||||||
|
mLines[externalToInternalRow(row)].mLineWrap = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resize the screen which this transcript backs. Currently, this only works if the number of columns does not
|
||||||
|
* change or the rows expand (that is, it only works when shrinking the number of rows).
|
||||||
|
*
|
||||||
|
* @param newColumns The number of columns the screen should have.
|
||||||
|
* @param newRows The number of rows the screen should have.
|
||||||
|
* @param cursor An int[2] containing the (column, row) cursor location.
|
||||||
|
*/
|
||||||
|
public void resize(int newColumns, int newRows, int newTotalRows, int[] cursor, long currentStyle, boolean altScreen) {
|
||||||
|
// newRows > mTotalRows should not normally happen since mTotalRows is TRANSCRIPT_ROWS (10000):
|
||||||
|
if (newColumns == mColumns && newRows <= mTotalRows) {
|
||||||
|
// Fast resize where just the rows changed.
|
||||||
|
int shiftDownOfTopRow = mScreenRows - newRows;
|
||||||
|
if (shiftDownOfTopRow > 0 && shiftDownOfTopRow < mScreenRows) {
|
||||||
|
// Shrinking. Check if we can skip blank rows at bottom below cursor.
|
||||||
|
for (int i = mScreenRows - 1; i > 0; i--) {
|
||||||
|
if (cursor[1] >= i) break;
|
||||||
|
int r = externalToInternalRow(i);
|
||||||
|
if (mLines[r] == null || mLines[r].isBlank()) {
|
||||||
|
if (--shiftDownOfTopRow == 0) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (shiftDownOfTopRow < 0) {
|
||||||
|
// Negative shift down = expanding. Only move screen up if there is transcript to show:
|
||||||
|
int actualShift = Math.max(shiftDownOfTopRow, -mActiveTranscriptRows);
|
||||||
|
if (shiftDownOfTopRow != actualShift) {
|
||||||
|
// The new lines revealed by the resizing are not all from the transcript. Blank the below ones.
|
||||||
|
for (int i = 0; i < actualShift - shiftDownOfTopRow; i++)
|
||||||
|
allocateFullLineIfNecessary((mScreenFirstRow + mScreenRows + i) % mTotalRows).clear(currentStyle);
|
||||||
|
shiftDownOfTopRow = actualShift;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mScreenFirstRow += shiftDownOfTopRow;
|
||||||
|
mScreenFirstRow = (mScreenFirstRow < 0) ? (mScreenFirstRow + mTotalRows) : (mScreenFirstRow % mTotalRows);
|
||||||
|
mTotalRows = newTotalRows;
|
||||||
|
mActiveTranscriptRows = altScreen ? 0 : Math.max(0, mActiveTranscriptRows + shiftDownOfTopRow);
|
||||||
|
cursor[1] -= shiftDownOfTopRow;
|
||||||
|
mScreenRows = newRows;
|
||||||
|
} else {
|
||||||
|
// Copy away old state and update new:
|
||||||
|
TerminalRow[] oldLines = mLines;
|
||||||
|
mLines = new TerminalRow[newTotalRows];
|
||||||
|
for (int i = 0; i < newTotalRows; i++)
|
||||||
|
mLines[i] = new TerminalRow(newColumns, currentStyle);
|
||||||
|
|
||||||
|
final int oldActiveTranscriptRows = mActiveTranscriptRows;
|
||||||
|
final int oldScreenFirstRow = mScreenFirstRow;
|
||||||
|
final int oldScreenRows = mScreenRows;
|
||||||
|
final int oldTotalRows = mTotalRows;
|
||||||
|
mTotalRows = newTotalRows;
|
||||||
|
mScreenRows = newRows;
|
||||||
|
mActiveTranscriptRows = mScreenFirstRow = 0;
|
||||||
|
mColumns = newColumns;
|
||||||
|
|
||||||
|
int newCursorRow = -1;
|
||||||
|
int newCursorColumn = -1;
|
||||||
|
int oldCursorRow = cursor[1];
|
||||||
|
int oldCursorColumn = cursor[0];
|
||||||
|
boolean newCursorPlaced = false;
|
||||||
|
|
||||||
|
int currentOutputExternalRow = 0;
|
||||||
|
int currentOutputExternalColumn = 0;
|
||||||
|
|
||||||
|
// Loop over every character in the initial state.
|
||||||
|
// Blank lines should be skipped only if at end of transcript (just as is done in the "fast" resize), so we
|
||||||
|
// keep track how many blank lines we have skipped if we later on find a non-blank line.
|
||||||
|
int skippedBlankLines = 0;
|
||||||
|
for (int externalOldRow = -oldActiveTranscriptRows; externalOldRow < oldScreenRows; externalOldRow++) {
|
||||||
|
// Do what externalToInternalRow() does but for the old state:
|
||||||
|
int internalOldRow = oldScreenFirstRow + externalOldRow;
|
||||||
|
internalOldRow = (internalOldRow < 0) ? (oldTotalRows + internalOldRow) : (internalOldRow % oldTotalRows);
|
||||||
|
|
||||||
|
TerminalRow oldLine = oldLines[internalOldRow];
|
||||||
|
boolean cursorAtThisRow = externalOldRow == oldCursorRow;
|
||||||
|
// The cursor may only be on a non-null line, which we should not skip:
|
||||||
|
if (oldLine == null || (!(!newCursorPlaced && cursorAtThisRow)) && oldLine.isBlank()) {
|
||||||
|
skippedBlankLines++;
|
||||||
|
continue;
|
||||||
|
} else if (skippedBlankLines > 0) {
|
||||||
|
// After skipping some blank lines we encounter a non-blank line. Insert the skipped blank lines.
|
||||||
|
for (int i = 0; i < skippedBlankLines; i++) {
|
||||||
|
if (currentOutputExternalRow == mScreenRows - 1) {
|
||||||
|
scrollDownOneLine(0, mScreenRows, currentStyle);
|
||||||
|
} else {
|
||||||
|
currentOutputExternalRow++;
|
||||||
|
}
|
||||||
|
currentOutputExternalColumn = 0;
|
||||||
|
}
|
||||||
|
skippedBlankLines = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int lastNonSpaceIndex = 0;
|
||||||
|
boolean justToCursor = false;
|
||||||
|
if (cursorAtThisRow || oldLine.mLineWrap) {
|
||||||
|
// Take the whole line, either because of cursor on it, or if line wrapping.
|
||||||
|
lastNonSpaceIndex = oldLine.getSpaceUsed();
|
||||||
|
if (cursorAtThisRow) justToCursor = true;
|
||||||
|
} else {
|
||||||
|
for (int i = 0; i < oldLine.getSpaceUsed(); i++)
|
||||||
|
// NEWLY INTRODUCED BUG! Should not index oldLine.mStyle with char indices
|
||||||
|
if (oldLine.mText[i] != ' '/* || oldLine.mStyle[i] != currentStyle */)
|
||||||
|
lastNonSpaceIndex = i + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int currentOldCol = 0;
|
||||||
|
long styleAtCol = 0;
|
||||||
|
for (int i = 0; i < lastNonSpaceIndex; i++) {
|
||||||
|
// Note that looping over java character, not cells.
|
||||||
|
char c = oldLine.mText[i];
|
||||||
|
int codePoint = (Character.isHighSurrogate(c)) ? Character.toCodePoint(c, oldLine.mText[++i]) : c;
|
||||||
|
int displayWidth = WcWidth.width(codePoint);
|
||||||
|
// Use the last style if this is a zero-width character:
|
||||||
|
if (displayWidth > 0) styleAtCol = oldLine.getStyle(currentOldCol);
|
||||||
|
|
||||||
|
// Line wrap as necessary:
|
||||||
|
if (currentOutputExternalColumn + displayWidth > mColumns) {
|
||||||
|
setLineWrap(currentOutputExternalRow);
|
||||||
|
if (currentOutputExternalRow == mScreenRows - 1) {
|
||||||
|
if (newCursorPlaced) newCursorRow--;
|
||||||
|
scrollDownOneLine(0, mScreenRows, currentStyle);
|
||||||
|
} else {
|
||||||
|
currentOutputExternalRow++;
|
||||||
|
}
|
||||||
|
currentOutputExternalColumn = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int offsetDueToCombiningChar = ((displayWidth <= 0 && currentOutputExternalColumn > 0) ? 1 : 0);
|
||||||
|
int outputColumn = currentOutputExternalColumn - offsetDueToCombiningChar;
|
||||||
|
setChar(outputColumn, currentOutputExternalRow, codePoint, styleAtCol);
|
||||||
|
|
||||||
|
if (displayWidth > 0) {
|
||||||
|
if (oldCursorRow == externalOldRow && oldCursorColumn == currentOldCol) {
|
||||||
|
newCursorColumn = currentOutputExternalColumn;
|
||||||
|
newCursorRow = currentOutputExternalRow;
|
||||||
|
newCursorPlaced = true;
|
||||||
|
}
|
||||||
|
currentOldCol += displayWidth;
|
||||||
|
currentOutputExternalColumn += displayWidth;
|
||||||
|
if (justToCursor && newCursorPlaced) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Old row has been copied. Check if we need to insert newline if old line was not wrapping:
|
||||||
|
if (externalOldRow != (oldScreenRows - 1) && !oldLine.mLineWrap) {
|
||||||
|
if (currentOutputExternalRow == mScreenRows - 1) {
|
||||||
|
if (newCursorPlaced) newCursorRow--;
|
||||||
|
scrollDownOneLine(0, mScreenRows, currentStyle);
|
||||||
|
} else {
|
||||||
|
currentOutputExternalRow++;
|
||||||
|
}
|
||||||
|
currentOutputExternalColumn = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor[0] = newCursorColumn;
|
||||||
|
cursor[1] = newCursorRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle cursor scrolling off screen:
|
||||||
|
if (cursor[0] < 0 || cursor[1] < 0) cursor[0] = cursor[1] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Block copy lines and associated metadata from one location to another in the circular buffer, taking wraparound
|
||||||
|
* into account.
|
||||||
|
*
|
||||||
|
* @param srcInternal The first line to be copied.
|
||||||
|
* @param len The number of lines to be copied.
|
||||||
|
*/
|
||||||
|
private void blockCopyLinesDown(int srcInternal, int len) {
|
||||||
|
if (len == 0) return;
|
||||||
|
int totalRows = mTotalRows;
|
||||||
|
|
||||||
|
int start = len - 1;
|
||||||
|
// Save away line to be overwritten:
|
||||||
|
TerminalRow lineToBeOverWritten = mLines[(srcInternal + start + 1) % totalRows];
|
||||||
|
// Do the copy from bottom to top.
|
||||||
|
for (int i = start; i >= 0; --i)
|
||||||
|
mLines[(srcInternal + i + 1) % totalRows] = mLines[(srcInternal + i) % totalRows];
|
||||||
|
// Put back overwritten line, now above the block:
|
||||||
|
mLines[(srcInternal) % totalRows] = lineToBeOverWritten;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scroll the screen down one line. To scroll the whole screen of a 24 line screen, the arguments would be (0, 24).
|
||||||
|
*
|
||||||
|
* @param topMargin First line that is scrolled.
|
||||||
|
* @param bottomMargin One line after the last line that is scrolled.
|
||||||
|
* @param style the style for the newly exposed line.
|
||||||
|
*/
|
||||||
|
public void scrollDownOneLine(int topMargin, int bottomMargin, long style) {
|
||||||
|
if (topMargin > bottomMargin - 1 || topMargin < 0 || bottomMargin > mScreenRows)
|
||||||
|
throw new IllegalArgumentException("topMargin=" + topMargin + ", bottomMargin=" + bottomMargin + ", mScreenRows=" + mScreenRows);
|
||||||
|
|
||||||
|
// Copy the fixed topMargin lines one line down so that they remain on screen in same position:
|
||||||
|
blockCopyLinesDown(mScreenFirstRow, topMargin);
|
||||||
|
// Copy the fixed mScreenRows-bottomMargin lines one line down so that they remain on screen in same
|
||||||
|
// position:
|
||||||
|
blockCopyLinesDown(externalToInternalRow(bottomMargin), mScreenRows - bottomMargin);
|
||||||
|
|
||||||
|
// Update the screen location in the ring buffer:
|
||||||
|
mScreenFirstRow = (mScreenFirstRow + 1) % mTotalRows;
|
||||||
|
// Note that the history has grown if not already full:
|
||||||
|
if (mActiveTranscriptRows < mTotalRows - mScreenRows) mActiveTranscriptRows++;
|
||||||
|
|
||||||
|
// Blank the newly revealed line above the bottom margin:
|
||||||
|
int blankRow = externalToInternalRow(bottomMargin - 1);
|
||||||
|
if (mLines[blankRow] == null) {
|
||||||
|
mLines[blankRow] = new TerminalRow(mColumns, style);
|
||||||
|
} else {
|
||||||
|
mLines[blankRow].clear(style);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Block copy characters from one position in the screen to another. The two positions can overlap. All characters
|
||||||
|
* of the source and destination must be within the bounds of the screen, or else an InvalidParameterException will
|
||||||
|
* be thrown.
|
||||||
|
*
|
||||||
|
* @param sx source X coordinate
|
||||||
|
* @param sy source Y coordinate
|
||||||
|
* @param w width
|
||||||
|
* @param h height
|
||||||
|
* @param dx destination X coordinate
|
||||||
|
* @param dy destination Y coordinate
|
||||||
|
*/
|
||||||
|
public void blockCopy(int sx, int sy, int w, int h, int dx, int dy) {
|
||||||
|
if (w == 0) return;
|
||||||
|
if (sx < 0 || sx + w > mColumns || sy < 0 || sy + h > mScreenRows || dx < 0 || dx + w > mColumns || dy < 0 || dy + h > mScreenRows)
|
||||||
|
throw new IllegalArgumentException();
|
||||||
|
boolean copyingUp = sy > dy;
|
||||||
|
for (int y = 0; y < h; y++) {
|
||||||
|
int y2 = copyingUp ? y : (h - (y + 1));
|
||||||
|
TerminalRow sourceRow = allocateFullLineIfNecessary(externalToInternalRow(sy + y2));
|
||||||
|
allocateFullLineIfNecessary(externalToInternalRow(dy + y2)).copyInterval(sourceRow, sx, sx + w, dx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Block set characters. All characters must be within the bounds of the screen, or else and
|
||||||
|
* InvalidParemeterException will be thrown. Typically this is called with a "val" argument of 32 to clear a block
|
||||||
|
* of characters.
|
||||||
|
*/
|
||||||
|
public void blockSet(int sx, int sy, int w, int h, int val, long style) {
|
||||||
|
if (sx < 0 || sx + w > mColumns || sy < 0 || sy + h > mScreenRows) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Illegal arguments! blockSet(" + sx + ", " + sy + ", " + w + ", " + h + ", " + val + ", " + mColumns + ", " + mScreenRows + ")");
|
||||||
|
}
|
||||||
|
for (int y = 0; y < h; y++)
|
||||||
|
for (int x = 0; x < w; x++)
|
||||||
|
setChar(sx + x, sy + y, val, style);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TerminalRow allocateFullLineIfNecessary(int row) {
|
||||||
|
return (mLines[row] == null) ? (mLines[row] = new TerminalRow(mColumns, 0)) : mLines[row];
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setChar(int column, int row, int codePoint, long style) {
|
||||||
|
if (row < 0 || row >= mScreenRows || column < 0 || column >= mColumns)
|
||||||
|
throw new IllegalArgumentException("TerminalBuffer.setChar(): row=" + row + ", column=" + column + ", mScreenRows=" + mScreenRows + ", mColumns=" + mColumns);
|
||||||
|
row = externalToInternalRow(row);
|
||||||
|
allocateFullLineIfNecessary(row).setChar(column, codePoint, style);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getStyleAt(int externalRow, int column) {
|
||||||
|
return allocateFullLineIfNecessary(externalToInternalRow(externalRow)).getStyle(column);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Support for http://vt100.net/docs/vt510-rm/DECCARA and http://vt100.net/docs/vt510-rm/DECCARA */
|
||||||
|
public void setOrClearEffect(int bits, boolean setOrClear, boolean reverse, boolean rectangular, int leftMargin, int rightMargin, int top, int left,
|
||||||
|
int bottom, int right) {
|
||||||
|
for (int y = top; y < bottom; y++) {
|
||||||
|
TerminalRow line = mLines[externalToInternalRow(y)];
|
||||||
|
int startOfLine = (rectangular || y == top) ? left : leftMargin;
|
||||||
|
int endOfLine = (rectangular || y + 1 == bottom) ? right : rightMargin;
|
||||||
|
for (int x = startOfLine; x < endOfLine; x++) {
|
||||||
|
long currentStyle = line.getStyle(x);
|
||||||
|
int foreColor = TextStyle.decodeForeColor(currentStyle);
|
||||||
|
int backColor = TextStyle.decodeBackColor(currentStyle);
|
||||||
|
int effect = TextStyle.decodeEffect(currentStyle);
|
||||||
|
if (reverse) {
|
||||||
|
// Clear out the bits to reverse and add them back in reversed:
|
||||||
|
effect = (effect & ~bits) | (bits & ~effect);
|
||||||
|
} else if (setOrClear) {
|
||||||
|
effect |= bits;
|
||||||
|
} else {
|
||||||
|
effect &= ~bits;
|
||||||
|
}
|
||||||
|
line.mStyle[x] = TextStyle.encode(foreColor, backColor, effect);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clearTranscript() {
|
||||||
|
if (mScreenFirstRow < mActiveTranscriptRows) {
|
||||||
|
Arrays.fill(mLines, mTotalRows + mScreenFirstRow - mActiveTranscriptRows, mTotalRows, null);
|
||||||
|
Arrays.fill(mLines, 0, mScreenFirstRow, null);
|
||||||
|
} else {
|
||||||
|
Arrays.fill(mLines, mScreenFirstRow - mActiveTranscriptRows, mScreenFirstRow, null);
|
||||||
|
}
|
||||||
|
mActiveTranscriptRows = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Color scheme for a terminal with default colors, which may be overridden (and then reset) from the shell using
|
||||||
|
* Operating System Control (OSC) sequences.
|
||||||
|
*
|
||||||
|
* @see TerminalColors
|
||||||
|
*/
|
||||||
|
public final class TerminalColorScheme {
|
||||||
|
|
||||||
|
/** http://upload.wikimedia.org/wikipedia/en/1/15/Xterm_256color_chart.svg, but with blue color brighter. */
|
||||||
|
private static final int[] DEFAULT_COLORSCHEME = {
|
||||||
|
// 16 original colors. First 8 are dim.
|
||||||
|
0xff000000, // black
|
||||||
|
0xffcd0000, // dim red
|
||||||
|
0xff00cd00, // dim green
|
||||||
|
0xffcdcd00, // dim yellow
|
||||||
|
0xff6495ed, // dim blue
|
||||||
|
0xffcd00cd, // dim magenta
|
||||||
|
0xff00cdcd, // dim cyan
|
||||||
|
0xffe5e5e5, // dim white
|
||||||
|
// Second 8 are bright:
|
||||||
|
0xff7f7f7f, // medium grey
|
||||||
|
0xffff0000, // bright red
|
||||||
|
0xff00ff00, // bright green
|
||||||
|
0xffffff00, // bright yellow
|
||||||
|
0xff5c5cff, // light blue
|
||||||
|
0xffff00ff, // bright magenta
|
||||||
|
0xff00ffff, // bright cyan
|
||||||
|
0xffffffff, // bright white
|
||||||
|
|
||||||
|
// 216 color cube, six shades of each color:
|
||||||
|
0xff000000, 0xff00005f, 0xff000087, 0xff0000af, 0xff0000d7, 0xff0000ff, 0xff005f00, 0xff005f5f, 0xff005f87, 0xff005faf, 0xff005fd7, 0xff005fff,
|
||||||
|
0xff008700, 0xff00875f, 0xff008787, 0xff0087af, 0xff0087d7, 0xff0087ff, 0xff00af00, 0xff00af5f, 0xff00af87, 0xff00afaf, 0xff00afd7, 0xff00afff,
|
||||||
|
0xff00d700, 0xff00d75f, 0xff00d787, 0xff00d7af, 0xff00d7d7, 0xff00d7ff, 0xff00ff00, 0xff00ff5f, 0xff00ff87, 0xff00ffaf, 0xff00ffd7, 0xff00ffff,
|
||||||
|
0xff5f0000, 0xff5f005f, 0xff5f0087, 0xff5f00af, 0xff5f00d7, 0xff5f00ff, 0xff5f5f00, 0xff5f5f5f, 0xff5f5f87, 0xff5f5faf, 0xff5f5fd7, 0xff5f5fff,
|
||||||
|
0xff5f8700, 0xff5f875f, 0xff5f8787, 0xff5f87af, 0xff5f87d7, 0xff5f87ff, 0xff5faf00, 0xff5faf5f, 0xff5faf87, 0xff5fafaf, 0xff5fafd7, 0xff5fafff,
|
||||||
|
0xff5fd700, 0xff5fd75f, 0xff5fd787, 0xff5fd7af, 0xff5fd7d7, 0xff5fd7ff, 0xff5fff00, 0xff5fff5f, 0xff5fff87, 0xff5fffaf, 0xff5fffd7, 0xff5fffff,
|
||||||
|
0xff870000, 0xff87005f, 0xff870087, 0xff8700af, 0xff8700d7, 0xff8700ff, 0xff875f00, 0xff875f5f, 0xff875f87, 0xff875faf, 0xff875fd7, 0xff875fff,
|
||||||
|
0xff878700, 0xff87875f, 0xff878787, 0xff8787af, 0xff8787d7, 0xff8787ff, 0xff87af00, 0xff87af5f, 0xff87af87, 0xff87afaf, 0xff87afd7, 0xff87afff,
|
||||||
|
0xff87d700, 0xff87d75f, 0xff87d787, 0xff87d7af, 0xff87d7d7, 0xff87d7ff, 0xff87ff00, 0xff87ff5f, 0xff87ff87, 0xff87ffaf, 0xff87ffd7, 0xff87ffff,
|
||||||
|
0xffaf0000, 0xffaf005f, 0xffaf0087, 0xffaf00af, 0xffaf00d7, 0xffaf00ff, 0xffaf5f00, 0xffaf5f5f, 0xffaf5f87, 0xffaf5faf, 0xffaf5fd7, 0xffaf5fff,
|
||||||
|
0xffaf8700, 0xffaf875f, 0xffaf8787, 0xffaf87af, 0xffaf87d7, 0xffaf87ff, 0xffafaf00, 0xffafaf5f, 0xffafaf87, 0xffafafaf, 0xffafafd7, 0xffafafff,
|
||||||
|
0xffafd700, 0xffafd75f, 0xffafd787, 0xffafd7af, 0xffafd7d7, 0xffafd7ff, 0xffafff00, 0xffafff5f, 0xffafff87, 0xffafffaf, 0xffafffd7, 0xffafffff,
|
||||||
|
0xffd70000, 0xffd7005f, 0xffd70087, 0xffd700af, 0xffd700d7, 0xffd700ff, 0xffd75f00, 0xffd75f5f, 0xffd75f87, 0xffd75faf, 0xffd75fd7, 0xffd75fff,
|
||||||
|
0xffd78700, 0xffd7875f, 0xffd78787, 0xffd787af, 0xffd787d7, 0xffd787ff, 0xffd7af00, 0xffd7af5f, 0xffd7af87, 0xffd7afaf, 0xffd7afd7, 0xffd7afff,
|
||||||
|
0xffd7d700, 0xffd7d75f, 0xffd7d787, 0xffd7d7af, 0xffd7d7d7, 0xffd7d7ff, 0xffd7ff00, 0xffd7ff5f, 0xffd7ff87, 0xffd7ffaf, 0xffd7ffd7, 0xffd7ffff,
|
||||||
|
0xffff0000, 0xffff005f, 0xffff0087, 0xffff00af, 0xffff00d7, 0xffff00ff, 0xffff5f00, 0xffff5f5f, 0xffff5f87, 0xffff5faf, 0xffff5fd7, 0xffff5fff,
|
||||||
|
0xffff8700, 0xffff875f, 0xffff8787, 0xffff87af, 0xffff87d7, 0xffff87ff, 0xffffaf00, 0xffffaf5f, 0xffffaf87, 0xffffafaf, 0xffffafd7, 0xffffafff,
|
||||||
|
0xffffd700, 0xffffd75f, 0xffffd787, 0xffffd7af, 0xffffd7d7, 0xffffd7ff, 0xffffff00, 0xffffff5f, 0xffffff87, 0xffffffaf, 0xffffffd7, 0xffffffff,
|
||||||
|
|
||||||
|
// 24 grey scale ramp:
|
||||||
|
0xff080808, 0xff121212, 0xff1c1c1c, 0xff262626, 0xff303030, 0xff3a3a3a, 0xff444444, 0xff4e4e4e, 0xff585858, 0xff626262, 0xff6c6c6c, 0xff767676,
|
||||||
|
0xff808080, 0xff8a8a8a, 0xff949494, 0xff9e9e9e, 0xffa8a8a8, 0xffb2b2b2, 0xffbcbcbc, 0xffc6c6c6, 0xffd0d0d0, 0xffdadada, 0xffe4e4e4, 0xffeeeeee,
|
||||||
|
|
||||||
|
// COLOR_INDEX_DEFAULT_FOREGROUND, COLOR_INDEX_DEFAULT_BACKGROUND and COLOR_INDEX_DEFAULT_CURSOR:
|
||||||
|
0xffffffff, 0xff000000, 0xffffffff};
|
||||||
|
|
||||||
|
public final int[] mDefaultColors = new int[TextStyle.NUM_INDEXED_COLORS];
|
||||||
|
|
||||||
|
public TerminalColorScheme() {
|
||||||
|
reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void reset() {
|
||||||
|
System.arraycopy(DEFAULT_COLORSCHEME, 0, mDefaultColors, 0, TextStyle.NUM_INDEXED_COLORS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updateWith(Properties props) {
|
||||||
|
reset();
|
||||||
|
boolean cursorPropExists = false;
|
||||||
|
for (Map.Entry<Object, Object> entries : props.entrySet()) {
|
||||||
|
String key = (String) entries.getKey();
|
||||||
|
String value = (String) entries.getValue();
|
||||||
|
int colorIndex;
|
||||||
|
|
||||||
|
if (key.equals("foreground")) {
|
||||||
|
colorIndex = TextStyle.COLOR_INDEX_FOREGROUND;
|
||||||
|
} else if (key.equals("background")) {
|
||||||
|
colorIndex = TextStyle.COLOR_INDEX_BACKGROUND;
|
||||||
|
} else if (key.equals("cursor")) {
|
||||||
|
colorIndex = TextStyle.COLOR_INDEX_CURSOR;
|
||||||
|
cursorPropExists = true;
|
||||||
|
} else if (key.startsWith("color")) {
|
||||||
|
try {
|
||||||
|
colorIndex = Integer.parseInt(key.substring(5));
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
throw new IllegalArgumentException("Invalid property: '" + key + "'");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Invalid property: '" + key + "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
int colorValue = TerminalColors.parse(value);
|
||||||
|
if (colorValue == 0)
|
||||||
|
throw new IllegalArgumentException("Property '" + key + "' has invalid color: '" + value + "'");
|
||||||
|
|
||||||
|
mDefaultColors[colorIndex] = colorValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cursorPropExists)
|
||||||
|
setCursorColorForBackground();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the "cursor" color is not set by user, we need to decide on the appropriate color that will
|
||||||
|
* be visible on the current terminal background. White will not be visible on light backgrounds
|
||||||
|
* and black won't be visible on dark backgrounds. So we find the perceived brightness of the
|
||||||
|
* background color and if its below the threshold (too dark), we use white cursor and if its
|
||||||
|
* above (too bright), we use black cursor.
|
||||||
|
*/
|
||||||
|
public void setCursorColorForBackground() {
|
||||||
|
int backgroundColor = mDefaultColors[TextStyle.COLOR_INDEX_BACKGROUND];
|
||||||
|
int brightness = TerminalColors.getPerceivedBrightnessOfColor(backgroundColor);
|
||||||
|
if (brightness > 0) {
|
||||||
|
if (brightness < 130)
|
||||||
|
mDefaultColors[TextStyle.COLOR_INDEX_CURSOR] = 0xffffffff;
|
||||||
|
else
|
||||||
|
mDefaultColors[TextStyle.COLOR_INDEX_CURSOR] = 0xff000000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
import android.graphics.Color;
|
||||||
|
|
||||||
|
/** Current terminal colors (if different from default). */
|
||||||
|
public final class TerminalColors {
|
||||||
|
|
||||||
|
/** Static data - a bit ugly but ok for now. */
|
||||||
|
public static final TerminalColorScheme COLOR_SCHEME = new TerminalColorScheme();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The current terminal colors, which are normally set from the color theme, but may be set dynamically with the OSC
|
||||||
|
* 4 control sequence.
|
||||||
|
*/
|
||||||
|
public final int[] mCurrentColors = new int[TextStyle.NUM_INDEXED_COLORS];
|
||||||
|
|
||||||
|
/** Create a new instance with default colors from the theme. */
|
||||||
|
public TerminalColors() {
|
||||||
|
reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reset a particular indexed color with the default color from the color theme. */
|
||||||
|
public void reset(int index) {
|
||||||
|
mCurrentColors[index] = COLOR_SCHEME.mDefaultColors[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reset all indexed colors with the default color from the color theme. */
|
||||||
|
public void reset() {
|
||||||
|
System.arraycopy(COLOR_SCHEME.mDefaultColors, 0, mCurrentColors, 0, TextStyle.NUM_INDEXED_COLORS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse color according to http://manpages.ubuntu.com/manpages/intrepid/man3/XQueryColor.3.html
|
||||||
|
* <p/>
|
||||||
|
* Highest bit is set if successful, so return value is 0xFF${R}${G}${B}. Return 0 if failed.
|
||||||
|
*/
|
||||||
|
static int parse(String c) {
|
||||||
|
try {
|
||||||
|
int skipInitial, skipBetween;
|
||||||
|
if (c.charAt(0) == '#') {
|
||||||
|
// #RGB, #RRGGBB, #RRRGGGBBB or #RRRRGGGGBBBB. Most significant bits.
|
||||||
|
skipInitial = 1;
|
||||||
|
skipBetween = 0;
|
||||||
|
} else if (c.startsWith("rgb:")) {
|
||||||
|
// rgb:<red>/<green>/<blue> where <red>, <green>, <blue> := h | hh | hhh | hhhh. Scaled.
|
||||||
|
skipInitial = 4;
|
||||||
|
skipBetween = 1;
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int charsForColors = c.length() - skipInitial - 2 * skipBetween;
|
||||||
|
if (charsForColors % 3 != 0) return 0; // Unequal lengths.
|
||||||
|
int componentLength = charsForColors / 3;
|
||||||
|
double mult = 255 / (Math.pow(2, componentLength * 4) - 1);
|
||||||
|
|
||||||
|
int currentPosition = skipInitial;
|
||||||
|
String rString = c.substring(currentPosition, currentPosition + componentLength);
|
||||||
|
currentPosition += componentLength + skipBetween;
|
||||||
|
String gString = c.substring(currentPosition, currentPosition + componentLength);
|
||||||
|
currentPosition += componentLength + skipBetween;
|
||||||
|
String bString = c.substring(currentPosition, currentPosition + componentLength);
|
||||||
|
|
||||||
|
int r = (int) (Integer.parseInt(rString, 16) * mult);
|
||||||
|
int g = (int) (Integer.parseInt(gString, 16) * mult);
|
||||||
|
int b = (int) (Integer.parseInt(bString, 16) * mult);
|
||||||
|
return 0xFF << 24 | r << 16 | g << 8 | b;
|
||||||
|
} catch (NumberFormatException | IndexOutOfBoundsException e) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Try parse a color from a text parameter and into a specified index. */
|
||||||
|
public void tryParseColor(int intoIndex, String textParameter) {
|
||||||
|
int c = parse(textParameter);
|
||||||
|
if (c != 0) mCurrentColors[intoIndex] = c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the perceived brightness of the color based on its RGB components.
|
||||||
|
*
|
||||||
|
* https://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx
|
||||||
|
* http://alienryderflex.com/hsp.html
|
||||||
|
*
|
||||||
|
* @param color The color code int.
|
||||||
|
* @return Returns value between 0-255.
|
||||||
|
*/
|
||||||
|
public static int getPerceivedBrightnessOfColor(int color) {
|
||||||
|
return (int)
|
||||||
|
Math.floor(Math.sqrt(
|
||||||
|
Math.pow(Color.red(color), 2) * 0.241 +
|
||||||
|
Math.pow(Color.green(color), 2) * 0.691 +
|
||||||
|
Math.pow(Color.blue(color), 2) * 0.068
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
2605
android/app/src/main/java/com/termux/terminal/TerminalEmulator.java
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
/** A client which receives callbacks from events triggered by feeding input to a {@link TerminalEmulator}. */
|
||||||
|
public abstract class TerminalOutput {
|
||||||
|
|
||||||
|
/** Write a string using the UTF-8 encoding to the terminal client. */
|
||||||
|
public final void write(String data) {
|
||||||
|
if (data == null) return;
|
||||||
|
byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
|
||||||
|
write(bytes, 0, bytes.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Write bytes to the terminal client. */
|
||||||
|
public abstract void write(byte[] data, int offset, int count);
|
||||||
|
|
||||||
|
/** Notify the terminal client that the terminal title has changed. */
|
||||||
|
public abstract void titleChanged(String oldTitle, String newTitle);
|
||||||
|
|
||||||
|
/** Notify the terminal client that text should be copied to clipboard. */
|
||||||
|
public abstract void onCopyTextToClipboard(String text);
|
||||||
|
|
||||||
|
/** Notify the terminal client that text should be pasted from clipboard. */
|
||||||
|
public abstract void onPasteTextFromClipboard();
|
||||||
|
|
||||||
|
/** Notify the terminal client that a bell character (ASCII 7, bell, BEL, \a, ^G)) has been received. */
|
||||||
|
public abstract void onBell();
|
||||||
|
|
||||||
|
public abstract void onColorsChanged();
|
||||||
|
|
||||||
|
}
|
||||||
283
android/app/src/main/java/com/termux/terminal/TerminalRow.java
Normal file
@@ -0,0 +1,283 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A row in a terminal, composed of a fixed number of cells.
|
||||||
|
* <p>
|
||||||
|
* The text in the row is stored in a char[] array, {@link #mText}, for quick access during rendering.
|
||||||
|
*/
|
||||||
|
public final class TerminalRow {
|
||||||
|
|
||||||
|
private static final float SPARE_CAPACITY_FACTOR = 1.5f;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Max combining characters that can exist in a column, that are separate from the base character
|
||||||
|
* itself. Any additional combining characters will be ignored and not added to the column.
|
||||||
|
*
|
||||||
|
* There does not seem to be limit in unicode standard for max number of combination characters
|
||||||
|
* that can be combined but such characters are primarily under 10.
|
||||||
|
*
|
||||||
|
* "Section 3.6 Combination" of unicode standard contains combining characters info.
|
||||||
|
* - https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf
|
||||||
|
* - https://en.wikipedia.org/wiki/Combining_character#Unicode_ranges
|
||||||
|
* - https://stackoverflow.com/questions/71237212/what-is-the-maximum-number-of-unicode-combined-characters-that-may-be-needed-to
|
||||||
|
*
|
||||||
|
* UAX15-D3 Stream-Safe Text Format limits to max 30 combining characters.
|
||||||
|
* > The value of 30 is chosen to be significantly beyond what is required for any linguistic or technical usage.
|
||||||
|
* > While it would have been feasible to chose a smaller number, this value provides a very wide margin,
|
||||||
|
* > yet is well within the buffer size limits of practical implementations.
|
||||||
|
* - https://unicode.org/reports/tr15/#Stream_Safe_Text_Format
|
||||||
|
* - https://stackoverflow.com/a/11983435/14686958
|
||||||
|
*
|
||||||
|
* We choose the value 15 because it should be enough for terminal based applications and keep
|
||||||
|
* the memory usage low for a terminal row, won't affect performance or cause terminal to
|
||||||
|
* lag or hang, and will keep malicious applications from causing harm. The value can be
|
||||||
|
* increased if ever needed for legitimate applications.
|
||||||
|
*/
|
||||||
|
private static final int MAX_COMBINING_CHARACTERS_PER_COLUMN = 15;
|
||||||
|
|
||||||
|
/** The number of columns in this terminal row. */
|
||||||
|
private final int mColumns;
|
||||||
|
/** The text filling this terminal row. */
|
||||||
|
public char[] mText;
|
||||||
|
/** The number of java chars used in {@link #mText}. */
|
||||||
|
private short mSpaceUsed;
|
||||||
|
/** If this row has been line wrapped due to text output at the end of line. */
|
||||||
|
boolean mLineWrap;
|
||||||
|
/** The style bits of each cell in the row. See {@link TextStyle}. */
|
||||||
|
final long[] mStyle;
|
||||||
|
/** If this row might contain chars with width != 1, used for deactivating fast path */
|
||||||
|
boolean mHasNonOneWidthOrSurrogateChars;
|
||||||
|
|
||||||
|
/** Construct a blank row (containing only whitespace, ' ') with a specified style. */
|
||||||
|
public TerminalRow(int columns, long style) {
|
||||||
|
mColumns = columns;
|
||||||
|
mText = new char[(int) (SPARE_CAPACITY_FACTOR * columns)];
|
||||||
|
mStyle = new long[columns];
|
||||||
|
clear(style);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** NOTE: The sourceX2 is exclusive. */
|
||||||
|
public void copyInterval(TerminalRow line, int sourceX1, int sourceX2, int destinationX) {
|
||||||
|
mHasNonOneWidthOrSurrogateChars |= line.mHasNonOneWidthOrSurrogateChars;
|
||||||
|
final int x1 = line.findStartOfColumn(sourceX1);
|
||||||
|
final int x2 = line.findStartOfColumn(sourceX2);
|
||||||
|
boolean startingFromSecondHalfOfWideChar = (sourceX1 > 0 && line.wideDisplayCharacterStartingAt(sourceX1 - 1));
|
||||||
|
final char[] sourceChars = (this == line) ? Arrays.copyOf(line.mText, line.mText.length) : line.mText;
|
||||||
|
int latestNonCombiningWidth = 0;
|
||||||
|
for (int i = x1; i < x2; i++) {
|
||||||
|
char sourceChar = sourceChars[i];
|
||||||
|
int codePoint = Character.isHighSurrogate(sourceChar) ? Character.toCodePoint(sourceChar, sourceChars[++i]) : sourceChar;
|
||||||
|
if (startingFromSecondHalfOfWideChar) {
|
||||||
|
// Just treat copying second half of wide char as copying whitespace.
|
||||||
|
codePoint = ' ';
|
||||||
|
startingFromSecondHalfOfWideChar = false;
|
||||||
|
}
|
||||||
|
int w = WcWidth.width(codePoint);
|
||||||
|
if (w > 0) {
|
||||||
|
destinationX += latestNonCombiningWidth;
|
||||||
|
sourceX1 += latestNonCombiningWidth;
|
||||||
|
latestNonCombiningWidth = w;
|
||||||
|
}
|
||||||
|
setChar(destinationX, codePoint, line.getStyle(sourceX1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSpaceUsed() {
|
||||||
|
return mSpaceUsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Note that the column may end of second half of wide character. */
|
||||||
|
public int findStartOfColumn(int column) {
|
||||||
|
if (column == mColumns) return getSpaceUsed();
|
||||||
|
|
||||||
|
int currentColumn = 0;
|
||||||
|
int currentCharIndex = 0;
|
||||||
|
while (true) { // 0<2 1 < 2
|
||||||
|
int newCharIndex = currentCharIndex;
|
||||||
|
char c = mText[newCharIndex++]; // cci=1, cci=2
|
||||||
|
boolean isHigh = Character.isHighSurrogate(c);
|
||||||
|
int codePoint = isHigh ? Character.toCodePoint(c, mText[newCharIndex++]) : c;
|
||||||
|
int wcwidth = WcWidth.width(codePoint); // 1, 2
|
||||||
|
if (wcwidth > 0) {
|
||||||
|
currentColumn += wcwidth;
|
||||||
|
if (currentColumn == column) {
|
||||||
|
while (newCharIndex < mSpaceUsed) {
|
||||||
|
// Skip combining chars.
|
||||||
|
if (Character.isHighSurrogate(mText[newCharIndex])) {
|
||||||
|
if (WcWidth.width(Character.toCodePoint(mText[newCharIndex], mText[newCharIndex + 1])) <= 0) {
|
||||||
|
newCharIndex += 2;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if (WcWidth.width(mText[newCharIndex]) <= 0) {
|
||||||
|
newCharIndex++;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newCharIndex;
|
||||||
|
} else if (currentColumn > column) {
|
||||||
|
// Wide column going past end.
|
||||||
|
return currentCharIndex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
currentCharIndex = newCharIndex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean wideDisplayCharacterStartingAt(int column) {
|
||||||
|
for (int currentCharIndex = 0, currentColumn = 0; currentCharIndex < mSpaceUsed; ) {
|
||||||
|
char c = mText[currentCharIndex++];
|
||||||
|
int codePoint = Character.isHighSurrogate(c) ? Character.toCodePoint(c, mText[currentCharIndex++]) : c;
|
||||||
|
int wcwidth = WcWidth.width(codePoint);
|
||||||
|
if (wcwidth > 0) {
|
||||||
|
if (currentColumn == column && wcwidth == 2) return true;
|
||||||
|
currentColumn += wcwidth;
|
||||||
|
if (currentColumn > column) return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clear(long style) {
|
||||||
|
Arrays.fill(mText, ' ');
|
||||||
|
Arrays.fill(mStyle, style);
|
||||||
|
mSpaceUsed = (short) mColumns;
|
||||||
|
mHasNonOneWidthOrSurrogateChars = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://github.com/steven676/Android-Terminal-Emulator/commit/9a47042620bec87617f0b4f5d50568535668fe26
|
||||||
|
public void setChar(int columnToSet, int codePoint, long style) {
|
||||||
|
if (columnToSet < 0 || columnToSet >= mStyle.length)
|
||||||
|
throw new IllegalArgumentException("TerminalRow.setChar(): columnToSet=" + columnToSet + ", codePoint=" + codePoint + ", style=" + style);
|
||||||
|
|
||||||
|
mStyle[columnToSet] = style;
|
||||||
|
|
||||||
|
final int newCodePointDisplayWidth = WcWidth.width(codePoint);
|
||||||
|
|
||||||
|
// Fast path when we don't have any chars with width != 1
|
||||||
|
if (!mHasNonOneWidthOrSurrogateChars) {
|
||||||
|
if (codePoint >= Character.MIN_SUPPLEMENTARY_CODE_POINT || newCodePointDisplayWidth != 1) {
|
||||||
|
mHasNonOneWidthOrSurrogateChars = true;
|
||||||
|
} else {
|
||||||
|
mText[columnToSet] = (char) codePoint;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final boolean newIsCombining = newCodePointDisplayWidth <= 0;
|
||||||
|
|
||||||
|
boolean wasExtraColForWideChar = (columnToSet > 0) && wideDisplayCharacterStartingAt(columnToSet - 1);
|
||||||
|
|
||||||
|
if (newIsCombining) {
|
||||||
|
// When standing at second half of wide character and inserting combining:
|
||||||
|
if (wasExtraColForWideChar) columnToSet--;
|
||||||
|
} else {
|
||||||
|
// Check if we are overwriting the second half of a wide character starting at the previous column:
|
||||||
|
if (wasExtraColForWideChar) setChar(columnToSet - 1, ' ', style);
|
||||||
|
// Check if we are overwriting the first half of a wide character starting at the next column:
|
||||||
|
boolean overwritingWideCharInNextColumn = newCodePointDisplayWidth == 2 && wideDisplayCharacterStartingAt(columnToSet + 1);
|
||||||
|
if (overwritingWideCharInNextColumn) setChar(columnToSet + 1, ' ', style);
|
||||||
|
}
|
||||||
|
|
||||||
|
char[] text = mText;
|
||||||
|
final int oldStartOfColumnIndex = findStartOfColumn(columnToSet);
|
||||||
|
final int oldCodePointDisplayWidth = WcWidth.width(text, oldStartOfColumnIndex);
|
||||||
|
|
||||||
|
// Get the number of elements in the mText array this column uses now
|
||||||
|
int oldCharactersUsedForColumn;
|
||||||
|
if (columnToSet + oldCodePointDisplayWidth < mColumns) {
|
||||||
|
int oldEndOfColumnIndex = findStartOfColumn(columnToSet + oldCodePointDisplayWidth);
|
||||||
|
oldCharactersUsedForColumn = oldEndOfColumnIndex - oldStartOfColumnIndex;
|
||||||
|
} else {
|
||||||
|
// Last character.
|
||||||
|
oldCharactersUsedForColumn = mSpaceUsed - oldStartOfColumnIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If MAX_COMBINING_CHARACTERS_PER_COLUMN already exist in column, then ignore adding additional combining characters.
|
||||||
|
if (newIsCombining) {
|
||||||
|
int combiningCharsCount = WcWidth.zeroWidthCharsCount(mText, oldStartOfColumnIndex, oldStartOfColumnIndex + oldCharactersUsedForColumn);
|
||||||
|
if (combiningCharsCount >= MAX_COMBINING_CHARACTERS_PER_COLUMN)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find how many chars this column will need
|
||||||
|
int newCharactersUsedForColumn = Character.charCount(codePoint);
|
||||||
|
if (newIsCombining) {
|
||||||
|
// Combining characters are added to the contents of the column instead of overwriting them, so that they
|
||||||
|
// modify the existing contents.
|
||||||
|
// FIXME: Unassigned characters also get width=0.
|
||||||
|
newCharactersUsedForColumn += oldCharactersUsedForColumn;
|
||||||
|
}
|
||||||
|
|
||||||
|
int oldNextColumnIndex = oldStartOfColumnIndex + oldCharactersUsedForColumn;
|
||||||
|
int newNextColumnIndex = oldStartOfColumnIndex + newCharactersUsedForColumn;
|
||||||
|
|
||||||
|
final int javaCharDifference = newCharactersUsedForColumn - oldCharactersUsedForColumn;
|
||||||
|
if (javaCharDifference > 0) {
|
||||||
|
// Shift the rest of the line right.
|
||||||
|
int oldCharactersAfterColumn = mSpaceUsed - oldNextColumnIndex;
|
||||||
|
if (mSpaceUsed + javaCharDifference > text.length) {
|
||||||
|
// We need to grow the array
|
||||||
|
char[] newText = new char[text.length + mColumns];
|
||||||
|
System.arraycopy(text, 0, newText, 0, oldNextColumnIndex);
|
||||||
|
System.arraycopy(text, oldNextColumnIndex, newText, newNextColumnIndex, oldCharactersAfterColumn);
|
||||||
|
mText = text = newText;
|
||||||
|
} else {
|
||||||
|
System.arraycopy(text, oldNextColumnIndex, text, newNextColumnIndex, oldCharactersAfterColumn);
|
||||||
|
}
|
||||||
|
} else if (javaCharDifference < 0) {
|
||||||
|
// Shift the rest of the line left.
|
||||||
|
System.arraycopy(text, oldNextColumnIndex, text, newNextColumnIndex, mSpaceUsed - oldNextColumnIndex);
|
||||||
|
}
|
||||||
|
mSpaceUsed += javaCharDifference;
|
||||||
|
|
||||||
|
// Store char. A combining character is stored at the end of the existing contents so that it modifies them:
|
||||||
|
//noinspection ResultOfMethodCallIgnored - since we already now how many java chars is used.
|
||||||
|
Character.toChars(codePoint, text, oldStartOfColumnIndex + (newIsCombining ? oldCharactersUsedForColumn : 0));
|
||||||
|
|
||||||
|
if (oldCodePointDisplayWidth == 2 && newCodePointDisplayWidth == 1) {
|
||||||
|
// Replace second half of wide char with a space. Which mean that we actually add a ' ' java character.
|
||||||
|
if (mSpaceUsed + 1 > text.length) {
|
||||||
|
char[] newText = new char[text.length + mColumns];
|
||||||
|
System.arraycopy(text, 0, newText, 0, newNextColumnIndex);
|
||||||
|
System.arraycopy(text, newNextColumnIndex, newText, newNextColumnIndex + 1, mSpaceUsed - newNextColumnIndex);
|
||||||
|
mText = text = newText;
|
||||||
|
} else {
|
||||||
|
System.arraycopy(text, newNextColumnIndex, text, newNextColumnIndex + 1, mSpaceUsed - newNextColumnIndex);
|
||||||
|
}
|
||||||
|
text[newNextColumnIndex] = ' ';
|
||||||
|
|
||||||
|
++mSpaceUsed;
|
||||||
|
} else if (oldCodePointDisplayWidth == 1 && newCodePointDisplayWidth == 2) {
|
||||||
|
if (columnToSet == mColumns - 1) {
|
||||||
|
throw new IllegalArgumentException("Cannot put wide character in last column");
|
||||||
|
} else if (columnToSet == mColumns - 2) {
|
||||||
|
// Truncate the line to the second part of this wide char:
|
||||||
|
mSpaceUsed = (short) newNextColumnIndex;
|
||||||
|
} else {
|
||||||
|
// Overwrite the contents of the next column, which mean we actually remove java characters. Due to the
|
||||||
|
// check at the beginning of this method we know that we are not overwriting a wide char.
|
||||||
|
int newNextNextColumnIndex = newNextColumnIndex + (Character.isHighSurrogate(mText[newNextColumnIndex]) ? 2 : 1);
|
||||||
|
int nextLen = newNextNextColumnIndex - newNextColumnIndex;
|
||||||
|
|
||||||
|
// Shift the array leftwards.
|
||||||
|
System.arraycopy(text, newNextNextColumnIndex, text, newNextColumnIndex, mSpaceUsed - newNextNextColumnIndex);
|
||||||
|
mSpaceUsed -= nextLen;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isBlank() {
|
||||||
|
for (int charIndex = 0, charLen = getSpaceUsed(); charIndex < charLen; charIndex++)
|
||||||
|
if (mText[charIndex] != ' ') return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final long getStyle(int column) {
|
||||||
|
return mStyle[column];
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.os.Handler;
|
||||||
|
import android.os.Message;
|
||||||
|
import android.system.ErrnoException;
|
||||||
|
import android.system.Os;
|
||||||
|
import android.system.OsConstants;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileDescriptor;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A terminal session, consisting of a process coupled to a terminal interface.
|
||||||
|
* <p>
|
||||||
|
* The subprocess will be executed by the constructor, and when the size is made known by a call to
|
||||||
|
* {@link #updateSize(int, int, int, int)} terminal emulation will begin and threads will be spawned to handle the subprocess I/O.
|
||||||
|
* All terminal emulation and callback methods will be performed on the main thread.
|
||||||
|
* <p>
|
||||||
|
* The child process may be exited forcefully by using the {@link #finishIfRunning()} method.
|
||||||
|
* <p>
|
||||||
|
* NOTE: The terminal session may outlive the EmulatorView, so be careful with callbacks!
|
||||||
|
*/
|
||||||
|
public final class TerminalSession extends TerminalOutput {
|
||||||
|
|
||||||
|
private static final int MSG_NEW_INPUT = 1;
|
||||||
|
private static final int MSG_PROCESS_EXITED = 4;
|
||||||
|
|
||||||
|
public final String mHandle = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
TerminalEmulator mEmulator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A queue written to from a separate thread when the process outputs, and read by main thread to process by
|
||||||
|
* terminal emulator.
|
||||||
|
*/
|
||||||
|
final ByteQueue mProcessToTerminalIOQueue = new ByteQueue(4096);
|
||||||
|
/**
|
||||||
|
* A queue written to from the main thread due to user interaction, and read by another thread which forwards by
|
||||||
|
* writing to the {@link #mTerminalFileDescriptor}.
|
||||||
|
*/
|
||||||
|
final ByteQueue mTerminalToProcessIOQueue = new ByteQueue(4096);
|
||||||
|
/** Buffer to write translate code points into utf8 before writing to mTerminalToProcessIOQueue */
|
||||||
|
private final byte[] mUtf8InputBuffer = new byte[5];
|
||||||
|
|
||||||
|
/** Callback which gets notified when a session finishes or changes title. */
|
||||||
|
TerminalSessionClient mClient;
|
||||||
|
|
||||||
|
/** The pid of the shell process. 0 if not started and -1 if finished running. */
|
||||||
|
int mShellPid;
|
||||||
|
|
||||||
|
/** The exit status of the shell process. Only valid if ${@link #mShellPid} is -1. */
|
||||||
|
int mShellExitStatus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The file descriptor referencing the master half of a pseudo-terminal pair, resulting from calling
|
||||||
|
* {@link JNI#createSubprocess(String, String, String[], String[], int[], int, int, int, int)}.
|
||||||
|
*/
|
||||||
|
private int mTerminalFileDescriptor;
|
||||||
|
|
||||||
|
/** Set by the application for user identification of session, not by terminal. */
|
||||||
|
public String mSessionName;
|
||||||
|
|
||||||
|
final Handler mMainThreadHandler = new MainThreadHandler();
|
||||||
|
|
||||||
|
private final String mShellPath;
|
||||||
|
private final String mCwd;
|
||||||
|
private final String[] mArgs;
|
||||||
|
private final String[] mEnv;
|
||||||
|
private final Integer mTranscriptRows;
|
||||||
|
|
||||||
|
|
||||||
|
private static final String LOG_TAG = "TerminalSession";
|
||||||
|
|
||||||
|
public TerminalSession(String shellPath, String cwd, String[] args, String[] env, Integer transcriptRows, TerminalSessionClient client) {
|
||||||
|
this.mShellPath = shellPath;
|
||||||
|
this.mCwd = cwd;
|
||||||
|
this.mArgs = args;
|
||||||
|
this.mEnv = env;
|
||||||
|
this.mTranscriptRows = transcriptRows;
|
||||||
|
this.mClient = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param client The {@link TerminalSessionClient} interface implementation to allow
|
||||||
|
* for communication between {@link TerminalSession} and its client.
|
||||||
|
*/
|
||||||
|
public void updateTerminalSessionClient(TerminalSessionClient client) {
|
||||||
|
mClient = client;
|
||||||
|
|
||||||
|
if (mEmulator != null)
|
||||||
|
mEmulator.updateTerminalSessionClient(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Inform the attached pty of the new size and reflow or initialize the emulator. */
|
||||||
|
public void updateSize(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
|
||||||
|
if (mEmulator == null) {
|
||||||
|
initializeEmulator(columns, rows, cellWidthPixels, cellHeightPixels);
|
||||||
|
} else {
|
||||||
|
JNI.setPtyWindowSize(mTerminalFileDescriptor, rows, columns, cellWidthPixels, cellHeightPixels);
|
||||||
|
mEmulator.resize(columns, rows, cellWidthPixels, cellHeightPixels);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The terminal title as set through escape sequences or null if none set. */
|
||||||
|
public String getTitle() {
|
||||||
|
return (mEmulator == null) ? null : mEmulator.getTitle();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the terminal emulator's window size and start terminal emulation.
|
||||||
|
*
|
||||||
|
* @param columns The number of columns in the terminal window.
|
||||||
|
* @param rows The number of rows in the terminal window.
|
||||||
|
*/
|
||||||
|
public void initializeEmulator(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
|
||||||
|
mEmulator = new TerminalEmulator(this, columns, rows, cellWidthPixels, cellHeightPixels, mTranscriptRows, mClient);
|
||||||
|
|
||||||
|
int[] processId = new int[1];
|
||||||
|
mTerminalFileDescriptor = JNI.createSubprocess(mShellPath, mCwd, mArgs, mEnv, processId, rows, columns, cellWidthPixels, cellHeightPixels);
|
||||||
|
mShellPid = processId[0];
|
||||||
|
|
||||||
|
final FileDescriptor terminalFileDescriptorWrapped = wrapFileDescriptor(mTerminalFileDescriptor, mClient);
|
||||||
|
|
||||||
|
new Thread("TermSessionInputReader[pid=" + mShellPid + "]") {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
try (InputStream termIn = new FileInputStream(terminalFileDescriptorWrapped)) {
|
||||||
|
final byte[] buffer = new byte[4096];
|
||||||
|
while (true) {
|
||||||
|
int read = termIn.read(buffer);
|
||||||
|
if (read == -1) return;
|
||||||
|
if (!mProcessToTerminalIOQueue.write(buffer, 0, read)) return;
|
||||||
|
mMainThreadHandler.sendEmptyMessage(MSG_NEW_INPUT);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Ignore, just shutting down.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.start();
|
||||||
|
|
||||||
|
new Thread("TermSessionOutputWriter[pid=" + mShellPid + "]") {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
final byte[] buffer = new byte[4096];
|
||||||
|
try (FileOutputStream termOut = new FileOutputStream(terminalFileDescriptorWrapped)) {
|
||||||
|
while (true) {
|
||||||
|
int bytesToWrite = mTerminalToProcessIOQueue.read(buffer, true);
|
||||||
|
if (bytesToWrite == -1) return;
|
||||||
|
termOut.write(buffer, 0, bytesToWrite);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
// Ignore.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.start();
|
||||||
|
|
||||||
|
new Thread("TermSessionWaiter[pid=" + mShellPid + "]") {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
int processExitCode = JNI.waitFor(mShellPid);
|
||||||
|
mMainThreadHandler.sendMessage(mMainThreadHandler.obtainMessage(MSG_PROCESS_EXITED, processExitCode));
|
||||||
|
}
|
||||||
|
}.start();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Write data to the shell process. */
|
||||||
|
@Override
|
||||||
|
public void write(byte[] data, int offset, int count) {
|
||||||
|
if (mShellPid > 0) mTerminalToProcessIOQueue.write(data, offset, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Write the Unicode code point to the terminal encoded in UTF-8. */
|
||||||
|
public void writeCodePoint(boolean prependEscape, int codePoint) {
|
||||||
|
if (codePoint > 1114111 || (codePoint >= 0xD800 && codePoint <= 0xDFFF)) {
|
||||||
|
// 1114111 (= 2**16 + 1024**2 - 1) is the highest code point, [0xD800,0xDFFF] is the surrogate range.
|
||||||
|
throw new IllegalArgumentException("Invalid code point: " + codePoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
int bufferPosition = 0;
|
||||||
|
if (prependEscape) mUtf8InputBuffer[bufferPosition++] = 27;
|
||||||
|
|
||||||
|
if (codePoint <= /* 7 bits */0b1111111) {
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) codePoint;
|
||||||
|
} else if (codePoint <= /* 11 bits */0b11111111111) {
|
||||||
|
/* 110xxxxx leading byte with leading 5 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11000000 | (codePoint >> 6));
|
||||||
|
/* 10xxxxxx continuation byte with following 6 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
|
||||||
|
} else if (codePoint <= /* 16 bits */0b1111111111111111) {
|
||||||
|
/* 1110xxxx leading byte with leading 4 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11100000 | (codePoint >> 12));
|
||||||
|
/* 10xxxxxx continuation byte with following 6 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 6) & 0b111111));
|
||||||
|
/* 10xxxxxx continuation byte with following 6 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
|
||||||
|
} else { /* We have checked codePoint <= 1114111 above, so we have max 21 bits = 0b111111111111111111111 */
|
||||||
|
/* 11110xxx leading byte with leading 3 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11110000 | (codePoint >> 18));
|
||||||
|
/* 10xxxxxx continuation byte with following 6 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 12) & 0b111111));
|
||||||
|
/* 10xxxxxx continuation byte with following 6 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 6) & 0b111111));
|
||||||
|
/* 10xxxxxx continuation byte with following 6 bits */
|
||||||
|
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
|
||||||
|
}
|
||||||
|
write(mUtf8InputBuffer, 0, bufferPosition);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TerminalEmulator getEmulator() {
|
||||||
|
return mEmulator;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Notify the {@link #mClient} that the screen has changed. */
|
||||||
|
protected void notifyScreenUpdate() {
|
||||||
|
mClient.onTextChanged(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reset state for terminal emulator state. */
|
||||||
|
public void reset() {
|
||||||
|
mEmulator.reset();
|
||||||
|
notifyScreenUpdate();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Finish this terminal session by sending SIGKILL to the shell. */
|
||||||
|
public void finishIfRunning() {
|
||||||
|
if (isRunning()) {
|
||||||
|
try {
|
||||||
|
Os.kill(mShellPid, OsConstants.SIGKILL);
|
||||||
|
} catch (ErrnoException e) {
|
||||||
|
Logger.logWarn(mClient, LOG_TAG, "Failed sending SIGKILL: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cleanup resources when the process exits. */
|
||||||
|
void cleanupResources(int exitStatus) {
|
||||||
|
synchronized (this) {
|
||||||
|
mShellPid = -1;
|
||||||
|
mShellExitStatus = exitStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop the reader and writer threads, and close the I/O streams
|
||||||
|
mTerminalToProcessIOQueue.close();
|
||||||
|
mProcessToTerminalIOQueue.close();
|
||||||
|
JNI.close(mTerminalFileDescriptor);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void titleChanged(String oldTitle, String newTitle) {
|
||||||
|
mClient.onTitleChanged(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized boolean isRunning() {
|
||||||
|
return mShellPid != -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only valid if not {@link #isRunning()}. */
|
||||||
|
public synchronized int getExitStatus() {
|
||||||
|
return mShellExitStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onCopyTextToClipboard(String text) {
|
||||||
|
mClient.onCopyTextToClipboard(this, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onPasteTextFromClipboard() {
|
||||||
|
mClient.onPasteTextFromClipboard(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onBell() {
|
||||||
|
mClient.onBell(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onColorsChanged() {
|
||||||
|
mClient.onColorsChanged(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPid() {
|
||||||
|
return mShellPid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns the shell's working directory or null if it was unavailable. */
|
||||||
|
public String getCwd() {
|
||||||
|
if (mShellPid < 1) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final String cwdSymlink = String.format("/proc/%s/cwd/", mShellPid);
|
||||||
|
String outputPath = new File(cwdSymlink).getCanonicalPath();
|
||||||
|
String outputPathWithTrailingSlash = outputPath;
|
||||||
|
if (!outputPath.endsWith("/")) {
|
||||||
|
outputPathWithTrailingSlash += '/';
|
||||||
|
}
|
||||||
|
if (!cwdSymlink.equals(outputPathWithTrailingSlash)) {
|
||||||
|
return outputPath;
|
||||||
|
}
|
||||||
|
} catch (IOException | SecurityException e) {
|
||||||
|
Logger.logStackTraceWithMessage(mClient, LOG_TAG, "Error getting current directory", e);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FileDescriptor wrapFileDescriptor(int fileDescriptor, TerminalSessionClient client) {
|
||||||
|
FileDescriptor result = new FileDescriptor();
|
||||||
|
try {
|
||||||
|
Field descriptorField;
|
||||||
|
try {
|
||||||
|
descriptorField = FileDescriptor.class.getDeclaredField("descriptor");
|
||||||
|
} catch (NoSuchFieldException e) {
|
||||||
|
// For desktop java:
|
||||||
|
descriptorField = FileDescriptor.class.getDeclaredField("fd");
|
||||||
|
}
|
||||||
|
descriptorField.setAccessible(true);
|
||||||
|
descriptorField.set(result, fileDescriptor);
|
||||||
|
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
|
||||||
|
Logger.logStackTraceWithMessage(client, LOG_TAG, "Error accessing FileDescriptor#descriptor private field", e);
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("HandlerLeak")
|
||||||
|
class MainThreadHandler extends Handler {
|
||||||
|
|
||||||
|
final byte[] mReceiveBuffer = new byte[4 * 1024];
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handleMessage(Message msg) {
|
||||||
|
int bytesRead = mProcessToTerminalIOQueue.read(mReceiveBuffer, false);
|
||||||
|
if (bytesRead > 0) {
|
||||||
|
mEmulator.append(mReceiveBuffer, bytesRead);
|
||||||
|
notifyScreenUpdate();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.what == MSG_PROCESS_EXITED) {
|
||||||
|
int exitCode = (Integer) msg.obj;
|
||||||
|
cleanupResources(exitCode);
|
||||||
|
|
||||||
|
String exitDescription = "\r\n[Process completed";
|
||||||
|
if (exitCode > 0) {
|
||||||
|
// Non-zero process exit.
|
||||||
|
exitDescription += " (code " + exitCode + ")";
|
||||||
|
} else if (exitCode < 0) {
|
||||||
|
// Negated signal.
|
||||||
|
exitDescription += " (signal " + (-exitCode) + ")";
|
||||||
|
}
|
||||||
|
exitDescription += " - press Enter]";
|
||||||
|
|
||||||
|
byte[] bytesToWrite = exitDescription.getBytes(StandardCharsets.UTF_8);
|
||||||
|
mEmulator.append(bytesToWrite, bytesToWrite.length);
|
||||||
|
notifyScreenUpdate();
|
||||||
|
|
||||||
|
mClient.onSessionFinished(TerminalSession.this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The interface for communication between {@link TerminalSession} and its client. It is used to
|
||||||
|
* send callbacks to the client when {@link TerminalSession} changes or for sending other
|
||||||
|
* back data to the client like logs.
|
||||||
|
*/
|
||||||
|
public interface TerminalSessionClient {
|
||||||
|
|
||||||
|
void onTextChanged(TerminalSession changedSession);
|
||||||
|
|
||||||
|
void onTitleChanged(TerminalSession changedSession);
|
||||||
|
|
||||||
|
void onSessionFinished(TerminalSession finishedSession);
|
||||||
|
|
||||||
|
void onCopyTextToClipboard(TerminalSession session, String text);
|
||||||
|
|
||||||
|
void onPasteTextFromClipboard(TerminalSession session);
|
||||||
|
|
||||||
|
void onBell(TerminalSession session);
|
||||||
|
|
||||||
|
void onColorsChanged(TerminalSession session);
|
||||||
|
|
||||||
|
void onTerminalCursorStateChange(boolean state);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Integer getTerminalCursorStyle();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
void logError(String tag, String message);
|
||||||
|
|
||||||
|
void logWarn(String tag, String message);
|
||||||
|
|
||||||
|
void logInfo(String tag, String message);
|
||||||
|
|
||||||
|
void logDebug(String tag, String message);
|
||||||
|
|
||||||
|
void logVerbose(String tag, String message);
|
||||||
|
|
||||||
|
void logStackTraceWithMessage(String tag, String message, Exception e);
|
||||||
|
|
||||||
|
void logStackTrace(String tag, Exception e);
|
||||||
|
|
||||||
|
}
|
||||||
90
android/app/src/main/java/com/termux/terminal/TextStyle.java
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>
|
||||||
|
* Encodes effects, foreground and background colors into a 64 bit long, which are stored for each cell in a terminal
|
||||||
|
* row in {@link TerminalRow#mStyle}.
|
||||||
|
* </p>
|
||||||
|
* <p>
|
||||||
|
* The bit layout is:
|
||||||
|
* </p>
|
||||||
|
* - 16 flags (11 currently used).
|
||||||
|
* - 24 for foreground color (only 9 first bits if a color index).
|
||||||
|
* - 24 for background color (only 9 first bits if a color index).
|
||||||
|
*/
|
||||||
|
public final class TextStyle {
|
||||||
|
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_BOLD = 1;
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_ITALIC = 1 << 1;
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_UNDERLINE = 1 << 2;
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_BLINK = 1 << 3;
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_INVERSE = 1 << 4;
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_INVISIBLE = 1 << 5;
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_STRIKETHROUGH = 1 << 6;
|
||||||
|
/**
|
||||||
|
* The selective erase control functions (DECSED and DECSEL) can only erase characters defined as erasable.
|
||||||
|
* <p>
|
||||||
|
* This bit is set if DECSCA (Select Character Protection Attribute) has been used to define the characters that
|
||||||
|
* come after it as erasable from the screen.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_PROTECTED = 1 << 7;
|
||||||
|
/** Dim colors. Also known as faint or half intensity. */
|
||||||
|
public final static int CHARACTER_ATTRIBUTE_DIM = 1 << 8;
|
||||||
|
/** If true (24-bit) color is used for the cell for foreground. */
|
||||||
|
private final static int CHARACTER_ATTRIBUTE_TRUECOLOR_FOREGROUND = 1 << 9;
|
||||||
|
/** If true (24-bit) color is used for the cell for foreground. */
|
||||||
|
private final static int CHARACTER_ATTRIBUTE_TRUECOLOR_BACKGROUND= 1 << 10;
|
||||||
|
|
||||||
|
public final static int COLOR_INDEX_FOREGROUND = 256;
|
||||||
|
public final static int COLOR_INDEX_BACKGROUND = 257;
|
||||||
|
public final static int COLOR_INDEX_CURSOR = 258;
|
||||||
|
|
||||||
|
/** The 256 standard color entries and the three special (foreground, background and cursor) ones. */
|
||||||
|
public final static int NUM_INDEXED_COLORS = 259;
|
||||||
|
|
||||||
|
/** Normal foreground and background colors and no effects. */
|
||||||
|
final static long NORMAL = encode(COLOR_INDEX_FOREGROUND, COLOR_INDEX_BACKGROUND, 0);
|
||||||
|
|
||||||
|
static long encode(int foreColor, int backColor, int effect) {
|
||||||
|
long result = effect & 0b111111111;
|
||||||
|
if ((0xff000000 & foreColor) == 0xff000000) {
|
||||||
|
// 24-bit color.
|
||||||
|
result |= CHARACTER_ATTRIBUTE_TRUECOLOR_FOREGROUND | ((foreColor & 0x00ffffffL) << 40L);
|
||||||
|
} else {
|
||||||
|
// Indexed color.
|
||||||
|
result |= (foreColor & 0b111111111L) << 40;
|
||||||
|
}
|
||||||
|
if ((0xff000000 & backColor) == 0xff000000) {
|
||||||
|
// 24-bit color.
|
||||||
|
result |= CHARACTER_ATTRIBUTE_TRUECOLOR_BACKGROUND | ((backColor & 0x00ffffffL) << 16L);
|
||||||
|
} else {
|
||||||
|
// Indexed color.
|
||||||
|
result |= (backColor & 0b111111111L) << 16L;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int decodeForeColor(long style) {
|
||||||
|
if ((style & CHARACTER_ATTRIBUTE_TRUECOLOR_FOREGROUND) == 0) {
|
||||||
|
return (int) ((style >>> 40) & 0b111111111L);
|
||||||
|
} else {
|
||||||
|
return 0xff000000 | (int) ((style >>> 40) & 0x00ffffffL);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int decodeBackColor(long style) {
|
||||||
|
if ((style & CHARACTER_ATTRIBUTE_TRUECOLOR_BACKGROUND) == 0) {
|
||||||
|
return (int) ((style >>> 16) & 0b111111111L);
|
||||||
|
} else {
|
||||||
|
return 0xff000000 | (int) ((style >>> 16) & 0x00ffffffL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int decodeEffect(long style) {
|
||||||
|
return (int) (style & 0b11111111111);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
566
android/app/src/main/java/com/termux/terminal/WcWidth.java
Normal file
@@ -0,0 +1,566 @@
|
|||||||
|
package com.termux.terminal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implementation of wcwidth(3) for Unicode 15.
|
||||||
|
*
|
||||||
|
* Implementation from https://github.com/jquast/wcwidth but we return 0 for unprintable characters.
|
||||||
|
*
|
||||||
|
* IMPORTANT:
|
||||||
|
* Must be kept in sync with the following:
|
||||||
|
* https://github.com/termux/wcwidth
|
||||||
|
* https://github.com/termux/libandroid-support
|
||||||
|
* https://github.com/termux/termux-packages/tree/master/packages/libandroid-support
|
||||||
|
*/
|
||||||
|
public final class WcWidth {
|
||||||
|
|
||||||
|
// From https://github.com/jquast/wcwidth/blob/master/wcwidth/table_zero.py
|
||||||
|
// from https://github.com/jquast/wcwidth/pull/64
|
||||||
|
// at commit 1b9b6585b0080ea5cb88dc9815796505724793fe (2022-12-16):
|
||||||
|
private static final int[][] ZERO_WIDTH = {
|
||||||
|
{0x00300, 0x0036f}, // Combining Grave Accent ..Combining Latin Small Le
|
||||||
|
{0x00483, 0x00489}, // Combining Cyrillic Titlo..Combining Cyrillic Milli
|
||||||
|
{0x00591, 0x005bd}, // Hebrew Accent Etnahta ..Hebrew Point Meteg
|
||||||
|
{0x005bf, 0x005bf}, // Hebrew Point Rafe ..Hebrew Point Rafe
|
||||||
|
{0x005c1, 0x005c2}, // Hebrew Point Shin Dot ..Hebrew Point Sin Dot
|
||||||
|
{0x005c4, 0x005c5}, // Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot
|
||||||
|
{0x005c7, 0x005c7}, // Hebrew Point Qamats Qata..Hebrew Point Qamats Qata
|
||||||
|
{0x00610, 0x0061a}, // Arabic Sign Sallallahou ..Arabic Small Kasra
|
||||||
|
{0x0064b, 0x0065f}, // Arabic Fathatan ..Arabic Wavy Hamza Below
|
||||||
|
{0x00670, 0x00670}, // Arabic Letter Superscrip..Arabic Letter Superscrip
|
||||||
|
{0x006d6, 0x006dc}, // Arabic Small High Ligatu..Arabic Small High Seen
|
||||||
|
{0x006df, 0x006e4}, // Arabic Small High Rounde..Arabic Small High Madda
|
||||||
|
{0x006e7, 0x006e8}, // Arabic Small High Yeh ..Arabic Small High Noon
|
||||||
|
{0x006ea, 0x006ed}, // Arabic Empty Centre Low ..Arabic Small Low Meem
|
||||||
|
{0x00711, 0x00711}, // Syriac Letter Superscrip..Syriac Letter Superscrip
|
||||||
|
{0x00730, 0x0074a}, // Syriac Pthaha Above ..Syriac Barrekh
|
||||||
|
{0x007a6, 0x007b0}, // Thaana Abafili ..Thaana Sukun
|
||||||
|
{0x007eb, 0x007f3}, // Nko Combining Short High..Nko Combining Double Dot
|
||||||
|
{0x007fd, 0x007fd}, // Nko Dantayalan ..Nko Dantayalan
|
||||||
|
{0x00816, 0x00819}, // Samaritan Mark In ..Samaritan Mark Dagesh
|
||||||
|
{0x0081b, 0x00823}, // Samaritan Mark Epentheti..Samaritan Vowel Sign A
|
||||||
|
{0x00825, 0x00827}, // Samaritan Vowel Sign Sho..Samaritan Vowel Sign U
|
||||||
|
{0x00829, 0x0082d}, // Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa
|
||||||
|
{0x00859, 0x0085b}, // Mandaic Affrication Mark..Mandaic Gemination Mark
|
||||||
|
{0x00898, 0x0089f}, // Arabic Small High Word A..Arabic Half Madda Over M
|
||||||
|
{0x008ca, 0x008e1}, // Arabic Small High Farsi ..Arabic Small High Sign S
|
||||||
|
{0x008e3, 0x00902}, // Arabic Turned Damma Belo..Devanagari Sign Anusvara
|
||||||
|
{0x0093a, 0x0093a}, // Devanagari Vowel Sign Oe..Devanagari Vowel Sign Oe
|
||||||
|
{0x0093c, 0x0093c}, // Devanagari Sign Nukta ..Devanagari Sign Nukta
|
||||||
|
{0x00941, 0x00948}, // Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai
|
||||||
|
{0x0094d, 0x0094d}, // Devanagari Sign Virama ..Devanagari Sign Virama
|
||||||
|
{0x00951, 0x00957}, // Devanagari Stress Sign U..Devanagari Vowel Sign Uu
|
||||||
|
{0x00962, 0x00963}, // Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo
|
||||||
|
{0x00981, 0x00981}, // Bengali Sign Candrabindu..Bengali Sign Candrabindu
|
||||||
|
{0x009bc, 0x009bc}, // Bengali Sign Nukta ..Bengali Sign Nukta
|
||||||
|
{0x009c1, 0x009c4}, // Bengali Vowel Sign U ..Bengali Vowel Sign Vocal
|
||||||
|
{0x009cd, 0x009cd}, // Bengali Sign Virama ..Bengali Sign Virama
|
||||||
|
{0x009e2, 0x009e3}, // Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal
|
||||||
|
{0x009fe, 0x009fe}, // Bengali Sandhi Mark ..Bengali Sandhi Mark
|
||||||
|
{0x00a01, 0x00a02}, // Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi
|
||||||
|
{0x00a3c, 0x00a3c}, // Gurmukhi Sign Nukta ..Gurmukhi Sign Nukta
|
||||||
|
{0x00a41, 0x00a42}, // Gurmukhi Vowel Sign U ..Gurmukhi Vowel Sign Uu
|
||||||
|
{0x00a47, 0x00a48}, // Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai
|
||||||
|
{0x00a4b, 0x00a4d}, // Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama
|
||||||
|
{0x00a51, 0x00a51}, // Gurmukhi Sign Udaat ..Gurmukhi Sign Udaat
|
||||||
|
{0x00a70, 0x00a71}, // Gurmukhi Tippi ..Gurmukhi Addak
|
||||||
|
{0x00a75, 0x00a75}, // Gurmukhi Sign Yakash ..Gurmukhi Sign Yakash
|
||||||
|
{0x00a81, 0x00a82}, // Gujarati Sign Candrabind..Gujarati Sign Anusvara
|
||||||
|
{0x00abc, 0x00abc}, // Gujarati Sign Nukta ..Gujarati Sign Nukta
|
||||||
|
{0x00ac1, 0x00ac5}, // Gujarati Vowel Sign U ..Gujarati Vowel Sign Cand
|
||||||
|
{0x00ac7, 0x00ac8}, // Gujarati Vowel Sign E ..Gujarati Vowel Sign Ai
|
||||||
|
{0x00acd, 0x00acd}, // Gujarati Sign Virama ..Gujarati Sign Virama
|
||||||
|
{0x00ae2, 0x00ae3}, // Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca
|
||||||
|
{0x00afa, 0x00aff}, // Gujarati Sign Sukun ..Gujarati Sign Two-circle
|
||||||
|
{0x00b01, 0x00b01}, // Oriya Sign Candrabindu ..Oriya Sign Candrabindu
|
||||||
|
{0x00b3c, 0x00b3c}, // Oriya Sign Nukta ..Oriya Sign Nukta
|
||||||
|
{0x00b3f, 0x00b3f}, // Oriya Vowel Sign I ..Oriya Vowel Sign I
|
||||||
|
{0x00b41, 0x00b44}, // Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic
|
||||||
|
{0x00b4d, 0x00b4d}, // Oriya Sign Virama ..Oriya Sign Virama
|
||||||
|
{0x00b55, 0x00b56}, // Oriya Sign Overline ..Oriya Ai Length Mark
|
||||||
|
{0x00b62, 0x00b63}, // Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic
|
||||||
|
{0x00b82, 0x00b82}, // Tamil Sign Anusvara ..Tamil Sign Anusvara
|
||||||
|
{0x00bc0, 0x00bc0}, // Tamil Vowel Sign Ii ..Tamil Vowel Sign Ii
|
||||||
|
{0x00bcd, 0x00bcd}, // Tamil Sign Virama ..Tamil Sign Virama
|
||||||
|
{0x00c00, 0x00c00}, // Telugu Sign Combining Ca..Telugu Sign Combining Ca
|
||||||
|
{0x00c04, 0x00c04}, // Telugu Sign Combining An..Telugu Sign Combining An
|
||||||
|
{0x00c3c, 0x00c3c}, // Telugu Sign Nukta ..Telugu Sign Nukta
|
||||||
|
{0x00c3e, 0x00c40}, // Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii
|
||||||
|
{0x00c46, 0x00c48}, // Telugu Vowel Sign E ..Telugu Vowel Sign Ai
|
||||||
|
{0x00c4a, 0x00c4d}, // Telugu Vowel Sign O ..Telugu Sign Virama
|
||||||
|
{0x00c55, 0x00c56}, // Telugu Length Mark ..Telugu Ai Length Mark
|
||||||
|
{0x00c62, 0x00c63}, // Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali
|
||||||
|
{0x00c81, 0x00c81}, // Kannada Sign Candrabindu..Kannada Sign Candrabindu
|
||||||
|
{0x00cbc, 0x00cbc}, // Kannada Sign Nukta ..Kannada Sign Nukta
|
||||||
|
{0x00cbf, 0x00cbf}, // Kannada Vowel Sign I ..Kannada Vowel Sign I
|
||||||
|
{0x00cc6, 0x00cc6}, // Kannada Vowel Sign E ..Kannada Vowel Sign E
|
||||||
|
{0x00ccc, 0x00ccd}, // Kannada Vowel Sign Au ..Kannada Sign Virama
|
||||||
|
{0x00ce2, 0x00ce3}, // Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal
|
||||||
|
{0x00d00, 0x00d01}, // Malayalam Sign Combining..Malayalam Sign Candrabin
|
||||||
|
{0x00d3b, 0x00d3c}, // Malayalam Sign Vertical ..Malayalam Sign Circular
|
||||||
|
{0x00d41, 0x00d44}, // Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc
|
||||||
|
{0x00d4d, 0x00d4d}, // Malayalam Sign Virama ..Malayalam Sign Virama
|
||||||
|
{0x00d62, 0x00d63}, // Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc
|
||||||
|
{0x00d81, 0x00d81}, // Sinhala Sign Candrabindu..Sinhala Sign Candrabindu
|
||||||
|
{0x00dca, 0x00dca}, // Sinhala Sign Al-lakuna ..Sinhala Sign Al-lakuna
|
||||||
|
{0x00dd2, 0x00dd4}, // Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti
|
||||||
|
{0x00dd6, 0x00dd6}, // Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga
|
||||||
|
{0x00e31, 0x00e31}, // Thai Character Mai Han-a..Thai Character Mai Han-a
|
||||||
|
{0x00e34, 0x00e3a}, // Thai Character Sara I ..Thai Character Phinthu
|
||||||
|
{0x00e47, 0x00e4e}, // Thai Character Maitaikhu..Thai Character Yamakkan
|
||||||
|
{0x00eb1, 0x00eb1}, // Lao Vowel Sign Mai Kan ..Lao Vowel Sign Mai Kan
|
||||||
|
{0x00eb4, 0x00ebc}, // Lao Vowel Sign I ..Lao Semivowel Sign Lo
|
||||||
|
{0x00ec8, 0x00ece}, // Lao Tone Mai Ek ..(nil)
|
||||||
|
{0x00f18, 0x00f19}, // Tibetan Astrological Sig..Tibetan Astrological Sig
|
||||||
|
{0x00f35, 0x00f35}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung
|
||||||
|
{0x00f37, 0x00f37}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung
|
||||||
|
{0x00f39, 0x00f39}, // Tibetan Mark Tsa -phru ..Tibetan Mark Tsa -phru
|
||||||
|
{0x00f71, 0x00f7e}, // Tibetan Vowel Sign Aa ..Tibetan Sign Rjes Su Nga
|
||||||
|
{0x00f80, 0x00f84}, // Tibetan Vowel Sign Rever..Tibetan Mark Halanta
|
||||||
|
{0x00f86, 0x00f87}, // Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags
|
||||||
|
{0x00f8d, 0x00f97}, // Tibetan Subjoined Sign L..Tibetan Subjoined Letter
|
||||||
|
{0x00f99, 0x00fbc}, // Tibetan Subjoined Letter..Tibetan Subjoined Letter
|
||||||
|
{0x00fc6, 0x00fc6}, // Tibetan Symbol Padma Gda..Tibetan Symbol Padma Gda
|
||||||
|
{0x0102d, 0x01030}, // Myanmar Vowel Sign I ..Myanmar Vowel Sign Uu
|
||||||
|
{0x01032, 0x01037}, // Myanmar Vowel Sign Ai ..Myanmar Sign Dot Below
|
||||||
|
{0x01039, 0x0103a}, // Myanmar Sign Virama ..Myanmar Sign Asat
|
||||||
|
{0x0103d, 0x0103e}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M
|
||||||
|
{0x01058, 0x01059}, // Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal
|
||||||
|
{0x0105e, 0x01060}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M
|
||||||
|
{0x01071, 0x01074}, // Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah
|
||||||
|
{0x01082, 0x01082}, // Myanmar Consonant Sign S..Myanmar Consonant Sign S
|
||||||
|
{0x01085, 0x01086}, // Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan
|
||||||
|
{0x0108d, 0x0108d}, // Myanmar Sign Shan Counci..Myanmar Sign Shan Counci
|
||||||
|
{0x0109d, 0x0109d}, // Myanmar Vowel Sign Aiton..Myanmar Vowel Sign Aiton
|
||||||
|
{0x0135d, 0x0135f}, // Ethiopic Combining Gemin..Ethiopic Combining Gemin
|
||||||
|
{0x01712, 0x01714}, // Tagalog Vowel Sign I ..Tagalog Sign Virama
|
||||||
|
{0x01732, 0x01733}, // Hanunoo Vowel Sign I ..Hanunoo Vowel Sign U
|
||||||
|
{0x01752, 0x01753}, // Buhid Vowel Sign I ..Buhid Vowel Sign U
|
||||||
|
{0x01772, 0x01773}, // Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U
|
||||||
|
{0x017b4, 0x017b5}, // Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa
|
||||||
|
{0x017b7, 0x017bd}, // Khmer Vowel Sign I ..Khmer Vowel Sign Ua
|
||||||
|
{0x017c6, 0x017c6}, // Khmer Sign Nikahit ..Khmer Sign Nikahit
|
||||||
|
{0x017c9, 0x017d3}, // Khmer Sign Muusikatoan ..Khmer Sign Bathamasat
|
||||||
|
{0x017dd, 0x017dd}, // Khmer Sign Atthacan ..Khmer Sign Atthacan
|
||||||
|
{0x0180b, 0x0180d}, // Mongolian Free Variation..Mongolian Free Variation
|
||||||
|
{0x0180f, 0x0180f}, // Mongolian Free Variation..Mongolian Free Variation
|
||||||
|
{0x01885, 0x01886}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal
|
||||||
|
{0x018a9, 0x018a9}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal
|
||||||
|
{0x01920, 0x01922}, // Limbu Vowel Sign A ..Limbu Vowel Sign U
|
||||||
|
{0x01927, 0x01928}, // Limbu Vowel Sign E ..Limbu Vowel Sign O
|
||||||
|
{0x01932, 0x01932}, // Limbu Small Letter Anusv..Limbu Small Letter Anusv
|
||||||
|
{0x01939, 0x0193b}, // Limbu Sign Mukphreng ..Limbu Sign Sa-i
|
||||||
|
{0x01a17, 0x01a18}, // Buginese Vowel Sign I ..Buginese Vowel Sign U
|
||||||
|
{0x01a1b, 0x01a1b}, // Buginese Vowel Sign Ae ..Buginese Vowel Sign Ae
|
||||||
|
{0x01a56, 0x01a56}, // Tai Tham Consonant Sign ..Tai Tham Consonant Sign
|
||||||
|
{0x01a58, 0x01a5e}, // Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign
|
||||||
|
{0x01a60, 0x01a60}, // Tai Tham Sign Sakot ..Tai Tham Sign Sakot
|
||||||
|
{0x01a62, 0x01a62}, // Tai Tham Vowel Sign Mai ..Tai Tham Vowel Sign Mai
|
||||||
|
{0x01a65, 0x01a6c}, // Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B
|
||||||
|
{0x01a73, 0x01a7c}, // Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue
|
||||||
|
{0x01a7f, 0x01a7f}, // Tai Tham Combining Crypt..Tai Tham Combining Crypt
|
||||||
|
{0x01ab0, 0x01ace}, // Combining Doubled Circum..Combining Latin Small Le
|
||||||
|
{0x01b00, 0x01b03}, // Balinese Sign Ulu Ricem ..Balinese Sign Surang
|
||||||
|
{0x01b34, 0x01b34}, // Balinese Sign Rerekan ..Balinese Sign Rerekan
|
||||||
|
{0x01b36, 0x01b3a}, // Balinese Vowel Sign Ulu ..Balinese Vowel Sign Ra R
|
||||||
|
{0x01b3c, 0x01b3c}, // Balinese Vowel Sign La L..Balinese Vowel Sign La L
|
||||||
|
{0x01b42, 0x01b42}, // Balinese Vowel Sign Pepe..Balinese Vowel Sign Pepe
|
||||||
|
{0x01b6b, 0x01b73}, // Balinese Musical Symbol ..Balinese Musical Symbol
|
||||||
|
{0x01b80, 0x01b81}, // Sundanese Sign Panyecek ..Sundanese Sign Panglayar
|
||||||
|
{0x01ba2, 0x01ba5}, // Sundanese Consonant Sign..Sundanese Vowel Sign Pan
|
||||||
|
{0x01ba8, 0x01ba9}, // Sundanese Vowel Sign Pam..Sundanese Vowel Sign Pan
|
||||||
|
{0x01bab, 0x01bad}, // Sundanese Sign Virama ..Sundanese Consonant Sign
|
||||||
|
{0x01be6, 0x01be6}, // Batak Sign Tompi ..Batak Sign Tompi
|
||||||
|
{0x01be8, 0x01be9}, // Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee
|
||||||
|
{0x01bed, 0x01bed}, // Batak Vowel Sign Karo O ..Batak Vowel Sign Karo O
|
||||||
|
{0x01bef, 0x01bf1}, // Batak Vowel Sign U For S..Batak Consonant Sign H
|
||||||
|
{0x01c2c, 0x01c33}, // Lepcha Vowel Sign E ..Lepcha Consonant Sign T
|
||||||
|
{0x01c36, 0x01c37}, // Lepcha Sign Ran ..Lepcha Sign Nukta
|
||||||
|
{0x01cd0, 0x01cd2}, // Vedic Tone Karshana ..Vedic Tone Prenkha
|
||||||
|
{0x01cd4, 0x01ce0}, // Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash
|
||||||
|
{0x01ce2, 0x01ce8}, // Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda
|
||||||
|
{0x01ced, 0x01ced}, // Vedic Sign Tiryak ..Vedic Sign Tiryak
|
||||||
|
{0x01cf4, 0x01cf4}, // Vedic Tone Candra Above ..Vedic Tone Candra Above
|
||||||
|
{0x01cf8, 0x01cf9}, // Vedic Tone Ring Above ..Vedic Tone Double Ring A
|
||||||
|
{0x01dc0, 0x01dff}, // Combining Dotted Grave A..Combining Right Arrowhea
|
||||||
|
{0x020d0, 0x020f0}, // Combining Left Harpoon A..Combining Asterisk Above
|
||||||
|
{0x02cef, 0x02cf1}, // Coptic Combining Ni Abov..Coptic Combining Spiritu
|
||||||
|
{0x02d7f, 0x02d7f}, // Tifinagh Consonant Joine..Tifinagh Consonant Joine
|
||||||
|
{0x02de0, 0x02dff}, // Combining Cyrillic Lette..Combining Cyrillic Lette
|
||||||
|
{0x0302a, 0x0302d}, // Ideographic Level Tone M..Ideographic Entering Ton
|
||||||
|
{0x03099, 0x0309a}, // Combining Katakana-hirag..Combining Katakana-hirag
|
||||||
|
{0x0a66f, 0x0a672}, // Combining Cyrillic Vzmet..Combining Cyrillic Thous
|
||||||
|
{0x0a674, 0x0a67d}, // Combining Cyrillic Lette..Combining Cyrillic Payer
|
||||||
|
{0x0a69e, 0x0a69f}, // Combining Cyrillic Lette..Combining Cyrillic Lette
|
||||||
|
{0x0a6f0, 0x0a6f1}, // Bamum Combining Mark Koq..Bamum Combining Mark Tuk
|
||||||
|
{0x0a802, 0x0a802}, // Syloti Nagri Sign Dvisva..Syloti Nagri Sign Dvisva
|
||||||
|
{0x0a806, 0x0a806}, // Syloti Nagri Sign Hasant..Syloti Nagri Sign Hasant
|
||||||
|
{0x0a80b, 0x0a80b}, // Syloti Nagri Sign Anusva..Syloti Nagri Sign Anusva
|
||||||
|
{0x0a825, 0x0a826}, // Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign
|
||||||
|
{0x0a82c, 0x0a82c}, // Syloti Nagri Sign Altern..Syloti Nagri Sign Altern
|
||||||
|
{0x0a8c4, 0x0a8c5}, // Saurashtra Sign Virama ..Saurashtra Sign Candrabi
|
||||||
|
{0x0a8e0, 0x0a8f1}, // Combining Devanagari Dig..Combining Devanagari Sig
|
||||||
|
{0x0a8ff, 0x0a8ff}, // Devanagari Vowel Sign Ay..Devanagari Vowel Sign Ay
|
||||||
|
{0x0a926, 0x0a92d}, // Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop
|
||||||
|
{0x0a947, 0x0a951}, // Rejang Vowel Sign I ..Rejang Consonant Sign R
|
||||||
|
{0x0a980, 0x0a982}, // Javanese Sign Panyangga ..Javanese Sign Layar
|
||||||
|
{0x0a9b3, 0x0a9b3}, // Javanese Sign Cecak Telu..Javanese Sign Cecak Telu
|
||||||
|
{0x0a9b6, 0x0a9b9}, // Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku
|
||||||
|
{0x0a9bc, 0x0a9bd}, // Javanese Vowel Sign Pepe..Javanese Consonant Sign
|
||||||
|
{0x0a9e5, 0x0a9e5}, // Myanmar Sign Shan Saw ..Myanmar Sign Shan Saw
|
||||||
|
{0x0aa29, 0x0aa2e}, // Cham Vowel Sign Aa ..Cham Vowel Sign Oe
|
||||||
|
{0x0aa31, 0x0aa32}, // Cham Vowel Sign Au ..Cham Vowel Sign Ue
|
||||||
|
{0x0aa35, 0x0aa36}, // Cham Consonant Sign La ..Cham Consonant Sign Wa
|
||||||
|
{0x0aa43, 0x0aa43}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina
|
||||||
|
{0x0aa4c, 0x0aa4c}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina
|
||||||
|
{0x0aa7c, 0x0aa7c}, // Myanmar Sign Tai Laing T..Myanmar Sign Tai Laing T
|
||||||
|
{0x0aab0, 0x0aab0}, // Tai Viet Mai Kang ..Tai Viet Mai Kang
|
||||||
|
{0x0aab2, 0x0aab4}, // Tai Viet Vowel I ..Tai Viet Vowel U
|
||||||
|
{0x0aab7, 0x0aab8}, // Tai Viet Mai Khit ..Tai Viet Vowel Ia
|
||||||
|
{0x0aabe, 0x0aabf}, // Tai Viet Vowel Am ..Tai Viet Tone Mai Ek
|
||||||
|
{0x0aac1, 0x0aac1}, // Tai Viet Tone Mai Tho ..Tai Viet Tone Mai Tho
|
||||||
|
{0x0aaec, 0x0aaed}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
|
||||||
|
{0x0aaf6, 0x0aaf6}, // Meetei Mayek Virama ..Meetei Mayek Virama
|
||||||
|
{0x0abe5, 0x0abe5}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
|
||||||
|
{0x0abe8, 0x0abe8}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
|
||||||
|
{0x0abed, 0x0abed}, // Meetei Mayek Apun Iyek ..Meetei Mayek Apun Iyek
|
||||||
|
{0x0fb1e, 0x0fb1e}, // Hebrew Point Judeo-spani..Hebrew Point Judeo-spani
|
||||||
|
{0x0fe00, 0x0fe0f}, // Variation Selector-1 ..Variation Selector-16
|
||||||
|
{0x0fe20, 0x0fe2f}, // Combining Ligature Left ..Combining Cyrillic Titlo
|
||||||
|
{0x101fd, 0x101fd}, // Phaistos Disc Sign Combi..Phaistos Disc Sign Combi
|
||||||
|
{0x102e0, 0x102e0}, // Coptic Epact Thousands M..Coptic Epact Thousands M
|
||||||
|
{0x10376, 0x1037a}, // Combining Old Permic Let..Combining Old Permic Let
|
||||||
|
{0x10a01, 0x10a03}, // Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo
|
||||||
|
{0x10a05, 0x10a06}, // Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O
|
||||||
|
{0x10a0c, 0x10a0f}, // Kharoshthi Vowel Length ..Kharoshthi Sign Visarga
|
||||||
|
{0x10a38, 0x10a3a}, // Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo
|
||||||
|
{0x10a3f, 0x10a3f}, // Kharoshthi Virama ..Kharoshthi Virama
|
||||||
|
{0x10ae5, 0x10ae6}, // Manichaean Abbreviation ..Manichaean Abbreviation
|
||||||
|
{0x10d24, 0x10d27}, // Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas
|
||||||
|
{0x10eab, 0x10eac}, // Yezidi Combining Hamza M..Yezidi Combining Madda M
|
||||||
|
{0x10efd, 0x10eff}, // (nil) ..(nil)
|
||||||
|
{0x10f46, 0x10f50}, // Sogdian Combining Dot Be..Sogdian Combining Stroke
|
||||||
|
{0x10f82, 0x10f85}, // Old Uyghur Combining Dot..Old Uyghur Combining Two
|
||||||
|
{0x11001, 0x11001}, // Brahmi Sign Anusvara ..Brahmi Sign Anusvara
|
||||||
|
{0x11038, 0x11046}, // Brahmi Vowel Sign Aa ..Brahmi Virama
|
||||||
|
{0x11070, 0x11070}, // Brahmi Sign Old Tamil Vi..Brahmi Sign Old Tamil Vi
|
||||||
|
{0x11073, 0x11074}, // Brahmi Vowel Sign Old Ta..Brahmi Vowel Sign Old Ta
|
||||||
|
{0x1107f, 0x11081}, // Brahmi Number Joiner ..Kaithi Sign Anusvara
|
||||||
|
{0x110b3, 0x110b6}, // Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai
|
||||||
|
{0x110b9, 0x110ba}, // Kaithi Sign Virama ..Kaithi Sign Nukta
|
||||||
|
{0x110c2, 0x110c2}, // Kaithi Vowel Sign Vocali..Kaithi Vowel Sign Vocali
|
||||||
|
{0x11100, 0x11102}, // Chakma Sign Candrabindu ..Chakma Sign Visarga
|
||||||
|
{0x11127, 0x1112b}, // Chakma Vowel Sign A ..Chakma Vowel Sign Uu
|
||||||
|
{0x1112d, 0x11134}, // Chakma Vowel Sign Ai ..Chakma Maayyaa
|
||||||
|
{0x11173, 0x11173}, // Mahajani Sign Nukta ..Mahajani Sign Nukta
|
||||||
|
{0x11180, 0x11181}, // Sharada Sign Candrabindu..Sharada Sign Anusvara
|
||||||
|
{0x111b6, 0x111be}, // Sharada Vowel Sign U ..Sharada Vowel Sign O
|
||||||
|
{0x111c9, 0x111cc}, // Sharada Sandhi Mark ..Sharada Extra Short Vowe
|
||||||
|
{0x111cf, 0x111cf}, // Sharada Sign Inverted Ca..Sharada Sign Inverted Ca
|
||||||
|
{0x1122f, 0x11231}, // Khojki Vowel Sign U ..Khojki Vowel Sign Ai
|
||||||
|
{0x11234, 0x11234}, // Khojki Sign Anusvara ..Khojki Sign Anusvara
|
||||||
|
{0x11236, 0x11237}, // Khojki Sign Nukta ..Khojki Sign Shadda
|
||||||
|
{0x1123e, 0x1123e}, // Khojki Sign Sukun ..Khojki Sign Sukun
|
||||||
|
{0x11241, 0x11241}, // (nil) ..(nil)
|
||||||
|
{0x112df, 0x112df}, // Khudawadi Sign Anusvara ..Khudawadi Sign Anusvara
|
||||||
|
{0x112e3, 0x112ea}, // Khudawadi Vowel Sign U ..Khudawadi Sign Virama
|
||||||
|
{0x11300, 0x11301}, // Grantha Sign Combining A..Grantha Sign Candrabindu
|
||||||
|
{0x1133b, 0x1133c}, // Combining Bindu Below ..Grantha Sign Nukta
|
||||||
|
{0x11340, 0x11340}, // Grantha Vowel Sign Ii ..Grantha Vowel Sign Ii
|
||||||
|
{0x11366, 0x1136c}, // Combining Grantha Digit ..Combining Grantha Digit
|
||||||
|
{0x11370, 0x11374}, // Combining Grantha Letter..Combining Grantha Letter
|
||||||
|
{0x11438, 0x1143f}, // Newa Vowel Sign U ..Newa Vowel Sign Ai
|
||||||
|
{0x11442, 0x11444}, // Newa Sign Virama ..Newa Sign Anusvara
|
||||||
|
{0x11446, 0x11446}, // Newa Sign Nukta ..Newa Sign Nukta
|
||||||
|
{0x1145e, 0x1145e}, // Newa Sandhi Mark ..Newa Sandhi Mark
|
||||||
|
{0x114b3, 0x114b8}, // Tirhuta Vowel Sign U ..Tirhuta Vowel Sign Vocal
|
||||||
|
{0x114ba, 0x114ba}, // Tirhuta Vowel Sign Short..Tirhuta Vowel Sign Short
|
||||||
|
{0x114bf, 0x114c0}, // Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara
|
||||||
|
{0x114c2, 0x114c3}, // Tirhuta Sign Virama ..Tirhuta Sign Nukta
|
||||||
|
{0x115b2, 0x115b5}, // Siddham Vowel Sign U ..Siddham Vowel Sign Vocal
|
||||||
|
{0x115bc, 0x115bd}, // Siddham Sign Candrabindu..Siddham Sign Anusvara
|
||||||
|
{0x115bf, 0x115c0}, // Siddham Sign Virama ..Siddham Sign Nukta
|
||||||
|
{0x115dc, 0x115dd}, // Siddham Vowel Sign Alter..Siddham Vowel Sign Alter
|
||||||
|
{0x11633, 0x1163a}, // Modi Vowel Sign U ..Modi Vowel Sign Ai
|
||||||
|
{0x1163d, 0x1163d}, // Modi Sign Anusvara ..Modi Sign Anusvara
|
||||||
|
{0x1163f, 0x11640}, // Modi Sign Virama ..Modi Sign Ardhacandra
|
||||||
|
{0x116ab, 0x116ab}, // Takri Sign Anusvara ..Takri Sign Anusvara
|
||||||
|
{0x116ad, 0x116ad}, // Takri Vowel Sign Aa ..Takri Vowel Sign Aa
|
||||||
|
{0x116b0, 0x116b5}, // Takri Vowel Sign U ..Takri Vowel Sign Au
|
||||||
|
{0x116b7, 0x116b7}, // Takri Sign Nukta ..Takri Sign Nukta
|
||||||
|
{0x1171d, 0x1171f}, // Ahom Consonant Sign Medi..Ahom Consonant Sign Medi
|
||||||
|
{0x11722, 0x11725}, // Ahom Vowel Sign I ..Ahom Vowel Sign Uu
|
||||||
|
{0x11727, 0x1172b}, // Ahom Vowel Sign Aw ..Ahom Sign Killer
|
||||||
|
{0x1182f, 0x11837}, // Dogra Vowel Sign U ..Dogra Sign Anusvara
|
||||||
|
{0x11839, 0x1183a}, // Dogra Sign Virama ..Dogra Sign Nukta
|
||||||
|
{0x1193b, 0x1193c}, // Dives Akuru Sign Anusvar..Dives Akuru Sign Candrab
|
||||||
|
{0x1193e, 0x1193e}, // Dives Akuru Virama ..Dives Akuru Virama
|
||||||
|
{0x11943, 0x11943}, // Dives Akuru Sign Nukta ..Dives Akuru Sign Nukta
|
||||||
|
{0x119d4, 0x119d7}, // Nandinagari Vowel Sign U..Nandinagari Vowel Sign V
|
||||||
|
{0x119da, 0x119db}, // Nandinagari Vowel Sign E..Nandinagari Vowel Sign A
|
||||||
|
{0x119e0, 0x119e0}, // Nandinagari Sign Virama ..Nandinagari Sign Virama
|
||||||
|
{0x11a01, 0x11a0a}, // Zanabazar Square Vowel S..Zanabazar Square Vowel L
|
||||||
|
{0x11a33, 0x11a38}, // Zanabazar Square Final C..Zanabazar Square Sign An
|
||||||
|
{0x11a3b, 0x11a3e}, // Zanabazar Square Cluster..Zanabazar Square Cluster
|
||||||
|
{0x11a47, 0x11a47}, // Zanabazar Square Subjoin..Zanabazar Square Subjoin
|
||||||
|
{0x11a51, 0x11a56}, // Soyombo Vowel Sign I ..Soyombo Vowel Sign Oe
|
||||||
|
{0x11a59, 0x11a5b}, // Soyombo Vowel Sign Vocal..Soyombo Vowel Length Mar
|
||||||
|
{0x11a8a, 0x11a96}, // Soyombo Final Consonant ..Soyombo Sign Anusvara
|
||||||
|
{0x11a98, 0x11a99}, // Soyombo Gemination Mark ..Soyombo Subjoiner
|
||||||
|
{0x11c30, 0x11c36}, // Bhaiksuki Vowel Sign I ..Bhaiksuki Vowel Sign Voc
|
||||||
|
{0x11c38, 0x11c3d}, // Bhaiksuki Vowel Sign E ..Bhaiksuki Sign Anusvara
|
||||||
|
{0x11c3f, 0x11c3f}, // Bhaiksuki Sign Virama ..Bhaiksuki Sign Virama
|
||||||
|
{0x11c92, 0x11ca7}, // Marchen Subjoined Letter..Marchen Subjoined Letter
|
||||||
|
{0x11caa, 0x11cb0}, // Marchen Subjoined Letter..Marchen Vowel Sign Aa
|
||||||
|
{0x11cb2, 0x11cb3}, // Marchen Vowel Sign U ..Marchen Vowel Sign E
|
||||||
|
{0x11cb5, 0x11cb6}, // Marchen Sign Anusvara ..Marchen Sign Candrabindu
|
||||||
|
{0x11d31, 0x11d36}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign
|
||||||
|
{0x11d3a, 0x11d3a}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign
|
||||||
|
{0x11d3c, 0x11d3d}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign
|
||||||
|
{0x11d3f, 0x11d45}, // Masaram Gondi Vowel Sign..Masaram Gondi Virama
|
||||||
|
{0x11d47, 0x11d47}, // Masaram Gondi Ra-kara ..Masaram Gondi Ra-kara
|
||||||
|
{0x11d90, 0x11d91}, // Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign
|
||||||
|
{0x11d95, 0x11d95}, // Gunjala Gondi Sign Anusv..Gunjala Gondi Sign Anusv
|
||||||
|
{0x11d97, 0x11d97}, // Gunjala Gondi Virama ..Gunjala Gondi Virama
|
||||||
|
{0x11ef3, 0x11ef4}, // Makasar Vowel Sign I ..Makasar Vowel Sign U
|
||||||
|
{0x11f00, 0x11f01}, // (nil) ..(nil)
|
||||||
|
{0x11f36, 0x11f3a}, // (nil) ..(nil)
|
||||||
|
{0x11f40, 0x11f40}, // (nil) ..(nil)
|
||||||
|
{0x11f42, 0x11f42}, // (nil) ..(nil)
|
||||||
|
{0x13440, 0x13440}, // (nil) ..(nil)
|
||||||
|
{0x13447, 0x13455}, // (nil) ..(nil)
|
||||||
|
{0x16af0, 0x16af4}, // Bassa Vah Combining High..Bassa Vah Combining High
|
||||||
|
{0x16b30, 0x16b36}, // Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta
|
||||||
|
{0x16f4f, 0x16f4f}, // Miao Sign Consonant Modi..Miao Sign Consonant Modi
|
||||||
|
{0x16f8f, 0x16f92}, // Miao Tone Right ..Miao Tone Below
|
||||||
|
{0x16fe4, 0x16fe4}, // Khitan Small Script Fill..Khitan Small Script Fill
|
||||||
|
{0x1bc9d, 0x1bc9e}, // Duployan Thick Letter Se..Duployan Double Mark
|
||||||
|
{0x1cf00, 0x1cf2d}, // Znamenny Combining Mark ..Znamenny Combining Mark
|
||||||
|
{0x1cf30, 0x1cf46}, // Znamenny Combining Tonal..Znamenny Priznak Modifie
|
||||||
|
{0x1d167, 0x1d169}, // Musical Symbol Combining..Musical Symbol Combining
|
||||||
|
{0x1d17b, 0x1d182}, // Musical Symbol Combining..Musical Symbol Combining
|
||||||
|
{0x1d185, 0x1d18b}, // Musical Symbol Combining..Musical Symbol Combining
|
||||||
|
{0x1d1aa, 0x1d1ad}, // Musical Symbol Combining..Musical Symbol Combining
|
||||||
|
{0x1d242, 0x1d244}, // Combining Greek Musical ..Combining Greek Musical
|
||||||
|
{0x1da00, 0x1da36}, // Signwriting Head Rim ..Signwriting Air Sucking
|
||||||
|
{0x1da3b, 0x1da6c}, // Signwriting Mouth Closed..Signwriting Excitement
|
||||||
|
{0x1da75, 0x1da75}, // Signwriting Upper Body T..Signwriting Upper Body T
|
||||||
|
{0x1da84, 0x1da84}, // Signwriting Location Hea..Signwriting Location Hea
|
||||||
|
{0x1da9b, 0x1da9f}, // Signwriting Fill Modifie..Signwriting Fill Modifie
|
||||||
|
{0x1daa1, 0x1daaf}, // Signwriting Rotation Mod..Signwriting Rotation Mod
|
||||||
|
{0x1e000, 0x1e006}, // Combining Glagolitic Let..Combining Glagolitic Let
|
||||||
|
{0x1e008, 0x1e018}, // Combining Glagolitic Let..Combining Glagolitic Let
|
||||||
|
{0x1e01b, 0x1e021}, // Combining Glagolitic Let..Combining Glagolitic Let
|
||||||
|
{0x1e023, 0x1e024}, // Combining Glagolitic Let..Combining Glagolitic Let
|
||||||
|
{0x1e026, 0x1e02a}, // Combining Glagolitic Let..Combining Glagolitic Let
|
||||||
|
{0x1e08f, 0x1e08f}, // (nil) ..(nil)
|
||||||
|
{0x1e130, 0x1e136}, // Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T
|
||||||
|
{0x1e2ae, 0x1e2ae}, // Toto Sign Rising Tone ..Toto Sign Rising Tone
|
||||||
|
{0x1e2ec, 0x1e2ef}, // Wancho Tone Tup ..Wancho Tone Koini
|
||||||
|
{0x1e4ec, 0x1e4ef}, // (nil) ..(nil)
|
||||||
|
{0x1e8d0, 0x1e8d6}, // Mende Kikakui Combining ..Mende Kikakui Combining
|
||||||
|
{0x1e944, 0x1e94a}, // Adlam Alif Lengthener ..Adlam Nukta
|
||||||
|
{0xe0100, 0xe01ef}, // Variation Selector-17 ..Variation Selector-256
|
||||||
|
};
|
||||||
|
|
||||||
|
// https://github.com/jquast/wcwidth/blob/master/wcwidth/table_wide.py
|
||||||
|
// from https://github.com/jquast/wcwidth/pull/64
|
||||||
|
// at commit 1b9b6585b0080ea5cb88dc9815796505724793fe (2022-12-16):
|
||||||
|
private static final int[][] WIDE_EASTASIAN = {
|
||||||
|
{0x01100, 0x0115f}, // Hangul Choseong Kiyeok ..Hangul Choseong Filler
|
||||||
|
{0x0231a, 0x0231b}, // Watch ..Hourglass
|
||||||
|
{0x02329, 0x0232a}, // Left-pointing Angle Brac..Right-pointing Angle Bra
|
||||||
|
{0x023e9, 0x023ec}, // Black Right-pointing Dou..Black Down-pointing Doub
|
||||||
|
{0x023f0, 0x023f0}, // Alarm Clock ..Alarm Clock
|
||||||
|
{0x023f3, 0x023f3}, // Hourglass With Flowing S..Hourglass With Flowing S
|
||||||
|
{0x025fd, 0x025fe}, // White Medium Small Squar..Black Medium Small Squar
|
||||||
|
{0x02614, 0x02615}, // Umbrella With Rain Drops..Hot Beverage
|
||||||
|
{0x02648, 0x02653}, // Aries ..Pisces
|
||||||
|
{0x0267f, 0x0267f}, // Wheelchair Symbol ..Wheelchair Symbol
|
||||||
|
{0x02693, 0x02693}, // Anchor ..Anchor
|
||||||
|
{0x026a1, 0x026a1}, // High Voltage Sign ..High Voltage Sign
|
||||||
|
{0x026aa, 0x026ab}, // Medium White Circle ..Medium Black Circle
|
||||||
|
{0x026bd, 0x026be}, // Soccer Ball ..Baseball
|
||||||
|
{0x026c4, 0x026c5}, // Snowman Without Snow ..Sun Behind Cloud
|
||||||
|
{0x026ce, 0x026ce}, // Ophiuchus ..Ophiuchus
|
||||||
|
{0x026d4, 0x026d4}, // No Entry ..No Entry
|
||||||
|
{0x026ea, 0x026ea}, // Church ..Church
|
||||||
|
{0x026f2, 0x026f3}, // Fountain ..Flag In Hole
|
||||||
|
{0x026f5, 0x026f5}, // Sailboat ..Sailboat
|
||||||
|
{0x026fa, 0x026fa}, // Tent ..Tent
|
||||||
|
{0x026fd, 0x026fd}, // Fuel Pump ..Fuel Pump
|
||||||
|
{0x02705, 0x02705}, // White Heavy Check Mark ..White Heavy Check Mark
|
||||||
|
{0x0270a, 0x0270b}, // Raised Fist ..Raised Hand
|
||||||
|
{0x02728, 0x02728}, // Sparkles ..Sparkles
|
||||||
|
{0x0274c, 0x0274c}, // Cross Mark ..Cross Mark
|
||||||
|
{0x0274e, 0x0274e}, // Negative Squared Cross M..Negative Squared Cross M
|
||||||
|
{0x02753, 0x02755}, // Black Question Mark Orna..White Exclamation Mark O
|
||||||
|
{0x02757, 0x02757}, // Heavy Exclamation Mark S..Heavy Exclamation Mark S
|
||||||
|
{0x02795, 0x02797}, // Heavy Plus Sign ..Heavy Division Sign
|
||||||
|
{0x027b0, 0x027b0}, // Curly Loop ..Curly Loop
|
||||||
|
{0x027bf, 0x027bf}, // Double Curly Loop ..Double Curly Loop
|
||||||
|
{0x02b1b, 0x02b1c}, // Black Large Square ..White Large Square
|
||||||
|
{0x02b50, 0x02b50}, // White Medium Star ..White Medium Star
|
||||||
|
{0x02b55, 0x02b55}, // Heavy Large Circle ..Heavy Large Circle
|
||||||
|
{0x02e80, 0x02e99}, // Cjk Radical Repeat ..Cjk Radical Rap
|
||||||
|
{0x02e9b, 0x02ef3}, // Cjk Radical Choke ..Cjk Radical C-simplified
|
||||||
|
{0x02f00, 0x02fd5}, // Kangxi Radical One ..Kangxi Radical Flute
|
||||||
|
{0x02ff0, 0x02ffb}, // Ideographic Description ..Ideographic Description
|
||||||
|
{0x03000, 0x0303e}, // Ideographic Space ..Ideographic Variation In
|
||||||
|
{0x03041, 0x03096}, // Hiragana Letter Small A ..Hiragana Letter Small Ke
|
||||||
|
{0x03099, 0x030ff}, // Combining Katakana-hirag..Katakana Digraph Koto
|
||||||
|
{0x03105, 0x0312f}, // Bopomofo Letter B ..Bopomofo Letter Nn
|
||||||
|
{0x03131, 0x0318e}, // Hangul Letter Kiyeok ..Hangul Letter Araeae
|
||||||
|
{0x03190, 0x031e3}, // Ideographic Annotation L..Cjk Stroke Q
|
||||||
|
{0x031f0, 0x0321e}, // Katakana Letter Small Ku..Parenthesized Korean Cha
|
||||||
|
{0x03220, 0x03247}, // Parenthesized Ideograph ..Circled Ideograph Koto
|
||||||
|
{0x03250, 0x04dbf}, // Partnership Sign ..Cjk Unified Ideograph-4d
|
||||||
|
{0x04e00, 0x0a48c}, // Cjk Unified Ideograph-4e..Yi Syllable Yyr
|
||||||
|
{0x0a490, 0x0a4c6}, // Yi Radical Qot ..Yi Radical Ke
|
||||||
|
{0x0a960, 0x0a97c}, // Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo
|
||||||
|
{0x0ac00, 0x0d7a3}, // Hangul Syllable Ga ..Hangul Syllable Hih
|
||||||
|
{0x0f900, 0x0faff}, // Cjk Compatibility Ideogr..(nil)
|
||||||
|
{0x0fe10, 0x0fe19}, // Presentation Form For Ve..Presentation Form For Ve
|
||||||
|
{0x0fe30, 0x0fe52}, // Presentation Form For Ve..Small Full Stop
|
||||||
|
{0x0fe54, 0x0fe66}, // Small Semicolon ..Small Equals Sign
|
||||||
|
{0x0fe68, 0x0fe6b}, // Small Reverse Solidus ..Small Commercial At
|
||||||
|
{0x0ff01, 0x0ff60}, // Fullwidth Exclamation Ma..Fullwidth Right White Pa
|
||||||
|
{0x0ffe0, 0x0ffe6}, // Fullwidth Cent Sign ..Fullwidth Won Sign
|
||||||
|
{0x16fe0, 0x16fe4}, // Tangut Iteration Mark ..Khitan Small Script Fill
|
||||||
|
{0x16ff0, 0x16ff1}, // Vietnamese Alternate Rea..Vietnamese Alternate Rea
|
||||||
|
{0x17000, 0x187f7}, // (nil) ..(nil)
|
||||||
|
{0x18800, 0x18cd5}, // Tangut Component-001 ..Khitan Small Script Char
|
||||||
|
{0x18d00, 0x18d08}, // (nil) ..(nil)
|
||||||
|
{0x1aff0, 0x1aff3}, // Katakana Letter Minnan T..Katakana Letter Minnan T
|
||||||
|
{0x1aff5, 0x1affb}, // Katakana Letter Minnan T..Katakana Letter Minnan N
|
||||||
|
{0x1affd, 0x1affe}, // Katakana Letter Minnan N..Katakana Letter Minnan N
|
||||||
|
{0x1b000, 0x1b122}, // Katakana Letter Archaic ..Katakana Letter Archaic
|
||||||
|
{0x1b132, 0x1b132}, // (nil) ..(nil)
|
||||||
|
{0x1b150, 0x1b152}, // Hiragana Letter Small Wi..Hiragana Letter Small Wo
|
||||||
|
{0x1b155, 0x1b155}, // (nil) ..(nil)
|
||||||
|
{0x1b164, 0x1b167}, // Katakana Letter Small Wi..Katakana Letter Small N
|
||||||
|
{0x1b170, 0x1b2fb}, // Nushu Character-1b170 ..Nushu Character-1b2fb
|
||||||
|
{0x1f004, 0x1f004}, // Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon
|
||||||
|
{0x1f0cf, 0x1f0cf}, // Playing Card Black Joker..Playing Card Black Joker
|
||||||
|
{0x1f18e, 0x1f18e}, // Negative Squared Ab ..Negative Squared Ab
|
||||||
|
{0x1f191, 0x1f19a}, // Squared Cl ..Squared Vs
|
||||||
|
{0x1f200, 0x1f202}, // Square Hiragana Hoka ..Squared Katakana Sa
|
||||||
|
{0x1f210, 0x1f23b}, // Squared Cjk Unified Ideo..Squared Cjk Unified Ideo
|
||||||
|
{0x1f240, 0x1f248}, // Tortoise Shell Bracketed..Tortoise Shell Bracketed
|
||||||
|
{0x1f250, 0x1f251}, // Circled Ideograph Advant..Circled Ideograph Accept
|
||||||
|
{0x1f260, 0x1f265}, // Rounded Symbol For Fu ..Rounded Symbol For Cai
|
||||||
|
{0x1f300, 0x1f320}, // Cyclone ..Shooting Star
|
||||||
|
{0x1f32d, 0x1f335}, // Hot Dog ..Cactus
|
||||||
|
{0x1f337, 0x1f37c}, // Tulip ..Baby Bottle
|
||||||
|
{0x1f37e, 0x1f393}, // Bottle With Popping Cork..Graduation Cap
|
||||||
|
{0x1f3a0, 0x1f3ca}, // Carousel Horse ..Swimmer
|
||||||
|
{0x1f3cf, 0x1f3d3}, // Cricket Bat And Ball ..Table Tennis Paddle And
|
||||||
|
{0x1f3e0, 0x1f3f0}, // House Building ..European Castle
|
||||||
|
{0x1f3f4, 0x1f3f4}, // Waving Black Flag ..Waving Black Flag
|
||||||
|
{0x1f3f8, 0x1f43e}, // Badminton Racquet And Sh..Paw Prints
|
||||||
|
{0x1f440, 0x1f440}, // Eyes ..Eyes
|
||||||
|
{0x1f442, 0x1f4fc}, // Ear ..Videocassette
|
||||||
|
{0x1f4ff, 0x1f53d}, // Prayer Beads ..Down-pointing Small Red
|
||||||
|
{0x1f54b, 0x1f54e}, // Kaaba ..Menorah With Nine Branch
|
||||||
|
{0x1f550, 0x1f567}, // Clock Face One Oclock ..Clock Face Twelve-thirty
|
||||||
|
{0x1f57a, 0x1f57a}, // Man Dancing ..Man Dancing
|
||||||
|
{0x1f595, 0x1f596}, // Reversed Hand With Middl..Raised Hand With Part Be
|
||||||
|
{0x1f5a4, 0x1f5a4}, // Black Heart ..Black Heart
|
||||||
|
{0x1f5fb, 0x1f64f}, // Mount Fuji ..Person With Folded Hands
|
||||||
|
{0x1f680, 0x1f6c5}, // Rocket ..Left Luggage
|
||||||
|
{0x1f6cc, 0x1f6cc}, // Sleeping Accommodation ..Sleeping Accommodation
|
||||||
|
{0x1f6d0, 0x1f6d2}, // Place Of Worship ..Shopping Trolley
|
||||||
|
{0x1f6d5, 0x1f6d7}, // Hindu Temple ..Elevator
|
||||||
|
{0x1f6dc, 0x1f6df}, // (nil) ..Ring Buoy
|
||||||
|
{0x1f6eb, 0x1f6ec}, // Airplane Departure ..Airplane Arriving
|
||||||
|
{0x1f6f4, 0x1f6fc}, // Scooter ..Roller Skate
|
||||||
|
{0x1f7e0, 0x1f7eb}, // Large Orange Circle ..Large Brown Square
|
||||||
|
{0x1f7f0, 0x1f7f0}, // Heavy Equals Sign ..Heavy Equals Sign
|
||||||
|
{0x1f90c, 0x1f93a}, // Pinched Fingers ..Fencer
|
||||||
|
{0x1f93c, 0x1f945}, // Wrestlers ..Goal Net
|
||||||
|
{0x1f947, 0x1f9ff}, // First Place Medal ..Nazar Amulet
|
||||||
|
{0x1fa70, 0x1fa7c}, // Ballet Shoes ..Crutch
|
||||||
|
{0x1fa80, 0x1fa88}, // Yo-yo ..(nil)
|
||||||
|
{0x1fa90, 0x1fabd}, // Ringed Planet ..(nil)
|
||||||
|
{0x1fabf, 0x1fac5}, // (nil) ..Person With Crown
|
||||||
|
{0x1face, 0x1fadb}, // (nil) ..(nil)
|
||||||
|
{0x1fae0, 0x1fae8}, // Melting Face ..(nil)
|
||||||
|
{0x1faf0, 0x1faf8}, // Hand With Index Finger A..(nil)
|
||||||
|
{0x20000, 0x2fffd}, // Cjk Unified Ideograph-20..(nil)
|
||||||
|
{0x30000, 0x3fffd}, // Cjk Unified Ideograph-30..(nil)
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
private static boolean intable(int[][] table, int c) {
|
||||||
|
// First quick check f|| Latin1 etc. characters.
|
||||||
|
if (c < table[0][0]) return false;
|
||||||
|
|
||||||
|
// Binary search in table.
|
||||||
|
int bot = 0;
|
||||||
|
int top = table.length - 1; // (int)(size / sizeof(struct interval) - 1);
|
||||||
|
while (top >= bot) {
|
||||||
|
int mid = (bot + top) / 2;
|
||||||
|
if (table[mid][1] < c) {
|
||||||
|
bot = mid + 1;
|
||||||
|
} else if (table[mid][0] > c) {
|
||||||
|
top = mid - 1;
|
||||||
|
} else {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Return the terminal display width of a code point: 0, 1 || 2. */
|
||||||
|
public static int width(int ucs) {
|
||||||
|
if (ucs == 0 ||
|
||||||
|
ucs == 0x034F ||
|
||||||
|
(0x200B <= ucs && ucs <= 0x200F) ||
|
||||||
|
ucs == 0x2028 ||
|
||||||
|
ucs == 0x2029 ||
|
||||||
|
(0x202A <= ucs && ucs <= 0x202E) ||
|
||||||
|
(0x2060 <= ucs && ucs <= 0x2063)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// C0/C1 control characters
|
||||||
|
// Termux change: Return 0 instead of -1.
|
||||||
|
if (ucs < 32 || (0x07F <= ucs && ucs < 0x0A0)) return 0;
|
||||||
|
|
||||||
|
// combining characters with zero width
|
||||||
|
if (intable(ZERO_WIDTH, ucs)) return 0;
|
||||||
|
|
||||||
|
return intable(WIDE_EASTASIAN, ucs) ? 2 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The width at an index position in a java char array. */
|
||||||
|
public static int width(char[] chars, int index) {
|
||||||
|
char c = chars[index];
|
||||||
|
return Character.isHighSurrogate(c) ? width(Character.toCodePoint(c, chars[index + 1])) : width(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The zero width characters count like combining characters in the `chars` array from start
|
||||||
|
* index to end index (exclusive).
|
||||||
|
*/
|
||||||
|
public static int zeroWidthCharsCount(char[] chars, int start, int end) {
|
||||||
|
if (start < 0 || start >= chars.length)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
int count = 0;
|
||||||
|
for (int i = start; i < end && i < chars.length;) {
|
||||||
|
if (Character.isHighSurrogate(chars[i])) {
|
||||||
|
if (width(Character.toCodePoint(chars[i], chars[i + 1])) <= 0) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
i += 2;
|
||||||
|
} else {
|
||||||
|
if (width(chars[i]) <= 0) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package com.termux.view;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.view.GestureDetector;
|
||||||
|
import android.view.MotionEvent;
|
||||||
|
import android.view.ScaleGestureDetector;
|
||||||
|
|
||||||
|
/** A combination of {@link GestureDetector} and {@link ScaleGestureDetector}. */
|
||||||
|
final class GestureAndScaleRecognizer {
|
||||||
|
|
||||||
|
public interface Listener {
|
||||||
|
boolean onSingleTapUp(MotionEvent e);
|
||||||
|
|
||||||
|
boolean onDoubleTap(MotionEvent e);
|
||||||
|
|
||||||
|
boolean onScroll(MotionEvent e2, float dx, float dy);
|
||||||
|
|
||||||
|
boolean onFling(MotionEvent e, float velocityX, float velocityY);
|
||||||
|
|
||||||
|
boolean onScale(float focusX, float focusY, float scale);
|
||||||
|
|
||||||
|
boolean onDown(float x, float y);
|
||||||
|
|
||||||
|
boolean onUp(MotionEvent e);
|
||||||
|
|
||||||
|
void onLongPress(MotionEvent e);
|
||||||
|
}
|
||||||
|
|
||||||
|
private final GestureDetector mGestureDetector;
|
||||||
|
private final ScaleGestureDetector mScaleDetector;
|
||||||
|
final Listener mListener;
|
||||||
|
boolean isAfterLongPress;
|
||||||
|
|
||||||
|
public GestureAndScaleRecognizer(Context context, Listener listener) {
|
||||||
|
mListener = listener;
|
||||||
|
|
||||||
|
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
|
||||||
|
@Override
|
||||||
|
public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) {
|
||||||
|
return mListener.onScroll(e2, dx, dy);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
|
||||||
|
return mListener.onFling(e2, velocityX, velocityY);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onDown(MotionEvent e) {
|
||||||
|
return mListener.onDown(e.getX(), e.getY());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onLongPress(MotionEvent e) {
|
||||||
|
mListener.onLongPress(e);
|
||||||
|
isAfterLongPress = true;
|
||||||
|
}
|
||||||
|
}, null, true /* ignoreMultitouch */);
|
||||||
|
|
||||||
|
mGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
|
||||||
|
@Override
|
||||||
|
public boolean onSingleTapConfirmed(MotionEvent e) {
|
||||||
|
return mListener.onSingleTapUp(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onDoubleTap(MotionEvent e) {
|
||||||
|
return mListener.onDoubleTap(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onDoubleTapEvent(MotionEvent e) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
mScaleDetector = new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
|
||||||
|
@Override
|
||||||
|
public boolean onScaleBegin(ScaleGestureDetector detector) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onScale(ScaleGestureDetector detector) {
|
||||||
|
return mListener.onScale(detector.getFocusX(), detector.getFocusY(), detector.getScaleFactor());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
mScaleDetector.setQuickScaleEnabled(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void onTouchEvent(MotionEvent event) {
|
||||||
|
mGestureDetector.onTouchEvent(event);
|
||||||
|
mScaleDetector.onTouchEvent(event);
|
||||||
|
switch (event.getAction()) {
|
||||||
|
case MotionEvent.ACTION_DOWN:
|
||||||
|
isAfterLongPress = false;
|
||||||
|
break;
|
||||||
|
case MotionEvent.ACTION_UP:
|
||||||
|
if (!isAfterLongPress) {
|
||||||
|
// This behaviour is desired when in e.g. vim with mouse events, where we do not
|
||||||
|
// want to move the cursor when lifting finger after a long press.
|
||||||
|
mListener.onUp(event);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isInProgress() {
|
||||||
|
return mScaleDetector.isInProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
249
android/app/src/main/java/com/termux/view/TerminalRenderer.java
Normal file
@@ -0,0 +1,249 @@
|
|||||||
|
package com.termux.view;
|
||||||
|
|
||||||
|
import android.graphics.Canvas;
|
||||||
|
import android.graphics.Paint;
|
||||||
|
import android.graphics.PorterDuff;
|
||||||
|
import android.graphics.Typeface;
|
||||||
|
|
||||||
|
import com.termux.terminal.TerminalBuffer;
|
||||||
|
import com.termux.terminal.TerminalEmulator;
|
||||||
|
import com.termux.terminal.TerminalRow;
|
||||||
|
import com.termux.terminal.TextStyle;
|
||||||
|
import com.termux.terminal.WcWidth;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renderer of a {@link TerminalEmulator} into a {@link Canvas}.
|
||||||
|
* <p/>
|
||||||
|
* Saves font metrics, so needs to be recreated each time the typeface or font size changes.
|
||||||
|
*/
|
||||||
|
public final class TerminalRenderer {
|
||||||
|
|
||||||
|
final int mTextSize;
|
||||||
|
final Typeface mTypeface;
|
||||||
|
private final Paint mTextPaint = new Paint();
|
||||||
|
|
||||||
|
/** The width of a single mono spaced character obtained by {@link Paint#measureText(String)} on a single 'X'. */
|
||||||
|
final float mFontWidth;
|
||||||
|
/** The {@link Paint#getFontSpacing()}. See http://www.fampennings.nl/maarten/android/08numgrid/font.png */
|
||||||
|
final int mFontLineSpacing;
|
||||||
|
/** The {@link Paint#ascent()}. See http://www.fampennings.nl/maarten/android/08numgrid/font.png */
|
||||||
|
private final int mFontAscent;
|
||||||
|
/** The {@link #mFontLineSpacing} + {@link #mFontAscent}. */
|
||||||
|
final int mFontLineSpacingAndAscent;
|
||||||
|
|
||||||
|
private final float[] asciiMeasures = new float[127];
|
||||||
|
|
||||||
|
public TerminalRenderer(int textSize, Typeface typeface) {
|
||||||
|
mTextSize = textSize;
|
||||||
|
mTypeface = typeface;
|
||||||
|
|
||||||
|
mTextPaint.setTypeface(typeface);
|
||||||
|
mTextPaint.setAntiAlias(true);
|
||||||
|
mTextPaint.setTextSize(textSize);
|
||||||
|
|
||||||
|
mFontLineSpacing = (int) Math.ceil(mTextPaint.getFontSpacing());
|
||||||
|
mFontAscent = (int) Math.ceil(mTextPaint.ascent());
|
||||||
|
mFontLineSpacingAndAscent = mFontLineSpacing + mFontAscent;
|
||||||
|
mFontWidth = mTextPaint.measureText("X");
|
||||||
|
|
||||||
|
StringBuilder sb = new StringBuilder(" ");
|
||||||
|
for (int i = 0; i < asciiMeasures.length; i++) {
|
||||||
|
sb.setCharAt(0, (char) i);
|
||||||
|
asciiMeasures[i] = mTextPaint.measureText(sb, 0, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render the terminal to a canvas with at a specified row scroll, and an optional rectangular selection. */
|
||||||
|
public final void render(TerminalEmulator mEmulator, Canvas canvas, int topRow,
|
||||||
|
int selectionY1, int selectionY2, int selectionX1, int selectionX2) {
|
||||||
|
final boolean reverseVideo = mEmulator.isReverseVideo();
|
||||||
|
final int endRow = topRow + mEmulator.mRows;
|
||||||
|
final int columns = mEmulator.mColumns;
|
||||||
|
final int cursorCol = mEmulator.getCursorCol();
|
||||||
|
final int cursorRow = mEmulator.getCursorRow();
|
||||||
|
final boolean cursorVisible = mEmulator.shouldCursorBeVisible();
|
||||||
|
final TerminalBuffer screen = mEmulator.getScreen();
|
||||||
|
final int[] palette = mEmulator.mColors.mCurrentColors;
|
||||||
|
final int cursorShape = mEmulator.getCursorStyle();
|
||||||
|
|
||||||
|
if (reverseVideo)
|
||||||
|
canvas.drawColor(palette[TextStyle.COLOR_INDEX_FOREGROUND], PorterDuff.Mode.SRC);
|
||||||
|
|
||||||
|
float heightOffset = mFontLineSpacingAndAscent;
|
||||||
|
for (int row = topRow; row < endRow; row++) {
|
||||||
|
heightOffset += mFontLineSpacing;
|
||||||
|
|
||||||
|
final int cursorX = (row == cursorRow && cursorVisible) ? cursorCol : -1;
|
||||||
|
int selx1 = -1, selx2 = -1;
|
||||||
|
if (row >= selectionY1 && row <= selectionY2) {
|
||||||
|
if (row == selectionY1) selx1 = selectionX1;
|
||||||
|
selx2 = (row == selectionY2) ? selectionX2 : mEmulator.mColumns;
|
||||||
|
}
|
||||||
|
|
||||||
|
TerminalRow lineObject = screen.allocateFullLineIfNecessary(screen.externalToInternalRow(row));
|
||||||
|
final char[] line = lineObject.mText;
|
||||||
|
final int charsUsedInLine = lineObject.getSpaceUsed();
|
||||||
|
|
||||||
|
long lastRunStyle = 0;
|
||||||
|
boolean lastRunInsideCursor = false;
|
||||||
|
boolean lastRunInsideSelection = false;
|
||||||
|
int lastRunStartColumn = -1;
|
||||||
|
int lastRunStartIndex = 0;
|
||||||
|
boolean lastRunFontWidthMismatch = false;
|
||||||
|
int currentCharIndex = 0;
|
||||||
|
float measuredWidthForRun = 0.f;
|
||||||
|
|
||||||
|
for (int column = 0; column < columns; ) {
|
||||||
|
final char charAtIndex = line[currentCharIndex];
|
||||||
|
final boolean charIsHighsurrogate = Character.isHighSurrogate(charAtIndex);
|
||||||
|
final int charsForCodePoint = charIsHighsurrogate ? 2 : 1;
|
||||||
|
final int codePoint = charIsHighsurrogate ? Character.toCodePoint(charAtIndex, line[currentCharIndex + 1]) : charAtIndex;
|
||||||
|
final int codePointWcWidth = WcWidth.width(codePoint);
|
||||||
|
final boolean insideCursor = (cursorX == column || (codePointWcWidth == 2 && cursorX == column + 1));
|
||||||
|
final boolean insideSelection = column >= selx1 && column <= selx2;
|
||||||
|
final long style = lineObject.getStyle(column);
|
||||||
|
|
||||||
|
// Check if the measured text width for this code point is not the same as that expected by wcwidth().
|
||||||
|
// This could happen for some fonts which are not truly monospace, or for more exotic characters such as
|
||||||
|
// smileys which android font renders as wide.
|
||||||
|
// If this is detected, we draw this code point scaled to match what wcwidth() expects.
|
||||||
|
final float measuredCodePointWidth = (codePoint < asciiMeasures.length) ? asciiMeasures[codePoint] : mTextPaint.measureText(line,
|
||||||
|
currentCharIndex, charsForCodePoint);
|
||||||
|
final boolean fontWidthMismatch = Math.abs(measuredCodePointWidth / mFontWidth - codePointWcWidth) > 0.01;
|
||||||
|
|
||||||
|
if (style != lastRunStyle || insideCursor != lastRunInsideCursor || insideSelection != lastRunInsideSelection || fontWidthMismatch || lastRunFontWidthMismatch) {
|
||||||
|
if (column == 0) {
|
||||||
|
// Skip first column as there is nothing to draw, just record the current style.
|
||||||
|
} else {
|
||||||
|
final int columnWidthSinceLastRun = column - lastRunStartColumn;
|
||||||
|
final int charsSinceLastRun = currentCharIndex - lastRunStartIndex;
|
||||||
|
int cursorColor = lastRunInsideCursor ? mEmulator.mColors.mCurrentColors[TextStyle.COLOR_INDEX_CURSOR] : 0;
|
||||||
|
boolean invertCursorTextColor = false;
|
||||||
|
if (lastRunInsideCursor && cursorShape == TerminalEmulator.TERMINAL_CURSOR_STYLE_BLOCK) {
|
||||||
|
invertCursorTextColor = true;
|
||||||
|
}
|
||||||
|
drawTextRun(canvas, line, palette, heightOffset, lastRunStartColumn, columnWidthSinceLastRun,
|
||||||
|
lastRunStartIndex, charsSinceLastRun, measuredWidthForRun,
|
||||||
|
cursorColor, cursorShape, lastRunStyle, reverseVideo || invertCursorTextColor || lastRunInsideSelection);
|
||||||
|
}
|
||||||
|
measuredWidthForRun = 0.f;
|
||||||
|
lastRunStyle = style;
|
||||||
|
lastRunInsideCursor = insideCursor;
|
||||||
|
lastRunInsideSelection = insideSelection;
|
||||||
|
lastRunStartColumn = column;
|
||||||
|
lastRunStartIndex = currentCharIndex;
|
||||||
|
lastRunFontWidthMismatch = fontWidthMismatch;
|
||||||
|
}
|
||||||
|
measuredWidthForRun += measuredCodePointWidth;
|
||||||
|
column += codePointWcWidth;
|
||||||
|
currentCharIndex += charsForCodePoint;
|
||||||
|
while (currentCharIndex < charsUsedInLine && WcWidth.width(line, currentCharIndex) <= 0) {
|
||||||
|
// Eat combining chars so that they are treated as part of the last non-combining code point,
|
||||||
|
// instead of e.g. being considered inside the cursor in the next run.
|
||||||
|
currentCharIndex += Character.isHighSurrogate(line[currentCharIndex]) ? 2 : 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final int columnWidthSinceLastRun = columns - lastRunStartColumn;
|
||||||
|
final int charsSinceLastRun = currentCharIndex - lastRunStartIndex;
|
||||||
|
int cursorColor = lastRunInsideCursor ? mEmulator.mColors.mCurrentColors[TextStyle.COLOR_INDEX_CURSOR] : 0;
|
||||||
|
boolean invertCursorTextColor = false;
|
||||||
|
if (lastRunInsideCursor && cursorShape == TerminalEmulator.TERMINAL_CURSOR_STYLE_BLOCK) {
|
||||||
|
invertCursorTextColor = true;
|
||||||
|
}
|
||||||
|
drawTextRun(canvas, line, palette, heightOffset, lastRunStartColumn, columnWidthSinceLastRun, lastRunStartIndex, charsSinceLastRun,
|
||||||
|
measuredWidthForRun, cursorColor, cursorShape, lastRunStyle, reverseVideo || invertCursorTextColor || lastRunInsideSelection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawTextRun(Canvas canvas, char[] text, int[] palette, float y, int startColumn, int runWidthColumns,
|
||||||
|
int startCharIndex, int runWidthChars, float mes, int cursor, int cursorStyle,
|
||||||
|
long textStyle, boolean reverseVideo) {
|
||||||
|
int foreColor = TextStyle.decodeForeColor(textStyle);
|
||||||
|
final int effect = TextStyle.decodeEffect(textStyle);
|
||||||
|
int backColor = TextStyle.decodeBackColor(textStyle);
|
||||||
|
final boolean bold = (effect & (TextStyle.CHARACTER_ATTRIBUTE_BOLD | TextStyle.CHARACTER_ATTRIBUTE_BLINK)) != 0;
|
||||||
|
final boolean underline = (effect & TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE) != 0;
|
||||||
|
final boolean italic = (effect & TextStyle.CHARACTER_ATTRIBUTE_ITALIC) != 0;
|
||||||
|
final boolean strikeThrough = (effect & TextStyle.CHARACTER_ATTRIBUTE_STRIKETHROUGH) != 0;
|
||||||
|
final boolean dim = (effect & TextStyle.CHARACTER_ATTRIBUTE_DIM) != 0;
|
||||||
|
|
||||||
|
if ((foreColor & 0xff000000) != 0xff000000) {
|
||||||
|
// Let bold have bright colors if applicable (one of the first 8):
|
||||||
|
if (bold && foreColor >= 0 && foreColor < 8) foreColor += 8;
|
||||||
|
foreColor = palette[foreColor];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((backColor & 0xff000000) != 0xff000000) {
|
||||||
|
backColor = palette[backColor];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reverse video here if _one and only one_ of the reverse flags are set:
|
||||||
|
final boolean reverseVideoHere = reverseVideo ^ (effect & (TextStyle.CHARACTER_ATTRIBUTE_INVERSE)) != 0;
|
||||||
|
if (reverseVideoHere) {
|
||||||
|
int tmp = foreColor;
|
||||||
|
foreColor = backColor;
|
||||||
|
backColor = tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
float left = startColumn * mFontWidth;
|
||||||
|
float right = left + runWidthColumns * mFontWidth;
|
||||||
|
|
||||||
|
mes = mes / mFontWidth;
|
||||||
|
boolean savedMatrix = false;
|
||||||
|
if (Math.abs(mes - runWidthColumns) > 0.01) {
|
||||||
|
canvas.save();
|
||||||
|
canvas.scale(runWidthColumns / mes, 1.f);
|
||||||
|
left *= mes / runWidthColumns;
|
||||||
|
right *= mes / runWidthColumns;
|
||||||
|
savedMatrix = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (backColor != palette[TextStyle.COLOR_INDEX_BACKGROUND]) {
|
||||||
|
// Only draw non-default background.
|
||||||
|
mTextPaint.setColor(backColor);
|
||||||
|
canvas.drawRect(left, y - mFontLineSpacingAndAscent + mFontAscent, right, y, mTextPaint);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cursor != 0) {
|
||||||
|
mTextPaint.setColor(cursor);
|
||||||
|
float cursorHeight = mFontLineSpacingAndAscent - mFontAscent;
|
||||||
|
if (cursorStyle == TerminalEmulator.TERMINAL_CURSOR_STYLE_UNDERLINE) cursorHeight /= 4.;
|
||||||
|
else if (cursorStyle == TerminalEmulator.TERMINAL_CURSOR_STYLE_BAR) right -= ((right - left) * 3) / 4.;
|
||||||
|
canvas.drawRect(left, y - cursorHeight, right, y, mTextPaint);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((effect & TextStyle.CHARACTER_ATTRIBUTE_INVISIBLE) == 0) {
|
||||||
|
if (dim) {
|
||||||
|
int red = (0xFF & (foreColor >> 16));
|
||||||
|
int green = (0xFF & (foreColor >> 8));
|
||||||
|
int blue = (0xFF & foreColor);
|
||||||
|
// Dim color handling used by libvte which in turn took it from xterm
|
||||||
|
// (https://bug735245.bugzilla-attachments.gnome.org/attachment.cgi?id=284267):
|
||||||
|
red = red * 2 / 3;
|
||||||
|
green = green * 2 / 3;
|
||||||
|
blue = blue * 2 / 3;
|
||||||
|
foreColor = 0xFF000000 + (red << 16) + (green << 8) + blue;
|
||||||
|
}
|
||||||
|
|
||||||
|
mTextPaint.setFakeBoldText(bold);
|
||||||
|
mTextPaint.setUnderlineText(underline);
|
||||||
|
mTextPaint.setTextSkewX(italic ? -0.35f : 0.f);
|
||||||
|
mTextPaint.setStrikeThruText(strikeThrough);
|
||||||
|
mTextPaint.setColor(foreColor);
|
||||||
|
|
||||||
|
// The text alignment is the default Paint.Align.LEFT.
|
||||||
|
canvas.drawTextRun(text, startCharIndex, runWidthChars, startCharIndex, runWidthChars, left, y - mFontLineSpacingAndAscent, false, mTextPaint);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (savedMatrix) canvas.restore();
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getFontWidth() {
|
||||||
|
return mFontWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getFontLineSpacing() {
|
||||||
|
return mFontLineSpacing;
|
||||||
|
}
|
||||||
|
}
|
||||||
1476
android/app/src/main/java/com/termux/view/TerminalView.java
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package com.termux.view;
|
||||||
|
|
||||||
|
import android.view.KeyEvent;
|
||||||
|
import android.view.MotionEvent;
|
||||||
|
import android.view.ScaleGestureDetector;
|
||||||
|
import android.view.View;
|
||||||
|
|
||||||
|
import com.termux.terminal.TerminalSession;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The interface for communication between {@link TerminalView} and its client. It allows for getting
|
||||||
|
* various configuration options from the client and for sending back data to the client like logs,
|
||||||
|
* key events, both hardware and IME (which makes it different from that available with
|
||||||
|
* {@link View#setOnKeyListener(View.OnKeyListener)}, etc. It must be set for the
|
||||||
|
* {@link TerminalView} through {@link TerminalView#setTerminalViewClient(TerminalViewClient)}.
|
||||||
|
*/
|
||||||
|
public interface TerminalViewClient {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Callback function on scale events according to {@link ScaleGestureDetector#getScaleFactor()}.
|
||||||
|
*/
|
||||||
|
float onScale(float scale);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* On a single tap on the terminal if terminal mouse reporting not enabled.
|
||||||
|
*/
|
||||||
|
void onSingleTapUp(MotionEvent e);
|
||||||
|
|
||||||
|
boolean shouldBackButtonBeMappedToEscape();
|
||||||
|
|
||||||
|
boolean shouldEnforceCharBasedInput();
|
||||||
|
|
||||||
|
boolean shouldUseCtrlSpaceWorkaround();
|
||||||
|
|
||||||
|
boolean isTerminalViewSelected();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
void copyModeChanged(boolean copyMode);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
boolean onKeyDown(int keyCode, KeyEvent e, TerminalSession session);
|
||||||
|
|
||||||
|
boolean onKeyUp(int keyCode, KeyEvent e);
|
||||||
|
|
||||||
|
boolean onLongPress(MotionEvent event);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
boolean readControlKey();
|
||||||
|
|
||||||
|
boolean readAltKey();
|
||||||
|
|
||||||
|
boolean readShiftKey();
|
||||||
|
|
||||||
|
boolean readFnKey();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
boolean onCodePoint(int codePoint, boolean ctrlDown, TerminalSession session);
|
||||||
|
|
||||||
|
|
||||||
|
void onEmulatorSet();
|
||||||
|
|
||||||
|
|
||||||
|
void logError(String tag, String message);
|
||||||
|
|
||||||
|
void logWarn(String tag, String message);
|
||||||
|
|
||||||
|
void logInfo(String tag, String message);
|
||||||
|
|
||||||
|
void logDebug(String tag, String message);
|
||||||
|
|
||||||
|
void logVerbose(String tag, String message);
|
||||||
|
|
||||||
|
void logStackTraceWithMessage(String tag, String message, Exception e);
|
||||||
|
|
||||||
|
void logStackTrace(String tag, Exception e);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.termux.view.textselection;
|
||||||
|
|
||||||
|
import android.view.MotionEvent;
|
||||||
|
import android.view.ViewTreeObserver;
|
||||||
|
|
||||||
|
import com.termux.view.TerminalView;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A CursorController instance can be used to control cursors in the text.
|
||||||
|
* It is not used outside of {@link TerminalView}.
|
||||||
|
*/
|
||||||
|
public interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
|
||||||
|
/**
|
||||||
|
* Show the cursors on screen. Will be drawn by {@link #render()} by a call during onDraw.
|
||||||
|
* See also {@link #hide()}.
|
||||||
|
*/
|
||||||
|
void show(MotionEvent event);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide the cursors from screen.
|
||||||
|
* See also {@link #show(MotionEvent event)}.
|
||||||
|
*/
|
||||||
|
boolean hide();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the cursors.
|
||||||
|
*/
|
||||||
|
void render();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the cursor positions.
|
||||||
|
*/
|
||||||
|
void updatePosition(TextSelectionHandleView handle, int x, int y);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is called by {@link #onTouchEvent(MotionEvent)} and gives the cursors
|
||||||
|
* a chance to become active and/or visible.
|
||||||
|
*
|
||||||
|
* @param event The touch event
|
||||||
|
*/
|
||||||
|
boolean onTouchEvent(MotionEvent event);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when the view is detached from window. Perform house keeping task, such as
|
||||||
|
* stopping Runnable thread that would otherwise keep a reference on the context, thus
|
||||||
|
* preventing the activity to be recycled.
|
||||||
|
*/
|
||||||
|
void onDetached();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return true if the cursors are currently active.
|
||||||
|
*/
|
||||||
|
boolean isActive();
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
package com.termux.view.textselection;
|
||||||
|
|
||||||
|
import android.content.ClipData;
|
||||||
|
import android.content.ClipboardManager;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.graphics.Rect;
|
||||||
|
import android.text.TextUtils;
|
||||||
|
import android.view.ActionMode;
|
||||||
|
import android.view.InputDevice;
|
||||||
|
import android.view.Menu;
|
||||||
|
import android.view.MenuItem;
|
||||||
|
import android.view.MotionEvent;
|
||||||
|
import android.view.View;
|
||||||
|
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import com.termux.terminal.TerminalBuffer;
|
||||||
|
import com.termux.terminal.WcWidth;
|
||||||
|
import com.doubao.lynxclone.R;
|
||||||
|
import com.termux.view.TerminalView;
|
||||||
|
|
||||||
|
public class TextSelectionCursorController implements CursorController {
|
||||||
|
|
||||||
|
private final TerminalView terminalView;
|
||||||
|
private final TextSelectionHandleView mStartHandle, mEndHandle;
|
||||||
|
private String mStoredSelectedText;
|
||||||
|
private boolean mIsSelectingText = false;
|
||||||
|
private long mShowStartTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
private final int mHandleHeight;
|
||||||
|
private int mSelX1 = -1, mSelX2 = -1, mSelY1 = -1, mSelY2 = -1;
|
||||||
|
|
||||||
|
private ActionMode mActionMode;
|
||||||
|
public final int ACTION_COPY = 1;
|
||||||
|
public final int ACTION_PASTE = 2;
|
||||||
|
public final int ACTION_MORE = 3;
|
||||||
|
|
||||||
|
public TextSelectionCursorController(TerminalView terminalView) {
|
||||||
|
this.terminalView = terminalView;
|
||||||
|
mStartHandle = new TextSelectionHandleView(terminalView, this, TextSelectionHandleView.LEFT);
|
||||||
|
mEndHandle = new TextSelectionHandleView(terminalView, this, TextSelectionHandleView.RIGHT);
|
||||||
|
|
||||||
|
mHandleHeight = Math.max(mStartHandle.getHandleHeight(), mEndHandle.getHandleHeight());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void show(MotionEvent event) {
|
||||||
|
setInitialTextSelectionPosition(event);
|
||||||
|
mStartHandle.positionAtCursor(mSelX1, mSelY1, true);
|
||||||
|
mEndHandle.positionAtCursor(mSelX2 + 1, mSelY2, true);
|
||||||
|
|
||||||
|
setActionModeCallBacks();
|
||||||
|
mShowStartTime = System.currentTimeMillis();
|
||||||
|
mIsSelectingText = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean hide() {
|
||||||
|
if (!isActive()) return false;
|
||||||
|
|
||||||
|
// prevent hide calls right after a show call, like long pressing the down key
|
||||||
|
// 300ms seems long enough that it wouldn't cause hide problems if action button
|
||||||
|
// is quickly clicked after the show, otherwise decrease it
|
||||||
|
if (System.currentTimeMillis() - mShowStartTime < 300) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
mStartHandle.hide();
|
||||||
|
mEndHandle.hide();
|
||||||
|
|
||||||
|
if (mActionMode != null) {
|
||||||
|
// This will hide the TextSelectionCursorController
|
||||||
|
mActionMode.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
mSelX1 = mSelY1 = mSelX2 = mSelY2 = -1;
|
||||||
|
mIsSelectingText = false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void render() {
|
||||||
|
if (!isActive()) return;
|
||||||
|
|
||||||
|
mStartHandle.positionAtCursor(mSelX1, mSelY1, false);
|
||||||
|
mEndHandle.positionAtCursor(mSelX2 + 1, mSelY2, false);
|
||||||
|
|
||||||
|
if (mActionMode != null) {
|
||||||
|
mActionMode.invalidate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInitialTextSelectionPosition(MotionEvent event) {
|
||||||
|
int[] columnAndRow = terminalView.getColumnAndRow(event, true);
|
||||||
|
mSelX1 = mSelX2 = columnAndRow[0];
|
||||||
|
mSelY1 = mSelY2 = columnAndRow[1];
|
||||||
|
|
||||||
|
TerminalBuffer screen = terminalView.mEmulator.getScreen();
|
||||||
|
if (!" ".equals(screen.getSelectedText(mSelX1, mSelY1, mSelX1, mSelY1))) {
|
||||||
|
// Selecting something other than whitespace. Expand to word.
|
||||||
|
while (mSelX1 > 0 && !"".equals(screen.getSelectedText(mSelX1 - 1, mSelY1, mSelX1 - 1, mSelY1))) {
|
||||||
|
mSelX1--;
|
||||||
|
}
|
||||||
|
while (mSelX2 < terminalView.mEmulator.mColumns - 1 && !"".equals(screen.getSelectedText(mSelX2 + 1, mSelY1, mSelX2 + 1, mSelY1))) {
|
||||||
|
mSelX2++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setActionModeCallBacks() {
|
||||||
|
final ActionMode.Callback callback = new ActionMode.Callback() {
|
||||||
|
@Override
|
||||||
|
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
|
||||||
|
int show = MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT;
|
||||||
|
|
||||||
|
ClipboardManager clipboard = (ClipboardManager) terminalView.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
|
||||||
|
menu.add(Menu.NONE, ACTION_COPY, Menu.NONE, R.string.copy_text).setShowAsAction(show);
|
||||||
|
menu.add(Menu.NONE, ACTION_PASTE, Menu.NONE, R.string.paste_text).setEnabled(clipboard != null && clipboard.hasPrimaryClip()).setShowAsAction(show);
|
||||||
|
menu.add(Menu.NONE, ACTION_MORE, Menu.NONE, R.string.text_selection_more);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
|
||||||
|
if (!isActive()) {
|
||||||
|
// Fix issue where the dialog is pressed while being dismissed.
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (item.getItemId()) {
|
||||||
|
case ACTION_COPY:
|
||||||
|
String selectedText = getSelectedText();
|
||||||
|
terminalView.mTermSession.onCopyTextToClipboard(selectedText);
|
||||||
|
terminalView.stopTextSelectionMode();
|
||||||
|
break;
|
||||||
|
case ACTION_PASTE:
|
||||||
|
terminalView.stopTextSelectionMode();
|
||||||
|
terminalView.mTermSession.onPasteTextFromClipboard();
|
||||||
|
break;
|
||||||
|
case ACTION_MORE:
|
||||||
|
// We first store the selected text in case TerminalViewClient needs the
|
||||||
|
// selected text before MORE button was pressed since we are going to
|
||||||
|
// stop selection mode
|
||||||
|
mStoredSelectedText = getSelectedText();
|
||||||
|
// The text selection needs to be stopped before showing context menu,
|
||||||
|
// otherwise handles will show above popup
|
||||||
|
terminalView.stopTextSelectionMode();
|
||||||
|
terminalView.showContextMenu();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDestroyActionMode(ActionMode mode) {
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
mActionMode = terminalView.startActionMode(new ActionMode.Callback2() {
|
||||||
|
@Override
|
||||||
|
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
|
||||||
|
return callback.onCreateActionMode(mode, menu);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
|
||||||
|
return callback.onActionItemClicked(mode, item);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDestroyActionMode(ActionMode mode) {
|
||||||
|
// Ignore.
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
|
||||||
|
int x1 = Math.round(mSelX1 * terminalView.mRenderer.getFontWidth());
|
||||||
|
int x2 = Math.round(mSelX2 * terminalView.mRenderer.getFontWidth());
|
||||||
|
int y1 = Math.round((mSelY1 - 1 - terminalView.getTopRow()) * terminalView.mRenderer.getFontLineSpacing());
|
||||||
|
int y2 = Math.round((mSelY2 + 1 - terminalView.getTopRow()) * terminalView.mRenderer.getFontLineSpacing());
|
||||||
|
|
||||||
|
if (x1 > x2) {
|
||||||
|
int tmp = x1;
|
||||||
|
x1 = x2;
|
||||||
|
x2 = tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
int terminalBottom = terminalView.getBottom();
|
||||||
|
int top = y1 + mHandleHeight;
|
||||||
|
int bottom = y2 + mHandleHeight;
|
||||||
|
if (top > terminalBottom) top = terminalBottom;
|
||||||
|
if (bottom > terminalBottom) bottom = terminalBottom;
|
||||||
|
|
||||||
|
outRect.set(x1, top, x2, bottom);
|
||||||
|
}
|
||||||
|
}, ActionMode.TYPE_FLOATING);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void updatePosition(TextSelectionHandleView handle, int x, int y) {
|
||||||
|
TerminalBuffer screen = terminalView.mEmulator.getScreen();
|
||||||
|
final int scrollRows = screen.getActiveRows() - terminalView.mEmulator.mRows;
|
||||||
|
if (handle == mStartHandle) {
|
||||||
|
mSelX1 = terminalView.getCursorX(x);
|
||||||
|
mSelY1 = terminalView.getCursorY(y);
|
||||||
|
if (mSelX1 < 0) {
|
||||||
|
mSelX1 = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mSelY1 < -scrollRows) {
|
||||||
|
mSelY1 = -scrollRows;
|
||||||
|
|
||||||
|
} else if (mSelY1 > terminalView.mEmulator.mRows - 1) {
|
||||||
|
mSelY1 = terminalView.mEmulator.mRows - 1;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mSelY1 > mSelY2) {
|
||||||
|
mSelY1 = mSelY2;
|
||||||
|
}
|
||||||
|
if (mSelY1 == mSelY2 && mSelX1 > mSelX2) {
|
||||||
|
mSelX1 = mSelX2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!terminalView.mEmulator.isAlternateBufferActive()) {
|
||||||
|
int topRow = terminalView.getTopRow();
|
||||||
|
|
||||||
|
if (mSelY1 <= topRow) {
|
||||||
|
topRow--;
|
||||||
|
if (topRow < -scrollRows) {
|
||||||
|
topRow = -scrollRows;
|
||||||
|
}
|
||||||
|
} else if (mSelY1 >= topRow + terminalView.mEmulator.mRows) {
|
||||||
|
topRow++;
|
||||||
|
if (topRow > 0) {
|
||||||
|
topRow = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
terminalView.setTopRow(topRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
mSelX1 = getValidCurX(screen, mSelY1, mSelX1);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
mSelX2 = terminalView.getCursorX(x);
|
||||||
|
mSelY2 = terminalView.getCursorY(y);
|
||||||
|
if (mSelX2 < 0) {
|
||||||
|
mSelX2 = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mSelY2 < -scrollRows) {
|
||||||
|
mSelY2 = -scrollRows;
|
||||||
|
} else if (mSelY2 > terminalView.mEmulator.mRows - 1) {
|
||||||
|
mSelY2 = terminalView.mEmulator.mRows - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mSelY1 > mSelY2) {
|
||||||
|
mSelY2 = mSelY1;
|
||||||
|
}
|
||||||
|
if (mSelY1 == mSelY2 && mSelX1 > mSelX2) {
|
||||||
|
mSelX2 = mSelX1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!terminalView.mEmulator.isAlternateBufferActive()) {
|
||||||
|
int topRow = terminalView.getTopRow();
|
||||||
|
|
||||||
|
if (mSelY2 <= topRow) {
|
||||||
|
topRow--;
|
||||||
|
if (topRow < -scrollRows) {
|
||||||
|
topRow = -scrollRows;
|
||||||
|
}
|
||||||
|
} else if (mSelY2 >= topRow + terminalView.mEmulator.mRows) {
|
||||||
|
topRow++;
|
||||||
|
if (topRow > 0) {
|
||||||
|
topRow = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
terminalView.setTopRow(topRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
mSelX2 = getValidCurX(screen, mSelY2, mSelX2);
|
||||||
|
}
|
||||||
|
|
||||||
|
terminalView.invalidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getValidCurX(TerminalBuffer screen, int cy, int cx) {
|
||||||
|
String line = screen.getSelectedText(0, cy, cx, cy);
|
||||||
|
if (!TextUtils.isEmpty(line)) {
|
||||||
|
int col = 0;
|
||||||
|
for (int i = 0, len = line.length(); i < len; i++) {
|
||||||
|
char ch1 = line.charAt(i);
|
||||||
|
if (ch1 == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
int wc;
|
||||||
|
if (Character.isHighSurrogate(ch1) && i + 1 < len) {
|
||||||
|
char ch2 = line.charAt(++i);
|
||||||
|
wc = WcWidth.width(Character.toCodePoint(ch1, ch2));
|
||||||
|
} else {
|
||||||
|
wc = WcWidth.width(ch1);
|
||||||
|
}
|
||||||
|
|
||||||
|
final int cend = col + wc;
|
||||||
|
if (cx > col && cx < cend) {
|
||||||
|
return cend;
|
||||||
|
}
|
||||||
|
if (cend == col) {
|
||||||
|
return col;
|
||||||
|
}
|
||||||
|
col = cend;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void decrementYTextSelectionCursors(int decrement) {
|
||||||
|
mSelY1 -= decrement;
|
||||||
|
mSelY2 -= decrement;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean onTouchEvent(MotionEvent event) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void onTouchModeChanged(boolean isInTouchMode) {
|
||||||
|
if (!isInTouchMode) {
|
||||||
|
terminalView.stopTextSelectionMode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDetached() {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isActive() {
|
||||||
|
return mIsSelectingText;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void getSelectors(int[] sel) {
|
||||||
|
if (sel == null || sel.length != 4) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sel[0] = mSelY1;
|
||||||
|
sel[1] = mSelY2;
|
||||||
|
sel[2] = mSelX1;
|
||||||
|
sel[3] = mSelX2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the currently selected text. */
|
||||||
|
public String getSelectedText() {
|
||||||
|
return terminalView.mEmulator.getSelectedText(mSelX1, mSelY1, mSelX2, mSelY2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the selected text stored before "MORE" button was pressed on the context menu. */
|
||||||
|
@Nullable
|
||||||
|
public String getStoredSelectedText() {
|
||||||
|
return mStoredSelectedText;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unset the selected text stored before "MORE" button was pressed on the context menu. */
|
||||||
|
public void unsetStoredSelectedText() {
|
||||||
|
mStoredSelectedText = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ActionMode getActionMode() {
|
||||||
|
return mActionMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return true if this controller is currently used to move the start selection.
|
||||||
|
*/
|
||||||
|
public boolean isSelectionStartDragged() {
|
||||||
|
return mStartHandle.isDragging();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return true if this controller is currently used to move the end selection.
|
||||||
|
*/
|
||||||
|
public boolean isSelectionEndDragged() {
|
||||||
|
return mEndHandle.isDragging();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
package com.termux.view.textselection;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.graphics.Canvas;
|
||||||
|
import android.graphics.Rect;
|
||||||
|
import android.graphics.drawable.Drawable;
|
||||||
|
import android.os.SystemClock;
|
||||||
|
import android.view.MotionEvent;
|
||||||
|
import android.view.View;
|
||||||
|
import android.view.ViewGroup;
|
||||||
|
import android.view.ViewParent;
|
||||||
|
import android.view.WindowManager;
|
||||||
|
import android.widget.PopupWindow;
|
||||||
|
|
||||||
|
import com.doubao.lynxclone.R;
|
||||||
|
import com.termux.view.TerminalView;
|
||||||
|
|
||||||
|
@SuppressLint("ViewConstructor")
|
||||||
|
public class TextSelectionHandleView extends View {
|
||||||
|
private final TerminalView terminalView;
|
||||||
|
private PopupWindow mHandle;
|
||||||
|
private final CursorController mCursorController;
|
||||||
|
|
||||||
|
private final Drawable mHandleLeftDrawable;
|
||||||
|
private final Drawable mHandleRightDrawable;
|
||||||
|
private Drawable mHandleDrawable;
|
||||||
|
|
||||||
|
private boolean mIsDragging;
|
||||||
|
|
||||||
|
final int[] mTempCoords = new int[2];
|
||||||
|
Rect mTempRect;
|
||||||
|
|
||||||
|
private int mPointX;
|
||||||
|
private int mPointY;
|
||||||
|
private float mTouchToWindowOffsetX;
|
||||||
|
private float mTouchToWindowOffsetY;
|
||||||
|
private float mHotspotX;
|
||||||
|
private float mHotspotY;
|
||||||
|
private float mTouchOffsetY;
|
||||||
|
private int mLastParentX;
|
||||||
|
private int mLastParentY;
|
||||||
|
|
||||||
|
private int mHandleHeight;
|
||||||
|
private int mHandleWidth;
|
||||||
|
|
||||||
|
private final int mInitialOrientation;
|
||||||
|
private int mOrientation;
|
||||||
|
|
||||||
|
public static final int LEFT = 0;
|
||||||
|
public static final int RIGHT = 2;
|
||||||
|
|
||||||
|
private long mLastTime;
|
||||||
|
|
||||||
|
public TextSelectionHandleView(TerminalView terminalView, CursorController cursorController, int initialOrientation) {
|
||||||
|
super(terminalView.getContext());
|
||||||
|
this.terminalView = terminalView;
|
||||||
|
mCursorController = cursorController;
|
||||||
|
mInitialOrientation = initialOrientation;
|
||||||
|
|
||||||
|
mHandleLeftDrawable = getContext().getDrawable(R.drawable.text_select_handle_left_material);
|
||||||
|
mHandleRightDrawable = getContext().getDrawable(R.drawable.text_select_handle_right_material);
|
||||||
|
|
||||||
|
setOrientation(mInitialOrientation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initHandle() {
|
||||||
|
mHandle = new PopupWindow(terminalView.getContext(), null,
|
||||||
|
android.R.attr.textSelectHandleWindowStyle);
|
||||||
|
mHandle.setSplitTouchEnabled(true);
|
||||||
|
mHandle.setClippingEnabled(false);
|
||||||
|
mHandle.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
|
||||||
|
mHandle.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||||
|
mHandle.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||||
|
mHandle.setBackgroundDrawable(null);
|
||||||
|
mHandle.setAnimationStyle(0);
|
||||||
|
mHandle.setEnterTransition(null);
|
||||||
|
mHandle.setExitTransition(null);
|
||||||
|
mHandle.setContentView(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOrientation(int orientation) {
|
||||||
|
mOrientation = orientation;
|
||||||
|
int handleWidth = 0;
|
||||||
|
switch (orientation) {
|
||||||
|
case LEFT: {
|
||||||
|
mHandleDrawable = mHandleLeftDrawable;
|
||||||
|
handleWidth = mHandleDrawable.getIntrinsicWidth();
|
||||||
|
mHotspotX = (handleWidth * 3) / (float) 4;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case RIGHT: {
|
||||||
|
mHandleDrawable = mHandleRightDrawable;
|
||||||
|
handleWidth = mHandleDrawable.getIntrinsicWidth();
|
||||||
|
mHotspotX = handleWidth / (float) 4;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mHandleHeight = mHandleDrawable.getIntrinsicHeight();
|
||||||
|
|
||||||
|
mHandleWidth = handleWidth;
|
||||||
|
mTouchOffsetY = -mHandleHeight * 0.3f;
|
||||||
|
mHotspotY = 0;
|
||||||
|
invalidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void show() {
|
||||||
|
if (!isPositionVisible()) {
|
||||||
|
hide();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// We remove handle from its parent first otherwise the following exception may be thrown
|
||||||
|
// java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
|
||||||
|
removeFromParent();
|
||||||
|
|
||||||
|
initHandle(); // init the handle
|
||||||
|
invalidate(); // invalidate to make sure onDraw is called
|
||||||
|
|
||||||
|
final int[] coords = mTempCoords;
|
||||||
|
terminalView.getLocationInWindow(coords);
|
||||||
|
coords[0] += mPointX;
|
||||||
|
coords[1] += mPointY;
|
||||||
|
|
||||||
|
if (mHandle != null)
|
||||||
|
mHandle.showAtLocation(terminalView, 0, coords[0], coords[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void hide() {
|
||||||
|
mIsDragging = false;
|
||||||
|
|
||||||
|
if (mHandle != null) {
|
||||||
|
mHandle.dismiss();
|
||||||
|
|
||||||
|
// We remove handle from its parent, otherwise it may still be shown in some cases even after the dismiss call
|
||||||
|
removeFromParent();
|
||||||
|
mHandle = null; // garbage collect the handle
|
||||||
|
}
|
||||||
|
invalidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void removeFromParent() {
|
||||||
|
if (!isParentNull()) {
|
||||||
|
((ViewGroup)this.getParent()).removeView(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void positionAtCursor(final int cx, final int cy, boolean forceOrientationCheck) {
|
||||||
|
int x = terminalView.getPointX(cx);
|
||||||
|
int y = terminalView.getPointY(cy + 1);
|
||||||
|
moveTo(x, y, forceOrientationCheck);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void moveTo(int x, int y, boolean forceOrientationCheck) {
|
||||||
|
float oldHotspotX = mHotspotX;
|
||||||
|
checkChangedOrientation(x, forceOrientationCheck);
|
||||||
|
mPointX = (int) (x - (isShowing() ? oldHotspotX : mHotspotX));
|
||||||
|
mPointY = y;
|
||||||
|
|
||||||
|
if (isPositionVisible()) {
|
||||||
|
int[] coords = null;
|
||||||
|
|
||||||
|
if (isShowing()) {
|
||||||
|
coords = mTempCoords;
|
||||||
|
terminalView.getLocationInWindow(coords);
|
||||||
|
int x1 = coords[0] + mPointX;
|
||||||
|
int y1 = coords[1] + mPointY;
|
||||||
|
if (mHandle != null)
|
||||||
|
mHandle.update(x1, y1, getWidth(), getHeight());
|
||||||
|
} else {
|
||||||
|
show();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mIsDragging) {
|
||||||
|
if (coords == null) {
|
||||||
|
coords = mTempCoords;
|
||||||
|
terminalView.getLocationInWindow(coords);
|
||||||
|
}
|
||||||
|
if (coords[0] != mLastParentX || coords[1] != mLastParentY) {
|
||||||
|
mTouchToWindowOffsetX += coords[0] - mLastParentX;
|
||||||
|
mTouchToWindowOffsetY += coords[1] - mLastParentY;
|
||||||
|
mLastParentX = coords[0];
|
||||||
|
mLastParentY = coords[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
hide();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void changeOrientation(int orientation) {
|
||||||
|
if (mOrientation != orientation) {
|
||||||
|
setOrientation(orientation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkChangedOrientation(int posX, boolean force) {
|
||||||
|
if (!mIsDragging && !force) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long millis = SystemClock.currentThreadTimeMillis();
|
||||||
|
if (millis - mLastTime < 50 && !force) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
mLastTime = millis;
|
||||||
|
|
||||||
|
final TerminalView hostView = terminalView;
|
||||||
|
final int left = hostView.getLeft();
|
||||||
|
final int right = hostView.getWidth();
|
||||||
|
final int top = hostView.getTop();
|
||||||
|
final int bottom = hostView.getHeight();
|
||||||
|
|
||||||
|
if (mTempRect == null) {
|
||||||
|
mTempRect = new Rect();
|
||||||
|
}
|
||||||
|
final Rect clip = mTempRect;
|
||||||
|
clip.left = left + terminalView.getPaddingLeft();
|
||||||
|
clip.top = top + terminalView.getPaddingTop();
|
||||||
|
clip.right = right - terminalView.getPaddingRight();
|
||||||
|
clip.bottom = bottom - terminalView.getPaddingBottom();
|
||||||
|
|
||||||
|
final ViewParent parent = hostView.getParent();
|
||||||
|
if (parent == null || !parent.getChildVisibleRect(hostView, clip, null)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (posX - mHandleWidth < clip.left) {
|
||||||
|
changeOrientation(RIGHT);
|
||||||
|
} else if (posX + mHandleWidth > clip.right) {
|
||||||
|
changeOrientation(LEFT);
|
||||||
|
} else {
|
||||||
|
changeOrientation(mInitialOrientation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isPositionVisible() {
|
||||||
|
// Always show a dragging handle.
|
||||||
|
if (mIsDragging) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
final TerminalView hostView = terminalView;
|
||||||
|
final int left = 0;
|
||||||
|
final int right = hostView.getWidth();
|
||||||
|
final int top = 0;
|
||||||
|
final int bottom = hostView.getHeight();
|
||||||
|
|
||||||
|
if (mTempRect == null) {
|
||||||
|
mTempRect = new Rect();
|
||||||
|
}
|
||||||
|
final Rect clip = mTempRect;
|
||||||
|
clip.left = left + terminalView.getPaddingLeft();
|
||||||
|
clip.top = top + terminalView.getPaddingTop();
|
||||||
|
clip.right = right - terminalView.getPaddingRight();
|
||||||
|
clip.bottom = bottom - terminalView.getPaddingBottom();
|
||||||
|
|
||||||
|
final ViewParent parent = hostView.getParent();
|
||||||
|
if (parent == null || !parent.getChildVisibleRect(hostView, clip, null)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
final int[] coords = mTempCoords;
|
||||||
|
hostView.getLocationInWindow(coords);
|
||||||
|
final int posX = coords[0] + mPointX + (int) mHotspotX;
|
||||||
|
final int posY = coords[1] + mPointY + (int) mHotspotY;
|
||||||
|
|
||||||
|
return posX >= clip.left && posX <= clip.right &&
|
||||||
|
posY >= clip.top && posY <= clip.bottom;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDraw(Canvas c) {
|
||||||
|
final int width = mHandleDrawable.getIntrinsicWidth();
|
||||||
|
int height = mHandleDrawable.getIntrinsicHeight();
|
||||||
|
mHandleDrawable.setBounds(0, 0, width, height);
|
||||||
|
mHandleDrawable.draw(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("ClickableViewAccessibility")
|
||||||
|
@Override
|
||||||
|
public boolean onTouchEvent(MotionEvent event) {
|
||||||
|
terminalView.updateFloatingToolbarVisibility(event);
|
||||||
|
switch (event.getActionMasked()) {
|
||||||
|
case MotionEvent.ACTION_DOWN: {
|
||||||
|
final float rawX = event.getRawX();
|
||||||
|
final float rawY = event.getRawY();
|
||||||
|
mTouchToWindowOffsetX = rawX - mPointX;
|
||||||
|
mTouchToWindowOffsetY = rawY - mPointY;
|
||||||
|
final int[] coords = mTempCoords;
|
||||||
|
terminalView.getLocationInWindow(coords);
|
||||||
|
mLastParentX = coords[0];
|
||||||
|
mLastParentY = coords[1];
|
||||||
|
mIsDragging = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case MotionEvent.ACTION_MOVE: {
|
||||||
|
final float rawX = event.getRawX();
|
||||||
|
final float rawY = event.getRawY();
|
||||||
|
|
||||||
|
final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
|
||||||
|
final float newPosY = rawY - mTouchToWindowOffsetY + mHotspotY + mTouchOffsetY;
|
||||||
|
|
||||||
|
mCursorController.updatePosition(this, Math.round(newPosX), Math.round(newPosY));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case MotionEvent.ACTION_UP:
|
||||||
|
case MotionEvent.ACTION_CANCEL:
|
||||||
|
mIsDragging = false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
|
||||||
|
setMeasuredDimension(mHandleDrawable.getIntrinsicWidth(),
|
||||||
|
mHandleDrawable.getIntrinsicHeight());
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getHandleHeight() {
|
||||||
|
return mHandleHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getHandleWidth() {
|
||||||
|
return mHandleWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isShowing() {
|
||||||
|
if (mHandle != null)
|
||||||
|
return mHandle.isShowing();
|
||||||
|
else
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isParentNull() {
|
||||||
|
return this.getParent() == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isDragging() {
|
||||||
|
return mIsDragging;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
BIN
android/app/src/main/jniLibs/arm64-v8a/libtermux.so
Normal file
BIN
android/app/src/main/jniLibs/x86_64/libtermux.so
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="48dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="132"
|
||||||
|
android:viewportHeight="66">
|
||||||
|
<path
|
||||||
|
android:pathData="M52.3,1.6c-5.7,2.1 -12.9,8.6 -16,14.8 -2.2,4.1 -2.8,6.9 -3.1,14.3 -0.6,12.6 1.3,17.8 9.3,25.8 8,8 13.2,9.9 25.8,9.3 11.1,-0.5 17.3,-3.2 23.5,-10.3 6.5,-7.4 7.2,-10.8 7.2,-34.7l0,-20.8 -21.2,0.1c-16.1,-0 -22.3,0.4 -25.5,1.5z"
|
||||||
|
android:fillColor="#2196F3"
|
||||||
|
android:strokeColor="#00000000"/>
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="48dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="132"
|
||||||
|
android:viewportHeight="66">
|
||||||
|
<path
|
||||||
|
android:pathData="M33,20.8c0,23.9 0.7,27.3 7.2,34.7 6.2,7.1 12.4,9.8 23.5,10.3 12.6,0.6 17.8,-1.3 25.8,-9.3 8,-8 9.9,-13.2 9.3,-25.8 -0.5,-11.1 -3.2,-17.3 -10.3,-23.5 -7.4,-6.5 -10.8,-7.2 -34.7,-7.2l-20.8,-0 0,20.8z"
|
||||||
|
android:fillColor="#2196F3"
|
||||||
|
android:strokeColor="#00000000"/>
|
||||||
|
</vector>
|
||||||
BIN
android/app/src/main/res/mipmap-hdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 9.1 KiB |
BIN
android/app/src/main/res/mipmap-mdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 4.7 KiB |
BIN
android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 27 KiB |
BIN
android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
4
android/app/src/main/res/values/strings.xml
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="app_name">豆包</string>
|
||||||
|
</resources>
|
||||||
10
android/app/src/main/res/values/termux_strings.xml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!--
|
||||||
|
来自 Termux 的 terminal-view 模块(Apache-2.0)。
|
||||||
|
单独放一个文件,避免和本 App 自己的 strings.xml 互相覆盖。
|
||||||
|
-->
|
||||||
|
<resources>
|
||||||
|
<string name="paste_text">粘贴</string>
|
||||||
|
<string name="copy_text">复制</string>
|
||||||
|
<string name="text_selection_more">更多…</string>
|
||||||
|
</resources>
|
||||||
9
android/app/src/main/res/values/themes.xml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<!-- 用系统 Material 主题,省掉 AppCompat 依赖 -->
|
||||||
|
<style name="AppTheme" parent="@android:style/Theme.Material.Light.NoActionBar">
|
||||||
|
<item name="android:windowBackground">@android:color/white</item>
|
||||||
|
<item name="android:statusBarColor">#FFFFFF</item>
|
||||||
|
<item name="android:windowLightStatusBar">true</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
9
android/build.gradle.kts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
// 顶层构建脚本:只声明插件版本
|
||||||
|
plugins {
|
||||||
|
id("com.android.application") version "8.7.3" apply false
|
||||||
|
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
|
||||||
|
// Kotlin 2.0 起 Compose 编译器是独立插件
|
||||||
|
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
|
||||||
|
// Chaquopy:把 CPython 嵌进 APK,跑 Python 内核与 Python 工具
|
||||||
|
id("com.chaquo.python") version "17.0.0" apply false
|
||||||
|
}
|
||||||
6
android/gradle.properties
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx2560m -Dfile.encoding=UTF-8
|
||||||
|
org.gradle.parallel=true
|
||||||
|
org.gradle.caching=true
|
||||||
|
android.useAndroidX=true
|
||||||
|
android.nonTransitiveRClass=true
|
||||||
|
kotlin.code.style=official
|
||||||
298
android/kernel/README.md
Normal file
@@ -0,0 +1,298 @@
|
|||||||
|
# 豆鲍 AI 内核 · Python 版(安卓 / Chaquopy)
|
||||||
|
|
||||||
|
这是 Node 版内核(`server/src/*.mjs`)的 **纯 Python 重写**,接口逐字段对齐,
|
||||||
|
所以 **Lynx 前端一行都不用改**,只要把 `apiBase` 指到这个内核就能在安卓上跑。
|
||||||
|
|
||||||
|
- **只用标准库**:`http.server` / `ThreadingHTTPServer` / `urllib.request` / `json` / `threading` / `subprocess`。
|
||||||
|
没有 flask / fastapi / aiohttp,也没有官方 `mcp` 包 —— 安卓 APK 里少打几百 KB,也少一堆装不上的依赖。
|
||||||
|
- **能不靠安卓直接跑**(Windows/macOS/Linux 都行),方便调试:
|
||||||
|
```bash
|
||||||
|
python android/kernel/main.py --port 5399 --data-dir <临时目录> --tools-dir tools
|
||||||
|
```
|
||||||
|
- **也能当库被安卓调用**(Chaquopy):
|
||||||
|
```python
|
||||||
|
from main import start_kernel
|
||||||
|
handle = start_kernel(port=0, data_dir='/data/data/<包名>/files', tools_dir='<工具目录>')
|
||||||
|
print(handle.port) # 实际端口(port=0 时系统分配)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 文件职责
|
||||||
|
|
||||||
|
| 文件 | 对应 Node 版 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `main.py` | `index.mjs` 的 `startKernel` | 入口:命令行参数、启动 HTTP、优雅退出 |
|
||||||
|
| `app.py` | `index.mjs` | 路由 / SSE / 静态托管 / CORS,全部接口都在这里 |
|
||||||
|
| `providers.py` | `providers.mjs` | 上游 OpenAI 兼容调用(`urllib` 流式 SSE、参数归一化、思考强度映射) |
|
||||||
|
| `agent_loop.py` | `agent.mjs` 的 `runAgent` | 系统提示词 + 多轮工具循环 + 事件流 |
|
||||||
|
| `tools_runtime.py` | `python-tools.mjs` + `agent.mjs` 工具部分 | 工具发现(importlib)、执行、安全模式过滤 |
|
||||||
|
| `builtin_tools.py` | —(安卓专用) | 内置 `shell` / `python_run`(进程内实现) |
|
||||||
|
| `mcp_client.py` | `mcp.mjs` | 手写 JSON-RPC 2.0 客户端:`http` / `stdio` / `inproc` |
|
||||||
|
| `store.py` | `config.mjs` + `store.mjs` + `agents.mjs` | 设置 / 会话 / 智能体持久化 |
|
||||||
|
| `uploads.py` | `uploads.mjs` | 附件上传、待取队列、附件→模型输入转换 |
|
||||||
|
| `defaults.py` | `config.mjs` + `agents.mjs` 常量 | 提供商预设、默认设置、内置 4 个智能体 |
|
||||||
|
| `paths.py` | `config.mjs` 路径部分 | 数据目录 / 工具目录 / 静态目录,安卓判断 |
|
||||||
|
| `__init__.py` / `__main__.py` | — | 支持 `python -m android.kernel` 与包方式导入 |
|
||||||
|
|
||||||
|
数据目录(默认由 `--data-dir` 指定)里的文件名和 Node 版一致,可以互相读:
|
||||||
|
`settings.json`、`conversations.json`、`agents.json`、`mcp.servers.json`、`uploads/`、`tmp/`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 快速开始
|
||||||
|
|
||||||
|
### Windows / 桌面调试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 仓库根目录下
|
||||||
|
python android/kernel/main.py --port 5399 --data-dir "%TEMP%\pykernel" --tools-dir "tools"
|
||||||
|
# 或者
|
||||||
|
python -m android.kernel --port 5399 --data-dir "%TEMP%\pykernel" --tools-dir tools
|
||||||
|
```
|
||||||
|
|
||||||
|
启动后可用的自检:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://127.0.0.1:5399/api/state
|
||||||
|
curl -X POST http://127.0.0.1:5399/api/tools/run -H "Content-Type: application/json" ^
|
||||||
|
-d "{\"name\":\"python_run\",\"args\":{\"code\":\"print(1+1)\"}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
参数一览:
|
||||||
|
|
||||||
|
| 参数 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `--host` | 监听地址,默认 `127.0.0.1` |
|
||||||
|
| `--port` | 监听端口,默认 5199(`0` = 系统分配,安卓推荐) |
|
||||||
|
| `--data-dir` | 可写数据目录(安卓指到 App 私有目录) |
|
||||||
|
| `--tools-dir` | 工具目录,默认仓库里的 `tools/`(运行时可被 `settings.toolsDir` 覆盖) |
|
||||||
|
| `--web-dir` / `--dist-dir` / `--web-core` | 静态托管目录(安卓上一般用不到,页面在 assets 里) |
|
||||||
|
| `--no-mcp-autostart` | 启动时不自动连 MCP 服务器 |
|
||||||
|
| `--quiet` / `--json` | 不打印日志 / 启动后打印一行 JSON(含真实端口,便于脚本拉起) |
|
||||||
|
|
||||||
|
### 安卓(Chaquopy)
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
val py = Python.getInstance()
|
||||||
|
val kernel = py.getModule("main") // android/kernel 作为 Chaquopy 源码目录
|
||||||
|
val handle = kernel.callAttr(
|
||||||
|
"start_kernel",
|
||||||
|
/* host = */ "127.0.0.1",
|
||||||
|
/* port = */ 0,
|
||||||
|
/* data_dir = */ filesDir.absolutePath,
|
||||||
|
/* tools_dir = */ File(filesDir, "tools").absolutePath,
|
||||||
|
)
|
||||||
|
val port = handle.get("port").toInt()
|
||||||
|
```
|
||||||
|
|
||||||
|
前端(`app/src/api.ts`)用 `setApiBase('http://127.0.0.1:<port>')` 或宿主页注入 `window.__DOUBAO_API__` 即可。
|
||||||
|
|
||||||
|
安卓侧还可以挂三个原生钩子(对应 Electron 的 `__doubaoClipboard` / `__doubaoPickFile` / `__doubaoReveal`):
|
||||||
|
|
||||||
|
```python
|
||||||
|
import app
|
||||||
|
app.set_native_hooks(clipboard=my_clipboard, pick_file=my_picker, reveal=my_reveal)
|
||||||
|
```
|
||||||
|
|
||||||
|
没挂钩子时 `/api/clipboard` 返回 `{ok:false, via:"none"}`、`/api/pick-file` 返回"当前环境不支持原生选文件"、`/api/mcp/reveal` 返回"当前运行方式不支持打开文件夹",和 Node 版在无钩子环境下完全一致。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 接口清单(与 Node 版逐字段一致)
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | `/api/health` | `{ok,pid,cwd}` |
|
||||||
|
| GET | `/api/state` | 设置(脱敏)+ 工具 + MCP + 会话 + 智能体 |
|
||||||
|
| PUT/POST | `/api/settings` | 合并保存设置(`apiKey='••••••••'` 表示不修改) |
|
||||||
|
| GET | `/api/models` | 拉上游模型列表,失败降级成预设 |
|
||||||
|
| GET/POST | `/api/conversations` | 列表 / 新建 |
|
||||||
|
| GET/PATCH/PUT/DELETE | `/api/conversations/<id>` | 单条会话 |
|
||||||
|
| GET | `/api/tools` | Python 工具 + MCP 状态 + `toolNames` + `suggestedAllow` |
|
||||||
|
| POST | `/api/tools/run` | 手动试运行工具(不受限制模式约束,和 Node 版一致) |
|
||||||
|
| GET | `/api/mcp` | 服务器状态 + 配置原文 + 路径 + 占位符 |
|
||||||
|
| PUT/POST | `/api/mcp/config` | 保存配置文本(先校验再落盘)并重连 |
|
||||||
|
| POST | `/api/mcp/reveal` | 打开配置目录(需要原生钩子) |
|
||||||
|
| POST | `/api/mcp/connect` `/api/mcp/disconnect` | 连接 / 断开 |
|
||||||
|
| GET/POST | `/api/agents` | 列表 / 新建 |
|
||||||
|
| PATCH/PUT/DELETE | `/api/agents/<id>` | 单个智能体 |
|
||||||
|
| POST | `/api/upload` | base64 上传(`dataUrl` 或 `base64`) |
|
||||||
|
| GET | `/api/uploads/pending` | 取走待处理附件(拖拽进窗口的文件) |
|
||||||
|
| POST | `/api/pick-file` | 原生选文件(需要钩子) |
|
||||||
|
| POST | `/api/clipboard` | 复制到剪贴板(需要钩子) |
|
||||||
|
| POST | `/api/chat` | 流式对话(SSE) |
|
||||||
|
|
||||||
|
### SSE 格式
|
||||||
|
|
||||||
|
响应头:`Content-Type: text/event-stream; charset=utf-8`,用 **chunked** 传输编码;
|
||||||
|
每条事件都是 `data: {json}\n\n`(JSON 无多余空格,中文原样输出),另发 `: connected` 与每 15 秒的 `: ping` 注释行。
|
||||||
|
|
||||||
|
事件类型(字段名与 Node 版相同):
|
||||||
|
|
||||||
|
```
|
||||||
|
start {provider, model, tools, mode, thinkingLevel, agent}
|
||||||
|
delta {text, round}
|
||||||
|
reasoning {text, round}
|
||||||
|
tool_call {id, name, args}
|
||||||
|
tool_result{id, name, ok, result}
|
||||||
|
done {content, reasoning, rounds, toolCalls, usage[, truncated]}
|
||||||
|
saved {conversationId, title}
|
||||||
|
error {message}
|
||||||
|
```
|
||||||
|
|
||||||
|
静态托管同样保留:`/`(`web/index.html`)、`/main.web.bundle`、`/lynx-web/*`、`/static/*`、`/uploads/*`、`app/dist` 下的其它文件。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 工具运行时(安卓的关键取舍)
|
||||||
|
|
||||||
|
**用 `importlib` 直接 import 工具模块,不用 `subprocess` 调 python。**
|
||||||
|
|
||||||
|
Node 版是 `python tool.py --spec`(发现)和 `python tool.py --input args.json`(执行),
|
||||||
|
桌面上一定有解释器所以没问题;**安卓(Chaquopy)里没有独立的 python 可执行文件**,
|
||||||
|
`spawn('python')` 必定 ENOENT。所以这里改成:
|
||||||
|
|
||||||
|
```python
|
||||||
|
spec = importlib.util.spec_from_file_location(唯一模块名, "<tools>/calc.py")
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module) # 执行模块,拿到 TOOL 和 run
|
||||||
|
result = module.run(args) # 直接调用
|
||||||
|
```
|
||||||
|
|
||||||
|
要点:
|
||||||
|
|
||||||
|
- 扫描 `toolsDir` 下的 `*.py`,跳过 `_` 开头的文件(`_protocol.py` 这类辅助模块);
|
||||||
|
- 按 mtime 缓存模块(改文件后自动重新 import);
|
||||||
|
- `toolsDir` 取 `settings.toolsDir`(存在时),否则用 `--tools-dir` / `DOUBAO_TOOLS` / 仓库 `tools/`;
|
||||||
|
- 执行有 **60 秒超时**:用「线程 + join(timeout)」实现。CPython 杀不掉线程,
|
||||||
|
超时后只能放弃等待(被放弃的线程会在后台跑完),这一点在返回的错误里写明了;
|
||||||
|
- 工具抛异常 → 返回 `{"ok":false,"error":"ValueError: xxx"}`,格式和 `_protocol.py` 一致;
|
||||||
|
- **内置工具优先**:`builtin_tools.py` 里的 `shell` / `python_run` 会覆盖同名的文件工具
|
||||||
|
(安卓上这两个必须走进程内实现)。`/api/state.python.tools` 里它们的 `file` 仍是
|
||||||
|
`shell.py` / `python_run.py`(保持和 Node 版逐字段一致),并额外带一个 `builtin: true` 便于识别。
|
||||||
|
|
||||||
|
### 内置 `shell`
|
||||||
|
|
||||||
|
`subprocess.run([shell, '-c', command])`:Windows 用 `cmd /c`,其它平台用 `/bin/sh -c`
|
||||||
|
(安卓上 `/bin/sh` 不存在时退回 `/system/bin/sh`)。带超时(默认 30s,上限 300s)、
|
||||||
|
工作目录校验、和 `tools/shell.py` 完全相同的黑名单(`DOUBAO_SHELL_UNSAFE=1` 可关闭)。
|
||||||
|
|
||||||
|
### 内置 `python_run`
|
||||||
|
|
||||||
|
**在内核进程内 exec 用户代码**,`contextlib.redirect_stdout/redirect_stderr` 捕获输出,
|
||||||
|
`sys.stdin` 手动换成 `io.StringIO(stdin)`(标准库只有 redirect_stdout/stderr,没有 redirect_stdin)。
|
||||||
|
`SystemExit` 的 code 当退出码,其它异常打印 traceback 到 stderr。
|
||||||
|
`action=libs` 列出 requests/httpx/urllib3 等常用库是否可用。
|
||||||
|
|
||||||
|
> ⚠️ 安全提示:进程内 exec 意味着用户代码和内核同进程、同权限,
|
||||||
|
> 既没有子进程隔离也无法强杀线程。安卓上没有更好的选择,
|
||||||
|
> 真要限制请把 `settings.security.mode` 设为 `restricted` 并只放行白名单工具。
|
||||||
|
|
||||||
|
### 安全模式
|
||||||
|
|
||||||
|
- `open`:所有工具都交给模型;
|
||||||
|
- `restricted`:只有 `security.allow` 里的工具可用 —— **两道拦截**(和 Node 版一致):
|
||||||
|
喂给模型的 `tools` 列表先过滤一道,`execute_tool()` 里再拦一道(模型硬编工具名也没用)。
|
||||||
|
- `/api/state`、`/api/tools` 的列表**不**过滤,只有 `toolNames` / `suggestedAllow` 照旧全给(与 Node 版相同)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. MCP 客户端
|
||||||
|
|
||||||
|
配置在 `<数据目录>/mcp.servers.json`(首次运行会从 `<toolsDir>/mcp.servers.json` 复制一份),
|
||||||
|
支持 `${VAR}` 占位符(`DOUBAO_DATA` 一定可用,指向数据目录)。工具名统一为 `mcp__<server>__<tool>`。
|
||||||
|
|
||||||
|
### 三种传输
|
||||||
|
|
||||||
|
**`http`(Streamable HTTP)**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "remote", "transport": "http", "url": "https://host/mcp",
|
||||||
|
"headers": { "Authorization": "Bearer ${MY_TOKEN}" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
POST JSON-RPC,`Accept: application/json, text/event-stream` 两个都带;
|
||||||
|
回包是 JSON 就直接解析,是 SSE 就在流里找本次请求 id 的响应;
|
||||||
|
响应头里的 `Mcp-Session-Id` 会记下来并在后续请求回传。
|
||||||
|
|
||||||
|
**`stdio`(桌面可用,安卓不可用)**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "fs", "transport": "stdio", "command": "npx",
|
||||||
|
"args": ["-y", "@modelcontextprotocol/server-filesystem", "${DOUBAO_DATA}"], "env": {} }
|
||||||
|
```
|
||||||
|
|
||||||
|
Windows 下 `npx/npm/node/pnpm/yarn` 会自动用 `cmd /c` 包一层。
|
||||||
|
**安卓上构造传输时就直接报错**并提示改用 `inproc`/`http`,而不是卡在那里等超时。
|
||||||
|
|
||||||
|
**`inproc`(安卓专用,桌面也能用,方便测试)**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "my-tools", "transport": "inproc", "file": "/sdcard/Android/data/<包名>/files/tools/my_mcp_server.py" }
|
||||||
|
```
|
||||||
|
|
||||||
|
(`file` 也可以写成 `path` / `script`。)内核用 `importlib` 导入这个 `.py`,
|
||||||
|
通过**内存管道(`queue.Queue` + 工作线程)**跑 JSON-RPC,模块只需暴露:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def handle(request: dict) -> dict:
|
||||||
|
"""request 是完整的 JSON-RPC 2.0 请求;返回响应(或只返回 {"result": ...} / 结果对象)"""
|
||||||
|
method = request.get("method")
|
||||||
|
if method == "tools/list":
|
||||||
|
return {"result": {"tools": [
|
||||||
|
{"name": "echo", "description": "回显", "inputSchema": {
|
||||||
|
"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}
|
||||||
|
]}}
|
||||||
|
if method == "tools/call":
|
||||||
|
args = (request.get("params") or {}).get("arguments") or {}
|
||||||
|
return {"result": {"content": [{"type": "text", "text": args.get("text", "")}]}}
|
||||||
|
return {"error": {"code": -32601, "message": f"method not found: {method}"}}
|
||||||
|
```
|
||||||
|
|
||||||
|
- 只有**带 id 的请求**会交给 `handle`;通知(`notifications/initialized` 等)直接跳过,
|
||||||
|
所以最小实现只要认 `initialize` / `tools/list` / `tools/call`;
|
||||||
|
- `initialize` 的报错会被容忍(有些最小实现不认它),`tools/list` 失败才算连接失败;
|
||||||
|
- `async def handle` 也支持(内核会用 `asyncio.run` 跑)。
|
||||||
|
|
||||||
|
### schema 清洗
|
||||||
|
|
||||||
|
`inputSchema` → OpenAI 的 `parameters` 时:删 `$schema`、删 `outputSchema`、强制 `type=object`、
|
||||||
|
补 `properties`/`required`(`required` 缺失时取 `properties` 里 `required:true` 的键)、
|
||||||
|
补 `additionalProperties=false`。
|
||||||
|
|
||||||
|
### 传输支持情况
|
||||||
|
|
||||||
|
| transport | Windows/桌面 | 安卓 | 备注 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `http` | ✅ 已实测 | ✅ | |
|
||||||
|
| `stdio` | ✅ | ❌ 明确报错 | 安卓没有独立可执行文件,也无法 fork |
|
||||||
|
| `inproc` | ✅ 已实测 | ✅ | 安卓主力方案 |
|
||||||
|
| `sse`(旧版 HTTP+SSE) | ❌ 明确报错 | ❌ | Node 版有;Python 版未实现,请用 `http` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 与 Node 版的有意差异
|
||||||
|
|
||||||
|
1. **`shell` / `python_run` 是进程内实现**(安卓没有子进程),所以 `/api/state.python.tools`
|
||||||
|
里多了 `builtin: true` 字段;`file` 字段仍是同名文件名,前端显示不变。
|
||||||
|
2. **`transport: "inproc"`** 是 Python 版新增的(安卓专用);配置校验也接受它。
|
||||||
|
3. **`sse` 传输未实现**,连接时给出明确报错(配置校验仍允许 `sse`,以免老配置文件判为非法)。
|
||||||
|
4. **`/lynx-web/*` 找不到文件时返回 404**:Node 版这里因为 `serveFile(...) || true` 的写法,
|
||||||
|
文件不存在时既不回 404 也不结束响应(请求会挂住),Python 版按正常 404 处理。
|
||||||
|
5. **`setting.pythonBin` 字段保留但不再使用**:进程内执行不需要解释器,仅为前后端字段兼容。
|
||||||
|
6. **`interpreter` 字段**返回 `sys.executable`(安卓上可能是空串时显示 `<进程内>`),语义和 Node 版一致("当前解释器")。
|
||||||
|
7. **`/api/models` 的失败信息**里错误串会略有不同(`上游 404:…` 与 Node 版相同格式,但网络层异常文案来自 Python)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 已知限制 / 未在真机验证
|
||||||
|
|
||||||
|
- **未在真实安卓设备(Chaquopy)上跑过**:`IS_ANDROID` 判定、`/bin/sh` 回退、
|
||||||
|
inproc 传输都用模拟方式验证(见 `paths.IS_ANDROID = True` 的测试),真机仍需一次实跑。
|
||||||
|
- 进程内执行的两点固有限制:`python_run` 超时后线程仍在后台跑;
|
||||||
|
`redirect_stdout` / `chdir` 是进程级的,并发执行多个 `python_run` 时输出可能串到一起。
|
||||||
|
(内核是单用户本地服务,影响有限。)
|
||||||
|
- `stdio` 传输的退出清理只在收到断开时 `terminate`,子进程再拉起孙子进程时可能残留。
|
||||||
|
- MCP 的 `resources` / `prompts` 能力没有实现,只做了 `tools/*` 三件套
|
||||||
|
(前端和 Node 版也只用 tools)。
|
||||||
24
android/kernel/__init__.py
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
"""
|
||||||
|
豆鲍 AI 内核(纯标准库 Python 版,安卓 / Chaquopy 用)。
|
||||||
|
|
||||||
|
对外的两个入口:
|
||||||
|
from main import start_kernel # 扁平的模块名(Chaquopy 默认把源码目录当 sys.path)
|
||||||
|
import android.kernel # 包方式(python -m android.kernel)
|
||||||
|
|
||||||
|
接口与 Node 版 server/src/index.mjs 完全一致,Lynx 前端不用改任何代码。
|
||||||
|
具体说明见 README.md。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# package 方式导入时,把本目录也加进 sys.path:子模块之间用的是扁平导入
|
||||||
|
# (因为安卓上 Chaquopy 往往直接把本目录当源码根,扁平导入才两种方式都通用)
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
if _HERE not in sys.path:
|
||||||
|
sys.path.insert(0, _HERE)
|
||||||
|
|
||||||
|
from main import KernelHandle, main, start_kernel # noqa: E402
|
||||||
|
|
||||||
|
__all__ = ['start_kernel', 'main', 'KernelHandle']
|
||||||
|
__version__ = '0.1.0'
|
||||||
13
android/kernel/__main__.py
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
"""`python -m android.kernel` 的入口(等价于 python android/kernel/main.py)。"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
if _HERE not in sys.path:
|
||||||
|
sys.path.insert(0, _HERE)
|
||||||
|
|
||||||
|
from main import main # noqa: E402
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
180
android/kernel/agent_loop.py
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
"""
|
||||||
|
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||||
|
|
||||||
|
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||||||
|
open 所有工具都交给模型
|
||||||
|
restricted 只有白名单里的工具可用(连执行都会再拦一道,见 tools_runtime.execute_tool)
|
||||||
|
|
||||||
|
同步实现(生成器 + 普通函数),因为上游是 stdlib urllib 的阻塞式读取;
|
||||||
|
在 HTTP 服务里每个请求占一个线程,ThreadingHTTPServer 正好够用。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Callable, Optional
|
||||||
|
|
||||||
|
import store
|
||||||
|
import tools_runtime
|
||||||
|
from providers import stream_chat
|
||||||
|
|
||||||
|
MAX_TOOL_RESULT_CHARS = 6000
|
||||||
|
|
||||||
|
|
||||||
|
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||||||
|
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||||||
|
if isinstance(text, str):
|
||||||
|
out = text
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
out = json.dumps(text, ensure_ascii=False)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
out = str(text)
|
||||||
|
return f'{out[:max_len]}\n…(已截断)' if len(out) > max_len else out
|
||||||
|
|
||||||
|
|
||||||
|
def _max_rounds(settings: dict) -> int:
|
||||||
|
raw = settings.get('maxRounds')
|
||||||
|
try:
|
||||||
|
value = int(float(raw))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
value = 6
|
||||||
|
if not value: # 0 / 空 都按默认 6 处理(对应 JS 的 `Number(x) || 6`)
|
||||||
|
value = 6
|
||||||
|
return max(1, min(12, value))
|
||||||
|
|
||||||
|
|
||||||
|
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||||||
|
should_stop: Optional[Callable[[], bool]] = None) -> dict:
|
||||||
|
"""
|
||||||
|
跑一轮完整对话。
|
||||||
|
|
||||||
|
settings 当前设置
|
||||||
|
messages [{role, content}] 历史(不含 system)
|
||||||
|
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||||
|
emit 事件回调,直接往 SSE 里写
|
||||||
|
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||||
|
"""
|
||||||
|
provider = store.provider_info(settings)
|
||||||
|
tool_defs = tools_runtime.build_tool_defs(settings)
|
||||||
|
max_rounds = _max_rounds(settings)
|
||||||
|
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||||
|
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||||||
|
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||||
|
|
||||||
|
emit({
|
||||||
|
'type': 'start',
|
||||||
|
'provider': settings.get('provider'),
|
||||||
|
'model': provider.get('model'),
|
||||||
|
'tools': len(tool_defs),
|
||||||
|
'mode': mode,
|
||||||
|
'thinkingLevel': thinking_level,
|
||||||
|
'agent': {'id': agent.get('id'), 'name': agent.get('name')} if agent else None,
|
||||||
|
})
|
||||||
|
|
||||||
|
convo = []
|
||||||
|
if system_prompt.strip():
|
||||||
|
convo.append({'role': 'system', 'content': system_prompt})
|
||||||
|
convo.extend(messages)
|
||||||
|
|
||||||
|
answer = ''
|
||||||
|
reasoning_all = ''
|
||||||
|
tool_call_count = 0
|
||||||
|
usage = None
|
||||||
|
|
||||||
|
for round_index in range(max_rounds):
|
||||||
|
round_text = ''
|
||||||
|
tool_calls = []
|
||||||
|
|
||||||
|
for event in stream_chat(
|
||||||
|
# 注意:这里的 provider 是"提供商名字"(ark/openai),
|
||||||
|
# 和上面 provider_info 出来的对象不是一回事
|
||||||
|
provider=settings.get('provider'),
|
||||||
|
base_url=provider.get('baseUrl'),
|
||||||
|
api_key=settings.get('apiKey') or '',
|
||||||
|
model=provider.get('model'),
|
||||||
|
messages=convo,
|
||||||
|
tools=tool_defs if tool_defs else None,
|
||||||
|
temperature=settings.get('temperature'),
|
||||||
|
thinking_level=thinking_level,
|
||||||
|
should_stop=should_stop,
|
||||||
|
):
|
||||||
|
kind = event.get('type')
|
||||||
|
if kind == 'text':
|
||||||
|
round_text += event['text']
|
||||||
|
# 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文,
|
||||||
|
# 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。
|
||||||
|
answer += event['text']
|
||||||
|
emit({'type': 'delta', 'text': event['text'], 'round': round_index})
|
||||||
|
elif kind == 'reasoning':
|
||||||
|
reasoning_all += event['text']
|
||||||
|
emit({'type': 'reasoning', 'text': event['text'], 'round': round_index})
|
||||||
|
elif kind == 'tool_calls':
|
||||||
|
tool_calls = event.get('toolCalls') or []
|
||||||
|
elif kind == 'usage':
|
||||||
|
usage = event.get('usage')
|
||||||
|
|
||||||
|
if not tool_calls:
|
||||||
|
emit({
|
||||||
|
'type': 'done',
|
||||||
|
'content': answer,
|
||||||
|
'reasoning': reasoning_all,
|
||||||
|
'rounds': round_index + 1,
|
||||||
|
'toolCalls': tool_call_count,
|
||||||
|
'usage': usage,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
'content': answer, 'reasoning': reasoning_all,
|
||||||
|
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||||
|
}
|
||||||
|
|
||||||
|
convo.append({
|
||||||
|
'role': 'assistant',
|
||||||
|
'content': round_text or '',
|
||||||
|
'tool_calls': [
|
||||||
|
{
|
||||||
|
'id': tc.get('id'),
|
||||||
|
'type': 'function',
|
||||||
|
'function': {
|
||||||
|
'name': tc.get('name'),
|
||||||
|
# 参数原样回传:模型可能给出坏 JSON,服务端往往还能自己纠正
|
||||||
|
'arguments': tc.get('argsRaw') or json.dumps(tc.get('args') or {}, ensure_ascii=False),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for tc in tool_calls
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
for tc in tool_calls:
|
||||||
|
tool_call_count += 1
|
||||||
|
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
||||||
|
try:
|
||||||
|
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||||||
|
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||||||
|
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||||
|
if result.get('ok'):
|
||||||
|
raw = result.get('result')
|
||||||
|
payload = truncate('(无输出)' if raw is None else raw)
|
||||||
|
else:
|
||||||
|
payload = f"调用失败:{result.get('error') or '未知错误'}"
|
||||||
|
emit({
|
||||||
|
'type': 'tool_result',
|
||||||
|
'id': tc.get('id'),
|
||||||
|
'name': tc.get('name'),
|
||||||
|
'ok': bool(result.get('ok')),
|
||||||
|
'result': payload,
|
||||||
|
})
|
||||||
|
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||||||
|
|
||||||
|
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||||||
|
emit({
|
||||||
|
'type': 'done',
|
||||||
|
'content': answer,
|
||||||
|
'reasoning': reasoning_all,
|
||||||
|
'rounds': max_rounds,
|
||||||
|
'toolCalls': tool_call_count,
|
||||||
|
'usage': usage,
|
||||||
|
'truncated': True,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
'content': answer, 'reasoning': reasoning_all,
|
||||||
|
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||||||
|
}
|
||||||
903
android/kernel/app.py
Normal file
@@ -0,0 +1,903 @@
|
|||||||
|
"""
|
||||||
|
HTTP 路由:把 Node 版 server/src/index.mjs 的接口逐条搬到 stdlib 上。
|
||||||
|
|
||||||
|
用的是 http.server.ThreadingHTTPServer + BaseHTTPRequestHandler:
|
||||||
|
* 零依赖(安卓上不用打 flask/fastapi/aiohttp 的包,APK 小很多);
|
||||||
|
* 每个连接一个线程,阻塞式上游读取正好合适;
|
||||||
|
* SSE 用 chunked 传输编码手写(http.server 不会自动帮你分块),
|
||||||
|
帧格式和 Node 版完全一样:`data: {json}\n\n`。
|
||||||
|
|
||||||
|
接口清单(与 Node 版逐字段一致):
|
||||||
|
GET /api/health
|
||||||
|
GET /api/state PUT/POST /api/settings GET /api/models
|
||||||
|
GET /api/conversations POST /api/conversations
|
||||||
|
GET/PATCH/PUT/DELETE /api/conversations/<id>
|
||||||
|
GET /api/tools POST /api/tools/run
|
||||||
|
GET /api/mcp PUT/POST /api/mcp/config
|
||||||
|
POST /api/mcp/reveal POST /api/mcp/connect POST /api/mcp/disconnect
|
||||||
|
GET /api/agents POST /api/agents PATCH/PUT/DELETE /api/agents/<id>
|
||||||
|
POST /api/upload POST /api/pick-file GET /api/uploads/pending
|
||||||
|
POST /api/clipboard POST /api/chat(SSE)
|
||||||
|
静态:/ /main.web.bundle /lynx-web/* /static/* /uploads/*
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from urllib.parse import unquote, urlsplit
|
||||||
|
|
||||||
|
import agent_loop
|
||||||
|
import mcp_client
|
||||||
|
import paths
|
||||||
|
import providers
|
||||||
|
import speech
|
||||||
|
import store
|
||||||
|
import tools_runtime
|
||||||
|
import uploads
|
||||||
|
from defaults import PROVIDER_PRESETS
|
||||||
|
|
||||||
|
QUIET = False
|
||||||
|
|
||||||
|
# 轮询式对话任务:runId -> {'events': [...], 'done': bool, 'at': 时间戳}
|
||||||
|
# 安卓上 Lynx 原生 fetch 没有 response.body,只能靠这个通道做"准流式"
|
||||||
|
_RUNS = {}
|
||||||
|
_RUNS_LOCK = threading.Lock()
|
||||||
|
_RUN_TTL_S = 600
|
||||||
|
|
||||||
|
|
||||||
|
def _reap_runs() -> None:
|
||||||
|
"""清掉过期任务,别一直占内存"""
|
||||||
|
now = time.time()
|
||||||
|
with _RUNS_LOCK:
|
||||||
|
for key in [k for k, v in _RUNS.items() if now - v.get('at', now) > _RUN_TTL_S]:
|
||||||
|
_RUNS.pop(key, None)
|
||||||
|
|
||||||
|
|
||||||
|
def chat_error_hint(exc, settings) -> str:
|
||||||
|
"""把常见报错翻成一句人话,前端直接展示"""
|
||||||
|
import re as _re
|
||||||
|
|
||||||
|
msg = str(exc)
|
||||||
|
if _re.search(r'401|Unauthorized|invalid.*api.?key', msg, _re.IGNORECASE):
|
||||||
|
return 'API Key 不对或没填:右上角 ✎ → AI 内核设置 → 粘贴 Key 后保存'
|
||||||
|
if _re.search(r'404|model.*not.*found|does not exist|InvalidEndpoint', msg, _re.IGNORECASE):
|
||||||
|
model = (settings or {}).get('model')
|
||||||
|
return f'模型或接入点不存在:当前是 {model},去「模型」那一栏换一个,或填方舟的 ep- 接入点 ID'
|
||||||
|
if _re.search(r'429|rate.?limit|quota|insufficient', msg, _re.IGNORECASE):
|
||||||
|
return '被限流或余额不足,等一会儿或去控制台看额度'
|
||||||
|
if _re.search(r'timed? ?out|URLError|Connection refused|Name or service|getaddrinfo', msg, _re.IGNORECASE):
|
||||||
|
return '网络不通:检查手机网络;远程内核模式下还要确认内网地址可达'
|
||||||
|
if '400' in msg:
|
||||||
|
return '请求被拒:多半是模型名/参数不匹配,试试把思考强度调成「自动」'
|
||||||
|
return ''
|
||||||
|
|
||||||
|
MIME = {
|
||||||
|
'.html': 'text/html; charset=utf-8',
|
||||||
|
'.js': 'text/javascript; charset=utf-8',
|
||||||
|
'.mjs': 'text/javascript; charset=utf-8',
|
||||||
|
'.css': 'text/css; charset=utf-8',
|
||||||
|
'.json': 'application/json; charset=utf-8',
|
||||||
|
'.png': 'image/png',
|
||||||
|
'.jpg': 'image/jpeg',
|
||||||
|
'.jpeg': 'image/jpeg',
|
||||||
|
'.webp': 'image/webp',
|
||||||
|
'.svg': 'image/svg+xml',
|
||||||
|
'.ico': 'image/x-icon',
|
||||||
|
'.bundle': 'application/octet-stream',
|
||||||
|
'.wasm': 'application/wasm',
|
||||||
|
'.woff2': 'font/woff2',
|
||||||
|
'.txt': 'text/plain; charset=utf-8',
|
||||||
|
'.map': 'application/json; charset=utf-8',
|
||||||
|
}
|
||||||
|
|
||||||
|
INDEX_MISSING_HINT = (
|
||||||
|
'宿主页不存在。请先运行 npm run build(app/),或在 app/ 里跑 npm run dev 用 Rspeedy 开发服务器预览。'
|
||||||
|
)
|
||||||
|
|
||||||
|
# 安卓侧(Kotlin/Chaquopy)可以挂上原生能力钩子,等价于 Electron 主进程挂的 __doubaoXxx
|
||||||
|
_hooks = {'clipboard': None, 'pick_file': None, 'reveal': None}
|
||||||
|
|
||||||
|
|
||||||
|
def set_native_hooks(clipboard=None, pick_file=None, reveal=None) -> None:
|
||||||
|
"""注册原生钩子:clipboard(text) / pick_file()->[路径] / reveal(路径)->错误串或 None。"""
|
||||||
|
_hooks.update({'clipboard': clipboard, 'pick_file': pick_file, 'reveal': reveal})
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 工具函数
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def safe_join(root: str, url_path: str):
|
||||||
|
"""
|
||||||
|
把 URL 路径安全地拼到 root 下(挡住 ../ 穿越)。
|
||||||
|
等价于 Node 版 safeJoin:先规范化再拼,最后确认还在 root 里面。
|
||||||
|
"""
|
||||||
|
decoded = unquote((url_path or '').split('?')[0]).replace('\\', '/')
|
||||||
|
relative = decoded.lstrip('/')
|
||||||
|
target = os.path.abspath(os.path.join(root, relative))
|
||||||
|
root_abs = os.path.abspath(root)
|
||||||
|
if target != root_abs and not target.startswith(root_abs + os.sep):
|
||||||
|
return None
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
class SseChannel:
|
||||||
|
"""
|
||||||
|
一条 SSE 连接。
|
||||||
|
|
||||||
|
写 chunked 编码而不是"直接写、靠关连接表示结束":
|
||||||
|
HTTP/1.1 下没有 Content-Length 就必须分块,否则前端 fetch 会一直等 EOF。
|
||||||
|
所有写操作加锁,因为心跳线程和请求线程都会写。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, handler):
|
||||||
|
self.handler = handler
|
||||||
|
self.closed = False
|
||||||
|
self.aborted = False
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._stop_event = threading.Event()
|
||||||
|
self._heartbeat = None
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
self.handler.send_response(200)
|
||||||
|
self.handler.send_header('Content-Type', 'text/event-stream; charset=utf-8')
|
||||||
|
self.handler.send_header('Cache-Control', 'no-cache, no-transform')
|
||||||
|
self.handler.send_header('Connection', 'keep-alive')
|
||||||
|
self.handler.send_header('X-Accel-Buffering', 'no')
|
||||||
|
self.handler.send_header('Transfer-Encoding', 'chunked')
|
||||||
|
for key, value in self.handler.cors_headers().items():
|
||||||
|
self.handler.send_header(key, value)
|
||||||
|
self.handler.end_headers()
|
||||||
|
self._write(': connected\n\n')
|
||||||
|
self._heartbeat = threading.Thread(target=self._ping_loop, name='sse-heartbeat', daemon=True)
|
||||||
|
self._heartbeat.start()
|
||||||
|
|
||||||
|
def _write(self, text: str) -> None:
|
||||||
|
if self.closed:
|
||||||
|
return
|
||||||
|
data = text.encode('utf-8')
|
||||||
|
with self._lock:
|
||||||
|
try:
|
||||||
|
self.handler.wfile.write(b'%x\r\n' % len(data) + data + b'\r\n')
|
||||||
|
self.handler.wfile.flush()
|
||||||
|
except (OSError, ValueError):
|
||||||
|
# 客户端断了:标记 + 让上游停止生成(由 should_stop 接手)
|
||||||
|
self.aborted = True
|
||||||
|
self.closed = True
|
||||||
|
self.handler.close_connection = True
|
||||||
|
|
||||||
|
def send(self, event: dict) -> None:
|
||||||
|
if self.closed:
|
||||||
|
return
|
||||||
|
payload = json.dumps(event, ensure_ascii=False, separators=(',', ':'))
|
||||||
|
self._write(f'data: {payload}\n\n')
|
||||||
|
|
||||||
|
def _ping_loop(self) -> None:
|
||||||
|
while not self.closed:
|
||||||
|
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满 15 秒
|
||||||
|
if self._stop_event.wait(15):
|
||||||
|
return
|
||||||
|
if self.closed:
|
||||||
|
return
|
||||||
|
self._write(': ping\n\n')
|
||||||
|
|
||||||
|
def end(self) -> None:
|
||||||
|
if self.closed:
|
||||||
|
return
|
||||||
|
self.closed = True
|
||||||
|
self._stop_event.set()
|
||||||
|
with self._lock:
|
||||||
|
try:
|
||||||
|
self.handler.wfile.write(b'0\r\n\r\n')
|
||||||
|
self.handler.wfile.flush()
|
||||||
|
except (OSError, ValueError):
|
||||||
|
self.handler.close_connection = True
|
||||||
|
|
||||||
|
def should_stop(self) -> bool:
|
||||||
|
return self.aborted or self.closed
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 请求处理
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
class KernelHandler(BaseHTTPRequestHandler):
|
||||||
|
protocol_version = 'HTTP/1.1'
|
||||||
|
server_version = 'doubao-kernel-py/0.1'
|
||||||
|
sys_version = ''
|
||||||
|
|
||||||
|
# 每个请求进来时由 _dispatch 填:请求体缓存(None 表示还没读)
|
||||||
|
_raw_body = None
|
||||||
|
|
||||||
|
# ------------------------------ 基础设施 ------------------------------ #
|
||||||
|
|
||||||
|
def log_message(self, fmt, *args): # noqa: A003 - 覆盖基类
|
||||||
|
if not QUIET:
|
||||||
|
print(f'[http] {self.address_string()} {fmt % args}', file=sys.stderr)
|
||||||
|
|
||||||
|
def cors_headers(self) -> dict:
|
||||||
|
return {
|
||||||
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||||
|
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
|
||||||
|
}
|
||||||
|
|
||||||
|
def _head(self, status: int, headers: dict) -> None:
|
||||||
|
self.send_response(status)
|
||||||
|
for key, value in {**self.cors_headers(), **headers}.items():
|
||||||
|
self.send_header(key, value)
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
|
def send_json(self, status: int, payload) -> None:
|
||||||
|
# 与 Node 的 JSON.stringify(payload, null, 2) 对齐:缩进 2,中文原样输出
|
||||||
|
body = json.dumps(payload, ensure_ascii=False, indent=2).encode('utf-8')
|
||||||
|
self._head(status, {'Content-Type': 'application/json; charset=utf-8',
|
||||||
|
'Content-Length': str(len(body))})
|
||||||
|
if self.command != 'HEAD' and status != 204:
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def send_text(self, status: int, text: str) -> None:
|
||||||
|
body = text.encode('utf-8')
|
||||||
|
self._head(status, {'Content-Type': 'text/plain; charset=utf-8',
|
||||||
|
'Content-Length': str(len(body))})
|
||||||
|
if self.command != 'HEAD':
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def read_body(self, limit: int = 4 * 1024 * 1024) -> bytes:
|
||||||
|
"""
|
||||||
|
取请求体。注意:底层读取在 _dispatch 里就已经做完了(见那里的注释),
|
||||||
|
这里只负责按各接口自己的上限做校验。
|
||||||
|
"""
|
||||||
|
raw = self._read_raw_body()
|
||||||
|
if len(raw) > limit:
|
||||||
|
raise ValueError('请求体过大')
|
||||||
|
return raw
|
||||||
|
|
||||||
|
def _read_raw_body(self) -> bytes:
|
||||||
|
if self._raw_body is None:
|
||||||
|
self._raw_body = self._read_body_raw(40 * 1024 * 1024)
|
||||||
|
return self._raw_body
|
||||||
|
|
||||||
|
def _read_body_raw(self, limit: int) -> bytes:
|
||||||
|
if (self.headers.get('Transfer-Encoding') or '').lower() == 'chunked':
|
||||||
|
return self._read_chunked(limit)
|
||||||
|
try:
|
||||||
|
length = int(self.headers.get('Content-Length') or 0)
|
||||||
|
except ValueError:
|
||||||
|
length = 0
|
||||||
|
if length <= 0:
|
||||||
|
return b''
|
||||||
|
if length > limit:
|
||||||
|
raise ValueError('请求体过大')
|
||||||
|
return self.rfile.read(length)
|
||||||
|
|
||||||
|
def _read_chunked(self, limit: int) -> bytes:
|
||||||
|
chunks = []
|
||||||
|
total = 0
|
||||||
|
while True:
|
||||||
|
line = self.rfile.readline().strip()
|
||||||
|
if not line:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
size = int(line.split(b';')[0], 16)
|
||||||
|
except ValueError:
|
||||||
|
break
|
||||||
|
if size == 0:
|
||||||
|
self.rfile.readline()
|
||||||
|
break
|
||||||
|
total += size
|
||||||
|
if total > limit:
|
||||||
|
raise ValueError('请求体过大')
|
||||||
|
chunks.append(self.rfile.read(size))
|
||||||
|
self.rfile.readline()
|
||||||
|
return b''.join(chunks)
|
||||||
|
|
||||||
|
def read_json_body(self, limit: int = 4 * 1024 * 1024) -> dict:
|
||||||
|
raw = self.read_body(limit)
|
||||||
|
if not raw:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
payload = json.loads(raw.decode('utf-8'))
|
||||||
|
except (ValueError, UnicodeDecodeError) as exc:
|
||||||
|
raise ValueError('请求体不是合法 JSON') from exc
|
||||||
|
return payload if isinstance(payload, dict) else {}
|
||||||
|
|
||||||
|
# ------------------------------ HTTP 方法 ------------------------------ #
|
||||||
|
|
||||||
|
def do_GET(self): # noqa: N802 - 基类约定
|
||||||
|
self._dispatch('GET')
|
||||||
|
|
||||||
|
def do_POST(self): # noqa: N802
|
||||||
|
self._dispatch('POST')
|
||||||
|
|
||||||
|
def do_PUT(self): # noqa: N802
|
||||||
|
self._dispatch('PUT')
|
||||||
|
|
||||||
|
def do_PATCH(self): # noqa: N802
|
||||||
|
self._dispatch('PATCH')
|
||||||
|
|
||||||
|
def do_DELETE(self): # noqa: N802
|
||||||
|
self._dispatch('DELETE')
|
||||||
|
|
||||||
|
def do_HEAD(self): # noqa: N802
|
||||||
|
self._dispatch('GET')
|
||||||
|
|
||||||
|
def do_OPTIONS(self): # noqa: N802
|
||||||
|
self._dispatch('OPTIONS')
|
||||||
|
|
||||||
|
def _dispatch(self, method: str) -> None:
|
||||||
|
try:
|
||||||
|
pathname = urlsplit(self.path).path
|
||||||
|
# 先把请求体整块读掉再路由。
|
||||||
|
# 为什么必须提前读:HTTP/1.1 是长连接,没被消费的字节会留在 socket 里,
|
||||||
|
# 被下一次请求解析成请求行(实测表现为 `{}PUT /api/settings` → 501)。
|
||||||
|
# Node 的 http 模块会在响应结束时自动丢弃未读数据,Python 的 http.server 不会。
|
||||||
|
#
|
||||||
|
# 注意 _raw_body 必须"每个请求"重置:BaseHTTPRequestHandler 的长连接
|
||||||
|
# 复用同一个 handler 实例(handle_one_request 循环),不重置就会把
|
||||||
|
# 上一个请求的 body 当成这一个的(GET 之后接 POST 会拿到空 body)。
|
||||||
|
self._raw_body = None
|
||||||
|
self._read_raw_body()
|
||||||
|
if os.environ.get('DOUBAO_HTTP_DEBUG'):
|
||||||
|
# 排查长连接错位时用:把每个请求实际读到的 body 前 80 字节打出来
|
||||||
|
print(
|
||||||
|
f'[req] {method} {pathname} clen={self.headers.get("Content-Length")} '
|
||||||
|
f'body={self._raw_body[:80]!r}',
|
||||||
|
file=sys.stderr,
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
if pathname.startswith('/api/'):
|
||||||
|
if not self.handle_api(method, pathname):
|
||||||
|
self.send_json(404, {'error': f'未知接口 {pathname}'})
|
||||||
|
return
|
||||||
|
if not self.handle_static(pathname):
|
||||||
|
self.send_text(404, '404 Not Found')
|
||||||
|
except Exception as exc: # noqa: BLE001 - 兜底,绝不让线程带着异常死掉
|
||||||
|
print(f'[http] 处理失败:{exc}', file=sys.stderr, flush=True)
|
||||||
|
try:
|
||||||
|
if not self.wfile.closed:
|
||||||
|
self.send_json(500, {'error': str(exc)})
|
||||||
|
except OSError:
|
||||||
|
self.close_connection = True
|
||||||
|
|
||||||
|
# -------------------------------- API -------------------------------- #
|
||||||
|
|
||||||
|
def handle_api(self, method: str, pathname: str) -> bool: # noqa: C901 - 就是一个大路由表
|
||||||
|
if method == 'OPTIONS':
|
||||||
|
self._head(204, {})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/health':
|
||||||
|
self.send_json(200, {'ok': True, 'pid': os.getpid(), 'cwd': os.getcwd()})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 当前状态:设置(脱敏)+ 工具 + MCP + 会话列表 + 智能体
|
||||||
|
if pathname == '/api/state' and method == 'GET':
|
||||||
|
settings = store.read_settings()
|
||||||
|
tools = tools_runtime.list_all_tools(settings)
|
||||||
|
tool_names = [t.get('name') for t in tools['python']] + \
|
||||||
|
[d['function']['name'] for d in tools['mcp']]
|
||||||
|
self.send_json(200, {
|
||||||
|
'settings': store.mask_settings(settings),
|
||||||
|
'provider': store.provider_info(settings),
|
||||||
|
'providers': PROVIDER_PRESETS,
|
||||||
|
'speech': speech.speech_state(settings),
|
||||||
|
'speechVoices': {
|
||||||
|
'volc': speech.VOLC_VOICES,
|
||||||
|
'openai': speech.OPENAI_VOICES,
|
||||||
|
'system': [],
|
||||||
|
},
|
||||||
|
'python': {
|
||||||
|
'tools': [tools_runtime.public_spec(t) for t in tools['python']],
|
||||||
|
'errors': tools['errors'],
|
||||||
|
'interpreter': (tools['pythonInfo'] or {}).get('bin') if tools['pythonInfo'] else None,
|
||||||
|
},
|
||||||
|
'mcp': mcp_client.get_mcp_state(),
|
||||||
|
'mcpConfig': mcp_client.read_mcp_config(),
|
||||||
|
'conversations': store.list_conversations(),
|
||||||
|
'agents': store.list_agents(),
|
||||||
|
'toolNames': tool_names,
|
||||||
|
'suggestedAllow': tools_runtime.suggest_allowlist(tool_names),
|
||||||
|
# 前端用它挑终端里的预设命令(安卓的 getprop / Windows 的 dir 不通用)
|
||||||
|
'platform': 'android' if paths.IS_ANDROID else ('win32' if paths.IS_WINDOWS else 'linux'),
|
||||||
|
'shellKind': 'toybox' if paths.IS_ANDROID else ('cmd' if paths.IS_WINDOWS else 'sh'),
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/settings' and method in ('PUT', 'POST'):
|
||||||
|
patch = self.read_json_body()
|
||||||
|
nxt = store.write_settings(patch)
|
||||||
|
self.send_json(200, {'ok': True, 'settings': store.mask_settings(nxt)})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/models' and method == 'GET':
|
||||||
|
settings = store.read_settings()
|
||||||
|
try:
|
||||||
|
models = providers.list_models(base_url=settings.get('baseUrl') or '',
|
||||||
|
api_key=settings.get('apiKey') or '')
|
||||||
|
self.send_json(200, {'ok': True, 'models': models})
|
||||||
|
except Exception as exc: # noqa: BLE001 - 拉模型失败不是致命错误
|
||||||
|
preset = PROVIDER_PRESETS.get(settings.get('provider')) or {}
|
||||||
|
self.send_json(200, {'ok': False, 'error': str(exc), 'fallback': preset.get('models') or []})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- #
|
||||||
|
# 语音
|
||||||
|
#
|
||||||
|
# 两个接口都刻意**失败也返回 HTTP 200 + ok:false**:
|
||||||
|
# 缺 Key、厂商报错这些都是"预期内的失败",界面要的是把原因显示出来,
|
||||||
|
# 而不是让 fetch 抛一个网络异常(那样错误信息就丢了)。
|
||||||
|
# ---------------------------------------------------------------- #
|
||||||
|
if pathname == '/api/tts' and method == 'POST':
|
||||||
|
try:
|
||||||
|
body = self.read_json_body()
|
||||||
|
except ValueError:
|
||||||
|
body = {}
|
||||||
|
settings = store.read_settings()
|
||||||
|
try:
|
||||||
|
result = speech.synthesize(body.get('text') or '', settings)
|
||||||
|
self.send_json(200, {'ok': True, **result})
|
||||||
|
except speech.SpeechError as exc:
|
||||||
|
self.send_json(200, {'ok': False, 'error': str(exc)})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/stt' and method == 'POST':
|
||||||
|
# 音频是原始字节(不套 JSON/base64):省一次编解码,安卓那边录完直接发
|
||||||
|
audio = self._read_raw_body()
|
||||||
|
settings = store.read_settings()
|
||||||
|
try:
|
||||||
|
result = speech.transcribe(
|
||||||
|
audio,
|
||||||
|
self.headers.get('X-Audio-Filename') or 'audio.wav',
|
||||||
|
self.headers.get('X-Audio-Type') or 'audio/wav',
|
||||||
|
settings,
|
||||||
|
)
|
||||||
|
self.send_json(200, {'ok': True, **result})
|
||||||
|
except speech.SpeechError as exc:
|
||||||
|
self.send_json(200, {'ok': False, 'error': str(exc)})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/speech' and method == 'GET':
|
||||||
|
settings = store.read_settings()
|
||||||
|
state = speech.speech_state(settings)
|
||||||
|
self.send_json(200, {
|
||||||
|
'ok': True,
|
||||||
|
'speech': state,
|
||||||
|
'voices': {
|
||||||
|
'volc': speech.VOLC_VOICES,
|
||||||
|
'openai': speech.OPENAI_VOICES,
|
||||||
|
'system': [],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 会话
|
||||||
|
if pathname == '/api/conversations' and method == 'GET':
|
||||||
|
self.send_json(200, {'conversations': store.list_conversations()})
|
||||||
|
return True
|
||||||
|
if pathname == '/api/conversations' and method == 'POST':
|
||||||
|
try:
|
||||||
|
body = self.read_json_body()
|
||||||
|
except ValueError:
|
||||||
|
body = {}
|
||||||
|
self.send_json(200, {'conversation': store.create_conversation(body.get('title') or '新对话')})
|
||||||
|
return True
|
||||||
|
conv_id = self._match_id(pathname, '/api/conversations/')
|
||||||
|
if conv_id is not None:
|
||||||
|
if method == 'GET':
|
||||||
|
conv = store.get_conversation(conv_id)
|
||||||
|
if conv:
|
||||||
|
self.send_json(200, {'conversation': conv})
|
||||||
|
else:
|
||||||
|
self.send_json(404, {'error': '会话不存在'})
|
||||||
|
return True
|
||||||
|
if method in ('PATCH', 'PUT'):
|
||||||
|
body = self.read_json_body()
|
||||||
|
conv = store.update_conversation(conv_id, body)
|
||||||
|
if conv:
|
||||||
|
self.send_json(200, {'conversation': conv})
|
||||||
|
else:
|
||||||
|
self.send_json(404, {'error': '会话不存在'})
|
||||||
|
return True
|
||||||
|
if method == 'DELETE':
|
||||||
|
ok = store.delete_conversation(conv_id)
|
||||||
|
self.send_json(200 if ok else 404, {'ok': ok})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 工具
|
||||||
|
if pathname == '/api/tools' and method == 'GET':
|
||||||
|
settings = store.read_settings()
|
||||||
|
tools = tools_runtime.list_all_tools(settings)
|
||||||
|
tool_names = [t.get('name') for t in tools['python']] + \
|
||||||
|
[d['function']['name'] for d in tools['mcp']]
|
||||||
|
self.send_json(200, {
|
||||||
|
'python': [tools_runtime.public_spec(t) for t in tools['python']],
|
||||||
|
'errors': tools['errors'],
|
||||||
|
'mcp': mcp_client.get_mcp_state(),
|
||||||
|
'toolNames': tool_names,
|
||||||
|
'suggestedAllow': tools_runtime.suggest_allowlist(tool_names),
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/tools/run' and method == 'POST':
|
||||||
|
body = self.read_json_body()
|
||||||
|
name = body.get('name')
|
||||||
|
if not name:
|
||||||
|
self.send_json(400, {'error': '缺少 name'})
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
# 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错
|
||||||
|
result = tools_runtime.execute_tool(name, body.get('args') or {},
|
||||||
|
{'security': {'mode': 'open'}})
|
||||||
|
self.send_json(200, result)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.send_json(500, {'ok': False, 'error': str(exc)})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# MCP
|
||||||
|
if pathname == '/api/mcp' and method == 'GET':
|
||||||
|
config_path = mcp_client.mcp_config_path()
|
||||||
|
self.send_json(200, {
|
||||||
|
'servers': mcp_client.get_mcp_state(),
|
||||||
|
'config': mcp_client.read_mcp_config(),
|
||||||
|
'path': config_path,
|
||||||
|
'dir': os.path.dirname(config_path),
|
||||||
|
'text': mcp_client.read_mcp_config_text(),
|
||||||
|
# 安卓上没有"打开文件夹"这回事,除非 Kotlin 侧挂了钩子
|
||||||
|
'canReveal': callable(_hooks.get('reveal')),
|
||||||
|
'placeholders': {
|
||||||
|
'DOUBAO_DATA': paths.get().data_dir,
|
||||||
|
'APPDATA': os.environ.get('APPDATA', ''),
|
||||||
|
'USERPROFILE': os.environ.get('USERPROFILE', ''),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/mcp/config' and method in ('PUT', 'POST'):
|
||||||
|
body = self.read_json_body()
|
||||||
|
try:
|
||||||
|
count = mcp_client.write_mcp_config_text(str(body.get('text') or ''))
|
||||||
|
mcp_client.disconnect_all()
|
||||||
|
results = mcp_client.connect_all_enabled()
|
||||||
|
self.send_json(200, {
|
||||||
|
'ok': True,
|
||||||
|
'count': count,
|
||||||
|
'results': results,
|
||||||
|
'servers': mcp_client.get_mcp_state(),
|
||||||
|
})
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.send_json(400, {'ok': False, 'error': str(exc)})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/mcp/reveal' and method == 'POST':
|
||||||
|
target = mcp_client.mcp_config_path()
|
||||||
|
reveal = _hooks.get('reveal')
|
||||||
|
if callable(reveal):
|
||||||
|
error = reveal(target)
|
||||||
|
self.send_json(200, {'ok': not error, 'error': error or None, 'path': target})
|
||||||
|
else:
|
||||||
|
self.send_json(200, {'ok': False, 'error': '当前运行方式不支持打开文件夹', 'path': target})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/mcp/connect' and method == 'POST':
|
||||||
|
body = self.read_json_body()
|
||||||
|
if body.get('name'):
|
||||||
|
record = mcp_client.connect(body['name'], force=True)
|
||||||
|
self.send_json(200, {'ok': not record.get('error'), 'error': record.get('error'),
|
||||||
|
'toolCount': len(record.get('tools') or [])})
|
||||||
|
else:
|
||||||
|
results = mcp_client.connect_all_enabled()
|
||||||
|
self.send_json(200, {'ok': all(r.get('ok') for r in results), 'results': results})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/mcp/disconnect' and method == 'POST':
|
||||||
|
body = self.read_json_body()
|
||||||
|
mcp_client.disconnect(body.get('name'))
|
||||||
|
self.send_json(200, {'ok': True})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 智能体
|
||||||
|
if pathname == '/api/agents' and method == 'GET':
|
||||||
|
self.send_json(200, {'agents': store.list_agents()})
|
||||||
|
return True
|
||||||
|
if pathname == '/api/agents' and method == 'POST':
|
||||||
|
body = self.read_json_body()
|
||||||
|
self.send_json(200, {'agent': store.create_agent(body)})
|
||||||
|
return True
|
||||||
|
agent_id = self._match_id(pathname, '/api/agents/')
|
||||||
|
if agent_id is not None:
|
||||||
|
if method in ('PATCH', 'PUT'):
|
||||||
|
body = self.read_json_body()
|
||||||
|
agent = store.update_agent(agent_id, body)
|
||||||
|
if agent:
|
||||||
|
self.send_json(200, {'agent': agent})
|
||||||
|
else:
|
||||||
|
self.send_json(404, {'error': '智能体不存在'})
|
||||||
|
return True
|
||||||
|
if method == 'DELETE':
|
||||||
|
self.send_json(200 if store.delete_agent(agent_id) else 404, {'ok': True})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 附件
|
||||||
|
if pathname == '/api/upload' and method == 'POST':
|
||||||
|
body = self.read_json_body(40 * 1024 * 1024)
|
||||||
|
try:
|
||||||
|
item = uploads.save_upload(body.get('name'), body.get('dataUrl') or body.get('base64'))
|
||||||
|
if body.get('pending'):
|
||||||
|
uploads.add_pending([item])
|
||||||
|
self.send_json(200, {'ok': True, 'file': item})
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.send_json(400, {'ok': False, 'error': str(exc)})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/pick-file' and method == 'POST':
|
||||||
|
picker = _hooks.get('pick_file')
|
||||||
|
if not callable(picker):
|
||||||
|
self.send_json(200, {'ok': False, 'error': '当前环境不支持原生选文件,请拖拽文件到窗口里',
|
||||||
|
'files': []})
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
picked = picker() or []
|
||||||
|
files = [uploads.register_local_file(p) for p in picked]
|
||||||
|
self.send_json(200, {'ok': True, 'files': files})
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.send_json(500, {'ok': False, 'error': str(exc), 'files': []})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/uploads/pending' and method == 'GET':
|
||||||
|
self.send_json(200, {'files': uploads.take_pending()})
|
||||||
|
return True
|
||||||
|
|
||||||
|
if pathname == '/api/clipboard' and method == 'POST':
|
||||||
|
body = self.read_json_body()
|
||||||
|
writer = _hooks.get('clipboard')
|
||||||
|
if callable(writer):
|
||||||
|
writer(str(body.get('text') or ''))
|
||||||
|
self.send_json(200, {'ok': True, 'via': 'native'})
|
||||||
|
else:
|
||||||
|
self.send_json(200, {'ok': False, 'via': 'none'})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 流式对话(SSE 或轮询,由 body.transport 决定)
|
||||||
|
if pathname == '/api/chat' and method == 'POST':
|
||||||
|
_reap_runs()
|
||||||
|
self._handle_chat()
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 轮询取增量:安卓端 Lynx 原生 fetch 没有流式 body,走这条
|
||||||
|
if pathname == '/api/chat/poll' and method == 'GET':
|
||||||
|
self._handle_chat_poll()
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 前端用它判断"这条通道能不能边收边解析"
|
||||||
|
if pathname == '/api/chat/transport' and method == 'GET':
|
||||||
|
self.send_json(200, {'ok': True, 'sse': True, 'poll': True})
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _match_id(pathname: str, prefix: str):
|
||||||
|
"""匹配 /api/xxx/<id>;id 里带斜杠的情况按 Node 的正则一样不支持。"""
|
||||||
|
if not pathname.startswith(prefix):
|
||||||
|
return None
|
||||||
|
rest = pathname[len(prefix):]
|
||||||
|
if not rest or '/' in rest:
|
||||||
|
return None
|
||||||
|
return unquote(rest)
|
||||||
|
|
||||||
|
# ------------------------------- 对话 ------------------------------- #
|
||||||
|
|
||||||
|
def _handle_chat(self) -> None:
|
||||||
|
body = self.read_json_body()
|
||||||
|
settings = store.read_settings()
|
||||||
|
conversation_id = body.get('conversationId') or 'c_main'
|
||||||
|
text = str(body.get('message') or '').strip()
|
||||||
|
attachments = body.get('attachments') if isinstance(body.get('attachments'), list) else []
|
||||||
|
if not text and not attachments:
|
||||||
|
self.send_json(400, {'error': '消息为空'})
|
||||||
|
return
|
||||||
|
|
||||||
|
# ★ 轮询模式:安卓上 Lynx 原生端的 fetch 没有 response.body,边收边解析做不到,
|
||||||
|
# 所以那条路走「先拿 runId,再每 200ms GET /api/chat/poll 取增量」。
|
||||||
|
# 两条路共用 _perform_chat,事件完全一致。
|
||||||
|
if body.get('transport') == 'poll':
|
||||||
|
run_id = 'r%d%s' % (int(time.time() * 1000), uuid.uuid4().hex[:5])
|
||||||
|
with _RUNS_LOCK:
|
||||||
|
_RUNS[run_id] = {'events': [], 'done': False, 'at': time.time()}
|
||||||
|
self.send_json(200, {'ok': True, 'runId': run_id, 'transport': 'poll'})
|
||||||
|
|
||||||
|
def sink_send(event):
|
||||||
|
with _RUNS_LOCK:
|
||||||
|
run = _RUNS.get(run_id)
|
||||||
|
if run is None:
|
||||||
|
return
|
||||||
|
run['events'].append(event)
|
||||||
|
if event.get('type') in ('done', 'error'):
|
||||||
|
run['done'] = True
|
||||||
|
|
||||||
|
def sink_end():
|
||||||
|
with _RUNS_LOCK:
|
||||||
|
run = _RUNS.get(run_id)
|
||||||
|
if run is not None:
|
||||||
|
run['done'] = True
|
||||||
|
|
||||||
|
# 后台线程跑,立刻把 HTTP 请求放掉
|
||||||
|
worker = threading.Thread(
|
||||||
|
target=self._perform_chat,
|
||||||
|
args=(sink_send, sink_end, settings, conversation_id, text, attachments, body),
|
||||||
|
name='chat-run',
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
worker.start()
|
||||||
|
return
|
||||||
|
|
||||||
|
sse = SseChannel(self)
|
||||||
|
sse.start()
|
||||||
|
self._perform_chat(
|
||||||
|
sse.send, sse.end, settings, conversation_id, text, attachments, body,
|
||||||
|
should_stop=sse.should_stop,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _perform_chat(self, emit, end, settings, conversation_id, text, attachments, body,
|
||||||
|
should_stop=None) -> None:
|
||||||
|
"""跑一轮对话。SSE 与轮询两条路共用,保证事件序列一致。"""
|
||||||
|
cancelled = should_stop or (lambda: False)
|
||||||
|
try:
|
||||||
|
existing = store.get_conversation(conversation_id) or {}
|
||||||
|
history_source = body.get('history') if isinstance(body.get('history'), list) else \
|
||||||
|
existing.get('messages') or []
|
||||||
|
history = [
|
||||||
|
{'role': m.get('role'), 'content': m.get('content')}
|
||||||
|
for m in history_source
|
||||||
|
if isinstance(m, dict) and m.get('role') in ('user', 'assistant')
|
||||||
|
]
|
||||||
|
|
||||||
|
# 附件 → 模型输入:图片走视觉格式,文本类内联正文
|
||||||
|
parts = []
|
||||||
|
if text:
|
||||||
|
parts.append({'type': 'text', 'text': text})
|
||||||
|
attachment_meta = []
|
||||||
|
for item in attachments:
|
||||||
|
payload = uploads.attachment_payload(item)
|
||||||
|
if payload.get('text'):
|
||||||
|
parts.append({'type': 'text', 'text': payload['text']})
|
||||||
|
for image in payload.get('images') or []:
|
||||||
|
parts.append({'type': 'image_url', 'image_url': {'url': image['url']}})
|
||||||
|
attachment_meta.append({
|
||||||
|
'id': item.get('id'),
|
||||||
|
'name': item.get('name'),
|
||||||
|
'size': item.get('size'),
|
||||||
|
'mime': item.get('mime'),
|
||||||
|
'url': item.get('url') or '',
|
||||||
|
})
|
||||||
|
|
||||||
|
has_image = any(p.get('type') == 'image_url' for p in parts)
|
||||||
|
user_content = parts if (has_image or len(parts) > 1) else text
|
||||||
|
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
|
||||||
|
|
||||||
|
store.append_messages(conversation_id, [{
|
||||||
|
'role': 'user',
|
||||||
|
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
|
||||||
|
'attachments': attachment_meta,
|
||||||
|
'at': store.now_iso(),
|
||||||
|
}])
|
||||||
|
if text:
|
||||||
|
store.auto_title(conversation_id, text)
|
||||||
|
|
||||||
|
result = agent_loop.run_agent(
|
||||||
|
settings=settings,
|
||||||
|
agent=agent,
|
||||||
|
messages=[*history, {'role': 'user', 'content': user_content}],
|
||||||
|
emit=emit,
|
||||||
|
should_stop=cancelled,
|
||||||
|
)
|
||||||
|
|
||||||
|
store.append_messages(conversation_id, [{
|
||||||
|
'role': 'assistant',
|
||||||
|
'content': result.get('content', ''),
|
||||||
|
# 思维链也要落库,否则一刷新「思考过程」就没了
|
||||||
|
'reasoning': result.get('reasoning', '') or '',
|
||||||
|
'agentId': (agent or {}).get('id') or '',
|
||||||
|
'at': store.now_iso(),
|
||||||
|
}])
|
||||||
|
conv = store.get_conversation(conversation_id) or {}
|
||||||
|
emit({'type': 'saved', 'conversationId': conversation_id, 'title': conv.get('title')})
|
||||||
|
except Exception as exc: # noqa: BLE001 - 出错也要以 error 事件收尾,前端才知道停了
|
||||||
|
emit({'type': 'error', 'message': str(exc), 'hint': chat_error_hint(exc, settings)})
|
||||||
|
finally:
|
||||||
|
end()
|
||||||
|
|
||||||
|
def _handle_chat_poll(self) -> None:
|
||||||
|
"""GET /api/chat/poll?runId=xxx&cursor=N —— 取增量事件"""
|
||||||
|
parsed = urlsplit(self.path)
|
||||||
|
params = dict(
|
||||||
|
pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair
|
||||||
|
)
|
||||||
|
run_id = unquote(params.get('runId') or '')
|
||||||
|
try:
|
||||||
|
cursor = max(0, int(params.get('cursor') or 0))
|
||||||
|
except ValueError:
|
||||||
|
cursor = 0
|
||||||
|
with _RUNS_LOCK:
|
||||||
|
run = _RUNS.get(run_id)
|
||||||
|
if run is None:
|
||||||
|
self.send_json(404, {'ok': False, 'error': '任务不存在或已过期'})
|
||||||
|
return
|
||||||
|
events = run['events'][cursor:]
|
||||||
|
total = len(run['events'])
|
||||||
|
done = run['done']
|
||||||
|
if done and total == cursor:
|
||||||
|
run['at'] = time.time() - 9 * 60 # 取完了,很快就能回收
|
||||||
|
self.send_json(200, {'ok': True, 'events': events, 'cursor': total, 'done': done})
|
||||||
|
|
||||||
|
# -------------------------------- 静态 -------------------------------- #
|
||||||
|
|
||||||
|
def handle_static(self, pathname: str) -> bool:
|
||||||
|
p = paths.get()
|
||||||
|
|
||||||
|
if pathname in ('/', '/index.html'):
|
||||||
|
index = os.path.join(p.web_dir, 'index.html')
|
||||||
|
if not os.path.isfile(index):
|
||||||
|
self.send_text(503, INDEX_MISSING_HINT)
|
||||||
|
return True
|
||||||
|
return self.serve_file(index)
|
||||||
|
|
||||||
|
if pathname.startswith('/lynx-web/'):
|
||||||
|
target = safe_join(p.web_core_dir, pathname[len('/lynx-web'):])
|
||||||
|
# 注意:Node 版这里漏了 404(serveFile 返回 false 被 `|| true` 吃掉,
|
||||||
|
# 请求会一直挂着)。Python 版改成正常 404,行为更好且不影响前端。
|
||||||
|
return bool(target and self.serve_file(target))
|
||||||
|
|
||||||
|
# 上传的附件(图片缩略图要用)
|
||||||
|
if pathname.startswith('/uploads/'):
|
||||||
|
target = safe_join(p.uploads_dir, pathname[len('/uploads'):])
|
||||||
|
if target and os.path.isfile(target):
|
||||||
|
return self.serve_file(target)
|
||||||
|
|
||||||
|
# @lynx-js/web-core 的运行时固定从 /static/ 拉 chunk 与 wasm,必须原样托管
|
||||||
|
if pathname.startswith('/static/'):
|
||||||
|
target = safe_join(p.web_core_dir, pathname[len('/static'):])
|
||||||
|
if target and os.path.isfile(target):
|
||||||
|
return self.serve_file(target)
|
||||||
|
|
||||||
|
if pathname in ('/main.web.bundle', '/main.lynx.bundle'):
|
||||||
|
return self.serve_file(os.path.join(p.dist_dir, os.path.basename(pathname)))
|
||||||
|
|
||||||
|
dist_file = safe_join(p.dist_dir, pathname)
|
||||||
|
if dist_file and os.path.isfile(dist_file):
|
||||||
|
return self.serve_file(dist_file)
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
def serve_file(self, file_path: str) -> bool:
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
return False
|
||||||
|
ext = os.path.splitext(file_path)[1].lower()
|
||||||
|
size = os.path.getsize(file_path)
|
||||||
|
cache = 'no-cache' if ext == '.bundle' else 'public, max-age=0, must-revalidate'
|
||||||
|
self._head(200, {
|
||||||
|
'Content-Type': MIME.get(ext, 'application/octet-stream'),
|
||||||
|
'Content-Length': str(size),
|
||||||
|
'Cache-Control': cache,
|
||||||
|
})
|
||||||
|
if self.command == 'HEAD':
|
||||||
|
return True
|
||||||
|
with open(file_path, 'rb') as fh:
|
||||||
|
while True:
|
||||||
|
chunk = fh.read(256 * 1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
self.wfile.write(chunk)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def create_server(host: str, port: int) -> ThreadingHTTPServer:
|
||||||
|
"""建好但还没启动的 HTTP 服务(main.py / 安卓侧都用这个)。"""
|
||||||
|
server = ThreadingHTTPServer((host, port), KernelHandler)
|
||||||
|
server.daemon_threads = True
|
||||||
|
return server
|
||||||
323
android/kernel/builtin_tools.py
Normal file
@@ -0,0 +1,323 @@
|
|||||||
|
"""
|
||||||
|
内置工具:shell 与 python_run。
|
||||||
|
|
||||||
|
为什么要内置,而不是直接复用 tools/shell.py、tools/python_run.py:
|
||||||
|
* 那两个文件是"子进程 + 解释器"模型:`python tool.py --input x.json`,
|
||||||
|
安卓上根本没有独立的 python 可执行文件(唯一解释器就在 Kern 进程里),
|
||||||
|
所以必须把这两个能力做成进程内实现。
|
||||||
|
* 内置版本在工具发现阶段**优先于同名文件工具**(和"安卓端优先"的取舍一致),
|
||||||
|
用户在 tools/ 里放自己的 shell.py 也不会把内核搞挂。
|
||||||
|
|
||||||
|
安全说明:python_run 在**内核进程内** exec 用户代码,这是安卓端的必然取舍
|
||||||
|
(没有子进程可以隔离)。因此只保留超时(线程 + 放弃)和 stdout/stderr 捕获,
|
||||||
|
真正要沙箱只能靠 settings.security.mode = restricted 的白名单。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import builtins
|
||||||
|
import contextlib
|
||||||
|
import importlib.util
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import platform
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
import paths
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 工具定义(与 tools/shell.py、tools/python_run.py 的 TOOL 完全一致,
|
||||||
|
# 这样模型看到的 description / parameters 在两端一模一样)
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
SHELL_TOOL = {
|
||||||
|
'name': 'shell',
|
||||||
|
'description': (
|
||||||
|
'在用户电脑/手机的终端里执行一条 shell 命令,返回退出码、标准输出和标准错误。'
|
||||||
|
'适合查看文件、跑脚本、装依赖、查系统信息。危险命令会被拦截。'
|
||||||
|
),
|
||||||
|
'parameters': {
|
||||||
|
'type': 'object',
|
||||||
|
'properties': {
|
||||||
|
'command': {'type': 'string', 'description': '要执行的命令,例如 ls -la 或 python --version'},
|
||||||
|
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||||||
|
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||||||
|
},
|
||||||
|
'required': ['command'],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
PYTHON_RUN_TOOL = {
|
||||||
|
'name': 'python_run',
|
||||||
|
'description': (
|
||||||
|
'运行一段 Python 代码或指定 .py 文件,返回标准输出/错误。'
|
||||||
|
'适合做计算、数据处理、调用网络接口(requests/httpx/urllib 可用)。'
|
||||||
|
'action=libs 可以查看当前环境装了哪些库。'
|
||||||
|
),
|
||||||
|
'parameters': {
|
||||||
|
'type': 'object',
|
||||||
|
'properties': {
|
||||||
|
'action': {
|
||||||
|
'type': 'string',
|
||||||
|
'enum': ['run', 'libs'],
|
||||||
|
'description': 'run=执行代码/文件(默认);libs=列出可用库',
|
||||||
|
},
|
||||||
|
'code': {'type': 'string', 'description': '要执行的 Python 代码(action=run 时二选一)'},
|
||||||
|
'file': {'type': 'string', 'description': '要执行的 .py 文件路径(action=run 时二选一)'},
|
||||||
|
'stdin': {'type': 'string', 'description': '传给脚本的标准输入,可留空'},
|
||||||
|
'timeout': {'type': 'number', 'description': '超时秒数,默认 60,最大 600'},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
# 明显会搞坏机器的模式(可用 DOUBAO_SHELL_UNSAFE=1 关闭)
|
||||||
|
BLOCKED = [
|
||||||
|
'rm -rf /',
|
||||||
|
'rm -rf /*',
|
||||||
|
'mkfs',
|
||||||
|
'dd if=/dev/zero',
|
||||||
|
':(){:|:&};:',
|
||||||
|
'shutdown',
|
||||||
|
'reboot',
|
||||||
|
'format c:',
|
||||||
|
'del /f /s /q c:\\',
|
||||||
|
'rmdir /s /q c:\\',
|
||||||
|
]
|
||||||
|
|
||||||
|
# python_run action=libs 里检查的常用库
|
||||||
|
WATCHED = [
|
||||||
|
'requests', 'httpx', 'aiohttp', 'urllib3', 'bs4', 'lxml', 'pandas', 'numpy',
|
||||||
|
'PIL', 'openpyxl', 'docx', 'pptx', 'yaml', 'dotenv', 'mcp', 'flask', 'fastapi',
|
||||||
|
]
|
||||||
|
|
||||||
|
# 进程内 exec 会临时切换 cwd(Python 没有"给这段代码单独设 cwd"的机制),
|
||||||
|
# 加锁只是为了让切换尽量短,不能解决并发请求看到临时 cwd 的问题,故在此说明。
|
||||||
|
_cwd_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
@contextlib.contextmanager
|
||||||
|
def _redirect_stdin(buffer):
|
||||||
|
"""标准库只有 redirect_stdout/redirect_stderr,没有 redirect_stdin,只能自己换。"""
|
||||||
|
saved = sys.stdin
|
||||||
|
sys.stdin = buffer
|
||||||
|
try:
|
||||||
|
yield buffer
|
||||||
|
finally:
|
||||||
|
sys.stdin = saved
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# shell
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def shell_run(args: dict) -> dict:
|
||||||
|
command = str(args.get('command') or '').strip()
|
||||||
|
if not command:
|
||||||
|
raise ValueError('command 不能为空')
|
||||||
|
if len(command) > 4000:
|
||||||
|
raise ValueError('命令过长')
|
||||||
|
|
||||||
|
if os.environ.get('DOUBAO_SHELL_UNSAFE') != '1':
|
||||||
|
lowered = command.lower()
|
||||||
|
for bad in BLOCKED:
|
||||||
|
if bad in lowered:
|
||||||
|
raise ValueError(f'命令命中黑名单({bad}),已拒绝执行。确实需要请设置 DOUBAO_SHELL_UNSAFE=1')
|
||||||
|
|
||||||
|
timeout = max(1, min(300, int(args.get('timeout') or 30)))
|
||||||
|
cwd = args.get('cwd') or None
|
||||||
|
if cwd and not os.path.isdir(cwd):
|
||||||
|
raise ValueError(f'工作目录不存在:{cwd}')
|
||||||
|
|
||||||
|
if paths.IS_WINDOWS:
|
||||||
|
argv = ['cmd', '/c', command]
|
||||||
|
else:
|
||||||
|
# 安卓系统里 /bin/sh 通常存在(是 /system/bin/sh 的软链),没有就退回真实路径
|
||||||
|
shell = '/bin/sh' if os.path.exists('/bin/sh') else '/system/bin/sh'
|
||||||
|
argv = [shell, '-c', command]
|
||||||
|
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
argv,
|
||||||
|
cwd=cwd,
|
||||||
|
capture_output=True,
|
||||||
|
timeout=timeout,
|
||||||
|
text=True,
|
||||||
|
errors='replace',
|
||||||
|
)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
return {'error': f'命令超时({timeout}s)', 'timeout': True}
|
||||||
|
except OSError as exc:
|
||||||
|
# 安卓上可能完全没有可执行权限/没有 shell,这里要给模型一个能读懂的原因
|
||||||
|
raise RuntimeError(f'无法启动命令({argv[0]}):{exc}') from exc
|
||||||
|
|
||||||
|
return {
|
||||||
|
'exit_code': proc.returncode,
|
||||||
|
'stdout': (proc.stdout or '')[-8000:],
|
||||||
|
'stderr': (proc.stderr or '')[-4000:],
|
||||||
|
'platform': f'{platform.system()} {platform.release()}',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# python_run
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def _libs_report() -> dict:
|
||||||
|
available, missing = [], []
|
||||||
|
for name in WATCHED:
|
||||||
|
try:
|
||||||
|
found = importlib.util.find_spec(name) is not None
|
||||||
|
except (ImportError, ValueError):
|
||||||
|
found = False
|
||||||
|
(available if found else missing).append(name)
|
||||||
|
return {
|
||||||
|
'python': sys.version.split()[0],
|
||||||
|
'executable': sys.executable or '<进程内>',
|
||||||
|
'available': available,
|
||||||
|
'missing': missing,
|
||||||
|
'hint': '缺库时可以用 shell 工具执行 pip install <包名>' if missing else '常用库齐全',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _exec_source(source: str, filename: str, cwd: str, stdin_text: str) -> tuple:
|
||||||
|
"""
|
||||||
|
在进程内执行 Python 源码,返回 (exit_code, stdout, stderr)。
|
||||||
|
|
||||||
|
- stdout/stderr 用 contextlib.redirect_* 捕获;
|
||||||
|
- sys.exit()/SystemExit 的 code 当作退出码;
|
||||||
|
- 其它异常打印完整 traceback 到 stderr(模型据此自我修正);
|
||||||
|
- cwd 临时切到脚本目录,跑完恢复(Python 没有更细粒度的办法)。
|
||||||
|
"""
|
||||||
|
out_buf, err_buf = io.StringIO(), io.StringIO()
|
||||||
|
namespace = {
|
||||||
|
'__name__': '__main__',
|
||||||
|
'__file__': filename,
|
||||||
|
'__builtins__': builtins,
|
||||||
|
'__doc__': None,
|
||||||
|
'__package__': None,
|
||||||
|
}
|
||||||
|
exit_code = 0
|
||||||
|
|
||||||
|
def _work():
|
||||||
|
nonlocal exit_code
|
||||||
|
try:
|
||||||
|
code_obj = compile(source, filename, 'exec')
|
||||||
|
except SyntaxError:
|
||||||
|
traceback.print_exc(file=err_buf)
|
||||||
|
exit_code = 1
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
exec(code_obj, namespace) # noqa: S102 - 这就是本工具存在的意义
|
||||||
|
except SystemExit as exc:
|
||||||
|
value = exc.code
|
||||||
|
exit_code = 0 if value is None else (value if isinstance(value, int) else 1)
|
||||||
|
except BaseException: # noqa: BLE001 - 用户代码什么都能抛,包括 KeyboardInterrupt
|
||||||
|
traceback.print_exc(file=err_buf)
|
||||||
|
exit_code = 1
|
||||||
|
|
||||||
|
saved_cwd = os.getcwd()
|
||||||
|
changed = bool(cwd) and os.path.isdir(cwd) and os.path.abspath(cwd) != os.path.abspath(saved_cwd)
|
||||||
|
# 注意:redirect_stdout/stderr 和 chdir 都是"进程级"的(Python 没有线程级实现),
|
||||||
|
# 因此在同一进程里并发跑 python_run 时,另一个请求的 print 也可能被收进本次结果。
|
||||||
|
# 安卓上内核是单用户本地服务,这个代价可以接受;桌面/服务器场景请改用独立进程。
|
||||||
|
with contextlib.ExitStack() as stack:
|
||||||
|
stack.enter_context(contextlib.redirect_stdout(out_buf))
|
||||||
|
stack.enter_context(contextlib.redirect_stderr(err_buf))
|
||||||
|
# 标准库里没有 redirect_stdin(只有 stdout/stderr),只能自己换 sys.stdin:
|
||||||
|
# Node 版是靠子进程的 stdin 参数,安卓上没子进程,这里就是等价实现。
|
||||||
|
stack.enter_context(_redirect_stdin(io.StringIO(stdin_text or '')))
|
||||||
|
try:
|
||||||
|
if changed:
|
||||||
|
with _cwd_lock:
|
||||||
|
os.chdir(cwd)
|
||||||
|
_work()
|
||||||
|
finally:
|
||||||
|
if changed:
|
||||||
|
with _cwd_lock:
|
||||||
|
os.chdir(saved_cwd)
|
||||||
|
return exit_code, out_buf.getvalue(), err_buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def run_with_timeout(fn, timeout_s: float):
|
||||||
|
"""
|
||||||
|
线程 + join(timeout) 实现超时。
|
||||||
|
|
||||||
|
为什么不用 signal.alarm / SIGALRM:安卓主线程之外信号不可用,
|
||||||
|
而且 CPython 根本杀不掉一个正在跑的线程。超时后我们只能"放弃等待",
|
||||||
|
被放弃的线程会继续在后台跑完(daemon 线程,不阻塞进程退出)。
|
||||||
|
这个取舍必须让用户知道,所以超时消息里写清楚。
|
||||||
|
"""
|
||||||
|
box = {}
|
||||||
|
|
||||||
|
def worker():
|
||||||
|
try:
|
||||||
|
box['value'] = fn()
|
||||||
|
except BaseException as exc: # noqa: BLE001 - 转成错误对象回主线程
|
||||||
|
box['error'] = exc
|
||||||
|
|
||||||
|
thread = threading.Thread(target=worker, name='doubao-python-run', daemon=True)
|
||||||
|
thread.start()
|
||||||
|
thread.join(timeout_s)
|
||||||
|
if thread.is_alive():
|
||||||
|
return None
|
||||||
|
if 'error' in box:
|
||||||
|
raise box['error']
|
||||||
|
return box.get('value')
|
||||||
|
|
||||||
|
|
||||||
|
def python_run(args: dict) -> dict:
|
||||||
|
action = str(args.get('action') or 'run').lower()
|
||||||
|
|
||||||
|
if action == 'libs':
|
||||||
|
return _libs_report()
|
||||||
|
|
||||||
|
code = args.get('code')
|
||||||
|
file_path = args.get('file')
|
||||||
|
if not code and not file_path:
|
||||||
|
raise ValueError('code 和 file 至少要给一个')
|
||||||
|
|
||||||
|
timeout = max(1, min(600, int(args.get('timeout') or 60)))
|
||||||
|
stdin_text = args.get('stdin') or ''
|
||||||
|
|
||||||
|
if file_path:
|
||||||
|
target = str(file_path)
|
||||||
|
if not os.path.isfile(target):
|
||||||
|
raise ValueError(f'文件不存在:{target}')
|
||||||
|
with open(target, 'r', encoding='utf-8', errors='replace') as fh:
|
||||||
|
source = fh.read()
|
||||||
|
filename = os.path.abspath(target)
|
||||||
|
cwd = os.path.dirname(filename)
|
||||||
|
else:
|
||||||
|
source = str(code)
|
||||||
|
# 用与安卓缓存目录同级的位置当"脚本目录",避免把临时文件写进只读的 assets
|
||||||
|
filename = os.path.join(paths.get().tmp_dir, f'doubao_run_{int(time.time() * 1000)}.py')
|
||||||
|
cwd = paths.get().tmp_dir
|
||||||
|
|
||||||
|
result = run_with_timeout(
|
||||||
|
lambda: _exec_source(source, filename, cwd, stdin_text),
|
||||||
|
timeout,
|
||||||
|
)
|
||||||
|
if result is None:
|
||||||
|
return {
|
||||||
|
'error': f'执行超时({timeout}s)',
|
||||||
|
'timeout': True,
|
||||||
|
'note': '进程内执行无法强杀线程,被放弃的代码可能仍在后台运行',
|
||||||
|
}
|
||||||
|
exit_code, stdout_text, stderr_text = result
|
||||||
|
return {
|
||||||
|
'exit_code': exit_code,
|
||||||
|
'stdout': stdout_text[-12000:],
|
||||||
|
'stderr': stderr_text[-6000:],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 注册表
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
BUILTIN_TOOLS = {
|
||||||
|
'shell': {'spec': SHELL_TOOL, 'run': shell_run},
|
||||||
|
'python_run': {'spec': PYTHON_RUN_TOOL, 'run': python_run},
|
||||||
|
}
|
||||||
241
android/kernel/defaults.py
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
"""
|
||||||
|
常量表:提供商预设、默认设置、内置智能体。
|
||||||
|
|
||||||
|
这些值必须和 Node 版 server/src/config.mjs、server/src/agents.mjs 逐字段一致,
|
||||||
|
否则 Lynx 前端读到的设置会出现"字段名对但默认值不同"的细微差异。
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEFAULT_SYSTEM_PROMPT = '\n'.join(
|
||||||
|
[
|
||||||
|
'你是豆包,一个由字节跳动开发的 AI 助手,风格自然、亲切、简洁。',
|
||||||
|
'',
|
||||||
|
'回答要求:',
|
||||||
|
'1. 用简体中文回答,除非用户要求其他语言。',
|
||||||
|
'2. 先给结论,再给必要的解释,避免空话和过度铺垫。',
|
||||||
|
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||||
|
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||||
|
'5. 不确定的信息要明确标注不确定。',
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
# 提供商预设。
|
||||||
|
#
|
||||||
|
# 全都是 **OpenAI 兼容协议**(POST {baseUrl}/chat/completions),区别只有
|
||||||
|
# baseUrl、模型名,以及"思考强度怎么传"。
|
||||||
|
#
|
||||||
|
# thinkingMode 就是在说这件事,别写死成"非 ark 即 openai":
|
||||||
|
# 'ark' → 顶层 thinking: {type: enabled|disabled}(火山方舟、智谱 GLM 同形状)
|
||||||
|
# 'effort' → reasoning_effort: low|medium|high(OpenAI 推理模型、OpenRouter 透传)
|
||||||
|
# 'none' → 什么都不发。★ 安全默认值:给不认 reasoning_effort 的服务发这个字段,
|
||||||
|
# 有些会直接 400。DeepSeek / Kimi / 通义 / 硅基流动 的思考由模型自己决定。
|
||||||
|
PROVIDER_PRESETS = {
|
||||||
|
'ark': {
|
||||||
|
'label': '火山方舟(豆包)',
|
||||||
|
'baseUrl': 'https://ark.cn-beijing.volces.com/api/v3',
|
||||||
|
'apiKeyEnv': 'ARK_API_KEY',
|
||||||
|
'defaultModel': 'doubao-seed-2-1-pro-260628',
|
||||||
|
'modelHint': '填模型 ID(如 doubao-seed-2-1-pro-260628)或推理接入点 ID(ep-xxxxxxxx)',
|
||||||
|
'docs': 'https://www.volcengine.com/docs/82379/1298454',
|
||||||
|
'thinkingMode': 'ark',
|
||||||
|
'models': [
|
||||||
|
'doubao-seed-2-1-pro-260628',
|
||||||
|
'doubao-seed-1-8-251228',
|
||||||
|
'deepseek-r1-250528',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
'openai': {
|
||||||
|
'label': 'OpenAI 官方',
|
||||||
|
'baseUrl': 'https://api.openai.com/v1',
|
||||||
|
'apiKeyEnv': 'OPENAI_API_KEY',
|
||||||
|
'defaultModel': 'gpt-4o-mini',
|
||||||
|
'modelHint': '填 model 名称;推理模型(o 系 / gpt-5 系)会自动剥离 temperature 等参数',
|
||||||
|
'docs': 'https://platform.openai.com/docs/api-reference/chat',
|
||||||
|
'thinkingMode': 'effort',
|
||||||
|
'models': ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-5-mini'],
|
||||||
|
},
|
||||||
|
'deepseek': {
|
||||||
|
'label': 'DeepSeek',
|
||||||
|
'baseUrl': 'https://api.deepseek.com/v1',
|
||||||
|
'apiKeyEnv': 'DEEPSEEK_API_KEY',
|
||||||
|
'defaultModel': 'deepseek-chat',
|
||||||
|
'modelHint': 'deepseek-chat 是通用对话;deepseek-reasoner 会自动返回思维链',
|
||||||
|
'docs': 'https://api-docs.deepseek.com/zh-cn/',
|
||||||
|
'thinkingMode': 'none',
|
||||||
|
'models': ['deepseek-chat', 'deepseek-reasoner'],
|
||||||
|
},
|
||||||
|
'kimi': {
|
||||||
|
'label': 'Kimi(月之暗面)',
|
||||||
|
'baseUrl': 'https://api.moonshot.cn/v1',
|
||||||
|
'apiKeyEnv': 'MOONSHOT_API_KEY',
|
||||||
|
'defaultModel': 'kimi-k2-0905-preview',
|
||||||
|
'modelHint': 'Kimi K2 支持工具调用;moonshot-v1-* 是上一代长文本模型',
|
||||||
|
'docs': 'https://platform.moonshot.cn/docs/api/chat',
|
||||||
|
'thinkingMode': 'none',
|
||||||
|
'models': ['kimi-k2-0905-preview', 'kimi-latest', 'moonshot-v1-128k'],
|
||||||
|
},
|
||||||
|
'zhipu': {
|
||||||
|
'label': '智谱 GLM',
|
||||||
|
'baseUrl': 'https://open.bigmodel.cn/api/paas/v4',
|
||||||
|
'apiKeyEnv': 'ZHIPU_API_KEY',
|
||||||
|
'defaultModel': 'glm-4.6',
|
||||||
|
'modelHint': 'GLM 的思考开关和方舟同形状(顶层 thinking),已按这个发',
|
||||||
|
'docs': 'https://docs.bigmodel.cn/cn/guide/develop/openai/introduction',
|
||||||
|
'thinkingMode': 'ark',
|
||||||
|
'models': ['glm-4.6', 'glm-4.5', 'glm-4-flash'],
|
||||||
|
},
|
||||||
|
'dashscope': {
|
||||||
|
'label': '通义千问(阿里云)',
|
||||||
|
'baseUrl': 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||||
|
'apiKeyEnv': 'DASHSCOPE_API_KEY',
|
||||||
|
'defaultModel': 'qwen-plus',
|
||||||
|
'modelHint': 'Qwen3 系列自己会思考,这里不发思考参数',
|
||||||
|
'docs': 'https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope',
|
||||||
|
'thinkingMode': 'none',
|
||||||
|
'models': ['qwen3-max', 'qwen-plus', 'qwen-turbo'],
|
||||||
|
},
|
||||||
|
'siliconflow': {
|
||||||
|
'label': '硅基流动',
|
||||||
|
'baseUrl': 'https://api.siliconflow.cn/v1',
|
||||||
|
'apiKeyEnv': 'SILICONFLOW_API_KEY',
|
||||||
|
'defaultModel': 'deepseek-ai/DeepSeek-V3',
|
||||||
|
'modelHint': '模型名带斜杠(组织/模型),例如 deepseek-ai/DeepSeek-V3',
|
||||||
|
'docs': 'https://docs.siliconflow.cn/cn/api-reference/chat-completions/chat-completions',
|
||||||
|
'thinkingMode': 'none',
|
||||||
|
'models': ['deepseek-ai/DeepSeek-V3', 'Qwen/Qwen3-235B-A22B', 'THUDM/glm-4-9b-chat'],
|
||||||
|
},
|
||||||
|
'openrouter': {
|
||||||
|
'label': 'OpenRouter(聚合)',
|
||||||
|
'baseUrl': 'https://openrouter.ai/api/v1',
|
||||||
|
'apiKeyEnv': 'OPENROUTER_API_KEY',
|
||||||
|
'defaultModel': 'openai/gpt-4o-mini',
|
||||||
|
'modelHint': '一个 Key 调各家模型,模型名是「厂商/模型」;会透传 reasoning_effort',
|
||||||
|
'docs': 'https://openrouter.ai/docs/api-reference/overview',
|
||||||
|
'thinkingMode': 'effort',
|
||||||
|
'models': ['openai/gpt-4o-mini', 'deepseek/deepseek-chat', 'anthropic/claude-3.5-sonnet'],
|
||||||
|
},
|
||||||
|
'ollama': {
|
||||||
|
'label': '本地 Ollama',
|
||||||
|
'baseUrl': 'http://127.0.0.1:11434/v1',
|
||||||
|
'apiKeyEnv': 'OLLAMA_API_KEY',
|
||||||
|
'defaultModel': 'qwen2.5:7b',
|
||||||
|
'modelHint': '本地跑,Key 随便填(Ollama 不校验)。手机连电脑要填电脑的局域网 IP',
|
||||||
|
'docs': 'https://github.com/ollama/ollama/blob/main/docs/openai.md',
|
||||||
|
'thinkingMode': 'none',
|
||||||
|
'models': ['qwen2.5:7b', 'llama3.1:8b', 'deepseek-r1:7b'],
|
||||||
|
},
|
||||||
|
'custom': {
|
||||||
|
'label': '自定义(任意兼容网关)',
|
||||||
|
'baseUrl': '',
|
||||||
|
'apiKeyEnv': 'CUSTOM_API_KEY',
|
||||||
|
'defaultModel': '',
|
||||||
|
'modelHint': '填完整的 /v1 地址和模型名,只要兼容 OpenAI 的 chat/completions 就能用',
|
||||||
|
'docs': '',
|
||||||
|
'thinkingMode': 'none',
|
||||||
|
'models': [],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
DEFAULT_SETTINGS = {
|
||||||
|
'provider': 'ark',
|
||||||
|
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||||
|
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||||
|
'apiKey': '',
|
||||||
|
'temperature': 0.7,
|
||||||
|
'maxRounds': 6,
|
||||||
|
# 思考强度:off / low / medium / high / auto
|
||||||
|
# - 方舟:映射到顶层 thinking 字段
|
||||||
|
# - OpenAI:映射到 reasoning_effort(推理模型)
|
||||||
|
'thinkingLevel': 'auto',
|
||||||
|
# 额外工具目录(留空则用内置 tools/);安卓端可以指到手机上的目录
|
||||||
|
'toolsDir': '',
|
||||||
|
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
|
||||||
|
'tools': {'python': True, 'mcp': True},
|
||||||
|
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
||||||
|
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
||||||
|
'speech': {
|
||||||
|
'ttsEngine': 'system', # system | volc | openai
|
||||||
|
'ttsVoice': '', # volc: voice_type;openai: alloy/nova/...
|
||||||
|
'ttsSpeed': 1.0,
|
||||||
|
'autoRead': False, # 新回复自动念出来
|
||||||
|
'sttEngine': 'system', # system | openai
|
||||||
|
'sttModel': 'whisper-1',
|
||||||
|
'sttLanguage': '', # 留空 = 自动判断
|
||||||
|
'volcAppId': '',
|
||||||
|
'volcToken': '',
|
||||||
|
'volcCluster': 'volcano_tts',
|
||||||
|
'volcEncoding': 'mp3',
|
||||||
|
'openaiApiKey': '', # 留空则复用主对话的 Key
|
||||||
|
'openaiBaseUrl': '', # 留空则复用主对话的 Base URL
|
||||||
|
'ttsModel': 'tts-1',
|
||||||
|
},
|
||||||
|
# 安全模式:open 全部放行 / restricted 只放 allow 白名单
|
||||||
|
'security': {'mode': 'open', 'allow': []},
|
||||||
|
# Node 版用它指定解释器;Python 内核在进程内执行工具,这个字段只为兼容而保留
|
||||||
|
'pythonBin': '',
|
||||||
|
'nickname': '我',
|
||||||
|
'doubaoId': '378269252',
|
||||||
|
'activeAgentId': 'a_doubao',
|
||||||
|
}
|
||||||
|
|
||||||
|
SECRET_KEYS = {'apiKey'}
|
||||||
|
|
||||||
|
# 内置智能体(前端有同名头像,靠 avatar 字段对应)
|
||||||
|
DEFAULT_AGENTS = [
|
||||||
|
{
|
||||||
|
'id': 'a_doubao',
|
||||||
|
'name': '豆包',
|
||||||
|
'avatar': 'doubao',
|
||||||
|
'tagline': '通用助手',
|
||||||
|
'systemPrompt': '',
|
||||||
|
'builtin': True,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 'a_coder',
|
||||||
|
'name': '代码搭子',
|
||||||
|
'avatar': 'coder',
|
||||||
|
'tagline': '只聊代码,直接给能跑的',
|
||||||
|
'systemPrompt': '\n'.join(
|
||||||
|
[
|
||||||
|
'你是一个资深工程师。',
|
||||||
|
'1. 先给可以直接复制运行的代码,再解释关键点。',
|
||||||
|
'2. 代码里不要有省略号,不要写"此处省略"。',
|
||||||
|
'3. 指出你方案里的坑和替代做法。',
|
||||||
|
'4. 涉及文件读写、执行命令时优先调用可用工具。',
|
||||||
|
]
|
||||||
|
),
|
||||||
|
'builtin': True,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 'a_writer',
|
||||||
|
'name': '文案师',
|
||||||
|
'avatar': 'writer',
|
||||||
|
'tagline': '写东西、改稿子',
|
||||||
|
'systemPrompt': '\n'.join(
|
||||||
|
[
|
||||||
|
'你是中文文案编辑。',
|
||||||
|
'1. 先问清楚用途、受众、字数要求,信息不全就按最常见的场景先给一版。',
|
||||||
|
'2. 给成品,不要给"写作思路"。',
|
||||||
|
'3. 口语化、短句、少用形容词堆砌,别用"赋能/闭环/抓手"这类词。',
|
||||||
|
]
|
||||||
|
),
|
||||||
|
'builtin': True,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 'a_analyst',
|
||||||
|
'name': '数据分析',
|
||||||
|
'avatar': 'analyst',
|
||||||
|
'tagline': '算数、看数据、讲结论',
|
||||||
|
'systemPrompt': '\n'.join(
|
||||||
|
[
|
||||||
|
'你是数据分析师。',
|
||||||
|
'1. 任何计算都必须调用 calc 工具,不要心算。',
|
||||||
|
'2. 先给结论,再给口径和数据来源。',
|
||||||
|
'3. 样本不足或数据可疑时直接说出来。',
|
||||||
|
]
|
||||||
|
),
|
||||||
|
'builtin': True,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
# 可选头像(前端有同名 SVG,这里只做白名单校验)
|
||||||
|
AVATAR_KEYS = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'robot', 'star', 'cloud', 'custom']
|
||||||
373
android/kernel/doubao_entry.py
Normal file
@@ -0,0 +1,373 @@
|
|||||||
|
"""
|
||||||
|
安卓端入口:Kotlin 侧通过 Chaquopy 调 `start(data_dir, work_dir, port)`。
|
||||||
|
|
||||||
|
为什么要有这个文件:
|
||||||
|
Chaquopy 把 CPython 嵌进 App 主进程,没有 `python` 可执行文件,
|
||||||
|
所以不能像电脑上那样 `python main.py --port 5199`,只能由 Kotlin 直接调函数。
|
||||||
|
这里把「准备目录 → 播种内置工具 → 注册原生能力 → 起 HTTP 服务」串起来。
|
||||||
|
|
||||||
|
与电脑端 Node 内核的关系:
|
||||||
|
接口完全一致,Lynx 前端不用改,只是把 apiBase 指到 http://127.0.0.1:<port>。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
||||||
|
BUNDLED_TOOL_FILES = [
|
||||||
|
'_protocol.py',
|
||||||
|
'calc.py',
|
||||||
|
'now.py',
|
||||||
|
'weather.py',
|
||||||
|
'notes.py',
|
||||||
|
'web_fetch.py',
|
||||||
|
'shell.py',
|
||||||
|
'python_run.py',
|
||||||
|
'_mcp_python_example.py',
|
||||||
|
]
|
||||||
|
|
||||||
|
_state = {'port': 0, 'handle': None, 'error': None}
|
||||||
|
_android = None
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 原生能力桥
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def set_android_bridge(bridge) -> None:
|
||||||
|
"""
|
||||||
|
Kotlin 传一个 NativeBridge 对象进来(Chaquopy 允许 Python 直接调它的方法)。
|
||||||
|
这里把它接到内核的钩子和 device 工具上。
|
||||||
|
"""
|
||||||
|
global _android
|
||||||
|
_android = bridge
|
||||||
|
try:
|
||||||
|
import app as kernel_app
|
||||||
|
|
||||||
|
kernel_app.set_native_hooks(
|
||||||
|
clipboard=lambda text: bridge.setClipboard(str(text)),
|
||||||
|
pick_file=lambda: list(bridge.pickFile() or []),
|
||||||
|
reveal=lambda path: bridge.reveal(str(path)),
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 钩子挂不上不该拦住内核启动
|
||||||
|
print(f'[entry] 注册原生钩子失败:{exc}', file=sys.stderr, flush=True)
|
||||||
|
|
||||||
|
_install_device_tool()
|
||||||
|
|
||||||
|
|
||||||
|
DEVICE_TOOL_SPEC = {
|
||||||
|
'name': 'device',
|
||||||
|
'description': (
|
||||||
|
'读取这台手机/平板的设备能力:位置(GPS)、运动传感器(加速度计/陀螺仪/磁场/气压/光线等)、'
|
||||||
|
'电量、系统信息、剪贴板。安卓端专属;电脑上会返回"不支持"。'
|
||||||
|
'用法:action 选 info/location/sensors/sensor/battery/clipboard_get/clipboard_set。'
|
||||||
|
'读某个传感器时传 sensor 参数(如 accelerometer / gyroscope / magnetic / light / pressure / proximity),'
|
||||||
|
'duration 是采样秒数(默认 1.5,最多 10)。'
|
||||||
|
),
|
||||||
|
'parameters': {
|
||||||
|
'type': 'object',
|
||||||
|
'properties': {
|
||||||
|
'action': {
|
||||||
|
'type': 'string',
|
||||||
|
'enum': [
|
||||||
|
'info', 'location', 'sensors', 'sensor', 'battery',
|
||||||
|
'clipboard_get', 'clipboard_set', 'termux_available', 'termux_run',
|
||||||
|
],
|
||||||
|
'description': '要做的事,默认 info',
|
||||||
|
},
|
||||||
|
'sensor': {'type': 'string', 'description': '传感器名,见 action=sensors 的返回'},
|
||||||
|
'duration': {'type': 'number', 'description': '采样秒数,默认 1.5'},
|
||||||
|
'text': {'type': 'string', 'description': 'action=clipboard_set 时要写入的内容'},
|
||||||
|
'command': {'type': 'string', 'description': 'action=termux_run 时要在 Termux 里跑的命令'},
|
||||||
|
'cwd': {'type': 'string', 'description': 'action=termux_run 的工作目录'},
|
||||||
|
'timeout': {'type': 'number', 'description': 'action=termux_run 的超时秒数'},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def device_run(args: dict) -> dict:
|
||||||
|
if _android is None:
|
||||||
|
return {'error': '当前环境没有安卓原生桥(电脑端请用 shell 工具)'}
|
||||||
|
action = str(args.get('action') or 'info')
|
||||||
|
payload = json.dumps(
|
||||||
|
{
|
||||||
|
'action': action,
|
||||||
|
'sensor': args.get('sensor') or '',
|
||||||
|
'duration': float(args.get('duration') or 1.5),
|
||||||
|
'text': args.get('text') or '',
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
raw = _android.device(payload)
|
||||||
|
try:
|
||||||
|
return json.loads(str(raw))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return {'raw': str(raw)}
|
||||||
|
|
||||||
|
|
||||||
|
def _install_device_tool() -> None:
|
||||||
|
"""把 device 工具塞进内核的内置工具表,并把 shell 换成「优先走 Termux」的版本"""
|
||||||
|
try:
|
||||||
|
import builtin_tools
|
||||||
|
|
||||||
|
builtin_tools.BUILTIN_TOOLS['device'] = {'spec': DEVICE_TOOL_SPEC, 'run': device_run}
|
||||||
|
builtin_tools.BUILTIN_TOOLS['shell'] = {'spec': SHELL_TOOL_SPEC, 'run': shell_run}
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
print(f'[entry] 注册 device 工具失败:{exc}', file=sys.stderr, flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
SHELL_TOOL_SPEC = {
|
||||||
|
'name': 'shell',
|
||||||
|
'description': (
|
||||||
|
'在手机的终端里执行一条 shell 命令,返回退出码、标准输出和标准错误。'
|
||||||
|
'装了 Termux 就走 Termux(完整 Linux 用户态,bash/apt/pip 都能用);'
|
||||||
|
'没装则退回到系统自带的 toybox shell(命令比 GNU 少,比如没有 grep -P、没有 apt)。'
|
||||||
|
'危险命令会被拦截。'
|
||||||
|
),
|
||||||
|
'parameters': {
|
||||||
|
'type': 'object',
|
||||||
|
'properties': {
|
||||||
|
'command': {'type': 'string', 'description': '要执行的命令'},
|
||||||
|
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||||||
|
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||||||
|
},
|
||||||
|
'required': ['command'],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Termux 探测状态:
|
||||||
|
# None = 还没试过;True = 可用;False = 试过但不可用
|
||||||
|
# 不可用时会在 _TERMUX_RETRY_AFTER 秒内直接走系统 shell,
|
||||||
|
# 否则每条命令都要先干等一次超时(实测 user 装了 Termux 但没开
|
||||||
|
# allow-external-apps 时,每条命令白等 30 秒,体验极差)。
|
||||||
|
_termux_ok = None
|
||||||
|
_termux_fail_until = 0.0
|
||||||
|
_TERMUX_FIRST_PROBE_S = 8
|
||||||
|
_TERMUX_RETRY_AFTER = 300
|
||||||
|
|
||||||
|
|
||||||
|
def _try_termux(command: str, cwd: str, timeout: int):
|
||||||
|
"""能走 Termux 就走,返回结果 dict;走不了返回 None"""
|
||||||
|
global _termux_ok, _termux_fail_until
|
||||||
|
|
||||||
|
import time as _time
|
||||||
|
|
||||||
|
now = _time.time()
|
||||||
|
if _termux_ok is False and now < _termux_fail_until:
|
||||||
|
return None
|
||||||
|
if _android is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 第一次只等很短:装了但没开外部命令时会秒回 errmsg,没装则更快
|
||||||
|
wait = min(timeout, _TERMUX_FIRST_PROBE_S) if _termux_ok is None else timeout
|
||||||
|
try:
|
||||||
|
raw = _android.device(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
'action': 'termux_run',
|
||||||
|
'command': command,
|
||||||
|
'cwd': cwd,
|
||||||
|
'timeout': wait,
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
res = json.loads(str(raw))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
res = {'error': f'{type(exc).__name__}: {exc}'}
|
||||||
|
|
||||||
|
if res.get('available') and not res.get('error'):
|
||||||
|
_termux_ok = True
|
||||||
|
return res
|
||||||
|
|
||||||
|
if res.get('installed') is False:
|
||||||
|
# 压根没装,以后别再试了(本次进程内)
|
||||||
|
_termux_ok = False
|
||||||
|
_termux_fail_until = now + 1e9
|
||||||
|
else:
|
||||||
|
_termux_ok = False
|
||||||
|
_termux_fail_until = now + _TERMUX_RETRY_AFTER
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def shell_run(args: dict) -> dict:
|
||||||
|
"""
|
||||||
|
安卓上的 shell:优先交给 Termux(有真 bash/apt/pip),没有就退回 /system/bin/sh。
|
||||||
|
|
||||||
|
为什么要这么绕:APK 自带的 CPython 是嵌在主进程里的,没有可执行文件、起不了子进程;
|
||||||
|
而 Termux 是个完整 Linux 用户态,借它的 bash 能跑通绝大多数命令。
|
||||||
|
"""
|
||||||
|
from builtin_tools import shell_run as fallback_shell # 内置实现(toybox / cmd)
|
||||||
|
|
||||||
|
command = str(args.get('command') or '').strip()
|
||||||
|
if not command or _android is None:
|
||||||
|
return fallback_shell(args)
|
||||||
|
|
||||||
|
timeout = max(1, min(300, int(args.get('timeout', 30) or 30)))
|
||||||
|
hit = _try_termux(command, str(args.get('cwd') or ''), timeout)
|
||||||
|
if hit is not None:
|
||||||
|
return {
|
||||||
|
'exit_code': hit.get('exit_code', 0),
|
||||||
|
'stdout': str(hit.get('stdout') or '')[-8000:],
|
||||||
|
'stderr': str(hit.get('stderr') or '')[-4000:],
|
||||||
|
'via': 'termux',
|
||||||
|
}
|
||||||
|
|
||||||
|
out = fallback_shell(args)
|
||||||
|
if isinstance(out, dict):
|
||||||
|
out['via'] = 'toybox'
|
||||||
|
if _termux_ok is False:
|
||||||
|
out['termux_note'] = (
|
||||||
|
'Termux 没能接管(装的没装、或没开 allow-external-apps)。'
|
||||||
|
'想要完整 Linux 环境:在 Termux 里执行 '
|
||||||
|
'echo "allow-external-apps=true" >> ~/.termux/termux.properties 然后重开 Termux。'
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 目录准备
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def _module_source(name: str):
|
||||||
|
"""取内置 py 工具的源码。Chaquopy 里文件在 APK 内,不能直接 open(),得走 loader。"""
|
||||||
|
try:
|
||||||
|
spec = importlib.util.find_spec(name)
|
||||||
|
except (ImportError, ValueError):
|
||||||
|
return None
|
||||||
|
if spec is None:
|
||||||
|
return None
|
||||||
|
loader = spec.loader
|
||||||
|
if loader is not None and hasattr(loader, 'get_source'):
|
||||||
|
try:
|
||||||
|
return loader.get_source(name)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
origin = getattr(spec, 'origin', None)
|
||||||
|
if origin and os.path.isfile(origin):
|
||||||
|
with open(origin, encoding='utf-8') as fh:
|
||||||
|
return fh.read()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_tools(tools_dir: str) -> int:
|
||||||
|
"""
|
||||||
|
首次运行把内置工具写到手机上的可写目录。
|
||||||
|
之后用户就能自己改、自己加(设置里的"工具目录"指向这里)。
|
||||||
|
|
||||||
|
源码来源优先级:
|
||||||
|
1) bundled_tool_sources(构建时嵌进来的 base64 源码)—— 安卓上唯一可靠的来源,
|
||||||
|
因为 Chaquopy 只留 .pyc,loader.get_source() 拿不到源码
|
||||||
|
2) 直接从模块读源码 —— 电脑上跑时用这条
|
||||||
|
"""
|
||||||
|
os.makedirs(tools_dir, exist_ok=True)
|
||||||
|
wanted = {name: _module_source(name[:-3]) for name in BUNDLED_TOOL_FILES}
|
||||||
|
|
||||||
|
try:
|
||||||
|
import bundled_tool_sources # type: ignore[import-not-found]
|
||||||
|
|
||||||
|
for name, source in bundled_tool_sources.sources().items():
|
||||||
|
wanted[name] = source
|
||||||
|
except Exception: # noqa: BLE001 - 电脑上没有这个生成文件,正常
|
||||||
|
pass
|
||||||
|
|
||||||
|
copied = 0
|
||||||
|
for filename, source in wanted.items():
|
||||||
|
if not source:
|
||||||
|
continue
|
||||||
|
dest = os.path.join(tools_dir, filename)
|
||||||
|
if os.path.exists(dest):
|
||||||
|
continue
|
||||||
|
with open(dest, 'w', encoding='utf-8') as fh:
|
||||||
|
fh.write(source)
|
||||||
|
copied += 1
|
||||||
|
return copied
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_mcp_config(data_dir: str) -> None:
|
||||||
|
"""
|
||||||
|
安卓上默认不配任何 MCP 服务。
|
||||||
|
为什么:出厂那份配置里的 npx/filesystem 在手机上根本跑不起来,
|
||||||
|
自动连接只会每次都报错,不如留空让用户自己加(设置页有图形化编辑)。
|
||||||
|
"""
|
||||||
|
target = os.path.join(data_dir, 'mcp.servers.json')
|
||||||
|
if os.path.exists(target):
|
||||||
|
return
|
||||||
|
with open(target, 'w', encoding='utf-8') as fh:
|
||||||
|
json.dump({'servers': []}, fh, ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
|
||||||
|
def tools_dir_for(work_dir: str) -> str:
|
||||||
|
return os.path.join(work_dir, 'tools')
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 启动
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def start(data_dir: str, work_dir: str, port: int = 5199) -> int:
|
||||||
|
"""
|
||||||
|
起内核(不阻塞)。返回**实际**监听的端口。
|
||||||
|
Kotlin 侧在子线程里调它,然后在主线程轮询 /api/health 再挂载 LynxView。
|
||||||
|
"""
|
||||||
|
with _lock:
|
||||||
|
if _state['port']:
|
||||||
|
return _state['port']
|
||||||
|
|
||||||
|
os.makedirs(data_dir, exist_ok=True)
|
||||||
|
os.makedirs(work_dir, exist_ok=True)
|
||||||
|
tools_dir = tools_dir_for(work_dir)
|
||||||
|
copied = _seed_tools(tools_dir)
|
||||||
|
_ensure_mcp_config(data_dir)
|
||||||
|
|
||||||
|
# 让 import 能找到可写目录里的工具(用户自己加的)
|
||||||
|
if tools_dir not in sys.path:
|
||||||
|
sys.path.insert(0, tools_dir)
|
||||||
|
|
||||||
|
_install_device_tool()
|
||||||
|
|
||||||
|
import main as kernel_main
|
||||||
|
|
||||||
|
last_error = None
|
||||||
|
for candidate in (port, 0):
|
||||||
|
try:
|
||||||
|
handle = kernel_main.start_kernel(
|
||||||
|
host='127.0.0.1',
|
||||||
|
port=candidate,
|
||||||
|
data_dir=data_dir,
|
||||||
|
tools_dir=tools_dir,
|
||||||
|
quiet=True,
|
||||||
|
autostart_mcp=True,
|
||||||
|
)
|
||||||
|
_state.update({'port': handle.port, 'handle': handle})
|
||||||
|
print(
|
||||||
|
f'[entry] 内核已启动 127.0.0.1:{handle.port} '
|
||||||
|
f'工具目录={tools_dir}(新播种 {copied} 个)',
|
||||||
|
file=sys.stderr,
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return handle.port
|
||||||
|
except OSError as exc: # 端口被占:再试一次随机端口
|
||||||
|
last_error = exc
|
||||||
|
print(f'[entry] 端口 {candidate} 起不来({exc}),换个端口重试', file=sys.stderr, flush=True)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
last_error = exc
|
||||||
|
_state['error'] = f'{type(exc).__name__}: {exc}'
|
||||||
|
print(f'[entry] 内核启动失败:{exc!r}', file=sys.stderr, flush=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
raise RuntimeError(f'内核起不来:{last_error}')
|
||||||
|
|
||||||
|
|
||||||
|
def status() -> str:
|
||||||
|
return json.dumps(
|
||||||
|
{'port': _state['port'], 'error': _state['error'], 'android': _android is not None},
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
220
android/kernel/main.py
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
"""
|
||||||
|
豆鲍 Python 内核入口。
|
||||||
|
|
||||||
|
两种用法:
|
||||||
|
|
||||||
|
1) 命令行(开发/桌面调试,Windows 上也能直接跑):
|
||||||
|
python android/kernel/main.py --port 5399 --data-dir <临时目录> --tools-dir tools
|
||||||
|
python -m android.kernel --port 5399 --data-dir <临时目录> --tools-dir tools
|
||||||
|
|
||||||
|
2) 安卓(Chaquopy)里被 Kotlin 调用:
|
||||||
|
from main import start_kernel
|
||||||
|
handle = start_kernel(port=0, data_dir='/data/data/<包名>/files', tools_dir=...)
|
||||||
|
handle.port # 实际监听端口(port=0 时由系统分配)
|
||||||
|
|
||||||
|
之所以要支持"进程内启动",是因为安卓上没有 node、也没有独立 python,
|
||||||
|
内核只能作为库跑在 App 进程里,由 Kotlin 决定端口和数据目录。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
# 先让本目录进 sys.path,再用扁平导入(和 tools/*.py 的写法一致)
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
if _HERE not in sys.path:
|
||||||
|
sys.path.insert(0, _HERE)
|
||||||
|
|
||||||
|
import app # noqa: E402
|
||||||
|
import mcp_client # noqa: E402
|
||||||
|
import paths # noqa: E402
|
||||||
|
import store # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _setup_stdio() -> None:
|
||||||
|
"""
|
||||||
|
Windows 管道/安卓 logcat 的默认编码经常不是 UTF-8,中文日志会炸 UnicodeEncodeError。
|
||||||
|
这里统一按 UTF-8 + replace 输出(Python 3.7+ 才有 reconfigure)。
|
||||||
|
"""
|
||||||
|
for stream in (sys.stdout, sys.stderr):
|
||||||
|
reconfigure = getattr(stream, 'reconfigure', None)
|
||||||
|
if callable(reconfigure):
|
||||||
|
try:
|
||||||
|
reconfigure(encoding='utf-8', errors='replace')
|
||||||
|
except (ValueError, OSError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class KernelHandle:
|
||||||
|
"""启动后的句柄:能拿到真实端口,也能优雅关掉。"""
|
||||||
|
|
||||||
|
def __init__(self, server, host: str, port: int, data_dir: str, config: dict):
|
||||||
|
self.server = server
|
||||||
|
self.host = host
|
||||||
|
self.port = port
|
||||||
|
self.data_dir = data_dir
|
||||||
|
self.config = config
|
||||||
|
self.url = f'http://{host}:{port}/'
|
||||||
|
self._thread = None
|
||||||
|
|
||||||
|
def serve_forever_in_thread(self) -> threading.Thread:
|
||||||
|
self._thread = threading.Thread(target=self.server.serve_forever, name='doubao-http', daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
return self._thread
|
||||||
|
|
||||||
|
def shutdown(self) -> None:
|
||||||
|
try:
|
||||||
|
self.server.shutdown()
|
||||||
|
except Exception: # noqa: BLE001 - 关服务失败不值得抛给调用方
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
self.server.server_close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
mcp_client.disconnect_all()
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
'ok': True,
|
||||||
|
'host': self.host,
|
||||||
|
'port': self.port,
|
||||||
|
'url': self.url,
|
||||||
|
'dataDir': self.data_dir,
|
||||||
|
'settingsFile': self.config.get('settingsFile'),
|
||||||
|
'toolsDir': self.config.get('toolsDir'),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def start_kernel(
|
||||||
|
host: str = '127.0.0.1',
|
||||||
|
port: int = 5199,
|
||||||
|
data_dir: str | None = None,
|
||||||
|
tools_dir: str | None = None,
|
||||||
|
web_dir: str | None = None,
|
||||||
|
dist_dir: str | None = None,
|
||||||
|
web_core_dir: str | None = None,
|
||||||
|
quiet: bool = False,
|
||||||
|
autostart_mcp: bool = True,
|
||||||
|
) -> KernelHandle:
|
||||||
|
"""
|
||||||
|
建目录 → 建 HTTP 服务 → 后台线程 serve_forever → (可选)连 MCP。
|
||||||
|
|
||||||
|
注意:这个函数**不阻塞**,安卓侧可以安全地在任意线程里调用。
|
||||||
|
"""
|
||||||
|
app.QUIET = quiet
|
||||||
|
config = paths.configure(
|
||||||
|
data_dir=data_dir,
|
||||||
|
tools_dir=tools_dir,
|
||||||
|
web_dir=web_dir,
|
||||||
|
dist_dir=dist_dir,
|
||||||
|
web_core_dir=web_core_dir,
|
||||||
|
)
|
||||||
|
# 首次运行把内置 mcp.servers.json 复制到数据目录(用户改的是可写的那份)
|
||||||
|
mcp_client.ensure_mcp_config()
|
||||||
|
|
||||||
|
server = app.create_server(host, port)
|
||||||
|
handle = KernelHandle(server, host, server.server_address[1], config.data_dir, config.as_dict())
|
||||||
|
handle.serve_forever_in_thread()
|
||||||
|
|
||||||
|
if not quiet:
|
||||||
|
settings = store.read_settings()
|
||||||
|
provider = store.provider_info(settings)
|
||||||
|
print('')
|
||||||
|
print(' Doubao Clone · AI kernel started (Python, stdlib only)')
|
||||||
|
print(f' ├─ UI {handle.url}')
|
||||||
|
print(f' ├─ provider {settings.get("provider")} · {provider.get("model")}')
|
||||||
|
print(f' ├─ api key {"configured" if settings.get("apiKey") else "missing (set it in Settings, or the data dir .env)"}')
|
||||||
|
print(f' ├─ tools python={settings.get("tools", {}).get("python")} mcp={settings.get("tools", {}).get("mcp")}')
|
||||||
|
print(f' ├─ data {config.data_dir}')
|
||||||
|
print(f' ├─ tools dir {config.tools_dir}')
|
||||||
|
print(f' └─ static web={config.web_dir}')
|
||||||
|
print('', flush=True)
|
||||||
|
|
||||||
|
if autostart_mcp:
|
||||||
|
def _connect():
|
||||||
|
try:
|
||||||
|
results = mcp_client.connect_all_enabled()
|
||||||
|
if results and not quiet:
|
||||||
|
summary = ', '.join(
|
||||||
|
f"{r.get('name')}={'ok' if r.get('ok') else 'fail'}" for r in results
|
||||||
|
)
|
||||||
|
print(f'[mcp] 启动连接:{summary}', flush=True)
|
||||||
|
except Exception as exc: # noqa: BLE001 - MCP 挂了不能影响内核
|
||||||
|
print(f'[mcp] 启动连接失败:{exc}', file=sys.stderr)
|
||||||
|
|
||||||
|
threading.Thread(target=_connect, name='mcp-autostart', daemon=True).start()
|
||||||
|
|
||||||
|
return handle
|
||||||
|
|
||||||
|
|
||||||
|
def build_parser() -> argparse.ArgumentParser:
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
prog='doubao-kernel',
|
||||||
|
description='豆鲍 AI 内核(纯标准库 Python 版,接口与 Node 版一致)',
|
||||||
|
)
|
||||||
|
parser.add_argument('--host', default=os.environ.get('HOST') or '127.0.0.1', help='监听地址,默认 127.0.0.1')
|
||||||
|
parser.add_argument(
|
||||||
|
'--port',
|
||||||
|
type=int,
|
||||||
|
default=int(os.environ.get('DOUBAO_PORT') or os.environ.get('PORT') or 5199),
|
||||||
|
help='监听端口,默认 5199(0 = 由系统分配,安卓上推荐)',
|
||||||
|
)
|
||||||
|
parser.add_argument('--data-dir', default=None,
|
||||||
|
help='可写数据目录(settings/conversations/agents/uploads),安卓上指到 App 私有目录')
|
||||||
|
parser.add_argument('--tools-dir', default=None, help='工具目录(默认仓库里的 tools/)')
|
||||||
|
parser.add_argument('--web-dir', default=None, help='宿主页目录(默认仓库里的 web/)')
|
||||||
|
parser.add_argument('--dist-dir', default=None, help='Lynx 产物目录(默认 app/dist)')
|
||||||
|
parser.add_argument('--web-core', default=None, help='@lynx-js/web-core 静态资源目录')
|
||||||
|
parser.add_argument('--no-mcp-autostart', action='store_true', help='启动时不自动连 MCP 服务器')
|
||||||
|
parser.add_argument('--quiet', action='store_true', help='不打印访问日志和启动横幅')
|
||||||
|
parser.add_argument('--json', action='store_true', help='启动后打印一行 JSON(含真实端口),便于脚本拉起')
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None) -> int:
|
||||||
|
_setup_stdio()
|
||||||
|
args = build_parser().parse_args(argv)
|
||||||
|
handle = start_kernel(
|
||||||
|
host=args.host,
|
||||||
|
port=args.port,
|
||||||
|
data_dir=args.data_dir,
|
||||||
|
tools_dir=args.tools_dir,
|
||||||
|
web_dir=args.web_dir,
|
||||||
|
dist_dir=args.dist_dir,
|
||||||
|
web_core_dir=args.web_core,
|
||||||
|
quiet=args.quiet or args.json,
|
||||||
|
autostart_mcp=not args.no_mcp_autostart,
|
||||||
|
)
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps(handle.as_dict(), ensure_ascii=False), flush=True)
|
||||||
|
|
||||||
|
stop = threading.Event()
|
||||||
|
|
||||||
|
def _on_signal(signum, _frame): # noqa: ANN001 - 信号回调签名固定
|
||||||
|
print(f'\n[kernel] 收到信号 {signum},正在退出…', file=sys.stderr)
|
||||||
|
stop.set()
|
||||||
|
|
||||||
|
for name in ('SIGINT', 'SIGTERM'):
|
||||||
|
sig = getattr(signal, name, None)
|
||||||
|
if sig is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
signal.signal(sig, _on_signal)
|
||||||
|
except (ValueError, OSError, RuntimeError):
|
||||||
|
# 非主线程/安卓上不允许注册信号:退化成 Ctrl+C 之外无法优雅停机
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
while not stop.is_set():
|
||||||
|
stop.wait(1)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
handle.shutdown()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
983
android/kernel/mcp_client.py
Normal file
@@ -0,0 +1,983 @@
|
|||||||
|
"""
|
||||||
|
MCP(Model Context Protocol)客户端。
|
||||||
|
|
||||||
|
对应 Node 版 server/src/mcp.mjs,但**不依赖官方 `mcp` 包** —— 手写 JSON-RPC 2.0。
|
||||||
|
原因:安卓上 pip/Node 包都装不进 APK;而 MCP 的线协议就是 JSON-RPC 2.0,
|
||||||
|
initialize / tools/list / tools/call 三步自己发就够了。
|
||||||
|
|
||||||
|
支持三种传输:
|
||||||
|
http Streamable HTTP:POST JSON-RPC,Accept 同时带 application/json 和 text/event-stream
|
||||||
|
stdio 起子进程按行收发(安卓上不可用,会给出明确报错而不是莫名卡死)
|
||||||
|
inproc 安卓专用:import 一个 .py,用队列 + 线程在内存里跑 JSON-RPC。
|
||||||
|
约定该文件暴露 `handle(request: dict) -> dict`(同步函数)。
|
||||||
|
|
||||||
|
对外工具名统一 `mcp__<server>__<tool>`,避免和 Python 工具重名。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import inspect
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import queue
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
import paths
|
||||||
|
|
||||||
|
PROTOCOL_VERSION = '2024-11-05'
|
||||||
|
CLIENT_INFO = {'name': 'doubao-kernel-py', 'version': '0.1.0'}
|
||||||
|
|
||||||
|
_clients: dict = {} # serverName -> {'spec','client','tools','error'}
|
||||||
|
_lock = threading.RLock()
|
||||||
|
|
||||||
|
_PENDING = object()
|
||||||
|
|
||||||
|
|
||||||
|
class McpError(RuntimeError):
|
||||||
|
"""MCP 层的任何错误(连接、协议、超时)都用它,便于统一转成 record.error。"""
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 配置文件
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def mcp_config_path() -> str:
|
||||||
|
return paths.get().mcp_file
|
||||||
|
|
||||||
|
|
||||||
|
def mcp_config_dir() -> str:
|
||||||
|
return os.path.dirname(mcp_config_path())
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_mcp_config() -> None:
|
||||||
|
"""
|
||||||
|
首次运行时把内置的 tools/mcp.servers.json 复制到数据目录。
|
||||||
|
和 Node 版一样:用户改的是自己可写的那份,升级程序不会覆盖。
|
||||||
|
"""
|
||||||
|
target = mcp_config_path()
|
||||||
|
bundled = os.path.join(paths.get().tools_dir, 'mcp.servers.json')
|
||||||
|
if os.path.isfile(target) or not os.path.isfile(bundled):
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||||
|
shutil.copyfile(bundled, target)
|
||||||
|
except OSError as exc:
|
||||||
|
print(f'[mcp] 初始化 mcp.servers.json 失败:{exc}', file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
_VAR_RE = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}')
|
||||||
|
|
||||||
|
|
||||||
|
def _expand(value):
|
||||||
|
"""展开 ${VAR} 占位符:打包/安卓上路径随机器变,写死绝对路径不合适。"""
|
||||||
|
if not isinstance(value, str):
|
||||||
|
return value
|
||||||
|
extra = {'DOUBAO_DATA': paths.get().data_dir}
|
||||||
|
|
||||||
|
def repl(match):
|
||||||
|
name = match.group(1)
|
||||||
|
return os.environ.get(name) or extra.get(name) or match.group(0)
|
||||||
|
|
||||||
|
return _VAR_RE.sub(repl, value)
|
||||||
|
|
||||||
|
|
||||||
|
def _expand_server(server: dict) -> dict:
|
||||||
|
return {
|
||||||
|
**server,
|
||||||
|
'command': _expand(server.get('command')),
|
||||||
|
'args': [_expand(a) for a in (server.get('args') or [])],
|
||||||
|
'url': _expand(server.get('url')),
|
||||||
|
'file': _expand(server.get('file')),
|
||||||
|
'env': {k: _expand(v) for k, v in (server.get('env') or {}).items()},
|
||||||
|
'headers': {k: _expand(v) for k, v in (server.get('headers') or {}).items()},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def read_mcp_config() -> dict:
|
||||||
|
file_path = mcp_config_path()
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
return {'servers': []}
|
||||||
|
try:
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as fh:
|
||||||
|
payload = json.load(fh)
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
print(f'[mcp] mcp.servers.json 解析失败:{exc}', file=sys.stderr)
|
||||||
|
return {'servers': [], 'error': str(exc)}
|
||||||
|
servers = payload if isinstance(payload, list) else payload.get('servers') or []
|
||||||
|
return {'servers': [_expand_server(s) for s in servers]}
|
||||||
|
|
||||||
|
|
||||||
|
def write_mcp_config(config: dict) -> None:
|
||||||
|
tmp = f'{mcp_config_path()}.tmp'
|
||||||
|
with open(tmp, 'w', encoding='utf-8') as fh:
|
||||||
|
json.dump(config, fh, ensure_ascii=False, indent=2)
|
||||||
|
os.replace(tmp, mcp_config_path())
|
||||||
|
|
||||||
|
|
||||||
|
def read_mcp_config_text() -> str:
|
||||||
|
file_path = mcp_config_path()
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
return '{\n "servers": []\n}\n'
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as fh:
|
||||||
|
return fh.read()
|
||||||
|
|
||||||
|
|
||||||
|
def write_mcp_config_text(text: str) -> int:
|
||||||
|
"""
|
||||||
|
保存界面里编辑的 JSON 文本:先校验再落盘,坏 JSON 不许写进去。
|
||||||
|
transport 白名单比 Node 版多一个 inproc(安卓专用)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
parsed = json.loads(text)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise McpError(f'JSON 格式错误:{exc}') from exc
|
||||||
|
servers = parsed if isinstance(parsed, list) else (parsed or {}).get('servers')
|
||||||
|
if not isinstance(servers, list):
|
||||||
|
raise McpError('顶层必须是 { "servers": [ ... ] } 或一个数组')
|
||||||
|
for index, server in enumerate(servers):
|
||||||
|
if not isinstance(server, dict):
|
||||||
|
raise McpError(f'第 {index + 1} 项不是对象')
|
||||||
|
name = server.get('name')
|
||||||
|
if not name:
|
||||||
|
raise McpError(f'第 {index + 1} 项缺少 name')
|
||||||
|
transport = server.get('transport') or 'stdio'
|
||||||
|
if transport not in ('stdio', 'http', 'sse', 'inproc'):
|
||||||
|
raise McpError(f'{name}: transport 只能是 stdio / http / sse / inproc')
|
||||||
|
if transport == 'stdio' and not server.get('command'):
|
||||||
|
raise McpError(f'{name}: stdio 需要 command')
|
||||||
|
if transport in ('http', 'sse') and not server.get('url'):
|
||||||
|
raise McpError(f'{name}: {transport} 需要 url')
|
||||||
|
if transport == 'inproc' and not (server.get('file') or server.get('path')):
|
||||||
|
raise McpError(f'{name}: inproc 需要 file(指向 .py 路径)')
|
||||||
|
if isinstance(parsed, list):
|
||||||
|
write_mcp_config({'servers': servers})
|
||||||
|
else:
|
||||||
|
# 保留顶层自定义字段(比如 note/注释),只覆盖 servers
|
||||||
|
merged = dict(parsed or {})
|
||||||
|
merged['servers'] = servers
|
||||||
|
write_mcp_config(merged)
|
||||||
|
return len(servers)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 传输层:http
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
class _HttpTransport:
|
||||||
|
"""Streamable HTTP:一个 POST 一次往返;也可能用 SSE 回包。"""
|
||||||
|
|
||||||
|
def __init__(self, spec: dict):
|
||||||
|
self.url = spec.get('url') or ''
|
||||||
|
self.headers = {str(k): str(v) for k, v in (spec.get('headers') or {}).items()}
|
||||||
|
self.session_id = None
|
||||||
|
|
||||||
|
def _post(self, message: dict, timeout: float):
|
||||||
|
data = json.dumps(message, ensure_ascii=False).encode('utf-8')
|
||||||
|
headers = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
# 两个都带:服务器可以回普通 JSON,也可以回 SSE 流
|
||||||
|
'Accept': 'application/json, text/event-stream',
|
||||||
|
**self.headers,
|
||||||
|
}
|
||||||
|
if self.session_id:
|
||||||
|
headers['Mcp-Session-Id'] = self.session_id
|
||||||
|
req = urllib.request.Request(self.url, data=data, headers=headers, method='POST')
|
||||||
|
try:
|
||||||
|
resp = urllib.request.urlopen(req, timeout=timeout)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
detail = ''
|
||||||
|
try:
|
||||||
|
detail = exc.read().decode('utf-8', errors='replace')[:400]
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
raise McpError(f'MCP HTTP {exc.code}:{detail}') from exc
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
raise McpError(f'无法连接 MCP 服务器 {self.url}:{exc.reason}') from exc
|
||||||
|
sid = resp.headers.get('Mcp-Session-Id')
|
||||||
|
if sid:
|
||||||
|
self.session_id = sid
|
||||||
|
return resp
|
||||||
|
|
||||||
|
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||||
|
resp = self._post(message, timeout)
|
||||||
|
try:
|
||||||
|
status = getattr(resp, 'status', 200)
|
||||||
|
if status == 202: # Accepted:通知类请求的正常响应
|
||||||
|
raise McpError('MCP 服务器没有返回响应(202 Accepted)')
|
||||||
|
content_type = (resp.headers.get('Content-Type') or '').lower()
|
||||||
|
if 'text/event-stream' in content_type:
|
||||||
|
return self._read_sse(resp, message.get('id'))
|
||||||
|
body = resp.read().decode('utf-8', errors='replace')
|
||||||
|
finally:
|
||||||
|
resp.close()
|
||||||
|
if not body.strip():
|
||||||
|
raise McpError('MCP 服务器返回空响应')
|
||||||
|
try:
|
||||||
|
payload = json.loads(body)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise McpError(f'MCP 返回非 JSON:{body[:300]}') from exc
|
||||||
|
if isinstance(payload, list):
|
||||||
|
payload = next((p for p in payload if p.get('id') == message.get('id')), payload[0] if payload else {})
|
||||||
|
return payload
|
||||||
|
|
||||||
|
def _read_sse(self, resp, want_id) -> dict:
|
||||||
|
"""从 SSE 流里挑出属于本次请求的那条响应(其它消息忽略/回绝)。"""
|
||||||
|
while True:
|
||||||
|
raw = resp.readline()
|
||||||
|
if not raw:
|
||||||
|
break
|
||||||
|
line = raw.decode('utf-8', errors='replace').strip()
|
||||||
|
if not line or line.startswith(':') or not line.startswith('data:'):
|
||||||
|
continue
|
||||||
|
payload = line[5:].strip()
|
||||||
|
if not payload:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
message = json.loads(payload)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if isinstance(message, dict) and message.get('id') == want_id:
|
||||||
|
return message
|
||||||
|
# 服务器反向发起的请求(采样/roots):一律回"方法不支持",别把连接吊死
|
||||||
|
if isinstance(message, dict) and message.get('method') and message.get('id') is not None:
|
||||||
|
try:
|
||||||
|
self._post({'jsonrpc': '2.0', 'id': message['id'],
|
||||||
|
'error': {'code': -32601, 'message': 'method not found'}}, 30)
|
||||||
|
except McpError:
|
||||||
|
pass
|
||||||
|
raise McpError('MCP 的 SSE 流结束了但没有返回本次请求的响应')
|
||||||
|
|
||||||
|
def notify(self, message: dict) -> None:
|
||||||
|
try:
|
||||||
|
resp = self._post(message, 30)
|
||||||
|
resp.read()
|
||||||
|
resp.close()
|
||||||
|
except McpError as exc:
|
||||||
|
# 通知失败不影响主流程(有些服务器对 notifications/initialized 直接 202/204)
|
||||||
|
print(f'[mcp] 通知发送失败(可忽略):{exc}', file=sys.stderr)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 传输层:stdio
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
_PYTHON_CMD_RE = re.compile(r'^python[0-9.]*(\.exe)?$', re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
def _python_script_of(command: str, args) -> str:
|
||||||
|
"""
|
||||||
|
判断"这条 stdio 命令是不是在拿 python 跑某个 .py",是就返回那个脚本路径。
|
||||||
|
|
||||||
|
为什么要判断:安卓(Chaquopy)把 CPython 嵌在 App 主进程里,**没有 python 可执行文件**,
|
||||||
|
`python xxx.py` 这种标准写法起不了子进程。但 MCP 的线协议就是"一行一条 JSON",
|
||||||
|
所以我们可以给它一对假的 stdin/stdout,把脚本跑在**进程内**,效果完全一样。
|
||||||
|
这样同一份 mcp.servers.json 在电脑上走真子进程、在手机上走进程内仿真,用户不用改配置。
|
||||||
|
"""
|
||||||
|
base = os.path.basename(command or '').lower()
|
||||||
|
looks_like_python = bool(_PYTHON_CMD_RE.match(base)) or base in ('py', 'py.exe')
|
||||||
|
if not looks_like_python and os.path.basename(sys.executable or '').lower() == base:
|
||||||
|
looks_like_python = True
|
||||||
|
if not looks_like_python:
|
||||||
|
return ''
|
||||||
|
for arg in args:
|
||||||
|
text = str(arg)
|
||||||
|
if text.lower().endswith('.py') and os.path.isfile(text):
|
||||||
|
return text
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def _inproc_stdio_enabled() -> bool:
|
||||||
|
"""安卓上自动启用;电脑上可以用 DOUBAO_MCP_INPROC_STDIO=1 强制打开(便于对照测试)"""
|
||||||
|
if paths.IS_ANDROID:
|
||||||
|
return True
|
||||||
|
return os.environ.get('DOUBAO_MCP_INPROC_STDIO') == '1'
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeStdin:
|
||||||
|
"""
|
||||||
|
喂给 MCP 脚本的假 stdin。
|
||||||
|
|
||||||
|
关键点:它**按线程区分**——只有跑 MCP 脚本的那个线程读到的是管道数据,
|
||||||
|
内核自己的线程读到的还是真正的 stdin。否则整个进程的标准输入就被这一个服务独占了。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, queue_in, real_stream, owner):
|
||||||
|
self._q = queue_in
|
||||||
|
self._real = real_stream
|
||||||
|
self._owner = owner
|
||||||
|
|
||||||
|
def _mine(self) -> bool:
|
||||||
|
return threading.current_thread() is self._owner
|
||||||
|
|
||||||
|
def readline(self, *_args, **_kwargs) -> str:
|
||||||
|
if not self._mine():
|
||||||
|
return self._real.readline() if self._real else ''
|
||||||
|
item = self._q.get()
|
||||||
|
return '' if item is None else item
|
||||||
|
|
||||||
|
def read(self, *_args, **_kwargs) -> str:
|
||||||
|
return self.readline()
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
while True:
|
||||||
|
line = self.readline()
|
||||||
|
if not line:
|
||||||
|
return
|
||||||
|
yield line
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def fileno(self): # 有些库会调,给个明确失败而不是乱返回值
|
||||||
|
raise OSError('inproc stdin 没有文件描述符')
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeStdout:
|
||||||
|
"""MCP 脚本的假 stdout:写进来的内容按行进队列,交给 reader 线程解析"""
|
||||||
|
|
||||||
|
def __init__(self, queue_out, real_stream, owner, mirror: bool):
|
||||||
|
self._q = queue_out
|
||||||
|
self._real = real_stream
|
||||||
|
self._owner = owner
|
||||||
|
self._mirror = mirror
|
||||||
|
|
||||||
|
def _mine(self) -> bool:
|
||||||
|
return threading.current_thread() is self._owner
|
||||||
|
|
||||||
|
def write(self, text) -> int:
|
||||||
|
text = str(text)
|
||||||
|
if not self._mine():
|
||||||
|
if self._real:
|
||||||
|
self._real.write(text)
|
||||||
|
return len(text)
|
||||||
|
if self._mirror and self._real:
|
||||||
|
# 进程内没法像子进程那样"日志去 stderr",这里镜像一份方便诊断
|
||||||
|
self._real.write(f'[mcp:inproc] {text}')
|
||||||
|
for line in text.splitlines(keepends=True):
|
||||||
|
self._q.put(line)
|
||||||
|
return len(text)
|
||||||
|
|
||||||
|
def flush(self):
|
||||||
|
if self._real and not self._mine():
|
||||||
|
self._real.flush()
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def fileno(self):
|
||||||
|
raise OSError('inproc stdout 没有文件描述符')
|
||||||
|
|
||||||
|
|
||||||
|
class _QueueWriter:
|
||||||
|
"""
|
||||||
|
给 _StdioTransport 用的"假 stdin":内核往这里写,就相当于写进了子进程的标准输入。
|
||||||
|
注意方向——transport 的 proc.stdin 是**写入端**,脚本那边的 sys.stdin 才是读取端。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, queue_in):
|
||||||
|
self._q = queue_in
|
||||||
|
|
||||||
|
def write(self, text) -> int:
|
||||||
|
text = str(text)
|
||||||
|
for line in text.splitlines(keepends=True):
|
||||||
|
self._q.put(line)
|
||||||
|
return len(text)
|
||||||
|
|
||||||
|
def flush(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self._q.put(None)
|
||||||
|
|
||||||
|
|
||||||
|
class _LineQueueReader:
|
||||||
|
"""给 _read_loop 用的可迭代流:一行一行从队列取,None 表示 EOF"""
|
||||||
|
|
||||||
|
def __init__(self, queue_out):
|
||||||
|
self._q = queue_out
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
while True:
|
||||||
|
item = self._q.get()
|
||||||
|
if item is None:
|
||||||
|
return
|
||||||
|
yield item
|
||||||
|
|
||||||
|
def readline(self, *_args, **_kwargs) -> str:
|
||||||
|
item = self._q.get()
|
||||||
|
return '' if item is None else item
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self._q.put(None)
|
||||||
|
|
||||||
|
|
||||||
|
class _InProcProcess:
|
||||||
|
"""
|
||||||
|
假装自己是 subprocess.Popen:只实现 _StdioTransport 用到的那几个接口
|
||||||
|
(stdin / stdout / poll / terminate / wait / kill),把 MCP 脚本跑在进程内。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, script: str, argv: list, env: dict):
|
||||||
|
self._to_script = queue.Queue()
|
||||||
|
self._from_script = queue.Queue()
|
||||||
|
self._alive = True
|
||||||
|
self._returncode = None
|
||||||
|
# transport 视角:stdin 写进去 → 脚本读到;stdout 读出来 ← 脚本写的
|
||||||
|
self.stdin = _QueueWriter(self._to_script)
|
||||||
|
self.stdout = _LineQueueReader(self._from_script)
|
||||||
|
self._thread = threading.Thread(
|
||||||
|
target=self._run, args=(script, argv, env), name='mcp-inproc', daemon=True,
|
||||||
|
)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def _run(self, script: str, argv: list, env: dict) -> None:
|
||||||
|
import runpy
|
||||||
|
|
||||||
|
me = threading.current_thread()
|
||||||
|
real_in, real_out, real_err = sys.stdin, sys.stdout, sys.stderr
|
||||||
|
real_argv = sys.argv
|
||||||
|
real_path = list(sys.path)
|
||||||
|
real_env = dict(os.environ)
|
||||||
|
|
||||||
|
sys.stdin = _FakeStdin(self._to_script, real_in, me)
|
||||||
|
# stdout 走进协议管道(镜像到真 stderr 方便排查);
|
||||||
|
# stderr 也镜像过去:MCP 服务经常把日志打到 stderr
|
||||||
|
sys.stdout = _FakeStdout(self._from_script, real_err, me, mirror=True)
|
||||||
|
sys.stderr = _FakeStdout(self._from_script, real_err, me, mirror=False)
|
||||||
|
sys.argv = argv
|
||||||
|
if os.path.dirname(script) not in sys.path:
|
||||||
|
sys.path.insert(0, os.path.dirname(script))
|
||||||
|
try:
|
||||||
|
os.environ.update({str(k): str(v) for k, v in (env or {}).items()})
|
||||||
|
runpy.run_path(script, run_name='__main__')
|
||||||
|
except SystemExit:
|
||||||
|
pass
|
||||||
|
except BaseException as exc: # noqa: BLE001 - 服务崩了要给出可读信息
|
||||||
|
print(f'[mcp] 进程内 stdio 服务异常退出:{exc!r}', file=real_err)
|
||||||
|
finally:
|
||||||
|
sys.stdin, sys.stdout, sys.stderr = real_in, real_out, real_err
|
||||||
|
sys.argv = real_argv
|
||||||
|
sys.path[:] = real_path
|
||||||
|
os.environ.clear()
|
||||||
|
os.environ.update(real_env)
|
||||||
|
self._alive = False
|
||||||
|
self._returncode = 0
|
||||||
|
self._from_script.put(None) # 告诉读取方 EOF
|
||||||
|
|
||||||
|
# --- Popen 的子集 ---
|
||||||
|
def poll(self):
|
||||||
|
return None if self._alive else self._returncode
|
||||||
|
|
||||||
|
def terminate(self):
|
||||||
|
self._to_script.put(None) # 让阻塞在 stdin 的脚本醒过来并结束
|
||||||
|
self._alive = False
|
||||||
|
self._returncode = -15
|
||||||
|
|
||||||
|
def kill(self):
|
||||||
|
self.terminate()
|
||||||
|
|
||||||
|
def wait(self, timeout=None):
|
||||||
|
self._thread.join(timeout)
|
||||||
|
return self._returncode
|
||||||
|
|
||||||
|
|
||||||
|
class _StdioTransport:
|
||||||
|
"""
|
||||||
|
按行收发 JSON-RPC。
|
||||||
|
|
||||||
|
三种情况:
|
||||||
|
- 安卓 + 命令是 python 跑 .py → 进程内仿真(没有 python 可执行文件,起不了子进程)
|
||||||
|
- 安卓 + 命令是原生可执行文件 → 照常起子进程(/system/bin/sh、toybox 这些是可以起的)
|
||||||
|
- 电脑 → 照常起子进程
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, spec: dict):
|
||||||
|
command = spec.get('command') or ''
|
||||||
|
args = [str(a) for a in (spec.get('args') or [])]
|
||||||
|
if not command:
|
||||||
|
raise McpError('stdio 传输缺少 command')
|
||||||
|
|
||||||
|
env = {**os.environ, **{str(k): str(v) for k, v in (spec.get('env') or {}).items()}}
|
||||||
|
script = _python_script_of(command, args) if _inproc_stdio_enabled() else ''
|
||||||
|
|
||||||
|
if script:
|
||||||
|
# 用 python 跑的 .py 服务:进程内仿真,不需要可执行文件
|
||||||
|
forwarded = [a for a in args if a != script and not str(a).startswith('-')]
|
||||||
|
self.proc = _InProcProcess(script, [script, *forwarded], env)
|
||||||
|
self._inproc = True
|
||||||
|
print(f'[mcp] {spec.get("name")}:安卓/无解释器环境,改用进程内 stdio 仿真({script})', file=sys.stderr)
|
||||||
|
else:
|
||||||
|
# Windows 下 npx/npm/node 是 .cmd,必须用 cmd /c 包一层(官方 README 明确要求)
|
||||||
|
if paths.IS_WINDOWS and re.match(r'^(npx|npm|node|pnpm|yarn)$', command, re.IGNORECASE):
|
||||||
|
argv = ['cmd', '/c', command, *args]
|
||||||
|
else:
|
||||||
|
argv = [command, *args]
|
||||||
|
if not shutil.which(command) and not os.path.isabs(command):
|
||||||
|
raise McpError(
|
||||||
|
f'找不到命令 {command}(请确认已安装并在 PATH 里)。'
|
||||||
|
'安卓上推荐把 MCP 服务写成 .py,用 transport="stdio" + command="python" 即可(内核会自动改用进程内执行)'
|
||||||
|
)
|
||||||
|
kwargs = {}
|
||||||
|
if paths.IS_WINDOWS:
|
||||||
|
kwargs['creationflags'] = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
|
||||||
|
try:
|
||||||
|
self.proc = subprocess.Popen(
|
||||||
|
argv,
|
||||||
|
stdin=subprocess.PIPE,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
# 子进程日志直接继承内核的 stderr:既能诊断又不会把管道塞满
|
||||||
|
stderr=None,
|
||||||
|
text=True,
|
||||||
|
encoding='utf-8',
|
||||||
|
errors='replace',
|
||||||
|
bufsize=1,
|
||||||
|
env=env,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
except OSError as exc:
|
||||||
|
raise McpError(f'无法启动 MCP 服务进程 {command}:{exc}') from exc
|
||||||
|
self._inproc = False
|
||||||
|
self._cv = threading.Condition()
|
||||||
|
self._responses: dict = {}
|
||||||
|
self._closed = False
|
||||||
|
self._reader = threading.Thread(target=self._read_loop, name='mcp-stdio-reader', daemon=True)
|
||||||
|
self._reader.start()
|
||||||
|
|
||||||
|
def _read_loop(self) -> None:
|
||||||
|
stream = self.proc.stdout
|
||||||
|
try:
|
||||||
|
for raw in stream:
|
||||||
|
line = raw.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
message = json.loads(line)
|
||||||
|
except ValueError:
|
||||||
|
# 有些服务会往 stdout 打日志,忽略掉,不要打断协议
|
||||||
|
print(f'[mcp] 忽略非 JSON 输出:{line[:200]}', file=sys.stderr)
|
||||||
|
continue
|
||||||
|
if isinstance(message, dict) and message.get('id') is not None:
|
||||||
|
with self._cv:
|
||||||
|
self._responses[message['id']] = message
|
||||||
|
self._cv.notify_all()
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
with self._cv:
|
||||||
|
self._closed = True
|
||||||
|
self._cv.notify_all()
|
||||||
|
|
||||||
|
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||||
|
with self._cv:
|
||||||
|
if self._closed:
|
||||||
|
raise McpError('MCP 服务进程已退出')
|
||||||
|
try:
|
||||||
|
self.proc.stdin.write(json.dumps(message, ensure_ascii=False) + '\n')
|
||||||
|
self.proc.stdin.flush()
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
raise McpError(f'写入 MCP 服务失败:{exc}') from exc
|
||||||
|
# 用单调时钟算总超时:被别的响应唤醒时不能把等待时间重新计一遍
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
with self._cv:
|
||||||
|
while message.get('id') not in self._responses:
|
||||||
|
remain = deadline - time.monotonic()
|
||||||
|
if remain <= 0:
|
||||||
|
raise McpError(f'MCP 请求超时({timeout}s):{message.get("method")}')
|
||||||
|
if self._closed:
|
||||||
|
raise McpError('MCP 服务进程已关闭连接')
|
||||||
|
self._cv.wait(remain)
|
||||||
|
return self._responses.pop(message['id'])
|
||||||
|
|
||||||
|
def notify(self, message: dict) -> None:
|
||||||
|
try:
|
||||||
|
self.proc.stdin.write(json.dumps(message, ensure_ascii=False) + '\n')
|
||||||
|
self.proc.stdin.flush()
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
print(f'[mcp] 通知发送失败:{exc}', file=sys.stderr)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
try:
|
||||||
|
if self.proc.poll() is None:
|
||||||
|
self.proc.terminate()
|
||||||
|
try:
|
||||||
|
self.proc.wait(timeout=3)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
self.proc.kill()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
for stream in (self.proc.stdin, self.proc.stdout):
|
||||||
|
try:
|
||||||
|
if stream:
|
||||||
|
stream.close()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 传输层:inproc(安卓专用)
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
class _InprocTransport:
|
||||||
|
"""
|
||||||
|
进程内 MCP:import 用户给的 .py,暴露 handle(request: dict) -> dict。
|
||||||
|
|
||||||
|
为什么要用"队列 + 工作线程"而不是直接调用 handle:
|
||||||
|
* 语义上和 http/stdio 完全一致(请求-响应配对、超时、异常 → JSON-RPC error),
|
||||||
|
这样内核上层的 initialize / tools/list / tools/call 编排只有一份代码;
|
||||||
|
* handle 里如果阻塞/抛异常,也不会把 HTTP 请求线程搞乱,超时能正常返回。
|
||||||
|
|
||||||
|
约定(写进 README 和对话提示里):
|
||||||
|
* 只把**带 id 的请求**交给 handle;通知(notifications/initialized 等)直接跳过,
|
||||||
|
这样最小实现只要处理 initialize / tools/list / tools/call 三个方法。
|
||||||
|
* 返回值可以是完整 JSON-RPC 响应,也可以只给 {"result": ...},甚至直接给结果对象。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, spec: dict):
|
||||||
|
file_path = spec.get('file') or spec.get('path') or spec.get('script') or ''
|
||||||
|
if not file_path:
|
||||||
|
raise McpError('inproc 需要 file 字段指向 .py 文件')
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
raise McpError(f'找不到 inproc 服务文件:{file_path}')
|
||||||
|
self.path = os.path.abspath(file_path)
|
||||||
|
module = _import_module(self.path)
|
||||||
|
handler = getattr(module, 'handle', None)
|
||||||
|
if not callable(handler):
|
||||||
|
raise McpError(f'{os.path.basename(self.path)} 必须暴露 handle(request) -> dict')
|
||||||
|
self._handler = handler
|
||||||
|
self._queue: queue.Queue = queue.Queue()
|
||||||
|
self._inflight: dict = {}
|
||||||
|
self._cv = threading.Condition()
|
||||||
|
self._closed = False
|
||||||
|
self._thread = threading.Thread(
|
||||||
|
target=self._worker, name=f'mcp-inproc-{os.path.basename(self.path)}', daemon=True
|
||||||
|
)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def _call_handler(self, message: dict):
|
||||||
|
result = self._handler(message)
|
||||||
|
# 顺手支持 async def handle:安卓上有些库只有异步接口
|
||||||
|
if inspect.iscoroutine(result):
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
result = asyncio.run(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _normalize(raw, req_id):
|
||||||
|
"""把 handle 的返回值规整成 JSON-RPC 响应(宽容一点,方便手写服务)。"""
|
||||||
|
if isinstance(raw, dict) and ('result' in raw or 'error' in raw):
|
||||||
|
out = {'jsonrpc': '2.0', 'id': raw.get('id', req_id)}
|
||||||
|
if 'error' in raw:
|
||||||
|
out['error'] = raw['error']
|
||||||
|
else:
|
||||||
|
out['result'] = raw.get('result')
|
||||||
|
return out
|
||||||
|
return {'jsonrpc': '2.0', 'id': req_id, 'result': raw}
|
||||||
|
|
||||||
|
def _worker(self) -> None:
|
||||||
|
while True:
|
||||||
|
item = self._queue.get()
|
||||||
|
if item is None: # 关闭信号
|
||||||
|
break
|
||||||
|
message = item
|
||||||
|
req_id = message.get('id')
|
||||||
|
try:
|
||||||
|
response = self._normalize(self._call_handler(message), req_id)
|
||||||
|
except BaseException as exc: # noqa: BLE001 - 服务里的异常要变成 JSON-RPC error
|
||||||
|
response = {
|
||||||
|
'jsonrpc': '2.0',
|
||||||
|
'id': req_id,
|
||||||
|
'error': {'code': -32603, 'message': f'{type(exc).__name__}: {exc}'},
|
||||||
|
}
|
||||||
|
with self._cv:
|
||||||
|
self._inflight[req_id] = response
|
||||||
|
self._cv.notify_all()
|
||||||
|
with self._cv:
|
||||||
|
self._closed = True
|
||||||
|
self._cv.notify_all()
|
||||||
|
|
||||||
|
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||||
|
req_id = message.get('id')
|
||||||
|
with self._cv:
|
||||||
|
if self._closed:
|
||||||
|
raise McpError('inproc MCP 服务已关闭')
|
||||||
|
self._inflight[req_id] = _PENDING
|
||||||
|
self._queue.put(message)
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
with self._cv:
|
||||||
|
while self._inflight.get(req_id) is _PENDING:
|
||||||
|
remain = deadline - time.monotonic()
|
||||||
|
if remain <= 0:
|
||||||
|
self._inflight.pop(req_id, None)
|
||||||
|
raise McpError(f'inproc MCP 请求超时({timeout}s):{message.get("method")}')
|
||||||
|
self._cv.wait(remain)
|
||||||
|
return self._inflight.pop(req_id)
|
||||||
|
|
||||||
|
def notify(self, message: dict) -> None:
|
||||||
|
# 通知不要求响应,也不交给 handle(见类注释:让最小实现只处理三个方法)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
with self._cv:
|
||||||
|
if self._closed:
|
||||||
|
return
|
||||||
|
self._queue.put(None)
|
||||||
|
self._thread.join(timeout=2)
|
||||||
|
|
||||||
|
|
||||||
|
def _import_module(file_path: str):
|
||||||
|
"""按路径 import 用户的 MCP 服务文件(和工具运行时同一套手法)。"""
|
||||||
|
stem = re.sub(r'\W', '_', os.path.splitext(os.path.basename(file_path))[0])
|
||||||
|
mod_name = f'_doubao_mcp_{stem}_{abs(hash(os.path.abspath(file_path))) % 100000}'
|
||||||
|
sys.modules.pop(mod_name, None)
|
||||||
|
folder = os.path.dirname(os.path.abspath(file_path))
|
||||||
|
if folder not in sys.path:
|
||||||
|
sys.path.insert(0, folder)
|
||||||
|
spec = importlib.util.spec_from_file_location(mod_name, file_path)
|
||||||
|
if spec is None or spec.loader is None:
|
||||||
|
raise McpError(f'无法为 {file_path} 建立模块 spec')
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules[mod_name] = module
|
||||||
|
try:
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
except BaseException as exc: # noqa: BLE001
|
||||||
|
sys.modules.pop(mod_name, None)
|
||||||
|
raise McpError(f'导入 {os.path.basename(file_path)} 失败:{type(exc).__name__}: {exc}') from exc
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
def _make_transport(spec: dict):
|
||||||
|
transport = (spec.get('transport') or 'stdio').lower()
|
||||||
|
if transport == 'http':
|
||||||
|
return _HttpTransport(spec)
|
||||||
|
if transport == 'stdio':
|
||||||
|
return _StdioTransport(spec)
|
||||||
|
if transport == 'inproc':
|
||||||
|
return _InprocTransport(spec)
|
||||||
|
if transport == 'sse':
|
||||||
|
raise McpError('sse(旧版 HTTP+SSE)传输在 Python 内核里未实现,请改用 transport="http" 或 "inproc"')
|
||||||
|
raise McpError(f'不认识的 transport:{transport}')
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 客户端:initialize / tools/list / tools/call 编排
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
class McpClient:
|
||||||
|
def __init__(self, spec: dict):
|
||||||
|
self.spec = spec
|
||||||
|
self.transport = _make_transport(spec)
|
||||||
|
self.tools: list = []
|
||||||
|
self._id = 0
|
||||||
|
self._lock = threading.RLock()
|
||||||
|
|
||||||
|
def _next_id(self) -> int:
|
||||||
|
with self._lock:
|
||||||
|
self._id += 1
|
||||||
|
return self._id
|
||||||
|
|
||||||
|
def _request(self, method: str, params: dict | None, timeout: float, tolerate_error: bool = False):
|
||||||
|
message = {'jsonrpc': '2.0', 'id': self._next_id(), 'method': method}
|
||||||
|
if params is not None:
|
||||||
|
message['params'] = params
|
||||||
|
try:
|
||||||
|
response = self.transport.request(message, timeout)
|
||||||
|
except McpError:
|
||||||
|
if tolerate_error:
|
||||||
|
return None
|
||||||
|
raise
|
||||||
|
if not isinstance(response, dict):
|
||||||
|
raise McpError(f'{method} 返回了非对象响应')
|
||||||
|
if response.get('error'):
|
||||||
|
err = response['error'] or {}
|
||||||
|
detail = err.get('message') if isinstance(err, dict) else str(err)
|
||||||
|
if tolerate_error:
|
||||||
|
print(f'[mcp] {method} 失败(已忽略):{detail}', file=sys.stderr)
|
||||||
|
return None
|
||||||
|
raise McpError(f'{method} 失败:{detail}')
|
||||||
|
return response.get('result')
|
||||||
|
|
||||||
|
def connect(self, timeout: float = 180) -> 'McpClient':
|
||||||
|
# initialize 允许失败:inproc 的最小实现可能只认 tools/list、tools/call
|
||||||
|
self._request(
|
||||||
|
'initialize',
|
||||||
|
{
|
||||||
|
'protocolVersion': PROTOCOL_VERSION,
|
||||||
|
'capabilities': {},
|
||||||
|
'clientInfo': CLIENT_INFO,
|
||||||
|
},
|
||||||
|
timeout,
|
||||||
|
tolerate_error=True,
|
||||||
|
)
|
||||||
|
self.transport.notify({'jsonrpc': '2.0', 'method': 'notifications/initialized', 'params': {}})
|
||||||
|
listed = self._request('tools/list', {}, 60) or {}
|
||||||
|
self.tools = listed.get('tools') or []
|
||||||
|
return self
|
||||||
|
|
||||||
|
def call_tool(self, name: str, arguments: dict, timeout: float = 120) -> dict:
|
||||||
|
result = self._request('tools/call', {'name': name, 'arguments': arguments or {}}, timeout)
|
||||||
|
return result or {}
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
try:
|
||||||
|
self.transport.close()
|
||||||
|
except Exception as exc: # noqa: BLE001 - 关闭失败不该影响别的服务器
|
||||||
|
print(f'[mcp] 关闭连接失败:{exc}', file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 连接池 / 对外接口
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def connect(server_name: str, force: bool = False) -> dict:
|
||||||
|
"""连接(或复用)一个 MCP 服务器;错误记在 record['error'] 里,不抛给调用方。"""
|
||||||
|
with _lock:
|
||||||
|
existing = _clients.get(server_name)
|
||||||
|
if existing and existing.get('client') and not force:
|
||||||
|
return existing
|
||||||
|
if existing and existing.get('client') and force:
|
||||||
|
disconnect(server_name)
|
||||||
|
|
||||||
|
spec = next((s for s in read_mcp_config()['servers'] if s.get('name') == server_name), None)
|
||||||
|
if not spec:
|
||||||
|
raise McpError(f'mcp.servers.json 里没有服务器 {server_name}')
|
||||||
|
if spec.get('enabled') is False:
|
||||||
|
raise McpError(f'服务器 {server_name} 已被禁用')
|
||||||
|
|
||||||
|
record = {'spec': spec, 'client': None, 'tools': [], 'error': None}
|
||||||
|
with _lock:
|
||||||
|
_clients[server_name] = record
|
||||||
|
try:
|
||||||
|
client = McpClient(spec).connect()
|
||||||
|
record['client'] = client
|
||||||
|
record['tools'] = client.tools
|
||||||
|
record['error'] = None
|
||||||
|
print(f'[mcp] {server_name} 已连接,{len(client.tools)} 个工具')
|
||||||
|
except BaseException as exc: # noqa: BLE001 - 单个服务器失败不能影响内核启动
|
||||||
|
record['error'] = str(exc)
|
||||||
|
print(f'[mcp] {server_name} 连接失败:{record["error"]}', file=sys.stderr)
|
||||||
|
return record
|
||||||
|
|
||||||
|
|
||||||
|
def disconnect(server_name: str) -> None:
|
||||||
|
with _lock:
|
||||||
|
record = _clients.pop(server_name, None)
|
||||||
|
if not record:
|
||||||
|
return
|
||||||
|
client = record.get('client')
|
||||||
|
if client:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
def disconnect_all() -> None:
|
||||||
|
for name in list(_clients.keys()):
|
||||||
|
disconnect(name)
|
||||||
|
|
||||||
|
|
||||||
|
def connect_all_enabled() -> list:
|
||||||
|
results = []
|
||||||
|
for spec in read_mcp_config()['servers']:
|
||||||
|
if spec.get('enabled') is False:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
record = connect(spec.get('name'))
|
||||||
|
results.append({
|
||||||
|
'name': spec.get('name'),
|
||||||
|
'ok': not record.get('error'),
|
||||||
|
'error': record.get('error'),
|
||||||
|
'toolCount': len(record.get('tools') or []),
|
||||||
|
})
|
||||||
|
except BaseException as exc: # noqa: BLE001
|
||||||
|
results.append({'name': spec.get('name'), 'ok': False, 'error': str(exc)})
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def get_mcp_state() -> list:
|
||||||
|
out = []
|
||||||
|
for spec in read_mcp_config()['servers']:
|
||||||
|
record = _clients.get(spec.get('name')) or {}
|
||||||
|
transport = spec.get('transport') or 'stdio'
|
||||||
|
if transport == 'stdio':
|
||||||
|
target = f"{spec.get('command') or ''} {' '.join(str(a) for a in (spec.get('args') or []))}".strip()
|
||||||
|
elif transport == 'inproc':
|
||||||
|
target = spec.get('file') or spec.get('path') or ''
|
||||||
|
else:
|
||||||
|
target = spec.get('url') or ''
|
||||||
|
out.append({
|
||||||
|
'name': spec.get('name'),
|
||||||
|
'enabled': spec.get('enabled') is not False,
|
||||||
|
'transport': transport,
|
||||||
|
'target': target,
|
||||||
|
'connected': bool(record.get('client')),
|
||||||
|
'error': record.get('error') or None,
|
||||||
|
'tools': [
|
||||||
|
{'name': t.get('name'), 'description': t.get('description') or ''}
|
||||||
|
for t in (record.get('tools') or [])
|
||||||
|
],
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_schema(schema) -> dict:
|
||||||
|
"""
|
||||||
|
MCP 的 inputSchema 不能直接当 OpenAI 的 parameters:
|
||||||
|
必须去 $schema、保证 type=object、补 properties/required,
|
||||||
|
并且 outputSchema 绝不能混进来(OpenAI 会直接拒)。
|
||||||
|
"""
|
||||||
|
src = schema if isinstance(schema, dict) else {}
|
||||||
|
out = dict(src)
|
||||||
|
out.pop('$schema', None)
|
||||||
|
out.pop('outputSchema', None)
|
||||||
|
if out.get('type') != 'object':
|
||||||
|
out['type'] = 'object'
|
||||||
|
if not isinstance(out.get('properties'), dict):
|
||||||
|
out['properties'] = {}
|
||||||
|
if not isinstance(out.get('required'), list):
|
||||||
|
out['required'] = [
|
||||||
|
key for key, value in out['properties'].items()
|
||||||
|
if isinstance(value, dict) and value.get('required') is True
|
||||||
|
]
|
||||||
|
if out.get('additionalProperties') is None:
|
||||||
|
out['additionalProperties'] = False
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def mcp_tool_defs() -> list:
|
||||||
|
defs = []
|
||||||
|
with _lock:
|
||||||
|
items = list(_clients.items())
|
||||||
|
for server_name, record in items:
|
||||||
|
if not record.get('client'):
|
||||||
|
continue
|
||||||
|
for tool in record.get('tools') or []:
|
||||||
|
defs.append({
|
||||||
|
'type': 'function',
|
||||||
|
'function': {
|
||||||
|
'name': f"mcp__{server_name}__{tool.get('name')}",
|
||||||
|
'description': f"[MCP:{server_name}] {tool.get('description') or tool.get('name')}",
|
||||||
|
'parameters': sanitize_schema(tool.get('inputSchema')),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return defs
|
||||||
|
|
||||||
|
|
||||||
|
def call_mcp_tool(full_name: str, args: dict) -> dict:
|
||||||
|
parts = full_name.split('__')
|
||||||
|
server_name = parts[1] if len(parts) > 1 else ''
|
||||||
|
tool_name = '__'.join(parts[2:])
|
||||||
|
record = _clients.get(server_name)
|
||||||
|
if not record or not record.get('client'):
|
||||||
|
raise McpError(f'MCP 服务器 {server_name} 未连接')
|
||||||
|
return record['client'].call_tool(tool_name, args or {})
|
||||||
|
|
||||||
|
|
||||||
|
def is_mcp_tool(name) -> bool:
|
||||||
|
return isinstance(name, str) and name.startswith('mcp__')
|
||||||
126
android/kernel/paths.py
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
"""
|
||||||
|
运行期路径与平台判断。
|
||||||
|
|
||||||
|
为什么单独一个模块:
|
||||||
|
* Node 版把路径写在 config.mjs 的模块级常量里(读进程环境变量),
|
||||||
|
Python 版要能在安卓(Chaquopy)里被反复以不同参数启动,所以做成可配置单例。
|
||||||
|
* 所有落盘位置都从「数据目录」派生,安卓上把数据目录指到
|
||||||
|
/data/data/<包名>/files 或外部存储即可,源码目录保持只读。
|
||||||
|
|
||||||
|
只用标准库;安卓相关判断也只用标准库(sys.platform / os.environ)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# 让 `python android/kernel/main.py` 和 `python -m android.kernel` 两种启动方式
|
||||||
|
# 都能用扁平导入(import store / from app import ...)。tools/*.py 也是这个套路。
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
if _HERE not in sys.path:
|
||||||
|
sys.path.insert(0, _HERE)
|
||||||
|
|
||||||
|
# 仓库根目录:android/kernel/ -> android/ -> <repo>
|
||||||
|
REPO_ROOT = os.path.dirname(os.path.dirname(_HERE))
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_android() -> bool:
|
||||||
|
"""
|
||||||
|
判断是否跑在安卓的 CPython(Chaquopy)里。
|
||||||
|
Chaquopy 会设 sys.platform == 'android'(较新版本)或提供 sys.getandroidapilevel(),
|
||||||
|
老版本两个都没有,只能退回看 ANDROID_ROOT / ANDROID_DATA 环境变量。
|
||||||
|
"""
|
||||||
|
if sys.platform.startswith('android') or sys.platform in ('linux-android', 'android'):
|
||||||
|
return True
|
||||||
|
if hasattr(sys, 'getandroidapilevel'):
|
||||||
|
return True
|
||||||
|
return bool(os.environ.get('ANDROID_ROOT') or os.environ.get('ANDROID_DATA'))
|
||||||
|
|
||||||
|
|
||||||
|
IS_ANDROID = _detect_android()
|
||||||
|
IS_WINDOWS = sys.platform.startswith('win')
|
||||||
|
|
||||||
|
|
||||||
|
class Paths:
|
||||||
|
"""一次内核进程用到的全部目录/文件位置。"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
data_dir: str | None = None,
|
||||||
|
tools_dir: str | None = None,
|
||||||
|
web_dir: str | None = None,
|
||||||
|
dist_dir: str | None = None,
|
||||||
|
web_core_dir: str | None = None,
|
||||||
|
):
|
||||||
|
# 数据目录:安卓上由 Kotlin 侧(或 --data-dir)指定,默认放在内核目录下的 data/
|
||||||
|
self.data_dir = os.path.abspath(
|
||||||
|
data_dir or os.environ.get('DOUBAO_DATA') or os.path.join(_HERE, 'data')
|
||||||
|
)
|
||||||
|
# 内置工具目录(仓库里的 tools/;settings.toolsDir 可以在运行时覆盖它)
|
||||||
|
self.tools_dir = os.path.abspath(
|
||||||
|
tools_dir or os.environ.get('DOUBAO_TOOLS') or os.path.join(REPO_ROOT, 'tools')
|
||||||
|
)
|
||||||
|
# 静态托管:宿主页 + Lynx 产物 + web-core 运行时(安卓上一般用不上,
|
||||||
|
# 因为页面在 assets 里,但保留以便桌面/局域网调试时同一端口全包)
|
||||||
|
self.web_dir = os.path.abspath(web_dir or os.environ.get('DOUBAO_WEB') or os.path.join(REPO_ROOT, 'web'))
|
||||||
|
self.dist_dir = os.path.abspath(
|
||||||
|
dist_dir or os.environ.get('DOUBAO_DIST') or os.path.join(REPO_ROOT, 'app', 'dist')
|
||||||
|
)
|
||||||
|
self.web_core_dir = self._resolve_web_core(web_core_dir)
|
||||||
|
|
||||||
|
# 数据目录下的固定文件(文件名与 Node 版保持一致,方便两边互相读)
|
||||||
|
self.uploads_dir = os.path.join(self.data_dir, 'uploads')
|
||||||
|
self.tmp_dir = os.path.join(self.data_dir, 'tmp')
|
||||||
|
self.settings_file = os.path.join(self.data_dir, 'settings.json')
|
||||||
|
self.conversations_file = os.path.join(self.data_dir, 'conversations.json')
|
||||||
|
self.agents_file = os.path.join(self.data_dir, 'agents.json')
|
||||||
|
self.mcp_file = os.path.join(self.data_dir, 'mcp.servers.json')
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _resolve_web_core(explicit: str | None) -> str:
|
||||||
|
candidates = [
|
||||||
|
explicit,
|
||||||
|
os.environ.get('DOUBAO_WEB_CORE'),
|
||||||
|
os.path.join(REPO_ROOT, 'web-core'),
|
||||||
|
os.path.join(REPO_ROOT, 'app', 'node_modules', '@lynx-js', 'web-core', 'dist', 'client_prod', 'static'),
|
||||||
|
]
|
||||||
|
for item in candidates:
|
||||||
|
if item and os.path.isdir(item):
|
||||||
|
return os.path.abspath(item)
|
||||||
|
# 都不存在时也返回最后一个候选,交给 404 分支处理(和 Node 版行为一致)
|
||||||
|
return os.path.abspath(candidates[-1])
|
||||||
|
|
||||||
|
def ensure_dirs(self) -> None:
|
||||||
|
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir):
|
||||||
|
try:
|
||||||
|
os.makedirs(folder, exist_ok=True)
|
||||||
|
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||||||
|
print(f'[paths] 无法创建目录 {folder}:{exc}', file=sys.stderr)
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
'dataDir': self.data_dir,
|
||||||
|
'toolsDir': self.tools_dir,
|
||||||
|
'webDir': self.web_dir,
|
||||||
|
'distDir': self.dist_dir,
|
||||||
|
'webCoreDir': self.web_core_dir,
|
||||||
|
'settingsFile': self.settings_file,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
_current: Paths | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def configure(**kwargs) -> Paths:
|
||||||
|
"""(重新)配置全局路径;main.py 启动时调一次,测试里可以反复调。"""
|
||||||
|
global _current
|
||||||
|
_current = Paths(**kwargs)
|
||||||
|
_current.ensure_dirs()
|
||||||
|
return _current
|
||||||
|
|
||||||
|
|
||||||
|
def get() -> Paths:
|
||||||
|
"""取当前路径配置,没配置过就用默认值(方便被安卓侧直接 import 调用)。"""
|
||||||
|
global _current
|
||||||
|
if _current is None:
|
||||||
|
_current = configure()
|
||||||
|
return _current
|
||||||
289
android/kernel/providers.py
Normal file
@@ -0,0 +1,289 @@
|
|||||||
|
"""
|
||||||
|
上游调用层:火山方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter …
|
||||||
|
全都是 OpenAI 兼容协议,所以这里只有一份实现。
|
||||||
|
|
||||||
|
对应 Node 版 server/src/providers.mjs,对外提供:
|
||||||
|
chat_once() 非流式
|
||||||
|
stream_chat() 流式(生成器,吐 text / reasoning / tool_calls / usage / finish)
|
||||||
|
list_models() 拉模型列表(可选能力,失败不致命)
|
||||||
|
|
||||||
|
为什么用 urllib.request 而不是 requests/httpx:
|
||||||
|
安卓(Chaquopy)里第三方库要额外打包,而 urllib 是标准库,装包体积为零;
|
||||||
|
流式读取只要 resp.readline() 逐行解析 SSE 就够了,不需要异步框架。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import gzip
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from typing import Callable, Iterator, Optional
|
||||||
|
|
||||||
|
from defaults import PROVIDER_PRESETS
|
||||||
|
|
||||||
|
# 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数
|
||||||
|
REASONING_MODEL_RE = re.compile(r'^(o1|o3|o4|gpt-5|gpt-6)', re.IGNORECASE)
|
||||||
|
|
||||||
|
DEFAULT_TIMEOUT_MS = 180000
|
||||||
|
|
||||||
|
|
||||||
|
def join_url(base_url: str, suffix: str) -> str:
|
||||||
|
return f"{str(base_url or '').rstrip('/')}{suffix}"
|
||||||
|
|
||||||
|
|
||||||
|
def thinking_mode_of(provider: str) -> str:
|
||||||
|
"""
|
||||||
|
这个提供商的思考强度该用哪个字段传 —— 由预设里的 thinkingMode 决定。
|
||||||
|
|
||||||
|
别写死成"是 ark 就发 thinking、是 openai 就发 reasoning_effort":
|
||||||
|
现在支持的兼容厂商有十来家,各家认的字段不一样,
|
||||||
|
而**给不认这个字段的服务发过去,有些会直接 400**。所以认不出来的一律 'none'。
|
||||||
|
"""
|
||||||
|
preset = PROVIDER_PRESETS.get(provider) or {}
|
||||||
|
return preset.get('thinkingMode') or 'none'
|
||||||
|
|
||||||
|
|
||||||
|
def apply_thinking(provider: str, level: str, body: dict) -> dict:
|
||||||
|
"""
|
||||||
|
思考强度映射(和 Node 版逐字一致):
|
||||||
|
'ark' → 顶层 thinking: {type: enabled|disabled}
|
||||||
|
'effort' → reasoning_effort: low|medium|high
|
||||||
|
'none' → 什么都不发(DeepSeek / Kimi / 通义 / 硅基流动 等自己决定)
|
||||||
|
"""
|
||||||
|
value = level or 'auto'
|
||||||
|
if value == 'auto':
|
||||||
|
return body
|
||||||
|
|
||||||
|
mode = thinking_mode_of(provider)
|
||||||
|
if mode == 'ark':
|
||||||
|
body['thinking'] = {'type': 'disabled' if value == 'off' else 'enabled'}
|
||||||
|
return body
|
||||||
|
if mode == 'effort':
|
||||||
|
if value == 'off':
|
||||||
|
body.pop('reasoning_effort', None)
|
||||||
|
else:
|
||||||
|
body['reasoning_effort'] = 'high' if value == 'high' else 'low' if value == 'low' else 'medium'
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_body(provider: str, model: str, thinking_level: str, body: dict) -> dict:
|
||||||
|
"""
|
||||||
|
推理模型不接受 temperature/top_p/... ,而且"传默认值"也算传了,
|
||||||
|
所以这里是 delete 而不是改回默认值(OpenAI 会对未知/不允许的参数直接 400)。
|
||||||
|
"""
|
||||||
|
if thinking_mode_of(provider) == 'effort' and REASONING_MODEL_RE.match(str(model or '')):
|
||||||
|
for key in ('temperature', 'top_p', 'presence_penalty', 'frequency_penalty', 'logprobs'):
|
||||||
|
body.pop(key, None)
|
||||||
|
if body.get('max_tokens') is not None:
|
||||||
|
body['max_completion_tokens'] = body.pop('max_tokens')
|
||||||
|
# 推理模型默认就带思考,off 时明确要求最小
|
||||||
|
if thinking_level == 'off':
|
||||||
|
body['reasoning_effort'] = 'minimal'
|
||||||
|
return apply_thinking(provider, thinking_level, body)
|
||||||
|
|
||||||
|
|
||||||
|
def build_body(*, provider: str, model: str, messages: list, tools=None, temperature=None,
|
||||||
|
stream: bool, thinking_level: str = 'auto') -> dict:
|
||||||
|
body = {'model': model, 'messages': messages, 'stream': bool(stream)}
|
||||||
|
# 只有真的是数字才带上 temperature(JS 用 typeof === 'number' + isFinite)
|
||||||
|
if isinstance(temperature, (int, float)) and not isinstance(temperature, bool):
|
||||||
|
body['temperature'] = temperature
|
||||||
|
if isinstance(tools, list) and len(tools) > 0:
|
||||||
|
body['tools'] = tools
|
||||||
|
body['tool_choice'] = 'auto'
|
||||||
|
return normalize_body(provider, model, thinking_level, body)
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamError(RuntimeError):
|
||||||
|
"""上游返回非 2xx 或网络异常时抛出(消息里带状态码和响应片段)。"""
|
||||||
|
|
||||||
|
|
||||||
|
def _request(url: str, api_key: str, body: dict | None = None, method: str = 'POST'):
|
||||||
|
if not api_key:
|
||||||
|
raise UpstreamError('缺少 API Key:请在「设置 → AI 内核」里填写,或在数据目录的 .env 里配置')
|
||||||
|
data = None
|
||||||
|
headers = {'Authorization': f'Bearer {api_key}'}
|
||||||
|
if body is not None:
|
||||||
|
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||||
|
try:
|
||||||
|
# 不用 urlopen 的 with:流式响应要留给调用方边读边消费
|
||||||
|
return urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
detail = ''
|
||||||
|
try:
|
||||||
|
detail = exc.read().decode('utf-8', errors='replace')
|
||||||
|
except Exception: # noqa: BLE001 - 读不到正文就算了
|
||||||
|
detail = ''
|
||||||
|
raise UpstreamError(f'上游 {exc.code}:{detail[:600]}') from exc
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
raise UpstreamError(f'无法连接上游 {url}:{exc.reason}') from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _line_source(resp):
|
||||||
|
"""
|
||||||
|
把响应体变成"可以逐行读的文本流"。
|
||||||
|
有些网关即使没请求 gzip 也会压缩,这里顺手解一下(br 需要第三方库,不处理)。
|
||||||
|
"""
|
||||||
|
encoding = (resp.headers.get('Content-Encoding') or '').lower()
|
||||||
|
if 'gzip' in encoding:
|
||||||
|
return gzip.GzipFile(fileobj=resp)
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
def chat_once(*, provider: str, base_url: str, api_key: str, model: str, messages: list,
|
||||||
|
tools=None, temperature=None, thinking_level: str = 'auto', **kwargs) -> dict:
|
||||||
|
"""非流式调用(内核目前用不到,保留给脚本/未来接口用)。"""
|
||||||
|
body = build_body(provider=provider, model=model, messages=messages, tools=tools,
|
||||||
|
temperature=temperature, stream=False, thinking_level=thinking_level)
|
||||||
|
resp = _request(join_url(base_url, '/chat/completions'), api_key, body)
|
||||||
|
try:
|
||||||
|
text = resp.read().decode('utf-8', errors='replace')
|
||||||
|
finally:
|
||||||
|
resp.close()
|
||||||
|
try:
|
||||||
|
payload = json.loads(text)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise UpstreamError(f'上游返回非 JSON:{text[:300]}') from exc
|
||||||
|
message = ((payload.get('choices') or [{}])[0] or {}).get('message') or {}
|
||||||
|
return {
|
||||||
|
'content': message.get('content') or '',
|
||||||
|
'reasoning': message.get('reasoning_content') or '',
|
||||||
|
'toolCalls': [
|
||||||
|
{
|
||||||
|
'id': tc.get('id'),
|
||||||
|
'name': (tc.get('function') or {}).get('name'),
|
||||||
|
'argsRaw': (tc.get('function') or {}).get('arguments') or '{}',
|
||||||
|
'args': safe_parse((tc.get('function') or {}).get('arguments')),
|
||||||
|
}
|
||||||
|
for tc in (message.get('tool_calls') or [])
|
||||||
|
],
|
||||||
|
'usage': payload.get('usage'),
|
||||||
|
'raw': payload,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def stream_chat(*, provider: str, base_url: str, api_key: str, model: str, messages: list,
|
||||||
|
tools=None, temperature=None, thinking_level: str = 'auto',
|
||||||
|
should_stop: Optional[Callable[[], bool]] = None, **kwargs) -> Iterator[dict]:
|
||||||
|
"""
|
||||||
|
流式调用。yield 的事件(与 Node 版 streamChat 一一对应):
|
||||||
|
{'type':'text', 'text'} / {'type':'reasoning', 'text'}
|
||||||
|
{'type':'tool_calls', 'toolCalls'} / {'type':'usage', 'usage'} / {'type':'finish', 'reason'}
|
||||||
|
|
||||||
|
should_stop:客户端断开时由 app.py 传入的回调;每读一行检查一次,
|
||||||
|
避免上游还在吐字而我们已经没人要了(安卓上尤其费电/费流量)。
|
||||||
|
"""
|
||||||
|
body = build_body(provider=provider, model=model, messages=messages, tools=tools,
|
||||||
|
temperature=temperature, stream=True, thinking_level=thinking_level)
|
||||||
|
resp = _request(join_url(base_url, '/chat/completions'), api_key, body)
|
||||||
|
tool_acc: dict = {}
|
||||||
|
finish_reason = None
|
||||||
|
try:
|
||||||
|
source = _line_source(resp)
|
||||||
|
while True:
|
||||||
|
if should_stop and should_stop():
|
||||||
|
raise UpstreamError('客户端断开')
|
||||||
|
raw = source.readline()
|
||||||
|
if not raw:
|
||||||
|
break
|
||||||
|
line = raw.decode('utf-8', errors='replace').strip()
|
||||||
|
if not line or line.startswith(':'):
|
||||||
|
continue
|
||||||
|
if not line.startswith('data:'):
|
||||||
|
continue
|
||||||
|
payload = line[5:].strip()
|
||||||
|
if payload == '[DONE]':
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
event = json.loads(payload)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
choices = event.get('choices') or []
|
||||||
|
choice = choices[0] if choices else None
|
||||||
|
if not choice:
|
||||||
|
# 只带 usage 的收尾包(很多网关这么发)
|
||||||
|
if event.get('usage'):
|
||||||
|
yield {'type': 'usage', 'usage': event['usage']}
|
||||||
|
continue
|
||||||
|
if choice.get('finish_reason'):
|
||||||
|
finish_reason = choice['finish_reason']
|
||||||
|
delta = choice.get('delta') or {}
|
||||||
|
# 思维链增量:方舟用 reasoning_content,部分网关用 reasoning
|
||||||
|
reasoning = delta.get('reasoning_content')
|
||||||
|
if isinstance(reasoning, str) and reasoning:
|
||||||
|
yield {'type': 'reasoning', 'text': reasoning}
|
||||||
|
content = delta.get('content')
|
||||||
|
if isinstance(content, str) and content:
|
||||||
|
yield {'type': 'text', 'text': content}
|
||||||
|
for tc in delta.get('tool_calls') or []:
|
||||||
|
idx = tc.get('index', 0)
|
||||||
|
acc = tool_acc.setdefault(idx, {'id': '', 'name': '', 'argsRaw': ''})
|
||||||
|
if tc.get('id'):
|
||||||
|
acc['id'] = tc['id']
|
||||||
|
fn = tc.get('function') or {}
|
||||||
|
if fn.get('name'):
|
||||||
|
acc['name'] = fn['name']
|
||||||
|
if fn.get('arguments'):
|
||||||
|
acc['argsRaw'] += fn['arguments']
|
||||||
|
if event.get('usage'):
|
||||||
|
yield {'type': 'usage', 'usage': event['usage']}
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
resp.close()
|
||||||
|
except Exception: # noqa: BLE001 - 关闭失败无所谓
|
||||||
|
pass
|
||||||
|
|
||||||
|
tool_calls = []
|
||||||
|
for index, key in enumerate(sorted(tool_acc.keys())):
|
||||||
|
item = tool_acc[key]
|
||||||
|
if not item['name']:
|
||||||
|
continue
|
||||||
|
tool_calls.append({
|
||||||
|
'id': item['id'] or f'call_{index}',
|
||||||
|
'name': item['name'],
|
||||||
|
'argsRaw': item['argsRaw'] or '{}',
|
||||||
|
'args': safe_parse(item['argsRaw']),
|
||||||
|
})
|
||||||
|
if tool_calls:
|
||||||
|
yield {'type': 'tool_calls', 'toolCalls': tool_calls}
|
||||||
|
yield {'type': 'finish', 'reason': finish_reason}
|
||||||
|
|
||||||
|
|
||||||
|
def list_models(*, base_url: str, api_key: str) -> list:
|
||||||
|
"""
|
||||||
|
拉上游模型列表(可选能力)。
|
||||||
|
|
||||||
|
注意错误文案要和 Node 版一致:这里**不带响应体**(Node 的 listModels 只抛 `上游 {status}`),
|
||||||
|
所以没有复用 _request,而是自己发一次请求。
|
||||||
|
"""
|
||||||
|
if not api_key:
|
||||||
|
raise UpstreamError('缺少 API Key')
|
||||||
|
url = join_url(base_url, '/models')
|
||||||
|
req = urllib.request.Request(url, headers={'Authorization': f'Bearer {api_key}'}, method='GET')
|
||||||
|
try:
|
||||||
|
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
raise UpstreamError(f'上游 {exc.code}') from exc
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
raise UpstreamError(f'无法连接上游 {url}:{exc.reason}') from exc
|
||||||
|
try:
|
||||||
|
payload = json.loads(resp.read().decode('utf-8', errors='replace'))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise UpstreamError('上游返回非 JSON') from exc
|
||||||
|
finally:
|
||||||
|
resp.close()
|
||||||
|
return [m.get('id') for m in (payload.get('data') or []) if m.get('id')]
|
||||||
|
|
||||||
|
|
||||||
|
def safe_parse(raw):
|
||||||
|
"""参数可能是字符串(流式拼接)也可能是对象,坏 JSON 时保留原文。"""
|
||||||
|
if raw is None:
|
||||||
|
return {}
|
||||||
|
if isinstance(raw, (dict, list)):
|
||||||
|
return raw
|
||||||
|
try:
|
||||||
|
return json.loads(raw)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return {'__raw': str(raw)}
|
||||||
364
android/kernel/speech.py
Normal file
@@ -0,0 +1,364 @@
|
|||||||
|
"""
|
||||||
|
语音:朗读(TTS)和语音识别(STT)。
|
||||||
|
|
||||||
|
对应 Node 版 server/src/speech.mjs,两份实现的请求体/返回字段逐字段一致。
|
||||||
|
|
||||||
|
为什么放在内核里而不是安卓端直接调:
|
||||||
|
1. API Key 只存一份(跟对话的 Key 放一起),安卓端拿不到也不该拿;
|
||||||
|
2. 电脑端的 Web/exe 版能白捡同一个能力(浏览器用 MediaRecorder 录音就行);
|
||||||
|
3. 厂商鉴权差异只在这一个文件里,界面侧只管"给我一段文字 / 给我一段音频"。
|
||||||
|
|
||||||
|
支持的引擎:
|
||||||
|
TTS
|
||||||
|
- 'volc' 火山语音合成(豆包同款音色)https://openspeech.bytedance.com/api/v1/tts
|
||||||
|
- 'openai' OpenAI 兼容的 /audio/speech(返回原始音频字节)
|
||||||
|
- 'system' 不调云端,交给设备自带的 TTS(安卓 TextToSpeech / 浏览器 speechSynthesis)
|
||||||
|
STT
|
||||||
|
- 'openai' OpenAI 兼容的 /audio/transcriptions(multipart)
|
||||||
|
- 'system' 交给设备自带的识别(安卓 SpeechRecognizer)
|
||||||
|
|
||||||
|
只用标准库:urllib 发请求;multipart 手拼(标准库没有现成的编码器)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
DEFAULT_TIMEOUT_TTS = 60
|
||||||
|
DEFAULT_TIMEOUT_STT = 120
|
||||||
|
|
||||||
|
# 允许用环境变量覆盖:自测时把火山接口指到本地 mock,就能验证"我们到底发了什么"
|
||||||
|
# (鉴权头那个分号、body 的层级,光看代码容易自我说服,实测才算数)
|
||||||
|
VOLC_TTS_URL = os.environ.get('DOUBAO_VOLC_TTS_URL') or 'https://openspeech.bytedance.com/api/v1/tts'
|
||||||
|
|
||||||
|
# 火山的 encoding -> MIME。文档里 mp3/wav/ogg_opus/pcm 是常用的几个
|
||||||
|
VOLC_MIME = {
|
||||||
|
'mp3': 'audio/mpeg',
|
||||||
|
'wav': 'audio/wav',
|
||||||
|
'ogg_opus': 'audio/ogg',
|
||||||
|
'pcm': 'audio/L16',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class SpeechError(Exception):
|
||||||
|
"""带用户可读原因的失败。界面直接把它显示出来,不用再猜。"""
|
||||||
|
|
||||||
|
|
||||||
|
def _settings_speech(settings: dict) -> dict:
|
||||||
|
speech = (settings or {}).get('speech')
|
||||||
|
return speech if isinstance(speech, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def _post_json(url: str, body: dict, headers: dict, timeout: int) -> dict:
|
||||||
|
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
||||||
|
req = urllib.request.Request(url, data=data, method='POST')
|
||||||
|
req.add_header('Content-Type', 'application/json')
|
||||||
|
for k, v in headers.items():
|
||||||
|
req.add_header(k, v)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||||
|
raw = resp.read()
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
detail = ''
|
||||||
|
try:
|
||||||
|
detail = exc.read().decode('utf-8', 'replace')[:400]
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||||||
|
try:
|
||||||
|
return json.loads(raw.decode('utf-8'))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise SpeechError(f'返回不是 JSON:{raw[:200]!r}') from exc
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 朗读
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def synthesize(text: str, settings: dict) -> dict:
|
||||||
|
"""
|
||||||
|
把文字合成为音频。
|
||||||
|
|
||||||
|
返回:
|
||||||
|
{'engine': 'system'} → 让设备自己念(没配云端时)
|
||||||
|
{'engine': 'volc'|'openai', 'mime': ..., 'audio': '<base64>'}
|
||||||
|
"""
|
||||||
|
content = (text or '').strip()
|
||||||
|
if not content:
|
||||||
|
raise SpeechError('没有要朗读的内容')
|
||||||
|
|
||||||
|
speech = _settings_speech(settings)
|
||||||
|
engine = (speech.get('ttsEngine') or 'system').lower()
|
||||||
|
speed = float(speech.get('ttsSpeed') or 1.0)
|
||||||
|
speed = min(max(speed, 0.2), 3.0)
|
||||||
|
|
||||||
|
if engine == 'volc':
|
||||||
|
return _synthesize_volc(content, speech, speed)
|
||||||
|
if engine == 'openai':
|
||||||
|
return _synthesize_openai(content, settings, speech, speed)
|
||||||
|
return {'engine': 'system'}
|
||||||
|
|
||||||
|
|
||||||
|
def _synthesize_volc(text: str, speech: dict, speed: float) -> dict:
|
||||||
|
"""
|
||||||
|
火山语音合成。
|
||||||
|
|
||||||
|
两个容易踩的点(都对着官方文档和第三方实现核对过):
|
||||||
|
1. 鉴权头是 `Bearer;{token}` —— **分号,不是空格**。写成空格会被判鉴权失败;
|
||||||
|
2. 成功判定看 body 里的 `code == 3000`,HTTP 状态码是 200 也可能带错误码。
|
||||||
|
返回的 `data` 是**纯 base64**(不是 data URL),直接解出来就是音频字节。
|
||||||
|
"""
|
||||||
|
app_id = (speech.get('volcAppId') or '').strip()
|
||||||
|
token = (speech.get('volcToken') or '').strip()
|
||||||
|
cluster = (speech.get('volcCluster') or 'volcano_tts').strip() or 'volcano_tts'
|
||||||
|
voice = (speech.get('ttsVoice') or '').strip() or 'BV700_streaming'
|
||||||
|
encoding = (speech.get('volcEncoding') or 'mp3').strip() or 'mp3'
|
||||||
|
|
||||||
|
if not app_id or not token:
|
||||||
|
raise SpeechError('火山语音需要 App ID 和 Access Token(在火山控制台「语音技术」里创建应用后拿到)')
|
||||||
|
|
||||||
|
body = {
|
||||||
|
'app': {'appid': app_id, 'token': token, 'cluster': cluster},
|
||||||
|
'user': {'uid': 'doubao'},
|
||||||
|
'audio': {
|
||||||
|
'voice_type': voice,
|
||||||
|
'encoding': encoding,
|
||||||
|
'speed_ratio': speed,
|
||||||
|
'volume_ratio': 1.0,
|
||||||
|
'pitch_ratio': 1.0,
|
||||||
|
},
|
||||||
|
'request': {
|
||||||
|
'reqid': str(uuid.uuid4()),
|
||||||
|
'text': text,
|
||||||
|
'text_type': 'plain',
|
||||||
|
'operation': 'query',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, DEFAULT_TIMEOUT_TTS)
|
||||||
|
|
||||||
|
code = result.get('code')
|
||||||
|
if code != 3000:
|
||||||
|
raise SpeechError(f'火山返回 code={code} message={result.get("message") or result.get("Message") or "?"}')
|
||||||
|
|
||||||
|
data = result.get('data')
|
||||||
|
if not data:
|
||||||
|
raise SpeechError('火山没返回音频数据')
|
||||||
|
return {'engine': 'volc', 'mime': VOLC_MIME.get(encoding, 'audio/mpeg'), 'audio': data}
|
||||||
|
|
||||||
|
|
||||||
|
def _synthesize_openai(text: str, settings: dict, speech: dict, speed: float) -> dict:
|
||||||
|
"""OpenAI 兼容的 /audio/speech:POST 进去,直接吐音频字节(不是 JSON)。"""
|
||||||
|
api_key, base_url = _resolve_openai(settings, speech)
|
||||||
|
voice = (speech.get('ttsVoice') or '').strip() or 'alloy'
|
||||||
|
model = (speech.get('ttsModel') or '').strip() or 'tts-1'
|
||||||
|
fmt = (speech.get('openaiFormat') or 'mp3').strip() or 'mp3'
|
||||||
|
|
||||||
|
body = json.dumps({
|
||||||
|
'model': model,
|
||||||
|
'input': text,
|
||||||
|
'voice': voice,
|
||||||
|
'response_format': fmt,
|
||||||
|
'speed': speed,
|
||||||
|
}, ensure_ascii=False).encode('utf-8')
|
||||||
|
|
||||||
|
req = urllib.request.Request(f'{base_url}/audio/speech', data=body, method='POST')
|
||||||
|
req.add_header('Content-Type', 'application/json')
|
||||||
|
req.add_header('Authorization', f'Bearer {api_key}')
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||||||
|
raw = resp.read()
|
||||||
|
ctype = resp.headers.get('Content-Type') or 'audio/mpeg'
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
detail = ''
|
||||||
|
try:
|
||||||
|
detail = exc.read().decode('utf-8', 'replace')[:400]
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||||||
|
|
||||||
|
if not raw:
|
||||||
|
raise SpeechError('返回了空音频')
|
||||||
|
return {
|
||||||
|
'engine': 'openai',
|
||||||
|
'mime': ctype.split(';')[0].strip() or 'audio/mpeg',
|
||||||
|
'audio': base64.b64encode(raw).decode('ascii'),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 语音识别
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def transcribe(audio: bytes, filename: str, content_type: str, settings: dict) -> dict:
|
||||||
|
"""
|
||||||
|
把一段音频转成文字。
|
||||||
|
|
||||||
|
返回 {'engine': 'system'} 表示"交给设备自己的识别",
|
||||||
|
否则 {'engine': 'openai', 'text': '...'}。
|
||||||
|
"""
|
||||||
|
if not audio:
|
||||||
|
raise SpeechError('没有录到音频')
|
||||||
|
|
||||||
|
speech = _settings_speech(settings)
|
||||||
|
engine = (speech.get('sttEngine') or 'system').lower()
|
||||||
|
if engine != 'openai':
|
||||||
|
return {'engine': 'system'}
|
||||||
|
|
||||||
|
api_key, base_url = _resolve_openai(settings, speech)
|
||||||
|
model = (speech.get('sttModel') or '').strip() or 'whisper-1'
|
||||||
|
lang = (speech.get('sttLanguage') or '').strip()
|
||||||
|
|
||||||
|
fields = {'model': model}
|
||||||
|
if lang:
|
||||||
|
fields['language'] = lang
|
||||||
|
|
||||||
|
body, boundary = _multipart(fields, 'file', filename or 'audio.wav', content_type or 'audio/wav', audio)
|
||||||
|
req = urllib.request.Request(f'{base_url}/audio/transcriptions', data=body, method='POST')
|
||||||
|
req.add_header('Content-Type', f'multipart/form-data; boundary={boundary}')
|
||||||
|
req.add_header('Authorization', f'Bearer {api_key}')
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_STT) as resp:
|
||||||
|
raw = resp.read()
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
detail = ''
|
||||||
|
try:
|
||||||
|
detail = exc.read().decode('utf-8', 'replace')[:400]
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = json.loads(raw.decode('utf-8'))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise SpeechError(f'返回不是 JSON:{raw[:200]!r}') from exc
|
||||||
|
|
||||||
|
text = (result.get('text') or '').strip()
|
||||||
|
if not text:
|
||||||
|
raise SpeechError('识别结果为空(可能是没人说话,或音频格式不对)')
|
||||||
|
return {'engine': 'openai', 'text': text}
|
||||||
|
|
||||||
|
|
||||||
|
def _multipart(fields: dict, file_field: str, filename: str, content_type: str, content: bytes):
|
||||||
|
"""
|
||||||
|
手拼 multipart/form-data。
|
||||||
|
|
||||||
|
为什么不用 requests:Chaquopy 里第三方库要额外打包,而标准库没有
|
||||||
|
multipart 编码器 —— 这个格式本身很简单,拼一遍就够了。
|
||||||
|
"""
|
||||||
|
boundary = f'----doubao{uuid.uuid4().hex}'
|
||||||
|
out = bytearray()
|
||||||
|
for key, value in fields.items():
|
||||||
|
out += f'--{boundary}\r\n'.encode()
|
||||||
|
out += f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode()
|
||||||
|
out += f'{value}\r\n'.encode()
|
||||||
|
out += f'--{boundary}\r\n'.encode()
|
||||||
|
out += f'Content-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n'.encode()
|
||||||
|
out += f'Content-Type: {content_type}\r\n\r\n'.encode()
|
||||||
|
out += content
|
||||||
|
out += f'\r\n--{boundary}--\r\n'.encode()
|
||||||
|
return bytes(out), boundary
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_openai(settings: dict, speech: dict):
|
||||||
|
"""
|
||||||
|
取 OpenAI 兼容那套的 Key 和地址。
|
||||||
|
|
||||||
|
默认复用主对话的设置(同一个 Key 通常也能用语音接口);
|
||||||
|
也可以在 speech 里单独填,方便"对话用方舟、语音用 OpenAI"这种组合。
|
||||||
|
"""
|
||||||
|
api_key = (speech.get('openaiApiKey') or '').strip() or (settings or {}).get('apiKey') or ''
|
||||||
|
base_url = (speech.get('openaiBaseUrl') or '').strip() or (settings or {}).get('baseUrl') or ''
|
||||||
|
base_url = base_url.rstrip('/')
|
||||||
|
if not api_key:
|
||||||
|
raise SpeechError('没有 API Key(在设置里填,或在「语音」里单独指定)')
|
||||||
|
if not base_url:
|
||||||
|
raise SpeechError('没有 Base URL')
|
||||||
|
return api_key, base_url
|
||||||
|
|
||||||
|
|
||||||
|
def speech_state(settings: dict) -> dict:
|
||||||
|
"""给界面看的当前语音配置(脱敏)。"""
|
||||||
|
speech = _settings_speech(settings)
|
||||||
|
return {
|
||||||
|
'ttsEngine': speech.get('ttsEngine') or 'system',
|
||||||
|
'ttsVoice': speech.get('ttsVoice') or '',
|
||||||
|
'ttsSpeed': speech.get('ttsSpeed') or 1.0,
|
||||||
|
'autoRead': bool(speech.get('autoRead')),
|
||||||
|
'sttEngine': speech.get('sttEngine') or 'system',
|
||||||
|
'sttModel': speech.get('sttModel') or 'whisper-1',
|
||||||
|
'sttLanguage': speech.get('sttLanguage') or '',
|
||||||
|
'volcAppId': speech.get('volcAppId') or '',
|
||||||
|
'volcCluster': speech.get('volcCluster') or 'volcano_tts',
|
||||||
|
'volcEncoding': speech.get('volcEncoding') or 'mp3',
|
||||||
|
'hasVolcToken': bool(speech.get('volcToken')),
|
||||||
|
'hasOpenaiKey': bool(speech.get('openaiApiKey') or (settings or {}).get('apiKey')),
|
||||||
|
'openaiBaseUrl': speech.get('openaiBaseUrl') or '',
|
||||||
|
'ttsModel': speech.get('ttsModel') or 'tts-1',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# 默认值:Android 端 Kotlin 侧也用不到这个,但 Node/Python 必须一致
|
||||||
|
DEFAULT_SPEECH = {
|
||||||
|
'ttsEngine': 'system',
|
||||||
|
'ttsVoice': '',
|
||||||
|
'ttsSpeed': 1.0,
|
||||||
|
'autoRead': False,
|
||||||
|
'sttEngine': 'system',
|
||||||
|
'sttModel': 'whisper-1',
|
||||||
|
'sttLanguage': '',
|
||||||
|
'volcAppId': '',
|
||||||
|
'volcToken': '',
|
||||||
|
'volcCluster': 'volcano_tts',
|
||||||
|
'volcEncoding': 'mp3',
|
||||||
|
'openaiApiKey': '',
|
||||||
|
'openaiBaseUrl': '',
|
||||||
|
'ttsModel': 'tts-1',
|
||||||
|
}
|
||||||
|
|
||||||
|
# 常用音色,给界面做下拉。火山那几个是文档里的常见 voice_type。
|
||||||
|
VOLC_VOICES = [
|
||||||
|
{'value': 'BV700_streaming', 'label': '通用女声(BV700)'},
|
||||||
|
{'value': 'BV001_streaming', 'label': '通用女声 2(BV001)'},
|
||||||
|
{'value': 'BV002_streaming', 'label': '通用男声(BV002)'},
|
||||||
|
{'value': 'BV701_streaming', 'label': '通用男声 2(BV701)'},
|
||||||
|
{'value': 'BV064_streaming', 'label': '甜美女声(BV064)'},
|
||||||
|
{'value': 'BV138_streaming', 'label': '沉稳男声(BV138)'},
|
||||||
|
]
|
||||||
|
|
||||||
|
OPENAI_VOICES = [
|
||||||
|
{'value': 'alloy', 'label': 'alloy(中性)'},
|
||||||
|
{'value': 'nova', 'label': 'nova(女声,推荐)'},
|
||||||
|
{'value': 'shimmer', 'label': 'shimmer(女声,柔和)'},
|
||||||
|
{'value': 'echo', 'label': 'echo(男声)'},
|
||||||
|
{'value': 'onyx', 'label': 'onyx(男声,低沉)'},
|
||||||
|
{'value': 'fable', 'label': 'fable(叙述)'},
|
||||||
|
{'value': 'coral', 'label': 'coral(女声,明快)'},
|
||||||
|
{'value': 'sage', 'label': 'sage(女声,沉稳)'},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def voice_options(engine: str):
|
||||||
|
if engine == 'volc':
|
||||||
|
return VOLC_VOICES
|
||||||
|
if engine == 'openai':
|
||||||
|
return OPENAI_VOICES
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def debug_env() -> dict:
|
||||||
|
"""给 /api/speech/state 用的环境信息(判断能不能用云端语音)。"""
|
||||||
|
return {
|
||||||
|
'isAndroid': bool(os.environ.get('ANDROID_ROOT')),
|
||||||
|
'hasStdlib': True,
|
||||||
|
}
|
||||||
460
android/kernel/store.py
Normal file
@@ -0,0 +1,460 @@
|
|||||||
|
"""
|
||||||
|
持久化:设置 / 会话 / 智能体。
|
||||||
|
|
||||||
|
对应 Node 版的 config.mjs(设置)+ store.mjs(会话)+ agents.mjs(智能体),
|
||||||
|
文件名也保持一致(settings.json / conversations.json / agents.json),
|
||||||
|
这样安卓内核和桌面内核可以共用同一个数据目录。
|
||||||
|
|
||||||
|
为什么用 JSON 文件而不是 SQLite:
|
||||||
|
* 数据量极小(几条会话、几个智能体),前端还要能直接看到/改这些文件;
|
||||||
|
* 安卓上 Chaquopy 自带 sqlite3,但跨端"人肉可读"更重要;
|
||||||
|
* 写盘走"临时文件 + 原子替换",避免安卓被杀进程时留下半个 JSON。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import paths
|
||||||
|
from defaults import DEFAULT_AGENTS, DEFAULT_SETTINGS
|
||||||
|
|
||||||
|
_lock = threading.RLock()
|
||||||
|
_conv_state = None # 会话状态在内存里缓存(和 Node 版 store.mjs 一样只 load 一次)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 通用小工具
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def now_iso() -> str:
|
||||||
|
"""
|
||||||
|
和 JS 的 new Date().toISOString() 完全一致的格式:
|
||||||
|
2025-01-01T12:00:00.000Z(毫秒精度 + Z 后缀)。
|
||||||
|
前端会把这些字符串直接排序/展示,格式不一致会出现"时间跳来跳去"。
|
||||||
|
"""
|
||||||
|
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||||||
|
|
||||||
|
|
||||||
|
def _read_json(file_path: str):
|
||||||
|
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as fh:
|
||||||
|
return json.load(fh)
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
print(f'[store] {os.path.basename(file_path)} 解析失败:{exc}', file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _write_json(file_path: str, payload) -> None:
|
||||||
|
"""原子写:先写 .tmp 再 os.replace,避免掉电/被杀时留下半个文件。"""
|
||||||
|
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
||||||
|
tmp = f'{file_path}.tmp'
|
||||||
|
with open(tmp, 'w', encoding='utf-8') as fh:
|
||||||
|
json.dump(payload, fh, ensure_ascii=False, indent=2)
|
||||||
|
os.replace(tmp, file_path)
|
||||||
|
|
||||||
|
|
||||||
|
def _as_text(value) -> str:
|
||||||
|
"""JS 的 String(x):None 会变成空串而不是 'None'。"""
|
||||||
|
if value is None:
|
||||||
|
return ''
|
||||||
|
if isinstance(value, str):
|
||||||
|
return value
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 设置
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
_dotenv_loaded = False
|
||||||
|
|
||||||
|
|
||||||
|
def _load_dotenv() -> None:
|
||||||
|
"""
|
||||||
|
极简 .env 解析。Node 版读 server/.env;Python 版读数据目录和内核目录下的 .env,
|
||||||
|
这样安卓上把 key 放在数据目录里就能用,不需要动源码目录。
|
||||||
|
"""
|
||||||
|
global _dotenv_loaded
|
||||||
|
if _dotenv_loaded:
|
||||||
|
return
|
||||||
|
_dotenv_loaded = True
|
||||||
|
p = paths.get()
|
||||||
|
for folder in (p.data_dir, os.path.dirname(os.path.abspath(__file__))):
|
||||||
|
env_file = os.path.join(folder, '.env')
|
||||||
|
if not os.path.isfile(env_file):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
with open(env_file, 'r', encoding='utf-8') as fh:
|
||||||
|
lines = fh.read().splitlines()
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
for raw in lines:
|
||||||
|
line = raw.strip()
|
||||||
|
if not line or line.startswith('#') or '=' not in line:
|
||||||
|
continue
|
||||||
|
key, _, value = line.partition('=')
|
||||||
|
key = key.strip()
|
||||||
|
value = value.strip()
|
||||||
|
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
|
||||||
|
value = value[1:-1]
|
||||||
|
if key and key not in os.environ:
|
||||||
|
os.environ[key] = value
|
||||||
|
|
||||||
|
|
||||||
|
def mask_settings(settings: dict) -> dict:
|
||||||
|
"""脱敏:apiKey / 语音 Token 只回掩码 + has* 标志(前端据此显示"已配置")。"""
|
||||||
|
out = dict(settings)
|
||||||
|
out['apiKey'] = '••••••••' if settings.get('apiKey') else ''
|
||||||
|
out['hasApiKey'] = bool(settings.get('apiKey'))
|
||||||
|
speech = dict(out.get('speech') or {})
|
||||||
|
speech['volcToken'] = '••••••••' if speech.get('volcToken') else ''
|
||||||
|
speech['openaiApiKey'] = '••••••••' if speech.get('openaiApiKey') else ''
|
||||||
|
out['speech'] = speech
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def read_settings() -> dict:
|
||||||
|
"""读设置:默认值 + 文件 + 环境变量兜底(字段与 Node 版一致)。"""
|
||||||
|
_load_dotenv()
|
||||||
|
stored = _read_json(paths.get().settings_file) or {}
|
||||||
|
if not isinstance(stored, dict):
|
||||||
|
stored = {}
|
||||||
|
settings = dict(DEFAULT_SETTINGS)
|
||||||
|
settings.update(stored)
|
||||||
|
# 子对象要深合并,否则用户只改 security.allow 会把 security.mode 冲掉。
|
||||||
|
# ★ 而且必须防住"子对象被非字典值覆盖":曾经前端把嵌套 Map 序列化成了字符串
|
||||||
|
# ({"speech":"{autoRead=true}"}),存进去之后**每一次**读配置都会抛
|
||||||
|
# TypeError,/api/state 从此一直 500 —— 一个坏字段把整个 App 弄成空白。
|
||||||
|
# 所以:读的时候发现不是字典就回落默认值(自愈),写的时候也不让非字典覆盖。
|
||||||
|
for key in ('tools', 'security', 'speech'):
|
||||||
|
defaults = DEFAULT_SETTINGS.get(key) or {}
|
||||||
|
raw = stored.get(key)
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
if raw is not None:
|
||||||
|
print(f'[config] settings.json 里的 {key} 不是对象,已回落默认值', file=sys.stderr, flush=True)
|
||||||
|
raw = {}
|
||||||
|
settings[key] = {**defaults, **raw}
|
||||||
|
if not isinstance(settings['security'].get('allow'), list):
|
||||||
|
settings['security']['allow'] = []
|
||||||
|
settings.pop('hasApiKey', None)
|
||||||
|
|
||||||
|
# 环境变量兜底:没填 key 时用 .env / 系统环境变量里的
|
||||||
|
preset = _preset_of(settings)
|
||||||
|
if not settings.get('apiKey') and preset.get('apiKeyEnv'):
|
||||||
|
settings['apiKey'] = os.environ.get(preset['apiKeyEnv'], '')
|
||||||
|
return settings
|
||||||
|
|
||||||
|
|
||||||
|
def _preset_of(settings: dict) -> dict:
|
||||||
|
from defaults import PROVIDER_PRESETS # 局部导入,避免循环依赖
|
||||||
|
|
||||||
|
return PROVIDER_PRESETS.get(settings.get('provider')) or PROVIDER_PRESETS['ark']
|
||||||
|
|
||||||
|
|
||||||
|
def write_settings(patch: dict) -> dict:
|
||||||
|
"""写设置:浅合并 + 子对象深合并 + 掩码值表示"不修改"。"""
|
||||||
|
if not isinstance(patch, dict):
|
||||||
|
patch = {}
|
||||||
|
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
|
||||||
|
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||||||
|
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
|
||||||
|
# systemPrompt / toolsDir 故意不在此列:它们"留空"是合理需求。
|
||||||
|
for key in ('baseUrl', 'model', 'apiKey', 'nickname', 'provider', 'thinkingLevel'):
|
||||||
|
if key in patch and isinstance(patch[key], str) and not patch[key].strip():
|
||||||
|
patch.pop(key)
|
||||||
|
current = read_settings()
|
||||||
|
nxt = {**current, **patch}
|
||||||
|
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
|
||||||
|
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 JSON 序列化踩坑),
|
||||||
|
# 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
|
||||||
|
for key in ('tools', 'security', 'speech'):
|
||||||
|
if key not in patch:
|
||||||
|
continue
|
||||||
|
if isinstance(patch[key], dict):
|
||||||
|
nxt[key] = {**(current.get(key) or {}), **patch[key]}
|
||||||
|
else:
|
||||||
|
nxt[key] = current.get(key) or {}
|
||||||
|
print(f'[config] 补丁里的 {key} 不是对象({type(patch[key]).__name__}),已忽略', file=sys.stderr, flush=True)
|
||||||
|
if patch.get('apiKey') == '••••••••':
|
||||||
|
nxt['apiKey'] = current.get('apiKey', '')
|
||||||
|
# ★ 掩码回写保护:界面读到的是 '••••••••',用户不改语音设置直接保存时,
|
||||||
|
# 这个掩码会跟着 patch 回来。不处理的话真 Token 就被这八个点覆盖了,
|
||||||
|
# 下次朗读直接报"缺 Token" —— 这类"看一眼就坏"的 bug 最难查。
|
||||||
|
speech_next = nxt.get('speech')
|
||||||
|
if isinstance(speech_next, dict):
|
||||||
|
speech_cur = current.get('speech') or {}
|
||||||
|
for secret in ('volcToken', 'openaiApiKey'):
|
||||||
|
if speech_next.get(secret) == '••••••••':
|
||||||
|
speech_next[secret] = speech_cur.get(secret, '')
|
||||||
|
# ★ 语音里"空字符串就等于坏掉"的字段,同样不许被空值覆盖。
|
||||||
|
# 引擎名一空,界面上一张卡片都不会高亮(看起来就是"设置被清空了");
|
||||||
|
# 模型名一空,朗读/识别会直接调不通。
|
||||||
|
# 注意 ttsVoice / volcAppId / sttLanguage 不在此列 —— 它们留空是合理需求
|
||||||
|
# (留空 = 用引擎默认音色 / 还没填)。
|
||||||
|
for key in ('ttsEngine', 'sttEngine', 'sttModel', 'ttsModel', 'volcCluster', 'volcEncoding'):
|
||||||
|
if key in speech_next and isinstance(speech_next[key], str) and not speech_next[key].strip():
|
||||||
|
speech_next[key] = speech_cur.get(key) or DEFAULT_SETTINGS['speech'].get(key, '')
|
||||||
|
nxt['speech'] = speech_next
|
||||||
|
nxt.pop('hasApiKey', None)
|
||||||
|
_write_json(paths.get().settings_file, nxt)
|
||||||
|
return nxt
|
||||||
|
|
||||||
|
|
||||||
|
def provider_info(settings: dict) -> dict:
|
||||||
|
"""当前提供商的完整信息(预设 + 生效的 baseUrl/model)。"""
|
||||||
|
preset = _preset_of(settings)
|
||||||
|
return {**preset, 'baseUrl': settings.get('baseUrl') or preset['baseUrl'],
|
||||||
|
'model': settings.get('model') or preset['defaultModel']}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 会话
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def _rid_conv() -> str:
|
||||||
|
# 和 Node 的 `c_${Date.now().toString(36)}_${random}` 同风格;不必逐字符相同
|
||||||
|
return f'c_{_ts36()}_{_rand36(5)}'
|
||||||
|
|
||||||
|
|
||||||
|
def _ts36() -> str:
|
||||||
|
return _base36(int(datetime.now(timezone.utc).timestamp() * 1000))
|
||||||
|
|
||||||
|
|
||||||
|
def _base36(num: int) -> str:
|
||||||
|
digits = '0123456789abcdefghijklmnopqrstuvwxyz'
|
||||||
|
if num == 0:
|
||||||
|
return '0'
|
||||||
|
out = ''
|
||||||
|
while num:
|
||||||
|
num, rem = divmod(num, 36)
|
||||||
|
out = digits[rem] + out
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _rand36(length: int) -> str:
|
||||||
|
import random
|
||||||
|
|
||||||
|
return ''.join(random.choice('0123456789abcdefghijklmnopqrstuvwxyz') for _ in range(length))
|
||||||
|
|
||||||
|
|
||||||
|
def _fresh_state() -> dict:
|
||||||
|
stamp = now_iso()
|
||||||
|
return {
|
||||||
|
'conversations': [
|
||||||
|
{
|
||||||
|
'id': 'c_main',
|
||||||
|
'title': '主对话',
|
||||||
|
'agentId': 'a_doubao',
|
||||||
|
'pinned': True,
|
||||||
|
'createdAt': stamp,
|
||||||
|
'updatedAt': stamp,
|
||||||
|
'messages': [],
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _load_conversations() -> dict:
|
||||||
|
global _conv_state
|
||||||
|
with _lock:
|
||||||
|
if _conv_state is None:
|
||||||
|
state = _read_json(paths.get().conversations_file)
|
||||||
|
if state is None:
|
||||||
|
state = _fresh_state()
|
||||||
|
if not isinstance(state.get('conversations'), list) or not state['conversations']:
|
||||||
|
state = _fresh_state()
|
||||||
|
_conv_state = state
|
||||||
|
return _conv_state
|
||||||
|
|
||||||
|
|
||||||
|
def _persist_conversations() -> None:
|
||||||
|
_write_json(paths.get().conversations_file, _load_conversations())
|
||||||
|
|
||||||
|
|
||||||
|
def _preview_of(messages: list) -> str:
|
||||||
|
"""列表预览:取最后一条有内容的消息,用户消息加"我:"前缀。"""
|
||||||
|
for msg in reversed(messages or []):
|
||||||
|
content = msg.get('content')
|
||||||
|
if not content:
|
||||||
|
continue
|
||||||
|
text = re.sub(r'\s+', ' ', _as_text(content)).strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
tag = '我:' if msg.get('role') == 'user' else ''
|
||||||
|
return f'{tag}{text[:30]}…' if len(text) > 30 else f'{tag}{text}'
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def list_conversations() -> list:
|
||||||
|
"""列表:带最后一条消息预览,置顶优先 + 更新时间倒序。"""
|
||||||
|
items = list(_load_conversations()['conversations'])
|
||||||
|
items.sort(
|
||||||
|
key=lambda c: (1 if c.get('pinned') else 0, _as_text(c.get('updatedAt'))),
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
out = []
|
||||||
|
for conv in items:
|
||||||
|
messages = conv.get('messages') or []
|
||||||
|
meta = {k: v for k, v in conv.items() if k != 'messages'}
|
||||||
|
meta['messageCount'] = len(messages)
|
||||||
|
meta['preview'] = _preview_of(messages)
|
||||||
|
out.append(meta)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def get_conversation(conv_id: str):
|
||||||
|
for conv in _load_conversations()['conversations']:
|
||||||
|
if conv.get('id') == conv_id:
|
||||||
|
return conv
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||||
|
item = {
|
||||||
|
'id': _rid_conv(),
|
||||||
|
'title': title,
|
||||||
|
'agentId': agent_id or '',
|
||||||
|
'pinned': False,
|
||||||
|
'createdAt': now_iso(),
|
||||||
|
'updatedAt': now_iso(),
|
||||||
|
'messages': [],
|
||||||
|
}
|
||||||
|
with _lock:
|
||||||
|
_load_conversations()['conversations'].insert(0, item)
|
||||||
|
_persist_conversations()
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def update_conversation(conv_id: str, patch: dict):
|
||||||
|
item = get_conversation(conv_id)
|
||||||
|
if not item:
|
||||||
|
return None
|
||||||
|
with _lock:
|
||||||
|
if isinstance(patch, dict):
|
||||||
|
item.update(patch)
|
||||||
|
item['updatedAt'] = now_iso()
|
||||||
|
_persist_conversations()
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def delete_conversation(conv_id: str) -> bool:
|
||||||
|
with _lock:
|
||||||
|
state = _load_conversations()
|
||||||
|
index = next((i for i, c in enumerate(state['conversations']) if c.get('id') == conv_id), -1)
|
||||||
|
if index < 0:
|
||||||
|
return False
|
||||||
|
state['conversations'].pop(index)
|
||||||
|
# 删光了就把"主对话"补回来,界面上不能出现空列表
|
||||||
|
if not state['conversations']:
|
||||||
|
state['conversations'].extend(_fresh_state()['conversations'])
|
||||||
|
_persist_conversations()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def append_messages(conv_id: str, messages: list):
|
||||||
|
item = get_conversation(conv_id)
|
||||||
|
if not item:
|
||||||
|
return None
|
||||||
|
with _lock:
|
||||||
|
item.setdefault('messages', []).extend(messages)
|
||||||
|
item['updatedAt'] = now_iso()
|
||||||
|
_persist_conversations()
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def auto_title(conv_id: str, text: str) -> None:
|
||||||
|
"""用首条用户消息自动起标题(只改还没起过名的会话)。"""
|
||||||
|
item = get_conversation(conv_id)
|
||||||
|
if not item or item.get('title') not in ('新对话', '主对话'):
|
||||||
|
return
|
||||||
|
title = re.sub(r'\s+', ' ', _as_text(text)).strip()[:18]
|
||||||
|
if title:
|
||||||
|
update_conversation(conv_id, {'title': title})
|
||||||
|
|
||||||
|
|
||||||
|
def store_file_path() -> str:
|
||||||
|
return paths.get().conversations_file
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 智能体
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def _rid_agent() -> str:
|
||||||
|
return f'a_{_ts36()}_{_rand36(4)}'
|
||||||
|
|
||||||
|
|
||||||
|
def list_agents() -> list:
|
||||||
|
file_path = paths.get().agents_file
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||||||
|
return [dict(a) for a in DEFAULT_AGENTS]
|
||||||
|
data = _read_json(file_path)
|
||||||
|
if not isinstance(data, dict) or not isinstance(data.get('agents'), list) or not data['agents']:
|
||||||
|
print('[store] agents.json 损坏,重建内置智能体', file=sys.stderr)
|
||||||
|
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||||||
|
return [dict(a) for a in DEFAULT_AGENTS]
|
||||||
|
return data['agents']
|
||||||
|
|
||||||
|
|
||||||
|
def get_agent(agent_id: str | None):
|
||||||
|
if not agent_id:
|
||||||
|
return None
|
||||||
|
for agent in list_agents():
|
||||||
|
if agent.get('id') == agent_id:
|
||||||
|
return agent
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def create_agent(payload: dict) -> dict:
|
||||||
|
payload = payload or {}
|
||||||
|
state = {'agents': list_agents()}
|
||||||
|
agent = {
|
||||||
|
'id': _rid_agent(),
|
||||||
|
'name': _as_text(payload.get('name') or '新智能体')[:24],
|
||||||
|
'avatar': payload.get('avatar') or 'custom',
|
||||||
|
'tagline': _as_text(payload.get('tagline'))[:40],
|
||||||
|
'systemPrompt': _as_text(payload.get('systemPrompt')),
|
||||||
|
'builtin': False,
|
||||||
|
'createdAt': now_iso(),
|
||||||
|
}
|
||||||
|
state['agents'].append(agent)
|
||||||
|
_write_json(paths.get().agents_file, state)
|
||||||
|
return agent
|
||||||
|
|
||||||
|
|
||||||
|
def update_agent(agent_id: str, patch: dict):
|
||||||
|
state = {'agents': list_agents()}
|
||||||
|
agent = next((a for a in state['agents'] if a.get('id') == agent_id), None)
|
||||||
|
if not agent:
|
||||||
|
return None
|
||||||
|
patch = patch or {}
|
||||||
|
for key in ('name', 'avatar', 'tagline', 'systemPrompt'):
|
||||||
|
if patch.get(key) is not None:
|
||||||
|
agent[key] = patch[key]
|
||||||
|
_write_json(paths.get().agents_file, state)
|
||||||
|
return agent
|
||||||
|
|
||||||
|
|
||||||
|
def delete_agent(agent_id: str) -> bool:
|
||||||
|
state = {'agents': list_agents()}
|
||||||
|
index = next((i for i, a in enumerate(state['agents']) if a.get('id') == agent_id), -1)
|
||||||
|
if index < 0:
|
||||||
|
return False
|
||||||
|
state['agents'].pop(index)
|
||||||
|
_write_json(paths.get().agents_file, state)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def reset_runtime_cache() -> None:
|
||||||
|
"""测试/热重载用:丢掉会话内存缓存(设置本来就不缓存)。"""
|
||||||
|
global _conv_state, _dotenv_loaded
|
||||||
|
with _lock:
|
||||||
|
_conv_state = None
|
||||||
|
_dotenv_loaded = False
|
||||||
341
android/kernel/tools_runtime.py
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
"""
|
||||||
|
工具运行时:发现、过滤、执行。
|
||||||
|
|
||||||
|
对应 Node 版 server/src/python-tools.mjs + agent.mjs 里的工具部分。
|
||||||
|
|
||||||
|
★ 最重要的安卓取舍:用 importlib 直接 import 工具模块,绝不用 subprocess 调 python。
|
||||||
|
|
||||||
|
Node 版是 `python tool.py --spec` / `python tool.py --input args.json`,
|
||||||
|
因为桌面上一定有解释器。安卓(Chaquopy)里**没有独立的 python 可执行文件**,
|
||||||
|
解释器只存在于本进程内,spawn('python') 一定 ENOENT。
|
||||||
|
所以这里改成:
|
||||||
|
importlib.util.spec_from_file_location(...) → exec_module
|
||||||
|
→ 取模块的 TOOL(工具描述)和 run(执行函数)
|
||||||
|
代价是工具代码和内核同进程(崩溃会一起死、全局状态会互相影响),
|
||||||
|
但对"安卓上必须能跑"这个目标,这是唯一可行的路。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
import mcp_client
|
||||||
|
import paths
|
||||||
|
from builtin_tools import BUILTIN_TOOLS, run_with_timeout
|
||||||
|
|
||||||
|
# 文件工具的缓存:path -> {'mtime':..., 'spec':..., 'error':...}
|
||||||
|
_spec_cache: dict = {}
|
||||||
|
_cache_lock = threading.Lock()
|
||||||
|
# 已经 import 过的模块名(重载时要先从 sys.modules 里摘掉)
|
||||||
|
_loaded_modules: dict = {}
|
||||||
|
|
||||||
|
TOOL_TIMEOUT_S = 60
|
||||||
|
BUILTIN_FILE_LABEL = '<内置>'
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 目录与文件
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def tools_dir() -> str:
|
||||||
|
"""
|
||||||
|
工具目录:settings.toolsDir 优先(安卓端指到手机上的目录),
|
||||||
|
否则用内置 tools/(--tools-dir / DOUBAO_TOOLS 指定)。
|
||||||
|
"""
|
||||||
|
import store # 局部导入:store 不依赖本模块,但放在顶部会让 import 顺序更难读
|
||||||
|
|
||||||
|
custom = (store.read_settings() or {}).get('toolsDir')
|
||||||
|
if custom and os.path.isdir(custom):
|
||||||
|
return os.path.abspath(custom)
|
||||||
|
return paths.get().tools_dir
|
||||||
|
|
||||||
|
|
||||||
|
def python_files() -> list:
|
||||||
|
folder = tools_dir()
|
||||||
|
if not os.path.isdir(folder):
|
||||||
|
return []
|
||||||
|
# 排序:Node 那边 readdir 在 NTFS 上正好是字典序,这里显式排序保证工具顺序稳定
|
||||||
|
names = sorted(
|
||||||
|
n for n in os.listdir(folder)
|
||||||
|
if n.endswith('.py') and not n.startswith('_')
|
||||||
|
)
|
||||||
|
return [os.path.join(folder, n) for n in names]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 导入工具模块
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def _import_tool_module(file_path: str, folder: str):
|
||||||
|
"""
|
||||||
|
用 importlib 按文件路径导入工具模块。
|
||||||
|
|
||||||
|
要点:
|
||||||
|
* 模块名带 `_doubao_tool_` 前缀 + 文件名哈希,避免和内核自己的模块重名;
|
||||||
|
* 把工具目录插进 sys.path —— tools/*.py 里有 `from _protocol import serve`,
|
||||||
|
它们自己也会 insert 一次,但我们先插好更稳(顺序:我们自己在前);
|
||||||
|
* 重新 import 前先 sys.modules.pop,否则拿到的是改了文件也没更新的旧模块。
|
||||||
|
"""
|
||||||
|
stem = os.path.splitext(os.path.basename(file_path))[0]
|
||||||
|
safe_stem = re.sub(r'\W', '_', stem)
|
||||||
|
mod_name = f'_doubao_tool_{safe_stem}_{abs(hash(os.path.abspath(file_path))) % 100000}'
|
||||||
|
old = _loaded_modules.get(file_path)
|
||||||
|
if old and old in sys.modules:
|
||||||
|
sys.modules.pop(old, None)
|
||||||
|
if folder and folder not in sys.path:
|
||||||
|
sys.path.insert(0, folder)
|
||||||
|
spec = importlib.util.spec_from_file_location(mod_name, file_path)
|
||||||
|
if spec is None or spec.loader is None:
|
||||||
|
raise ImportError(f'无法为 {file_path} 建立模块 spec')
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules[mod_name] = module
|
||||||
|
try:
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
except BaseException:
|
||||||
|
sys.modules.pop(mod_name, None)
|
||||||
|
raise
|
||||||
|
_loaded_modules[file_path] = mod_name
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
def _spec_from_module(module, file_path: str) -> dict:
|
||||||
|
tool = getattr(module, 'TOOL', None)
|
||||||
|
if not isinstance(tool, dict) or not tool.get('name'):
|
||||||
|
raise ValueError('模块里没有合法的 TOOL(需要 {name, description, parameters})')
|
||||||
|
if not callable(getattr(module, 'run', None)):
|
||||||
|
raise ValueError('模块里没有可调用的 run(args)')
|
||||||
|
spec = dict(tool)
|
||||||
|
spec.setdefault('description', spec['name'])
|
||||||
|
spec.setdefault('parameters', {'type': 'object', 'properties': {}})
|
||||||
|
spec['file'] = os.path.basename(file_path)
|
||||||
|
spec['_path'] = file_path
|
||||||
|
return spec
|
||||||
|
|
||||||
|
|
||||||
|
def _builtin_spec(name: str, file_path: str = '') -> dict:
|
||||||
|
"""
|
||||||
|
内置工具的工具描述。
|
||||||
|
|
||||||
|
file 字段:如果工具目录里存在同名文件(例如 tools/shell.py),就沿用它的文件名,
|
||||||
|
这样 /api/state 的 python.tools 和 Node 版逐字段一致(前端 Skills 页显示的就是它);
|
||||||
|
找不到同名文件时才写 <内置>。另外附一个 builtin=true 供调试识别(前端不读它)。
|
||||||
|
"""
|
||||||
|
entry = BUILTIN_TOOLS[name]
|
||||||
|
spec = dict(entry['spec'])
|
||||||
|
spec['file'] = os.path.basename(file_path) if file_path else BUILTIN_FILE_LABEL
|
||||||
|
spec['builtin'] = True
|
||||||
|
spec['_path'] = ''
|
||||||
|
spec['_builtin'] = True
|
||||||
|
return spec
|
||||||
|
|
||||||
|
|
||||||
|
def discover_python_tools(force: bool = False) -> dict:
|
||||||
|
"""
|
||||||
|
扫描并加载全部 Python 工具。
|
||||||
|
|
||||||
|
返回 {'tools': [...], 'errors': [{'file','error'}], 'python': {'bin','prefix'}|None}
|
||||||
|
语义与 Node 版 discoverPythonTools 一致;区别是用 import 代替子进程 --spec。
|
||||||
|
"""
|
||||||
|
folder = tools_dir()
|
||||||
|
files = python_files()
|
||||||
|
tools, errors = [], []
|
||||||
|
emitted_builtins = set()
|
||||||
|
|
||||||
|
for file_path in files:
|
||||||
|
try:
|
||||||
|
mtime = os.path.getmtime(file_path)
|
||||||
|
except OSError as exc:
|
||||||
|
errors.append({'file': os.path.basename(file_path), 'error': f'无法读取文件:{exc}'})
|
||||||
|
continue
|
||||||
|
with _cache_lock:
|
||||||
|
cached = _spec_cache.get(file_path)
|
||||||
|
if not force and cached and cached.get('mtime') == mtime:
|
||||||
|
spec, error, module = cached.get('spec'), cached.get('error'), cached.get('module')
|
||||||
|
else:
|
||||||
|
spec, error, module = None, None, None
|
||||||
|
try:
|
||||||
|
module = _import_tool_module(file_path, folder)
|
||||||
|
spec = _spec_from_module(module, file_path)
|
||||||
|
except BaseException as exc: # noqa: BLE001 - 单个工具坏掉不能拖垮内核
|
||||||
|
module = None
|
||||||
|
error = f'{type(exc).__name__}: {exc}'
|
||||||
|
with _cache_lock:
|
||||||
|
# 缓存里同时留着模块对象:执行时不必再 import 一遍
|
||||||
|
_spec_cache[file_path] = {'mtime': mtime, 'spec': spec, 'error': error, 'module': module}
|
||||||
|
|
||||||
|
if error:
|
||||||
|
errors.append({'file': os.path.basename(file_path), 'error': str(error)[:400]})
|
||||||
|
continue
|
||||||
|
if not spec:
|
||||||
|
continue
|
||||||
|
name = spec.get('name')
|
||||||
|
# 内置工具优先:同名文件工具被替换(安卓上 shell/python_run 必须走进程内实现),
|
||||||
|
# 但 file 字段仍沿用同名文件,保持和 Node 版一致的用户可见信息
|
||||||
|
if name in BUILTIN_TOOLS:
|
||||||
|
tools.append(_builtin_spec(name, file_path))
|
||||||
|
emitted_builtins.add(name)
|
||||||
|
else:
|
||||||
|
tools.append(spec)
|
||||||
|
|
||||||
|
# 文件目录里没有、但内置提供的工具(比如用户把 tools/ 指到空目录)
|
||||||
|
for name in BUILTIN_TOOLS:
|
||||||
|
if name not in emitted_builtins:
|
||||||
|
tools.append(_builtin_spec(name))
|
||||||
|
|
||||||
|
return {
|
||||||
|
'tools': tools,
|
||||||
|
'errors': errors,
|
||||||
|
'python': {'bin': sys.executable or '<进程内>', 'prefix': []},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _find_entry(name: str):
|
||||||
|
"""按名字找工具(内置优先),返回 (spec, module);找不到返回 (None, None)。"""
|
||||||
|
if name in BUILTIN_TOOLS:
|
||||||
|
file_path = ''
|
||||||
|
for candidate in python_files():
|
||||||
|
if os.path.splitext(os.path.basename(candidate))[0] == name:
|
||||||
|
file_path = candidate
|
||||||
|
break
|
||||||
|
return _builtin_spec(name, file_path), None
|
||||||
|
found = discover_python_tools()
|
||||||
|
for spec in found['tools']:
|
||||||
|
if spec.get('name') == name:
|
||||||
|
file_path = spec.get('_path') or ''
|
||||||
|
with _cache_lock:
|
||||||
|
module = (_spec_cache.get(file_path) or {}).get('module')
|
||||||
|
if module is None and file_path:
|
||||||
|
# 缓存里没模块(进程重启 / force 刷新过),重新 import 一次
|
||||||
|
module = _import_tool_module(file_path, os.path.dirname(file_path))
|
||||||
|
return spec, module
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 执行
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def run_python_tool(name: str, args: dict) -> dict:
|
||||||
|
"""
|
||||||
|
执行一个进程内工具,返回 {'ok':bool, 'result':..., 'error':...}。
|
||||||
|
结构与 Node 版 runPythonTool 的返回值保持兼容。
|
||||||
|
"""
|
||||||
|
spec, module = _find_entry(name)
|
||||||
|
if not spec:
|
||||||
|
raise RuntimeError(f'没有名为 {name} 的 Python 工具')
|
||||||
|
|
||||||
|
if spec.get('_builtin'):
|
||||||
|
runner = BUILTIN_TOOLS[name]['run']
|
||||||
|
else:
|
||||||
|
if module is None:
|
||||||
|
raise RuntimeError(f'工具 {name} 的模块已失效,请重新加载')
|
||||||
|
runner = getattr(module, 'run')
|
||||||
|
|
||||||
|
payload = args if isinstance(args, dict) else {}
|
||||||
|
try:
|
||||||
|
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
|
||||||
|
outcome = run_with_timeout(lambda: runner(payload), TOOL_TIMEOUT_S)
|
||||||
|
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||||
|
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
||||||
|
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
|
||||||
|
return {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||||
|
if outcome is None:
|
||||||
|
return {'ok': False, 'error': f'工具执行超时({TOOL_TIMEOUT_S}s)'}
|
||||||
|
result = outcome
|
||||||
|
# 工具可以像 _protocol 那样返回 {"ok":..,"result":..},也可以直接返回业务结果
|
||||||
|
if isinstance(result, dict) and 'ok' in result:
|
||||||
|
return {
|
||||||
|
'ok': bool(result.get('ok')),
|
||||||
|
'result': result.get('result'),
|
||||||
|
'error': result.get('error'),
|
||||||
|
}
|
||||||
|
return {'ok': True, 'result': result}
|
||||||
|
|
||||||
|
|
||||||
|
def to_openai_tool(spec: dict) -> dict:
|
||||||
|
"""转成 OpenAI tools 定义(与 Node 版 toOpenAITool 一致)。"""
|
||||||
|
return {
|
||||||
|
'type': 'function',
|
||||||
|
'function': {
|
||||||
|
'name': spec.get('name'),
|
||||||
|
'description': spec.get('description') or spec.get('name'),
|
||||||
|
'parameters': spec.get('parameters') or {'type': 'object', 'properties': {}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def public_spec(spec: dict) -> dict:
|
||||||
|
"""去掉内部字段(下划线开头),得到能直接塞进 JSON 响应的工具描述。"""
|
||||||
|
return {k: v for k, v in spec.items() if not k.startswith('_')}
|
||||||
|
|
||||||
|
|
||||||
|
def dump_specs_json(specs: list) -> str:
|
||||||
|
"""调试用:把工具描述打成 JSON(避免直接 print 中文在窄编码终端炸掉)。"""
|
||||||
|
return json.dumps([public_spec(s) for s in specs], ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 汇总 / 安全模式
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def list_all_tools(settings: dict) -> dict:
|
||||||
|
"""汇总当前可用的全部工具(Python + MCP),与 Node 版 listAllTools 对齐。"""
|
||||||
|
out = {'python': [], 'mcp': [], 'errors': [], 'pythonInfo': None}
|
||||||
|
if (settings.get('tools') or {}).get('python', True) is not False:
|
||||||
|
res = discover_python_tools()
|
||||||
|
out['python'] = res['tools']
|
||||||
|
out['errors'] = res['errors']
|
||||||
|
out['pythonInfo'] = res['python']
|
||||||
|
if (settings.get('tools') or {}).get('mcp', True) is not False:
|
||||||
|
out['mcp'] = mcp_client.mcp_tool_defs()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# 只读工具的名字特征,用来给"限制模式"生成一份保守的默认白名单
|
||||||
|
READONLY_NAME = re.compile(
|
||||||
|
r'^(read|list|get|search|open|find|fetch|show|describe|query|inspect|calc|now|web_fetch)',
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def suggest_allowlist(tool_names: list) -> list:
|
||||||
|
return [n for n in tool_names if READONLY_NAME.match((n.split('__') or [n])[-1] or n)]
|
||||||
|
|
||||||
|
|
||||||
|
def apply_security(defs: list, settings: dict) -> list:
|
||||||
|
"""按安全模式过滤工具定义(restricted 时只留白名单)。"""
|
||||||
|
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||||
|
if mode != 'restricted':
|
||||||
|
return defs
|
||||||
|
allow = set((settings.get('security') or {}).get('allow') or [])
|
||||||
|
return [d for d in defs if d.get('function', {}).get('name') in allow]
|
||||||
|
|
||||||
|
|
||||||
|
def build_tool_defs(settings: dict) -> list:
|
||||||
|
all_tools = list_all_tools(settings)
|
||||||
|
defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp'])
|
||||||
|
return apply_security(defs, settings)
|
||||||
|
|
||||||
|
|
||||||
|
def execute_tool(name: str, args: dict, settings: dict) -> dict:
|
||||||
|
"""
|
||||||
|
执行任意工具(Python 或 MCP)。
|
||||||
|
限制模式下即使模型硬编出工具名也不能执行(第二道拦截,与 Node 版一致)。
|
||||||
|
"""
|
||||||
|
if ((settings or {}).get('security') or {}).get('mode', 'open') == 'restricted':
|
||||||
|
allow = ((settings or {}).get('security') or {}).get('allow') or []
|
||||||
|
if name not in allow:
|
||||||
|
return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'}
|
||||||
|
if mcp_client.is_mcp_tool(name):
|
||||||
|
res = mcp_client.call_mcp_tool(name, args)
|
||||||
|
parts = []
|
||||||
|
for item in (res or {}).get('content') or []:
|
||||||
|
if item.get('type') == 'text':
|
||||||
|
parts.append(item.get('text') or '')
|
||||||
|
else:
|
||||||
|
parts.append(f"[{item.get('type')}]")
|
||||||
|
return {'ok': not (res or {}).get('isError'), 'result': '\n'.join(parts) or '(空结果)'}
|
||||||
|
return run_python_tool(name, args)
|
||||||
178
android/kernel/uploads.py
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
"""
|
||||||
|
附件:上传落盘、拖拽文件待取队列、以及"附件 → 模型输入"的转换。
|
||||||
|
|
||||||
|
对应 Node 版 server/src/uploads.mjs,字段完全一致:
|
||||||
|
{ id, name, size, mime, path, url, at }
|
||||||
|
|
||||||
|
安卓上的差异:
|
||||||
|
* 没有 Electron 的原生选文件钩子,选文件由 Kotlin 侧调用 /api/pick-file 时注入
|
||||||
|
(main.py 的 native hooks),默认返回"当前环境不支持原生选文件";
|
||||||
|
* 上传仍然走 base64(前端 FileReader → dataUrl),因为 WebView/Lynx 里拿不到真实路径。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
import paths
|
||||||
|
from store import _rand36, _ts36, now_iso # 复用同一套 id/时间风格
|
||||||
|
|
||||||
|
_pending = []
|
||||||
|
_pending_lock = threading.Lock()
|
||||||
|
|
||||||
|
IMAGE_EXT = {'.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp'}
|
||||||
|
TEXT_EXT = {
|
||||||
|
'.txt', '.md', '.markdown', '.json', '.csv', '.tsv', '.log', '.ini', '.toml', '.yml', '.yaml',
|
||||||
|
'.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.html', '.htm', '.css', '.scss',
|
||||||
|
'.xml', '.sql', '.sh', '.bat', '.ps1', '.java', '.c', '.h', '.cpp', '.cs', '.go', '.rs',
|
||||||
|
'.rb', '.php', '.swift', '.kt', '.lua', '.r', '.vue', '.svelte',
|
||||||
|
}
|
||||||
|
|
||||||
|
# 复制进 uploads 的上限;再大就只登记路径,不复制
|
||||||
|
COPY_LIMIT = 25 * 1024 * 1024
|
||||||
|
# 喂给模型的单张图片上限
|
||||||
|
VISION_LIMIT = 6 * 1024 * 1024
|
||||||
|
|
||||||
|
_MIME = {
|
||||||
|
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',
|
||||||
|
'.gif': 'image/gif', '.bmp': 'image/bmp', '.pdf': 'application/pdf',
|
||||||
|
'.json': 'application/json', '.md': 'text/markdown',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _rid() -> str:
|
||||||
|
return f'f_{_ts36()}_{_rand36(4)}'
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_name(name: str) -> str:
|
||||||
|
"""去掉路径分隔符和 Windows 非法字符,并只保留末尾 60 个字符(和 Node 一致)。"""
|
||||||
|
cleaned = re.sub(r'[\\/:*?"<>|]', '_', str(name or 'file'))
|
||||||
|
return cleaned[-60:]
|
||||||
|
|
||||||
|
|
||||||
|
def _ext_of(name: str) -> str:
|
||||||
|
return os.path.splitext(str(name or ''))[1].lower()
|
||||||
|
|
||||||
|
|
||||||
|
def is_image(name: str) -> bool:
|
||||||
|
return _ext_of(name) in IMAGE_EXT
|
||||||
|
|
||||||
|
|
||||||
|
def is_text(name: str) -> bool:
|
||||||
|
return _ext_of(name) in TEXT_EXT
|
||||||
|
|
||||||
|
|
||||||
|
def mime_of(name: str) -> str:
|
||||||
|
ext = _ext_of(name)
|
||||||
|
if ext in _MIME:
|
||||||
|
return _MIME[ext]
|
||||||
|
return 'text/plain' if is_text(name) else 'application/octet-stream'
|
||||||
|
|
||||||
|
|
||||||
|
def _meta(file_path: str, name: str, copy: bool = True) -> dict:
|
||||||
|
size = os.path.getsize(file_path)
|
||||||
|
stored_path = file_path
|
||||||
|
url = ''
|
||||||
|
if copy and size <= COPY_LIMIT:
|
||||||
|
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||||
|
with open(file_path, 'rb') as src, open(target, 'wb') as dst:
|
||||||
|
while True:
|
||||||
|
chunk = src.read(256 * 1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
dst.write(chunk)
|
||||||
|
stored_path = target
|
||||||
|
url = f'/uploads/{os.path.basename(target)}'
|
||||||
|
return {
|
||||||
|
'id': _rid(),
|
||||||
|
'name': str(name),
|
||||||
|
'size': size,
|
||||||
|
'mime': mime_of(name),
|
||||||
|
'path': stored_path,
|
||||||
|
'url': url,
|
||||||
|
'at': now_iso(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def save_upload(name: str, base64_data: str) -> dict:
|
||||||
|
"""浏览器上传:base64(dataUrl) → 落盘。"""
|
||||||
|
if not name or not base64_data:
|
||||||
|
raise ValueError('缺少 name 或 base64')
|
||||||
|
raw = re.sub(r'^data:[^,]+,', '', str(base64_data))
|
||||||
|
try:
|
||||||
|
# validate=False:和 Node 的 Buffer.from(x,'base64') 一样,忽略非法字符
|
||||||
|
buffer = base64.b64decode(raw, validate=False)
|
||||||
|
except (binascii.Error, ValueError) as exc:
|
||||||
|
raise ValueError(f'base64 解码失败:{exc}') from exc
|
||||||
|
if len(buffer) > COPY_LIMIT:
|
||||||
|
raise ValueError(f'文件超过 {COPY_LIMIT // 1024 // 1024}MB')
|
||||||
|
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||||
|
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||||
|
with open(target, 'wb') as fh:
|
||||||
|
fh.write(buffer)
|
||||||
|
return {
|
||||||
|
'id': _rid(),
|
||||||
|
'name': str(name),
|
||||||
|
'size': len(buffer),
|
||||||
|
'mime': mime_of(name),
|
||||||
|
'path': target,
|
||||||
|
'url': f'/uploads/{os.path.basename(target)}',
|
||||||
|
'at': now_iso(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def register_local_file(file_path: str) -> dict:
|
||||||
|
"""安卓/Kotlin 侧选完文件后登记(必要时复制进 uploads)。"""
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
raise ValueError(f'文件不存在:{file_path}')
|
||||||
|
return _meta(file_path, os.path.basename(file_path))
|
||||||
|
|
||||||
|
|
||||||
|
def add_pending(items: list) -> None:
|
||||||
|
with _pending_lock:
|
||||||
|
_pending.extend(items or [])
|
||||||
|
|
||||||
|
|
||||||
|
def take_pending() -> list:
|
||||||
|
"""取走待处理附件(取完即清空),Lynx 界面轮询这个接口挂输入框。"""
|
||||||
|
global _pending
|
||||||
|
with _pending_lock:
|
||||||
|
items = _pending
|
||||||
|
_pending = []
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def attachment_payload(attachment: dict) -> dict:
|
||||||
|
"""
|
||||||
|
把附件转成模型能吃的形式:图片走视觉格式(data URL),文本类内联正文。
|
||||||
|
返回 {text, images:[{url}]},与 Node 版 attachmentPayload 一致。
|
||||||
|
"""
|
||||||
|
out = {'text': '', 'images': []}
|
||||||
|
item = attachment or {}
|
||||||
|
file_path = item.get('path') or ''
|
||||||
|
if not file_path or not os.path.isfile(file_path):
|
||||||
|
out['text'] = f"【附件 {item.get('name') or '未知'} 已丢失】"
|
||||||
|
return out
|
||||||
|
size = os.path.getsize(file_path)
|
||||||
|
if is_image(item.get('name')) and size <= VISION_LIMIT:
|
||||||
|
with open(file_path, 'rb') as fh:
|
||||||
|
b64 = base64.b64encode(fh.read()).decode('ascii')
|
||||||
|
out['images'].append({'url': f"data:{item.get('mime')};base64,{b64}"})
|
||||||
|
out['text'] = f"【图片 {item.get('name')}】"
|
||||||
|
return out
|
||||||
|
if is_text(item.get('name')) or size < 64 * 1024:
|
||||||
|
body = ''
|
||||||
|
try:
|
||||||
|
with open(file_path, 'r', encoding='utf-8', errors='replace') as fh:
|
||||||
|
body = fh.read()
|
||||||
|
except OSError as exc:
|
||||||
|
print(f'[uploads] 读取 {file_path} 失败:{exc}', file=sys.stderr)
|
||||||
|
if body:
|
||||||
|
clipped = f'{body[:20000]}\n…(已截断,共 {len(body)} 字符)' if len(body) > 20000 else body
|
||||||
|
out['text'] = f"【文件 {item.get('name')}({size} 字节)】\n```\n{clipped}\n```"
|
||||||
|
return out
|
||||||
|
out['text'] = f"【附件 {item.get('name')}({size} 字节,二进制)本地路径:{file_path}】"
|
||||||
|
return out
|
||||||
18
android/settings.gradle.kts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = "DoubaoLynxClone"
|
||||||
|
include(":app")
|
||||||
1
app/.npmrc
Normal file
@@ -0,0 +1 @@
|
|||||||
|
registry=https://registry.npmjs.org/
|
||||||
27
app/lynx.config.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin';
|
||||||
|
import { defineConfig } from '@lynx-js/rspeedy';
|
||||||
|
import { pluginTypeCheck } from '@rsbuild/plugin-type-check';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [pluginReactLynx(), pluginTypeCheck()],
|
||||||
|
// web 环境用于在浏览器里跑(Lynx for Web),lynx 环境用于 LynxExplorer / 真机
|
||||||
|
environments: {
|
||||||
|
web: {},
|
||||||
|
lynx: {
|
||||||
|
output: {
|
||||||
|
// 原生端没有「URL 前缀」概念,data URI 也不渲染(实测),
|
||||||
|
// 所以把图片资源前缀指到 APK 的 assets:Fresco 的 LocalAssetFetchProducer 认这个 scheme。
|
||||||
|
assetPrefix: 'asset:///',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 3210,
|
||||||
|
},
|
||||||
|
output: {
|
||||||
|
filenameHash: false,
|
||||||
|
distPath: {
|
||||||
|
root: 'dist',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
6543
app/package-lock.json
generated
Normal file
25
app/package.json
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"name": "doubao-lynx-app",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"description": "豆包界面复刻 - ReactLynx (LynxJS) 客户端",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "rspeedy dev",
|
||||||
|
"build": "rspeedy build",
|
||||||
|
"preview": "rspeedy preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@lynx-js/react": "^0.126.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@lynx-js/react-rsbuild-plugin": "^0.20.3",
|
||||||
|
"@lynx-js/rspeedy": "^0.18.0",
|
||||||
|
"@lynx-js/types": "^4.3.0",
|
||||||
|
"@rsbuild/plugin-type-check": "^1.6.0",
|
||||||
|
"typescript": "^5.9.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
613
app/src/App.tsx
Normal file
@@ -0,0 +1,613 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from '@lynx-js/react';
|
||||||
|
|
||||||
|
import type { Agent, AppState, Attachment, ChatMessage, Security, StreamEvent } from './types.js';
|
||||||
|
import { api, streamChat } from './api.js';
|
||||||
|
import { cv } from './lynx-input.js';
|
||||||
|
import { ChatPage } from './pages/Chat.js';
|
||||||
|
import { Drawer } from './pages/Drawer.js';
|
||||||
|
import { ProfilePage } from './pages/Profile.js';
|
||||||
|
import { SettingsPage } from './pages/Settings.js';
|
||||||
|
import { SkillsPage } from './pages/Skills.js';
|
||||||
|
import { AgentsPage } from './pages/Agents.js';
|
||||||
|
import { ModelPicker, modelRowLabel } from './pages/ModelPicker.js';
|
||||||
|
import { TerminalPage } from './pages/Terminal.js';
|
||||||
|
import './app.css';
|
||||||
|
|
||||||
|
type PageName = 'chat' | 'profile' | 'settings' | 'skills' | 'agents' | 'terminal';
|
||||||
|
|
||||||
|
const PAGES: PageName[] = ['chat', 'profile', 'settings', 'skills', 'agents', 'terminal'];
|
||||||
|
|
||||||
|
/** 宿主页可以用 global-props 指定首屏,方便截图/演示:/index.html?page=drawer */
|
||||||
|
function bootPage(): { page: PageName; drawer: boolean } {
|
||||||
|
const lynxGlobal = (globalThis as unknown as { lynx?: { __globalProps?: { initialPage?: string } } }).lynx;
|
||||||
|
const wanted = lynxGlobal?.__globalProps?.initialPage;
|
||||||
|
if (wanted === 'drawer') return { page: 'chat', drawer: true };
|
||||||
|
if (wanted && (PAGES as string[]).includes(wanted)) return { page: wanted as PageName, drawer: false };
|
||||||
|
return { page: 'chat', drawer: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 给最后一条助手消息打补丁(流式输出用) */
|
||||||
|
function patchLastAssistant(list: ChatMessage[], fn: (msg: ChatMessage) => ChatMessage): ChatMessage[] {
|
||||||
|
const next = list.slice();
|
||||||
|
for (let i = next.length - 1; i >= 0; i -= 1) {
|
||||||
|
if (next[i].role === 'assistant') {
|
||||||
|
next[i] = fn(next[i]);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function App() {
|
||||||
|
const boot = bootPage();
|
||||||
|
const [state, setState] = useState<AppState | null>(null);
|
||||||
|
const [page, setPage] = useState<PageName>(boot.page);
|
||||||
|
const [drawerOpen, setDrawerOpen] = useState(boot.drawer);
|
||||||
|
/** 抽屉里「模型」那一栏点开的面板 */
|
||||||
|
const [modelPickerOpen, setModelPickerOpen] = useState(false);
|
||||||
|
const [activeId, setActiveId] = useState('c_main');
|
||||||
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||||
|
const [draft, setDraft] = useState('');
|
||||||
|
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||||
|
const [streaming, setStreaming] = useState(false);
|
||||||
|
const [memoryEnabled, setMemoryEnabled] = useState(true);
|
||||||
|
const [scrollAnchor, setScrollAnchor] = useState('');
|
||||||
|
const [scrollSignal, setScrollSignal] = useState(0);
|
||||||
|
const [bootError, setBootError] = useState('');
|
||||||
|
const [copyHint, setCopyHint] = useState('');
|
||||||
|
const [apiDraft, setApiDraft] = useState('');
|
||||||
|
/** 展开的思维链(按消息下标) */
|
||||||
|
const [openReasoning, setOpenReasoning] = useState<Record<number, boolean>>({});
|
||||||
|
const toggleReasoning = useCallback((index: number) => {
|
||||||
|
setOpenReasoning((prev) => ({ ...prev, [index]: !prev[index] }));
|
||||||
|
}, []);
|
||||||
|
/** 正在看「思考过程」的消息下标 */
|
||||||
|
const [thinkIndex, setThinkIndex] = useState<number | null>(null);
|
||||||
|
/** 正在朗读第几条;-1 = 没在念。用来把那一行的喇叭图标点亮 */
|
||||||
|
const [speakingIndex, setSpeakingIndex] = useState(-1);
|
||||||
|
const audioRef = useRef<{ pause: () => void } | null>(null);
|
||||||
|
/** shell 实际走哪条通道:termux / toybox / cmd / 未知 */
|
||||||
|
const [shellChannel, setShellChannel] = useState('');
|
||||||
|
|
||||||
|
/** 问内核:shell 现在实际走哪条通道(Termux / toybox / cmd / sh) */
|
||||||
|
const fallbackShellKind = state?.shellKind || 'sh';
|
||||||
|
const refreshShellChannel = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
// 直接跑一条最小命令看返回里的 via —— 比问"装没装 Termux"准,
|
||||||
|
// 因为装了不等于开了 allow-external-apps
|
||||||
|
const probe = await api.runTool('shell', { command: 'echo __doubao_probe__' });
|
||||||
|
const via = (probe.result as { via?: string } | undefined)?.via || '';
|
||||||
|
setShellChannel(via || fallbackShellKind);
|
||||||
|
} catch {
|
||||||
|
setShellChannel(fallbackShellKind);
|
||||||
|
}
|
||||||
|
}, [fallbackShellKind]);
|
||||||
|
|
||||||
|
// 必须先于下面那些 useCallback 计算出来:它们的依赖数组会在渲染期读它
|
||||||
|
const activeAgent = state
|
||||||
|
? (state.agents.find((a) => a.id === state.settings.activeAgentId) || state.agents[0] || null)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
/** 滚到底:每次 +1,scroll-top 用一个永远超过最大值的数就会被夹到底部 */
|
||||||
|
const pinBottom = useCallback(() => {
|
||||||
|
setScrollSignal((n) => n + 1);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const next = await api.state();
|
||||||
|
setState(next);
|
||||||
|
setBootError('');
|
||||||
|
return next;
|
||||||
|
} catch (err) {
|
||||||
|
setBootError((err as Error).message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
refresh();
|
||||||
|
}, [refresh]);
|
||||||
|
|
||||||
|
/** 宿主页拖拽进来的文件:轮询待接入队列 */
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.pendingUploads();
|
||||||
|
if (res.files && res.files.length) {
|
||||||
|
setAttachments((prev) => {
|
||||||
|
const known = new Set(prev.map((f) => f.id));
|
||||||
|
return [...prev, ...res.files.filter((f) => !known.has(f.id))];
|
||||||
|
});
|
||||||
|
setPage('chat');
|
||||||
|
pinBottom();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* 内核没起来就忽略 */
|
||||||
|
}
|
||||||
|
}, 1500);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [pinBottom]);
|
||||||
|
|
||||||
|
const showHint = useCallback((text: string) => {
|
||||||
|
setCopyHint(text);
|
||||||
|
setTimeout(() => setCopyHint(''), 1800);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const loadConversation = useCallback(async (id: string) => {
|
||||||
|
setActiveId(id);
|
||||||
|
setDrawerOpen(false);
|
||||||
|
setPage('chat');
|
||||||
|
try {
|
||||||
|
const { conversation } = await api.conversation(id);
|
||||||
|
setMessages(
|
||||||
|
(conversation.messages || []).map((m) => ({
|
||||||
|
role: m.role === 'user' ? 'user' : 'assistant',
|
||||||
|
content: m.content,
|
||||||
|
// 思维链要一起读回来,否则刷新后「思考过程」是空的
|
||||||
|
reasoning: (m as unknown as { reasoning?: string }).reasoning || '',
|
||||||
|
attachments: (m as unknown as { attachments?: Attachment[] }).attachments || [],
|
||||||
|
})) as ChatMessage[],
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
setMessages([]);
|
||||||
|
}
|
||||||
|
pinBottom();
|
||||||
|
}, [pinBottom]);
|
||||||
|
|
||||||
|
const newTopic = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const { conversation } = await api.createConversation('新对话');
|
||||||
|
setState((prev) => (prev ? { ...prev, conversations: [conversation, ...prev.conversations] } : prev));
|
||||||
|
setActiveId(conversation.id);
|
||||||
|
setMessages([]);
|
||||||
|
setAttachments([]);
|
||||||
|
setDrawerOpen(false);
|
||||||
|
setPage('chat');
|
||||||
|
pinBottom();
|
||||||
|
} catch {
|
||||||
|
/* 离线时也能继续用界面 */
|
||||||
|
}
|
||||||
|
}, [pinBottom]);
|
||||||
|
|
||||||
|
const deleteConversation = useCallback(async (conv: { id: string; title: string }) => {
|
||||||
|
try {
|
||||||
|
await api.deleteConversation(conv.id);
|
||||||
|
const next = await refresh();
|
||||||
|
if (conv.id === activeId) {
|
||||||
|
const fallback = next?.conversations?.[0];
|
||||||
|
if (fallback) await loadConversation(fallback.id);
|
||||||
|
}
|
||||||
|
showHint(`已删除「${conv.title}」`);
|
||||||
|
} catch (err) {
|
||||||
|
showHint(`删除失败:${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
}, [activeId, refresh, loadConversation, showHint]);
|
||||||
|
|
||||||
|
/** 真正发消息;regenerate 时复用同一段逻辑 */
|
||||||
|
const runChat = useCallback(async (text: string, files: Attachment[], history: ChatMessage[]) => {
|
||||||
|
setStreaming(true);
|
||||||
|
pinBottom();
|
||||||
|
try {
|
||||||
|
await streamChat(
|
||||||
|
{
|
||||||
|
conversationId: activeId,
|
||||||
|
message: text,
|
||||||
|
history: history.filter((m) => m.content).map((m) => ({ role: m.role, content: m.content })),
|
||||||
|
attachments: files,
|
||||||
|
agentId: activeAgent?.id,
|
||||||
|
},
|
||||||
|
(event: StreamEvent) => {
|
||||||
|
if (event.type === 'delta') {
|
||||||
|
const chunk = event.text;
|
||||||
|
setMessages((prev) => patchLastAssistant(prev, (m) => ({ ...m, content: m.content + chunk })));
|
||||||
|
} else if (event.type === 'reasoning') {
|
||||||
|
const chunk = event.text;
|
||||||
|
setMessages((prev) =>
|
||||||
|
patchLastAssistant(prev, (m) => ({ ...m, reasoning: (m.reasoning || '') + chunk }))
|
||||||
|
);
|
||||||
|
} else if (event.type === 'tool_call') {
|
||||||
|
setMessages((prev) =>
|
||||||
|
patchLastAssistant(prev, (m) => ({
|
||||||
|
...m,
|
||||||
|
toolTrace: [...(m.toolTrace || []), { id: event.id, name: event.name, args: event.args }],
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
} else if (event.type === 'tool_result') {
|
||||||
|
setMessages((prev) =>
|
||||||
|
patchLastAssistant(prev, (m) => ({
|
||||||
|
...m,
|
||||||
|
toolTrace: (m.toolTrace || []).map((t) =>
|
||||||
|
t.id === event.id ? { ...t, ok: event.ok, result: event.result } : t
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
} else if (event.type === 'error') {
|
||||||
|
// API 报错必须看得见:气泡里写原因,顶部再弹一条可操作的建议
|
||||||
|
const hint = event.hint ? `|${event.hint}` : '';
|
||||||
|
setMessages((prev) =>
|
||||||
|
patchLastAssistant(prev, (m) => ({
|
||||||
|
...m,
|
||||||
|
error: true,
|
||||||
|
content: m.content || `出错了:${event.message}${hint}`,
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
showHint(`出错了:${event.message}${hint}`);
|
||||||
|
} else if (event.type === 'saved') {
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
pinBottom();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
const message = (err as Error).message || String(err);
|
||||||
|
setMessages((prev) =>
|
||||||
|
patchLastAssistant(prev, (m) => ({
|
||||||
|
...m,
|
||||||
|
error: true,
|
||||||
|
content: m.content || `连不上内核:${message}`,
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
showHint(`连不上内核:${message}`);
|
||||||
|
} finally {
|
||||||
|
setStreaming(false);
|
||||||
|
// 流式结束后再钉一次底部,否则操作栏会停在可视区外
|
||||||
|
pinBottom();
|
||||||
|
}
|
||||||
|
}, [activeId, refresh, activeAgent, pinBottom, showHint]);
|
||||||
|
|
||||||
|
const send = useCallback(async () => {
|
||||||
|
const text = draft.trim();
|
||||||
|
if ((!text && attachments.length === 0) || streaming) return;
|
||||||
|
const files = attachments;
|
||||||
|
const history = messages;
|
||||||
|
|
||||||
|
setDraft('');
|
||||||
|
setAttachments([]);
|
||||||
|
setMessages((prev) => [
|
||||||
|
...prev,
|
||||||
|
{ role: 'user', content: text || `(发送了 ${files.length} 个附件)`, attachments: files },
|
||||||
|
{ role: 'assistant', content: '' },
|
||||||
|
]);
|
||||||
|
|
||||||
|
await runChat(text, files, history);
|
||||||
|
}, [draft, attachments, streaming, messages, runChat]);
|
||||||
|
|
||||||
|
/** 重新生成:撤掉最后一条回答,用同样的输入再跑一次 */
|
||||||
|
const regenerate = useCallback(async () => {
|
||||||
|
if (streaming) return;
|
||||||
|
const lastUserIndex = [...messages].reverse().findIndex((m) => m.role === 'user');
|
||||||
|
if (lastUserIndex < 0) return;
|
||||||
|
const index = messages.length - 1 - lastUserIndex;
|
||||||
|
const userMsg = messages[index];
|
||||||
|
const history = messages.slice(0, index);
|
||||||
|
|
||||||
|
setMessages([...history, userMsg, { role: 'assistant', content: '' }]);
|
||||||
|
await runChat(userMsg.content, userMsg.attachments || [], history);
|
||||||
|
}, [messages, streaming, runChat]);
|
||||||
|
|
||||||
|
const feedback = useCallback((index: number, value: 'up' | 'down') => {
|
||||||
|
setMessages((prev) =>
|
||||||
|
prev.map((msg, i) => (i === index ? { ...msg, feedback: msg.feedback === value ? null : value } : msg))
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const copy = useCallback(async (text: string) => { try {
|
||||||
|
const nav = globalThis as unknown as { navigator?: { clipboard?: { writeText?: (t: string) => Promise<void> } } };
|
||||||
|
if (nav.navigator?.clipboard?.writeText) {
|
||||||
|
await nav.navigator.clipboard.writeText(text);
|
||||||
|
} else {
|
||||||
|
await api.clipboard(text);
|
||||||
|
}
|
||||||
|
showHint('已复制');
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
await api.clipboard(text);
|
||||||
|
showHint('已复制');
|
||||||
|
} catch {
|
||||||
|
showHint('复制失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [showHint]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 朗读。
|
||||||
|
*
|
||||||
|
* 两条路:内核说 engine='system' 就用浏览器自带的 speechSynthesis(不联网);
|
||||||
|
* 否则内核已经把音频合成好了,base64 直接塞进 data URL 交给 Audio 播。
|
||||||
|
*
|
||||||
|
* 为什么每次都 new Audio:data URL 是一次性的,复用同一个元素在第二次播时
|
||||||
|
* 有些浏览器会不触发 loadeddata;新建一个最省心,代价只是几个对象。
|
||||||
|
*/
|
||||||
|
const speak = useCallback(async (text: string, index: number) => {
|
||||||
|
stopSpeaking();
|
||||||
|
setSpeakingIndex(index);
|
||||||
|
try {
|
||||||
|
const res = await api.speak(text);
|
||||||
|
if (!res.ok) {
|
||||||
|
showHint(`朗读失败:${res.error || '未知原因'}`);
|
||||||
|
setSpeakingIndex(-1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const g = globalThis as unknown as {
|
||||||
|
speechSynthesis?: { speak: (u: unknown) => void; cancel: () => void };
|
||||||
|
SpeechSynthesisUtterance?: new (t: string) => { lang: string; onend: () => void; onerror: () => void };
|
||||||
|
Audio?: new (src: string) => {
|
||||||
|
play: () => Promise<void>;
|
||||||
|
pause: () => void;
|
||||||
|
onended: () => void;
|
||||||
|
onerror: () => void;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
if (res.engine === 'system' || !res.audio) {
|
||||||
|
if (!g.speechSynthesis || !g.SpeechSynthesisUtterance) {
|
||||||
|
showHint('这个环境没有系统朗读,请在设置里选云端音色');
|
||||||
|
setSpeakingIndex(-1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const u = new g.SpeechSynthesisUtterance(text);
|
||||||
|
u.lang = 'zh-CN';
|
||||||
|
u.onend = () => setSpeakingIndex(-1);
|
||||||
|
u.onerror = () => setSpeakingIndex(-1);
|
||||||
|
g.speechSynthesis.speak(u);
|
||||||
|
} else {
|
||||||
|
if (!g.Audio) {
|
||||||
|
showHint('这个环境不能播放音频');
|
||||||
|
setSpeakingIndex(-1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const audio = new g.Audio(`data:${res.mime || 'audio/mpeg'};base64,${res.audio}`);
|
||||||
|
audioRef.current = audio;
|
||||||
|
audio.onended = () => setSpeakingIndex(-1);
|
||||||
|
audio.onerror = () => {
|
||||||
|
showHint('音频播放失败(格式可能不被支持)');
|
||||||
|
setSpeakingIndex(-1);
|
||||||
|
};
|
||||||
|
await audio.play();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showHint(`朗读失败:${(err as Error).message}`);
|
||||||
|
setSpeakingIndex(-1);
|
||||||
|
}
|
||||||
|
}, [showHint]);
|
||||||
|
|
||||||
|
const stopSpeaking = useCallback(() => {
|
||||||
|
const g = globalThis as unknown as { speechSynthesis?: { cancel: () => void } };
|
||||||
|
try {
|
||||||
|
g.speechSynthesis?.cancel();
|
||||||
|
audioRef.current?.pause();
|
||||||
|
} catch {
|
||||||
|
/* 停不掉也无所谓,下面会把状态复位 */
|
||||||
|
}
|
||||||
|
audioRef.current = null;
|
||||||
|
setSpeakingIndex(-1);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/** 选文件:桌面版走原生对话框,浏览器/手机端提示拖拽或走宿主页 */
|
||||||
|
const pickFile = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.pickFile();
|
||||||
|
if (res.ok && res.files?.length) {
|
||||||
|
setAttachments((prev) => {
|
||||||
|
const known = new Set(prev.map((f) => f.id));
|
||||||
|
return [...prev, ...res.files.filter((f) => !known.has(f.id))];
|
||||||
|
});
|
||||||
|
setPage('chat');
|
||||||
|
pinBottom();
|
||||||
|
} else if (res.error) {
|
||||||
|
showHint('把文件拖到窗口里,或在电脑端选文件');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
showHint('把文件拖到窗口里,或在电脑端选文件');
|
||||||
|
}
|
||||||
|
}, [showHint, pinBottom]);
|
||||||
|
|
||||||
|
const removeAttachment = useCallback((id: string) => {
|
||||||
|
setAttachments((prev) => prev.filter((f) => f.id !== id));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const saveSettings = useCallback(async (patch: Record<string, unknown>) => {
|
||||||
|
await api.saveSettings(patch);
|
||||||
|
await refresh();
|
||||||
|
}, [refresh]);
|
||||||
|
|
||||||
|
const saveSecurity = useCallback(async (security: Security) => {
|
||||||
|
await api.saveSettings({ security });
|
||||||
|
await refresh();
|
||||||
|
}, [refresh]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 抽屉里「模型」那一栏:换模型 / 换思考强度。
|
||||||
|
* 立即存盘并刷新,不关面板——这样用户能连着调两下看效果。
|
||||||
|
*/
|
||||||
|
const pickModel = useCallback(async (patch: Record<string, unknown>) => {
|
||||||
|
try {
|
||||||
|
await api.saveSettings(patch);
|
||||||
|
await refresh();
|
||||||
|
if (patch.model) showHint('已切换模型');
|
||||||
|
else if (patch.thinkingLevel) showHint('已切换思考强度');
|
||||||
|
} catch (err) {
|
||||||
|
showHint(`切换失败:${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
}, [refresh, showHint]);
|
||||||
|
|
||||||
|
const useAgent = useCallback(async (agent: Agent) => {
|
||||||
|
await api.saveSettings({ activeAgentId: agent.id });
|
||||||
|
await refresh();
|
||||||
|
setPage('chat');
|
||||||
|
showHint(`已切换到「${agent.name}」`);
|
||||||
|
}, [refresh, showHint]);
|
||||||
|
|
||||||
|
if (!state) {
|
||||||
|
return (
|
||||||
|
<view className="page" style={{ alignItems: 'center', justifyContent: 'center', paddingLeft: '24px', paddingRight: '24px' }}>
|
||||||
|
<text style={{ fontSize: '16px', color: '#1f2329', fontWeight: '600' }}>连不上 AI 内核</text>
|
||||||
|
<text style={{ fontSize: '12px', color: '#8a8f99', marginTop: '8px', textAlign: 'center' }}>
|
||||||
|
{bootError || '正在连接…'}
|
||||||
|
{'\n'}内核跑在电脑上时,手机端要填电脑的局域网地址。
|
||||||
|
</text>
|
||||||
|
<input
|
||||||
|
className="form-input"
|
||||||
|
style={{ marginTop: '16px', width: '100%' }}
|
||||||
|
placeholder="http://192.168.1.8:5199"
|
||||||
|
{...cv(apiDraft)}
|
||||||
|
bindinput={(e: { detail: { value: string } }) => setApiDraft(e.detail.value)}
|
||||||
|
/>
|
||||||
|
<view
|
||||||
|
className="ghost-btn"
|
||||||
|
style={{ marginTop: '12px' }}
|
||||||
|
bindtap={async () => {
|
||||||
|
const { setApiBase } = await import('./api.js');
|
||||||
|
if (apiDraft.trim()) setApiBase(apiDraft.trim());
|
||||||
|
setBootError('');
|
||||||
|
await refresh();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<text className="ghost-btn-text">用这个地址重试</text>
|
||||||
|
</view>
|
||||||
|
<view className="ghost-btn" style={{ marginTop: '10px' }} bindtap={refresh}>
|
||||||
|
<text className="ghost-btn-text">直接重试</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { settings } = state;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<view className="app">
|
||||||
|
{page === 'chat'
|
||||||
|
? (
|
||||||
|
<ChatPage
|
||||||
|
messages={messages}
|
||||||
|
streaming={streaming}
|
||||||
|
draft={draft}
|
||||||
|
agent={activeAgent}
|
||||||
|
attachments={attachments}
|
||||||
|
scrollAnchor={scrollAnchor}
|
||||||
|
scrollSignal={scrollSignal}
|
||||||
|
copyHint={copyHint}
|
||||||
|
thinkingLevel={settings.thinkingLevel || 'auto'}
|
||||||
|
openReasoning={openReasoning}
|
||||||
|
onToggleReasoning={toggleReasoning}
|
||||||
|
onOpenThink={setThinkIndex}
|
||||||
|
thinkIndex={thinkIndex}
|
||||||
|
onCloseThink={() => setThinkIndex(null)}
|
||||||
|
onDraftChange={setDraft}
|
||||||
|
onSend={send}
|
||||||
|
onOpenDrawer={() => setDrawerOpen(true)}
|
||||||
|
onOpenAgents={() => setPage('agents')}
|
||||||
|
onOpenSettings={() => setPage('settings')}
|
||||||
|
onPickFile={pickFile}
|
||||||
|
onRemoveAttachment={removeAttachment}
|
||||||
|
onRegenerate={regenerate}
|
||||||
|
onFeedback={feedback}
|
||||||
|
onCopy={copy}
|
||||||
|
onSpeak={speak}
|
||||||
|
speakingIndex={speakingIndex}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
{page === 'profile'
|
||||||
|
? (
|
||||||
|
<ProfilePage
|
||||||
|
nickname={settings.nickname}
|
||||||
|
doubaoId={settings.doubaoId}
|
||||||
|
memoryEnabled={memoryEnabled}
|
||||||
|
onToggleMemory={() => setMemoryEnabled((v) => !v)}
|
||||||
|
onOpenDrawer={() => setDrawerOpen(true)}
|
||||||
|
onOpenSettings={() => setPage('settings')}
|
||||||
|
onOpenAgents={() => setPage('agents')}
|
||||||
|
onNewTopic={newTopic}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
{page === 'settings'
|
||||||
|
? <SettingsPage state={state} onBack={() => setPage('chat')} onSaved={saveSettings} />
|
||||||
|
: null}
|
||||||
|
|
||||||
|
{page === 'skills'
|
||||||
|
? (
|
||||||
|
<SkillsPage
|
||||||
|
state={state}
|
||||||
|
onBack={() => setPage('chat')}
|
||||||
|
onRefresh={async () => { await refresh(); }}
|
||||||
|
onSaveSecurity={saveSecurity}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
{page === 'agents'
|
||||||
|
? (
|
||||||
|
<AgentsPage
|
||||||
|
state={state}
|
||||||
|
activeAgentId={activeAgent?.id || ''}
|
||||||
|
onBack={() => setPage('chat')}
|
||||||
|
onUse={useAgent}
|
||||||
|
onRefresh={async () => { await refresh(); }}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
{page === 'terminal'
|
||||||
|
? (
|
||||||
|
<TerminalPage
|
||||||
|
onBack={() => setPage('chat')}
|
||||||
|
shellChannel={shellChannel}
|
||||||
|
onRefreshChannel={refreshShellChannel}
|
||||||
|
platform={state.platform}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
{drawerOpen
|
||||||
|
? (
|
||||||
|
<Drawer
|
||||||
|
conversations={state.conversations}
|
||||||
|
activeId={activeId}
|
||||||
|
nickname={settings.nickname}
|
||||||
|
onSelect={loadConversation}
|
||||||
|
onClose={() => setDrawerOpen(false)}
|
||||||
|
onNewTopic={newTopic}
|
||||||
|
onDelete={deleteConversation}
|
||||||
|
onOpenProfile={() => {
|
||||||
|
setDrawerOpen(false);
|
||||||
|
setPage('profile');
|
||||||
|
}}
|
||||||
|
onOpenSettings={() => {
|
||||||
|
setDrawerOpen(false);
|
||||||
|
setPage('settings');
|
||||||
|
}}
|
||||||
|
onOpenSkills={() => {
|
||||||
|
setDrawerOpen(false);
|
||||||
|
setPage('skills');
|
||||||
|
}}
|
||||||
|
onOpenAgents={() => {
|
||||||
|
setDrawerOpen(false);
|
||||||
|
setPage('agents');
|
||||||
|
}}
|
||||||
|
modelLabel={modelRowLabel(state)}
|
||||||
|
onOpenModel={() => setModelPickerOpen(true)}
|
||||||
|
onOpenTerminal={() => {
|
||||||
|
setDrawerOpen(false);
|
||||||
|
setPage('terminal');
|
||||||
|
refreshShellChannel();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
{modelPickerOpen
|
||||||
|
? (
|
||||||
|
<ModelPicker
|
||||||
|
state={state}
|
||||||
|
onClose={() => setModelPickerOpen(false)}
|
||||||
|
onPick={pickModel}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
</view>
|
||||||
|
);
|
||||||
|
}
|
||||||
129
app/src/Icon.tsx
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
/** 图标:全部是本地 SVG 资源,运行时不需要联网 */
|
||||||
|
import avatarCircle from './assets/icons-png/avatar-circle.png';
|
||||||
|
import checkIcon from './assets/icons-png/check.png';
|
||||||
|
import modelIcon from './assets/icons-png/model.png';
|
||||||
|
import avatarC0 from './assets/icons-png/avatar-c0.png';
|
||||||
|
import avatarC1 from './assets/icons-png/avatar-c1.png';
|
||||||
|
import avatarC2 from './assets/icons-png/avatar-c2.png';
|
||||||
|
import avatarC3 from './assets/icons-png/avatar-c3.png';
|
||||||
|
import avatarC4 from './assets/icons-png/avatar-c4.png';
|
||||||
|
// 智能体头像
|
||||||
|
import agAnalyst from './assets/avatars-png/agent-analyst.png';
|
||||||
|
import agCat from './assets/avatars-png/agent-cat.png';
|
||||||
|
import agCloud from './assets/avatars-png/agent-cloud.png';
|
||||||
|
import agCoder from './assets/avatars-png/agent-coder.png';
|
||||||
|
import agCustom from './assets/avatars-png/agent-custom.png';
|
||||||
|
import agRobot from './assets/avatars-png/agent-robot.png';
|
||||||
|
import agStar from './assets/avatars-png/agent-star.png';
|
||||||
|
import agWriter from './assets/avatars-png/agent-writer.png';
|
||||||
|
import avatarDoubao from './assets/avatar-doubao.png';
|
||||||
|
import avatarMain from './assets/avatar-main.png';
|
||||||
|
import bell from './assets/icons-png/bell.png';
|
||||||
|
import bellPurple from './assets/icons-png/bell-purple.png';
|
||||||
|
import camera from './assets/icons-png/camera.png';
|
||||||
|
import chevronRight from './assets/icons-png/chevron-right.png';
|
||||||
|
import clock from './assets/icons-png/clock.png';
|
||||||
|
import close from './assets/icons-png/close.png';
|
||||||
|
import cloud from './assets/icons-png/cloud.png';
|
||||||
|
import compose from './assets/icons-png/compose.png';
|
||||||
|
import copy from './assets/icons-png/copy.png';
|
||||||
|
import dislike from './assets/icons-png/dislike.png';
|
||||||
|
import attach from './assets/icons-png/attach.png';
|
||||||
|
import like from './assets/icons-png/like.png';
|
||||||
|
import refresh from './assets/icons-png/refresh.png';
|
||||||
|
import send from './assets/icons-png/send.png';
|
||||||
|
import share from './assets/icons-png/share.png';
|
||||||
|
import gear from './assets/icons-png/gear.png';
|
||||||
|
import imageIcon from './assets/icons-png/image.png';
|
||||||
|
import layers from './assets/icons-png/layers.png';
|
||||||
|
import mapIcon from './assets/icons-png/map.png';
|
||||||
|
import memory from './assets/icons-png/memory.png';
|
||||||
|
import menu from './assets/icons-png/menu.png';
|
||||||
|
import messageCircle from './assets/icons-png/message-circle.png';
|
||||||
|
import more from './assets/icons-png/more.png';
|
||||||
|
import person from './assets/icons-png/person.png';
|
||||||
|
import phone from './assets/icons-png/phone.png';
|
||||||
|
import plus from './assets/icons-png/plus.png';
|
||||||
|
import plusCircleBlue from './assets/icons-png/plus-circle-blue.png';
|
||||||
|
import scan from './assets/icons-png/scan.png';
|
||||||
|
import search from './assets/icons-png/search.png';
|
||||||
|
import sparkle from './assets/icons-png/sparkle.png';
|
||||||
|
import sparkleSquare from './assets/icons-png/sparkle-square.png';
|
||||||
|
import speaker from './assets/icons-png/speaker.png';
|
||||||
|
import speakerPurple from './assets/icons-png/speaker-purple.png';
|
||||||
|
import textSize from './assets/icons-png/text-size.png';
|
||||||
|
import upgrade from './assets/icons-png/upgrade.png';
|
||||||
|
import voice from './assets/icons-png/voice.png';
|
||||||
|
|
||||||
|
export const ICONS: Record<string, string> = {
|
||||||
|
'avatar-circle': avatarCircle,
|
||||||
|
'avatar-c0': avatarC0,
|
||||||
|
'avatar-c1': avatarC1,
|
||||||
|
'avatar-c2': avatarC2,
|
||||||
|
'avatar-c3': avatarC3,
|
||||||
|
'avatar-c4': avatarC4,
|
||||||
|
bell,
|
||||||
|
'bell-purple': bellPurple,
|
||||||
|
camera,
|
||||||
|
check: checkIcon,
|
||||||
|
model: modelIcon,
|
||||||
|
'chevron-right': chevronRight,
|
||||||
|
clock,
|
||||||
|
close,
|
||||||
|
cloud,
|
||||||
|
compose,
|
||||||
|
copy,
|
||||||
|
dislike,
|
||||||
|
attach,
|
||||||
|
like,
|
||||||
|
refresh,
|
||||||
|
send,
|
||||||
|
share,
|
||||||
|
gear,
|
||||||
|
image: imageIcon,
|
||||||
|
layers,
|
||||||
|
map: mapIcon,
|
||||||
|
memory,
|
||||||
|
menu,
|
||||||
|
'message-circle': messageCircle,
|
||||||
|
more,
|
||||||
|
person,
|
||||||
|
phone,
|
||||||
|
plus,
|
||||||
|
'plus-circle-blue': plusCircleBlue,
|
||||||
|
scan,
|
||||||
|
search,
|
||||||
|
sparkle,
|
||||||
|
'sparkle-square': sparkleSquare,
|
||||||
|
speaker,
|
||||||
|
'speaker-purple': speakerPurple,
|
||||||
|
'text-size': textSize,
|
||||||
|
upgrade,
|
||||||
|
voice,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function Icon(props: { name: string; className?: string }) {
|
||||||
|
const src = ICONS[props.name];
|
||||||
|
if (!src) return null;
|
||||||
|
return <image className={props.className || 'icon'} src={src} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 智能体头像表:key 与内核里的 agent.avatar 对应 */
|
||||||
|
export const AGENT_AVATARS: Record<string, string> = {
|
||||||
|
doubao: avatarDoubao,
|
||||||
|
coder: agCoder,
|
||||||
|
writer: agWriter,
|
||||||
|
analyst: agAnalyst,
|
||||||
|
cat: agCat,
|
||||||
|
robot: agRobot,
|
||||||
|
star: agStar,
|
||||||
|
cloud: agCloud,
|
||||||
|
custom: agCustom,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function AgentAvatar(props: { avatar: string; className?: string }) {
|
||||||
|
const src = AGENT_AVATARS[props.avatar] || avatarMain;
|
||||||
|
return <image className={props.className || 'conv-avatar'} src={src} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { avatarMain, avatarDoubao };
|
||||||
293
app/src/api.ts
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
/**
|
||||||
|
* 内核 API 客户端。
|
||||||
|
* 之所以用绝对地址:Lynx 在原生端没有 location,web 端跑在 Worker 里,
|
||||||
|
* 两种情况下相对路径都不够可靠。
|
||||||
|
*/
|
||||||
|
import type { Agent, AppState, Attachment, StreamEvent } from './types.js';
|
||||||
|
|
||||||
|
const FALLBACK_BASE = 'http://127.0.0.1:5199';
|
||||||
|
const STORAGE_KEY = 'doubao.apiBase';
|
||||||
|
|
||||||
|
function store(): { getItem?: (k: string) => string | null; setItem?: (k: string, v: string) => void } | null {
|
||||||
|
const g = globalThis as unknown as { localStorage?: ReturnType<typeof store> };
|
||||||
|
return g.localStorage || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 运行时可覆盖的内核地址(手机端连电脑、或内核换了端口时用得上) */
|
||||||
|
let overrideBase = '';
|
||||||
|
|
||||||
|
export function setApiBase(url: string): void {
|
||||||
|
const clean = String(url || '').trim().replace(/\/+$/, '');
|
||||||
|
overrideBase = clean;
|
||||||
|
try {
|
||||||
|
store()?.setItem?.(STORAGE_KEY, clean);
|
||||||
|
} catch {
|
||||||
|
/* 某些宿主没有 localStorage */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getApiBaseOverride(): string {
|
||||||
|
if (overrideBase) return overrideBase;
|
||||||
|
try {
|
||||||
|
const saved = store()?.getItem?.(STORAGE_KEY) || '';
|
||||||
|
if (saved) {
|
||||||
|
overrideBase = saved;
|
||||||
|
return saved;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function apiBase(): string {
|
||||||
|
const g = globalThis as unknown as {
|
||||||
|
__DOUBAO_API__?: string;
|
||||||
|
lynx?: { __globalProps?: { apiBase?: string } };
|
||||||
|
location?: { origin?: string };
|
||||||
|
};
|
||||||
|
// 1) 宿主页注入 2) 原生壳(Android 端 updateGlobalProps)传进来的 3) 用户手填的 4) 同源 5) 本地默认
|
||||||
|
if (g.__DOUBAO_API__) return String(g.__DOUBAO_API__).replace(/\/+$/, '');
|
||||||
|
const fromNative = g.lynx?.__globalProps?.apiBase;
|
||||||
|
if (fromNative) return String(fromNative).replace(/\/+$/, '');
|
||||||
|
const saved = getApiBaseOverride();
|
||||||
|
if (saved) return saved;
|
||||||
|
const origin = g.location?.origin;
|
||||||
|
if (origin && origin.startsWith('http')) return origin;
|
||||||
|
return FALLBACK_BASE;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
|
const res = await fetch(`${apiBase()}${path}`, {
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
...init,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
if (!res.ok) throw new Error(`${res.status} ${text.slice(0, 200)}`);
|
||||||
|
return text ? (JSON.parse(text) as T) : ({} as T);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
state: () => request<AppState>('/api/state'),
|
||||||
|
/**
|
||||||
|
* 朗读:把文字交给内核合成。
|
||||||
|
* 返回三种形状之一 —— engine='system' 表示用浏览器自带的 speechSynthesis,
|
||||||
|
* 带 audio 表示云端已经把音频合成好了(base64),失败则 ok=false 带 error。
|
||||||
|
*/
|
||||||
|
speak: (text: string) =>
|
||||||
|
request<{ ok: boolean; engine?: string; mime?: string; audio?: string; error?: string }>('/api/tts', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ text }),
|
||||||
|
}),
|
||||||
|
saveSettings: (patch: Record<string, unknown>) =>
|
||||||
|
request<{ ok: boolean }>('/api/settings', { method: 'PUT', body: JSON.stringify(patch) }),
|
||||||
|
conversations: () => request<{ conversations: AppState['conversations'] }>('/api/conversations'),
|
||||||
|
createConversation: (title?: string) =>
|
||||||
|
request<{ conversation: AppState['conversations'][number] }>('/api/conversations', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ title: title || '新对话' }),
|
||||||
|
}),
|
||||||
|
deleteConversation: (id: string) =>
|
||||||
|
request<{ ok: boolean }>(`/api/conversations/${id}`, { method: 'DELETE' }),
|
||||||
|
conversation: (id: string) =>
|
||||||
|
request<{ conversation: { id: string; title: string; messages: { role: string; content: string }[] } }>(
|
||||||
|
`/api/conversations/${id}`,
|
||||||
|
),
|
||||||
|
runTool: (name: string, args: Record<string, unknown>) =>
|
||||||
|
request<{ ok: boolean; result?: unknown; error?: string }>('/api/tools/run', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ name, args }),
|
||||||
|
}),
|
||||||
|
connectMcp: (name?: string) =>
|
||||||
|
request<{ ok: boolean; error?: string; results?: unknown }>('/api/mcp/connect', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ name }),
|
||||||
|
}),
|
||||||
|
disconnectMcp: (name: string) =>
|
||||||
|
request<{ ok: boolean }>('/api/mcp/disconnect', { method: 'POST', body: JSON.stringify({ name }) }),
|
||||||
|
mcpDetail: () =>
|
||||||
|
request<{
|
||||||
|
path: string;
|
||||||
|
dir: string;
|
||||||
|
text: string;
|
||||||
|
canReveal: boolean;
|
||||||
|
placeholders: Record<string, string>;
|
||||||
|
}>('/api/mcp'),
|
||||||
|
saveMcpConfig: (text: string) =>
|
||||||
|
request<{ ok: boolean; count?: number; error?: string; results?: { name: string; ok: boolean; error?: string }[] }>(
|
||||||
|
'/api/mcp/config',
|
||||||
|
{ method: 'PUT', body: JSON.stringify({ text }) },
|
||||||
|
),
|
||||||
|
revealMcp: () => request<{ ok: boolean; path: string; error?: string }>('/api/mcp/reveal', { method: 'POST' }),
|
||||||
|
|
||||||
|
// 智能体
|
||||||
|
agents: () => request<{ agents: Agent[] }>('/api/agents'),
|
||||||
|
createAgent: (body: Partial<Agent>) =>
|
||||||
|
request<{ agent: Agent }>('/api/agents', { method: 'POST', body: JSON.stringify(body) }),
|
||||||
|
updateAgent: (id: string, body: Partial<Agent>) =>
|
||||||
|
request<{ agent: Agent }>(`/api/agents/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
|
||||||
|
deleteAgent: (id: string) => request<{ ok: boolean }>(`/api/agents/${id}`, { method: 'DELETE' }),
|
||||||
|
|
||||||
|
// 附件
|
||||||
|
pickFile: () => request<{ ok: boolean; files: Attachment[]; error?: string }>('/api/pick-file', { method: 'POST', body: '{}' }),
|
||||||
|
uploadFile: (name: string, dataUrl: string, pending = false) =>
|
||||||
|
request<{ ok: boolean; file: Attachment; error?: string }>('/api/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ name, dataUrl, pending }),
|
||||||
|
}),
|
||||||
|
pendingUploads: () => request<{ files: Attachment[] }>('/api/uploads/pending'),
|
||||||
|
|
||||||
|
// 复制到剪贴板(桌面版走原生,浏览器走 navigator.clipboard)
|
||||||
|
clipboard: (text: string) =>
|
||||||
|
request<{ ok: boolean; via: string }>('/api/clipboard', { method: 'POST', body: JSON.stringify({ text }) }),
|
||||||
|
};
|
||||||
|
|
||||||
|
function decodeChunk(value: unknown): string {
|
||||||
|
const g = globalThis as unknown as {
|
||||||
|
TextDecoder?: new () => { decode: (v: unknown, o?: { stream?: boolean }) => string };
|
||||||
|
TextCodecHelper?: { decode: (v: unknown) => string };
|
||||||
|
};
|
||||||
|
if (g.TextDecoder) return new g.TextDecoder().decode(value, { stream: true });
|
||||||
|
if (g.TextCodecHelper) return g.TextCodecHelper.decode(value);
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析 SSE 分片,把完整的 data: 行交给 onEvent */
|
||||||
|
function drainBuffer(buffer: string, onEvent: (e: StreamEvent) => void, flush = false): string {
|
||||||
|
let rest = buffer;
|
||||||
|
let idx: number;
|
||||||
|
while ((idx = rest.indexOf('\n\n')) >= 0) {
|
||||||
|
const block = rest.slice(0, idx);
|
||||||
|
rest = rest.slice(idx + 2);
|
||||||
|
for (const line of block.split('\n')) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (!trimmed.startsWith('data:')) continue;
|
||||||
|
const payload = trimmed.slice(5).trim();
|
||||||
|
if (!payload) continue;
|
||||||
|
try {
|
||||||
|
onEvent(JSON.parse(payload) as StreamEvent);
|
||||||
|
} catch {
|
||||||
|
/* 忽略坏包 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (flush && rest.trim()) {
|
||||||
|
for (const line of rest.split('\n')) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (!trimmed.startsWith('data:')) continue;
|
||||||
|
try {
|
||||||
|
onEvent(JSON.parse(trimmed.slice(5).trim()) as StreamEvent);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rest = '';
|
||||||
|
}
|
||||||
|
return rest;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatPayload {
|
||||||
|
conversationId: string;
|
||||||
|
message: string;
|
||||||
|
history: { role: string; content: string }[];
|
||||||
|
attachments?: { id: string; name: string; size: number; mime?: string; path?: string; url?: string }[];
|
||||||
|
agentId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 这条 Lynx 宿主到底能不能"边收边解析"?
|
||||||
|
*
|
||||||
|
* 为什么要探测:Web 端 fetch 有 response.body,能拿到 ReadableStream;
|
||||||
|
* 但 **Lynx 原生端(安卓)的 fetch 没有 body**,只能等到全部返回才知道内容 ——
|
||||||
|
* 表现出来就是"等很久然后一次性吐出来"。
|
||||||
|
* 所以启动时探一次,不支持就走轮询通道(内核把事件攒着,客户端 200ms 拉一次增量)。
|
||||||
|
*/
|
||||||
|
let streamProbe: Promise<boolean> | null = null;
|
||||||
|
|
||||||
|
async function supportsStreaming(): Promise<boolean> {
|
||||||
|
if (streamProbe) return streamProbe;
|
||||||
|
streamProbe = (async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${apiBase()}/api/health`);
|
||||||
|
const body = (res as unknown as { body?: { getReader?: unknown } }).body;
|
||||||
|
return Boolean(body && typeof body.getReader === 'function');
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return streamProbe;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 轮询通道:POST 拿 runId,然后不停拉增量 */
|
||||||
|
async function pollChat(payload: ChatPayload, onEvent: (e: StreamEvent) => void): Promise<void> {
|
||||||
|
const start = await fetch(`${apiBase()}/api/chat`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ ...payload, transport: 'poll' }),
|
||||||
|
});
|
||||||
|
if (!start.ok) {
|
||||||
|
const detail = await start.text().catch(() => '');
|
||||||
|
throw new Error(`内核返回 ${start.status}:${detail.slice(0, 300)}`);
|
||||||
|
}
|
||||||
|
const { runId } = (await start.json()) as { runId?: string };
|
||||||
|
if (!runId) throw new Error('内核没有返回 runId');
|
||||||
|
|
||||||
|
let cursor = 0;
|
||||||
|
let idle = 0;
|
||||||
|
for (;;) {
|
||||||
|
const res = await fetch(`${apiBase()}/api/chat/poll?runId=${encodeURIComponent(runId)}&cursor=${cursor}`);
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`轮询失败(HTTP ${res.status}),任务可能已过期`);
|
||||||
|
}
|
||||||
|
const data = (await res.json()) as { events?: StreamEvent[]; cursor?: number; done?: boolean };
|
||||||
|
const events = data.events || [];
|
||||||
|
for (const event of events) onEvent(event);
|
||||||
|
cursor = data.cursor ?? cursor;
|
||||||
|
if (data.done) return;
|
||||||
|
|
||||||
|
// 一直没新事件也别死等(比如内核那边的请求卡住了)
|
||||||
|
idle = events.length === 0 ? idle + 1 : 0;
|
||||||
|
if (idle > 600) throw new Error('长时间没有新内容(超过 2 分钟),已停止等待');
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 流式对话:自动挑通道。
|
||||||
|
* - 宿主支持 ReadableStream → SSE 增量读取(web / exe)
|
||||||
|
* - 不支持(Lynx 原生端) → 轮询增量(观感基本一致)
|
||||||
|
*/
|
||||||
|
export async function streamChat(payload: ChatPayload, onEvent: (e: StreamEvent) => void): Promise<void> {
|
||||||
|
if (!(await supportsStreaming())) {
|
||||||
|
await pollChat(payload, onEvent);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${apiBase()}/api/chat`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const detail = await res.text().catch(() => '');
|
||||||
|
throw new Error(`内核返回 ${res.status}:${detail.slice(0, 300)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = (res as unknown as { body?: { getReader?: () => { read: () => Promise<{ done: boolean; value?: unknown }> } } }).body;
|
||||||
|
if (body && typeof body.getReader === 'function') {
|
||||||
|
const reader = body.getReader();
|
||||||
|
let buffer = '';
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buffer += decodeChunk(value);
|
||||||
|
buffer = drainBuffer(buffer, onEvent);
|
||||||
|
}
|
||||||
|
drainBuffer(buffer, onEvent, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 探测说支持、实际却没拿到 body:兜底按整包解析,别让消息卡住
|
||||||
|
const text = await res.text();
|
||||||
|
drainBuffer(`${text}\n\n`, onEvent, true);
|
||||||
|
}
|
||||||
1752
app/src/app.css
Normal file
BIN
app/src/assets/avatar-doubao.png
Normal file
|
After Width: | Height: | Size: 68 KiB |
BIN
app/src/assets/avatar-main.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
app/src/assets/avatar-photo.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
app/src/assets/avatars-png/agent-analyst.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
app/src/assets/avatars-png/agent-cat.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
app/src/assets/avatars-png/agent-cloud.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
app/src/assets/avatars-png/agent-coder.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
app/src/assets/avatars-png/agent-custom.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
app/src/assets/avatars-png/agent-robot.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
app/src/assets/avatars-png/agent-star.png
Normal file
|
After Width: | Height: | Size: 10 KiB |