commit f056bcf45a3a696878c34c169a401da57f519681 Author: l Date: Fri Oct 9 14:09:36 2026 +0800 豆包复刻:原生安卓(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。 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..4dacdf6 --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5a34864 --- /dev/null +++ b/.gitignore @@ -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-* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9890f7e --- /dev/null +++ b/LICENSE @@ -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。 +- 仓库里的界面截图由项目作者在自己的设备上截取。 diff --git a/README.md b/README.md new file mode 100644 index 0000000..315cf88 --- /dev/null +++ b/README.md @@ -0,0 +1,638 @@ +# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版) + +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](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 就能用。 + +| 对话(原生) | 真实回复(含操作栏) | 抽屉(含「模型」栏) | +|---|---|---| +| ![对话](docs/screenshots/v4-native-chat.png) | ![回复](docs/screenshots/v4-native-reply.png) | ![抽屉](docs/screenshots/v4-native-drawer.png) | + +| 模型与思考强度 | 设置(10 家提供商) | 内置 Termux 终端 | +|---|---|---| +| ![模型](docs/screenshots/v4-native-modelsheet.png) | ![设置](docs/screenshots/v4-native-settings.png) | ![终端](docs/screenshots/v3-native-terminal.png) | + +| 早期 Lynx 版(真机实拍) | 浏览器版设置(10 家提供商) | Windows 桌面版 | +|---|---|---| +| ![android](docs/screenshots/android.png) | ![web](docs/screenshots/web-settings-providers.png) | ![exe](docs/screenshots/exe-window.png) | + +> 最左边那张是**旧的 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//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":""} + → {"ok":false, "error":"..."} 失败原因给人话 + +POST /api/stt + 头: 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//libtermux.so ← pty 的 JNI(createSubprocess 等 5 个符号) +├─ lib//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 ` → **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 # 设备端 18 项验收 +node scripts/parity-thinking.mjs # 两份内核的思考强度对拍 +node scripts/probe-settings-wipe.mjs # 设置保存不掉字段(电脑) +node scripts/device-settings-attack.mjs # 设置保存不掉字段(设备) +node scripts/test-shell-tool.mjs [port] # 试内置 Termux 的 shell +node scripts/device-state.mjs # 看设备内核当前设置 +node scripts/device-tool.mjs @args.json # 在设备上跑任意工具 +node scripts/verify-mcp-stdio.mjs # MCP stdio 传输 +node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍 +node scripts/screenshot.mjs # 无头浏览器截图 + +# mock(不消耗额度) +node scripts/mock-llm.mjs # 监听 5299 +``` + +--- + +## 10. 参考 + +- 火山方舟: +- OpenAI Chat Completions: +- Termux(Apache-2.0): +- Chaquopy: +- 调研笔记(`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。 + diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..c7e1d44 --- /dev/null +++ b/android/app/build.gradle.kts @@ -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//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) +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..e37fd2e --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,4 @@ +# Lynx 依赖较多反射,保守起见先不混淆 +-keep class com.lynx.** { *; } +-keep class org.lynxsdk.** { *; } +-dontwarn com.lynx.** diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..fccae1e --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/assets/APACHE-2.0.txt b/android/app/src/main/assets/APACHE-2.0.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/android/app/src/main/assets/APACHE-2.0.txt @@ -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. diff --git a/android/app/src/main/assets/TERMUX_LICENSE.txt b/android/app/src/main/assets/TERMUX_LICENSE.txt new file mode 100644 index 0000000..8896be3 --- /dev/null +++ b/android/app/src/main/assets/TERMUX_LICENSE.txt @@ -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//libtermux.so + pty 支持(forkpty 等 JNI 实现),TerminalSession 依赖它 + - android/app/src/main/jniLibs//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 diff --git a/android/app/src/main/java/com/doubao/lynxclone/DoubaoApplication.kt b/android/app/src/main/java/com/doubao/lynxclone/DoubaoApplication.kt new file mode 100644 index 0000000..a791a35 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/DoubaoApplication.kt @@ -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)) + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/LocalKernel.kt b/android/app/src/main/java/com/doubao/lynxclone/LocalKernel.kt new file mode 100644 index 0000000..4c2c4c9 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/LocalKernel.kt @@ -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 +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/MainActivity.kt b/android/app/src/main/java/com/doubao/lynxclone/MainActivity.kt new file mode 100644 index 0000000..1284d00 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/MainActivity.kt @@ -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 + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt new file mode 100644 index 0000000..6b2f747 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt @@ -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() + 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 = emptyList() + + @Suppress("unused") + fun pickFile(): Array { + 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() + 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) + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/speech/AudioIo.kt b/android/app/src/main/java/com/doubao/lynxclone/speech/AudioIo.kt new file mode 100644 index 0000000..e45145d --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/speech/AudioIo.kt @@ -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() + + /** 播完(或被停掉)回调一次,界面用它复位"正在朗读"的状态 */ + 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) { + 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() + 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 { + val clean = stripForSpeech(text) + if (clean.isEmpty()) return emptyList() + val out = ArrayList() + 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() } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt b/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt new file mode 100644 index 0000000..c10ae9b --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt @@ -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" + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt b/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt new file mode 100644 index 0000000..cd127ef --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt @@ -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//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 = + arrayOf("--rcfile", File(prefix(context), "etc/doubao.bashrc").absolutePath, "-i") + + /** 装完之后给内核/工具用的环境变量(Termux 的标准一套) */ + fun environment(context: Context): Map { + 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", + ) + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxShell.kt b/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxShell.kt new file mode 100644 index 0000000..4547cdc --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxShell.kt @@ -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}") + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxTerminal.kt b/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxTerminal.kt new file mode 100644 index 0000000..fc73562 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/termux/TermuxTerminal.kt @@ -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() +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt new file mode 100644 index 0000000..58dede8 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt @@ -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(null) } + var creating by remember { mutableStateOf(false) } + var confirmDelete by remember { mutableStateOf(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 -> "通用助手" +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt new file mode 100644 index 0000000..2a8325f --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt @@ -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 create(modelClass: Class): 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 -> "自动" +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt new file mode 100644 index 0000000..20c12e0 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -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() + var activeConversationId by mutableStateOf("c_main") + var streaming by mutableStateOf(false) + private set + var draft by mutableStateOf("") + val attachments = mutableStateListOf() + /** 正在看「思考过程」的消息下标;-1 表示没开 */ + var thinkingIndex by mutableStateOf(-1) + /** 模型 / 思考强度面板(底部升起) */ + var modelPickerOpen by mutableStateOf(false) + + private var chatJob: AtomicBoolean? = null + + val settings get() = state.settings + val agents: List 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) { + 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, 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) { + 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): 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 +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt new file mode 100644 index 0000000..6cbd8f3 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt @@ -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(), + ) + } + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/CommandConsole.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/CommandConsole.kt new file mode 100644 index 0000000..e2b7ef6 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/CommandConsole.kt @@ -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() } + 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, "执行") + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt new file mode 100644 index 0000000..6ee1d87 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt @@ -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, + ) +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ModelPickerDialog.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ModelPickerDialog.kt new file mode 100644 index 0000000..b0bf60e --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ModelPickerDialog.kt @@ -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)) + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ProfileScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ProfileScreen.kt new file mode 100644 index 0000000..b21dadc --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ProfileScreen.kt @@ -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 diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/SettingsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/SettingsScreen.kt new file mode 100644 index 0000000..e11f764 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/SettingsScreen.kt @@ -0,0 +1,1030 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +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.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Visibility +import androidx.compose.material.icons.filled.VisibilityOff +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.Slider +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +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.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.doubao.lynxclone.data.Settings +import com.doubao.lynxclone.data.SpeechSettings +import com.doubao.lynxclone.data.VoiceOption +import kotlin.math.round + +/** + * AI 内核设置页(对应旧版 Lynx 的 Settings.tsx)。 + * + * 两个不显然的取舍,注释写在这里免得以后被"优化"掉: + * + * 1. **本地草稿 + 一次性保存**。旧版就是先把改动攒在 form 里,点「保存设置」才落盘。 + * 这不是为了省请求,而是因为 /api/settings 是"改一个字段就可能换一次上游连接"的接口, + * 每敲一个字符就发一次会把内核打爆(还会把半截 baseUrl 写进配置文件)。 + * 所以这里只在本地改 draft,保存时才 vm.saveSettings(...)。 + * + * 2. **API Key 输入框不回填**。内核 /api/state 返回的 apiKey 是掩码(••••••••), + * 而且只在**恰好等于 8 个点**时才被当成"不修改"的哨兵值。要是把它填进输入框、 + * 用户在末尾补一个字符再保存,掩码就被当成真 Key 存进去了(等于把 Key 改坏)。 + * 所以:输入框永远从空开始,只有用户真的输入了非空内容才把 apiKey 放进补丁里。 + */ +@Composable +fun SettingsScreen(vm: AppViewModel) { + val s = vm.settings + /** + * 草稿只在**服务端设置真的变了**的时候重建。 + * + * 之前写成 `remember(s)`:任何一次 state 刷新(比如别处调了 refresh)都会把用户 + * 正在改的内容冲掉;而首屏 state 还没到时,草稿还是"全空",这时候点保存就把配置清空了。 + * 现在用 snapshot 记住上一份服务端值,只有它变了才同步草稿。 + */ + var snapshot by remember { mutableStateOf(s) } + var draft by remember { mutableStateOf(SettingsDraft.from(s)) } + LaunchedEffect(s) { + if (s != snapshot) { + // ★ 用户手上有没保存的改动时**不能**重建草稿。 + // + // 为什么:新建话题、删会话、换模型这些操作都会 refresh(), + // state 一变这里就会拿服务端值把草稿覆盖掉 —— 用户正在填 App ID / Token, + // 旁边随便点一下,填的东西就没了,看起来就是"一开设置就清空"。 + // 所以:只有在草稿和服务端一致(没有未保存改动)时才跟着刷新。 + val dirty = draft.changesAgainst(snapshot).isNotEmpty() + snapshot = s + if (!dirty) draft = SettingsDraft.from(s) + } + } + var saving by remember { mutableStateOf(false) } + var showKey by remember { mutableStateOf(false) } + // 火山 Access Token 也有自己的"看一眼"状态:跟 API Key 分开,免得一按眼睛两个框一起露 + var showVolcToken by remember { mutableStateOf(false) } + + Column(Modifier.fillMaxSize()) { + ScreenHeader("AI 内核设置", onBack = { vm.screen = Screen.Chat }) { + Text( + if (saving) "保存中…" else "", + fontSize = 12.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + Column( + Modifier + .weight(1f) + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + // 输入法弹起来时把内容顶上去,否则系统提示词这种多行框会被键盘盖住 + .imePadding() + .padding(horizontal = 14.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Spacer(Modifier.height(2.dp)) + + /* ---------------- 模型提供商 ---------------- */ + SettingsCard("模型提供商") { + // ★ 别写死"方舟 / OpenAI"两家:内核里现在有十来家 + // (方舟、OpenAI、DeepSeek、Kimi、智谱、通义、硅基流动、OpenRouter、本地 Ollama、自定义), + // 它们都是 OpenAI 兼容协议,只是地址和思考参数不同 —— 有几家就列几家。 + WrapRow { + vm.state.providers.entries.forEach { (key, preset) -> + val active = key == draft.provider + Box( + Modifier + .clip(RoundedCornerShape(12.dp)) + .background(if (active) Doubao.Blue else doubaoCard()) + .clickable { draft = draft.switchProvider(key, vm) } + .padding(horizontal = 14.dp, vertical = 9.dp), + ) { + Text( + shortProviderLabel(preset.label, key), + fontSize = 13.sp, + color = if (active) Color.White else doubaoText(), + maxLines = 1, + ) + } + } + } + val preset = vm.state.providers[draft.provider] + Spacer(Modifier.height(8.dp)) + FormHint("当前预设:${preset?.label ?: draft.provider}") + if (preset?.defaultModel?.isNotBlank() == true) { + FormHint("默认模型:${preset.defaultModel}") + } + if (preset?.modelHint?.isNotBlank() == true) { + FormHint(preset.modelHint) + } + } + + /* ---------------- 语音 ---------------- */ + SettingsCard("语音") { + // sp 是内核 speech_state 那份(/api/state 顶层的 speech),只有它带 + // hasVolcToken / hasOpenaiKey —— settings.speech 里是掩码,不能拿来判断"配没配" + val sp = vm.state.speech + + FormLabel("朗读(TTS)") + Spacer(Modifier.height(6.dp)) + // 引擎 chip 的写法照抄上面「模型提供商」:WrapRow + 圆胶囊 + Doubao.Blue 选中态。 + // 没用 SegmentedButton:这几个引擎名都不短("火山(豆包音色)"),分段按钮会压成省略号 + WrapRow { + TtsEngines.forEach { (key, label) -> + SpeechChip(label, active = draft.speech.ttsEngine == key) { + if (key != draft.speech.ttsEngine) { + // 换引擎时顺手清掉音色:音色是按引擎命名的(火山 BV700_streaming、 + // OpenAI alloy…),留着上一家的值一定会被厂商判非法,不如回落到默认音色 + draft = draft.copy( + speech = draft.speech.copy(ttsEngine = key, ttsVoice = ""), + ) + } + } + } + } + + if (draft.speech.ttsEngine == "volc") { + Spacer(Modifier.height(12.dp)) + FormLabel("App ID") + FormField( + value = draft.speech.volcAppId, + placeholder = "火山控制台里的 App ID", + onValue = { draft = draft.copy(speech = draft.speech.copy(volcAppId = it)) }, + ) + + Spacer(Modifier.height(12.dp)) + FormLabel("Access Token") + FormField( + value = draft.volcToken, + // 已配置时只说"留空则不变":接口只回掩码,回填会把真 Token 写坏(见文件头注释) + placeholder = if (sp.hasVolcToken) "已配置(留空则不变)" else "粘贴 Access Token", + onValue = { draft = draft.copy(volcToken = it) }, + password = !showVolcToken, + trailing = { + // 同 API Key:Token 又长又容易粘错,得能当场看一眼 + IconButton(onClick = { showVolcToken = !showVolcToken }) { + Icon( + if (showVolcToken) Icons.Filled.VisibilityOff else Icons.Filled.Visibility, + if (showVolcToken) "隐藏" else "显示", + modifier = Modifier.size(20.dp), + ) + } + }, + ) + FormHint("在火山控制台「语音技术」里创建应用后拿到 App ID 和 Access Token。") + + Spacer(Modifier.height(12.dp)) + VoicePicker( + title = "音色(voice_type)", + voices = vm.state.speechVoices["volc"].orEmpty(), + value = draft.speech.ttsVoice, + placeholder = "留空 = BV700_streaming(通用女声)", + onValue = { draft = draft.copy(speech = draft.speech.copy(ttsVoice = it)) }, + ) + } else if (draft.speech.ttsEngine == "openai") { + Spacer(Modifier.height(12.dp)) + VoicePicker( + title = "音色", + voices = vm.state.speechVoices["openai"].orEmpty(), + value = draft.speech.ttsVoice, + placeholder = "留空 = alloy(中性)", + onValue = { draft = draft.copy(speech = draft.speech.copy(ttsVoice = it)) }, + ) + + Spacer(Modifier.height(12.dp)) + FormLabel("模型") + FormField( + value = draft.speech.ttsModel, + placeholder = "tts-1", + onValue = { draft = draft.copy(speech = draft.speech.copy(ttsModel = it)) }, + ) + FormHint( + if (sp.hasOpenaiKey) { + // 语音自己那把 Key 留空时内核回落到对话设置里的 Key,所以这里只提示"复用" + "Base URL 和 Key 默认复用「连接与模型」里的设置(那边已配置 Key)。" + } else { + "Base URL 和 Key 默认复用「连接与模型」里的设置 —— 那边没填 Key,云端朗读会失败。" + }, + ) + } else { + FormHint("用系统自带语音,不联网、不需要 Key。想用豆包的音色就选「火山」。") + } + + // 语速只对云端引擎有效:系统 TTS 的语速归系统管,内核根本不参与合成 + if (draft.speech.ttsEngine != "system") { + Spacer(Modifier.height(12.dp)) + FormLabel("语速") + SpeedStepper(draft.speech.ttsSpeed) { + draft = draft.copy(speech = draft.speech.copy(ttsSpeed = it)) + } + FormHint("0.50 ~ 2.00 倍,1.00 是原速。火山按 speed_ratio、OpenAI 按 speed 传,都是倍率。") + } + + Spacer(Modifier.height(4.dp)) + HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)) + FormSwitch( + title = "自动朗读新回复", + sub = "回复一到就自动念出来", + checked = draft.speech.autoRead, + onChange = { draft = draft.copy(speech = draft.speech.copy(autoRead = it)) }, + ) + + FormLabel("语音输入(STT)") + Spacer(Modifier.height(6.dp)) + WrapRow { + SttEngines.forEach { (key, label) -> + SpeechChip(label, active = draft.speech.sttEngine == key) { + draft = draft.copy(speech = draft.speech.copy(sttEngine = key)) + } + } + } + if (draft.speech.sttEngine == "openai") { + Spacer(Modifier.height(12.dp)) + FormLabel("模型") + FormField( + value = draft.speech.sttModel, + placeholder = "whisper-1", + onValue = { draft = draft.copy(speech = draft.speech.copy(sttModel = it)) }, + ) + + Spacer(Modifier.height(12.dp)) + FormLabel("语言") + FormField( + value = draft.speech.sttLanguage, + placeholder = "留空 = 自动判断语种", + onValue = { draft = draft.copy(speech = draft.speech.copy(sttLanguage = it)) }, + ) + FormHint("留空 = 自动判断;填 zh 可强制中文(识别更稳,但说英文也会被当中文)。") + } + FormHint("识别时录音会发送到你配置的服务;用系统引擎则完全在本机。") + } + + /* ---------------- 连接与模型 ---------------- */ + SettingsCard("连接与模型") { + FormLabel("Base URL") + FormField( + value = draft.baseUrl, + placeholder = vm.state.providers[draft.provider]?.baseUrl ?: "https://…", + onValue = { draft = draft.copy(baseUrl = it) }, + ) + FormHint("留空则用预设地址:${vm.state.providers[draft.provider]?.baseUrl ?: "—"}") + + Spacer(Modifier.height(12.dp)) + FormLabel("API Key") + FormField( + value = draft.apiKey, + // 已配置时提示"留空则不变":因为接口只回掩码,回填会把 Key 写坏(见文件头注释) + placeholder = if (s.hasApiKey) "已配置(留空则不改动)" else "粘贴你的 API Key", + onValue = { draft = draft.copy(apiKey = it) }, + password = !showKey, + trailing = { + // 眼睛按钮:密码框默认打码,长 Key 粘错了要能看一眼 + IconButton(onClick = { showKey = !showKey }) { + Icon( + if (showKey) Icons.Filled.VisibilityOff else Icons.Filled.Visibility, + if (showKey) "隐藏" else "显示", + modifier = Modifier.size(20.dp), + ) + } + }, + ) + FormHint(if (s.hasApiKey) "已配置密钥;留空保存不会覆盖它。" else "也可以写在内核数据目录的 .env 里。") + + Spacer(Modifier.height(12.dp)) + FormLabel("模型") + FormField( + value = draft.model, + placeholder = "模型 ID 或接入点 ID(ep-…)", + onValue = { draft = draft.copy(model = it) }, + ) + val models = vm.state.providers[draft.provider]?.models.orEmpty() + if (models.isNotEmpty()) { + Spacer(Modifier.height(8.dp)) + Row( + // 候选模型可能挺多,横向滚比折行更像"候选条" + Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + models.forEach { m -> + FilterChip( + selected = m == draft.model, + onClick = { draft = draft.copy(model = m) }, + label = { Text(shortModel(m), fontSize = 12.sp) }, + ) + } + } + } + } + + /* ---------------- 思考与工具目录 ---------------- */ + SettingsCard("思考强度") { + // 5 个选项在手机上排一行会挤,WrapRow 自动折行(跟旧版 segment 换行一个效果) + WrapRow { + ThinkingLevels.forEach { (level, label) -> + FilterChip( + selected = draft.thinkingLevel == level, + onClick = { draft = draft.copy(thinkingLevel = level) }, + label = { Text(label, fontSize = 12.sp) }, + ) + } + } + FormHint(ThinkingHints[draft.thinkingLevel] ?: ThinkingHints.getValue("auto")) + + Spacer(Modifier.height(12.dp)) + FormLabel("工具目录(可选)") + FormField( + value = draft.toolsDir, + placeholder = "留空 = 内置 tools 目录", + onValue = { draft = draft.copy(toolsDir = it) }, + ) + FormHint("目录里的 *.py 会自动变成工具(同一套 _protocol 协议)。也可以指到手机上的目录,例如 /sdcard/Documents/doubao-tools") + } + + /* ---------------- 生成参数 ---------------- */ + SettingsCard("生成参数") { + FormLabel("温度 temperature:${"%.2f".format(draft.temperature)}") + Slider( + value = draft.temperature.toFloat(), + onValueChange = { draft = draft.copy(temperature = it.toDouble()) }, + valueRange = 0f..1.5f, + ) + FormHint("越低越稳、越高越发散。推理类模型会忽略这个参数。") + + Spacer(Modifier.height(12.dp)) + FormLabel("工具循环上限 maxRounds") + StepperRow( + value = draft.maxRounds, + onChange = { draft = draft.copy(maxRounds = it.coerceIn(1, 50)) }, + ) + FormHint("一轮对话里最多允许模型连续调用几轮工具。") + } + + /* ---------------- 系统提示词 ---------------- */ + SettingsCard("系统提示词(System Prompt)") { + FormField( + value = draft.systemPrompt, + onValue = { draft = draft.copy(systemPrompt = it) }, + placeholder = "你是豆包…", + singleLine = false, + minLines = 5, + ) + FormHint("这段提示词每次都放在对话最前面。选了智能体时,它的提示词会覆盖这一段。") + } + + /* ---------------- 工具开关 ---------------- */ + SettingsCard("工具") { + FormSwitch( + title = "Python 工具", + sub = "内置 tools/*.py 与自定义工具目录", + checked = draft.pythonEnabled, + onChange = { draft = draft.copy(pythonEnabled = it) }, + ) + HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)) + FormSwitch( + title = "MCP 服务", + sub = "外部 MCP 连接器提供的工具", + checked = draft.mcpEnabled, + onChange = { draft = draft.copy(mcpEnabled = it) }, + ) + FormHint("当前发现 Python 工具 ${vm.state.tools.size} 个 · MCP 工具 ${vm.state.mcp.sumOf { it.toolCount }} 个(在「技能·连接器」里看明细)") + } + + /* ---------------- 个人资料 ---------------- */ + SettingsCard("个人资料") { + FormLabel("昵称") + FormField( + value = draft.nickname, + placeholder = "我", + onValue = { draft = draft.copy(nickname = it) }, + ) + FormHint("显示在抽屉底部和「我的」页里。") + } + + /* ---------------- 保存 ---------------- */ + Button( + onClick = { + // 只发改动过的字段(未改动 = 不下发,服务端保持原样) + val patch = draft.changesAgainst(snapshot) + if (patch.isEmpty()) { + vm.showHint("没有改动") + return@Button + } + saving = true + vm.saveSettings(patch) { saving = false } + }, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(24.dp), + colors = ButtonDefaults.buttonColors(), + contentPadding = PaddingValues(vertical = 12.dp), + enabled = !saving, + ) { + Text(if (saving) "保存中…" else "保存设置", fontSize = 15.sp) + } + + FormHint("改完点保存才生效,避免半截地址被写进配置。") + Spacer(Modifier.height(20.dp)) + } + } +} + +/* ---------------------------- 语音卡片的零件 ---------------------------- */ + +/** 朗读引擎(key 跟内核 speech.ttsEngine 一致:system / volc / openai) */ +private val TtsEngines: List> = listOf( + "system" to "设备自带", + "volc" to "火山(豆包音色)", + "openai" to "OpenAI 兼容", +) + +/** 识别引擎(key 跟内核 speech.sttEngine 一致:system / openai) */ +private val SttEngines: List> = listOf( + "system" to "设备自带", + "openai" to "OpenAI(Whisper)", +) + +/** + * 语音卡片里的胶囊 chip:引擎选择、音色选择都用它。 + * + * 外观跟「模型提供商」那排引擎 chip 逐像素一致(选中 = Doubao.Blue 底 + 白字, + * 未选中 = 卡片同色 + 主文字色),抽成函数只是因为这三种选择得共用同一套外观 —— + * 卡片里再自创一种"选中态"会让整页看起来像两个人做的。 + */ +@Composable +private fun SpeechChip(label: String, active: Boolean, onClick: () -> Unit) { + Box( + Modifier + .clip(RoundedCornerShape(12.dp)) + .background(if (active) Doubao.Blue else doubaoCard()) + .clickable(onClick = onClick) + .padding(horizontal = 14.dp, vertical = 9.dp), + ) { + Text(label, fontSize = 13.sp, color = if (active) Color.White else doubaoText(), maxLines = 1) + } +} + +/** + * 音色选择:一排候选 chip + 一个能手填的输入框。 + * + * 为什么还留手填:候选表是内核里写死的几个常用音色,用户在厂商控制台里另开了音色时 + * 不该被界面挡住 —— chip 只是"常见值"的快捷方式,真正的取值永远以输入框为准。 + */ +@Composable +private fun VoicePicker( + title: String, + voices: List, + value: String, + placeholder: String, + onValue: (String) -> Unit, +) { + FormLabel(title) + if (voices.isNotEmpty()) { + Spacer(Modifier.height(6.dp)) + // 每行 2 个:音色名后面带括号备注("通用女声(BV700)"),一行 3 个会挤到折字 + WrapRow(perRow = 2) { + voices.forEach { v -> + SpeechChip(v.label.ifBlank { v.value }, active = v.value == value) { onValue(v.value) } + } + } + } + FormField(value = value, placeholder = placeholder, onValue = onValue) +} + +/** 语速取值范围:内核允许 0.2~3.0,界面只放开常用的这段(再极端就不是"听"了) */ +private const val SPEED_MIN = 0.5 +private const val SPEED_MAX = 2.0 +private const val SPEED_STEP = 0.05 + +/** + * 语速步进器(0.50 ~ 2.00,步进 0.05)。 + * + * 不用 Slider:滑块很难正好停在 1.00 这种"原速"上;也不用输入框:还得处理非法输入。 + * 浮点连加会累积误差(1.0 反复减 0.05 会变成 0.9500000000000001), + * 所以每一步都按两位小数重新取整 —— 显示和发回内核的值都必须是干净的。 + */ +@Composable +private fun SpeedStepper(value: Double, onChange: (Double) -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically) { + StepperButton("−") { onChange(stepSpeed(value, -SPEED_STEP)) } + Text( + "%.2f".format(value), + modifier = Modifier.padding(horizontal = 16.dp), + fontSize = 16.sp, + fontWeight = FontWeight.Medium, + ) + StepperButton("+") { onChange(stepSpeed(value, SPEED_STEP)) } + } +} + +private fun stepSpeed(value: Double, delta: Double): Double = + (round((value + delta) * 100.0) / 100.0).coerceIn(SPEED_MIN, SPEED_MAX) + +/* ====================================================================== */ +/* 下面这些是所有设置类页面共用的零件(同包内其它 4 个屏幕也在用) */ +/* ====================================================================== */ + +/** 思考强度选项(和旧版 Settings.tsx / ModelPicker.tsx 完全一致) */ +val ThinkingLevels: List> = listOf( + "auto" to "自动", + "off" to "关", + "low" to "低", + "medium" to "中", + "high" to "高", +) + +val ThinkingHints: Map = mapOf( + "auto" to "不干预,由模型自己决定要不要想。", + "off" to "方舟:thinking=disabled;OpenAI 推理模型:reasoning_effort=minimal。回答最快。", + "low" to "方舟:thinking=enabled;OpenAI:reasoning_effort=low。", + "medium" to "方舟:thinking=enabled;OpenAI:reasoning_effort=medium。", + "high" to "方舟:thinking=enabled;OpenAI:reasoning_effort=high。想得最久、最慢,难题用。", +) + +/** + * 二级页面的标题栏:返回箭头 + 标题。 + * 返回一律回聊天页 —— 这几个页面都是从抽屉进来的"旁路",回去就是对话。 + */ +@Composable +fun ScreenHeader(title: String, onBack: () -> Unit, trailing: @Composable () -> Unit = {}) { + Row( + Modifier + .fillMaxWidth() + .background(doubaoBg()) + .padding(horizontal = 6.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + Modifier.size(42.dp).clip(CircleShape).clickable(onClick = onBack), + contentAlignment = Alignment.Center, + ) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回", tint = doubaoText(), modifier = Modifier.size(22.dp)) + } + Spacer(Modifier.width(2.dp)) + Text(title, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = doubaoText()) + Spacer(Modifier.weight(1f)) + trailing() + Spacer(Modifier.width(8.dp)) + } +} + +/** + * 设置项卡片。 + * + * 豆包的做法是**纯白底 + 浅灰卡片**(不是浅灰底 + 白卡片), + * 所以这里用 doubaoCard() 当底色、去掉描边 —— 在一堆系统设置里一眼就认得出是豆包。 + */ +@Composable +fun SettingsCard(title: String? = null, content: @Composable () -> Unit) { + Column( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(doubaoCard()) + .padding(16.dp), + ) { + if (!title.isNullOrBlank()) { + SectionTitle(title) + Spacer(Modifier.height(10.dp)) + } + content() + } +} + +@Composable +fun SectionTitle(text: String) { + Text(text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = doubaoText()) +} + +@Composable +fun FormLabel(text: String) { + Text(text, fontSize = 13.sp, color = doubaoTextSecondary()) +} + +@Composable +fun FormHint(text: String) { + Text( + text, + modifier = Modifier.padding(top = 6.dp), + fontSize = 11.sp, + lineHeight = 16.sp, + color = doubaoTextSecondary(), + ) +} + +/** + * 统一样式的输入框。trailing 用来塞"显示/隐藏密码"这类按钮。 + * 用 TextField 而非 OutlinedTextField:整页都是卡片,再套一圈描边会显得很碎。 + */ +@Composable +fun FormField( + value: String, + onValue: (String) -> Unit, + placeholder: String = "", + password: Boolean = false, + singleLine: Boolean = true, + minLines: Int = 1, + trailing: @Composable (() -> Unit)? = null, +) { + TextField( + value = value, + onValueChange = onValue, + modifier = Modifier.fillMaxWidth().padding(top = 6.dp), + placeholder = { + Text(placeholder, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + }, + singleLine = singleLine, + minLines = minLines, + visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None, + trailingIcon = trailing, + shape = RoundedCornerShape(12.dp), + textStyle = TextStyle(fontSize = 14.sp), + colors = TextFieldDefaults.colors( + focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant, + unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant, + disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + disabledIndicatorColor = Color.Transparent, + ), + ) +} + +/** 一行开关:标题 + 副标题 + 右侧 Switch(点整行也能切) */ +@Composable +fun FormSwitch(title: String, sub: String, checked: Boolean, onChange: (Boolean) -> Unit) { + Row( + Modifier.fillMaxWidth().clickable { onChange(!checked) }.padding(vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(title, fontSize = 14.sp) + if (sub.isNotBlank()) { + Text(sub, fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + Switch(checked = checked, onCheckedChange = onChange) + } +} + +/** + * 单选分段按钮。内核里的取值是英文 key(ark/openai、open/restricted), + * 界面显示中文 label,所以这里传 Pair(key, label) 而不是只传字符串。 + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SegmentedOptions( + options: List>, + selected: String, + onSelect: (String) -> Unit, +) { + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { + options.forEachIndexed { index, (key, label) -> + SegmentedButton( + selected = key == selected, + onClick = { onSelect(key) }, + shape = SegmentedButtonDefaults.itemShape(index = index, count = options.size), + label = { Text(label, fontSize = 13.sp, maxLines = 1) }, + ) + } + } +} + +/** + * 提供商显示名:把括号里的补充说明去掉,chip 里才排得下。 + * 例:'Kimi(月之暗面)' → 'Kimi','通义千问(阿里云)' → '通义千问'。 + */ +fun shortProviderLabel(label: String, key: String): String { + val base = label.substringBefore("(").substringBefore("(").trim() + return base.ifBlank { key } +} + +/** + * 自动折行的 chip 组(FlowRow 的薄封装)。 + * + * 为什么单开一个函数:FlowRow 属于 ExperimentalLayoutApi,opt-in 注解得写在 + * 用到它的地方;把它收成一个函数,其它屏幕就不用各自 opt-in 了。 + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun WrapRow(perRow: Int = 3, content: @Composable () -> Unit) { + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(2.dp), + maxItemsInEachRow = perRow, + ) { content() } +} + +/** 「− 数值 +」步进器:maxRounds 这种小整数用滑块太糙、用键盘太麻烦 */ +@Composable +fun StepperRow(value: Int, onChange: (Int) -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically) { + StepperButton("−") { onChange(value - 1) } + Text( + value.toString(), + modifier = Modifier.padding(horizontal = 16.dp), + fontSize = 16.sp, + fontWeight = FontWeight.Medium, + ) + StepperButton("+") { onChange(value + 1) } + } +} + +@Composable +private fun StepperButton(label: String, onClick: () -> Unit) { + Surface( + modifier = Modifier.size(36.dp).clip(CircleShape).clickable(onClick = onClick), + color = MaterialTheme.colorScheme.surfaceVariant, + shape = CircleShape, + ) { + Box(contentAlignment = Alignment.Center) { Text(label, fontSize = 18.sp) } + } +} + +/** 圆头像:用彩色圆 + 首字代替真图片(对齐旧版的 avatar 资源语义,但不引入 drawable) */ +@Composable +fun AvatarCircle(name: String, avatar: String, size: Int = 40, selected: Boolean = false) { + // 选中态用"外圈描边"表达,而不是把圆画大 —— 大小一变,旁边的头像会跟着跳位 + Box( + modifier = Modifier + .size((size + 6).dp) + .clip(CircleShape) + .background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent), + contentAlignment = Alignment.Center, + ) { + Box( + Modifier + .size(size.dp) + .clip(CircleShape) + .background(AvatarColors[avatar] ?: AvatarColors.getValue("custom")), + contentAlignment = Alignment.Center, + ) { + Text( + AvatarGlyphs[avatar] ?: name.take(1).ifBlank { "?" }, + color = Color.White, + fontSize = (size * 0.42f).sp, + fontWeight = FontWeight.Medium, + ) + } + } +} + +/** 可选头像(顺序跟内核 defaults.AVATAR_KEYS 一致,方便对照) */ +val AvatarKeys: List = listOf( + "doubao", "coder", "writer", "analyst", "cat", "robot", "star", "cloud", "custom", +) + +/** 彩色圆 + 首字代表头像:不引入位图资源,也能一眼区分不同智能体 */ +val AvatarColors: Map = mapOf( + "doubao" to Color(0xFF2B7BFF), + "coder" to Color(0xFF3AA76D), + "writer" to Color(0xFF9B59D0), + "analyst" to Color(0xFFE08A1E), + "cat" to Color(0xFFEC6A8C), + "robot" to Color(0xFF5A6472), + "star" to Color(0xFFF2B01E), + "cloud" to Color(0xFF39A6C8), + "custom" to Color(0xFF1F2329), +) + +val AvatarGlyphs: Map = mapOf( + "doubao" to "豆", + "coder" to "码", + "writer" to "笔", + "analyst" to "析", + "cat" to "猫", + "robot" to "机", + "star" to "星", + "cloud" to "云", + "custom" to "自", +) + +/** 环形的选中标记(跟 SegmentedButton 里的勾保持同一套语义) */ +@Composable +fun CheckMark(visible: Boolean) { + if (visible) { + Icon( + Icons.Filled.Check, + "已选中", + modifier = Modifier.size(18.dp), + tint = MaterialTheme.colorScheme.primary, + ) + } +} + +/** 可点的一行:标题 + 右侧值 + 箭头(「我的」页里的设置项都用它) */ +@Composable +fun NavRow(label: String, value: String = "", onClick: () -> Unit) { + Row( + Modifier.fillMaxWidth().clickable(onClick = onClick).padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(label, fontSize = 14.sp) + Spacer(Modifier.weight(1f)) + if (value.isNotBlank()) { + Text(value, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Icon( + Icons.AutoMirrored.Filled.KeyboardArrowRight, + null, + modifier = Modifier.size(18.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/* ------------------------------ 设置草稿 ------------------------------ */ + +/** + * 设置页的本地草稿。 + * + * 为什么单独搞一个类型而不是直接 copy Settings: + * - Settings 里有 tools 开关的嵌套读法(pythonEnabled/mcpEnabled 是从 tools{} 里摊平的), + * 草稿只需要"能编辑 + 能生成补丁"这俩能力; + * - 不想让界面代码碰到 JSON 形状,补丁的组装统一在 saveSettings 之前做。 + */ +internal data class SettingsDraft( + val provider: String, + val baseUrl: String, + val model: String, + val apiKey: String, + val temperature: Double, + val maxRounds: Int, + val thinkingLevel: String, + val toolsDir: String, + val systemPrompt: String, + val pythonEnabled: Boolean, + val mcpEnabled: Boolean, + val nickname: String, + /** + * 语音草稿:直接复用 SpeechSettings(不可变,逐字段 copy 就行), + * 这样界面改哪个字段、补丁里出现哪些键,是一一对应的,不用再抄一层类型。 + */ + val speech: SpeechSettings, + /** + * 火山 Access Token。单独拎出来、且**永远从空开始**,理由跟 apiKey 完全一样: + * 接口回的是掩码(••••••••),把它填进输入框再保存就等于用八个点覆盖真 Token。 + * 所以它不参与 diff,只有"用户真敲了非空且不像掩码"时才进补丁。 + */ + val volcToken: String, +) { + /** + * 切提供商时顺带把 baseUrl / model 换成新提供商的预设。 + * 旧版就是这么干的:不换的话会拿"方舟的地址 + OpenAI 的模型"发请求,必然 404。 + */ + fun switchProvider(key: String, vm: AppViewModel): SettingsDraft { + if (key == provider) return this + val preset = vm.state.providers[key] + return copy( + provider = key, + baseUrl = preset?.baseUrl ?: baseUrl, + model = preset?.defaultModel ?: model, + ) + } + + /** + * 只生成"真正改动过"的字段,并且**绝不下发空的关键值**。 + * + * 为什么必须这样:/api/settings 是浅合并,多下发一个空字符串就等于把它清空。 + * 之前就是全量下发,一旦草稿还没从服务端同步好(首屏 state 还在路上时点保存), + * 整份配置就被空值覆盖了 —— 表现就是"一保存设置就清空"。 + * 现在改成 diff:没动过的字段根本不提,服务端自然保持原样。 + */ + fun changesAgainst(s: Settings): MutableMap { + val patch = mutableMapOf() + + if (provider != s.provider) patch["provider"] = provider + // baseUrl / model 空值一律跳过:那是"没填"而不是"要清空" + if (baseUrl.trim().isNotEmpty() && baseUrl.trim() != s.baseUrl) patch["baseUrl"] = baseUrl.trim() + if (model.trim().isNotEmpty() && model.trim() != s.model) patch["model"] = model.trim() + if (temperature != s.temperature) patch["temperature"] = temperature + if (maxRounds != s.maxRounds) patch["maxRounds"] = maxRounds + if (thinkingLevel != s.thinkingLevel) patch["thinkingLevel"] = thinkingLevel + if (toolsDir.trim() != s.toolsDir) patch["toolsDir"] = toolsDir.trim() + if (systemPrompt != s.systemPrompt) patch["systemPrompt"] = systemPrompt + if (nickname.isNotBlank() && nickname != s.nickname) patch["nickname"] = nickname + if (pythonEnabled != s.pythonEnabled || mcpEnabled != s.mcpEnabled) { + patch["tools"] = mapOf("python" to pythonEnabled, "mcp" to mcpEnabled) + } + // API Key:只有用户真的敲了才发,空白代表"不改" + if (apiKey.isNotBlank()) patch["apiKey"] = apiKey.trim() + + // ---- 语音 ---- + // 逐个子键比对,只有真变了的才进 speech 子对象:整段下发会把用户没碰过的键 + // (尤其是 volcToken 的掩码)一起送回去 —— 首屏草稿没同步好时那就等于清配置。 + val base = s.speech + val sp = mutableMapOf() + if (speech.ttsEngine != base.ttsEngine) sp["ttsEngine"] = speech.ttsEngine + // 音色留空是"回落到引擎默认音色",是个有效取值,所以照样下发 + if (speech.ttsVoice != base.ttsVoice) sp["ttsVoice"] = speech.ttsVoice + if (speech.ttsSpeed != base.ttsSpeed) sp["ttsSpeed"] = speech.ttsSpeed + if (speech.autoRead != base.autoRead) sp["autoRead"] = speech.autoRead + if (speech.sttEngine != base.sttEngine) sp["sttEngine"] = speech.sttEngine + if (speech.sttModel != base.sttModel) sp["sttModel"] = speech.sttModel + if (speech.sttLanguage != base.sttLanguage) sp["sttLanguage"] = speech.sttLanguage + if (speech.volcAppId != base.volcAppId) sp["volcAppId"] = speech.volcAppId + if (speech.ttsModel != base.ttsModel) sp["ttsModel"] = speech.ttsModel + // ★ 密钥:空白 = 不改,掩码 = 也不改。openaiApiKey 界面没有入口(复用对话那把 Key), + // 所以它压根不进草稿 —— 这比"进了草稿再过滤掉"更保险 + secretOrNull(volcToken)?.let { sp["volcToken"] = it } + // 界面没有入口的键(volcCluster / volcEncoding / openaiBaseUrl)故意不参与 diff: + // 它们只可能来自配置文件或环境变量,界面不该在任何情况下把它们改掉 + if (sp.isNotEmpty()) patch["speech"] = sp + return patch + } + + companion object { + fun from(s: Settings) = SettingsDraft( + provider = s.provider, + baseUrl = s.baseUrl, + model = s.model, + // ★ 一律留空:接口回的是掩码,回填会把它当真实 Key 保存(见 SettingsScreen 头注释) + apiKey = "", + temperature = s.temperature, + maxRounds = s.maxRounds, + thinkingLevel = s.thinkingLevel, + toolsDir = s.toolsDir, + systemPrompt = s.systemPrompt, + pythonEnabled = s.pythonEnabled, + mcpEnabled = s.mcpEnabled, + nickname = s.nickname, + // 语音配置整份照搬:diff 时逐键比对,改没改一目了然。 + // ★ 引擎名做个归一化:万一配置里是个空串或没见过的值(比如手工改过 settings.json), + // 界面上一张卡片都不会高亮,看上去就像"语音设置被清空了"。 + // 归一化成 'system' 之后至少有明确选中项,而且保存时会把坏值修回正常值。 + speech = s.speech.copy( + ttsEngine = normalizeEngine(s.speech.ttsEngine, TtsEngines.map { it.first }), + sttEngine = normalizeEngine(s.speech.sttEngine, SttEngines.map { it.first }), + ), + volcToken = "", + ) + } +} + +/** 引擎名不在候选里(空串 / 手改过 / 老版本遗留)时回落到列表第一项,保证界面总有高亮 */ +private fun normalizeEngine(value: String, known: List): String { + val v = value.trim() + return if (v in known) v else known.first() +} + +/** + * 密钥类字段的出口检查:空白 = "不改",整串点号 = 内核回传的掩码(同样"不改")。 + * + * 为什么收成一个函数:这类字段以后只会变多(每接一家厂商就多一个), + * 判断散在各处迟早漏一个 —— 漏掉的那次就是"一保存就把密钥写坏"。 + */ +private fun secretOrNull(raw: String): String? { + val v = raw.trim() + if (v.isEmpty()) return null + // 掩码未必正好 8 个点(换内核版本可能变),所以按"整串都是点号"来判断 + if (v.all { it == '•' }) return null + return v +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/SkillsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/SkillsScreen.kt new file mode 100644 index 0000000..4b133ed --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/SkillsScreen.kt @@ -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(null) } + val toolArgs = remember { mutableStateOf>(emptyMap()) } + val toolResults = remember { mutableStateOf>(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 diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/TerminalScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/TerminalScreen.kt new file mode 100644 index 0000000..cb9ab79 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/TerminalScreen.kt @@ -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), + ) + } + } + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/theme/Theme.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/theme/Theme.kt new file mode 100644 index 0000000..56ec277 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/theme/Theme.kt @@ -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, + ) +} diff --git a/android/app/src/main/java/com/termux/terminal/ByteQueue.java b/android/app/src/main/java/com/termux/terminal/ByteQueue.java new file mode 100644 index 0000000..adfdfa8 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/ByteQueue.java @@ -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. + *

+ * 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; + } +} diff --git a/android/app/src/main/java/com/termux/terminal/JNI.java b/android/app/src/main/java/com/termux/terminal/JNI.java new file mode 100644 index 0000000..e2fc477 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/JNI.java @@ -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. + *

+ * 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); + +} diff --git a/android/app/src/main/java/com/termux/terminal/KeyHandler.java b/android/app/src/main/java/com/termux/terminal/KeyHandler.java new file mode 100644 index 0000000..254f5e3 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/KeyHandler.java @@ -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 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 keypad home key + // t_K3 keypad page-up key + // t_K4 keypad end key + // t_K5 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 and keys. + // normal vt100 ~ + // t_k1 [11~ OP *-xterm* + // t_k2 [12~ OQ *-xterm* + // t_k3 [13~ OR *-xterm* + // t_k4 [14~ OS *-xterm* + // t_kh [7~ OH *-xterm* + // t_@7 [4~ OF *-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; + } +} diff --git a/android/app/src/main/java/com/termux/terminal/Logger.java b/android/app/src/main/java/com/termux/terminal/Logger.java new file mode 100644 index 0000000..d4d502e --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/Logger.java @@ -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; + } + +} diff --git a/android/app/src/main/java/com/termux/terminal/TerminalBuffer.java b/android/app/src/main/java/com/termux/terminal/TerminalBuffer.java new file mode 100644 index 0000000..21d6518 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TerminalBuffer.java @@ -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. + *

+ * 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. + * + *

+     * - 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         ]
+     * 
+ * + * @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; + } + +} diff --git a/android/app/src/main/java/com/termux/terminal/TerminalColorScheme.java b/android/app/src/main/java/com/termux/terminal/TerminalColorScheme.java new file mode 100644 index 0000000..4088781 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TerminalColorScheme.java @@ -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 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; + } + } + +} diff --git a/android/app/src/main/java/com/termux/terminal/TerminalColors.java b/android/app/src/main/java/com/termux/terminal/TerminalColors.java new file mode 100644 index 0000000..25135a2 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TerminalColors.java @@ -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 + *

+ * 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:// where , , := 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 + )); + } + +} diff --git a/android/app/src/main/java/com/termux/terminal/TerminalEmulator.java b/android/app/src/main/java/com/termux/terminal/TerminalEmulator.java new file mode 100644 index 0000000..8d7eaa8 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TerminalEmulator.java @@ -0,0 +1,2605 @@ +package com.termux.terminal; + +import android.util.Base64; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Locale; +import java.util.Objects; +import java.util.Stack; + +/** + * Renders text into a screen. Contains all the terminal-specific knowledge and state. Emulates a subset of the X Window + * System xterm terminal, which in turn is an emulator for a subset of the Digital Equipment Corporation vt100 terminal. + *

+ * References: + *

    + *
  • http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  • + *
  • http://en.wikipedia.org/wiki/ANSI_escape_code
  • + *
  • http://man.he.net/man4/console_codes
  • + *
  • http://bazaar.launchpad.net/~leonerd/libvterm/trunk/view/head:/src/state.c
  • + *
  • http://www.columbia.edu/~kermit/k95manual/iso2022.html
  • + *
  • http://www.vt100.net/docs/vt510-rm/chapter4
  • + *
  • http://en.wikipedia.org/wiki/ISO/IEC_2022 - for 7-bit and 8-bit GL GR explanation
  • + *
  • http://bjh21.me.uk/all-escapes/all-escapes.txt - extensive!
  • + *
  • http://woldlab.caltech.edu/~diane/kde4.10/workingdir/kubuntu/konsole/doc/developer/old-documents/VT100/techref. + * html - document for konsole - accessible!
  • + *
+ */ +public final class TerminalEmulator { + + /** Log unknown or unimplemented escape sequences received from the shell process. */ + private static final boolean LOG_ESCAPE_SEQUENCES = false; + + public static final int MOUSE_LEFT_BUTTON = 0; + + /** Mouse moving while having left mouse button pressed. */ + public static final int MOUSE_LEFT_BUTTON_MOVED = 32; + public static final int MOUSE_WHEELUP_BUTTON = 64; + public static final int MOUSE_WHEELDOWN_BUTTON = 65; + + /** Used for invalid data - http://en.wikipedia.org/wiki/Replacement_character#Replacement_character */ + public static final int UNICODE_REPLACEMENT_CHAR = 0xFFFD; + + /** Escape processing: Not currently in an escape sequence. */ + private static final int ESC_NONE = 0; + /** Escape processing: Have seen an ESC character - proceed to {@link #doEsc(int)} */ + private static final int ESC = 1; + /** Escape processing: Have seen ESC POUND */ + private static final int ESC_POUND = 2; + /** Escape processing: Have seen ESC and a character-set-select ( char */ + private static final int ESC_SELECT_LEFT_PAREN = 3; + /** Escape processing: Have seen ESC and a character-set-select ) char */ + private static final int ESC_SELECT_RIGHT_PAREN = 4; + /** Escape processing: "ESC [" or CSI (Control Sequence Introducer). */ + private static final int ESC_CSI = 6; + /** Escape processing: ESC [ ? */ + private static final int ESC_CSI_QUESTIONMARK = 7; + /** Escape processing: ESC [ $ */ + private static final int ESC_CSI_DOLLAR = 8; + /** Escape processing: ESC % */ + private static final int ESC_PERCENT = 9; + /** Escape processing: ESC ] (AKA OSC - Operating System Controls) */ + private static final int ESC_OSC = 10; + /** Escape processing: ESC ] (AKA OSC - Operating System Controls) ESC */ + private static final int ESC_OSC_ESC = 11; + /** Escape processing: ESC [ > */ + private static final int ESC_CSI_BIGGERTHAN = 12; + /** Escape procession: "ESC P" or Device Control String (DCS) */ + private static final int ESC_P = 13; + /** Escape processing: CSI > */ + private static final int ESC_CSI_QUESTIONMARK_ARG_DOLLAR = 14; + /** Escape processing: CSI $ARGS ' ' */ + private static final int ESC_CSI_ARGS_SPACE = 15; + /** Escape processing: CSI $ARGS '*' */ + private static final int ESC_CSI_ARGS_ASTERIX = 16; + /** Escape processing: CSI " */ + private static final int ESC_CSI_DOUBLE_QUOTE = 17; + /** Escape processing: CSI ' */ + private static final int ESC_CSI_SINGLE_QUOTE = 18; + /** Escape processing: CSI ! */ + private static final int ESC_CSI_EXCLAMATION = 19; + /** Escape processing: "ESC _" or Application Program Command (APC). */ + private static final int ESC_APC = 20; + /** Escape processing: "ESC _" or Application Program Command (APC), followed by Escape. */ + private static final int ESC_APC_ESCAPE = 21; + /** Escape processing: ESC [ */ + private static final int ESC_CSI_UNSUPPORTED_PARAMETER_BYTE = 22; + /** Escape processing: ESC [ */ + private static final int ESC_CSI_UNSUPPORTED_INTERMEDIATE_BYTE = 23; + + /** The number of parameter arguments including colon separated sub-parameters. */ + private static final int MAX_ESCAPE_PARAMETERS = 32; + + /** Needs to be large enough to contain reasonable OSC 52 pastes. */ + private static final int MAX_OSC_STRING_LENGTH = 8192; + + /** DECSET 1 - application cursor keys. */ + private static final int DECSET_BIT_APPLICATION_CURSOR_KEYS = 1; + private static final int DECSET_BIT_REVERSE_VIDEO = 1 << 1; + /** + * http://www.vt100.net/docs/vt510-rm/DECOM: "When DECOM is set, the home cursor position is at the upper-left + * corner of the screen, within the margins. The starting point for line numbers depends on the current top margin + * setting. The cursor cannot move outside of the margins. When DECOM is reset, the home cursor position is at the + * upper-left corner of the screen. The starting point for line numbers is independent of the margins. The cursor + * can move outside of the margins." + */ + private static final int DECSET_BIT_ORIGIN_MODE = 1 << 2; + /** + * http://www.vt100.net/docs/vt510-rm/DECAWM: "If the DECAWM function is set, then graphic characters received when + * the cursor is at the right border of the page appear at the beginning of the next line. Any text on the page + * scrolls up if the cursor is at the end of the scrolling region. If the DECAWM function is reset, then graphic + * characters received when the cursor is at the right border of the page replace characters already on the page." + */ + private static final int DECSET_BIT_AUTOWRAP = 1 << 3; + /** DECSET 25 - if the cursor should be enabled, {@link #isCursorEnabled()}. */ + private static final int DECSET_BIT_CURSOR_ENABLED = 1 << 4; + private static final int DECSET_BIT_APPLICATION_KEYPAD = 1 << 5; + /** DECSET 1000 - if to report mouse press&release events. */ + private static final int DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE = 1 << 6; + /** DECSET 1002 - like 1000, but report moving mouse while pressed. */ + private static final int DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT = 1 << 7; + /** DECSET 1004 - NOT implemented. */ + private static final int DECSET_BIT_SEND_FOCUS_EVENTS = 1 << 8; + /** DECSET 1006 - SGR-like mouse protocol (the modern sane choice). */ + private static final int DECSET_BIT_MOUSE_PROTOCOL_SGR = 1 << 9; + /** DECSET 2004 - see {@link #paste(String)} */ + private static final int DECSET_BIT_BRACKETED_PASTE_MODE = 1 << 10; + /** Toggled with DECLRMM - http://www.vt100.net/docs/vt510-rm/DECLRMM */ + private static final int DECSET_BIT_LEFTRIGHT_MARGIN_MODE = 1 << 11; + /** Not really DECSET bit... - http://www.vt100.net/docs/vt510-rm/DECSACE */ + private static final int DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE = 1 << 12; + + + private String mTitle; + private final Stack mTitleStack = new Stack<>(); + + /** The cursor position. Between (0,0) and (mRows-1, mColumns-1). */ + private int mCursorRow, mCursorCol; + + /** The number of character rows and columns in the terminal screen. */ + public int mRows, mColumns; + + /** Size of a terminal cell in pixels. */ + private int mCellWidthPixels, mCellHeightPixels; + + /** The number of terminal transcript rows that can be scrolled back to. */ + public static final int TERMINAL_TRANSCRIPT_ROWS_MIN = 100; + public static final int TERMINAL_TRANSCRIPT_ROWS_MAX = 50000; + public static final int DEFAULT_TERMINAL_TRANSCRIPT_ROWS = 2000; + + + /* The supported terminal cursor styles. */ + + public static final int TERMINAL_CURSOR_STYLE_BLOCK = 0; + public static final int TERMINAL_CURSOR_STYLE_UNDERLINE = 1; + public static final int TERMINAL_CURSOR_STYLE_BAR = 2; + public static final int DEFAULT_TERMINAL_CURSOR_STYLE = TERMINAL_CURSOR_STYLE_BLOCK; + public static final Integer[] TERMINAL_CURSOR_STYLES_LIST = new Integer[]{TERMINAL_CURSOR_STYLE_BLOCK, TERMINAL_CURSOR_STYLE_UNDERLINE, TERMINAL_CURSOR_STYLE_BAR}; + + /** The terminal cursor styles. */ + private int mCursorStyle = DEFAULT_TERMINAL_CURSOR_STYLE; + + + /** The normal screen buffer. Stores the characters that appear on the screen of the emulated terminal. */ + private final TerminalBuffer mMainBuffer; + /** + * The alternate screen buffer, exactly as large as the display and contains no additional saved lines (so that when + * the alternate screen buffer is active, you cannot scroll back to view saved lines). + *

+ * See http://www.xfree86.org/current/ctlseqs.html#The%20Alternate%20Screen%20Buffer + */ + final TerminalBuffer mAltBuffer; + /** The current screen buffer, pointing at either {@link #mMainBuffer} or {@link #mAltBuffer}. */ + private TerminalBuffer mScreen; + + /** The terminal session this emulator is bound to. */ + private final TerminalOutput mSession; + + TerminalSessionClient mClient; + + /** Keeps track of the current argument of the current escape sequence. Ranges from 0 to MAX_ESCAPE_PARAMETERS-1. */ + private int mArgIndex; + /** Holds the arguments of the current escape sequence. */ + private final int[] mArgs = new int[MAX_ESCAPE_PARAMETERS]; + /** Holds the bit flags which arguments are sub parameters (after a colon) - bit N is set if mArgs[N] is a sub parameter. */ + private int mArgsSubParamsBitSet = 0; + + /** Holds OSC and device control arguments, which can be strings. */ + private final StringBuilder mOSCOrDeviceControlArgs = new StringBuilder(); + + /** + * True if the current escape sequence should continue, false if the current escape sequence should be terminated. + * Used when parsing a single character. + */ + private boolean mContinueSequence; + + /** The current state of the escape sequence state machine. One of the ESC_* constants. */ + private int mEscapeState; + + private final SavedScreenState mSavedStateMain = new SavedScreenState(); + private final SavedScreenState mSavedStateAlt = new SavedScreenState(); + + /** http://www.vt100.net/docs/vt102-ug/table5-15.html */ + private boolean mUseLineDrawingG0, mUseLineDrawingG1, mUseLineDrawingUsesG0 = true; + + /** + * @see TerminalEmulator#mapDecSetBitToInternalBit(int) + */ + private int mCurrentDecSetFlags, mSavedDecSetFlags; + + /** + * If insert mode (as opposed to replace mode) is active. In insert mode new characters are inserted, pushing + * existing text to the right. Characters moved past the right margin are lost. + */ + private boolean mInsertMode; + + /** An array of tab stops. mTabStop[i] is true if there is a tab stop set for column i. */ + private boolean[] mTabStop; + + /** + * Top margin of screen for scrolling ranges from 0 to mRows-2. Bottom margin ranges from mTopMargin + 2 to mRows + * (Defines the first row after the scrolling region). Left/right margin in [0, mColumns]. + */ + private int mTopMargin, mBottomMargin, mLeftMargin, mRightMargin; + + /** + * If the next character to be emitted will be automatically wrapped to the next line. Used to disambiguate the case + * where the cursor is positioned on the last column (mColumns-1). When standing there, a written character will be + * output in the last column, the cursor not moving but this flag will be set. When outputting another character + * this will move to the next line. + */ + private boolean mAboutToAutoWrap; + + /** + * If the cursor blinking is enabled. It requires cursor itself to be enabled, which is controlled + * byt whether {@link #DECSET_BIT_CURSOR_ENABLED} bit is set or not. + */ + private boolean mCursorBlinkingEnabled; + + /** + * If currently cursor should be in a visible state or not if {@link #mCursorBlinkingEnabled} + * is {@code true}. + */ + private boolean mCursorBlinkState; + + /** + * Current foreground, background and underline colors. Can either be a color index in [0,259] or a truecolor (24-bit) value. + * For a 24-bit value the top byte (0xff000000) is set. + * + *

Note that the underline color is currently parsed but not yet used during rendering. + * + * @see TextStyle + */ + int mForeColor, mBackColor, mUnderlineColor; + + /** Current {@link TextStyle} effect. */ + int mEffect; + + /** + * The number of scrolled lines since last calling {@link #clearScrollCounter()}. Used for moving selection up along + * with the scrolling text. + */ + private int mScrollCounter = 0; + + private byte mUtf8ToFollow, mUtf8Index; + private final byte[] mUtf8InputBuffer = new byte[4]; + private int mLastEmittedCodePoint = -1; + + public final TerminalColors mColors = new TerminalColors(); + + private static final String LOG_TAG = "TerminalEmulator"; + + private boolean isDecsetInternalBitSet(int bit) { + return (mCurrentDecSetFlags & bit) != 0; + } + + private void setDecsetinternalBit(int internalBit, boolean set) { + if (set) { + // The mouse modes are mutually exclusive. + if (internalBit == DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE) { + setDecsetinternalBit(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT, false); + } else if (internalBit == DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT) { + setDecsetinternalBit(DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE, false); + } + } + if (set) { + mCurrentDecSetFlags |= internalBit; + } else { + mCurrentDecSetFlags &= ~internalBit; + } + } + + static int mapDecSetBitToInternalBit(int decsetBit) { + switch (decsetBit) { + case 1: + return DECSET_BIT_APPLICATION_CURSOR_KEYS; + case 5: + return DECSET_BIT_REVERSE_VIDEO; + case 6: + return DECSET_BIT_ORIGIN_MODE; + case 7: + return DECSET_BIT_AUTOWRAP; + case 25: + return DECSET_BIT_CURSOR_ENABLED; + case 66: + return DECSET_BIT_APPLICATION_KEYPAD; + case 69: + return DECSET_BIT_LEFTRIGHT_MARGIN_MODE; + case 1000: + return DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE; + case 1002: + return DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT; + case 1004: + return DECSET_BIT_SEND_FOCUS_EVENTS; + case 1006: + return DECSET_BIT_MOUSE_PROTOCOL_SGR; + case 2004: + return DECSET_BIT_BRACKETED_PASTE_MODE; + default: + return -1; + // throw new IllegalArgumentException("Unsupported decset: " + decsetBit); + } + } + + public TerminalEmulator(TerminalOutput session, int columns, int rows, int cellWidthPixels, int cellHeightPixels, Integer transcriptRows, TerminalSessionClient client) { + mSession = session; + mScreen = mMainBuffer = new TerminalBuffer(columns, getTerminalTranscriptRows(transcriptRows), rows); + mAltBuffer = new TerminalBuffer(columns, rows, rows); + mClient = client; + mRows = rows; + mColumns = columns; + mCellWidthPixels = cellWidthPixels; + mCellHeightPixels = cellHeightPixels; + mTabStop = new boolean[mColumns]; + reset(); + } + + public void updateTerminalSessionClient(TerminalSessionClient client) { + mClient = client; + setCursorStyle(); + setCursorBlinkState(true); + } + + public TerminalBuffer getScreen() { + return mScreen; + } + + public boolean isAlternateBufferActive() { + return mScreen == mAltBuffer; + } + + private int getTerminalTranscriptRows(Integer transcriptRows) { + if (transcriptRows == null || transcriptRows < TERMINAL_TRANSCRIPT_ROWS_MIN || transcriptRows > TERMINAL_TRANSCRIPT_ROWS_MAX) + return DEFAULT_TERMINAL_TRANSCRIPT_ROWS; + else + return transcriptRows; + } + + /** + * @param mouseButton one of the MOUSE_* constants of this class. + */ + public void sendMouseEvent(int mouseButton, int column, int row, boolean pressed) { + if (column < 1) column = 1; + if (column > mColumns) column = mColumns; + if (row < 1) row = 1; + if (row > mRows) row = mRows; + + if (mouseButton == MOUSE_LEFT_BUTTON_MOVED && !isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT)) { + // Do not send tracking. + } else if (isDecsetInternalBitSet(DECSET_BIT_MOUSE_PROTOCOL_SGR)) { + mSession.write(String.format("\033[<%d;%d;%d" + (pressed ? 'M' : 'm'), mouseButton, column, row)); + } else { + mouseButton = pressed ? mouseButton : 3; // 3 for release of all buttons. + // Clip to screen, and clip to the limits of 8-bit data. + boolean out_of_bounds = column > 255 - 32 || row > 255 - 32; + if (!out_of_bounds) { + byte[] data = {'\033', '[', 'M', (byte) (32 + mouseButton), (byte) (32 + column), (byte) (32 + row)}; + mSession.write(data, 0, data.length); + } + } + } + + public void resize(int columns, int rows, int cellWidthPixels, int cellHeightPixels) { + this.mCellWidthPixels = cellWidthPixels; + this.mCellHeightPixels = cellHeightPixels; + + if (mRows == rows && mColumns == columns) { + return; + } else if (columns < 2 || rows < 2) { + throw new IllegalArgumentException("rows=" + rows + ", columns=" + columns); + } + + if (mRows != rows) { + mRows = rows; + mTopMargin = 0; + mBottomMargin = mRows; + } + if (mColumns != columns) { + int oldColumns = mColumns; + mColumns = columns; + boolean[] oldTabStop = mTabStop; + mTabStop = new boolean[mColumns]; + setDefaultTabStops(); + int toTransfer = Math.min(oldColumns, columns); + System.arraycopy(oldTabStop, 0, mTabStop, 0, toTransfer); + mLeftMargin = 0; + mRightMargin = mColumns; + } + + resizeScreen(); + } + + private void resizeScreen() { + final int[] cursor = {mCursorCol, mCursorRow}; + int newTotalRows = (mScreen == mAltBuffer) ? mRows : mMainBuffer.mTotalRows; + mScreen.resize(mColumns, mRows, newTotalRows, cursor, getStyle(), isAlternateBufferActive()); + mCursorCol = cursor[0]; + mCursorRow = cursor[1]; + } + + public int getCursorRow() { + return mCursorRow; + } + + public int getCursorCol() { + return mCursorCol; + } + + /** Get the terminal cursor style. It will be one of {@link #TERMINAL_CURSOR_STYLES_LIST} */ + public int getCursorStyle() { + return mCursorStyle; + } + + /** Set the terminal cursor style. */ + public void setCursorStyle() { + Integer cursorStyle = null; + + if (mClient != null) + cursorStyle = mClient.getTerminalCursorStyle(); + + if (cursorStyle == null || !Arrays.asList(TERMINAL_CURSOR_STYLES_LIST).contains(cursorStyle)) + mCursorStyle = DEFAULT_TERMINAL_CURSOR_STYLE; + else + mCursorStyle = cursorStyle; + } + + public boolean isReverseVideo() { + return isDecsetInternalBitSet(DECSET_BIT_REVERSE_VIDEO); + } + + + + public boolean isCursorEnabled() { + return isDecsetInternalBitSet(DECSET_BIT_CURSOR_ENABLED); + } + public boolean shouldCursorBeVisible() { + if (!isCursorEnabled()) + return false; + else + return mCursorBlinkingEnabled ? mCursorBlinkState : true; + } + + public void setCursorBlinkingEnabled(boolean cursorBlinkingEnabled) { + this.mCursorBlinkingEnabled = cursorBlinkingEnabled; + } + + public void setCursorBlinkState(boolean cursorBlinkState) { + this.mCursorBlinkState = cursorBlinkState; + } + + + + public boolean isKeypadApplicationMode() { + return isDecsetInternalBitSet(DECSET_BIT_APPLICATION_KEYPAD); + } + + public boolean isCursorKeysApplicationMode() { + return isDecsetInternalBitSet(DECSET_BIT_APPLICATION_CURSOR_KEYS); + } + + /** If mouse events are being sent as escape codes to the terminal. */ + public boolean isMouseTrackingActive() { + return isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE) || isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT); + } + + private void setDefaultTabStops() { + for (int i = 0; i < mColumns; i++) + mTabStop[i] = (i & 7) == 0 && i != 0; + } + + /** + * Accept bytes (typically from the pseudo-teletype) and process them. + * + * @param buffer a byte array containing the bytes to be processed + * @param length the number of bytes in the array to process + */ + public void append(byte[] buffer, int length) { + for (int i = 0; i < length; i++) + processByte(buffer[i]); + } + + private void processByte(byte byteToProcess) { + if (mUtf8ToFollow > 0) { + if ((byteToProcess & 0b11000000) == 0b10000000) { + // 10xxxxxx, a continuation byte. + mUtf8InputBuffer[mUtf8Index++] = byteToProcess; + if (--mUtf8ToFollow == 0) { + byte firstByteMask = (byte) (mUtf8Index == 2 ? 0b00011111 : (mUtf8Index == 3 ? 0b00001111 : 0b00000111)); + int codePoint = (mUtf8InputBuffer[0] & firstByteMask); + for (int i = 1; i < mUtf8Index; i++) + codePoint = ((codePoint << 6) | (mUtf8InputBuffer[i] & 0b00111111)); + if (((codePoint <= 0b1111111) && mUtf8Index > 1) || (codePoint < 0b11111111111 && mUtf8Index > 2) + || (codePoint < 0b1111111111111111 && mUtf8Index > 3)) { + // Overlong encoding. + codePoint = UNICODE_REPLACEMENT_CHAR; + } + + mUtf8Index = mUtf8ToFollow = 0; + + if (codePoint >= 0x80 && codePoint <= 0x9F) { + // Sequence decoded to a C1 control character which we ignore. They are + // not used nowadays and increases the risk of messing up the terminal state + // on binary input. XTerm does not allow them in utf-8: + // "It is not possible to use a C1 control obtained from decoding the + // UTF-8 text" - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html + } else { + switch (Character.getType(codePoint)) { + case Character.UNASSIGNED: + case Character.SURROGATE: + codePoint = UNICODE_REPLACEMENT_CHAR; + } + processCodePoint(codePoint); + } + } + } else { + // Not a UTF-8 continuation byte so replace the entire sequence up to now with the replacement char: + mUtf8Index = mUtf8ToFollow = 0; + emitCodePoint(UNICODE_REPLACEMENT_CHAR); + // The Unicode Standard Version 6.2 – Core Specification + // (http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf): + // "If the converter encounters an ill-formed UTF-8 code unit sequence which starts with a valid first + // byte, but which does not continue with valid successor bytes (see Table 3-7), it must not consume the + // successor bytes as part of the ill-formed subsequence + // whenever those successor bytes themselves constitute part of a well-formed UTF-8 code unit + // subsequence." + processByte(byteToProcess); + } + } else { + if ((byteToProcess & 0b10000000) == 0) { // The leading bit is not set so it is a 7-bit ASCII character. + processCodePoint(byteToProcess); + return; + } else if ((byteToProcess & 0b11100000) == 0b11000000) { // 110xxxxx, a two-byte sequence. + mUtf8ToFollow = 1; + } else if ((byteToProcess & 0b11110000) == 0b11100000) { // 1110xxxx, a three-byte sequence. + mUtf8ToFollow = 2; + } else if ((byteToProcess & 0b11111000) == 0b11110000) { // 11110xxx, a four-byte sequence. + mUtf8ToFollow = 3; + } else { + // Not a valid UTF-8 sequence start, signal invalid data: + processCodePoint(UNICODE_REPLACEMENT_CHAR); + return; + } + mUtf8InputBuffer[mUtf8Index++] = byteToProcess; + } + } + + public void processCodePoint(int b) { + // The Application Program-Control (APC) string might be arbitrary non-printable characters, so handle that early. + if (mEscapeState == ESC_APC) { + doApc(b); + return; + } else if (mEscapeState == ESC_APC_ESCAPE) { + doApcEscape(b); + return; + } + + switch (b) { + case 0: // Null character (NUL, ^@). Do nothing. + break; + case 7: // Bell (BEL, ^G, \a). If in an OSC sequence, BEL may terminate a string; otherwise signal bell. + if (mEscapeState == ESC_OSC) + doOsc(b); + else + mSession.onBell(); + break; + case 8: // Backspace (BS, ^H). + if (mLeftMargin == mCursorCol) { + // Jump to previous line if it was auto-wrapped. + int previousRow = mCursorRow - 1; + if (previousRow >= 0 && mScreen.getLineWrap(previousRow)) { + mScreen.clearLineWrap(previousRow); + setCursorRowCol(previousRow, mRightMargin - 1); + } + } else { + setCursorCol(mCursorCol - 1); + } + break; + case 9: // Horizontal tab (HT, \t) - move to next tab stop, but not past edge of screen + // XXX: Should perhaps use color if writing to new cells. Try with + // printf "\033[41m\tXX\033[0m\n" + // The OSX Terminal.app colors the spaces from the tab red, but xterm does not. + // Note that Terminal.app only colors on new cells, in e.g. + // printf "\033[41m\t\r\033[42m\tXX\033[0m\n" + // the first cells are created with a red background, but when tabbing over + // them again with a green background they are not overwritten. + mCursorCol = nextTabStop(1); + break; + case 10: // Line feed (LF, \n). + case 11: // Vertical tab (VT, \v). + case 12: // Form feed (FF, \f). + doLinefeed(); + break; + case 13: // Carriage return (CR, \r). + setCursorCol(mLeftMargin); + break; + case 14: // Shift Out (Ctrl-N, SO) → Switch to Alternate Character Set. This invokes the G1 character set. + mUseLineDrawingUsesG0 = false; + break; + case 15: // Shift In (Ctrl-O, SI) → Switch to Standard Character Set. This invokes the G0 character set. + mUseLineDrawingUsesG0 = true; + break; + case 24: // CAN. + case 26: // SUB. + if (mEscapeState != ESC_NONE) { + // FIXME: What is this?? + mEscapeState = ESC_NONE; + emitCodePoint(127); + } + break; + case 27: // ESC + // Starts an escape sequence unless we're parsing a string + if (mEscapeState == ESC_P) { + // XXX: Ignore escape when reading device control sequence, since it may be part of string terminator. + return; + } else if (mEscapeState != ESC_OSC) { + startEscapeSequence(); + } else { + doOsc(b); + } + break; + default: + mContinueSequence = false; + switch (mEscapeState) { + case ESC_NONE: + if (b >= 32) emitCodePoint(b); + break; + case ESC: + doEsc(b); + break; + case ESC_POUND: + doEscPound(b); + break; + case ESC_SELECT_LEFT_PAREN: // Designate G0 Character Set (ISO 2022, VT100). + mUseLineDrawingG0 = (b == '0'); + break; + case ESC_SELECT_RIGHT_PAREN: // Designate G1 Character Set (ISO 2022, VT100). + mUseLineDrawingG1 = (b == '0'); + break; + case ESC_CSI: + doCsi(b); + break; + case ESC_CSI_UNSUPPORTED_PARAMETER_BYTE: + case ESC_CSI_UNSUPPORTED_INTERMEDIATE_BYTE: + doCsiUnsupportedParameterOrIntermediateByte(b); + break; + case ESC_CSI_EXCLAMATION: + if (b == 'p') { // Soft terminal reset (DECSTR, http://vt100.net/docs/vt510-rm/DECSTR). + reset(); + } else { + unknownSequence(b); + } + break; + case ESC_CSI_QUESTIONMARK: + doCsiQuestionMark(b); + break; + case ESC_CSI_BIGGERTHAN: + doCsiBiggerThan(b); + break; + case ESC_CSI_DOLLAR: + boolean originMode = isDecsetInternalBitSet(DECSET_BIT_ORIGIN_MODE); + int effectiveTopMargin = originMode ? mTopMargin : 0; + int effectiveBottomMargin = originMode ? mBottomMargin : mRows; + int effectiveLeftMargin = originMode ? mLeftMargin : 0; + int effectiveRightMargin = originMode ? mRightMargin : mColumns; + switch (b) { + case 'v': // ${CSI}${SRC_TOP}${SRC_LEFT}${SRC_BOTTOM}${SRC_RIGHT}${SRC_PAGE}${DST_TOP}${DST_LEFT}${DST_PAGE}$v" + // Copy rectangular area (DECCRA - http://vt100.net/docs/vt510-rm/DECCRA): + // "If Pbs is greater than Pts, or Pls is greater than Prs, the terminal ignores DECCRA. + // The coordinates of the rectangular area are affected by the setting of origin mode (DECOM). + // DECCRA is not affected by the page margins. + // The copied text takes on the line attributes of the destination area. + // If the value of Pt, Pl, Pb, or Pr exceeds the width or height of the active page, then the value + // is treated as the width or height of that page. + // If the destination area is partially off the page, then DECCRA clips the off-page data. + // DECCRA does not change the active cursor position." + int topSource = Math.min(getArg(0, 1, true) - 1 + effectiveTopMargin, mRows); + int leftSource = Math.min(getArg(1, 1, true) - 1 + effectiveLeftMargin, mColumns); + // Inclusive, so do not subtract one: + int bottomSource = Math.min(Math.max(getArg(2, mRows, true) + effectiveTopMargin, topSource), mRows); + int rightSource = Math.min(Math.max(getArg(3, mColumns, true) + effectiveLeftMargin, leftSource), mColumns); + // int sourcePage = getArg(4, 1, true); + int destionationTop = Math.min(getArg(5, 1, true) - 1 + effectiveTopMargin, mRows); + int destinationLeft = Math.min(getArg(6, 1, true) - 1 + effectiveLeftMargin, mColumns); + // int destinationPage = getArg(7, 1, true); + int heightToCopy = Math.min(mRows - destionationTop, bottomSource - topSource); + int widthToCopy = Math.min(mColumns - destinationLeft, rightSource - leftSource); + mScreen.blockCopy(leftSource, topSource, widthToCopy, heightToCopy, destinationLeft, destionationTop); + break; + case '{': // ${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${" + // Selective erase rectangular area (DECSERA - http://www.vt100.net/docs/vt510-rm/DECSERA). + case 'x': // ${CSI}${CHAR};${TOP}${LEFT}${BOTTOM}${RIGHT}$x" + // Fill rectangular area (DECFRA - http://www.vt100.net/docs/vt510-rm/DECFRA). + case 'z': // ${CSI}$${TOP}${LEFT}${BOTTOM}${RIGHT}$z" + // Erase rectangular area (DECERA - http://www.vt100.net/docs/vt510-rm/DECERA). + boolean erase = b != 'x'; + boolean selective = b == '{'; + // Only DECSERA keeps visual attributes, DECERA does not: + boolean keepVisualAttributes = erase && selective; + int argIndex = 0; + int fillChar = erase ? ' ' : getArg(argIndex++, -1, true); + // "Pch can be any value from 32 to 126 or from 160 to 255. If Pch is not in this range, then the + // terminal ignores the DECFRA command": + if ((fillChar >= 32 && fillChar <= 126) || (fillChar >= 160 && fillChar <= 255)) { + // "If the value of Pt, Pl, Pb, or Pr exceeds the width or height of the active page, the value + // is treated as the width or height of that page." + int top = Math.min(getArg(argIndex++, 1, true) + effectiveTopMargin, effectiveBottomMargin + 1); + int left = Math.min(getArg(argIndex++, 1, true) + effectiveLeftMargin, effectiveRightMargin + 1); + int bottom = Math.min(getArg(argIndex++, mRows, true) + effectiveTopMargin, effectiveBottomMargin); + int right = Math.min(getArg(argIndex, mColumns, true) + effectiveLeftMargin, effectiveRightMargin); + long style = getStyle(); + for (int row = top - 1; row < bottom; row++) + for (int col = left - 1; col < right; col++) + if (!selective || (TextStyle.decodeEffect(mScreen.getStyleAt(row, col)) & TextStyle.CHARACTER_ATTRIBUTE_PROTECTED) == 0) + mScreen.setChar(col, row, fillChar, keepVisualAttributes ? mScreen.getStyleAt(row, col) : style); + } + break; + case 'r': // "${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${ATTRIBUTES}$r" + // Change attributes in rectangular area (DECCARA - http://vt100.net/docs/vt510-rm/DECCARA). + case 't': // "${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${ATTRIBUTES}$t" + // Reverse attributes in rectangular area (DECRARA - http://www.vt100.net/docs/vt510-rm/DECRARA). + boolean reverse = b == 't'; + // FIXME: "coordinates of the rectangular area are affected by the setting of origin mode (DECOM)". + int top = Math.min(getArg(0, 1, true) - 1, effectiveBottomMargin) + effectiveTopMargin; + int left = Math.min(getArg(1, 1, true) - 1, effectiveRightMargin) + effectiveLeftMargin; + int bottom = Math.min(getArg(2, mRows, true) + 1, effectiveBottomMargin - 1) + effectiveTopMargin; + int right = Math.min(getArg(3, mColumns, true) + 1, effectiveRightMargin - 1) + effectiveLeftMargin; + if (mArgIndex >= 4) { + if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; + for (int i = 4; i <= mArgIndex; i++) { + int bits = 0; + boolean setOrClear = true; // True if setting, false if clearing. + switch (getArg(i, 0, false)) { + case 0: // Attributes off (no bold, no underline, no blink, positive image). + bits = (TextStyle.CHARACTER_ATTRIBUTE_BOLD | TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE | TextStyle.CHARACTER_ATTRIBUTE_BLINK + | TextStyle.CHARACTER_ATTRIBUTE_INVERSE); + if (!reverse) setOrClear = false; + break; + case 1: // Bold. + bits = TextStyle.CHARACTER_ATTRIBUTE_BOLD; + break; + case 4: // Underline. + bits = TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; + break; + case 5: // Blink. + bits = TextStyle.CHARACTER_ATTRIBUTE_BLINK; + break; + case 7: // Negative image. + bits = TextStyle.CHARACTER_ATTRIBUTE_INVERSE; + break; + case 22: // No bold. + bits = TextStyle.CHARACTER_ATTRIBUTE_BOLD; + setOrClear = false; + break; + case 24: // No underline. + bits = TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; + setOrClear = false; + break; + case 25: // No blink. + bits = TextStyle.CHARACTER_ATTRIBUTE_BLINK; + setOrClear = false; + break; + case 27: // Positive image. + bits = TextStyle.CHARACTER_ATTRIBUTE_INVERSE; + setOrClear = false; + break; + } + if (reverse && !setOrClear) { + // Reverse attributes in rectangular area ignores non-(1,4,5,7) bits. + } else { + mScreen.setOrClearEffect(bits, setOrClear, reverse, isDecsetInternalBitSet(DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE), + effectiveLeftMargin, effectiveRightMargin, top, left, bottom, right); + } + } + } else { + // Do nothing. + } + break; + default: + unknownSequence(b); + } + break; + case ESC_CSI_DOUBLE_QUOTE: + if (b == 'q') { + // http://www.vt100.net/docs/vt510-rm/DECSCA + int arg = getArg0(0); + if (arg == 0 || arg == 2) { + // DECSED and DECSEL can erase characters. + mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_PROTECTED; + } else if (arg == 1) { + // DECSED and DECSEL cannot erase characters. + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_PROTECTED; + } else { + unknownSequence(b); + } + } else { + unknownSequence(b); + } + break; + case ESC_CSI_SINGLE_QUOTE: + if (b == '}') { // Insert Ps Column(s) (default = 1) (DECIC), VT420 and up. + int columnsAfterCursor = mRightMargin - mCursorCol; + int columnsToInsert = Math.min(getArg0(1), columnsAfterCursor); + int columnsToMove = columnsAfterCursor - columnsToInsert; + mScreen.blockCopy(mCursorCol, 0, columnsToMove, mRows, mCursorCol + columnsToInsert, 0); + blockClear(mCursorCol, 0, columnsToInsert, mRows); + } else if (b == '~') { // Delete Ps Column(s) (default = 1) (DECDC), VT420 and up. + int columnsAfterCursor = mRightMargin - mCursorCol; + int columnsToDelete = Math.min(getArg0(1), columnsAfterCursor); + int columnsToMove = columnsAfterCursor - columnsToDelete; + mScreen.blockCopy(mCursorCol + columnsToDelete, 0, columnsToMove, mRows, mCursorCol, 0); + } else { + unknownSequence(b); + } + break; + case ESC_PERCENT: + break; + case ESC_OSC: + doOsc(b); + break; + case ESC_OSC_ESC: + doOscEsc(b); + break; + case ESC_P: + doDeviceControl(b); + break; + case ESC_CSI_QUESTIONMARK_ARG_DOLLAR: + if (b == 'p') { + // Request DEC private mode (DECRQM). + int mode = getArg0(0); + int value; + if (mode == 47 || mode == 1047 || mode == 1049) { + // This state is carried by mScreen pointer. + value = (mScreen == mAltBuffer) ? 1 : 2; + } else { + int internalBit = mapDecSetBitToInternalBit(mode); + if (internalBit != -1) { + value = isDecsetInternalBitSet(internalBit) ? 1 : 2; // 1=set, 2=reset. + } else { + Logger.logError(mClient, LOG_TAG, "Got DECRQM for unrecognized private DEC mode=" + mode); + value = 0; // 0=not recognized, 3=permanently set, 4=permanently reset + } + } + mSession.write(String.format(Locale.US, "\033[?%d;%d$y", mode, value)); + } else { + unknownSequence(b); + } + break; + case ESC_CSI_ARGS_SPACE: + int arg = getArg0(0); + switch (b) { + case 'q': // "${CSI}${STYLE} q" - set cursor style (http://www.vt100.net/docs/vt510-rm/DECSCUSR). + switch (arg) { + case 0: // Blinking block. + case 1: // Blinking block. + case 2: // Steady block. + mCursorStyle = TERMINAL_CURSOR_STYLE_BLOCK; + break; + case 3: // Blinking underline. + case 4: // Steady underline. + mCursorStyle = TERMINAL_CURSOR_STYLE_UNDERLINE; + break; + case 5: // Blinking bar (xterm addition). + case 6: // Steady bar (xterm addition). + mCursorStyle = TERMINAL_CURSOR_STYLE_BAR; + break; + } + break; + case 't': + case 'u': + // Set margin-bell volume - ignore. + break; + default: + unknownSequence(b); + } + break; + case ESC_CSI_ARGS_ASTERIX: + int attributeChangeExtent = getArg0(0); + if (b == 'x' && (attributeChangeExtent >= 0 && attributeChangeExtent <= 2)) { + // Select attribute change extent (DECSACE - http://www.vt100.net/docs/vt510-rm/DECSACE). + setDecsetinternalBit(DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE, attributeChangeExtent == 2); + } else { + unknownSequence(b); + } + break; + default: + unknownSequence(b); + break; + } + if (!mContinueSequence) mEscapeState = ESC_NONE; + break; + } + } + + /** When in {@link #ESC_P} ("device control") sequence. */ + private void doDeviceControl(int b) { + switch (b) { + case (byte) '\\': // End of ESC \ string Terminator + { + String dcs = mOSCOrDeviceControlArgs.toString(); + // DCS $ q P t ST. Request Status String (DECRQSS) + if (dcs.startsWith("$q")) { + if (dcs.equals("$q\"p")) { + // DECSCL, conformance level, http://www.vt100.net/docs/vt510-rm/DECSCL: + String csiString = "64;1\"p"; + mSession.write("\033P1$r" + csiString + "\033\\"); + } else { + finishSequenceAndLogError("Unrecognized DECRQSS string: '" + dcs + "'"); + } + } else if (dcs.startsWith("+q")) { + // Request Termcap/Terminfo String. The string following the "q" is a list of names encoded in + // hexadecimal (2 digits per character) separated by ; which correspond to termcap or terminfo key + // names. + // Two special features are also recognized, which are not key names: Co for termcap colors (or colors + // for terminfo colors), and TN for termcap name (or name for terminfo name). + // xterm responds with DCS 1 + r P t ST for valid requests, adding to P t an = , and the value of the + // corresponding string that xterm would send, or DCS 0 + r P t ST for invalid requests. The strings are + // encoded in hexadecimal (2 digits per character). + // Example: + // :kr=\EOC: ks=\E[?1h\E=: ku=\EOA: le=^H:mb=\E[5m:md=\E[1m:\ + // where + // kd=down-arrow key + // kl=left-arrow key + // kr=right-arrow key + // ku=up-arrow key + // #2=key_shome, "shifted home" + // #4=key_sleft, "shift arrow left" + // %i=key_sright, "shift arrow right" + // *7=key_send, "shifted end" + // k1=F1 function key + + // Example: Request for ku is "ESC P + q 6 b 7 5 ESC \", where 6b7d=ku in hexadecimal. + // Xterm response in normal cursor mode: + // "<27> P 1 + r 6 b 7 5 = 1 B 5 B 4 1" where 0x1B 0x5B 0x41 = 27 91 65 = ESC [ A + // Xterm response in application cursor mode: + // "<27> P 1 + r 6 b 7 5 = 1 B 5 B 4 1" where 0x1B 0x4F 0x41 = 27 91 65 = ESC 0 A + + // #4 is "shift arrow left": + // *** Device Control (DCS) for '#4'- 'ESC P + q 23 34 ESC \' + // Response: <27> P 1 + r 2 3 3 4 = 1 B 5 B 3 1 3 B 3 2 4 4 <27> \ + // where 0x1B 0x5B 0x31 0x3B 0x32 0x44 = ESC [ 1 ; 2 D + // which we find in: TermKeyListener.java: KEY_MAP.put(KEYMOD_SHIFT | KEYCODE_DPAD_LEFT, "\033[1;2D"); + + // See http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V40G_HTML/MAN/MAN4/0178____.HTM for what to + // respond, as well as http://www.freebsd.org/cgi/man.cgi?query=termcap&sektion=5#CAPABILITIES for + // the meaning of e.g. "ku", "kd", "kr", "kl" + + for (String part : dcs.substring(2).split(";")) { + if (part.length() % 2 == 0) { + StringBuilder transBuffer = new StringBuilder(); + char c; + for (int i = 0; i < part.length(); i += 2) { + try { + c = (char) Long.decode("0x" + part.charAt(i) + "" + part.charAt(i + 1)).longValue(); + } catch (NumberFormatException e) { + Logger.logStackTraceWithMessage(mClient, LOG_TAG, "Invalid device termcap/terminfo encoded name \"" + part + "\"", e); + continue; + } + transBuffer.append(c); + } + + String trans = transBuffer.toString(); + String responseValue; + switch (trans) { + case "Co": + case "colors": + responseValue = "256"; // Number of colors. + break; + case "TN": + case "name": + responseValue = "xterm"; + break; + default: + responseValue = KeyHandler.getCodeFromTermcap(trans, isDecsetInternalBitSet(DECSET_BIT_APPLICATION_CURSOR_KEYS), + isDecsetInternalBitSet(DECSET_BIT_APPLICATION_KEYPAD)); + break; + } + if (responseValue == null) { + switch (trans) { + case "%1": // Help key - ignore + case "&8": // Undo key - ignore. + break; + default: + Logger.logWarn(mClient, LOG_TAG, "Unhandled termcap/terminfo name: '" + trans + "'"); + } + // Respond with invalid request: + mSession.write("\033P0+r" + part + "\033\\"); + } else { + StringBuilder hexEncoded = new StringBuilder(); + for (int j = 0; j < responseValue.length(); j++) { + hexEncoded.append(String.format("%02X", (int) responseValue.charAt(j))); + } + mSession.write("\033P1+r" + part + "=" + hexEncoded + "\033\\"); + } + } else { + Logger.logError(mClient, LOG_TAG, "Invalid device termcap/terminfo name of odd length: " + part); + } + } + } else { + if (LOG_ESCAPE_SEQUENCES) + Logger.logError(mClient, LOG_TAG, "Unrecognized device control string: " + dcs); + } + finishSequence(); + } + break; + default: + if (mOSCOrDeviceControlArgs.length() > MAX_OSC_STRING_LENGTH) { + // Too long. + mOSCOrDeviceControlArgs.setLength(0); + finishSequence(); + } else { + mOSCOrDeviceControlArgs.appendCodePoint(b); + continueSequence(mEscapeState); + } + } + } + + /** + * When in {@link #ESC_APC} (APC, Application Program Command) sequence. + */ + private void doApc(int b) { + if (b == 27) { + continueSequence(ESC_APC_ESCAPE); + } + // Eat APC sequences silently for now. + } + + /** + * When in {@link #ESC_APC} (APC, Application Program Command) sequence. + */ + private void doApcEscape(int b) { + if (b == '\\') { + // A String Terminator (ST), ending the APC escape sequence. + finishSequence(); + } else { + // The Escape character was not the start of a String Terminator (ST), + // but instead just data inside of the APC escape sequence. + continueSequence(ESC_APC); + } + } + + private int nextTabStop(int numTabs) { + for (int i = mCursorCol + 1; i < mColumns; i++) + if (mTabStop[i] && --numTabs == 0) return Math.min(i, mRightMargin); + return mRightMargin - 1; + } + + /** + * Process byte while in the {@link #ESC_CSI_UNSUPPORTED_PARAMETER_BYTE} or + * {@link #ESC_CSI_UNSUPPORTED_INTERMEDIATE_BYTE} escape state. + * + * Parse unsupported parameter, intermediate and final bytes but ignore them. + * + * > For Control Sequence Introducer, ... the ESC [ is followed by + * > - any number (including none) of "parameter bytes" in the range 0x30–0x3F (ASCII 0–9:;<=>?), + * > - then by any number of "intermediate bytes" in the range 0x20–0x2F (ASCII space and !"#$%&'()*+,-./), + * > - then finally by a single "final byte" in the range 0x40–0x7E (ASCII @A–Z[\]^_`a–z{|}~). + * + * - https://en.wikipedia.org/wiki/ANSI_escape_code#Control_Sequence_Introducer_commands + * - https://invisible-island.net/xterm/ecma-48-parameter-format.html#section5.4 + */ + private void doCsiUnsupportedParameterOrIntermediateByte(int b) { + if (mEscapeState == ESC_CSI_UNSUPPORTED_PARAMETER_BYTE && b >= 0x30 && b <= 0x3F) { + // Supported `0–9:;>?` or unsupported `<=` parameter byte after an + // initial unsupported parameter byte in `doCsi()`, or a sequential parameter byte. + continueSequence(ESC_CSI_UNSUPPORTED_PARAMETER_BYTE); + } else if (b >= 0x20 && b <= 0x2F) { + // Optional intermediate byte `!"#$%&'()*+,-./` after parameter or intermediate byte. + continueSequence(ESC_CSI_UNSUPPORTED_INTERMEDIATE_BYTE); + } else if (b >= 0x40 && b <= 0x7E) { + // Final byte `@A–Z[\]^_`a–z{|}~` after parameter or intermediate byte. + // Calling `unknownSequence()` would log an error with only a final byte, so ignore it for now. + finishSequence(); + } else { + unknownSequence(b); + } + } + + /** Process byte while in the {@link #ESC_CSI_QUESTIONMARK} escape state. */ + private void doCsiQuestionMark(int b) { + switch (b) { + case 'J': // Selective erase in display (DECSED) - http://www.vt100.net/docs/vt510-rm/DECSED. + case 'K': // Selective erase in line (DECSEL) - http://vt100.net/docs/vt510-rm/DECSEL. + mAboutToAutoWrap = false; + int fillChar = ' '; + int startCol = -1; + int startRow = -1; + int endCol = -1; + int endRow = -1; + boolean justRow = (b == 'K'); + switch (getArg0(0)) { + case 0: // Erase from the active position to the end, inclusive (default). + startCol = mCursorCol; + startRow = mCursorRow; + endCol = mColumns; + endRow = justRow ? (mCursorRow + 1) : mRows; + break; + case 1: // Erase from start to the active position, inclusive. + startCol = 0; + startRow = justRow ? mCursorRow : 0; + endCol = mCursorCol + 1; + endRow = mCursorRow + 1; + break; + case 2: // Erase all of the display/line. + startCol = 0; + startRow = justRow ? mCursorRow : 0; + endCol = mColumns; + endRow = justRow ? (mCursorRow + 1) : mRows; + break; + default: + unknownSequence(b); + break; + } + long style = getStyle(); + for (int row = startRow; row < endRow; row++) { + for (int col = startCol; col < endCol; col++) { + if ((TextStyle.decodeEffect(mScreen.getStyleAt(row, col)) & TextStyle.CHARACTER_ATTRIBUTE_PROTECTED) == 0) + mScreen.setChar(col, row, fillChar, style); + } + } + break; + case 'h': + case 'l': + if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; + for (int i = 0; i <= mArgIndex; i++) + doDecSetOrReset(b == 'h', mArgs[i]); + break; + case 'n': // Device Status Report (DSR, DEC-specific). + switch (getArg0(-1)) { + case 6: + // Extended Cursor Position (DECXCPR - http://www.vt100.net/docs/vt510-rm/DECXCPR). Page=1. + mSession.write(String.format(Locale.US, "\033[?%d;%d;1R", mCursorRow + 1, mCursorCol + 1)); + break; + default: + finishSequence(); + return; + } + break; + case 'r': + case 's': + if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; + for (int i = 0; i <= mArgIndex; i++) { + int externalBit = mArgs[i]; + int internalBit = mapDecSetBitToInternalBit(externalBit); + if (internalBit == -1) { + Logger.logWarn(mClient, LOG_TAG, "Ignoring request to save/recall decset bit=" + externalBit); + } else { + if (b == 's') { + mSavedDecSetFlags |= internalBit; + } else { + doDecSetOrReset((mSavedDecSetFlags & internalBit) != 0, externalBit); + } + } + } + break; + case '$': + continueSequence(ESC_CSI_QUESTIONMARK_ARG_DOLLAR); + return; + default: + parseArg(b); + } + } + + public void doDecSetOrReset(boolean setting, int externalBit) { + int internalBit = mapDecSetBitToInternalBit(externalBit); + if (internalBit != -1) { + setDecsetinternalBit(internalBit, setting); + } + switch (externalBit) { + case 1: // Application Cursor Keys (DECCKM). + break; + case 3: // Set: 132 column mode (. Reset: 80 column mode. ANSI name: DECCOLM. + // We don't actually set/reset 132 cols, but we do want the side effects + // (FIXME: Should only do this if the 95 DECSET bit (DECNCSM) is set, and if changing value?): + // Sets the left, right, top and bottom scrolling margins to their default positions, which is important for + // the "reset" utility to really reset the terminal: + mLeftMargin = mTopMargin = 0; + mBottomMargin = mRows; + mRightMargin = mColumns; + // "DECCOLM resets vertical split screen mode (DECLRMM) to unavailable": + setDecsetinternalBit(DECSET_BIT_LEFTRIGHT_MARGIN_MODE, false); + // "Erases all data in page memory": + blockClear(0, 0, mColumns, mRows); + setCursorRowCol(0, 0); + break; + case 4: // DECSCLM-Scrolling Mode. Ignore. + break; + case 5: // Reverse video. No action. + break; + case 6: // Set: Origin Mode. Reset: Normal Cursor Mode. Ansi name: DECOM. + if (setting) setCursorPosition(0, 0); + break; + case 7: // Wrap-around bit, not specific action. + case 8: // Auto-repeat Keys (DECARM). Do not implement. + case 9: // X10 mouse reporting - outdated. Do not implement. + case 12: // Control cursor blinking - ignore. + case 25: // Hide/show cursor - no action needed, renderer will check with shouldCursorBeVisible(). + if (mClient != null) + mClient.onTerminalCursorStateChange(setting); + break; + case 40: // Allow 80 => 132 Mode, ignore. + case 45: // TODO: Reverse wrap-around. Implement??? + case 66: // Application keypad (DECNKM). + break; + case 69: // Left and right margin mode (DECLRMM). + if (!setting) { + mLeftMargin = 0; + mRightMargin = mColumns; + } + break; + case 1000: + case 1001: + case 1002: + case 1003: + case 1004: + case 1005: // UTF-8 mouse mode, ignore. + case 1006: // SGR Mouse Mode + case 1015: + case 1034: // Interpret "meta" key, sets eighth bit. + break; + case 1048: // Set: Save cursor as in DECSC. Reset: Restore cursor as in DECRC. + if (setting) + saveCursor(); + else + restoreCursor(); + break; + case 47: + case 1047: + case 1049: { + // Set: Save cursor as in DECSC and use Alternate Screen Buffer, clearing it first. + // Reset: Use Normal Screen Buffer and restore cursor as in DECRC. + TerminalBuffer newScreen = setting ? mAltBuffer : mMainBuffer; + if (newScreen != mScreen) { + boolean resized = !(newScreen.mColumns == mColumns && newScreen.mScreenRows == mRows); + if (setting) saveCursor(); + mScreen = newScreen; + if (!setting) { + int col = mSavedStateMain.mSavedCursorCol; + int row = mSavedStateMain.mSavedCursorRow; + restoreCursor(); + if (resized) { + // Restore cursor position _not_ clipped to current screen (let resizeScreen() handle that): + mCursorCol = col; + mCursorRow = row; + } + } + // Check if buffer size needs to be updated: + if (resized) resizeScreen(); + // Clear new screen if alt buffer: + if (newScreen == mAltBuffer) + newScreen.blockSet(0, 0, mColumns, mRows, ' ', getStyle()); + } + break; + } + case 2004: + // Bracketed paste mode - setting bit is enough. + break; + default: + unknownParameter(externalBit); + break; + } + } + + private void doCsiBiggerThan(int b) { + switch (b) { + case 'c': // "${CSI}>c" or "${CSI}>c". Secondary Device Attributes (DA2). + // Originally this was used for the terminal to respond with "identification code, firmware version level, + // and hardware options" (http://vt100.net/docs/vt510-rm/DA2), with the first "41" meaning the VT420 + // terminal type. This is not used anymore, but the second version level field has been changed by xterm + // to mean it's release number ("patch numbers" listed at http://invisible-island.net/xterm/xterm.log.html), + // and some applications use it as a feature check: + // * tmux used to have a "xterm won't reach version 500 for a while so set that as the upper limit" check, + // and then check "xterm_version > 270" if rectangular area operations such as DECCRA could be used. + // * vim checks xterm version number >140 for "Request termcap/terminfo string" functionality >276 for SGR + // mouse report. + // The third number is a keyboard identifier not used nowadays. + mSession.write("\033[>41;320;0c"); + break; + case 'm': + // https://bugs.launchpad.net/gnome-terminal/+bug/96676/comments/25 + // Depending on the first number parameter, this can set one of the xterm resources + // modifyKeyboard, modifyCursorKeys, modifyFunctionKeys and modifyOtherKeys. + // http://invisible-island.net/xterm/manpage/xterm.html#RESOURCES + + // * modifyKeyboard (parameter=1): + // Normally xterm makes a special case regarding modifiers (shift, control, etc.) to handle special keyboard + // layouts (legacy and vt220). This is done to provide compatible keyboards for DEC VT220 and related + // terminals that implement user-defined keys (UDK). + // The bits of the resource value selectively enable modification of the given category when these keyboards + // are selected. The default is "0": + // (0) The legacy/vt220 keyboards interpret only the Control-modifier when constructing numbered + // function-keys. Other special keys are not modified. + // (1) allows modification of the numeric keypad + // (2) allows modification of the editing keypad + // (4) allows modification of function-keys, overrides use of Shift-modifier for UDK. + // (8) allows modification of other special keys + + // * modifyCursorKeys (parameter=2): + // Tells how to handle the special case where Control-, Shift-, Alt- or Meta-modifiers are used to add a + // parameter to the escape sequence returned by a cursor-key. The default is "2". + // - Set it to -1 to disable it. + // - Set it to 0 to use the old/obsolete behavior. + // - Set it to 1 to prefix modified sequences with CSI. + // - Set it to 2 to force the modifier to be the second parameter if it would otherwise be the first. + // - Set it to 3 to mark the sequence with a ">" to hint that it is private. + + // * modifyFunctionKeys (parameter=3): + // Tells how to handle the special case where Control-, Shift-, Alt- or Meta-modifiers are used to add a + // parameter to the escape sequence returned by a (numbered) function- + // key. The default is "2". The resource values are similar to modifyCursorKeys: + // Set it to -1 to permit the user to use shift- and control-modifiers to construct function-key strings + // using the normal encoding scheme. + // - Set it to 0 to use the old/obsolete behavior. + // - Set it to 1 to prefix modified sequences with CSI. + // - Set it to 2 to force the modifier to be the second parameter if it would otherwise be the first. + // - Set it to 3 to mark the sequence with a ">" to hint that it is private. + // If modifyFunctionKeys is zero, xterm uses Control- and Shift-modifiers to allow the user to construct + // numbered function-keys beyond the set provided by the keyboard: + // (Control) adds the value given by the ctrlFKeys resource. + // (Shift) adds twice the value given by the ctrlFKeys resource. + // (Control/Shift) adds three times the value given by the ctrlFKeys resource. + // + // As a special case, legacy (when oldFunctionKeys is true) or vt220 (when sunKeyboard is true) + // keyboards interpret only the Control-modifier when constructing numbered function-keys. + // This is done to provide compatible keyboards for DEC VT220 and related terminals that + // implement user-defined keys (UDK). + + // * modifyOtherKeys (parameter=4): + // Like modifyCursorKeys, tells xterm to construct an escape sequence for other keys (such as "2") when + // modified by Control-, Alt- or Meta-modifiers. This feature does not apply to function keys and + // well-defined keys such as ESC or the control keys. The default is "0". + // (0) disables this feature. + // (1) enables this feature for keys except for those with well-known behavior, e.g., Tab, Backarrow and + // some special control character cases, e.g., Control-Space to make a NUL. + // (2) enables this feature for keys including the exceptions listed. + Logger.logError(mClient, LOG_TAG, "(ignored) CSI > MODIFY RESOURCE: " + getArg0(-1) + " to " + getArg1(-1)); + break; + default: + parseArg(b); + break; + } + } + + private void startEscapeSequence() { + mEscapeState = ESC; + mArgIndex = 0; + Arrays.fill(mArgs, -1); + mArgsSubParamsBitSet = 0; + } + + private void doLinefeed() { + boolean belowScrollingRegion = mCursorRow >= mBottomMargin; + int newCursorRow = mCursorRow + 1; + if (belowScrollingRegion) { + // Move down (but not scroll) as long as we are above the last row. + if (mCursorRow != mRows - 1) { + setCursorRow(newCursorRow); + } + } else { + if (newCursorRow == mBottomMargin) { + scrollDownOneLine(); + newCursorRow = mBottomMargin - 1; + } + setCursorRow(newCursorRow); + } + } + + private void continueSequence(int state) { + mEscapeState = state; + mContinueSequence = true; + } + + private void doEscPound(int b) { + switch (b) { + case '8': // Esc # 8 - DEC screen alignment test - fill screen with E's. + mScreen.blockSet(0, 0, mColumns, mRows, 'E', getStyle()); + break; + default: + unknownSequence(b); + break; + } + } + + /** Encountering a character in the {@link #ESC} state. */ + private void doEsc(int b) { + switch (b) { + case '#': + continueSequence(ESC_POUND); + break; + case '(': + continueSequence(ESC_SELECT_LEFT_PAREN); + break; + case ')': + continueSequence(ESC_SELECT_RIGHT_PAREN); + break; + case '6': // Back index (http://www.vt100.net/docs/vt510-rm/DECBI). Move left, insert blank column if start. + if (mCursorCol > mLeftMargin) { + mCursorCol--; + } else { + int rows = mBottomMargin - mTopMargin; + mScreen.blockCopy(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin - 1, rows, mLeftMargin + 1, mTopMargin); + mScreen.blockSet(mLeftMargin, mTopMargin, 1, rows, ' ', TextStyle.encode(mForeColor, mBackColor, 0)); + } + break; + case '7': // DECSC save cursor - http://www.vt100.net/docs/vt510-rm/DECSC + saveCursor(); + break; + case '8': // DECRC restore cursor - http://www.vt100.net/docs/vt510-rm/DECRC + restoreCursor(); + break; + case '9': // Forward Index (http://www.vt100.net/docs/vt510-rm/DECFI). Move right, insert blank column if end. + if (mCursorCol < mRightMargin - 1) { + mCursorCol++; + } else { + int rows = mBottomMargin - mTopMargin; + mScreen.blockCopy(mLeftMargin + 1, mTopMargin, mRightMargin - mLeftMargin - 1, rows, mLeftMargin, mTopMargin); + mScreen.blockSet(mRightMargin - 1, mTopMargin, 1, rows, ' ', TextStyle.encode(mForeColor, mBackColor, 0)); + } + break; + case 'c': // RIS - Reset to Initial State (http://vt100.net/docs/vt510-rm/RIS). + reset(); + mMainBuffer.clearTranscript(); + blockClear(0, 0, mColumns, mRows); + setCursorPosition(0, 0); + break; + case 'D': // INDEX + doLinefeed(); + break; + case 'E': // Next line (http://www.vt100.net/docs/vt510-rm/NEL). + setCursorCol(isDecsetInternalBitSet(DECSET_BIT_ORIGIN_MODE) ? mLeftMargin : 0); + doLinefeed(); + break; + case 'F': // Cursor to lower-left corner of screen + setCursorRowCol(0, mBottomMargin - 1); + break; + case 'H': // Tab set + mTabStop[mCursorCol] = true; + break; + case 'M': // "${ESC}M" - reverse index (RI). + // http://www.vt100.net/docs/vt100-ug/chapter3.html: "Move the active position to the same horizontal + // position on the preceding line. If the active position is at the top margin, a scroll down is performed". + if (mCursorRow <= mTopMargin) { + mScreen.blockCopy(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin, mBottomMargin - (mTopMargin + 1), mLeftMargin, mTopMargin + 1); + blockClear(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin); + } else { + mCursorRow--; + } + break; + case 'N': // SS2, ignore. + case '0': // SS3, ignore. + break; + case 'P': // Device control string + mOSCOrDeviceControlArgs.setLength(0); + continueSequence(ESC_P); + break; + case '[': + continueSequence(ESC_CSI); + break; + case '=': // DECKPAM + setDecsetinternalBit(DECSET_BIT_APPLICATION_KEYPAD, true); + break; + case ']': // OSC + mOSCOrDeviceControlArgs.setLength(0); + continueSequence(ESC_OSC); + break; + case '>': // DECKPNM + setDecsetinternalBit(DECSET_BIT_APPLICATION_KEYPAD, false); + break; + case '_': // APC - Application Program Command. + continueSequence(ESC_APC); + break; + default: + unknownSequence(b); + break; + } + } + + /** DECSC save cursor - http://www.vt100.net/docs/vt510-rm/DECSC . See {@link #restoreCursor()}. */ + private void saveCursor() { + SavedScreenState state = (mScreen == mMainBuffer) ? mSavedStateMain : mSavedStateAlt; + state.mSavedCursorRow = mCursorRow; + state.mSavedCursorCol = mCursorCol; + state.mSavedEffect = mEffect; + state.mSavedForeColor = mForeColor; + state.mSavedBackColor = mBackColor; + state.mSavedDecFlags = mCurrentDecSetFlags; + state.mUseLineDrawingG0 = mUseLineDrawingG0; + state.mUseLineDrawingG1 = mUseLineDrawingG1; + state.mUseLineDrawingUsesG0 = mUseLineDrawingUsesG0; + } + + /** DECRS restore cursor - http://www.vt100.net/docs/vt510-rm/DECRC. See {@link #saveCursor()}. */ + private void restoreCursor() { + SavedScreenState state = (mScreen == mMainBuffer) ? mSavedStateMain : mSavedStateAlt; + setCursorRowCol(state.mSavedCursorRow, state.mSavedCursorCol); + mEffect = state.mSavedEffect; + mForeColor = state.mSavedForeColor; + mBackColor = state.mSavedBackColor; + int mask = (DECSET_BIT_AUTOWRAP | DECSET_BIT_ORIGIN_MODE); + mCurrentDecSetFlags = (mCurrentDecSetFlags & ~mask) | (state.mSavedDecFlags & mask); + mUseLineDrawingG0 = state.mUseLineDrawingG0; + mUseLineDrawingG1 = state.mUseLineDrawingG1; + mUseLineDrawingUsesG0 = state.mUseLineDrawingUsesG0; + } + + /** Following a CSI - Control Sequence Introducer, "\033[". {@link #ESC_CSI}. */ + private void doCsi(int b) { + switch (b) { + case '!': + continueSequence(ESC_CSI_EXCLAMATION); + break; + case '"': + continueSequence(ESC_CSI_DOUBLE_QUOTE); + break; + case '\'': + continueSequence(ESC_CSI_SINGLE_QUOTE); + break; + case '$': + continueSequence(ESC_CSI_DOLLAR); + break; + case '*': + continueSequence(ESC_CSI_ARGS_ASTERIX); + break; + case '@': { + // "CSI{n}@" - Insert ${n} space characters (ICH) - http://www.vt100.net/docs/vt510-rm/ICH. + mAboutToAutoWrap = false; + int columnsAfterCursor = mColumns - mCursorCol; + int spacesToInsert = Math.min(getArg0(1), columnsAfterCursor); + int charsToMove = columnsAfterCursor - spacesToInsert; + mScreen.blockCopy(mCursorCol, mCursorRow, charsToMove, 1, mCursorCol + spacesToInsert, mCursorRow); + blockClear(mCursorCol, mCursorRow, spacesToInsert); + } + break; + case 'A': // "CSI${n}A" - Cursor up (CUU) ${n} rows. + setCursorRow(Math.max(0, mCursorRow - getArg0(1))); + break; + case 'B': // "CSI${n}B" - Cursor down (CUD) ${n} rows. + setCursorRow(Math.min(mRows - 1, mCursorRow + getArg0(1))); + break; + case 'C': // "CSI${n}C" - Cursor forward (CUF). + case 'a': // "CSI${n}a" - Horizontal position relative (HPR). From ISO-6428/ECMA-48. + setCursorCol(Math.min(mRightMargin - 1, mCursorCol + getArg0(1))); + break; + case 'D': // "CSI${n}D" - Cursor backward (CUB) ${n} columns. + setCursorCol(Math.max(mLeftMargin, mCursorCol - getArg0(1))); + break; + case 'E': // "CSI{n}E - Cursor Next Line (CNL). From ISO-6428/ECMA-48. + setCursorPosition(0, mCursorRow + getArg0(1)); + break; + case 'F': // "CSI{n}F - Cursor Previous Line (CPL). From ISO-6428/ECMA-48. + setCursorPosition(0, mCursorRow - getArg0(1)); + break; + case 'G': // "CSI${n}G" - Cursor horizontal absolute (CHA) to column ${n}. + setCursorCol(Math.min(Math.max(1, getArg0(1)), mColumns) - 1); + break; + case 'H': // "${CSI}${ROW};${COLUMN}H" - Cursor position (CUP). + case 'f': // "${CSI}${ROW};${COLUMN}f" - Horizontal and Vertical Position (HVP). + setCursorPosition(getArg1(1) - 1, getArg0(1) - 1); + break; + case 'I': // Cursor Horizontal Forward Tabulation (CHT). Move the active position n tabs forward. + setCursorCol(nextTabStop(getArg0(1))); + break; + case 'J': // "${CSI}${0,1,2,3}J" - Erase in Display (ED) + // ED ignores the scrolling margins. + switch (getArg0(0)) { + case 0: // Erase from the active position to the end of the screen, inclusive (default). + blockClear(mCursorCol, mCursorRow, mColumns - mCursorCol); + blockClear(0, mCursorRow + 1, mColumns, mRows - (mCursorRow + 1)); + break; + case 1: // Erase from start of the screen to the active position, inclusive. + blockClear(0, 0, mColumns, mCursorRow); + blockClear(0, mCursorRow, mCursorCol + 1); + break; + case 2: // Erase all of the display - all lines are erased, changed to single-width, and the cursor does not + // move.. + blockClear(0, 0, mColumns, mRows); + break; + case 3: // Delete all lines saved in the scrollback buffer (xterm etc) + mMainBuffer.clearTranscript(); + break; + default: + unknownSequence(b); + return; + } + mAboutToAutoWrap = false; + break; + case 'K': // "CSI{n}K" - Erase in line (EL). + switch (getArg0(0)) { + case 0: // Erase from the cursor to the end of the line, inclusive (default) + blockClear(mCursorCol, mCursorRow, mColumns - mCursorCol); + break; + case 1: // Erase from the start of the screen to the cursor, inclusive. + blockClear(0, mCursorRow, mCursorCol + 1); + break; + case 2: // Erase all of the line. + blockClear(0, mCursorRow, mColumns); + break; + default: + unknownSequence(b); + return; + } + mAboutToAutoWrap = false; + break; + case 'L': // "${CSI}{N}L" - insert ${N} lines (IL). + { + int linesAfterCursor = mBottomMargin - mCursorRow; + int linesToInsert = Math.min(getArg0(1), linesAfterCursor); + int linesToMove = linesAfterCursor - linesToInsert; + mScreen.blockCopy(0, mCursorRow, mColumns, linesToMove, 0, mCursorRow + linesToInsert); + blockClear(0, mCursorRow, mColumns, linesToInsert); + } + break; + case 'M': // "${CSI}${N}M" - delete N lines (DL). + { + mAboutToAutoWrap = false; + int linesAfterCursor = mBottomMargin - mCursorRow; + int linesToDelete = Math.min(getArg0(1), linesAfterCursor); + int linesToMove = linesAfterCursor - linesToDelete; + mScreen.blockCopy(0, mCursorRow + linesToDelete, mColumns, linesToMove, 0, mCursorRow); + blockClear(0, mCursorRow + linesToMove, mColumns, linesToDelete); + } + break; + case 'P': // "${CSI}{N}P" - delete ${N} characters (DCH). + { + // http://www.vt100.net/docs/vt510-rm/DCH: "If ${N} is greater than the number of characters between the + // cursor and the right margin, then DCH only deletes the remaining characters. + // As characters are deleted, the remaining characters between the cursor and right margin move to the left. + // Character attributes move with the characters. The terminal adds blank spaces with no visual character + // attributes at the right margin. DCH has no effect outside the scrolling margins." + mAboutToAutoWrap = false; + int cellsAfterCursor = mColumns - mCursorCol; + int cellsToDelete = Math.min(getArg0(1), cellsAfterCursor); + int cellsToMove = cellsAfterCursor - cellsToDelete; + mScreen.blockCopy(mCursorCol + cellsToDelete, mCursorRow, cellsToMove, 1, mCursorCol, mCursorRow); + blockClear(mCursorCol + cellsToMove, mCursorRow, cellsToDelete); + } + break; + case 'S': { // "${CSI}${N}S" - scroll up ${N} lines (default = 1) (SU). + final int linesToScroll = getArg0(1); + for (int i = 0; i < linesToScroll; i++) + scrollDownOneLine(); + break; + } + case 'T': + if (mArgIndex == 0) { + // "${CSI}${N}T" - Scroll down N lines (default = 1) (SD). + // http://vt100.net/docs/vt510-rm/SD: "N is the number of lines to move the user window up in page + // memory. N new lines appear at the top of the display. N old lines disappear at the bottom of the + // display. You cannot pan past the top margin of the current page". + final int linesToScrollArg = getArg0(1); + final int linesBetweenTopAndBottomMargins = mBottomMargin - mTopMargin; + final int linesToScroll = Math.min(linesBetweenTopAndBottomMargins, linesToScrollArg); + mScreen.blockCopy(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin, linesBetweenTopAndBottomMargins - linesToScroll, mLeftMargin, mTopMargin + linesToScroll); + blockClear(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin, linesToScroll); + } else { + // "${CSI}${func};${startx};${starty};${firstrow};${lastrow}T" - initiate highlight mouse tracking. + unimplementedSequence(b); + } + break; + case 'X': // "${CSI}${N}X" - Erase ${N:=1} character(s) (ECH). FIXME: Clears character attributes? + mAboutToAutoWrap = false; + mScreen.blockSet(mCursorCol, mCursorRow, Math.min(getArg0(1), mColumns - mCursorCol), 1, ' ', getStyle()); + break; + case 'Z': // Cursor Backward Tabulation (CBT). Move the active position n tabs backward. + int numberOfTabs = getArg0(1); + int newCol = mLeftMargin; + for (int i = mCursorCol - 1; i >= 0; i--) + if (mTabStop[i]) { + if (--numberOfTabs == 0) { + newCol = Math.max(i, mLeftMargin); + break; + } + } + mCursorCol = newCol; + break; + case '?': // Esc [ ? -- start of a private parameter byte + continueSequence(ESC_CSI_QUESTIONMARK); + break; + case '>': // "Esc [ >" -- start of a private parameter byte + continueSequence(ESC_CSI_BIGGERTHAN); + break; + case '<': // "Esc [ <" -- start of a private parameter byte + case '=': // "Esc [ =" -- start of a private parameter byte + continueSequence(ESC_CSI_UNSUPPORTED_PARAMETER_BYTE); + break; + case '`': // Horizontal position absolute (HPA - http://www.vt100.net/docs/vt510-rm/HPA). + setCursorColRespectingOriginMode(getArg0(1) - 1); + break; + case 'b': // Repeat the preceding graphic character Ps times (REP). + if (mLastEmittedCodePoint == -1) break; + final int numRepeat = getArg0(1); + for (int i = 0; i < numRepeat; i++) emitCodePoint(mLastEmittedCodePoint); + break; + case 'c': // Primary Device Attributes (http://www.vt100.net/docs/vt510-rm/DA1) if argument is missing or zero. + // The important part that may still be used by some (tmux stores this value but does not currently use it) + // is the first response parameter identifying the terminal service class, where we send 64 for "vt420". + // This is followed by a list of attributes which is probably unused by applications. Send like xterm. + if (getArg0(0) == 0) mSession.write("\033[?64;1;2;6;9;15;18;21;22c"); + break; + case 'd': // ESC [ Pn d - Vert Position Absolute + setCursorRow(Math.min(Math.max(1, getArg0(1)), mRows) - 1); + break; + case 'e': // Vertical Position Relative (VPR). From ISO-6429 (ECMA-48). + setCursorPosition(mCursorCol, mCursorRow + getArg0(1)); + break; + // case 'f': "${CSI}${ROW};${COLUMN}f" - Horizontal and Vertical Position (HVP). Grouped with case 'H'. + case 'g': // Clear tab stop + switch (getArg0(0)) { + case 0: + mTabStop[mCursorCol] = false; + break; + case 3: + for (int i = 0; i < mColumns; i++) { + mTabStop[i] = false; + } + break; + default: + // Specified to have no effect. + break; + } + break; + case 'h': // Set Mode + doSetMode(true); + break; + case 'l': // Reset Mode + doSetMode(false); + break; + case 'm': // Esc [ Pn m - character attributes. (can have up to 16 numerical arguments) + selectGraphicRendition(); + break; + case 'n': // Esc [ Pn n - ECMA-48 Status Report Commands + // sendDeviceAttributes() + switch (getArg0(0)) { + case 5: // Device status report (DSR): + // Answer is ESC [ 0 n (Terminal OK). + byte[] dsr = {(byte) 27, (byte) '[', (byte) '0', (byte) 'n'}; + mSession.write(dsr, 0, dsr.length); + break; + case 6: // Cursor position report (CPR): + // Answer is ESC [ y ; x R, where x,y is + // the cursor location. + mSession.write(String.format(Locale.US, "\033[%d;%dR", mCursorRow + 1, mCursorCol + 1)); + break; + default: + break; + } + break; + case 'r': // "CSI${top};${bottom}r" - set top and bottom Margins (DECSTBM). + { + // https://vt100.net/docs/vt510-rm/DECSTBM.html + // The top margin defaults to 1, the bottom margin defaults to mRows. + // The escape sequence numbers top 1..23, but we number top 0..22. + // The escape sequence numbers bottom 2..24, and so do we (because we use a zero based numbering + // scheme, but we store the first line below the bottom-most scrolling line. + // As a result, we adjust the top line by -1, but we leave the bottom line alone. + // Also require that top + 2 <= bottom. + mTopMargin = Math.max(0, Math.min(getArg0(1) - 1, mRows - 2)); + mBottomMargin = Math.max(mTopMargin + 2, Math.min(getArg1(mRows), mRows)); + + // DECSTBM moves the cursor to column 1, line 1 of the page respecting origin mode. + setCursorPosition(0, 0); + } + break; + case 's': + if (isDecsetInternalBitSet(DECSET_BIT_LEFTRIGHT_MARGIN_MODE)) { + // Set left and right margins (DECSLRM - http://www.vt100.net/docs/vt510-rm/DECSLRM). + mLeftMargin = Math.min(getArg0(1) - 1, mColumns - 2); + mRightMargin = Math.max(mLeftMargin + 1, Math.min(getArg1(mColumns), mColumns)); + // DECSLRM moves the cursor to column 1, line 1 of the page. + setCursorPosition(0, 0); + } else { + // Save cursor (ANSI.SYS), available only when DECLRMM is disabled. + saveCursor(); + } + break; + case 't': // Window manipulation (from dtterm, as well as extensions) + switch (getArg0(0)) { + case 11: // Report xterm window state. If the xterm window is open (non-iconified), it returns CSI 1 t . + mSession.write("\033[1t"); + break; + case 13: // Report xterm window position. Result is CSI 3 ; x ; y t + mSession.write("\033[3;0;0t"); + break; + case 14: // Report xterm window in pixels. Result is CSI 4 ; height ; width t + mSession.write(String.format(Locale.US, "\033[4;%d;%dt", mRows * mCellHeightPixels, mColumns * mCellWidthPixels)); + break; + case 16: // Report xterm character cell size in pixels. Result is CSI 6 ; height ; width t + mSession.write(String.format(Locale.US, "\033[6;%d;%dt", mCellHeightPixels, mCellWidthPixels)); + break; + case 18: // Report the size of the text area in characters. Result is CSI 8 ; height ; width t + mSession.write(String.format(Locale.US, "\033[8;%d;%dt", mRows, mColumns)); + break; + case 19: // Report the size of the screen in characters. Result is CSI 9 ; height ; width t + // We report the same size as the view, since it's the view really isn't resizable from the shell. + mSession.write(String.format(Locale.US, "\033[9;%d;%dt", mRows, mColumns)); + break; + case 20: // Report xterm windows icon label. Result is OSC L label ST. Disabled due to security concerns: + mSession.write("\033]LIconLabel\033\\"); + break; + case 21: // Report xterm windows title. Result is OSC l label ST. Disabled due to security concerns: + mSession.write("\033]l\033\\"); + break; + case 22: + // 22;0 -> Save xterm icon and window title on stack. + // 22;1 -> Save xterm icon title on stack. + // 22;2 -> Save xterm window title on stack. + mTitleStack.push(mTitle); + if (mTitleStack.size() > 20) { + // Limit size + mTitleStack.remove(0); + } + break; + case 23: // Like 22 above but restore from stack. + if (!mTitleStack.isEmpty()) setTitle(mTitleStack.pop()); + break; + default: + // Ignore window manipulation. + break; + } + break; + case 'u': // Restore cursor (ANSI.SYS). + restoreCursor(); + break; + case ' ': + continueSequence(ESC_CSI_ARGS_SPACE); + break; + default: + parseArg(b); + break; + } + } + + /** Select Graphic Rendition (SGR) - see http://en.wikipedia.org/wiki/ANSI_escape_code#graphics. */ + private void selectGraphicRendition() { + if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; + for (int i = 0; i <= mArgIndex; i++) { + // Skip leading sub parameters: + if ((mArgsSubParamsBitSet & (1 << i)) != 0) { + continue; + } + + int code = getArg(i, 0, false); + if (code < 0) { + if (mArgIndex > 0) { + continue; + } else { + code = 0; + } + } + if (code == 0) { // reset + mForeColor = TextStyle.COLOR_INDEX_FOREGROUND; + mBackColor = TextStyle.COLOR_INDEX_BACKGROUND; + mEffect = 0; + } else if (code == 1) { + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_BOLD; + } else if (code == 2) { + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_DIM; + } else if (code == 3) { + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_ITALIC; + } else if (code == 4) { + if (i + 1 <= mArgIndex && ((mArgsSubParamsBitSet & (1 << (i + 1))) != 0)) { + // Sub parameter, see https://sw.kovidgoyal.net/kitty/underlines/ + i++; + if (mArgs[i] == 0) { + // No underline. + mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; + } else { + // Different variations of underlines: https://sw.kovidgoyal.net/kitty/underlines/ + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; + } + } else { + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; + } + } else if (code == 5) { + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_BLINK; + } else if (code == 7) { + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_INVERSE; + } else if (code == 8) { + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_INVISIBLE; + } else if (code == 9) { + mEffect |= TextStyle.CHARACTER_ATTRIBUTE_STRIKETHROUGH; + } else if (code == 10) { + // Exit alt charset (TERM=linux) - ignore. + } else if (code == 11) { + // Enter alt charset (TERM=linux) - ignore. + } else if (code == 22) { // Normal color or intensity, neither bright, bold nor faint. + mEffect &= ~(TextStyle.CHARACTER_ATTRIBUTE_BOLD | TextStyle.CHARACTER_ATTRIBUTE_DIM); + } else if (code == 23) { // not italic, but rarely used as such; clears standout with TERM=screen + mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_ITALIC; + } else if (code == 24) { // underline: none + mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; + } else if (code == 25) { // blink: none + mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_BLINK; + } else if (code == 27) { // image: positive + mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_INVERSE; + } else if (code == 28) { + mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_INVISIBLE; + } else if (code == 29) { + mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_STRIKETHROUGH; + } else if (code >= 30 && code <= 37) { + mForeColor = code - 30; + } else if (code == 38 || code == 48 || code == 58) { + // Extended set foreground(38)/background(48)/underline(58) color. + // This is followed by either "2;$R;$G;$B" to set a 24-bit color or + // "5;$INDEX" to set an indexed color. + if (i + 2 > mArgIndex) continue; + int firstArg = mArgs[i + 1]; + if (firstArg == 2) { + if (i + 4 > mArgIndex) { + Logger.logWarn(mClient, LOG_TAG, "Too few CSI" + code + ";2 RGB arguments"); + } else { + int red = getArg(i + 2, 0, false); + int green = getArg(i + 3, 0, false); + int blue = getArg(i + 4, 0, false); + + if (red < 0 || green < 0 || blue < 0 || red > 255 || green > 255 || blue > 255) { + finishSequenceAndLogError("Invalid RGB: " + red + "," + green + "," + blue); + } else { + int argbColor = 0xff_00_00_00 | (red << 16) | (green << 8) | blue; + switch (code) { + case 38: mForeColor = argbColor; break; + case 48: mBackColor = argbColor; break; + case 58: mUnderlineColor = argbColor; break; + } + } + i += 4; // "2;P_r;P_g;P_r" + } + } else if (firstArg == 5) { + int color = getArg(i + 2, 0, false); + i += 2; // "5;P_s" + if (color >= 0 && color < TextStyle.NUM_INDEXED_COLORS) { + switch (code) { + case 38: mForeColor = color; break; + case 48: mBackColor = color; break; + case 58: mUnderlineColor = color; break; + } + } else { + if (LOG_ESCAPE_SEQUENCES) Logger.logWarn(mClient, LOG_TAG, "Invalid color index: " + color); + } + } else { + finishSequenceAndLogError("Invalid ISO-8613-3 SGR first argument: " + firstArg); + } + } else if (code == 39) { // Set default foreground color. + mForeColor = TextStyle.COLOR_INDEX_FOREGROUND; + } else if (code >= 40 && code <= 47) { // Set background color. + mBackColor = code - 40; + } else if (code == 49) { // Set default background color. + mBackColor = TextStyle.COLOR_INDEX_BACKGROUND; + } else if (code == 59) { // Set default underline color. + mUnderlineColor = TextStyle.COLOR_INDEX_FOREGROUND; + } else if (code >= 90 && code <= 97) { // Bright foreground colors (aixterm codes). + mForeColor = code - 90 + 8; + } else if (code >= 100 && code <= 107) { // Bright background color (aixterm codes). + mBackColor = code - 100 + 8; + } else { + if (LOG_ESCAPE_SEQUENCES) + Logger.logWarn(mClient, LOG_TAG, String.format("SGR unknown code %d", code)); + } + } + } + + private void doOsc(int b) { + switch (b) { + case 7: // Bell. + doOscSetTextParameters("\007"); + break; + case 27: // Escape. + continueSequence(ESC_OSC_ESC); + break; + default: + collectOSCArgs(b); + break; + } + } + + private void doOscEsc(int b) { + switch (b) { + case '\\': + doOscSetTextParameters("\033\\"); + break; + default: + // The ESC character was not followed by a \, so insert the ESC and + // the current character in arg buffer. + collectOSCArgs(27); + collectOSCArgs(b); + continueSequence(ESC_OSC); + break; + } + } + + /** An Operating System Controls (OSC) Set Text Parameters. May come here from BEL or ST. */ + private void doOscSetTextParameters(String bellOrStringTerminator) { + int value = -1; + String textParameter = ""; + // Extract initial $value from initial "$value;..." string. + for (int mOSCArgTokenizerIndex = 0; mOSCArgTokenizerIndex < mOSCOrDeviceControlArgs.length(); mOSCArgTokenizerIndex++) { + char b = mOSCOrDeviceControlArgs.charAt(mOSCArgTokenizerIndex); + if (b == ';') { + textParameter = mOSCOrDeviceControlArgs.substring(mOSCArgTokenizerIndex + 1); + break; + } else if (b >= '0' && b <= '9') { + value = ((value < 0) ? 0 : value * 10) + (b - '0'); + } else { + unknownSequence(b); + return; + } + } + + switch (value) { + case 0: // Change icon name and window title to T. + case 1: // Change icon name to T. + case 2: // Change window title to T. + setTitle(textParameter); + break; + case 4: + // P s = 4 ; c ; spec → Change Color Number c to the color specified by spec. This can be a name or RGB + // specification as per XParseColor. Any number of c name pairs may be given. The color numbers correspond + // to the ANSI colors 0-7, their bright versions 8-15, and if supported, the remainder of the 88-color or + // 256-color table. + // If a "?" is given rather than a name or RGB specification, xterm replies with a control sequence of the + // same form which can be used to set the corresponding color. Because more than one pair of color number + // and specification can be given in one control sequence, xterm can make more than one reply. + int colorIndex = -1; + int parsingPairStart = -1; + for (int i = 0; ; i++) { + boolean endOfInput = i == textParameter.length(); + char b = endOfInput ? ';' : textParameter.charAt(i); + if (b == ';') { + if (parsingPairStart < 0) { + parsingPairStart = i + 1; + } else { + if (colorIndex < 0 || colorIndex > 255) { + unknownSequence(b); + return; + } else { + mColors.tryParseColor(colorIndex, textParameter.substring(parsingPairStart, i)); + mSession.onColorsChanged(); + colorIndex = -1; + parsingPairStart = -1; + } + } + } else if (parsingPairStart >= 0) { + // We have passed a color index and are now going through color spec. + } else if (parsingPairStart < 0 && (b >= '0' && b <= '9')) { + colorIndex = ((colorIndex < 0) ? 0 : colorIndex * 10) + (b - '0'); + } else { + unknownSequence(b); + return; + } + if (endOfInput) break; + } + break; + case 10: // Set foreground color. + case 11: // Set background color. + case 12: // Set cursor color. + int specialIndex = TextStyle.COLOR_INDEX_FOREGROUND + (value - 10); + int lastSemiIndex = 0; + for (int charIndex = 0; ; charIndex++) { + boolean endOfInput = charIndex == textParameter.length(); + if (endOfInput || textParameter.charAt(charIndex) == ';') { + try { + String colorSpec = textParameter.substring(lastSemiIndex, charIndex); + if ("?".equals(colorSpec)) { + // Report current color in the same format xterm and gnome-terminal does. + int rgb = mColors.mCurrentColors[specialIndex]; + int r = (65535 * ((rgb & 0x00FF0000) >> 16)) / 255; + int g = (65535 * ((rgb & 0x0000FF00) >> 8)) / 255; + int b = (65535 * ((rgb & 0x000000FF))) / 255; + mSession.write("\033]" + value + ";rgb:" + String.format(Locale.US, "%04x", r) + "/" + String.format(Locale.US, "%04x", g) + "/" + + String.format(Locale.US, "%04x", b) + bellOrStringTerminator); + } else { + mColors.tryParseColor(specialIndex, colorSpec); + mSession.onColorsChanged(); + } + specialIndex++; + if (endOfInput || (specialIndex > TextStyle.COLOR_INDEX_CURSOR) || ++charIndex >= textParameter.length()) + break; + lastSemiIndex = charIndex; + } catch (NumberFormatException e) { + // Ignore. + } + } + } + break; + case 52: // Manipulate Selection Data. Skip the optional first selection parameter(s). + int startIndex = textParameter.indexOf(";") + 1; + try { + String clipboardText = new String(Base64.decode(textParameter.substring(startIndex), 0), StandardCharsets.UTF_8); + mSession.onCopyTextToClipboard(clipboardText); + } catch (Exception e) { + Logger.logError(mClient, LOG_TAG, "OSC Manipulate selection, invalid string '" + textParameter + ""); + } + break; + case 104: + // "104;$c" → Reset Color Number $c. It is reset to the color specified by the corresponding X + // resource. Any number of c parameters may be given. These parameters correspond to the ANSI colors 0-7, + // their bright versions 8-15, and if supported, the remainder of the 88-color or 256-color table. If no + // parameters are given, the entire table will be reset. + if (textParameter.isEmpty()) { + mColors.reset(); + mSession.onColorsChanged(); + } else { + int lastIndex = 0; + for (int charIndex = 0; ; charIndex++) { + boolean endOfInput = charIndex == textParameter.length(); + if (endOfInput || textParameter.charAt(charIndex) == ';') { + try { + int colorToReset = Integer.parseInt(textParameter.substring(lastIndex, charIndex)); + mColors.reset(colorToReset); + mSession.onColorsChanged(); + if (endOfInput) break; + charIndex++; + lastIndex = charIndex; + } catch (NumberFormatException e) { + // Ignore. + } + } + } + } + break; + case 110: // Reset foreground color. + case 111: // Reset background color. + case 112: // Reset cursor color. + mColors.reset(TextStyle.COLOR_INDEX_FOREGROUND + (value - 110)); + mSession.onColorsChanged(); + break; + case 119: // Reset highlight color. + break; + default: + unknownParameter(value); + break; + } + finishSequence(); + } + + private void blockClear(int sx, int sy, int w) { + blockClear(sx, sy, w, 1); + } + + private void blockClear(int sx, int sy, int w, int h) { + mScreen.blockSet(sx, sy, w, h, ' ', getStyle()); + } + + private long getStyle() { + return TextStyle.encode(mForeColor, mBackColor, mEffect); + } + + /** "CSI P_m h" for set or "CSI P_m l" for reset ANSI mode. */ + private void doSetMode(boolean newValue) { + int modeBit = getArg0(0); + switch (modeBit) { + case 4: // Set="Insert Mode". Reset="Replace Mode". (IRM). + mInsertMode = newValue; + break; + case 20: // Normal Linefeed (LNM). + unknownParameter(modeBit); + // http://www.vt100.net/docs/vt510-rm/LNM + break; + case 34: + // Normal cursor visibility - when using TERM=screen, see + // http://www.gnu.org/software/screen/manual/html_node/Control-Sequences.html + break; + default: + unknownParameter(modeBit); + break; + } + } + + /** + * NOTE: The parameters of this function respect the {@link #DECSET_BIT_ORIGIN_MODE}. Use + * {@link #setCursorRowCol(int, int)} for absolute pos. + */ + private void setCursorPosition(int x, int y) { + boolean originMode = isDecsetInternalBitSet(DECSET_BIT_ORIGIN_MODE); + int effectiveTopMargin = originMode ? mTopMargin : 0; + int effectiveBottomMargin = originMode ? mBottomMargin : mRows; + int effectiveLeftMargin = originMode ? mLeftMargin : 0; + int effectiveRightMargin = originMode ? mRightMargin : mColumns; + int newRow = Math.max(effectiveTopMargin, Math.min(effectiveTopMargin + y, effectiveBottomMargin - 1)); + int newCol = Math.max(effectiveLeftMargin, Math.min(effectiveLeftMargin + x, effectiveRightMargin - 1)); + setCursorRowCol(newRow, newCol); + } + + private void scrollDownOneLine() { + mScrollCounter++; + long currentStyle = getStyle(); + if (mLeftMargin != 0 || mRightMargin != mColumns) { + // Horizontal margin: Do not put anything into scroll history, just non-margin part of screen up. + mScreen.blockCopy(mLeftMargin, mTopMargin + 1, mRightMargin - mLeftMargin, mBottomMargin - mTopMargin - 1, mLeftMargin, mTopMargin); + // .. and blank bottom row between margins: + mScreen.blockSet(mLeftMargin, mBottomMargin - 1, mRightMargin - mLeftMargin, 1, ' ', currentStyle); + } else { + mScreen.scrollDownOneLine(mTopMargin, mBottomMargin, currentStyle); + } + } + + /** + * Process the next ASCII character of a parameter. + * + *

You must use the ; character to separate parameters and : to separate sub-parameters. + * + *

Parameter characters modify the action or interpretation of the sequence. Originally + * you can use up to 16 parameters per sequence, but following at least xterm and alacritty + * we use a common space for parameters and sub-parameters, allowing 32 in total. + * + *

All parameters are unsigned, positive decimal integers, with the most significant + * digit sent first. Any parameter greater than 9999 (decimal) is set to 9999 + * (decimal). If you do not specify a value, a 0 value is assumed. A 0 value + * or omitted parameter indicates a default value for the sequence. For most + * sequences, the default value is 1. + * + *

References: + * VT510 Video Terminal Programmer Information: Control Sequences + * alacritty/vte: Implement colon separated CSI parameters + * */ + private void parseArg(int b) { + if (b >= '0' && b <= '9') { + if (mArgIndex < mArgs.length) { + int oldValue = mArgs[mArgIndex]; + int thisDigit = b - '0'; + int value; + if (oldValue >= 0) { + value = oldValue * 10 + thisDigit; + } else { + value = thisDigit; + } + if (value > 9999) + value = 9999; + mArgs[mArgIndex] = value; + } + continueSequence(mEscapeState); + } else if (b == ';' || b == ':') { + if (mArgIndex + 1 < mArgs.length) { + mArgIndex++; + if (b == ':') { + mArgsSubParamsBitSet |= 1 << mArgIndex; + } + } else { + logError("Too many parameters when in state: " + mEscapeState); + } + continueSequence(mEscapeState); + } else { + unknownSequence(b); + } + } + + private int getArg0(int defaultValue) { + return getArg(0, defaultValue, true); + } + + private int getArg1(int defaultValue) { + return getArg(1, defaultValue, true); + } + + private int getArg(int index, int defaultValue, boolean treatZeroAsDefault) { + int result = mArgs[index]; + if (result < 0 || (result == 0 && treatZeroAsDefault)) { + result = defaultValue; + } + return result; + } + + private void collectOSCArgs(int b) { + if (mOSCOrDeviceControlArgs.length() < MAX_OSC_STRING_LENGTH) { + mOSCOrDeviceControlArgs.appendCodePoint(b); + continueSequence(mEscapeState); + } else { + unknownSequence(b); + } + } + + private void unimplementedSequence(int b) { + logError("Unimplemented sequence char '" + (char) b + "' (U+" + String.format("%04x", b) + ")"); + finishSequence(); + } + + private void unknownSequence(int b) { + logError("Unknown sequence char '" + (char) b + "' (numeric value=" + b + ")"); + finishSequence(); + } + + private void unknownParameter(int parameter) { + logError("Unknown parameter: " + parameter); + finishSequence(); + } + + private void logError(String errorType) { + if (LOG_ESCAPE_SEQUENCES) { + StringBuilder buf = new StringBuilder(); + buf.append(errorType); + buf.append(", escapeState="); + buf.append(mEscapeState); + boolean firstArg = true; + if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; + for (int i = 0; i <= mArgIndex; i++) { + int value = mArgs[i]; + if (value >= 0) { + if (firstArg) { + firstArg = false; + buf.append(", args={"); + } else { + buf.append(','); + } + buf.append(value); + } + } + if (!firstArg) buf.append('}'); + finishSequenceAndLogError(buf.toString()); + } + } + + private void finishSequenceAndLogError(String error) { + if (LOG_ESCAPE_SEQUENCES) Logger.logWarn(mClient, LOG_TAG, error); + finishSequence(); + } + + private void finishSequence() { + mEscapeState = ESC_NONE; + } + + /** + * Send a Unicode code point to the screen. + * + * @param codePoint The code point of the character to display + */ + private void emitCodePoint(int codePoint) { + mLastEmittedCodePoint = codePoint; + if (mUseLineDrawingUsesG0 ? mUseLineDrawingG0 : mUseLineDrawingG1) { + // http://www.vt100.net/docs/vt102-ug/table5-15.html. + switch (codePoint) { + case '_': + codePoint = ' '; // Blank. + break; + case '`': + codePoint = '◆'; // Diamond. + break; + case '0': + codePoint = '█'; // Solid block; + break; + case 'a': + codePoint = '▒'; // Checker board. + break; + case 'b': + codePoint = '␉'; // Horizontal tab. + break; + case 'c': + codePoint = '␌'; // Form feed. + break; + case 'd': + codePoint = '\r'; // Carriage return. + break; + case 'e': + codePoint = '␊'; // Linefeed. + break; + case 'f': + codePoint = '°'; // Degree. + break; + case 'g': + codePoint = '±'; // Plus-minus. + break; + case 'h': + codePoint = '\n'; // Newline. + break; + case 'i': + codePoint = '␋'; // Vertical tab. + break; + case 'j': + codePoint = '┘'; // Lower right corner. + break; + case 'k': + codePoint = '┐'; // Upper right corner. + break; + case 'l': + codePoint = '┌'; // Upper left corner. + break; + case 'm': + codePoint = '└'; // Left left corner. + break; + case 'n': + codePoint = '┼'; // Crossing lines. + break; + case 'o': + codePoint = '⎺'; // Horizontal line - scan 1. + break; + case 'p': + codePoint = '⎻'; // Horizontal line - scan 3. + break; + case 'q': + codePoint = '─'; // Horizontal line - scan 5. + break; + case 'r': + codePoint = '⎼'; // Horizontal line - scan 7. + break; + case 's': + codePoint = '⎽'; // Horizontal line - scan 9. + break; + case 't': + codePoint = '├'; // T facing rightwards. + break; + case 'u': + codePoint = '┤'; // T facing leftwards. + break; + case 'v': + codePoint = '┴'; // T facing upwards. + break; + case 'w': + codePoint = '┬'; // T facing downwards. + break; + case 'x': + codePoint = '│'; // Vertical line. + break; + case 'y': + codePoint = '≤'; // Less than or equal to. + break; + case 'z': + codePoint = '≥'; // Greater than or equal to. + break; + case '{': + codePoint = 'π'; // Pi. + break; + case '|': + codePoint = '≠'; // Not equal to. + break; + case '}': + codePoint = '£'; // UK pound. + break; + case '~': + codePoint = '·'; // Centered dot. + break; + } + } + + final boolean autoWrap = isDecsetInternalBitSet(DECSET_BIT_AUTOWRAP); + final int displayWidth = WcWidth.width(codePoint); + final boolean cursorInLastColumn = mCursorCol == mRightMargin - 1; + + if (autoWrap) { + if (cursorInLastColumn && ((mAboutToAutoWrap && displayWidth == 1) || displayWidth == 2)) { + mScreen.setLineWrap(mCursorRow); + mCursorCol = mLeftMargin; + if (mCursorRow + 1 < mBottomMargin) { + mCursorRow++; + } else { + scrollDownOneLine(); + } + } + } else if (cursorInLastColumn && displayWidth == 2) { + // The behaviour when a wide character is output with cursor in the last column when + // autowrap is disabled is not obvious - it's ignored here. + return; + } + + if (mInsertMode && displayWidth > 0) { + // Move character to right one space. + int destCol = mCursorCol + displayWidth; + if (destCol < mRightMargin) + mScreen.blockCopy(mCursorCol, mCursorRow, mRightMargin - destCol, 1, destCol, mCursorRow); + } + + int offsetDueToCombiningChar = ((displayWidth <= 0 && mCursorCol > 0 && !mAboutToAutoWrap) ? 1 : 0); + int column = mCursorCol - offsetDueToCombiningChar; + + // Fix TerminalRow.setChar() ArrayIndexOutOfBoundsException index=-1 exception reported + // The offsetDueToCombiningChar would never be 1 if mCursorCol was 0 to get column/index=-1, + // so was mCursorCol changed after the offsetDueToCombiningChar conditional by another thread? + // TODO: Check if there are thread synchronization issues with mCursorCol and mCursorRow, possibly causing others bugs too. + if (column < 0) column = 0; + mScreen.setChar(column, mCursorRow, codePoint, getStyle()); + + if (autoWrap && displayWidth > 0) + mAboutToAutoWrap = (mCursorCol == mRightMargin - displayWidth); + + mCursorCol = Math.min(mCursorCol + displayWidth, mRightMargin - 1); + } + + private void setCursorRow(int row) { + mCursorRow = row; + mAboutToAutoWrap = false; + } + + private void setCursorCol(int col) { + mCursorCol = col; + mAboutToAutoWrap = false; + } + + /** Set the cursor mode, but limit it to margins if {@link #DECSET_BIT_ORIGIN_MODE} is enabled. */ + private void setCursorColRespectingOriginMode(int col) { + setCursorPosition(col, mCursorRow); + } + + /** TODO: Better name, distinguished from {@link #setCursorPosition(int, int)} by not regarding origin mode. */ + private void setCursorRowCol(int row, int col) { + mCursorRow = Math.max(0, Math.min(row, mRows - 1)); + mCursorCol = Math.max(0, Math.min(col, mColumns - 1)); + mAboutToAutoWrap = false; + } + + public int getScrollCounter() { + return mScrollCounter; + } + + public void clearScrollCounter() { + mScrollCounter = 0; + } + + /** Reset terminal state so user can interact with it regardless of present state. */ + public void reset() { + setCursorStyle(); + mArgIndex = 0; + mContinueSequence = false; + mEscapeState = ESC_NONE; + mInsertMode = false; + mTopMargin = mLeftMargin = 0; + mBottomMargin = mRows; + mRightMargin = mColumns; + mAboutToAutoWrap = false; + mForeColor = mSavedStateMain.mSavedForeColor = mSavedStateAlt.mSavedForeColor = TextStyle.COLOR_INDEX_FOREGROUND; + mBackColor = mSavedStateMain.mSavedBackColor = mSavedStateAlt.mSavedBackColor = TextStyle.COLOR_INDEX_BACKGROUND; + setDefaultTabStops(); + + mUseLineDrawingG0 = mUseLineDrawingG1 = false; + mUseLineDrawingUsesG0 = true; + + mSavedStateMain.mSavedCursorRow = mSavedStateMain.mSavedCursorCol = mSavedStateMain.mSavedEffect = mSavedStateMain.mSavedDecFlags = 0; + mSavedStateAlt.mSavedCursorRow = mSavedStateAlt.mSavedCursorCol = mSavedStateAlt.mSavedEffect = mSavedStateAlt.mSavedDecFlags = 0; + mCurrentDecSetFlags = 0; + // Initial wrap-around is not accurate but makes terminal more useful, especially on a small screen: + setDecsetinternalBit(DECSET_BIT_AUTOWRAP, true); + setDecsetinternalBit(DECSET_BIT_CURSOR_ENABLED, true); + mSavedDecSetFlags = mSavedStateMain.mSavedDecFlags = mSavedStateAlt.mSavedDecFlags = mCurrentDecSetFlags; + + // XXX: Should we set terminal driver back to IUTF8 with termios? + mUtf8Index = mUtf8ToFollow = 0; + + mColors.reset(); + mSession.onColorsChanged(); + } + + public String getSelectedText(int x1, int y1, int x2, int y2) { + return mScreen.getSelectedText(x1, y1, x2, y2); + } + + /** Get the terminal session's title (null if not set). */ + public String getTitle() { + return mTitle; + } + + /** Change the terminal session's title. */ + private void setTitle(String newTitle) { + String oldTitle = mTitle; + mTitle = newTitle; + if (!Objects.equals(oldTitle, newTitle)) { + mSession.titleChanged(oldTitle, newTitle); + } + } + + /** If DECSET 2004 is set, prefix paste with "\033[200~" and suffix with "\033[201~". */ + public void paste(String text) { + // First: Always remove escape key and C1 control characters [0x80,0x9F]: + text = text.replaceAll("(\u001B|[\u0080-\u009F])", ""); + // Second: Replace all newlines (\n) or CRLF (\r\n) with carriage returns (\r). + text = text.replaceAll("\r?\n", "\r"); + + // Then: Implement bracketed paste mode if enabled: + boolean bracketed = isDecsetInternalBitSet(DECSET_BIT_BRACKETED_PASTE_MODE); + if (bracketed) mSession.write("\033[200~"); + mSession.write(text); + if (bracketed) mSession.write("\033[201~"); + } + + /** http://www.vt100.net/docs/vt510-rm/DECSC */ + static final class SavedScreenState { + /** Saved state of the cursor position, Used to implement the save/restore cursor position escape sequences. */ + int mSavedCursorRow, mSavedCursorCol; + int mSavedEffect, mSavedForeColor, mSavedBackColor; + int mSavedDecFlags; + boolean mUseLineDrawingG0, mUseLineDrawingG1, mUseLineDrawingUsesG0 = true; + } + + @Override + public String toString() { + return "TerminalEmulator[size=" + mScreen.mColumns + "x" + mScreen.mScreenRows + ", margins={" + mTopMargin + "," + mRightMargin + "," + mBottomMargin + + "," + mLeftMargin + "}]"; + } + +} diff --git a/android/app/src/main/java/com/termux/terminal/TerminalOutput.java b/android/app/src/main/java/com/termux/terminal/TerminalOutput.java new file mode 100644 index 0000000..305082a --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TerminalOutput.java @@ -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(); + +} diff --git a/android/app/src/main/java/com/termux/terminal/TerminalRow.java b/android/app/src/main/java/com/termux/terminal/TerminalRow.java new file mode 100644 index 0000000..d68dc32 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TerminalRow.java @@ -0,0 +1,283 @@ +package com.termux.terminal; + +import java.util.Arrays; + +/** + * A row in a terminal, composed of a fixed number of cells. + *

+ * 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]; + } + +} diff --git a/android/app/src/main/java/com/termux/terminal/TerminalSession.java b/android/app/src/main/java/com/termux/terminal/TerminalSession.java new file mode 100644 index 0000000..324e0bc --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TerminalSession.java @@ -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. + *

+ * 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. + *

+ * The child process may be exited forcefully by using the {@link #finishIfRunning()} method. + *

+ * 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); + } + } + + } + +} diff --git a/android/app/src/main/java/com/termux/terminal/TerminalSessionClient.java b/android/app/src/main/java/com/termux/terminal/TerminalSessionClient.java new file mode 100644 index 0000000..0ffe8e4 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TerminalSessionClient.java @@ -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); + +} diff --git a/android/app/src/main/java/com/termux/terminal/TextStyle.java b/android/app/src/main/java/com/termux/terminal/TextStyle.java new file mode 100644 index 0000000..173d6ae --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/TextStyle.java @@ -0,0 +1,90 @@ +package com.termux.terminal; + +/** + *

+ * 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}. + *

+ *

+ * The bit layout is: + *

+ * - 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. + *

+ * 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. + *

+ */ + 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); + } + +} diff --git a/android/app/src/main/java/com/termux/terminal/WcWidth.java b/android/app/src/main/java/com/termux/terminal/WcWidth.java new file mode 100644 index 0000000..d71cc27 --- /dev/null +++ b/android/app/src/main/java/com/termux/terminal/WcWidth.java @@ -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; + } + +} diff --git a/android/app/src/main/java/com/termux/view/GestureAndScaleRecognizer.java b/android/app/src/main/java/com/termux/view/GestureAndScaleRecognizer.java new file mode 100644 index 0000000..f7fc9d2 --- /dev/null +++ b/android/app/src/main/java/com/termux/view/GestureAndScaleRecognizer.java @@ -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(); + } + +} diff --git a/android/app/src/main/java/com/termux/view/TerminalRenderer.java b/android/app/src/main/java/com/termux/view/TerminalRenderer.java new file mode 100644 index 0000000..a4bef7d --- /dev/null +++ b/android/app/src/main/java/com/termux/view/TerminalRenderer.java @@ -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}. + *

+ * 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; + } +} diff --git a/android/app/src/main/java/com/termux/view/TerminalView.java b/android/app/src/main/java/com/termux/view/TerminalView.java new file mode 100644 index 0000000..351f47a --- /dev/null +++ b/android/app/src/main/java/com/termux/view/TerminalView.java @@ -0,0 +1,1476 @@ +package com.termux.view; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Typeface; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.text.Editable; +import android.text.InputType; +import android.text.TextUtils; +import android.util.AttributeSet; +import android.view.ActionMode; +import android.view.HapticFeedbackConstants; +import android.view.InputDevice; +import android.view.KeyCharacterMap; +import android.view.KeyEvent; +import android.view.Menu; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.ViewTreeObserver; +import android.view.accessibility.AccessibilityManager; +import android.view.autofill.AutofillManager; +import android.view.autofill.AutofillValue; +import android.view.inputmethod.BaseInputConnection; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.widget.Scroller; + +import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; + +import com.termux.terminal.KeyHandler; +import com.termux.terminal.TerminalEmulator; +import com.termux.terminal.TerminalSession; +import com.termux.view.textselection.TextSelectionCursorController; + +/** View displaying and interacting with a {@link TerminalSession}. */ +public final class TerminalView extends View { + + /** Log terminal view key and IME events. */ + private static boolean TERMINAL_VIEW_KEY_LOGGING_ENABLED = false; + + /** The currently displayed terminal session, whose emulator is {@link #mEmulator}. */ + public TerminalSession mTermSession; + /** Our terminal emulator whose session is {@link #mTermSession}. */ + public TerminalEmulator mEmulator; + + public TerminalRenderer mRenderer; + + public TerminalViewClient mClient; + + private TextSelectionCursorController mTextSelectionCursorController; + + private Handler mTerminalCursorBlinkerHandler; + private TerminalCursorBlinkerRunnable mTerminalCursorBlinkerRunnable; + private int mTerminalCursorBlinkerRate; + private boolean mCursorInvisibleIgnoreOnce; + public static final int TERMINAL_CURSOR_BLINK_RATE_MIN = 100; + public static final int TERMINAL_CURSOR_BLINK_RATE_MAX = 2000; + + /** The top row of text to display. Ranges from -activeTranscriptRows to 0. */ + int mTopRow; + int[] mDefaultSelectors = new int[]{-1,-1,-1,-1}; + + float mScaleFactor = 1.f; + final GestureAndScaleRecognizer mGestureRecognizer; + + /** Keep track of where mouse touch event started which we report as mouse scroll. */ + private int mMouseScrollStartX = -1, mMouseScrollStartY = -1; + /** Keep track of the time when a touch event leading to sending mouse scroll events started. */ + private long mMouseStartDownTime = -1; + + final Scroller mScroller; + + /** What was left in from scrolling movement. */ + float mScrollRemainder; + + /** If non-zero, this is the last unicode code point received if that was a combining character. */ + int mCombiningAccent; + + /** + * The current AutoFill type returned for {@link View#getAutofillType()} by {@link #getAutofillType()}. + * + * The default is {@link #AUTOFILL_TYPE_NONE} so that AutoFill UI, like toolbar above keyboard + * is not shown automatically, like on Activity starts/View create. This value should be updated + * to required value, like {@link #AUTOFILL_TYPE_TEXT} before calling + * {@link AutofillManager#requestAutofill(View)} so that AutoFill UI shows. The updated value + * set will automatically be restored to {@link #AUTOFILL_TYPE_NONE} in + * {@link #autofill(AutofillValue)} so that AutoFill UI isn't shown anymore by calling + * {@link #resetAutoFill()}. + */ + @RequiresApi(api = Build.VERSION_CODES.O) + private int mAutoFillType = AUTOFILL_TYPE_NONE; + + /** + * The current AutoFill type returned for {@link View#getImportantForAutofill()} by + * {@link #getImportantForAutofill()}. + * + * The default is {@link #IMPORTANT_FOR_AUTOFILL_NO} so that view is not considered important + * for AutoFill. This value should be updated to required value, like + * {@link #IMPORTANT_FOR_AUTOFILL_YES} before calling {@link AutofillManager#requestAutofill(View)} + * so that Android and apps consider the view as important for AutoFill to process the request. + * The updated value set will automatically be restored to {@link #IMPORTANT_FOR_AUTOFILL_NO} in + * {@link #autofill(AutofillValue)} by calling {@link #resetAutoFill()}. + */ + @RequiresApi(api = Build.VERSION_CODES.O) + private int mAutoFillImportance = IMPORTANT_FOR_AUTOFILL_NO; + + /** + * The current AutoFill hints returned for {@link View#getAutofillHints()} ()} by {@link #getAutofillHints()} ()}. + * + * The default is an empty `string[]`. This value should be updated to required value. The + * updated value set will automatically be restored an empty `string[]` in + * {@link #autofill(AutofillValue)} by calling {@link #resetAutoFill()}. + */ + private String[] mAutoFillHints = new String[0]; + + private final boolean mAccessibilityEnabled; + + private static final String LOG_TAG = "TerminalView"; + + public TerminalView(Context context, AttributeSet attributes) { // NO_UCD (unused code) + super(context, attributes); + mGestureRecognizer = new GestureAndScaleRecognizer(context, new GestureAndScaleRecognizer.Listener() { + + boolean scrolledWithFinger; + + @Override + public boolean onUp(MotionEvent event) { + mScrollRemainder = 0.0f; + if (mEmulator != null && mEmulator.isMouseTrackingActive() && !event.isFromSource(InputDevice.SOURCE_MOUSE) && !isSelectingText() && !scrolledWithFinger) { + // Quick event processing when mouse tracking is active - do not wait for check of double tapping + // for zooming. + sendMouseEventCode(event, TerminalEmulator.MOUSE_LEFT_BUTTON, true); + sendMouseEventCode(event, TerminalEmulator.MOUSE_LEFT_BUTTON, false); + return true; + } + scrolledWithFinger = false; + return false; + } + + @Override + public boolean onSingleTapUp(MotionEvent event) { + if (mEmulator == null) return true; + + if (isSelectingText()) { + stopTextSelectionMode(); + return true; + } + requestFocus(); + mClient.onSingleTapUp(event); + return true; + } + + @Override + public boolean onScroll(MotionEvent e, float distanceX, float distanceY) { + if (mEmulator == null) return true; + if (mEmulator.isMouseTrackingActive() && e.isFromSource(InputDevice.SOURCE_MOUSE)) { + // If moving with mouse pointer while pressing button, report that instead of scroll. + // This means that we never report moving with button press-events for touch input, + // since we cannot just start sending these events without a starting press event, + // which we do not do for touch input, only mouse in onTouchEvent(). + sendMouseEventCode(e, TerminalEmulator.MOUSE_LEFT_BUTTON_MOVED, true); + } else { + scrolledWithFinger = true; + distanceY += mScrollRemainder; + int deltaRows = (int) (distanceY / mRenderer.mFontLineSpacing); + mScrollRemainder = distanceY - deltaRows * mRenderer.mFontLineSpacing; + doScroll(e, deltaRows); + } + return true; + } + + @Override + public boolean onScale(float focusX, float focusY, float scale) { + if (mEmulator == null || isSelectingText()) return true; + mScaleFactor *= scale; + mScaleFactor = mClient.onScale(mScaleFactor); + return true; + } + + @Override + public boolean onFling(final MotionEvent e2, float velocityX, float velocityY) { + if (mEmulator == null) return true; + // Do not start scrolling until last fling has been taken care of: + if (!mScroller.isFinished()) return true; + + final boolean mouseTrackingAtStartOfFling = mEmulator.isMouseTrackingActive(); + float SCALE = 0.25f; + if (mouseTrackingAtStartOfFling) { + mScroller.fling(0, 0, 0, -(int) (velocityY * SCALE), 0, 0, -mEmulator.mRows / 2, mEmulator.mRows / 2); + } else { + mScroller.fling(0, mTopRow, 0, -(int) (velocityY * SCALE), 0, 0, -mEmulator.getScreen().getActiveTranscriptRows(), 0); + } + + post(new Runnable() { + private int mLastY = 0; + + @Override + public void run() { + if (mouseTrackingAtStartOfFling != mEmulator.isMouseTrackingActive()) { + mScroller.abortAnimation(); + return; + } + if (mScroller.isFinished()) return; + boolean more = mScroller.computeScrollOffset(); + int newY = mScroller.getCurrY(); + int diff = mouseTrackingAtStartOfFling ? (newY - mLastY) : (newY - mTopRow); + doScroll(e2, diff); + mLastY = newY; + if (more) post(this); + } + }); + + return true; + } + + @Override + public boolean onDown(float x, float y) { + // Why is true not returned here? + // https://developer.android.com/training/gestures/detector.html#detect-a-subset-of-supported-gestures + // Although setting this to true still does not solve the following errors when long pressing in terminal view text area + // ViewDragHelper: Ignoring pointerId=0 because ACTION_DOWN was not received for this pointer before ACTION_MOVE + // Commenting out the call to mGestureDetector.onTouchEvent(event) in GestureAndScaleRecognizer#onTouchEvent() removes + // the error logging, so issue is related to GestureDetector + return false; + } + + @Override + public boolean onDoubleTap(MotionEvent event) { + // Do not treat is as a single confirmed tap - it may be followed by zoom. + return false; + } + + @Override + public void onLongPress(MotionEvent event) { + if (mGestureRecognizer.isInProgress()) return; + if (mClient.onLongPress(event)) return; + if (!isSelectingText()) { + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); + startTextSelectionMode(event); + } + } + }); + mScroller = new Scroller(context); + AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); + mAccessibilityEnabled = am.isEnabled(); + } + + + + /** + * @param client The {@link TerminalViewClient} interface implementation to allow + * for communication between {@link TerminalView} and its client. + */ + public void setTerminalViewClient(TerminalViewClient client) { + this.mClient = client; + } + + /** + * Sets whether terminal view key logging is enabled or not. + * + * @param value The boolean value that defines the state. + */ + public void setIsTerminalViewKeyLoggingEnabled(boolean value) { + TERMINAL_VIEW_KEY_LOGGING_ENABLED = value; + } + + + + /** + * Attach a {@link TerminalSession} to this view. + * + * @param session The {@link TerminalSession} this view will be displaying. + */ + public boolean attachSession(TerminalSession session) { + if (session == mTermSession) return false; + mTopRow = 0; + + mTermSession = session; + mEmulator = null; + mCombiningAccent = 0; + + updateSize(); + + // Wait with enabling the scrollbar until we have a terminal to get scroll position from. + setVerticalScrollBarEnabled(true); + + return true; + } + + @Override + public InputConnection onCreateInputConnection(EditorInfo outAttrs) { + // Ensure that inputType is only set if TerminalView is selected view with the keyboard and + // an alternate view is not selected, like an EditText. This is necessary if an activity is + // initially started with the alternate view or if activity is returned to from another app + // and the alternate view was the one selected the last time. + if (mClient.isTerminalViewSelected()) { + if (mClient.shouldEnforceCharBasedInput()) { + // Some keyboards seems do not reset the internal state on TYPE_NULL. + // Affects mostly Samsung stock keyboards. + // https://github.com/termux/termux-app/issues/686 + // However, this is not a valid value as per AOSP since `InputType.TYPE_CLASS_*` is + // not set and it logs a warning: + // W/InputAttributes: Unexpected input class: inputType=0x00080090 imeOptions=0x02000000 + // https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:packages/inputmethods/LatinIME/java/src/com/android/inputmethod/latin/InputAttributes.java;l=79 + outAttrs.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; + } else { + // Using InputType.NULL is the most correct input type and avoids issues with other hacks. + // + // Previous keyboard issues: + // https://github.com/termux/termux-packages/issues/25 + // https://github.com/termux/termux-app/issues/87. + // https://github.com/termux/termux-app/issues/126. + // https://github.com/termux/termux-app/issues/137 (japanese chars and TYPE_NULL). + outAttrs.inputType = InputType.TYPE_NULL; + } + } else { + // Corresponds to android:inputType="text" + outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL; + } + + // Note that IME_ACTION_NONE cannot be used as that makes it impossible to input newlines using the on-screen + // keyboard on Android TV (see https://github.com/termux/termux-app/issues/221). + outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN; + + return new BaseInputConnection(this, true) { + + @Override + public boolean finishComposingText() { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) mClient.logInfo(LOG_TAG, "IME: finishComposingText()"); + super.finishComposingText(); + + sendTextToTerminal(getEditable()); + getEditable().clear(); + return true; + } + + @Override + public boolean commitText(CharSequence text, int newCursorPosition) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) { + mClient.logInfo(LOG_TAG, "IME: commitText(\"" + text + "\", " + newCursorPosition + ")"); + } + super.commitText(text, newCursorPosition); + + if (mEmulator == null) return true; + + Editable content = getEditable(); + sendTextToTerminal(content); + content.clear(); + return true; + } + + @Override + public boolean deleteSurroundingText(int leftLength, int rightLength) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) { + mClient.logInfo(LOG_TAG, "IME: deleteSurroundingText(" + leftLength + ", " + rightLength + ")"); + } + // The stock Samsung keyboard with 'Auto check spelling' enabled sends leftLength > 1. + KeyEvent deleteKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL); + for (int i = 0; i < leftLength; i++) sendKeyEvent(deleteKey); + return super.deleteSurroundingText(leftLength, rightLength); + } + + void sendTextToTerminal(CharSequence text) { + stopTextSelectionMode(); + final int textLengthInChars = text.length(); + for (int i = 0; i < textLengthInChars; i++) { + char firstChar = text.charAt(i); + int codePoint; + if (Character.isHighSurrogate(firstChar)) { + if (++i < textLengthInChars) { + codePoint = Character.toCodePoint(firstChar, text.charAt(i)); + } else { + // At end of string, with no low surrogate following the high: + codePoint = TerminalEmulator.UNICODE_REPLACEMENT_CHAR; + } + } else { + codePoint = firstChar; + } + + // Check onKeyDown() for details. + if (mClient.readShiftKey()) + codePoint = Character.toUpperCase(codePoint); + + boolean ctrlHeld = false; + if (codePoint <= 31 && codePoint != 27) { + if (codePoint == '\n') { + // The AOSP keyboard and descendants seems to send \n as text when the enter key is pressed, + // instead of a key event like most other keyboard apps. A terminal expects \r for the enter + // key (although when icrnl is enabled this doesn't make a difference - run 'stty -icrnl' to + // check the behaviour). + codePoint = '\r'; + } + + // E.g. penti keyboard for ctrl input. + ctrlHeld = true; + switch (codePoint) { + case 31: + codePoint = '_'; + break; + case 30: + codePoint = '^'; + break; + case 29: + codePoint = ']'; + break; + case 28: + codePoint = '\\'; + break; + default: + codePoint += 96; + break; + } + } + + inputCodePoint(codePoint, ctrlHeld, false); + } + } + + }; + } + + @Override + protected int computeVerticalScrollRange() { + return mEmulator == null ? 1 : mEmulator.getScreen().getActiveRows(); + } + + @Override + protected int computeVerticalScrollExtent() { + return mEmulator == null ? 1 : mEmulator.mRows; + } + + @Override + protected int computeVerticalScrollOffset() { + return mEmulator == null ? 1 : mEmulator.getScreen().getActiveRows() + mTopRow - mEmulator.mRows; + } + + public void onScreenUpdated() { + if (mEmulator == null) return; + + int rowsInHistory = mEmulator.getScreen().getActiveTranscriptRows(); + if (mTopRow < -rowsInHistory) mTopRow = -rowsInHistory; + + boolean skipScrolling = false; + if (isSelectingText()) { + // Do not scroll when selecting text. + int rowShift = mEmulator.getScrollCounter(); + if (-mTopRow + rowShift > rowsInHistory) { + // .. unless we're hitting the end of history transcript, in which + // case we abort text selection and scroll to end. + stopTextSelectionMode(); + } else { + skipScrolling = true; + mTopRow -= rowShift; + decrementYTextSelectionCursors(rowShift); + } + } + + if (!skipScrolling && mTopRow != 0) { + // Scroll down if not already there. + if (mTopRow < -3) { + // Awaken scroll bars only if scrolling a noticeable amount + // - we do not want visible scroll bars during normal typing + // of one row at a time. + awakenScrollBars(); + } + mTopRow = 0; + } + + mEmulator.clearScrollCounter(); + + invalidate(); + if (mAccessibilityEnabled) setContentDescription(getText()); + } + + /** This must be called by the hosting activity in {@link Activity#onContextMenuClosed(Menu)} + * when context menu for the {@link TerminalView} is started by + * {@link TextSelectionCursorController#ACTION_MORE} is closed. */ + public void onContextMenuClosed(Menu menu) { + // Unset the stored text since it shouldn't be used anymore and should be cleared from memory + unsetStoredSelectedText(); + } + + /** + * Sets the text size, which in turn sets the number of rows and columns. + * + * @param textSize the new font size, in density-independent pixels. + */ + public void setTextSize(int textSize) { + mRenderer = new TerminalRenderer(textSize, mRenderer == null ? Typeface.MONOSPACE : mRenderer.mTypeface); + updateSize(); + } + + public void setTypeface(Typeface newTypeface) { + mRenderer = new TerminalRenderer(mRenderer.mTextSize, newTypeface); + updateSize(); + invalidate(); + } + + @Override + public boolean onCheckIsTextEditor() { + return true; + } + + @Override + public boolean isOpaque() { + return true; + } + + /** + * Get the zero indexed column and row of the terminal view for the + * position of the event. + * + * @param event The event with the position to get the column and row for. + * @param relativeToScroll If true the column number will take the scroll + * position into account. E.g. if scrolled 3 lines up and the event + * position is in the top left, column will be -3 if relativeToScroll is + * true and 0 if relativeToScroll is false. + * @return Array with the column and row. + */ + public int[] getColumnAndRow(MotionEvent event, boolean relativeToScroll) { + int column = (int) (event.getX() / mRenderer.mFontWidth); + int row = (int) ((event.getY() - mRenderer.mFontLineSpacingAndAscent) / mRenderer.mFontLineSpacing); + if (relativeToScroll) { + row += mTopRow; + } + return new int[] { column, row }; + } + + /** Send a single mouse event code to the terminal. */ + void sendMouseEventCode(MotionEvent e, int button, boolean pressed) { + int[] columnAndRow = getColumnAndRow(e, false); + int x = columnAndRow[0] + 1; + int y = columnAndRow[1] + 1; + if (pressed && (button == TerminalEmulator.MOUSE_WHEELDOWN_BUTTON || button == TerminalEmulator.MOUSE_WHEELUP_BUTTON)) { + if (mMouseStartDownTime == e.getDownTime()) { + x = mMouseScrollStartX; + y = mMouseScrollStartY; + } else { + mMouseStartDownTime = e.getDownTime(); + mMouseScrollStartX = x; + mMouseScrollStartY = y; + } + } + mEmulator.sendMouseEvent(button, x, y, pressed); + } + + /** Perform a scroll, either from dragging the screen or by scrolling a mouse wheel. */ + void doScroll(MotionEvent event, int rowsDown) { + boolean up = rowsDown < 0; + int amount = Math.abs(rowsDown); + for (int i = 0; i < amount; i++) { + if (mEmulator.isMouseTrackingActive()) { + sendMouseEventCode(event, up ? TerminalEmulator.MOUSE_WHEELUP_BUTTON : TerminalEmulator.MOUSE_WHEELDOWN_BUTTON, true); + } else if (mEmulator.isAlternateBufferActive()) { + // Send up and down key events for scrolling, which is what some terminals do to make scroll work in + // e.g. less, which shifts to the alt screen without mouse handling. + handleKeyCode(up ? KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN, 0); + } else { + mTopRow = Math.min(0, Math.max(-(mEmulator.getScreen().getActiveTranscriptRows()), mTopRow + (up ? -1 : 1))); + if (!awakenScrollBars()) invalidate(); + } + } + } + + /** Overriding {@link View#onGenericMotionEvent(MotionEvent)}. */ + @Override + public boolean onGenericMotionEvent(MotionEvent event) { + if (mEmulator != null && event.isFromSource(InputDevice.SOURCE_MOUSE) && event.getAction() == MotionEvent.ACTION_SCROLL) { + // Handle mouse wheel scrolling. + boolean up = event.getAxisValue(MotionEvent.AXIS_VSCROLL) > 0.0f; + doScroll(event, up ? -3 : 3); + return true; + } + return false; + } + + @SuppressLint("ClickableViewAccessibility") + @Override + @TargetApi(23) + public boolean onTouchEvent(MotionEvent event) { + if (mEmulator == null) return true; + final int action = event.getAction(); + + if (isSelectingText()) { + updateFloatingToolbarVisibility(event); + mGestureRecognizer.onTouchEvent(event); + return true; + } else if (event.isFromSource(InputDevice.SOURCE_MOUSE)) { + if (event.isButtonPressed(MotionEvent.BUTTON_SECONDARY)) { + if (action == MotionEvent.ACTION_DOWN) showContextMenu(); + return true; + } else if (event.isButtonPressed(MotionEvent.BUTTON_TERTIARY)) { + ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clipData = clipboardManager.getPrimaryClip(); + if (clipData != null) { + ClipData.Item clipItem = clipData.getItemAt(0); + if (clipItem != null) { + CharSequence text = clipItem.coerceToText(getContext()); + if (!TextUtils.isEmpty(text)) mEmulator.paste(text.toString()); + } + } + } else if (mEmulator.isMouseTrackingActive()) { // BUTTON_PRIMARY. + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_UP: + sendMouseEventCode(event, TerminalEmulator.MOUSE_LEFT_BUTTON, event.getAction() == MotionEvent.ACTION_DOWN); + break; + case MotionEvent.ACTION_MOVE: + sendMouseEventCode(event, TerminalEmulator.MOUSE_LEFT_BUTTON_MOVED, true); + break; + } + } + } + + mGestureRecognizer.onTouchEvent(event); + return true; + } + + @Override + public boolean onKeyPreIme(int keyCode, KeyEvent event) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) + mClient.logInfo(LOG_TAG, "onKeyPreIme(keyCode=" + keyCode + ", event=" + event + ")"); + if (keyCode == KeyEvent.KEYCODE_BACK) { + cancelRequestAutoFill(); + if (isSelectingText()) { + stopTextSelectionMode(); + return true; + } else if (mClient.shouldBackButtonBeMappedToEscape()) { + // Intercept back button to treat it as escape: + switch (event.getAction()) { + case KeyEvent.ACTION_DOWN: + return onKeyDown(keyCode, event); + case KeyEvent.ACTION_UP: + return onKeyUp(keyCode, event); + } + } + } else if (mClient.shouldUseCtrlSpaceWorkaround() && + keyCode == KeyEvent.KEYCODE_SPACE && event.isCtrlPressed()) { + /* ctrl+space does not work on some ROMs without this workaround. + However, this breaks it on devices where it works out of the box. */ + return onKeyDown(keyCode, event); + } + return super.onKeyPreIme(keyCode, event); + } + + /** + * Key presses in software keyboards will generally NOT trigger this listener, although some + * may elect to do so in some situations. Do not rely on this to catch software key presses. + * Gboard calls this when shouldEnforceCharBasedInput() is disabled (InputType.TYPE_NULL) instead + * of calling commitText(), with deviceId=-1. However, Hacker's Keyboard, OpenBoard, LG Keyboard + * call commitText(). + * + * This function may also be called directly without android calling it, like by + * `TerminalExtraKeys` which generates a KeyEvent manually which uses {@link KeyCharacterMap#VIRTUAL_KEYBOARD} + * as the device (deviceId=-1), as does Gboard. That would normally use mappings defined in + * `/system/usr/keychars/Virtual.kcm`. You can run `dumpsys input` to find the `KeyCharacterMapFile` + * used by virtual keyboard or hardware keyboard. Note that virtual keyboard device is not the + * same as software keyboard, like Gboard, etc. Its a fake device used for generating events and + * for testing. + * + * We handle shift key in `commitText()` to convert codepoint to uppercase case there with a + * call to {@link Character#toUpperCase(int)}, but here we instead rely on getUnicodeChar() for + * conversion of keyCode, for both hardware keyboard shift key (via effectiveMetaState) and + * `mClient.readShiftKey()`, based on value in kcm files. + * This may result in different behaviour depending on keyboard and android kcm files set for the + * InputDevice for the event passed to this function. This will likely be an issue for non-english + * languages since `Virtual.kcm` in english only by default or at least in AOSP. For both hardware + * shift key (via effectiveMetaState) and `mClient.readShiftKey()`, `getUnicodeChar()` is used + * for shift specific behaviour which usually is to uppercase. + * + * For fn key on hardware keyboard, android checks kcm files for hardware keyboards, which is + * `Generic.kcm` by default, unless a vendor specific one is defined. The event passed will have + * {@link KeyEvent#META_FUNCTION_ON} set. If the kcm file only defines a single character or unicode + * code point `\\uxxxx`, then only one event is passed with that value. However, if kcm defines + * a `fallback` key for fn or others, like `key DPAD_UP { ... fn: fallback PAGE_UP }`, then + * android will first pass an event with original key `DPAD_UP` and {@link KeyEvent#META_FUNCTION_ON} + * set. But this function will not consume it and android will pass another event with `PAGE_UP` + * and {@link KeyEvent#META_FUNCTION_ON} not set, which will be consumed. + * + * Now there are some other issues as well, firstly ctrl and alt flags are not passed to + * `getUnicodeChar()`, so modified key values in kcm are not used. Secondly, if the kcm file + * for other modifiers like shift or fn define a non-alphabet, like { fn: '\u0015' } to act as + * DPAD_LEFT, the `getUnicodeChar()` will correctly return `21` as the code point but action will + * not happen because the `handleKeyCode()` function that transforms DPAD_LEFT to `\033[D` + * escape sequence for the terminal to perform the left action would not be called since its + * called before `getUnicodeChar()` and terminal will instead get `21 0x15 Negative Acknowledgement`. + * The solution to such issues is calling `getUnicodeChar()` before the call to `handleKeyCode()` + * if user has defined a custom kcm file, like done in POC mentioned in #2237. Note that + * Hacker's Keyboard calls `commitText()` so don't test fn/shift with it for this function. + * https://github.com/termux/termux-app/pull/2237 + * https://github.com/agnostic-apollo/termux-app/blob/terminal-code-point-custom-mapping/terminal-view/src/main/java/com/termux/view/TerminalView.java + * + * Key Character Map (kcm) and Key Layout (kl) files info: + * https://source.android.com/devices/input/key-character-map-files + * https://source.android.com/devices/input/key-layout-files + * https://source.android.com/devices/input/keyboard-devices + * AOSP kcm and kl files: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/base/data/keyboards + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/base/packages/InputDevices/res/raw + * + * KeyCodes: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/base/core/java/android/view/KeyEvent.java + * https://cs.android.com/android/platform/superproject/+/master:frameworks/native/include/android/keycodes.h + * + * `dumpsys input`: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/services/inputflinger/reader/EventHub.cpp;l=1917 + * + * Loading of keymap: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/services/inputflinger/reader/EventHub.cpp;l=1644 + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/libs/input/Keyboard.cpp;l=41 + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/libs/input/InputDevice.cpp + * OVERLAY keymaps for hardware keyboards may be combined as well: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/libs/input/KeyCharacterMap.cpp;l=165 + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/libs/input/KeyCharacterMap.cpp;l=831 + * + * Parse kcm file: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/libs/input/KeyCharacterMap.cpp;l=727 + * Parse key value: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/libs/input/KeyCharacterMap.cpp;l=981 + * + * `KeyEvent.getUnicodeChar()` + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/base/core/java/android/view/KeyEvent.java;l=2716 + * https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/android/view/KeyCharacterMap.java;l=368 + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/base/core/jni/android_view_KeyCharacterMap.cpp;l=117 + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/native/libs/input/KeyCharacterMap.cpp;l=231 + * + * Keyboard layouts advertised by applications, like for hardware keyboards via #ACTION_QUERY_KEYBOARD_LAYOUTS + * Config is stored in `/data/system/input-manager-state.xml` + * https://github.com/ris58h/custom-keyboard-layout + * Loading from apps: + * https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/core/java/com/android/server/input/InputManagerService.java;l=1221 + * Set: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/base/core/java/android/hardware/input/InputManager.java;l=89 + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/base/core/java/android/hardware/input/InputManager.java;l=543 + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:packages/apps/Settings/src/com/android/settings/inputmethod/KeyboardLayoutDialogFragment.java;l=167 + * https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/core/java/com/android/server/input/InputManagerService.java;l=1385 + * https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/core/java/com/android/server/input/PersistentDataStore.java + * Get overlay keyboard layout + * https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/core/java/com/android/server/input/InputManagerService.java;l=2158 + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r40:frameworks/base/services/core/jni/com_android_server_input_InputManagerService.cpp;l=616 + */ + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) + mClient.logInfo(LOG_TAG, "onKeyDown(keyCode=" + keyCode + ", isSystem()=" + event.isSystem() + ", event=" + event + ")"); + if (mEmulator == null) return true; + if (isSelectingText()) { + stopTextSelectionMode(); + } + + if (mClient.onKeyDown(keyCode, event, mTermSession)) { + invalidate(); + return true; + } else if (event.isSystem() && (!mClient.shouldBackButtonBeMappedToEscape() || keyCode != KeyEvent.KEYCODE_BACK)) { + return super.onKeyDown(keyCode, event); + } else if (event.getAction() == KeyEvent.ACTION_MULTIPLE && keyCode == KeyEvent.KEYCODE_UNKNOWN) { + mTermSession.write(event.getCharacters()); + return true; + } + + final int metaState = event.getMetaState(); + final boolean controlDown = event.isCtrlPressed() || mClient.readControlKey(); + final boolean leftAltDown = (metaState & KeyEvent.META_ALT_LEFT_ON) != 0 || mClient.readAltKey(); + final boolean shiftDown = event.isShiftPressed() || mClient.readShiftKey(); + final boolean rightAltDownFromEvent = (metaState & KeyEvent.META_ALT_RIGHT_ON) != 0; + + int keyMod = 0; + if (controlDown) keyMod |= KeyHandler.KEYMOD_CTRL; + if (event.isAltPressed() || leftAltDown) keyMod |= KeyHandler.KEYMOD_ALT; + if (shiftDown) keyMod |= KeyHandler.KEYMOD_SHIFT; + if (event.isNumLockOn()) keyMod |= KeyHandler.KEYMOD_NUM_LOCK; + // https://github.com/termux/termux-app/issues/731 + if (!event.isFunctionPressed() && handleKeyCode(keyCode, keyMod)) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) mClient.logInfo(LOG_TAG, "handleKeyCode() took key event"); + return true; + } + + // Clear Ctrl since we handle that ourselves: + int bitsToClear = KeyEvent.META_CTRL_MASK; + if (rightAltDownFromEvent) { + // Let right Alt/Alt Gr be used to compose characters. + } else { + // Use left alt to send to terminal (e.g. Left Alt+B to jump back a word), so remove: + bitsToClear |= KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON; + } + int effectiveMetaState = event.getMetaState() & ~bitsToClear; + + if (shiftDown) effectiveMetaState |= KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON; + if (mClient.readFnKey()) effectiveMetaState |= KeyEvent.META_FUNCTION_ON; + + int result = event.getUnicodeChar(effectiveMetaState); + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) + mClient.logInfo(LOG_TAG, "KeyEvent#getUnicodeChar(" + effectiveMetaState + ") returned: " + result); + if (result == 0) { + return false; + } + + int oldCombiningAccent = mCombiningAccent; + if ((result & KeyCharacterMap.COMBINING_ACCENT) != 0) { + // If entered combining accent previously, write it out: + if (mCombiningAccent != 0) + inputCodePoint(mCombiningAccent, controlDown, leftAltDown); + mCombiningAccent = result & KeyCharacterMap.COMBINING_ACCENT_MASK; + } else { + if (mCombiningAccent != 0) { + int combinedChar = KeyCharacterMap.getDeadChar(mCombiningAccent, result); + if (combinedChar > 0) result = combinedChar; + mCombiningAccent = 0; + } + inputCodePoint(result, controlDown, leftAltDown); + } + + if (mCombiningAccent != oldCombiningAccent) invalidate(); + + return true; + } + + public void inputCodePoint(int codePoint, boolean controlDownFromEvent, boolean leftAltDownFromEvent) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) { + mClient.logInfo(LOG_TAG, "inputCodePoint(codePoint=" + codePoint + ", controlDownFromEvent=" + controlDownFromEvent + ", leftAltDownFromEvent=" + + leftAltDownFromEvent + ")"); + } + + if (mTermSession == null) return; + + // Ensure cursor is shown when a key is pressed down like long hold on (arrow) keys + if (mEmulator != null) + mEmulator.setCursorBlinkState(true); + + final boolean controlDown = controlDownFromEvent || mClient.readControlKey(); + final boolean altDown = leftAltDownFromEvent || mClient.readAltKey(); + + if (mClient.onCodePoint(codePoint, controlDown, mTermSession)) return; + + if (controlDown) { + if (codePoint >= 'a' && codePoint <= 'z') { + codePoint = codePoint - 'a' + 1; + } else if (codePoint >= 'A' && codePoint <= 'Z') { + codePoint = codePoint - 'A' + 1; + } else if (codePoint == ' ' || codePoint == '2') { + codePoint = 0; + } else if (codePoint == '[' || codePoint == '3') { + codePoint = 27; // ^[ (Esc) + } else if (codePoint == '\\' || codePoint == '4') { + codePoint = 28; + } else if (codePoint == ']' || codePoint == '5') { + codePoint = 29; + } else if (codePoint == '^' || codePoint == '6') { + codePoint = 30; // control-^ + } else if (codePoint == '_' || codePoint == '7' || codePoint == '/') { + // "Ctrl-/ sends 0x1f which is equivalent of Ctrl-_ since the days of VT102" + // - http://apple.stackexchange.com/questions/24261/how-do-i-send-c-that-is-control-slash-to-the-terminal + codePoint = 31; + } else if (codePoint == '8') { + codePoint = 127; // DEL + } + } + + if (codePoint > -1) { + // Work around bluetooth keyboards sending funny unicode characters instead + // of the more normal ones from ASCII that terminal programs expect - the + // desire to input the original characters should be low. + switch (codePoint) { + case 0x02DC: // SMALL TILDE. + codePoint = 0x007E; // TILDE (~). + break; + case 0x02CB: // MODIFIER LETTER GRAVE ACCENT. + codePoint = 0x0060; // GRAVE ACCENT (`). + break; + case 0x02C6: // MODIFIER LETTER CIRCUMFLEX ACCENT. + codePoint = 0x005E; // CIRCUMFLEX ACCENT (^). + break; + } + + // If left alt, send escape before the code point to make e.g. Alt+B and Alt+F work in readline: + mTermSession.writeCodePoint(altDown, codePoint); + } + } + + /** Input the specified keyCode if applicable and return if the input was consumed. */ + public boolean handleKeyCode(int keyCode, int keyMod) { + // Ensure cursor is shown when a key is pressed down like long hold on (arrow) keys + if (mEmulator != null) + mEmulator.setCursorBlinkState(true); + + if (handleKeyCodeAction(keyCode, keyMod)) + return true; + + TerminalEmulator term = mTermSession.getEmulator(); + String code = KeyHandler.getCode(keyCode, keyMod, term.isCursorKeysApplicationMode(), term.isKeypadApplicationMode()); + if (code == null) return false; + mTermSession.write(code); + return true; + } + + public boolean handleKeyCodeAction(int keyCode, int keyMod) { + boolean shiftDown = (keyMod & KeyHandler.KEYMOD_SHIFT) != 0; + + switch (keyCode) { + case KeyEvent.KEYCODE_PAGE_UP: + case KeyEvent.KEYCODE_PAGE_DOWN: + // shift+page_up and shift+page_down should scroll scrollback history instead of + // scrolling command history or changing pages + if (shiftDown) { + long time = SystemClock.uptimeMillis(); + MotionEvent motionEvent = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0); + doScroll(motionEvent, keyCode == KeyEvent.KEYCODE_PAGE_UP ? -mEmulator.mRows : mEmulator.mRows); + motionEvent.recycle(); + return true; + } + } + + return false; + } + + /** + * Called when a key is released in the view. + * + * @param keyCode The keycode of the key which was released. + * @param event A {@link KeyEvent} describing the event. + * @return Whether the event was handled. + */ + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) + mClient.logInfo(LOG_TAG, "onKeyUp(keyCode=" + keyCode + ", event=" + event + ")"); + + // Do not return for KEYCODE_BACK and send it to the client since user may be trying + // to exit the activity. + if (mEmulator == null && keyCode != KeyEvent.KEYCODE_BACK) return true; + + if (mClient.onKeyUp(keyCode, event)) { + invalidate(); + return true; + } else if (event.isSystem()) { + // Let system key events through. + return super.onKeyUp(keyCode, event); + } + + return true; + } + + /** + * This is called during layout when the size of this view has changed. If you were just added to the view + * hierarchy, you're called with the old values of 0. + */ + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + updateSize(); + } + + /** Check if the terminal size in rows and columns should be updated. */ + public void updateSize() { + int viewWidth = getWidth(); + int viewHeight = getHeight(); + if (viewWidth == 0 || viewHeight == 0 || mTermSession == null) return; + + // Set to 80 and 24 if you want to enable vttest. + int newColumns = Math.max(4, (int) (viewWidth / mRenderer.mFontWidth)); + int newRows = Math.max(4, (viewHeight - mRenderer.mFontLineSpacingAndAscent) / mRenderer.mFontLineSpacing); + + if (mEmulator == null || (newColumns != mEmulator.mColumns || newRows != mEmulator.mRows)) { + mTermSession.updateSize(newColumns, newRows, (int) mRenderer.getFontWidth(), mRenderer.getFontLineSpacing()); + mEmulator = mTermSession.getEmulator(); + mClient.onEmulatorSet(); + + // Update mTerminalCursorBlinkerRunnable inner class mEmulator on session change + if (mTerminalCursorBlinkerRunnable != null) + mTerminalCursorBlinkerRunnable.setEmulator(mEmulator); + + mTopRow = 0; + scrollTo(0, 0); + invalidate(); + } + } + + @Override + protected void onDraw(Canvas canvas) { + if (mEmulator == null) { + canvas.drawColor(0XFF000000); + } else { + // render the terminal view and highlight any selected text + int[] sel = mDefaultSelectors; + if (mTextSelectionCursorController != null) { + mTextSelectionCursorController.getSelectors(sel); + } + + mRenderer.render(mEmulator, canvas, mTopRow, sel[0], sel[1], sel[2], sel[3]); + + // render the text selection handles + renderTextSelection(); + } + } + + public TerminalSession getCurrentSession() { + return mTermSession; + } + + private CharSequence getText() { + return mEmulator.getScreen().getSelectedText(0, mTopRow, mEmulator.mColumns, mTopRow + mEmulator.mRows); + } + + public int getCursorX(float x) { + return (int) (x / mRenderer.mFontWidth); + } + + public int getCursorY(float y) { + return (int) (((y - 40) / mRenderer.mFontLineSpacing) + mTopRow); + } + + public int getPointX(int cx) { + if (cx > mEmulator.mColumns) { + cx = mEmulator.mColumns; + } + return Math.round(cx * mRenderer.mFontWidth); + } + + public int getPointY(int cy) { + return Math.round((cy - mTopRow) * mRenderer.mFontLineSpacing); + } + + public int getTopRow() { + return mTopRow; + } + + public void setTopRow(int mTopRow) { + this.mTopRow = mTopRow; + } + + + + /** + * Define functions required for AutoFill API + */ + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public void autofill(AutofillValue value) { + if (value.isText()) { + mTermSession.write(value.getTextValue().toString()); + } + + resetAutoFill(); + } + + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public int getAutofillType() { + return mAutoFillType; + } + + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public String[] getAutofillHints() { + return mAutoFillHints; + } + + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public AutofillValue getAutofillValue() { + return AutofillValue.forText(""); + } + + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public int getImportantForAutofill() { + return mAutoFillImportance; + } + + @RequiresApi(api = Build.VERSION_CODES.O) + private synchronized void resetAutoFill() { + // Restore none type so that AutoFill UI isn't shown anymore. + mAutoFillType = AUTOFILL_TYPE_NONE; + mAutoFillImportance = IMPORTANT_FOR_AUTOFILL_NO; + mAutoFillHints = new String[0]; + } + + public AutofillManager getAutoFillManagerService() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return null; + + try { + Context context = getContext(); + if (context == null) return null; + return context.getSystemService(AutofillManager.class); + } catch (Exception e) { + mClient.logStackTraceWithMessage(LOG_TAG, "Failed to get AutofillManager service", e); + return null; + } + } + + public boolean isAutoFillEnabled() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return false; + + try { + AutofillManager autofillManager = getAutoFillManagerService(); + return autofillManager != null && autofillManager.isEnabled(); + } catch (Exception e) { + mClient.logStackTraceWithMessage(LOG_TAG, "Failed to check if Autofill is enabled", e); + return false; + } + } + + public synchronized void requestAutoFillUsername() { + requestAutoFill( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? new String[]{View.AUTOFILL_HINT_USERNAME} : + null); + } + + public synchronized void requestAutoFillPassword() { + requestAutoFill( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? new String[]{View.AUTOFILL_HINT_PASSWORD} : + null); + } + + public synchronized void requestAutoFill(String[] autoFillHints) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return; + if (autoFillHints == null || autoFillHints.length < 1) return; + + try { + AutofillManager autofillManager = getAutoFillManagerService(); + if (autofillManager != null && autofillManager.isEnabled()) { + // Update type that will be returned by `getAutofillType()` so that AutoFill UI is shown. + mAutoFillType = AUTOFILL_TYPE_TEXT; + // Update importance that will be returned by `getImportantForAutofill()` so that + // AutoFill considers the view as important. + mAutoFillImportance = IMPORTANT_FOR_AUTOFILL_YES; + // Update hints that will be returned by `getAutofillHints()` for which to show AutoFill UI. + mAutoFillHints = autoFillHints; + autofillManager.requestAutofill(this); + } + } catch (Exception e) { + mClient.logStackTraceWithMessage(LOG_TAG, "Failed to request Autofill", e); + } + } + + public synchronized void cancelRequestAutoFill() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return; + if (mAutoFillType == AUTOFILL_TYPE_NONE) return; + + try { + AutofillManager autofillManager = getAutoFillManagerService(); + if (autofillManager != null && autofillManager.isEnabled()) { + resetAutoFill(); + autofillManager.cancel(); + } + } catch (Exception e) { + mClient.logStackTraceWithMessage(LOG_TAG, "Failed to cancel Autofill request", e); + } + } + + + + + + /** + * Set terminal cursor blinker rate. It must be between {@link #TERMINAL_CURSOR_BLINK_RATE_MIN} + * and {@link #TERMINAL_CURSOR_BLINK_RATE_MAX}, otherwise it will be disabled. + * + * The {@link #setTerminalCursorBlinkerState(boolean, boolean)} must be called after this + * for changes to take effect if not disabling. + * + * @param blinkRate The value to set. + * @return Returns {@code true} if setting blinker rate was successfully set, otherwise [@code false}. + */ + public synchronized boolean setTerminalCursorBlinkerRate(int blinkRate) { + boolean result; + + // If cursor blinking rate is not valid + if (blinkRate != 0 && (blinkRate < TERMINAL_CURSOR_BLINK_RATE_MIN || blinkRate > TERMINAL_CURSOR_BLINK_RATE_MAX)) { + mClient.logError(LOG_TAG, "The cursor blink rate must be in between " + TERMINAL_CURSOR_BLINK_RATE_MIN + "-" + TERMINAL_CURSOR_BLINK_RATE_MAX + ": " + blinkRate); + mTerminalCursorBlinkerRate = 0; + result = false; + } else { + mClient.logVerbose(LOG_TAG, "Setting cursor blinker rate to " + blinkRate); + mTerminalCursorBlinkerRate = blinkRate; + result = true; + } + + if (mTerminalCursorBlinkerRate == 0) { + mClient.logVerbose(LOG_TAG, "Cursor blinker disabled"); + stopTerminalCursorBlinker(); + } + + return result; + } + + /** + * Sets whether cursor blinker should be started or stopped. Cursor blinker will only be + * started if {@link #mTerminalCursorBlinkerRate} does not equal 0 and is between + * {@link #TERMINAL_CURSOR_BLINK_RATE_MIN} and {@link #TERMINAL_CURSOR_BLINK_RATE_MAX}. + * + * This should be called when the view holding this activity is resumed or stopped so that + * cursor blinker does not run when activity is not visible. If you call this on onResume() + * to start cursor blinking, then ensure that {@link #mEmulator} is set, otherwise wait for the + * {@link TerminalViewClient#onEmulatorSet()} event after calling {@link #attachSession(TerminalSession)} + * for the first session added in the activity since blinking will not start if {@link #mEmulator} + * is not set, like if activity is started again after exiting it with double back press. Do not + * call this directly after {@link #attachSession(TerminalSession)} since {@link #updateSize()} + * may return without setting {@link #mEmulator} since width/height may be 0. Its called again in + * {@link #onSizeChanged(int, int, int, int)}. Calling on onResume() if emulator is already set + * is necessary, since onEmulatorSet() may not be called after activity is started after device + * display timeout with double tap and not power button. + * + * It should also be called on the + * {@link com.termux.terminal.TerminalSessionClient#onTerminalCursorStateChange(boolean)} + * callback when cursor is enabled or disabled so that blinker is disabled if cursor is not + * to be shown. It should also be checked if activity is visible if blinker is to be started + * before calling this. + * + * It should also be called after terminal is reset with {@link TerminalSession#reset()} in case + * cursor blinker was disabled before reset due to call to + * {@link com.termux.terminal.TerminalSessionClient#onTerminalCursorStateChange(boolean)}. + * + * How cursor blinker starting works is by registering a {@link Runnable} with the looper of + * the main thread of the app which when run, toggles the cursor blinking state and re-registers + * itself to be called with the delay set by {@link #mTerminalCursorBlinkerRate}. When cursor + * blinking needs to be disabled, we just cancel any callbacks registered. We don't run our own + * "thread" and let the thread for the main looper do the work for us, whose usage is also + * required to update the UI, since it also handles other calls to update the UI as well based + * on a queue. + * + * Note that when moving cursor in text editors like nano, the cursor state is quickly + * toggled `-> off -> on`, which would call this very quickly sequentially. So that if cursor + * is moved 2 or more times quickly, like long hold on arrow keys, it would trigger + * `-> off -> on -> off -> on -> ...`, and the "on" callback at index 2 is automatically + * cancelled by next "off" callback at index 3 before getting a chance to be run. For this case + * we log only if {@link #TERMINAL_VIEW_KEY_LOGGING_ENABLED} is enabled, otherwise would clutter + * the log. We don't start the blinking with a delay to immediately show cursor in case it was + * previously not visible. + * + * @param start If cursor blinker should be started or stopped. + * @param startOnlyIfCursorEnabled If set to {@code true}, then it will also be checked if the + * cursor is even enabled by {@link TerminalEmulator} before + * starting the cursor blinker. + */ + public synchronized void setTerminalCursorBlinkerState(boolean start, boolean startOnlyIfCursorEnabled) { + // Stop any existing cursor blinker callbacks + stopTerminalCursorBlinker(); + + if (mEmulator == null) return; + + mEmulator.setCursorBlinkingEnabled(false); + + if (start) { + // If cursor blinker is not enabled or is not valid + if (mTerminalCursorBlinkerRate < TERMINAL_CURSOR_BLINK_RATE_MIN || mTerminalCursorBlinkerRate > TERMINAL_CURSOR_BLINK_RATE_MAX) + return; + // If cursor blinder is to be started only if cursor is enabled + else if (startOnlyIfCursorEnabled && ! mEmulator.isCursorEnabled()) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) + mClient.logVerbose(LOG_TAG, "Ignoring call to start cursor blinker since cursor is not enabled"); + return; + } + + // Start cursor blinker runnable + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) + mClient.logVerbose(LOG_TAG, "Starting cursor blinker with the blink rate " + mTerminalCursorBlinkerRate); + if (mTerminalCursorBlinkerHandler == null) + mTerminalCursorBlinkerHandler = new Handler(Looper.getMainLooper()); + mTerminalCursorBlinkerRunnable = new TerminalCursorBlinkerRunnable(mEmulator, mTerminalCursorBlinkerRate); + mEmulator.setCursorBlinkingEnabled(true); + mTerminalCursorBlinkerRunnable.run(); + } + } + + /** + * Cancel the terminal cursor blinker callbacks + */ + private void stopTerminalCursorBlinker() { + if (mTerminalCursorBlinkerHandler != null && mTerminalCursorBlinkerRunnable != null) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) + mClient.logVerbose(LOG_TAG, "Stopping cursor blinker"); + mTerminalCursorBlinkerHandler.removeCallbacks(mTerminalCursorBlinkerRunnable); + } + } + + private class TerminalCursorBlinkerRunnable implements Runnable { + + private TerminalEmulator mEmulator; + private final int mBlinkRate; + + // Initialize with false so that initial blink state is visible after toggling + boolean mCursorVisible = false; + + public TerminalCursorBlinkerRunnable(TerminalEmulator emulator, int blinkRate) { + mEmulator = emulator; + mBlinkRate = blinkRate; + } + + public void setEmulator(TerminalEmulator emulator) { + mEmulator = emulator; + } + + public void run() { + try { + if (mEmulator != null) { + // Toggle the blink state and then invalidate() the view so + // that onDraw() is called, which then calls TerminalRenderer.render() + // which checks with TerminalEmulator.shouldCursorBeVisible() to decide whether + // to draw the cursor or not + mCursorVisible = !mCursorVisible; + //mClient.logVerbose(LOG_TAG, "Toggling cursor blink state to " + mCursorVisible); + mEmulator.setCursorBlinkState(mCursorVisible); + invalidate(); + } + } finally { + // Recall the Runnable after mBlinkRate milliseconds to toggle the blink state + mTerminalCursorBlinkerHandler.postDelayed(this, mBlinkRate); + } + } + } + + + + /** + * Define functions required for text selection and its handles. + */ + TextSelectionCursorController getTextSelectionCursorController() { + if (mTextSelectionCursorController == null) { + mTextSelectionCursorController = new TextSelectionCursorController(this); + + final ViewTreeObserver observer = getViewTreeObserver(); + if (observer != null) { + observer.addOnTouchModeChangeListener(mTextSelectionCursorController); + } + } + + return mTextSelectionCursorController; + } + + private void showTextSelectionCursors(MotionEvent event) { + getTextSelectionCursorController().show(event); + } + + private boolean hideTextSelectionCursors() { + return getTextSelectionCursorController().hide(); + } + + private void renderTextSelection() { + if (mTextSelectionCursorController != null) + mTextSelectionCursorController.render(); + } + + public boolean isSelectingText() { + if (mTextSelectionCursorController != null) { + return mTextSelectionCursorController.isActive(); + } else { + return false; + } + } + + /** Get the currently selected text if selecting. */ + public String getSelectedText() { + if (isSelectingText() && mTextSelectionCursorController != null) + return mTextSelectionCursorController.getSelectedText(); + else + return null; + } + + /** Get the selected text stored before "MORE" button was pressed on the context menu. */ + @Nullable + public String getStoredSelectedText() { + return mTextSelectionCursorController != null ? mTextSelectionCursorController.getStoredSelectedText() : null; + } + + /** Unset the selected text stored before "MORE" button was pressed on the context menu. */ + public void unsetStoredSelectedText() { + if (mTextSelectionCursorController != null) mTextSelectionCursorController.unsetStoredSelectedText(); + } + + private ActionMode getTextSelectionActionMode() { + if (mTextSelectionCursorController != null) { + return mTextSelectionCursorController.getActionMode(); + } else { + return null; + } + } + + public void startTextSelectionMode(MotionEvent event) { + if (!requestFocus()) { + return; + } + + showTextSelectionCursors(event); + mClient.copyModeChanged(isSelectingText()); + + invalidate(); + } + + public void stopTextSelectionMode() { + if (hideTextSelectionCursors()) { + mClient.copyModeChanged(isSelectingText()); + invalidate(); + } + } + + private void decrementYTextSelectionCursors(int decrement) { + if (mTextSelectionCursorController != null) { + mTextSelectionCursorController.decrementYTextSelectionCursors(decrement); + } + } + + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + + if (mTextSelectionCursorController != null) { + getViewTreeObserver().addOnTouchModeChangeListener(mTextSelectionCursorController); + } + } + + @Override + protected void onDetachedFromWindow() { + super.onDetachedFromWindow(); + + if (mTextSelectionCursorController != null) { + // Might solve the following exception + // android.view.WindowLeaked: Activity com.termux.app.TermuxActivity has leaked window android.widget.PopupWindow + stopTextSelectionMode(); + + getViewTreeObserver().removeOnTouchModeChangeListener(mTextSelectionCursorController); + mTextSelectionCursorController.onDetached(); + } + } + + + + /** + * Define functions required for long hold toolbar. + */ + private final Runnable mShowFloatingToolbar = new Runnable() { + @Override + public void run() { + if (getTextSelectionActionMode() != null) { + getTextSelectionActionMode().hide(0); // hide off. + } + } + }; + + private void showFloatingToolbar() { + if (getTextSelectionActionMode() != null) { + int delay = ViewConfiguration.getDoubleTapTimeout(); + postDelayed(mShowFloatingToolbar, delay); + } + } + + void hideFloatingToolbar() { + if (getTextSelectionActionMode() != null) { + removeCallbacks(mShowFloatingToolbar); + getTextSelectionActionMode().hide(-1); + } + } + + public void updateFloatingToolbarVisibility(MotionEvent event) { + if (getTextSelectionActionMode() != null) { + switch (event.getActionMasked()) { + case MotionEvent.ACTION_MOVE: + hideFloatingToolbar(); + break; + case MotionEvent.ACTION_UP: // fall through + case MotionEvent.ACTION_CANCEL: + showFloatingToolbar(); + } + } + } + +} diff --git a/android/app/src/main/java/com/termux/view/TerminalViewClient.java b/android/app/src/main/java/com/termux/view/TerminalViewClient.java new file mode 100644 index 0000000..d6b49b8 --- /dev/null +++ b/android/app/src/main/java/com/termux/view/TerminalViewClient.java @@ -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); + +} diff --git a/android/app/src/main/java/com/termux/view/textselection/CursorController.java b/android/app/src/main/java/com/termux/view/textselection/CursorController.java new file mode 100644 index 0000000..f0e1cc5 --- /dev/null +++ b/android/app/src/main/java/com/termux/view/textselection/CursorController.java @@ -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(); + +} diff --git a/android/app/src/main/java/com/termux/view/textselection/TextSelectionCursorController.java b/android/app/src/main/java/com/termux/view/textselection/TextSelectionCursorController.java new file mode 100644 index 0000000..07bca5c --- /dev/null +++ b/android/app/src/main/java/com/termux/view/textselection/TextSelectionCursorController.java @@ -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(); + } + +} diff --git a/android/app/src/main/java/com/termux/view/textselection/TextSelectionHandleView.java b/android/app/src/main/java/com/termux/view/textselection/TextSelectionHandleView.java new file mode 100644 index 0000000..ffd3c25 --- /dev/null +++ b/android/app/src/main/java/com/termux/view/textselection/TextSelectionHandleView.java @@ -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; + } + +} diff --git a/android/app/src/main/jniLibs/arm64-v8a/libtermux.so b/android/app/src/main/jniLibs/arm64-v8a/libtermux.so new file mode 100644 index 0000000..0499e68 Binary files /dev/null and b/android/app/src/main/jniLibs/arm64-v8a/libtermux.so differ diff --git a/android/app/src/main/jniLibs/x86_64/libtermux.so b/android/app/src/main/jniLibs/x86_64/libtermux.so new file mode 100644 index 0000000..3660fa2 Binary files /dev/null and b/android/app/src/main/jniLibs/x86_64/libtermux.so differ diff --git a/android/app/src/main/res/drawable/text_select_handle_left_material.xml b/android/app/src/main/res/drawable/text_select_handle_left_material.xml new file mode 100644 index 0000000..576ff4a --- /dev/null +++ b/android/app/src/main/res/drawable/text_select_handle_left_material.xml @@ -0,0 +1,10 @@ + + + diff --git a/android/app/src/main/res/drawable/text_select_handle_right_material.xml b/android/app/src/main/res/drawable/text_select_handle_right_material.xml new file mode 100644 index 0000000..d049d3a --- /dev/null +++ b/android/app/src/main/res/drawable/text_select_handle_right_material.xml @@ -0,0 +1,10 @@ + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..d28b0b5 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..6685797 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..3086623 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..e6b1b42 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..42340b8 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..c9a0137 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + 豆包 + diff --git a/android/app/src/main/res/values/termux_strings.xml b/android/app/src/main/res/values/termux_strings.xml new file mode 100644 index 0000000..a72f21c --- /dev/null +++ b/android/app/src/main/res/values/termux_strings.xml @@ -0,0 +1,10 @@ + + + + 粘贴 + 复制 + 更多… + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..673a4a8 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..e249d00 --- /dev/null +++ b/android/build.gradle.kts @@ -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 +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..63c5aa7 --- /dev/null +++ b/android/gradle.properties @@ -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 diff --git a/android/kernel/README.md b/android/kernel/README.md new file mode 100644 index 0000000..614e2e8 --- /dev/null +++ b/android/kernel/README.md @@ -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:')` 或宿主页注入 `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/` | 单条会话 | +| 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/` | 单个智能体 | +| 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(唯一模块名, "/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`(首次运行会从 `/mcp.servers.json` 复制一份), +支持 `${VAR}` 占位符(`DOUBAO_DATA` 一定可用,指向数据目录)。工具名统一为 `mcp____`。 + +### 三种传输 + +**`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)。 diff --git a/android/kernel/__init__.py b/android/kernel/__init__.py new file mode 100644 index 0000000..237b6e3 --- /dev/null +++ b/android/kernel/__init__.py @@ -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' diff --git a/android/kernel/__main__.py b/android/kernel/__main__.py new file mode 100644 index 0000000..c476d42 --- /dev/null +++ b/android/kernel/__main__.py @@ -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()) diff --git a/android/kernel/agent_loop.py b/android/kernel/agent_loop.py new file mode 100644 index 0000000..a052acb --- /dev/null +++ b/android/kernel/agent_loop.py @@ -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, + } diff --git a/android/kernel/app.py b/android/kernel/app.py new file mode 100644 index 0000000..c204574 --- /dev/null +++ b/android/kernel/app.py @@ -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/ + 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/ + 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 里带斜杠的情况按 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 diff --git a/android/kernel/builtin_tools.py b/android/kernel/builtin_tools.py new file mode 100644 index 0000000..3f0a21f --- /dev/null +++ b/android/kernel/builtin_tools.py @@ -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}, +} diff --git a/android/kernel/defaults.py b/android/kernel/defaults.py new file mode 100644 index 0000000..99d8ccd --- /dev/null +++ b/android/kernel/defaults.py @@ -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'] diff --git a/android/kernel/doubao_entry.py b/android/kernel/doubao_entry.py new file mode 100644 index 0000000..4e6472a --- /dev/null +++ b/android/kernel/doubao_entry.py @@ -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:。 +""" + +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, + ) diff --git a/android/kernel/main.py b/android/kernel/main.py new file mode 100644 index 0000000..8e7de57 --- /dev/null +++ b/android/kernel/main.py @@ -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()) diff --git a/android/kernel/mcp_client.py b/android/kernel/mcp_client.py new file mode 100644 index 0000000..e468c9c --- /dev/null +++ b/android/kernel/mcp_client.py @@ -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____`,避免和 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__') diff --git a/android/kernel/paths.py b/android/kernel/paths.py new file mode 100644 index 0000000..efbe18b --- /dev/null +++ b/android/kernel/paths.py @@ -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_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 diff --git a/android/kernel/providers.py b/android/kernel/providers.py new file mode 100644 index 0000000..06fcaa4 --- /dev/null +++ b/android/kernel/providers.py @@ -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)} diff --git a/android/kernel/speech.py b/android/kernel/speech.py new file mode 100644 index 0000000..16eb591 --- /dev/null +++ b/android/kernel/speech.py @@ -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': ''} + """ + 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, + } diff --git a/android/kernel/store.py b/android/kernel/store.py new file mode 100644 index 0000000..7a1778c --- /dev/null +++ b/android/kernel/store.py @@ -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 diff --git a/android/kernel/tools_runtime.py b/android/kernel/tools_runtime.py new file mode 100644 index 0000000..5a47c5d --- /dev/null +++ b/android/kernel/tools_runtime.py @@ -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) diff --git a/android/kernel/uploads.py b/android/kernel/uploads.py new file mode 100644 index 0000000..beac58e --- /dev/null +++ b/android/kernel/uploads.py @@ -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 diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..7359f02 --- /dev/null +++ b/android/settings.gradle.kts @@ -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") diff --git a/app/.npmrc b/app/.npmrc new file mode 100644 index 0000000..214c29d --- /dev/null +++ b/app/.npmrc @@ -0,0 +1 @@ +registry=https://registry.npmjs.org/ diff --git a/app/lynx.config.ts b/app/lynx.config.ts new file mode 100644 index 0000000..c46537a --- /dev/null +++ b/app/lynx.config.ts @@ -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', + }, + }, +}); diff --git a/app/package-lock.json b/app/package-lock.json new file mode 100644 index 0000000..45ba90d --- /dev/null +++ b/app/package-lock.json @@ -0,0 +1,6543 @@ +{ + "name": "doubao-lynx-app", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "doubao-lynx-app", + "version": "0.1.0", + "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" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.26.2", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", + "integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.25.9", + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@colordx/core": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@colordx/core/-/core-5.8.0.tgz", + "integrity": "sha512-cG0QJAO6VkaRUlIb0zOzX9gfJgs1pjoOL9gZ/PK1kfvBs0GCkADu5oQh6gPxXgQnZ3gV575h+lQRC0NlMDTclA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@emnapi/core": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", + "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", + "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@jest/pattern": { + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.5.0.tgz", + "integrity": "sha512-HdNQYSdRTEBNrginaqzQtTjG0HRMfrra/z6Ok7uL3S87vSlarIVohEsJsSj5edu3MiHoHjAkvPROz5ZjoKai+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-regex-util": "30.5.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/schemas": { + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.5.0.tgz", + "integrity": "sha512-/hunigyNpc4RCjC0VaW3f5RCUZVM2+WQ65qP7z083Gmvac7or2LI50XVNOtE4YPgBpV0yxYiAgorAPGniCoJmg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.34.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/types": { + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.5.1.tgz", + "integrity": "sha512-LvVYn83nnXPl+Rg98nvcFgjx6nRMTArhSn6RAX/w3ELn54S8A42TYZvsCMdGUqTM8S0wyXbtlQdU6Hi6dykj9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/pattern": "30.5.0", + "@jest/schemas": "30.5.0", + "@types/istanbul-lib-coverage": "^2.0.6", + "@types/istanbul-reports": "^3.0.4", + "@types/node": "*", + "@types/yargs": "^17.0.33", + "chalk": "^4.1.2" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jsonjoy.com/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-q6XAnWQDIMA3+FTiOYajoYqySkO+JSat0ytXGSuRdq9uXE7o92gzuQwQM14xaCRlBLGq3v5miDGC4vkVTn54xA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/buffers": { + "version": "17.67.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/buffers/-/buffers-17.67.0.tgz", + "integrity": "sha512-tfExRpYxBvi32vPs9ZHaTjSP4fHAfzSmcahOfNxtvGHcyJel+aibkPlGeBB+7AoC6hL7lXIE++8okecBxx7lcw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/codegen": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/codegen/-/codegen-1.0.0.tgz", + "integrity": "sha512-E8Oy+08cmCf0EK/NMxpaJZmOxPqM+6iSe2S4nlSBrPZOORoDJILxtbSUEDKQyTamm/BVAhIGllOBNU79/dwf0g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-core": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-core/-/fs-core-4.80.0.tgz", + "integrity": "sha512-qMKWshnyjbyhm+NbzqGE3w5y1mckFFEMj0aDPU2/JBNh1BzIjVy9esq9lBmRnNVmhMEkxwDzLZ8Gqh5G1P5Dag==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/fs-node-builtins": "4.80.0", + "@jsonjoy.com/fs-node-utils": "4.80.0", + "thingies": "^2.5.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-fsa": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-fsa/-/fs-fsa-4.80.0.tgz", + "integrity": "sha512-ZBEKl7J6dbkRCfmrFV48Re211A/FHqniTUhsWCsaRteNSOqMgkX3qF1UreVgwB9oSPm81JLAwhIi6Lb/NH/PoA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/fs-core": "4.80.0", + "@jsonjoy.com/fs-node-builtins": "4.80.0", + "@jsonjoy.com/fs-node-utils": "4.80.0", + "thingies": "^2.5.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-node": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node/-/fs-node-4.80.0.tgz", + "integrity": "sha512-yiBlUfkMMRFFGy8CD/h2zd5rPnrM6bjlF+nx2LRAxNV6hOSiuObQIUEE7m7y2VTMisjxCRtzINH94bFGySWL7g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/fs-core": "4.80.0", + "@jsonjoy.com/fs-node-builtins": "4.80.0", + "@jsonjoy.com/fs-node-utils": "4.80.0", + "@jsonjoy.com/fs-print": "4.80.0", + "@jsonjoy.com/fs-snapshot": "4.80.0", + "glob-to-regex.js": "^1.3.1", + "thingies": "^2.5.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-node-builtins": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-builtins/-/fs-node-builtins-4.80.0.tgz", + "integrity": "sha512-OIOIhqaWiwUySFMny4epIAoviXsyMaQQ63PTc3zH+5HEOvarl5hpUmZIhp2m5+OfyKAh5ylxXnQIgew1OgJDVw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-node-to-fsa": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-to-fsa/-/fs-node-to-fsa-4.80.0.tgz", + "integrity": "sha512-ljeaR5xwtX1EyRmB0wvXANUMQZ3mjKcm7z8s2N8D8SLQ04CcAGtUhHFRZQXFb9mhgFyEVMydQGQtSOFS7pcrFQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/fs-fsa": "4.80.0", + "@jsonjoy.com/fs-node-builtins": "4.80.0", + "@jsonjoy.com/fs-node-utils": "4.80.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-node-utils": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-utils/-/fs-node-utils-4.80.0.tgz", + "integrity": "sha512-xwHeVVi3f+Khg/Fmb8i5qoYVmQ08QznE5TWhQokUmIZjz4KBPzU+zt/+bahBI6G1ghtqajt27lWuAciIxApuzA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/fs-node-builtins": "4.80.0", + "glob-to-regex.js": "^1.3.1" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-print": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-print/-/fs-print-4.80.0.tgz", + "integrity": "sha512-1ocZLJw/m/xlq0moaIHO7HV9nHRVBUvdc2zMzhsJGkFOrqfwWvexfCv5cYCPPLRhP+9p3yunoi4Ep5YhRORC9Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/fs-node-utils": "4.80.0", + "tree-dump": "^1.1.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-snapshot": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-snapshot/-/fs-snapshot-4.80.0.tgz", + "integrity": "sha512-3AV23Q1H228KTtJKTUE0nNq8FCtxSvtENOLrEat80wkAJCKHuqQEv8yjhpS8Bei2OEFJAnluGXp9Ri2SWBlROw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/buffers": "^17.65.0", + "@jsonjoy.com/fs-node-utils": "4.80.0", + "@jsonjoy.com/json-pack": "^17.65.0", + "@jsonjoy.com/util": "^17.65.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-snapshot/node_modules/@jsonjoy.com/base64": { + "version": "17.67.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/base64/-/base64-17.67.0.tgz", + "integrity": "sha512-5SEsJGsm15aP8TQGkDfJvz9axgPwAEm98S5DxOuYe8e1EbfajcDmgeXXzccEjh+mLnjqEKrkBdjHWS5vFNwDdw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-snapshot/node_modules/@jsonjoy.com/codegen": { + "version": "17.67.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/codegen/-/codegen-17.67.0.tgz", + "integrity": "sha512-idnkUplROpdBOV0HMcwhsCUS5TRUi9poagdGs70A6S4ux9+/aPuKbh8+UYRTLYQHtXvAdNfQWXDqZEx5k4Dj2Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-snapshot/node_modules/@jsonjoy.com/json-pack": { + "version": "17.67.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/json-pack/-/json-pack-17.67.0.tgz", + "integrity": "sha512-t0ejURcGaZsn1ClbJ/3kFqSOjlryd92eQY465IYrezsXmPcfHPE/av4twRSxf6WE+TkZgLY+71vCZbiIiFKA/w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/base64": "17.67.0", + "@jsonjoy.com/buffers": "17.67.0", + "@jsonjoy.com/codegen": "17.67.0", + "@jsonjoy.com/json-pointer": "17.67.0", + "@jsonjoy.com/util": "17.67.0", + "hyperdyperid": "^1.2.0", + "thingies": "^2.5.0", + "tree-dump": "^1.1.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-snapshot/node_modules/@jsonjoy.com/json-pointer": { + "version": "17.67.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/json-pointer/-/json-pointer-17.67.0.tgz", + "integrity": "sha512-+iqOFInH+QZGmSuaybBUNdh7yvNrXvqR+h3wjXm0N/3JK1EyyFAeGJvqnmQL61d1ARLlk/wJdFKSL+LHJ1eaUA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/util": "17.67.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/fs-snapshot/node_modules/@jsonjoy.com/util": { + "version": "17.67.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/util/-/util-17.67.0.tgz", + "integrity": "sha512-6+8xBaz1rLSohlGh68D1pdw3AwDi9xydm8QNlAFkvnavCJYSze+pxoW2VKP8p308jtlMRLs5NTHfPlZLd4w7ew==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/buffers": "17.67.0", + "@jsonjoy.com/codegen": "17.67.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/json-pack": { + "version": "1.21.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/json-pack/-/json-pack-1.21.0.tgz", + "integrity": "sha512-+AKG+R2cfZMShzrF2uQw34v3zbeDYUqnQ+jg7ORic3BGtfw9p/+N6RJbq/kkV8JmYZaINknaEQ2m0/f693ZPpg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/base64": "^1.1.2", + "@jsonjoy.com/buffers": "^1.2.0", + "@jsonjoy.com/codegen": "^1.0.0", + "@jsonjoy.com/json-pointer": "^1.0.2", + "@jsonjoy.com/util": "^1.9.0", + "hyperdyperid": "^1.2.0", + "thingies": "^2.5.0", + "tree-dump": "^1.1.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/json-pack/node_modules/@jsonjoy.com/buffers": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/buffers/-/buffers-1.2.1.tgz", + "integrity": "sha512-12cdlDwX4RUM3QxmUbVJWqZ/mrK6dFQH4Zxq6+r1YXKXYBNgZXndx2qbCJwh3+WWkCSn67IjnlG3XYTvmvYtgA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/json-pointer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/json-pointer/-/json-pointer-1.0.2.tgz", + "integrity": "sha512-Fsn6wM2zlDzY1U+v4Nc8bo3bVqgfNTGcn6dMgs6FjrEnt4ZCe60o6ByKRjOGlI2gow0aE/Q41QOigdTqkyK5fg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/codegen": "^1.0.0", + "@jsonjoy.com/util": "^1.9.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/util": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/util/-/util-1.9.0.tgz", + "integrity": "sha512-pLuQo+VPRnN8hfPqUTLTHk126wuYdXVxE6aDmjSeV4NCAgyxWbiOIeNJVtID3h1Vzpoi9m4jXezf73I6LgabgQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/buffers": "^1.0.0", + "@jsonjoy.com/codegen": "^1.0.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/util/node_modules/@jsonjoy.com/buffers": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/buffers/-/buffers-1.2.1.tgz", + "integrity": "sha512-12cdlDwX4RUM3QxmUbVJWqZ/mrK6dFQH4Zxq6+r1YXKXYBNgZXndx2qbCJwh3+WWkCSn67IjnlG3XYTvmvYtgA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@lynx-js/cache-events-webpack-plugin": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@lynx-js/cache-events-webpack-plugin/-/cache-events-webpack-plugin-0.2.1.tgz", + "integrity": "sha512-BclJ0H6tEdI0ZX0YrxNqRLuVcUvm5SyHxgLvvCHUWwRWlYc37xewv2sQTdPHNipNbmq9xvrNuauJIDucdjOouw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/webpack-runtime-globals": "^0.0.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@lynx-js/chunk-loading-webpack-plugin": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@lynx-js/chunk-loading-webpack-plugin/-/chunk-loading-webpack-plugin-0.4.2.tgz", + "integrity": "sha512-iU7rgaDKZwchDnFA3wYK8RWlfUS0EyxtUgL+ojlGmBwWXY4BfysShf1jvv6FcRq7in7nQRss2U4Gfi7x1161wA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/webpack-runtime-globals": "0.0.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@lynx-js/css-extract-webpack-plugin": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@lynx-js/css-extract-webpack-plugin/-/css-extract-webpack-plugin-0.11.0.tgz", + "integrity": "sha512-5XcrXYWzZo2tLy9IRIf2GVn2i+oADAU5tgO9zuBUSdc3GEiworghEezhwvLQgOdq140KoZ7OlKPK1BXkkk0DeA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@lynx-js/template-webpack-plugin": "^0.16.0" + } + }, + "node_modules/@lynx-js/css-serializer": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/@lynx-js/css-serializer/-/css-serializer-0.1.9.tgz", + "integrity": "sha512-O4wthGp3eBcE9mX+A7Ojla8mRJwucBhRJthEha5dgtvBfcx+P8GI6A0VvhvNwjclTaLnqNNbBRd+ClJQtirptA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "css-tree": "^3.2.1", + "pathe": "^2.0.3" + } + }, + "node_modules/@lynx-js/debug-metadata": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@lynx-js/debug-metadata/-/debug-metadata-0.1.0.tgz", + "integrity": "sha512-3N+Wgc/kIc4/aG5KpdPWKsC9MsNngygeyg9JS6IOayS8AQJ37xjVEzlz1U3aYzT9al0RJKL7w4poa0tGaXBv1g==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "debug-metadata": "dist/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@lynx-js/debug-metadata-rsbuild-plugin": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@lynx-js/debug-metadata-rsbuild-plugin/-/debug-metadata-rsbuild-plugin-0.2.3.tgz", + "integrity": "sha512-fsSN9lGYHjmnL94rI9T8/HnOAM1VHAIGBgH6Stv+uUrAa7GiKuaytIu2dO6wZ0oGGzHFHPXmCmMNVbw5yQRWlQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/debug-metadata": "^0.1.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@rsbuild/core": "^2.0.0" + }, + "peerDependenciesMeta": { + "@rsbuild/core": { + "optional": true + } + } + }, + "node_modules/@lynx-js/react": { + "version": "0.126.2", + "resolved": "https://registry.npmjs.org/@lynx-js/react/-/react-0.126.2.tgz", + "integrity": "sha512-zoCufpLPY+escwgiSoVCslz/1c6xgulbDb0ppaYdqLTqt7yUE09YPwayN4giGCCyg2mIDh1Cs/cwXbK4avInUQ==", + "dependencies": { + "preact": "npm:@lynx-js/internal-preact@11.0.0-rc.1-20260903085447-f95471a" + }, + "peerDependencies": { + "@lynx-js/types": "*", + "@types/react": "^18 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@lynx-js/types": { + "optional": true + } + } + }, + "node_modules/@lynx-js/react-alias-rsbuild-plugin": { + "version": "0.20.3", + "resolved": "https://registry.npmjs.org/@lynx-js/react-alias-rsbuild-plugin/-/react-alias-rsbuild-plugin-0.20.3.tgz", + "integrity": "sha512-khBWmwU63cj5+YXTkFrsFlHq3lzHMCXjFfW268vllQiKQIqFamSe3q9N9XukZeBPTsacxlI2kX65RGG3PgW1Cw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@lynx-js/rspeedy": "^0.16.0 || ^0.17.0 || ^0.18.0", + "@rsbuild/core": "^2.0.0" + }, + "peerDependenciesMeta": { + "@lynx-js/rspeedy": { + "optional": true + }, + "@rsbuild/core": { + "optional": true + } + } + }, + "node_modules/@lynx-js/react-refresh-webpack-plugin": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@lynx-js/react-refresh-webpack-plugin/-/react-refresh-webpack-plugin-0.4.3.tgz", + "integrity": "sha512-itVM5NJuuTLOmHV1exAPGaw5j0XdklP4R4K9f9sjmZoN+/UqtDfT4zImp4pd1BdXgEs2RvfU1VlzBRK/dqbiBw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@lynx-js/react-webpack-plugin": "^0.3.0 || ^0.4.0 || ^0.5.0 || ^0.6.0 || ^0.7.0 || ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0" + } + }, + "node_modules/@lynx-js/react-rsbuild-plugin": { + "version": "0.20.3", + "resolved": "https://registry.npmjs.org/@lynx-js/react-rsbuild-plugin/-/react-rsbuild-plugin-0.20.3.tgz", + "integrity": "sha512-j9gNSr9ri4G9er0CUm9U345t1M/osPx6flQ6Eh92p+Ih8U50WONnXfNHYcWQXE08R/Gc9P1NJgA/KdEKZt9cvg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/css-extract-webpack-plugin": "0.11.0", + "@lynx-js/react-alias-rsbuild-plugin": "0.20.3", + "@lynx-js/react-refresh-webpack-plugin": "0.4.3", + "@lynx-js/react-webpack-plugin": "0.12.0", + "@lynx-js/rsbuild-plugin": "0.1.3", + "@lynx-js/runtime-config-webpack-plugin": "0.0.1", + "@lynx-js/runtime-wrapper-webpack-plugin": "0.2.4", + "@lynx-js/template-webpack-plugin": "0.16.2", + "@lynx-js/use-sync-external-store": "1.5.0", + "background-only": "^0.0.1", + "tiny-invariant": "^1.3.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@lynx-js/react": "^0.124.0 || ^0.125.0 || ^0.126.0", + "@lynx-js/rspeedy": "^0.17.0 || ^0.18.0", + "@rsbuild/core": "^2.0.0" + }, + "peerDependenciesMeta": { + "@lynx-js/react": { + "optional": true + }, + "@lynx-js/rspeedy": { + "optional": true + }, + "@rsbuild/core": { + "optional": true + } + } + }, + "node_modules/@lynx-js/react-webpack-plugin": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@lynx-js/react-webpack-plugin/-/react-webpack-plugin-0.12.0.tgz", + "integrity": "sha512-jPN3b6ROR0U4V3al1Kq9HiV9WyB/laKvna9ZwKbwBDTzbsxsohrfq0/6dNWKV4VI8ZN1WBLyqDU2vUIyjK+Dgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/debug-metadata": "^0.1.0", + "@lynx-js/webpack-runtime-globals": "0.0.8", + "tiny-invariant": "^1.3.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@lynx-js/template-webpack-plugin": "^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + }, + "peerDependenciesMeta": { + "@lynx-js/react": { + "optional": true + } + } + }, + "node_modules/@lynx-js/rsbuild-plugin": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@lynx-js/rsbuild-plugin/-/rsbuild-plugin-0.1.3.tgz", + "integrity": "sha512-F9wtDVDAgRbNzBNJFazE2Ibhdyz+xFZHJyCqL4sVpiwQNyIQzwX5eQ4K9eVIUoqIBmLvBDehENnCYefTAlmwDg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/cache-events-webpack-plugin": "^0.2.1", + "@lynx-js/chunk-loading-webpack-plugin": "^0.4.2", + "@lynx-js/debug-metadata-rsbuild-plugin": "^0.2.3", + "@lynx-js/runtime-wrapper-webpack-plugin": "^0.2.4", + "@lynx-js/template-webpack-plugin": "^0.16.2", + "@lynx-js/web-rsbuild-server-middleware": "0.26.2", + "@lynx-js/webpack-dev-transport": "^0.4.0", + "@lynx-js/websocket": "^0.0.4", + "@rsbuild/plugin-css-minimizer": "2.0.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@rsbuild/core": "^2.0.0" + }, + "peerDependenciesMeta": { + "@rsbuild/core": { + "optional": true + } + } + }, + "node_modules/@lynx-js/rspeedy": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/@lynx-js/rspeedy/-/rspeedy-0.18.0.tgz", + "integrity": "sha512-/P94vbnxOjiuaQO7hWSqK7MkRjntJvijA9d5wUWNfLdYkP0o7+bNoaGVNW+ohiqCZ9el2AAS+FP2iUg1RIBT7A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/rsbuild-plugin": "0.1.3", + "@rsbuild/core": "2.2.9", + "@rsdoctor/rspack-plugin": "~1.6.4" + }, + "bin": { + "rspeedy": "bin/rspeedy.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "typescript": "5.1.6 - 6.0.x" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lynx-js/runtime-config-webpack-plugin": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@lynx-js/runtime-config-webpack-plugin/-/runtime-config-webpack-plugin-0.0.1.tgz", + "integrity": "sha512-4ligJLiYGwQ6gVqizl1ULwF4/VrogkzymA1k1Tm+3NDlFUHPyyU/HXgmEUXi8xKnh08pe+TVyl6nu97AAB1sxg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/webpack-runtime-globals": "^0.0.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@lynx-js/runtime-wrapper-webpack-plugin": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@lynx-js/runtime-wrapper-webpack-plugin/-/runtime-wrapper-webpack-plugin-0.2.4.tgz", + "integrity": "sha512-u+1d/V3PiegtfS5CSDkppEVXLjZtvNnAsfRRuWk/sayAML6zUGDBeJrAwJLYujv20Zlq5S3AgdUt7DYxeqlgTw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/webpack-runtime-globals": "0.0.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@lynx-js/tasm": { + "version": "0.0.49", + "resolved": "https://registry.npmjs.org/@lynx-js/tasm/-/tasm-0.0.49.tgz", + "integrity": "sha512-sI+xmLXaMvXWFN5n47kYNHFEMIEpkrz/bVvU2GwvhB26lXfYPdSNedE3bh85vfW/vAmYsB/TbKwtiNhXgN3LDw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "lynx-tasm": "cli.js" + } + }, + "node_modules/@lynx-js/template-webpack-plugin": { + "version": "0.16.2", + "resolved": "https://registry.npmjs.org/@lynx-js/template-webpack-plugin/-/template-webpack-plugin-0.16.2.tgz", + "integrity": "sha512-raz8fnerhbz/kVK+ucMj2KBodUrqfplesj5EL8+wwugLl7Ef2LswAlrmnnaHp6UTDhHWRi5kByeAmPegBj6KpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "@lynx-js/css-serializer": "0.1.9", + "@lynx-js/tasm": "0.0.49", + "@lynx-js/web-core": "0.26.2", + "@lynx-js/webpack-runtime-globals": "^0.0.8", + "@rspack/lite-tapable": "1.1.5", + "css-tree": "^3.2.1", + "object.groupby": "^1.0.3", + "tinypool": "^2.2.0" + }, + "engines": { + "node": "^18.14 || >=19.4" + } + }, + "node_modules/@lynx-js/types": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@lynx-js/types/-/types-4.3.0.tgz", + "integrity": "sha512-R/vx25411wKgbs2yO8XX1cvlpzcLmyK1JaTgN1fXz1p0hgn/X+W73/XJKU98HvD05A16mI5jwRl7Nx3H2po8mw==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "csstype": "3.1.3" + } + }, + "node_modules/@lynx-js/use-sync-external-store": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@lynx-js/use-sync-external-store/-/use-sync-external-store-1.5.0.tgz", + "integrity": "sha512-iXwLiGUBgfWLozCIh3ICe07x534p9CVlFS3/iGEiFOce58MLX6/PbAvWcE8qEhYaOKiQNe9hqUnS2RbyCqoqGg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@lynx-js/react": "*" + } + }, + "node_modules/@lynx-js/web-core": { + "version": "0.26.2", + "resolved": "https://registry.npmjs.org/@lynx-js/web-core/-/web-core-0.26.2.tgz", + "integrity": "sha512-y/+5uztLYQmZ7lXVkYDbpwKtbKtUQyGnymEhwU1ohPlNW2mJLLesFnblAljci2UdjCedlIq/KE7tE4ILYXDrpw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@lynx-js/css-serializer": "0.1.9", + "@lynx-js/web-elements": "0.12.12", + "@lynx-js/web-worker-rpc": "0.26.2", + "wasm-feature-detect": "^1.8.0" + }, + "peerDependencies": { + "@lynx-js/animax": "0.1.0-alpha.0", + "@lynx-js/lynx-core": "0.1.4", + "tslib": "^2.5.0" + }, + "peerDependenciesMeta": { + "@lynx-js/animax": { + "optional": true + }, + "@lynx-js/lynx-core": { + "optional": true + }, + "tslib": { + "optional": true + } + } + }, + "node_modules/@lynx-js/web-elements": { + "version": "0.12.12", + "resolved": "https://registry.npmjs.org/@lynx-js/web-elements/-/web-elements-0.12.12.tgz", + "integrity": "sha512-LHxCTMoSTgM5iLKSMolE87riEuFkNY9NpMxC27x4MO28+7PLI/mA18i644l4I0BweiU6gbD82+NAvak0SjWcCA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dompurify": "^3.4.13", + "markdown-it": "^15.0.2" + }, + "peerDependencies": { + "tslib": "^2.5.0" + } + }, + "node_modules/@lynx-js/web-rsbuild-server-middleware": { + "version": "0.26.2", + "resolved": "https://registry.npmjs.org/@lynx-js/web-rsbuild-server-middleware/-/web-rsbuild-server-middleware-0.26.2.tgz", + "integrity": "sha512-DeBYye1wZK61pDEDvR1cbRhSWh7lO76M6iZ1CX8kouglaMpmI+ZQBtOk3FLa5KoRHxTi1++qC0DsCRx6NlnhQQ==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@lynx-js/web-worker-rpc": { + "version": "0.26.2", + "resolved": "https://registry.npmjs.org/@lynx-js/web-worker-rpc/-/web-worker-rpc-0.26.2.tgz", + "integrity": "sha512-HrM/pFLmcDKPq0MSxl8D8JleZIYbkbHPD2v20USVIPDUqHSk6HdP4APpioZ2lMmItS/S7t+8xuHKVNTtLeQTRw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@lynx-js/webpack-dev-transport": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@lynx-js/webpack-dev-transport/-/webpack-dev-transport-0.4.0.tgz", + "integrity": "sha512-+XeG9yUGM7oCWeXe/Pbxl6cBmF6JQ6jQ08rm9w8zbV6Liq1THghlcKPdj2DAS1u1WU3llSi1RGzGQabWlDwR1w==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@lynx-js/webpack-runtime-globals": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/@lynx-js/webpack-runtime-globals/-/webpack-runtime-globals-0.0.8.tgz", + "integrity": "sha512-TqxsPb58LJgiqgxU3zCBrGybmUFJ8EZtu0Hq9sH0UTPztk2ghcUxn18YrU+816KuYeSqOM2qT2Nh+Q69KZWXvw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@lynx-js/websocket": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/@lynx-js/websocket/-/websocket-0.0.4.tgz", + "integrity": "sha512-yXuMiTALLNvkDz8hG+0KdkBodnyJDvyfr8bdIq6zMP9X8JAoBC/czc1HIhUgYEJ3Zee5F/vGKjNxcoSx2t1E6w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "eventemitter3": "^5.0.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", + "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + } + }, + "node_modules/@rsbuild/core": { + "version": "2.2.9", + "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.2.9.tgz", + "integrity": "sha512-ZeOYQYIBOtYkfvmbNUiKEYBK1aMGE03mhuHKVcHiWk+Y63FuUTnuQtlr1RyLErh0E7F/KyDTIaraDVH3g3GNkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rspack/core": "~2.2.7", + "@swc/helpers": "^0.5.23" + }, + "bin": { + "rsbuild": "bin/rsbuild.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "core-js": ">= 3.0.0" + }, + "peerDependenciesMeta": { + "core-js": { + "optional": true + } + } + }, + "node_modules/@rsbuild/plugin-check-syntax": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@rsbuild/plugin-check-syntax/-/plugin-check-syntax-1.6.1.tgz", + "integrity": "sha512-26xtEYN0QjZYoyt0lWnvIztBWjEZJvcfw7MN4f5B4SpNggmnF7F7aNPrgkY3EccXVFx1VGQBhnCkBV//OoS07Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.15.0", + "browserslist-to-es-version": "^1.2.0", + "htmlparser2": "10.0.0", + "picocolors": "^1.1.1", + "source-map": "^0.7.6" + }, + "peerDependencies": { + "@rsbuild/core": "^1.0.0 || ^2.0.0-0" + }, + "peerDependenciesMeta": { + "@rsbuild/core": { + "optional": true + } + } + }, + "node_modules/@rsbuild/plugin-css-minimizer": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@rsbuild/plugin-css-minimizer/-/plugin-css-minimizer-2.0.1.tgz", + "integrity": "sha512-QZUEBLTYXwtCUVziK3XHaPv+3wLLGvO6X27sIwt12eyuIMSA5WbeuLD9y1hwsXu27jZBofP6s/mdV5H5bA/FOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-minimizer-webpack-plugin": "^8.0.0", + "reduce-configs": "^1.1.2" + }, + "peerDependencies": { + "@rsbuild/core": "^1.0.0 || ^2.0.0-0" + }, + "peerDependenciesMeta": { + "@rsbuild/core": { + "optional": true + } + } + }, + "node_modules/@rsbuild/plugin-type-check": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@rsbuild/plugin-type-check/-/plugin-type-check-1.6.0.tgz", + "integrity": "sha512-AZDLYGUfqAqwn50pkliVgI9UN4+AsM8yh0XqySCianYUeftSPa4By7tyP7+TBXpnJ6Ev3xaha/cS/462MNT18w==", + "dev": true, + "license": "MIT", + "dependencies": { + "deepmerge": "^4.3.1", + "json5": "^2.2.3", + "reduce-configs": "^1.1.2", + "ts-checker-rspack-plugin": "^1.6.0" + }, + "peerDependencies": { + "@rsbuild/core": "^1.0.0 || ^2.0.0-0", + "@typescript/native-preview": "^7.0.0-0" + }, + "peerDependenciesMeta": { + "@rsbuild/core": { + "optional": true + }, + "@typescript/native-preview": { + "optional": true + } + } + }, + "node_modules/@rsdoctor/client": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/@rsdoctor/client/-/client-1.6.4.tgz", + "integrity": "sha512-11GvDTusVzlqlyTVoeI0kw1n5TH9MTrzOJxL5L/Qgyzmf5SSl+iw3NrEPRqyi2pgzQsOumad6FSq2n0LdBKzrg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rsdoctor/core": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/@rsdoctor/core/-/core-1.6.4.tgz", + "integrity": "sha512-Z504K+VjKpbqYnRG6ORr0BNidObjTZSb6Z6nXpZDkBSIdmA4fZcKz8U0iRLsZuy8kq7PN+Xm7ym0fTTGh8xeVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rsbuild/plugin-check-syntax": "^1.6.1", + "@rsdoctor/graph": "1.6.4", + "@rsdoctor/sdk": "1.6.4", + "@rsdoctor/types": "1.6.4", + "@rsdoctor/utils": "1.6.4", + "@rspack/resolver": "^0.2.8", + "browserslist-load-config": "^1.0.2", + "es-toolkit": "^1.49.0", + "filesize": "^11.0.17", + "fs-extra": "^11.1.1", + "semver": "^7.8.5", + "source-map": "^0.7.6" + } + }, + "node_modules/@rsdoctor/graph": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/@rsdoctor/graph/-/graph-1.6.4.tgz", + "integrity": "sha512-UnCRJ9uhH0+z5OX8UfLdVnDnxr21PuMa6wMt9+cD0NsJZTdd+6gts4RcEp3BFbzs0g/BQoNCciQzRBULZr+OUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rsdoctor/types": "1.6.4", + "@rsdoctor/utils": "1.6.4", + "es-toolkit": "^1.49.0", + "path-browserify": "1.0.1", + "source-map": "^0.7.6" + } + }, + "node_modules/@rsdoctor/rspack-plugin": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/@rsdoctor/rspack-plugin/-/rspack-plugin-1.6.4.tgz", + "integrity": "sha512-hHCRsHV0Qy0zPuDpNQq72dgnhevGxUFcPAL/JJPDzH3idI+IxMb08vCohWJWYvQVliNTACiS9kCMKUGZjIAzCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rsdoctor/core": "1.6.4", + "@rsdoctor/graph": "1.6.4", + "@rsdoctor/sdk": "1.6.4", + "@rsdoctor/types": "1.6.4", + "@rsdoctor/utils": "1.6.4" + }, + "peerDependencies": { + "@rspack/core": "*" + }, + "peerDependenciesMeta": { + "@rspack/core": { + "optional": true + } + } + }, + "node_modules/@rsdoctor/sdk": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/@rsdoctor/sdk/-/sdk-1.6.4.tgz", + "integrity": "sha512-oLCUCqVlzbcVIoPoDLycqAqgUYxWcCZEK21cGu4ZDVVo+H8pmA2iEvi7T9KnE0sgkNm5U2bt6SkyNx/Tt1eTkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rsdoctor/client": "1.6.4", + "@rsdoctor/graph": "1.6.4", + "@rsdoctor/types": "1.6.4", + "@rsdoctor/utils": "1.6.4", + "launch-editor": "^2.13.2", + "safer-buffer": "2.1.2", + "socket.io": "4.8.1", + "tapable": "2.3.3" + } + }, + "node_modules/@rsdoctor/types": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/@rsdoctor/types/-/types-1.6.4.tgz", + "integrity": "sha512-+nE5MoP7smDrJt5LkeoY6cj8P/ZJBF7lNvvJ658+sV8cde6agu2bEreSUjR5zcAldUs1j4oSgLY5x6TukeseEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "3.4.38", + "@types/estree": "1.0.5", + "@types/tapable": "2.3.0", + "source-map": "^0.7.6" + }, + "peerDependencies": { + "@rspack/core": "*", + "webpack": "5.x" + }, + "peerDependenciesMeta": { + "@rspack/core": { + "optional": true + }, + "webpack": { + "optional": true + } + } + }, + "node_modules/@rsdoctor/utils": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/@rsdoctor/utils/-/utils-1.6.4.tgz", + "integrity": "sha512-7oliDqtaLVtmVFkfSN3AKWoMQb8kuZA9AURCgb26cUW7+ZD3qgADg9uyD+WevpA6IOeF6gqo3hezTZKlwFR2Sg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "7.26.2", + "@rsdoctor/types": "1.6.4", + "@types/estree": "1.0.5", + "acorn": "^8.10.0", + "acorn-import-attributes": "^1.9.5", + "acorn-walk": "8.3.5", + "deep-eql": "4.1.4", + "envinfo": "7.21.0", + "fs-extra": "^11.1.1", + "get-port": "5.1.1", + "json-stream-stringify": "3.0.1", + "lines-and-columns": "2.0.4", + "picocolors": "^1.1.1", + "rslog": "^2.1.2", + "strip-ansi": "^7.2.0" + } + }, + "node_modules/@rspack/binding": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.2.8.tgz", + "integrity": "sha512-c9flkSua3khHnOKBCRk8BkHGOwU9YB7niv+5JfQXiLZIvJmgKsZ7PD8QrFklMhsJT3oVAc6c9GN7/wy1YkACjA==", + "dev": true, + "license": "MIT", + "optionalDependencies": { + "@rspack/binding-darwin-arm64": "2.2.8", + "@rspack/binding-darwin-x64": "2.2.8", + "@rspack/binding-linux-arm64-gnu": "2.2.8", + "@rspack/binding-linux-arm64-musl": "2.2.8", + "@rspack/binding-linux-ppc64-gnu": "2.2.8", + "@rspack/binding-linux-riscv64-gnu": "2.2.8", + "@rspack/binding-linux-riscv64-musl": "2.2.8", + "@rspack/binding-linux-s390x-gnu": "2.2.8", + "@rspack/binding-linux-x64-gnu": "2.2.8", + "@rspack/binding-linux-x64-musl": "2.2.8", + "@rspack/binding-wasm32-wasi": "2.2.8", + "@rspack/binding-win32-arm64-msvc": "2.2.8", + "@rspack/binding-win32-ia32-msvc": "2.2.8", + "@rspack/binding-win32-x64-msvc": "2.2.8" + } + }, + "node_modules/@rspack/binding-darwin-arm64": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.2.8.tgz", + "integrity": "sha512-d6GuY/k7kJk7SOXmruIz0m+2fIXaLv2SnBHEYsbvBzE7ZO6QXq7fSABWFWNnSnNu+brYHA5Dr/skV81bXgTTCw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rspack/binding-darwin-x64": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.2.8.tgz", + "integrity": "sha512-xCVou/jJASjEAjwy1T3hPJcJqA5QZASJfUwHqEk+nA0v44MagwH8tM8lsOvRfhzR7N2+YFac1rfZOUT8uM3awg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rspack/binding-linux-arm64-gnu": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.2.8.tgz", + "integrity": "sha512-Zy/ss6YAQTjOWKDkcWrbKtu+pySltqT22wn68nlrWKygPWLNmMdU5anlsnwRTIuQ3MF0YJRS42ARauVtlqvRQw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/binding-linux-arm64-musl": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.2.8.tgz", + "integrity": "sha512-lxgp5O8PhL3St9p82llHoNoeWzp9jltW5S9F00p00XPJZHUIuxbwfLSzn/6Wg86USEmafLoBkyD9CM8rBd3SNQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/binding-linux-ppc64-gnu": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.2.8.tgz", + "integrity": "sha512-MY+YqpT02tcDCMgHy+IewQsaz7ql4mbJaAqqMlTIqvQwAUl9dXEP7BL352OgCxm9VRebTldE5lK99A3wVd3zqA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/binding-linux-riscv64-gnu": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.2.8.tgz", + "integrity": "sha512-wmN9OigSGNGCKY+AOYaWI8LJcIi8qvs5KjueBueCKOnTV6MPIEujA75QZH1pehTTYKvdGv7r2EtUXUmWpn7/SQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/binding-linux-riscv64-musl": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.2.8.tgz", + "integrity": "sha512-ZcQMYR10hLh581zs9MFnFFn0F7wyt5fkDffyukeMHJEoPJrbkfl6cQtsUdpQnZ+mYGYS5KydD1DT9/eMH65jjw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/binding-linux-s390x-gnu": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.2.8.tgz", + "integrity": "sha512-ahBiE+Ir1FMYvStYicihhSJlS2YRagxtry0jWH8zW287o7C0eiHJ+pteJHHC15T5RJqm0j6w5TuwYe+F9AYxxg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/binding-linux-x64-gnu": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.2.8.tgz", + "integrity": "sha512-dncEI515NoPXh3zzWk06Rb3mhSV76myiFKqXiJ8K4fVAe5x/RlweMhvPhHhm7RnIMeBld7BeStzOqj38XFsWGA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/binding-linux-x64-musl": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.2.8.tgz", + "integrity": "sha512-pfFyU03PjD0GaQG8zOQOHwq51rrJZetXjTGpMmz7iA1hq/f9lChJsDWrC8/7VXeQLwBofLZlOODqe8OM8OBzgA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/binding-wasm32-wasi": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.2.8.tgz", + "integrity": "sha512-3mOJuZTrF56jOh/GD9chLMJKbzPZ6Ty2OIML7+lLz0Yk2XS/xWRfLn85Dmnkb/O6UF65x7+p8VPAIZlBtLTclw==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.11.3", + "@emnapi/runtime": "1.11.3", + "@napi-rs/wasm-runtime": "1.1.6" + } + }, + "node_modules/@rspack/binding-win32-arm64-msvc": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.2.8.tgz", + "integrity": "sha512-Cu/RMZT/16s+67xhl6X1pswetL3GLSQl+LnugKRh08Ul21A/tR7vxC4g4aih4u9k5SXCAngxFUt8zAjKnHIBqA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rspack/binding-win32-ia32-msvc": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.2.8.tgz", + "integrity": "sha512-H/erd6di8OapZhhM0raA/7XduPn9jusfLMeO1XF+AmF9WF3HzHgMjha1j+KwtPgQnaH69w6AhY+G2472VIwQmw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rspack/binding-win32-x64-msvc": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.2.8.tgz", + "integrity": "sha512-BziHSUlIQM0MliCqdcHuBXSkQGtPoHQTXJce7fsgnTAzQFgPeog92qTNezYI4IrQ7pQouyiVJ2HPieUbVPRKQQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rspack/core": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.2.8.tgz", + "integrity": "sha512-JugsVrnbMGNYzMH++7gR9enygpP/lAo9PbVRq3XmJg0ryIvCpST0XJjBcccaSjYaaPamsjrddihmgVLMFp+yXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rspack/binding": "2.2.8" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@module-federation/runtime-tools": "^0.24.1 || ^2.0.0", + "@swc/helpers": "^0.5.23" + }, + "peerDependenciesMeta": { + "@module-federation/runtime-tools": { + "optional": true + }, + "@swc/helpers": { + "optional": true + } + } + }, + "node_modules/@rspack/lite-tapable": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rspack/lite-tapable/-/lite-tapable-1.1.5.tgz", + "integrity": "sha512-uzB782zJbFTM3ta+e2Glikx36dca/6Y+DXyvFN+wb0Tx5ItIW+g03A0t3amP3LGzPHSkb0k81VHCm4jxLQwfag==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rspack/resolver": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver/-/resolver-0.2.8.tgz", + "integrity": "sha512-FBWqdHhzS8mcf/WN4Ktzr7EaeaN+hsxbN98EweegX3924beZuY6H70CSFWCv1fIHAieCUv/9XCjKggHvhCsLwA==", + "dev": true, + "license": "MIT", + "optionalDependencies": { + "@rspack/resolver-binding-darwin-arm64": "0.2.8", + "@rspack/resolver-binding-darwin-x64": "0.2.8", + "@rspack/resolver-binding-linux-arm64-gnu": "0.2.8", + "@rspack/resolver-binding-linux-arm64-musl": "0.2.8", + "@rspack/resolver-binding-linux-x64-gnu": "0.2.8", + "@rspack/resolver-binding-linux-x64-musl": "0.2.8", + "@rspack/resolver-binding-wasm32-wasi": "0.2.8", + "@rspack/resolver-binding-win32-arm64-msvc": "0.2.8", + "@rspack/resolver-binding-win32-ia32-msvc": "0.2.8", + "@rspack/resolver-binding-win32-x64-msvc": "0.2.8" + } + }, + "node_modules/@rspack/resolver-binding-darwin-arm64": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-0.2.8.tgz", + "integrity": "sha512-nTnK17kmxXEvR+WpOIZPSIzUFYeWCHoffgU9tvOLOwuTBH41kWnSQXXWu+AiMVwvJ6wdRO6Vo30hPhlXEG7Pyw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rspack/resolver-binding-darwin-x64": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-0.2.8.tgz", + "integrity": "sha512-Aqr4TK2rA6XVYUOmM5YCtYyCMZhOIR53P4cOGgGARg99A7OuMBMzUL4r1n0M0Fx35v6/sSx1OBe+odHmPxksEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rspack/resolver-binding-linux-arm64-gnu": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-0.2.8.tgz", + "integrity": "sha512-wGvkxm2G4mNTztslaOzLzx5JuySQSy5DcOWEZxHcjJJzp5L3ODbYLK18HtUc6cvmaVOmjaGrrYPrqJJ0hHTVFg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/resolver-binding-linux-arm64-musl": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-0.2.8.tgz", + "integrity": "sha512-EqRJ9zLQsLAvyDKJKVZ45BSqRIMS12f5HtJdy3KkAHU14ZmsGv8e5IKkwUZN5CNBRad8xVlOMMx3dOfF4whJzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/resolver-binding-linux-x64-gnu": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-0.2.8.tgz", + "integrity": "sha512-eXbeotNCTntL4/+mxJRVCxK63YeWzTfp0F3POeHJFSs6Nt0f2J/mZNFlasJmd6xm7zvE80h/HWOwbwjRBLcElA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/resolver-binding-linux-x64-musl": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-0.2.8.tgz", + "integrity": "sha512-KWFHlOWGkT+eMngoUgPGXrDi+rU04VCh9jyk0U6Ot2RTWvhGxwKykjmLS+CWZI/EBrzr9A6g2U3jzKTMNz9oCw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rspack/resolver-binding-wasm32-wasi": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-0.2.8.tgz", + "integrity": "sha512-I6GIhgICFViE88jejIV74oiiWHnpLpQ5ogaZM1ozM9KDnfqcHoX0IVEyrIh5KqA8iLDyhuoFSW+Hf0qN7VTBBQ==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^1.1.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rspack/resolver-binding-win32-arm64-msvc": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-0.2.8.tgz", + "integrity": "sha512-ZXCt3qUfDAEbtc2sHpvxM7lNFZM+DxfblgXUIl3Jy6BuEZbHe1i6z+t9c34ayHoGTVbVSNCtaYuG/MaWdSnPHw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rspack/resolver-binding-win32-ia32-msvc": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-0.2.8.tgz", + "integrity": "sha512-2LRymjDK8MpUERD8CL0PPae5y2crU5TAg4T4EzpeL5jLARVq6izsEruiWzB6Y+D15vUYlvmgs2370GXVSB861w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rspack/resolver-binding-win32-x64-msvc": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@rspack/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-0.2.8.tgz", + "integrity": "sha512-hzRpfbtvv4M4EVrKKIAaHDs5wT8lVcbSUjtwPs5u4IeLEix45nQPQ6ZQjmE4lIH0GP/3L3XQhZroYmTcH/xdsQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@sinclair/typebox": { + "version": "0.34.52", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz", + "integrity": "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@swc/helpers": { + "version": "0.5.23", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", + "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cors": { + "version": "2.8.19", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", + "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", + "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", + "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", + "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", + "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz", + "integrity": "sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "license": "MIT", + "peer": true, + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react/node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT", + "peer": true + }, + "node_modules/@types/tapable": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@types/tapable/-/tapable-2.3.0.tgz", + "integrity": "sha512-oMnbAXeVo+KUnje3hzdORXUbfnzTfqD0H92mLl19NE5hFqH9Q4ktq+xehNSxcNeeLm1COopYwa0zeP6Iz+oIXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tapable": "^2.3.0" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/structured-clone": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz", + "integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/helper-numbers": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz", + "integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz", + "integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz", + "integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz", + "integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.13.2", + "@webassemblyjs/helper-api-error": "1.13.2", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz", + "integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz", + "integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/wasm-gen": "1.14.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz", + "integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz", + "integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz", + "integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz", + "integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/helper-wasm-section": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-opt": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1", + "@webassemblyjs/wast-printer": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz", + "integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz", + "integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz", + "integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-api-error": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz", + "integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true, + "license": "Apache-2.0", + "peer": true + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", + "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/anymatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/argparse": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.2.tgz", + "integrity": "sha512-mFdDM6WqWKraGLsVb+C9CahPnzTXOefAOLq3jYcca2YZ8bEWpr++Tzj+zSaKW9+X9L5uSxcm1AZ3Y6aZJ09OhQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/background-only": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/background-only/-/background-only-0.0.1.tgz", + "integrity": "sha512-YXR2zshAf3qs3jnpApQaDUG0x4L6YWpSZfLDhdeiCFxfp/n8YwfoAQ1hAigEF3VpXOMOJeZYFWtBbiFv/v2Qfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^4.5.0 || >= 5.9" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.27", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz", + "integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "dev": true, + "license": "ISC" + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.29.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz", + "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.26", + "caniuse-lite": "^1.0.30001813", + "electron-to-chromium": "^1.5.439", + "node-releases": "^2.0.57", + "update-browserslist-db": "^1.3.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/browserslist-load-config": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/browserslist-load-config/-/browserslist-load-config-1.0.3.tgz", + "integrity": "sha512-boNaPS4KlW6AITZQ60G+1oDJLuxauljDd7QNQFOYpRtldzcTDknMZ8awbwI0BT/8h1/Y/CG4k/tDOLip9lAGcg==", + "dev": true, + "license": "MIT" + }, + "node_modules/browserslist-to-es-version": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/browserslist-to-es-version/-/browserslist-to-es-version-1.4.2.tgz", + "integrity": "sha512-3NV13pCv0wmPxxZZcekHAG6vt8rQ94w2c4/UBe3ZU3NDUm5TP+QFK3rjS6XeKWSHWpnPYNfQzlhnljka0BrEOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2" + }, + "bin": { + "browserslist-to-es-version": "dist/cli.js" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/caniuse-api": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-3.0.0.tgz", + "integrity": "sha512-bsTwuIg/BZZK/vreVTYYbSWoe2F+71P7K5QGEX+pT250DZbfU1MQ5prOKpPR+LL6uWKK3KMwMCAS74QB3Um1uw==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.0.0", + "caniuse-lite": "^1.0.0", + "lodash.memoize": "^4.1.2", + "lodash.uniq": "^4.5.0" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001815", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001815.tgz", + "integrity": "sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", + "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/ci-info": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/commander": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/css-declaration-sorter": { + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/css-declaration-sorter/-/css-declaration-sorter-7.4.0.tgz", + "integrity": "sha512-LTuzjPoyA2vMGKKcaOqKSp7Ub2eGrNfKiZH4LpezxpNrsICGCSFvsQOI29psISxNZtaXibkC2CXzrQ5enMeGGw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14 || ^16 || >=18" + }, + "peerDependencies": { + "postcss": "^8.0.9" + } + }, + "node_modules/css-minimizer-webpack-plugin": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/css-minimizer-webpack-plugin/-/css-minimizer-webpack-plugin-8.0.0.tgz", + "integrity": "sha512-9bEpzHs8gEq6/cbEj418jXL/YWjBUD2YTLLk905Npt2JODqnRITin0+So5Vx4Dp5vyi2Lpt9pp2QHzQ7fdxNrw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "cssnano": "^7.0.4", + "jest-worker": "^30.0.5", + "postcss": "^8.4.40", + "schema-utils": "^4.2.0", + "serialize-javascript": "^7.0.3" + }, + "engines": { + "node": ">= 20.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + }, + "peerDependenciesMeta": { + "@parcel/css": { + "optional": true + }, + "@swc/css": { + "optional": true + }, + "clean-css": { + "optional": true + }, + "csso": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "lightningcss": { + "optional": true + } + } + }, + "node_modules/css-select": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-6.0.0.tgz", + "integrity": "sha512-rZZVSLle8v0+EY8QAkDWrKhpgt6SA5OtHsgBnsj6ZaLb5dmDVOWUDtQitd9ydxxvEjhewNudS6eTVU7uOyzvXw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^7.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "nth-check": "^2.1.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/css-what": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-7.0.0.tgz", + "integrity": "sha512-wD5oz5xibMOPHzy13CyGmogB3phdvcDaB5t0W/Nr5Z2O/agcB8YwOz6e2Lsp10pNDzBoDO9nVa3RGs/2BttpHQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/cssnano": { + "version": "7.1.9", + "resolved": "https://registry.npmjs.org/cssnano/-/cssnano-7.1.9.tgz", + "integrity": "sha512-uPR75+5Dk/WJ/YSPR1/YDHdwMM9c5FsaARljfKWgeCKLKOtJ0we21xy/RcCjn53fZnD/f6yYEIZ8pu18+GnbNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssnano-preset-default": "^7.0.17", + "lilconfig": "^3.1.3" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/cssnano" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/cssnano-preset-default": { + "version": "7.0.17", + "resolved": "https://registry.npmjs.org/cssnano-preset-default/-/cssnano-preset-default-7.0.17.tgz", + "integrity": "sha512-11qO63A+czwguQFJCaTdICvbaxn0pJzz/XghLlv+OT7WyToDxAMR0Xb3/26/l0y0hQJywwNbj/SLSQlGBHE1OA==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "css-declaration-sorter": "^7.2.0", + "cssnano-utils": "^5.0.3", + "postcss-calc": "^10.1.1", + "postcss-colormin": "^7.0.10", + "postcss-convert-values": "^7.0.12", + "postcss-discard-comments": "^7.0.8", + "postcss-discard-duplicates": "^7.0.4", + "postcss-discard-empty": "^7.0.3", + "postcss-discard-overridden": "^7.0.3", + "postcss-merge-longhand": "^7.0.7", + "postcss-merge-rules": "^7.0.11", + "postcss-minify-font-values": "^7.0.3", + "postcss-minify-gradients": "^7.0.5", + "postcss-minify-params": "^7.0.9", + "postcss-minify-selectors": "^7.1.2", + "postcss-normalize-charset": "^7.0.3", + "postcss-normalize-display-values": "^7.0.3", + "postcss-normalize-positions": "^7.0.4", + "postcss-normalize-repeat-style": "^7.0.4", + "postcss-normalize-string": "^7.0.3", + "postcss-normalize-timing-functions": "^7.0.3", + "postcss-normalize-unicode": "^7.0.9", + "postcss-normalize-url": "^7.0.3", + "postcss-normalize-whitespace": "^7.0.3", + "postcss-ordered-values": "^7.0.4", + "postcss-reduce-initial": "^7.0.9", + "postcss-reduce-transforms": "^7.0.3", + "postcss-svgo": "^7.1.3", + "postcss-unique-selectors": "^7.0.7" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/cssnano-utils": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/cssnano-utils/-/cssnano-utils-5.0.3.tgz", + "integrity": "sha512-ynIREMICLxkxm7e9bCR9sh75s4Q5drICi0ua1yxo5jH2XPBqSKkl4dOh4EbFqtUmnTMhRffHgYL0EKKkMjtJTg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/csso": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/csso/-/csso-5.0.5.tgz", + "integrity": "sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "~2.2.0" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/csso/node_modules/css-tree": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.2.1.tgz", + "integrity": "sha512-OA0mILzGc1kCOCSJerOeqDxDQ4HOh+G8NbOJFOTgOCzpw7fCBubk0fEyxp8AgOL/jvLgYA/uV0cMbe43ElF1JA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.0.28", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/csso/node_modules/mdn-data": { + "version": "2.0.28", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.28.tgz", + "integrity": "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.4.tgz", + "integrity": "sha512-SUwdGfqdKOwxCPeVYjwSyRpJ7Z+fhpwIAtmCUdZIWZ/YP5R9WAsyuSgpLVDi9bjWoN2LXHNss/dk3urXtdQxGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/dom-serializer/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/dompurify": { + "version": "3.4.16", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz", + "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", + "dev": true, + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.451", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.451.tgz", + "integrity": "sha512-vUNKPrUzw8ByEMOxloq0a71iD/mPuPxVkbDm3G5YhnxTzOw/I6qAg2MUS0cYj/c267lWmw26yW4Vv7foxTxPLg==", + "dev": true, + "license": "ISC" + }, + "node_modules/engine.io": { + "version": "6.6.11", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.11.tgz", + "integrity": "sha512-z34mGpLoY/82ZbkX1LqGMIaf3wjVMPL6gVC681QDqnmzJ26synI8qAE32P+a7UazmpJZ8UGrFIeAavgRfXzYrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "@types/ws": "^8.5.12", + "accepts": "~1.3.4", + "cookie": "~0.7.2", + "cors": "~2.8.5", + "debug": "~4.4.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.21.0" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/enhanced-resolve": { + "version": "5.26.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", + "integrity": "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/envinfo": { + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.21.0.tgz", + "integrity": "sha512-Lw7I8Zp5YKHFCXL7+Dz95g4CcbMEpgvqZNNq3AmlT5XAV6CgAAk6gyAMqn2zjw08K9BHfcNuKrMiCPLByGafow==", + "dev": true, + "license": "MIT", + "bin": { + "envinfo": "dist/cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/es-abstract": { + "version": "1.24.2", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", + "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-abstract-get": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-abstract-get/-/es-abstract-get-1.0.0.tgz", + "integrity": "sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.2", + "is-callable": "^1.2.7", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.4.tgz", + "integrity": "sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-abstract-get": "^1.0.0", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "is-callable": "^1.2.7", + "is-date-object": "^1.1.0", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-toolkit": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz", + "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==", + "dev": true, + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/filesize": { + "version": "11.0.25", + "resolved": "https://registry.npmjs.org/filesize/-/filesize-11.0.25.tgz", + "integrity": "sha512-oPVK4S+B5nRK8eL5FORi4RSzbz/1PmUx17NQLMIWv8tlNVDUFgLY0GNApL7tEebL4WgkBqSJGB3AJsCXUs01hw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 10.8.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/fs-extra": { + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.2.0.tgz", + "integrity": "sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2", + "hasown": "^2.0.4", + "is-callable": "^1.2.7", + "is-document.all": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-port": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/get-port/-/get-port-5.1.1.tgz", + "integrity": "sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regex.js": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/glob-to-regex.js/-/glob-to-regex.js-1.3.1.tgz", + "integrity": "sha512-zhWhMRsgnOym+1txhUmYJGD6eUsbUdrZv55gCYKuJX8t2p3+M8My23PD09bEIsreGUs5pnSa/idmcfp2/IlqGg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/htmlparser2": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.0.0.tgz", + "integrity": "sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==", + "dev": true, + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.1", + "entities": "^6.0.0" + } + }, + "node_modules/hyperdyperid": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/hyperdyperid/-/hyperdyperid-1.2.0.tgz", + "integrity": "sha512-Y93lCzHYgGWdrJ66yIktxiaGULYc6oGiABxhcO5AufBeOyoIdZF7bIfLaOrbM0iGIOXQQgxxRrFEnb+Y6w1n4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.18" + } + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-document.all": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-document.all/-/is-document.all-1.0.0.tgz", + "integrity": "sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-regex-util": { + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-30.5.0.tgz", + "integrity": "sha512-Mg0WK7A6xRHLSA1udJ8y9f3lM0uUhFTBnLKzwPmqB9AylvpleJ6BLemR8K9dK27DY+cesDryoA7yLZCAHsPG1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/jest-util": { + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-30.5.1.tgz", + "integrity": "sha512-yKuxmNy2rSbTXw+3SIPanJo+nV4/BS1p26v44IYBFMsswSQySfMMcPHErnOncda7i9HEz0q605rIhSTBVgrZTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "30.5.1", + "@types/node": "*", + "chalk": "^4.1.2", + "ci-info": "^4.2.0", + "graceful-fs": "^4.2.11", + "picomatch": "^4.0.3" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/jest-worker": { + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-30.5.1.tgz", + "integrity": "sha512-Cbxh5v7AoLuFRmFJSM4/aHdQ68rjXvUWr716EE0Dh3I7T+T/3FgFKhOERGXHcU2Meftq9+9zxPM3TSNyI9D+HA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@ungap/structured-clone": "^1.3.0", + "jest-util": "30.5.1", + "merge-stream": "^2.0.0", + "supports-color": "^8.1.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stream-stringify": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-stream-stringify/-/json-stream-stringify-3.0.1.tgz", + "integrity": "sha512-vuxs3G1ocFDiAQ/SX0okcZbtqXwgj1g71qE9+vrjJ2EkjKQlEFDAcUNRxRU8O+GekV4v5cM2qXP0Wyt/EMDBiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/launch-editor": { + "version": "2.14.2", + "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.2.tgz", + "integrity": "sha512-NHJEb30MGBCkmZXLZwz25t37QR4aY03ZzPYUJXOJaOa92uWwExI9SBQUuIznBYc1xkD7cJNGX7oc3Nl3sq2kQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "picocolors": "^1.1.1", + "shell-quote": "^1.10.0" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-2.0.4.tgz", + "integrity": "sha512-wM1+Z03eypVAVUCE7QdSqpVIvelbOakn1M0bPDoA4SGWPx3sNDVUiMo3L6To6WWGClB7VyXnhQ4Sn7gxiJbE6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/linkify-it": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-6.1.0.tgz", + "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^3.0.0" + } + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/markdown-it": { + "version": "15.0.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.2.tgz", + "integrity": "sha512-q4IGxMv56jCqT4OCRCADBoDP3LO4MhmTXjFbphHPXs4g3j9Xg5RDnxqN8IF/3vIWEU+VCnUq+7JUg/cfy2E6Qw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^3.0.0", + "entities": "^8.0.0", + "linkify-it": "^6.0.0", + "mdurl": "^2.1.0", + "punycode.js": "^2.3.1", + "uc.micro": "^3.0.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdown-it/node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "dev": true, + "license": "MIT" + }, + "node_modules/memfs": { + "version": "4.80.0", + "resolved": "https://registry.npmjs.org/memfs/-/memfs-4.80.0.tgz", + "integrity": "sha512-N70W2isi44XdGn7uPo9NJ4zRukcdkwSFHlnYx42SWOH/+hzqNc8P7+tVoA2up4z7faHvNi1RSNCFjxoYQ71VPQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/fs-core": "4.80.0", + "@jsonjoy.com/fs-fsa": "4.80.0", + "@jsonjoy.com/fs-node": "4.80.0", + "@jsonjoy.com/fs-node-builtins": "4.80.0", + "@jsonjoy.com/fs-node-to-fsa": "4.80.0", + "@jsonjoy.com/fs-node-utils": "4.80.0", + "@jsonjoy.com/fs-print": "4.80.0", + "@jsonjoy.com/fs-snapshot": "4.80.0", + "@jsonjoy.com/json-pack": "^1.11.0", + "@jsonjoy.com/util": "^1.9.0", + "glob-to-regex.js": "^1.3.1", + "thingies": "^2.5.0", + "tree-dump": "^1.0.3", + "tslib": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimizer-webpack-plugin": { + "version": "5.13.0", + "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.13.0.tgz", + "integrity": "sha512-OO1NF2zHj6sf4CNv2AsUWYcS8WEwkVKQDXxxKzlOxx1Xl+WlqYtVC+oNlGNwGkLAOnpj277BSHypWwRtd9w4JQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "jest-worker": "^27.4.5", + "schema-utils": "^4.3.3", + "terser": "^5.51.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@minify-html/node": { + "optional": true + }, + "@napi-rs/image": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "@swc/css": { + "optional": true + }, + "@swc/html": { + "optional": true + }, + "clean-css": { + "optional": true + }, + "cssnano": { + "optional": true + }, + "csso": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "html-minifier-terser": { + "optional": true + }, + "imagemin": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "postcss": { + "optional": true + }, + "sharp": { + "optional": true + }, + "svgo": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/minimizer-webpack-plugin/node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-releases": { + "version": "2.0.58", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.58.tgz", + "integrity": "sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.groupby": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", + "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/own-keys": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.2.tgz", + "integrity": "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss": { + "version": "8.5.29", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.19", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-calc": { + "version": "10.1.1", + "resolved": "https://registry.npmjs.org/postcss-calc/-/postcss-calc-10.1.1.tgz", + "integrity": "sha512-NYEsLHh8DgG/PRH2+G9BTuUdtf9ViS+vdoQ0YA5OQdGsfN4ztiwtDWNtBl9EKeqNMFnIu8IKZ0cLxEQ5r5KVMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^7.0.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12 || ^20.9 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.4.38" + } + }, + "node_modules/postcss-colormin": { + "version": "7.0.10", + "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-7.0.10.tgz", + "integrity": "sha512-yFr6JezOolHLta/buLE71VKPh2mXursp4saVe98/ol8ZnEWhL+racShqPKlvd/DKWLre/39B6HhcMXf7RZ3hxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@colordx/core": "^5.4.3", + "browserslist": "^4.28.2", + "caniuse-api": "^3.0.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-convert-values": { + "version": "7.0.12", + "resolved": "https://registry.npmjs.org/postcss-convert-values/-/postcss-convert-values-7.0.12.tgz", + "integrity": "sha512-xurKu5qqk4viR3Cp3p4xBR4KfnZm4w4ys6+UBwBmeuBSNkH7+DtLnYOYnOffgtE4yx8sH9S1VZ6RAAvROXzP2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-discard-comments": { + "version": "7.0.8", + "resolved": "https://registry.npmjs.org/postcss-discard-comments/-/postcss-discard-comments-7.0.8.tgz", + "integrity": "sha512-CvvS5S9WrXblFXCEJ9nVo+4z+eA7zSC7Z88V1HEJuwlQhlFnYTIjg1xJY+BCUiG2bvICap2tXii4mP22BD108Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^7.1.1" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-discard-duplicates": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/postcss-discard-duplicates/-/postcss-discard-duplicates-7.0.4.tgz", + "integrity": "sha512-VBNn1+EuMZkeGVVtz0gRfbNGtx9IFgAsAV+E2pHtXPrp4qfGBkhTIiAuE/wrb+Y6Pakg9NewAlfTpYIFAWODtw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-discard-empty": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-discard-empty/-/postcss-discard-empty-7.0.3.tgz", + "integrity": "sha512-M2pyjQCU+/7cMHVtL6bKTHjv0lZnPLMpicgr67Dlth7AbuV9gjVTtUqaRwn6Pp6BwSDspUzhz8SaUrRykJU5Dw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-discard-overridden": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-discard-overridden/-/postcss-discard-overridden-7.0.3.tgz", + "integrity": "sha512-aNovXo9UsZuRNLzHJtp13lHIvinDPfiXBPePpXkSjCbgp++iU2FqE+YxvjIsg6EdyPZsASFbfu+JcBFVsErXIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-merge-longhand": { + "version": "7.0.7", + "resolved": "https://registry.npmjs.org/postcss-merge-longhand/-/postcss-merge-longhand-7.0.7.tgz", + "integrity": "sha512-b3mfYUxR388u5Pt0HPcVIUtUDn/k15UfTY9M+ORW+meCR6JLNxoZffiYvXyOYQoRYQNZyX/UFkMCM/mNHxe1qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0", + "stylehacks": "^7.0.11" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-merge-rules": { + "version": "7.0.11", + "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-7.0.11.tgz", + "integrity": "sha512-SJUPM18g2BmPhf8BVlbwqWz4aK3pLu6u6xjfwEzra7xL6IBR10sUaiB++EzqcVfadPHrKBSMlNdP+XieykhI+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "caniuse-api": "^3.0.0", + "cssnano-utils": "^5.0.3", + "postcss-selector-parser": "^7.1.1" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-minify-font-values": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-minify-font-values/-/postcss-minify-font-values-7.0.3.tgz", + "integrity": "sha512-yilG/VOaNI74IylQvAQQxm3/wZVBkXyYUqNUAdxqwtbWUXPsbK1q8Ms0mL83v+f8YicgcyfYCRZtWACUdYajpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-minify-gradients": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/postcss-minify-gradients/-/postcss-minify-gradients-7.0.5.tgz", + "integrity": "sha512-YraROyQRg3BI1+Hg8E05B/JPdnTm8EDSVu4P2BxdM+CRiOyfmou809+chGIqo6fQqwjPGQ947nbGncSjmTU1WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@colordx/core": "^5.4.3", + "cssnano-utils": "^5.0.3", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-minify-params": { + "version": "7.0.9", + "resolved": "https://registry.npmjs.org/postcss-minify-params/-/postcss-minify-params-7.0.9.tgz", + "integrity": "sha512-R8itbB8BhlpoYyBm1ou0dD+vJnQ3F6adQipR4UnkCHUwlo+S9WXJaDRg1RHjC8YVAtIdrQzSWvJl40HnGDTKjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "cssnano-utils": "^5.0.3", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-minify-selectors": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/postcss-minify-selectors/-/postcss-minify-selectors-7.1.2.tgz", + "integrity": "sha512-aQtrEWKwqafNlExcKHQvPGsXR2+vlUqqJtf5XsCQcgsSb5PL4wlujWBYDJuWsP4UnQX1YHDHU8qRlD+1PzTQ+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.1", + "caniuse-api": "^3.0.0", + "cssesc": "^3.0.0", + "postcss-selector-parser": "^7.1.1" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-charset": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-normalize-charset/-/postcss-normalize-charset-7.0.3.tgz", + "integrity": "sha512-NoBfZu8PR4c2NlmjvrqQTzCzLY79hwcSRgNQ3ZiNK0ABzf9kYKloE/jNj+/8GQY1wsm8pRRgANk6ydLH8cwo0Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-display-values": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-normalize-display-values/-/postcss-normalize-display-values-7.0.3.tgz", + "integrity": "sha512-ldsCX0QIt05pKIOobZtVQ48wXJecr+czw4+e1/YjVhLMqslShgpVxgPtI2CefURR8oyVoYaU/l829MMwExDMLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-positions": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/postcss-normalize-positions/-/postcss-normalize-positions-7.0.4.tgz", + "integrity": "sha512-VEvlpeGd3Ju1Hqa/oN4jaP3+ms4laYwkEL9N9u+B6k54PZjXbW1n6wI+aVprf1BQXlCYpS5+1pl/7/vHiKgARg==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-repeat-style": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/postcss-normalize-repeat-style/-/postcss-normalize-repeat-style-7.0.4.tgz", + "integrity": "sha512-6mPKlY/8cSaDHxX502wERADarJsccwlky6yIrOapHH2ZgfoKAV94SbiTKfKEs4EEpdazuc3J72WsqeYk7hp9+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-string": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-normalize-string/-/postcss-normalize-string-7.0.3.tgz", + "integrity": "sha512-HnEQPUchi1eznmDKEYrKUTqrprEq97SrpUYClgUkv7V2zRODD9DFoUsYU+m9ZOetmD5ku7fEMZB/lwy8IT6xVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-timing-functions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-normalize-timing-functions/-/postcss-normalize-timing-functions-7.0.3.tgz", + "integrity": "sha512-zmEzHdvpZBZu0OKlbJSfgASQvaayyAoVuWtvyr34IJ/LyS+DaOKvvR3EvFJ9RWWtNIx+CMvO125OVophaxNYew==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-unicode": { + "version": "7.0.9", + "resolved": "https://registry.npmjs.org/postcss-normalize-unicode/-/postcss-normalize-unicode-7.0.9.tgz", + "integrity": "sha512-DRAdWfeh/TjmhLJsw91vdiWCnUod9iwvM7xyS02/nF/sLsCR3A8l3pztrSUrWG8DSBqfX7yEk9FM0USaVJ2mSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-url": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-normalize-url/-/postcss-normalize-url-7.0.3.tgz", + "integrity": "sha512-CL93wmloq5qsffmFv+bw24MIRbmhHrp53qoh1LDAb/5TtjWEXI/np4xcP/Gw9oWCb2XyWnqHYLDUwiKRoJBA1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-normalize-whitespace": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-normalize-whitespace/-/postcss-normalize-whitespace-7.0.3.tgz", + "integrity": "sha512-FdHjjn+Ht5Z2ZRjNOmeCbNq6lq09sUYKpmlF/Aq0XjVNSLTL6fmHlA/3swN2wP2caY9GV/tjSDcIIyS7aN7W0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-ordered-values": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/postcss-ordered-values/-/postcss-ordered-values-7.0.4.tgz", + "integrity": "sha512-nubSi49hDHQk4E8KIj+IbLY8Bg+8OcSUEhgyolgM+atnOvXjV7EjaR6bac4YGZoFyPa9mWoAF3EaYbWdFkKqVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssnano-utils": "^5.0.3", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-reduce-initial": { + "version": "7.0.9", + "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-7.0.9.tgz", + "integrity": "sha512-ztTNPdIxXTxtBcG03E9u8v44M4ElXbMIRT7pf2onlquGula0Y83nKKxqM22FA/hMgkfCjN7ohevkVlaNwI8iOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "caniuse-api": "^3.0.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-reduce-transforms": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/postcss-reduce-transforms/-/postcss-reduce-transforms-7.0.3.tgz", + "integrity": "sha512-FXsnN9ZwcZTT8Yf8cAHA8qIGUXcX6WfLd9JoYhrdDfmvsVhhfqkkv7m4AC3rwFOfz+GzkUa87OCKF9dUcicd+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-selector-parser": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", + "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-svgo": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/postcss-svgo/-/postcss-svgo-7.1.3.tgz", + "integrity": "sha512-2QfoFOYMcj8lwcVEf9WeTlkVIAm7u2QvOEhMzkQU3KUhhGX/l8hVV9EtjMv4iq3E9iI3OeeMN0YoMLbGusuigw==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0", + "svgo": "^4.0.1" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >= 18" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-unique-selectors": { + "version": "7.0.7", + "resolved": "https://registry.npmjs.org/postcss-unique-selectors/-/postcss-unique-selectors-7.0.7.tgz", + "integrity": "sha512-d+sCkaRnSefghOUdH8CMJZV9yUQhj2ojpe8Nw/lA+LV1UOfeleGkLTl6XdCFFSai9UJ+DJPb69FFuqthXYsY8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^7.1.1" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/preact": { + "name": "@lynx-js/internal-preact", + "version": "11.0.0-rc.1-20260903085447-f95471a", + "resolved": "https://registry.npmjs.org/@lynx-js/internal-preact/-/internal-preact-11.0.0-rc.1-20260903085447-f95471a.tgz", + "integrity": "sha512-RsU+km8Ulg+HVEJpx1/lq/38GUB+KtJKypB80gbumAtswd+og0RpVppy8bZTBVZY7jSjxx2GHYPTjT61+HDPaw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + }, + "peerDependencies": { + "preact-render-to-string": ">=6.7.0" + }, + "peerDependenciesMeta": { + "preact-render-to-string": { + "optional": true + } + } + }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/readdirp/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/reduce-configs": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/reduce-configs/-/reduce-configs-1.1.2.tgz", + "integrity": "sha512-AgBP55V8FC7NaqoOP2RCbTpu6LE+YuX3LUZkNAoitcfyS3/PIC8Obg/TJrBzTkJ+lDvZv0TTAeDpLkzjTtYlbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rslog": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/rslog/-/rslog-2.3.0.tgz", + "integrity": "sha512-g2wW/ermwzGTLlzGdJBDRc4YKz2/yPBjf57w9g5CvhtpZ91Xq95OaWku0oNHYi+XsuV6v8QrCo2oJJR/pCUR8g==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz", + "integrity": "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz", + "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=11.0.0" + } + }, + "node_modules/schema-utils": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.5.0.tgz", + "integrity": "sha512-zJlMCZ0cAR5p/Y4oVpRoqioDMJcGxaXRrQ/4rP4WyR84vc5z/DolXdbvXeDpTwbtocDFr2rhPqHPErDCUtz2kA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/serialize-javascript": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.2.tgz", + "integrity": "sha512-GL2BWwVa6JydKO6l/ljVgjAZF4QJ3S7dWDWi53s5GZT8PJzD2fNxi67HANQGKAqPrwEpL5ba7gUBGi0Ls/sEoQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/shell-quote": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/socket.io": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.1.tgz", + "integrity": "sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "cors": "~2.8.5", + "debug": "~4.3.2", + "engine.io": "~6.6.0", + "socket.io-adapter": "~2.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/socket.io-adapter": { + "version": "2.5.8", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.8.tgz", + "integrity": "sha512-6Oy52pbg+kvdCVvjcN+FnY7BvxZ7cIHNScbvztT/It5d0vbwoJoVZmF2gjJmnV0/4WlXRfG15zc45ySk9Ah8bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "~4.4.1", + "ws": "~8.21.0" + } + }, + "node_modules/socket.io-adapter/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz", + "integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.11.tgz", + "integrity": "sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.2", + "es-object-atoms": "^1.1.2", + "has-property-descriptors": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.10.tgz", + "integrity": "sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/stylehacks": { + "version": "7.0.11", + "resolved": "https://registry.npmjs.org/stylehacks/-/stylehacks-7.0.11.tgz", + "integrity": "sha512-iODNfhXVLqc5LADs+Y6Oh5wJuK5ZcHbVng8aiK3y9pjMQdc5hLrBW0eFU6FtnpNrE6PoEg/MmFTU4waotj5WNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "postcss-selector-parser": "^7.1.1" + }, + "engines": { + "node": "^18.12.0 || ^20.9.0 || >=22.0" + }, + "peerDependencies": { + "postcss": "^8.5.13" + } + }, + "node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/svgo": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/svgo/-/svgo-4.1.0.tgz", + "integrity": "sha512-bkxnTg1kSU0guhIBmibA6UUhrQmPVA1XsQLN+ylCd+UWzbnLkySOcXpyk1mrl05f+pcaCx2eHb+sp6BgMZWX+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "commander": "^11.1.0", + "css-select": "^6.0.0", + "css-tree": "^3.0.1", + "css-what": "^7.0.0", + "csso": "^5.0.5", + "picocolors": "^1.1.1", + "sax": "1.6.1" + }, + "bin": { + "svgo": "bin/svgo.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/svgo" + } + }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/terser": { + "version": "5.51.2", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", + "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==", + "dev": true, + "license": "BSD-2-Clause", + "peer": true, + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.15.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser/node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/thingies": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/thingies/-/thingies-2.6.1.tgz", + "integrity": "sha512-cV/CMGTK3M4MlnJ/0At6ismOw/A0EEniDNScajjz/Br3c1sqE72YD01rGpPTKwd27wAxI5Pr+6+0w8yofzFRYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "^2" + } + }, + "node_modules/tiny-invariant": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", + "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinypool": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.2.0.tgz", + "integrity": "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.0.0 || >=22.0.0" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tree-dump": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/tree-dump/-/tree-dump-1.1.0.tgz", + "integrity": "sha512-rMuvhU4MCDbcbnleZTFezWsaZXRFemSqAM+7jPnzUl1fo9w3YEKOxAeui0fz3OI4EU4hf23iyA7uQRVko+UaBA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/ts-checker-rspack-plugin": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/ts-checker-rspack-plugin/-/ts-checker-rspack-plugin-1.6.2.tgz", + "integrity": "sha512-WDvN9dtylDf3pOkSw3F/3fm4jEmCdppvLCIv7HNtMSvs38lIJRPWuwYWcvQkD9jFF62Hn4FvSnq92U2C9tg60A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rspack/lite-tapable": "^1.3.0", + "chokidar": "^3.6.0", + "memfs": "^4.79.0", + "picocolors": "^1.1.1" + }, + "peerDependencies": { + "@rspack/core": "^1.0.0 || ^2.0.0", + "@typescript/native-preview": "^7.0.0-0", + "typescript": ">=3.8.0" + }, + "peerDependenciesMeta": { + "@rspack/core": { + "optional": true + }, + "@typescript/native-preview": { + "optional": true + } + } + }, + "node_modules/ts-checker-rspack-plugin/node_modules/@rspack/lite-tapable": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@rspack/lite-tapable/-/lite-tapable-1.3.0.tgz", + "integrity": "sha512-YQLaGRltBp5wzh9ee7PMmh1pErbx0E3zDlfO4K3iQpsEcJcBcgj3+9gq6/wqB/zbXbluoWoRCvL+odkft/Qt3A==", + "dev": true, + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD" + }, + "node_modules/type-detect": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.1.0.tgz", + "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.5.tgz", + "integrity": "sha512-0FHJvLPqZ7KJzp17O13jfsAjsqazgrxBu2zEK95PmUz8lv2+GjRuxUInCr2Rk9Dms3ihN21zJ929ZO43yJ95QQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.8.tgz", + "integrity": "sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "is-typed-array": "^1.1.15", + "possible-typed-array-names": "^1.1.0", + "reflect.getprototypeof": "^1.0.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uc.micro": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-3.0.0.tgz", + "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "dev": true, + "license": "MIT" + }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wasm-feature-detect": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/wasm-feature-detect/-/wasm-feature-detect-1.9.0.tgz", + "integrity": "sha512-zonE+xlIIYtxPy++L24ow0hAD8CICb4+FgPyROd3buyXIqsJvUEDkBgfCCoXOd1Hu3DUr0GOfnPIdcGV+YpNaA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/watchpack": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz", + "integrity": "sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack": { + "version": "5.111.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.111.1.tgz", + "integrity": "sha512-cNypaz0RP+S4cvQVi1M/3bRUkvNP0xZpL0TjFx+c6jg64VbxD+2weWDgY9UnjRI6dhZgtaj8DU76GGFcJ79xPQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@types/estree": "^1.0.8", + "@types/json-schema": "^7.0.15", + "@webassemblyjs/ast": "^1.14.1", + "@webassemblyjs/wasm-edit": "^1.14.1", + "@webassemblyjs/wasm-parser": "^1.14.1", + "browserslist": "^4.28.1", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.25.0", + "es-module-lexer": "^2.1.0", + "events": "^3.2.0", + "graceful-fs": "^4.2.11", + "mime-db": "^1.54.0", + "minimizer-webpack-plugin": "^5.7.0", + "schema-utils": "^4.5.0", + "tapable": "^2.3.0", + "watchpack": "^2.5.2", + "webpack-sources": "^3.5.1" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-sources": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.6.0.tgz", + "integrity": "sha512-EIMmPVvNI0CYXyRPp34F2Qk7W37/BZVZIofS6LAUnrNjCVahS+hO4mxwFJDjQjODTGZDtVzLYoN2+1dYkhk9qA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack/node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/webpack/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.24", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.24.tgz", + "integrity": "sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/app/package.json b/app/package.json new file mode 100644 index 0000000..215b351 --- /dev/null +++ b/app/package.json @@ -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" + } +} diff --git a/app/src/App.tsx b/app/src/App.tsx new file mode 100644 index 0000000..1fac7de --- /dev/null +++ b/app/src/App.tsx @@ -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(null); + const [page, setPage] = useState(boot.page); + const [drawerOpen, setDrawerOpen] = useState(boot.drawer); + /** 抽屉里「模型」那一栏点开的面板 */ + const [modelPickerOpen, setModelPickerOpen] = useState(false); + const [activeId, setActiveId] = useState('c_main'); + const [messages, setMessages] = useState([]); + const [draft, setDraft] = useState(''); + const [attachments, setAttachments] = useState([]); + 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>({}); + const toggleReasoning = useCallback((index: number) => { + setOpenReasoning((prev) => ({ ...prev, [index]: !prev[index] })); + }, []); + /** 正在看「思考过程」的消息下标 */ + const [thinkIndex, setThinkIndex] = useState(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 } } }; + 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; + 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) => { + 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) => { + 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 ( + + 连不上 AI 内核 + + {bootError || '正在连接…'} + {'\n'}内核跑在电脑上时,手机端要填电脑的局域网地址。 + + setApiDraft(e.detail.value)} + /> + { + const { setApiBase } = await import('./api.js'); + if (apiDraft.trim()) setApiBase(apiDraft.trim()); + setBootError(''); + await refresh(); + }} + > + 用这个地址重试 + + + 直接重试 + + + ); + } + + const { settings } = state; + + return ( + + {page === 'chat' + ? ( + 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' + ? ( + setMemoryEnabled((v) => !v)} + onOpenDrawer={() => setDrawerOpen(true)} + onOpenSettings={() => setPage('settings')} + onOpenAgents={() => setPage('agents')} + onNewTopic={newTopic} + /> + ) + : null} + + {page === 'settings' + ? setPage('chat')} onSaved={saveSettings} /> + : null} + + {page === 'skills' + ? ( + setPage('chat')} + onRefresh={async () => { await refresh(); }} + onSaveSecurity={saveSecurity} + /> + ) + : null} + + {page === 'agents' + ? ( + setPage('chat')} + onUse={useAgent} + onRefresh={async () => { await refresh(); }} + /> + ) + : null} + + {page === 'terminal' + ? ( + setPage('chat')} + shellChannel={shellChannel} + onRefreshChannel={refreshShellChannel} + platform={state.platform} + /> + ) + : null} + + {drawerOpen + ? ( + 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 + ? ( + setModelPickerOpen(false)} + onPick={pickModel} + /> + ) + : null} + + ); +} diff --git a/app/src/Icon.tsx b/app/src/Icon.tsx new file mode 100644 index 0000000..7cee0ed --- /dev/null +++ b/app/src/Icon.tsx @@ -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 = { + '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 ; +} + +/** 智能体头像表:key 与内核里的 agent.avatar 对应 */ +export const AGENT_AVATARS: Record = { + 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 ; +} + +export { avatarMain, avatarDoubao }; diff --git a/app/src/api.ts b/app/src/api.ts new file mode 100644 index 0000000..7a934a5 --- /dev/null +++ b/app/src/api.ts @@ -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 }; + 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(path: string, init?: RequestInit): Promise { + 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('/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) => + 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) => + 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; + }>('/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) => + request<{ agent: Agent }>('/api/agents', { method: 'POST', body: JSON.stringify(body) }), + updateAgent: (id: string, body: Partial) => + 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 | null = null; + +async function supportsStreaming(): Promise { + 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 { + 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 { + 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); +} diff --git a/app/src/app.css b/app/src/app.css new file mode 100644 index 0000000..f62a5a6 --- /dev/null +++ b/app/src/app.css @@ -0,0 +1,1752 @@ +/* ============================================================ + 豆包复刻 · 全局样式 + 注意 Lynx 的几个硬约束: + 1) display 默认是 linear,需要 flex 就得显式写 + 2) 不支持 overflow: scroll,滚动只能用 + 3) 文字必须在 里 + 4) 不支持 !important + ============================================================ */ + +.app { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + background-color: #ffffff; + position: relative; +} + +.page { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + background-color: #ffffff; +} + +/* ---------------- 通用图标尺寸 ---------------- */ +.icon { + width: 24px; + height: 24px; +} +.icon-sm { + width: 20px; + height: 20px; +} +.icon-lg { + width: 26px; + height: 26px; +} +.icon-xl { + width: 30px; + height: 30px; +} + +/* ============================================================ + 聊天页 + ============================================================ */ +.chat-header { + display: flex; + flex-direction: row; + align-items: center; + height: 52px; + padding-left: 8px; + padding-right: 8px; + background-color: #ffffff; +} + +.hdr-btn { + display: flex; + align-items: center; + justify-content: center; + width: 40px; + height: 40px; +} + +.hdr-title { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + flex: 1; +} + +.hdr-title-row { + display: flex; + flex-direction: row; + align-items: center; +} + +.hdr-title-text { + font-size: 17px; + font-weight: 600; + color: #1f2329; +} + +.hdr-caret { + font-size: 15px; + color: #b6bac2; + margin-left: 4px; +} + +.hdr-sub { + font-size: 11px; + color: #a3a8b3; + margin-top: 2px; +} + +.chat-body { + flex: 1; + width: 100%; +} + +.chat-body-inner { + display: flex; + flex-direction: column; + padding-left: 16px; + padding-right: 16px; + padding-bottom: 16px; +} + +.hero { + display: flex; + align-items: center; + justify-content: center; + padding-top: 72px; + padding-bottom: 16px; +} + +.hero-avatar { + width: 168px; + height: 168px; + border-radius: 84px; + background-color: #dbe8ff; +} + +.bubble { + display: flex; + flex-direction: column; + padding: 14px 16px; + border-radius: 18px; + margin-bottom: 18px; +} + +.bubble-bot { + background-color: #f4f5f7; + align-self: flex-start; + max-width: 86%; +} + +.bubble-user { + background-color: #2b7bff; + align-self: flex-end; + max-width: 86%; +} + +.bubble-text { + font-size: 17px; + line-height: 26px; + color: #1f2329; +} + +.bubble-text-user { + font-size: 17px; + line-height: 26px; + color: #ffffff; +} + +.bubble-error { + background-color: #fff1f0; +} + +.bubble-error .bubble-text { + color: #d4380d; +} + +.typing { + display: flex; + flex-direction: row; + align-items: center; +} + +.typing-dot { + width: 7px; + height: 7px; + border-radius: 4px; + background-color: #c2c7d0; + margin-right: 5px; +} + +.trace { + display: flex; + flex-direction: column; + margin-bottom: 14px; + padding: 10px 12px; + border-radius: 12px; + background-color: #f7f8fa; + border: 1px solid #eceef2; + max-width: 86%; + align-self: flex-start; +} + +.trace-row { + display: flex; + flex-direction: row; + align-items: center; + margin-bottom: 4px; +} + +.trace-title { + font-size: 12px; + font-weight: 600; + color: #5b6270; +} + +.trace-text { + font-size: 12px; + line-height: 18px; + color: #8a8f99; +} + +/* 底部快捷入口 */ +.quick-row { + display: flex; + flex-direction: row; + align-items: center; + padding-left: 12px; + padding-right: 12px; + padding-bottom: 10px; +} + +.chip { + display: flex; + flex-direction: row; + align-items: center; + height: 38px; + padding-left: 12px; + padding-right: 14px; + margin-right: 8px; + border-radius: 12px; + border: 1px solid #e8eaee; + background-color: #ffffff; + flex-shrink: 0; +} + +.chip-text { + font-size: 15px; + color: #1f2329; + margin-left: 6px; + lines: 1; + flex-shrink: 0; +} + +.quick-row { + flex-shrink: 0; +} + +/* 输入栏 */ +.input-bar { + display: flex; + flex-direction: row; + align-items: center; + padding-left: 12px; + padding-right: 12px; + padding-bottom: 18px; + padding-top: 4px; + background-color: #ffffff; +} + +.input-pill { + display: flex; + flex-direction: row; + align-items: center; + flex: 1; + height: 52px; + border-radius: 26px; + background-color: #ffffff; + border: 1px solid #e8eaee; + box-shadow: 0px 2px 10px rgba(31, 35, 41, 0.06); + padding-left: 12px; + padding-right: 8px; +} + +.input-field { + flex: 1; + height: 40px; + font-size: 16px; + color: #1f2329; + margin-left: 8px; + margin-right: 4px; +} + +.input-btn { + display: flex; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; +} + +/* ============================================================ + 抽屉(会话列表) + ============================================================ */ +.drawer-mask { + position: absolute; + left: 0; + top: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.35); + z-index: 20; +} + +.drawer { + position: absolute; + left: 0; + top: 0; + bottom: 0; + width: 86%; + background-color: #ffffff; + display: flex; + flex-direction: column; + padding-left: 12px; + padding-right: 12px; +} + +.drawer-header { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + height: 56px; + padding-left: 12px; + padding-right: 4px; +} + +.drawer-title { + font-size: 24px; + font-weight: 700; + color: #1f2329; +} + +.drawer-menu { + display: flex; + flex-direction: column; + padding-top: 4px; + padding-bottom: 6px; +} + +.menu-item { + display: flex; + flex-direction: row; + align-items: center; + height: 46px; + padding-left: 12px; + border-radius: 12px; +} + +.menu-item-text { + font-size: 17px; + color: #1f2329; + margin-left: 14px; +} + +.section-head { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + height: 34px; + padding-left: 12px; + padding-right: 6px; +} + +.section-label { + font-size: 14px; + color: #a3a8b3; +} + +.conv-item { + display: flex; + flex-direction: row; + align-items: center; + height: 50px; + padding-left: 12px; + padding-right: 8px; + border-radius: 12px; +} + +.conv-item-active { + background-color: #f2f3f5; +} + +.conv-avatar { + width: 32px; + height: 32px; + border-radius: 16px; +} + +.conv-title { + font-size: 17px; + color: #1f2329; + margin-left: 12px; + flex: 1; + lines: 1; + text-overflow: ellipsis; +} + +.drawer-spacer { + flex: 1; +} + +.drawer-bottom { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + height: 56px; + padding-left: 6px; + padding-right: 6px; + border-top: 1px solid #f0f1f3; +} + +.user-pill { + display: flex; + flex-direction: row; + align-items: center; + height: 38px; + padding-left: 6px; + padding-right: 10px; + border-radius: 19px; + background-color: #f2f3f5; +} + +.user-pill-avatar { + width: 28px; + height: 28px; + border-radius: 14px; + margin-right: 6px; +} + +.user-pill-text { + font-size: 16px; + color: #1f2329; +} + +.bell-wrap { + position: relative; + display: flex; + align-items: center; + justify-content: center; + width: 40px; + height: 40px; +} + +.bell-dot { + position: absolute; + right: 6px; + top: 6px; + width: 10px; + height: 10px; + border-radius: 5px; + background-color: #ff3b30; + border: 1.5px solid #ffffff; +} + +/* ============================================================ + 我的页 + ============================================================ */ +.profile-page { + background-color: #f5f6f7; +} + +.profile-header { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + height: 48px; + padding-left: 8px; + padding-right: 8px; +} + +.profile-hero { + display: flex; + flex-direction: column; + align-items: center; + padding-top: 18px; + padding-bottom: 18px; +} + +.avatar-row { + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; +} + +.avatar-add { + display: flex; + align-items: center; + justify-content: center; + width: 52px; + height: 52px; + border-radius: 26px; + background-color: #ffffff; + margin-right: -18px; +} + +.avatar-main-big { + width: 96px; + height: 96px; + border-radius: 48px; + background-color: #dbe8ff; +} + +.avatar-photo-big { + width: 52px; + height: 52px; + border-radius: 26px; + margin-left: -18px; + border: 2px solid #f5f6f7; +} + +.profile-name { + font-size: 20px; + font-weight: 600; + color: #1f2329; + margin-top: 12px; +} + +.profile-id { + font-size: 13px; + color: #a3a8b3; + margin-top: 6px; +} + +.account-btn { + display: flex; + align-items: center; + justify-content: center; + height: 40px; + padding-left: 20px; + padding-right: 20px; + border-radius: 20px; + background-color: #ffffff; + margin-top: 14px; +} + +.account-btn-text { + font-size: 16px; + color: #1f2329; +} + +.profile-card { + display: flex; + flex-direction: column; + background-color: #ffffff; + border-radius: 16px; + margin-left: 12px; + margin-right: 12px; + margin-bottom: 12px; + padding-left: 14px; + padding-right: 14px; +} + +.profile-row { + display: flex; + flex-direction: row; + align-items: center; + height: 60px; +} + +.profile-row-icon { + width: 30px; + height: 30px; +} + +.profile-row-text { + flex: 1; + font-size: 17px; + color: #1f2329; + margin-left: 14px; +} + +.profile-row-value { + font-size: 15px; + color: #a3a8b3; + margin-right: 2px; +} + +.row-divider { + height: 1px; + background-color: #f2f3f5; + margin-left: 44px; +} + +/* ============================================================ + 设置 / 技能页(通用列表与表单) + ============================================================ */ +.sub-header { + display: flex; + flex-direction: row; + align-items: center; + height: 52px; + padding-left: 8px; + padding-right: 12px; + background-color: #ffffff; +} + +.sub-header-title { + flex: 1; + font-size: 17px; + font-weight: 600; + color: #1f2329; +} + +.back-btn { + display: flex; + align-items: center; + justify-content: center; + width: 44px; + height: 40px; +} + +.form-scroll { + flex: 1; + width: 100%; +} + +.form-inner { + display: flex; + flex-direction: column; + padding: 12px; + padding-bottom: 40px; +} + +.form-card { + display: flex; + flex-direction: column; + background-color: #ffffff; + border-radius: 16px; + padding: 14px; + margin-bottom: 12px; +} + +.form-label { + font-size: 13px; + color: #8a8f99; + margin-bottom: 6px; +} + +.form-input { + height: 42px; + border-radius: 10px; + background-color: #f4f5f7; + padding-left: 12px; + padding-right: 12px; + font-size: 15px; + color: #1f2329; +} + +.form-textarea { + height: 190px; + border-radius: 10px; + background-color: #f4f5f7; + padding: 10px 12px; + font-size: 14px; + line-height: 21px; + color: #1f2329; +} + +.form-hint { + font-size: 12px; + line-height: 18px; + color: #a3a8b3; + margin-top: 6px; +} + +.segment { + display: flex; + flex-direction: row; + background-color: #f4f5f7; + border-radius: 10px; + padding: 3px; +} + +/* 提供商现在有十来家,一行排不下,让它换行 */ +.segment-wrap { + flex-wrap: wrap; + row-gap: 4px; +} + +.segment-wrap .segment-item { + flex: 0 0 auto; + min-width: 76px; + padding: 0 12px; +} + +.segment-item { + display: flex; + align-items: center; + justify-content: center; + flex: 1; + height: 34px; + border-radius: 8px; +} + +.segment-item-active { + background-color: #ffffff; + /* 白底压在浅灰上对比太弱,加一点描边和投影才看得出选了哪个 */ + box-shadow: 0 1px 3px rgba(15, 23, 42, 0.12); +} + +.segment-text { + font-size: 14px; + color: #5b6270; +} + +.segment-text-active { + color: #2b7bff; + font-weight: 600; +} + +.chip-row { + display: flex; + flex-direction: row; + flex-wrap: wrap; + margin-top: 8px; +} + +.model-chip { + display: flex; + align-items: center; + height: 30px; + padding-left: 10px; + padding-right: 10px; + border-radius: 8px; + background-color: #f4f5f7; + margin-right: 8px; + margin-bottom: 8px; +} + +.model-chip-text { + font-size: 12px; + color: #5b6270; +} + +.model-chip-active { + background-color: #e8f1ff; +} + +.model-chip-text-active { + color: #2b7bff; +} + +.switch-row { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + height: 52px; +} + +.switch-label { + font-size: 16px; + color: #1f2329; +} + +.switch { + width: 48px; + height: 28px; + border-radius: 14px; + background-color: #e3e5e9; + display: flex; + flex-direction: row; + align-items: center; + padding-left: 2px; + padding-right: 2px; +} + +.switch-on { + background-color: #2b7bff; + justify-content: flex-end; +} + +.switch-knob { + width: 24px; + height: 24px; + border-radius: 12px; + background-color: #ffffff; +} + +.primary-btn { + display: flex; + align-items: center; + justify-content: center; + height: 46px; + border-radius: 23px; + background-color: #2b7bff; + margin-top: 4px; +} + +.primary-btn-text { + font-size: 16px; + font-weight: 600; + color: #ffffff; +} + +.ghost-btn { + display: flex; + align-items: center; + justify-content: center; + height: 38px; + padding-left: 16px; + padding-right: 16px; + border-radius: 19px; + border: 1px solid #e3e5e9; + background-color: #ffffff; +} + +.ghost-btn-text { + font-size: 14px; + color: #1f2329; +} + +.tool-item { + display: flex; + flex-direction: column; + padding-top: 12px; + padding-bottom: 12px; + border-bottom: 1px solid #f2f3f5; +} + +.tool-name { + font-size: 15px; + font-weight: 600; + color: #1f2329; +} + +.tool-desc { + font-size: 12px; + line-height: 18px; + color: #8a8f99; + margin-top: 4px; +} + +.tool-meta { + font-size: 11px; + color: #b6bac2; + margin-top: 4px; +} + +.tool-actions { + display: flex; + flex-direction: row; + align-items: center; + margin-top: 10px; +} + +.badge { + display: flex; + align-items: center; + height: 22px; + padding-left: 8px; + padding-right: 8px; + border-radius: 11px; + background-color: #f2f3f5; + margin-left: 8px; +} + +.badge-ok { + background-color: #e8f7ee; +} + +.badge-text { + font-size: 11px; + color: #5b6270; +} + +.badge-text-ok { + color: #12a150; +} + +.result-box { + margin-top: 10px; + padding: 10px; + border-radius: 10px; + background-color: #f7f8fa; +} + +.result-text { + font-size: 12px; + line-height: 18px; + color: #5b6270; +} + +.empty-tip { + font-size: 13px; + color: #a3a8b3; + padding-top: 12px; + padding-bottom: 12px; +} + +/* ============================================================ + 动画 + ============================================================ */ +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(10px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes slideInLeft { + from { + transform: translateX(-100%); + } + to { + transform: translateX(0); + } +} + +@keyframes dotBounce { + 0%, + 70%, + 100% { + transform: translateY(0); + opacity: 0.45; + } + 35% { + transform: translateY(-5px); + opacity: 1; + } +} + +@keyframes popIn { + from { + transform: scale(0.8); + opacity: 0; + } + to { + transform: scale(1); + opacity: 1; + } +} + +@keyframes breathe { + 0%, + 100% { + transform: scale(1); + } + 50% { + transform: scale(1.04); + } +} + +.bubble-enter { + animation: fadeInUp 0.24s ease-out; +} + +.fade-in-up { + animation: fadeInUp 0.26s ease-out; +} + +.drawer-slide { + animation: slideInLeft 0.28s cubic-bezier(0.22, 0.61, 0.36, 1); +} + +.drawer-fade { + animation: fadeIn 0.22s ease-out; +} + +.typing-dot { + animation: dotBounce 1.1s infinite ease-in-out; +} + +.dot-1 { + animation-delay: 0s; +} +.dot-2 { + animation-delay: 0.15s; +} +.dot-3 { + animation-delay: 0.3s; +} + +/* 头像的呼吸动画:部分模拟器(雷电)GL 合成有问题会导致图片不绘制,这里只做很轻的动效 */ +.hero-avatar { + background-color: #dbe8ff; +} + +.attach-tile, +.send-btn, +.avatar-choice-on { + animation: popIn 0.18s ease-out; +} + +/* ============================================================ + 智能体 / 消息操作 / 附件 + ============================================================ */ +.icon-xs { + width: 12px; + height: 12px; +} +.icon-sm.active { + /* 点赞/点踩选中态:换成蓝色描边图做不到,用底色块表示 */ + background-color: #e8f1ff; + border-radius: 6px; +} + +.round { + border-radius: 999px; +} + +.hdr-agent-avatar { + width: 20px; + height: 20px; + border-radius: 10px; + margin-right: 6px; +} + +/* 助手消息整块(气泡 + 操作栏) */ +.bubble-group { + display: flex; + flex-direction: column; + align-self: flex-start; + max-width: 86%; + margin-bottom: 4px; +} + +.bubble-group .bubble { + max-width: 100%; + margin-bottom: 8px; +} + +.msg-actions { + display: flex; + flex-direction: row; + align-items: center; + padding-bottom: 14px; +} + +.msg-action { + display: flex; + align-items: center; + justify-content: center; + width: 34px; + height: 30px; + border-radius: 9px; + margin-right: 6px; + background-color: #f4f5f7; +} + +.msg-action-right { + margin-left: auto; + margin-right: 0; +} + +/* ===== 应用内终端 ===== */ + +.terminal-page { + padding: 0; +} + +.term-head { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + padding: 10px 12px; +} + +.back-flip { + transform: rotate(180deg); +} + +.term-title { + font-size: 17px; + font-weight: 600; + color: #1f2329; +} + +.term-chip { + background-color: #fff7e6; + border-radius: 10px; + padding: 8px 10px; + margin: 0 12px 8px 12px; +} + +.term-chip-ok { + background-color: #eaf7ef; +} + +.term-chip-text { + font-size: 12px; + line-height: 18px; + color: #6b6250; +} + +.term-presets { + display: flex; + flex-direction: row; + padding: 0 12px 8px 12px; +} + +.term-body { + flex: 1; + background-color: #14161a; + margin: 0 12px; + border-radius: 12px; + padding: 10px; +} + +.term-line { + font-size: 12px; + line-height: 18px; + color: #d7dae0; + margin-bottom: 3px; +} + +.term-cmd { + color: #7fd1a0; +} + +.term-err { + color: #ff8f8f; +} + +.term-note { + color: #8a93a0; +} + +.term-input-bar { + display: flex; + flex-direction: row; + align-items: center; + padding: 10px 12px 16px 12px; +} + +.term-input { + flex: 1; + height: 40px; + background-color: #f2f4f7; + border-radius: 20px; + padding: 0 14px; + font-size: 14px; + color: #1f2329; + margin-right: 8px; +} + +/* ===== 抽屉里的「模型」一栏 + 模型选择面板 ===== */ + +.menu-item-model { + justify-content: flex-start; +} + +.menu-model-value { + font-size: 13px; + color: #8a9099; + margin-left: auto; + margin-right: 6px; +} + +.menu-caret { + font-size: 14px; + color: #b8bec7; + margin-bottom: 6px; +} + +.sheet-mask { + position: fixed; + left: 0; + top: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.35); + display: flex; + flex-direction: column; + justify-content: flex-end; + z-index: 60; +} + +.sheet { + background-color: #ffffff; + border-top-left-radius: 20px; + border-top-right-radius: 20px; + padding: 16px 16px 24px 16px; + display: flex; + flex-direction: column; + max-height: 78%; +} + +.model-sheet { + animation: fadeInUp 0.22s ease-out; +} + +.sheet-head { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + margin-bottom: 10px; +} + +.sheet-title { + font-size: 17px; + font-weight: 600; + color: #1f2329; +} + +.sheet-section { + font-size: 12px; + color: #9aa0a8; + margin: 12px 0 8px 2px; +} + +.model-tip-row { + display: flex; + flex-direction: row; + align-items: center; + background-color: #f2f5fa; + border-radius: 10px; + padding: 8px 10px; +} + +.model-tip { + font-size: 12px; + color: #6b7280; + margin-left: 6px; + flex: 1; +} + +.model-list { + display: flex; + flex-direction: column; +} + +.model-option { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + padding: 10px 12px; + border-radius: 12px; + border: 1px solid #eef1f5; + margin-bottom: 8px; +} + +.model-option-active { + border-color: #2b7bff; + background-color: #f2f7ff; +} + +.model-option-text { + display: flex; + flex-direction: column; +} + +.model-name { + font-size: 15px; + color: #1f2329; + font-weight: 500; +} + +.model-id { + font-size: 11px; + color: #a3a9b1; + margin-top: 2px; + lines: 1; + text-overflow: ellipsis; +} + +.copy-hint { + align-self: center; + font-size: 12px; + color: #ffffff; + background-color: rgba(31, 35, 41, 0.78); + border-radius: 12px; + padding: 5px 12px; + margin-bottom: 10px; + animation: fadeIn 0.2s ease-out; +} + +/* 思维链:正文里只放一个入口,点开是底部「思考过程」弹层 */ +.think-entry { + display: flex; + flex-direction: row; + align-items: center; + align-self: flex-start; + background-color: #f4f6fa; + border-radius: 14px; + padding: 6px 12px; + margin-bottom: 8px; + animation: fadeInUp 0.24s ease-out; +} + +.think-entry-text { + font-size: 13px; + color: #5a6472; + margin-left: 6px; + margin-right: 4px; +} + +/* 工具步骤 */ +.steps { + display: flex; + flex-direction: column; + margin-bottom: 8px; +} + +.step-item { + display: flex; + flex-direction: column; +} + +.step-row { + display: flex; + flex-direction: row; + align-items: center; + background-color: #f7f8fa; + border-radius: 10px; + padding: 8px 10px; + margin-bottom: 6px; +} + +.step-name { + font-size: 13px; + color: #3c4450; + margin-left: 6px; +} + +.step-badge { + font-size: 11px; + color: #34a853; + margin-left: auto; + margin-right: 6px; +} + +.step-badge-bad { + color: #e5484d; +} + +.step-result { + font-size: 12px; + line-height: 18px; + color: #6b7280; + background-color: #fbfcfd; + border-radius: 10px; + padding: 8px 10px; + margin: -2px 0 8px 0; +} + +/* 思考过程弹层 */ +.think-sheet { + max-height: 72%; +} + +.think-head { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + margin-bottom: 8px; +} + +.think-close { + width: 34px; + height: 34px; + border-radius: 17px; + background-color: #f2f4f7; + display: flex; + align-items: center; + justify-content: center; +} + +.think-title { + font-size: 17px; + font-weight: 600; + color: #1f2329; +} + +.think-scroll { + height: 380px; +} + +.think-facts { + display: flex; + flex-direction: column; + margin-bottom: 10px; +} + +.think-fact { + display: flex; + flex-direction: row; + align-items: center; + margin-bottom: 6px; +} + +.think-fact-text { + font-size: 13px; + color: #4b5563; + margin-left: 6px; +} + +.think-body { + font-size: 13px; + line-height: 21px; + color: #5f6672; +} + +/* 思维链(深度思考) */ +.reason-box { + display: flex; + flex-direction: column; + background-color: #fbfaf5; + border: 1px solid #f0ead6; + border-radius: 12px; + padding: 10px 12px; + margin-bottom: 8px; + animation: fadeInUp 0.24s ease-out; +} + +.reason-head { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; +} + +.reason-title { + font-size: 12px; + font-weight: 600; + color: #9a7b28; +} + +.reason-toggle { + font-size: 12px; + color: #b6a165; +} + +.reason-text { + font-size: 12px; + line-height: 19px; + color: #7a6a44; + margin-top: 8px; + lines: 60; +} + +/* 用户气泡里的附件 */ +.bubble-files { + display: flex; + flex-direction: column; + margin-bottom: 6px; +} + +.bubble-file { + display: flex; + flex-direction: row; + align-items: center; + margin-bottom: 4px; +} + +.bubble-file-img { + width: 120px; + height: 120px; + border-radius: 12px; + margin-bottom: 6px; +} + +.bubble-file-name { + font-size: 13px; + color: #ffffff; + margin-left: 4px; + lines: 1; +} + +/* 输入框上方的附件条 */ +.attach-strip { + display: flex; + flex-direction: row; + align-items: flex-end; + padding-left: 16px; + padding-right: 16px; + padding-bottom: 8px; +} + +.attach-tile { + position: relative; + width: 64px; + height: 64px; + border-radius: 12px; + margin-right: 10px; + background-color: #f4f5f7; + overflow: hidden; +} + +.attach-thumb { + width: 64px; + height: 64px; +} + +.attach-file { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + width: 64px; + height: 64px; +} + +.attach-file-name { + font-size: 10px; + color: #5b6270; + margin-top: 2px; + lines: 1; +} + +.attach-file-size { + font-size: 9px; + color: #a3a8b3; +} + +.attach-remove { + position: absolute; + right: 0; + top: 0; + width: 18px; + height: 18px; + border-radius: 9px; + background-color: rgba(31, 35, 41, 0.7); + display: flex; + align-items: center; + justify-content: center; +} + +.attach-add { + width: 64px; + height: 64px; + border-radius: 12px; + border: 1px dashed #cfd4dc; + display: flex; + align-items: center; + justify-content: center; + background-color: #fafbfc; +} + +.attach-add-plus { + font-size: 26px; + color: #a3a8b3; +} + +.send-btn { + width: 36px; + height: 36px; + border-radius: 18px; + background-color: #2b7bff; + display: flex; + align-items: center; + justify-content: center; +} + +/* 智能体列表 */ +.agent-item { + display: flex; + flex-direction: row; + align-items: center; + padding-top: 12px; + padding-bottom: 12px; + border-bottom: 1px solid #f2f3f5; +} + +.agent-avatar { + width: 44px; + height: 44px; + border-radius: 22px; +} + +.agent-info { + flex: 1; + display: flex; + flex-direction: column; + margin-left: 12px; + margin-right: 8px; +} + +.agent-name-row { + display: flex; + flex-direction: row; + align-items: center; +} + +.agent-name { + font-size: 16px; + font-weight: 600; + color: #1f2329; +} + +.agent-tagline { + font-size: 12px; + color: #8a8f99; + margin-top: 3px; + lines: 1; +} + +.avatar-picker { + display: flex; + flex-direction: row; + flex-wrap: wrap; +} + +.avatar-choice { + width: 48px; + height: 48px; + border-radius: 24px; + margin-right: 10px; + margin-bottom: 10px; + border: 2px solid transparent; +} + +.avatar-choice-on { + border: 2px solid #2b7bff; +} + +.avatar-choice-img { + width: 44px; + height: 44px; + border-radius: 22px; +} + +/* 抽屉里的会话条目:标题 + 预览 + 时间 */ +.conv-item { + height: 62px; +} + +.conv-text { + flex: 1; + display: flex; + flex-direction: column; + margin-left: 12px; + margin-right: 6px; +} + +.conv-title { + font-size: 16px; + color: #1f2329; + lines: 1; + margin-left: 0px; +} + +.conv-preview { + font-size: 11px; + color: #a3a8b3; + margin-top: 3px; + lines: 1; +} + +.conv-time { + font-size: 11px; + color: #b6bac2; +} + +.conv-del { + display: flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; +} + +.drawer-list { + flex: 1; +} + +/* MCP 图形化编辑 */ +.server-card { + display: flex; + flex-direction: column; + border: 1px solid #eceef2; + border-radius: 12px; + padding: 12px; + margin-bottom: 12px; + background-color: #fbfcfd; +} + +.server-head { + display: flex; + flex-direction: row; + align-items: center; +} + +.server-name { + flex: 1; + margin-right: 10px; +} + +/* 工具授权勾选 */ +.tool-picker { + display: flex; + flex-direction: column; + margin-top: 10px; + border: 1px solid #eceef2; + border-radius: 12px; + padding: 6px 10px; + max-height: 320px; +} + +.tool-pick-row { + display: flex; + flex-direction: row; + align-items: center; + padding-top: 8px; + padding-bottom: 8px; +} + +.checkbox { + width: 18px; + height: 18px; + border-radius: 5px; + border: 1.5px solid #cfd4dc; + display: flex; + align-items: center; + justify-content: center; + margin-right: 10px; +} + +.checkbox-on { + background-color: #2b7bff; + border: 1.5px solid #2b7bff; +} + +.checkbox-tick { + font-size: 12px; + color: #ffffff; +} + +.tool-pick-name { + flex: 1; + font-size: 13px; + color: #1f2329; + lines: 1; +} + +.tool-pick-tag { + font-size: 10px; + color: #12a150; + background-color: #e8f7ee; + border-radius: 8px; + padding: 1px 6px; +} diff --git a/app/src/assets/avatar-doubao.png b/app/src/assets/avatar-doubao.png new file mode 100644 index 0000000..62d3f76 Binary files /dev/null and b/app/src/assets/avatar-doubao.png differ diff --git a/app/src/assets/avatar-main.png b/app/src/assets/avatar-main.png new file mode 100644 index 0000000..3578d16 Binary files /dev/null and b/app/src/assets/avatar-main.png differ diff --git a/app/src/assets/avatar-photo.png b/app/src/assets/avatar-photo.png new file mode 100644 index 0000000..3d33677 Binary files /dev/null and b/app/src/assets/avatar-photo.png differ diff --git a/app/src/assets/avatars-png/agent-analyst.png b/app/src/assets/avatars-png/agent-analyst.png new file mode 100644 index 0000000..d0a8f98 Binary files /dev/null and b/app/src/assets/avatars-png/agent-analyst.png differ diff --git a/app/src/assets/avatars-png/agent-cat.png b/app/src/assets/avatars-png/agent-cat.png new file mode 100644 index 0000000..419fff4 Binary files /dev/null and b/app/src/assets/avatars-png/agent-cat.png differ diff --git a/app/src/assets/avatars-png/agent-cloud.png b/app/src/assets/avatars-png/agent-cloud.png new file mode 100644 index 0000000..b3da2cc Binary files /dev/null and b/app/src/assets/avatars-png/agent-cloud.png differ diff --git a/app/src/assets/avatars-png/agent-coder.png b/app/src/assets/avatars-png/agent-coder.png new file mode 100644 index 0000000..0e4d29d Binary files /dev/null and b/app/src/assets/avatars-png/agent-coder.png differ diff --git a/app/src/assets/avatars-png/agent-custom.png b/app/src/assets/avatars-png/agent-custom.png new file mode 100644 index 0000000..c1486c3 Binary files /dev/null and b/app/src/assets/avatars-png/agent-custom.png differ diff --git a/app/src/assets/avatars-png/agent-robot.png b/app/src/assets/avatars-png/agent-robot.png new file mode 100644 index 0000000..da71a06 Binary files /dev/null and b/app/src/assets/avatars-png/agent-robot.png differ diff --git a/app/src/assets/avatars-png/agent-star.png b/app/src/assets/avatars-png/agent-star.png new file mode 100644 index 0000000..3d5c114 Binary files /dev/null and b/app/src/assets/avatars-png/agent-star.png differ diff --git a/app/src/assets/avatars-png/agent-writer.png b/app/src/assets/avatars-png/agent-writer.png new file mode 100644 index 0000000..88db1bc Binary files /dev/null and b/app/src/assets/avatars-png/agent-writer.png differ diff --git a/app/src/assets/avatars-png/analyst.png b/app/src/assets/avatars-png/analyst.png new file mode 100644 index 0000000..d0a8f98 Binary files /dev/null and b/app/src/assets/avatars-png/analyst.png differ diff --git a/app/src/assets/avatars-png/cat.png b/app/src/assets/avatars-png/cat.png new file mode 100644 index 0000000..419fff4 Binary files /dev/null and b/app/src/assets/avatars-png/cat.png differ diff --git a/app/src/assets/avatars-png/cloud.png b/app/src/assets/avatars-png/cloud.png new file mode 100644 index 0000000..b3da2cc Binary files /dev/null and b/app/src/assets/avatars-png/cloud.png differ diff --git a/app/src/assets/avatars-png/coder.png b/app/src/assets/avatars-png/coder.png new file mode 100644 index 0000000..0e4d29d Binary files /dev/null and b/app/src/assets/avatars-png/coder.png differ diff --git a/app/src/assets/avatars-png/custom.png b/app/src/assets/avatars-png/custom.png new file mode 100644 index 0000000..c1486c3 Binary files /dev/null and b/app/src/assets/avatars-png/custom.png differ diff --git a/app/src/assets/avatars-png/robot.png b/app/src/assets/avatars-png/robot.png new file mode 100644 index 0000000..da71a06 Binary files /dev/null and b/app/src/assets/avatars-png/robot.png differ diff --git a/app/src/assets/avatars-png/star.png b/app/src/assets/avatars-png/star.png new file mode 100644 index 0000000..3d5c114 Binary files /dev/null and b/app/src/assets/avatars-png/star.png differ diff --git a/app/src/assets/avatars-png/writer.png b/app/src/assets/avatars-png/writer.png new file mode 100644 index 0000000..88db1bc Binary files /dev/null and b/app/src/assets/avatars-png/writer.png differ diff --git a/app/src/assets/avatars/analyst.svg b/app/src/assets/avatars/analyst.svg new file mode 100644 index 0000000..881ed93 --- /dev/null +++ b/app/src/assets/avatars/analyst.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/avatars/cat.svg b/app/src/assets/avatars/cat.svg new file mode 100644 index 0000000..2adb6d7 --- /dev/null +++ b/app/src/assets/avatars/cat.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/avatars/cloud.svg b/app/src/assets/avatars/cloud.svg new file mode 100644 index 0000000..f6b3dff --- /dev/null +++ b/app/src/assets/avatars/cloud.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/avatars/coder.svg b/app/src/assets/avatars/coder.svg new file mode 100644 index 0000000..d048cfb --- /dev/null +++ b/app/src/assets/avatars/coder.svg @@ -0,0 +1 @@ +</> \ No newline at end of file diff --git a/app/src/assets/avatars/custom.svg b/app/src/assets/avatars/custom.svg new file mode 100644 index 0000000..10d5527 --- /dev/null +++ b/app/src/assets/avatars/custom.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/avatars/robot.svg b/app/src/assets/avatars/robot.svg new file mode 100644 index 0000000..91af5e1 --- /dev/null +++ b/app/src/assets/avatars/robot.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/avatars/star.svg b/app/src/assets/avatars/star.svg new file mode 100644 index 0000000..3162c37 --- /dev/null +++ b/app/src/assets/avatars/star.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/avatars/writer.svg b/app/src/assets/avatars/writer.svg new file mode 100644 index 0000000..eebfb4b --- /dev/null +++ b/app/src/assets/avatars/writer.svg @@ -0,0 +1 @@ +✎ \ No newline at end of file diff --git a/app/src/assets/icons-png/attach.png b/app/src/assets/icons-png/attach.png new file mode 100644 index 0000000..409304c Binary files /dev/null and b/app/src/assets/icons-png/attach.png differ diff --git a/app/src/assets/icons-png/avatar-c0.png b/app/src/assets/icons-png/avatar-c0.png new file mode 100644 index 0000000..9469a56 Binary files /dev/null and b/app/src/assets/icons-png/avatar-c0.png differ diff --git a/app/src/assets/icons-png/avatar-c1.png b/app/src/assets/icons-png/avatar-c1.png new file mode 100644 index 0000000..ff86081 Binary files /dev/null and b/app/src/assets/icons-png/avatar-c1.png differ diff --git a/app/src/assets/icons-png/avatar-c2.png b/app/src/assets/icons-png/avatar-c2.png new file mode 100644 index 0000000..37e948f Binary files /dev/null and b/app/src/assets/icons-png/avatar-c2.png differ diff --git a/app/src/assets/icons-png/avatar-c3.png b/app/src/assets/icons-png/avatar-c3.png new file mode 100644 index 0000000..d930cf9 Binary files /dev/null and b/app/src/assets/icons-png/avatar-c3.png differ diff --git a/app/src/assets/icons-png/avatar-c4.png b/app/src/assets/icons-png/avatar-c4.png new file mode 100644 index 0000000..397ac0b Binary files /dev/null and b/app/src/assets/icons-png/avatar-c4.png differ diff --git a/app/src/assets/icons-png/avatar-circle.png b/app/src/assets/icons-png/avatar-circle.png new file mode 100644 index 0000000..58117e2 Binary files /dev/null and b/app/src/assets/icons-png/avatar-circle.png differ diff --git a/app/src/assets/icons-png/bell-purple.png b/app/src/assets/icons-png/bell-purple.png new file mode 100644 index 0000000..3d6740a Binary files /dev/null and b/app/src/assets/icons-png/bell-purple.png differ diff --git a/app/src/assets/icons-png/bell.png b/app/src/assets/icons-png/bell.png new file mode 100644 index 0000000..19e798b Binary files /dev/null and b/app/src/assets/icons-png/bell.png differ diff --git a/app/src/assets/icons-png/camera.png b/app/src/assets/icons-png/camera.png new file mode 100644 index 0000000..3cfdc11 Binary files /dev/null and b/app/src/assets/icons-png/camera.png differ diff --git a/app/src/assets/icons-png/check.png b/app/src/assets/icons-png/check.png new file mode 100644 index 0000000..35bcfec Binary files /dev/null and b/app/src/assets/icons-png/check.png differ diff --git a/app/src/assets/icons-png/chevron-right.png b/app/src/assets/icons-png/chevron-right.png new file mode 100644 index 0000000..52e4a12 Binary files /dev/null and b/app/src/assets/icons-png/chevron-right.png differ diff --git a/app/src/assets/icons-png/clock.png b/app/src/assets/icons-png/clock.png new file mode 100644 index 0000000..5bf98dc Binary files /dev/null and b/app/src/assets/icons-png/clock.png differ diff --git a/app/src/assets/icons-png/close.png b/app/src/assets/icons-png/close.png new file mode 100644 index 0000000..b1432ba Binary files /dev/null and b/app/src/assets/icons-png/close.png differ diff --git a/app/src/assets/icons-png/cloud.png b/app/src/assets/icons-png/cloud.png new file mode 100644 index 0000000..608931a Binary files /dev/null and b/app/src/assets/icons-png/cloud.png differ diff --git a/app/src/assets/icons-png/compose.png b/app/src/assets/icons-png/compose.png new file mode 100644 index 0000000..2a55ef4 Binary files /dev/null and b/app/src/assets/icons-png/compose.png differ diff --git a/app/src/assets/icons-png/copy.png b/app/src/assets/icons-png/copy.png new file mode 100644 index 0000000..fe4d4a4 Binary files /dev/null and b/app/src/assets/icons-png/copy.png differ diff --git a/app/src/assets/icons-png/dislike.png b/app/src/assets/icons-png/dislike.png new file mode 100644 index 0000000..a061800 Binary files /dev/null and b/app/src/assets/icons-png/dislike.png differ diff --git a/app/src/assets/icons-png/gear.png b/app/src/assets/icons-png/gear.png new file mode 100644 index 0000000..7476963 Binary files /dev/null and b/app/src/assets/icons-png/gear.png differ diff --git a/app/src/assets/icons-png/image.png b/app/src/assets/icons-png/image.png new file mode 100644 index 0000000..d85c500 Binary files /dev/null and b/app/src/assets/icons-png/image.png differ diff --git a/app/src/assets/icons-png/layers.png b/app/src/assets/icons-png/layers.png new file mode 100644 index 0000000..2ac9816 Binary files /dev/null and b/app/src/assets/icons-png/layers.png differ diff --git a/app/src/assets/icons-png/like.png b/app/src/assets/icons-png/like.png new file mode 100644 index 0000000..caace33 Binary files /dev/null and b/app/src/assets/icons-png/like.png differ diff --git a/app/src/assets/icons-png/map.png b/app/src/assets/icons-png/map.png new file mode 100644 index 0000000..feb7ed4 Binary files /dev/null and b/app/src/assets/icons-png/map.png differ diff --git a/app/src/assets/icons-png/memory.png b/app/src/assets/icons-png/memory.png new file mode 100644 index 0000000..875f42b Binary files /dev/null and b/app/src/assets/icons-png/memory.png differ diff --git a/app/src/assets/icons-png/menu.png b/app/src/assets/icons-png/menu.png new file mode 100644 index 0000000..14010c8 Binary files /dev/null and b/app/src/assets/icons-png/menu.png differ diff --git a/app/src/assets/icons-png/message-circle.png b/app/src/assets/icons-png/message-circle.png new file mode 100644 index 0000000..9fb72a0 Binary files /dev/null and b/app/src/assets/icons-png/message-circle.png differ diff --git a/app/src/assets/icons-png/model.png b/app/src/assets/icons-png/model.png new file mode 100644 index 0000000..cbbfb76 Binary files /dev/null and b/app/src/assets/icons-png/model.png differ diff --git a/app/src/assets/icons-png/more.png b/app/src/assets/icons-png/more.png new file mode 100644 index 0000000..f054686 Binary files /dev/null and b/app/src/assets/icons-png/more.png differ diff --git a/app/src/assets/icons-png/person.png b/app/src/assets/icons-png/person.png new file mode 100644 index 0000000..18c8dc8 Binary files /dev/null and b/app/src/assets/icons-png/person.png differ diff --git a/app/src/assets/icons-png/phone.png b/app/src/assets/icons-png/phone.png new file mode 100644 index 0000000..948fa87 Binary files /dev/null and b/app/src/assets/icons-png/phone.png differ diff --git a/app/src/assets/icons-png/plus-circle-blue.png b/app/src/assets/icons-png/plus-circle-blue.png new file mode 100644 index 0000000..7808be3 Binary files /dev/null and b/app/src/assets/icons-png/plus-circle-blue.png differ diff --git a/app/src/assets/icons-png/plus.png b/app/src/assets/icons-png/plus.png new file mode 100644 index 0000000..abd056d Binary files /dev/null and b/app/src/assets/icons-png/plus.png differ diff --git a/app/src/assets/icons-png/refresh.png b/app/src/assets/icons-png/refresh.png new file mode 100644 index 0000000..6be2f2a Binary files /dev/null and b/app/src/assets/icons-png/refresh.png differ diff --git a/app/src/assets/icons-png/scan.png b/app/src/assets/icons-png/scan.png new file mode 100644 index 0000000..3a388d7 Binary files /dev/null and b/app/src/assets/icons-png/scan.png differ diff --git a/app/src/assets/icons-png/search.png b/app/src/assets/icons-png/search.png new file mode 100644 index 0000000..93a4639 Binary files /dev/null and b/app/src/assets/icons-png/search.png differ diff --git a/app/src/assets/icons-png/send.png b/app/src/assets/icons-png/send.png new file mode 100644 index 0000000..b1432ba Binary files /dev/null and b/app/src/assets/icons-png/send.png differ diff --git a/app/src/assets/icons-png/share.png b/app/src/assets/icons-png/share.png new file mode 100644 index 0000000..b3fba1a Binary files /dev/null and b/app/src/assets/icons-png/share.png differ diff --git a/app/src/assets/icons-png/sparkle-square.png b/app/src/assets/icons-png/sparkle-square.png new file mode 100644 index 0000000..76a0c7e Binary files /dev/null and b/app/src/assets/icons-png/sparkle-square.png differ diff --git a/app/src/assets/icons-png/sparkle.png b/app/src/assets/icons-png/sparkle.png new file mode 100644 index 0000000..42f8ab2 Binary files /dev/null and b/app/src/assets/icons-png/sparkle.png differ diff --git a/app/src/assets/icons-png/speaker-purple.png b/app/src/assets/icons-png/speaker-purple.png new file mode 100644 index 0000000..784f393 Binary files /dev/null and b/app/src/assets/icons-png/speaker-purple.png differ diff --git a/app/src/assets/icons-png/speaker.png b/app/src/assets/icons-png/speaker.png new file mode 100644 index 0000000..b8c14ed Binary files /dev/null and b/app/src/assets/icons-png/speaker.png differ diff --git a/app/src/assets/icons-png/text-size.png b/app/src/assets/icons-png/text-size.png new file mode 100644 index 0000000..367eb28 Binary files /dev/null and b/app/src/assets/icons-png/text-size.png differ diff --git a/app/src/assets/icons-png/upgrade.png b/app/src/assets/icons-png/upgrade.png new file mode 100644 index 0000000..9e0a21b Binary files /dev/null and b/app/src/assets/icons-png/upgrade.png differ diff --git a/app/src/assets/icons-png/voice.png b/app/src/assets/icons-png/voice.png new file mode 100644 index 0000000..b079117 Binary files /dev/null and b/app/src/assets/icons-png/voice.png differ diff --git a/app/src/assets/icons/attach.svg b/app/src/assets/icons/attach.svg new file mode 100644 index 0000000..59ac5ee --- /dev/null +++ b/app/src/assets/icons/attach.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/avatar-c0.svg b/app/src/assets/icons/avatar-c0.svg new file mode 100644 index 0000000..30b9322 --- /dev/null +++ b/app/src/assets/icons/avatar-c0.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/avatar-c1.svg b/app/src/assets/icons/avatar-c1.svg new file mode 100644 index 0000000..48a07a2 --- /dev/null +++ b/app/src/assets/icons/avatar-c1.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/avatar-c2.svg b/app/src/assets/icons/avatar-c2.svg new file mode 100644 index 0000000..8b9ad79 --- /dev/null +++ b/app/src/assets/icons/avatar-c2.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/avatar-c3.svg b/app/src/assets/icons/avatar-c3.svg new file mode 100644 index 0000000..e62611b --- /dev/null +++ b/app/src/assets/icons/avatar-c3.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/avatar-c4.svg b/app/src/assets/icons/avatar-c4.svg new file mode 100644 index 0000000..6f88507 --- /dev/null +++ b/app/src/assets/icons/avatar-c4.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/avatar-circle.svg b/app/src/assets/icons/avatar-circle.svg new file mode 100644 index 0000000..af14735 --- /dev/null +++ b/app/src/assets/icons/avatar-circle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/bell-purple.svg b/app/src/assets/icons/bell-purple.svg new file mode 100644 index 0000000..b9643eb --- /dev/null +++ b/app/src/assets/icons/bell-purple.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/bell.svg b/app/src/assets/icons/bell.svg new file mode 100644 index 0000000..bb0cd3e --- /dev/null +++ b/app/src/assets/icons/bell.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/camera.svg b/app/src/assets/icons/camera.svg new file mode 100644 index 0000000..3d8ae90 --- /dev/null +++ b/app/src/assets/icons/camera.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/check.svg b/app/src/assets/icons/check.svg new file mode 100644 index 0000000..3353211 --- /dev/null +++ b/app/src/assets/icons/check.svg @@ -0,0 +1 @@ + diff --git a/app/src/assets/icons/chevron-right.svg b/app/src/assets/icons/chevron-right.svg new file mode 100644 index 0000000..f5d3b14 --- /dev/null +++ b/app/src/assets/icons/chevron-right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/clock.svg b/app/src/assets/icons/clock.svg new file mode 100644 index 0000000..d2ac307 --- /dev/null +++ b/app/src/assets/icons/clock.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/close.svg b/app/src/assets/icons/close.svg new file mode 100644 index 0000000..ac393cd --- /dev/null +++ b/app/src/assets/icons/close.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/cloud.svg b/app/src/assets/icons/cloud.svg new file mode 100644 index 0000000..09ff60b --- /dev/null +++ b/app/src/assets/icons/cloud.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/compose.svg b/app/src/assets/icons/compose.svg new file mode 100644 index 0000000..d3a739a --- /dev/null +++ b/app/src/assets/icons/compose.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/copy.svg b/app/src/assets/icons/copy.svg new file mode 100644 index 0000000..bdfe29e --- /dev/null +++ b/app/src/assets/icons/copy.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/dislike.svg b/app/src/assets/icons/dislike.svg new file mode 100644 index 0000000..ce99bdc --- /dev/null +++ b/app/src/assets/icons/dislike.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/gear.svg b/app/src/assets/icons/gear.svg new file mode 100644 index 0000000..2b7b3db --- /dev/null +++ b/app/src/assets/icons/gear.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/image.svg b/app/src/assets/icons/image.svg new file mode 100644 index 0000000..1b50dc6 --- /dev/null +++ b/app/src/assets/icons/image.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/layers.svg b/app/src/assets/icons/layers.svg new file mode 100644 index 0000000..97d74a9 --- /dev/null +++ b/app/src/assets/icons/layers.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/like.svg b/app/src/assets/icons/like.svg new file mode 100644 index 0000000..37887e1 --- /dev/null +++ b/app/src/assets/icons/like.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/map.svg b/app/src/assets/icons/map.svg new file mode 100644 index 0000000..1c3dcee --- /dev/null +++ b/app/src/assets/icons/map.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/memory.svg b/app/src/assets/icons/memory.svg new file mode 100644 index 0000000..f5e4e42 --- /dev/null +++ b/app/src/assets/icons/memory.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/menu.svg b/app/src/assets/icons/menu.svg new file mode 100644 index 0000000..0ad9496 --- /dev/null +++ b/app/src/assets/icons/menu.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/message-circle.svg b/app/src/assets/icons/message-circle.svg new file mode 100644 index 0000000..f0ad45e --- /dev/null +++ b/app/src/assets/icons/message-circle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/model.svg b/app/src/assets/icons/model.svg new file mode 100644 index 0000000..6bc2007 --- /dev/null +++ b/app/src/assets/icons/model.svg @@ -0,0 +1 @@ + diff --git a/app/src/assets/icons/more.svg b/app/src/assets/icons/more.svg new file mode 100644 index 0000000..8103fb1 --- /dev/null +++ b/app/src/assets/icons/more.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/person.svg b/app/src/assets/icons/person.svg new file mode 100644 index 0000000..f160505 --- /dev/null +++ b/app/src/assets/icons/person.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/phone.svg b/app/src/assets/icons/phone.svg new file mode 100644 index 0000000..83d03e5 --- /dev/null +++ b/app/src/assets/icons/phone.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/plus-circle-blue.svg b/app/src/assets/icons/plus-circle-blue.svg new file mode 100644 index 0000000..f7b3ef4 --- /dev/null +++ b/app/src/assets/icons/plus-circle-blue.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/plus.svg b/app/src/assets/icons/plus.svg new file mode 100644 index 0000000..1b8aed7 --- /dev/null +++ b/app/src/assets/icons/plus.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/refresh.svg b/app/src/assets/icons/refresh.svg new file mode 100644 index 0000000..6073e2d --- /dev/null +++ b/app/src/assets/icons/refresh.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/scan.svg b/app/src/assets/icons/scan.svg new file mode 100644 index 0000000..77db8bf --- /dev/null +++ b/app/src/assets/icons/scan.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/search.svg b/app/src/assets/icons/search.svg new file mode 100644 index 0000000..43b0151 --- /dev/null +++ b/app/src/assets/icons/search.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/send.svg b/app/src/assets/icons/send.svg new file mode 100644 index 0000000..966be1d --- /dev/null +++ b/app/src/assets/icons/send.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/share.svg b/app/src/assets/icons/share.svg new file mode 100644 index 0000000..6433b74 --- /dev/null +++ b/app/src/assets/icons/share.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/sparkle-square.svg b/app/src/assets/icons/sparkle-square.svg new file mode 100644 index 0000000..36f32b8 --- /dev/null +++ b/app/src/assets/icons/sparkle-square.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/sparkle.svg b/app/src/assets/icons/sparkle.svg new file mode 100644 index 0000000..47b7f70 --- /dev/null +++ b/app/src/assets/icons/sparkle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/speaker-purple.svg b/app/src/assets/icons/speaker-purple.svg new file mode 100644 index 0000000..a3f98b9 --- /dev/null +++ b/app/src/assets/icons/speaker-purple.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/speaker.svg b/app/src/assets/icons/speaker.svg new file mode 100644 index 0000000..9e6bdbf --- /dev/null +++ b/app/src/assets/icons/speaker.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/text-size.svg b/app/src/assets/icons/text-size.svg new file mode 100644 index 0000000..7153276 --- /dev/null +++ b/app/src/assets/icons/text-size.svg @@ -0,0 +1 @@ +AA \ No newline at end of file diff --git a/app/src/assets/icons/upgrade.svg b/app/src/assets/icons/upgrade.svg new file mode 100644 index 0000000..b5b1b64 --- /dev/null +++ b/app/src/assets/icons/upgrade.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/assets/icons/voice.svg b/app/src/assets/icons/voice.svg new file mode 100644 index 0000000..f813d35 --- /dev/null +++ b/app/src/assets/icons/voice.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app/src/index.tsx b/app/src/index.tsx new file mode 100644 index 0000000..3c072aa --- /dev/null +++ b/app/src/index.tsx @@ -0,0 +1,9 @@ +import { root } from '@lynx-js/react'; + +import { App } from './App.js'; + +root.render(); + +if (import.meta.webpackHot) { + import.meta.webpackHot.accept(); +} diff --git a/app/src/lynx-env.d.ts b/app/src/lynx-env.d.ts new file mode 100644 index 0000000..f4e9878 --- /dev/null +++ b/app/src/lynx-env.d.ts @@ -0,0 +1,24 @@ +declare module '@lynx-js/types' { + interface GlobalProps { + /** + * Define your global properties in this interface. + * These types will be accessible through `lynx.__globalProps`. + */ + /** 宿主页可以通过 `?page=` 指定首屏(chat / drawer / profile / settings / skills / agents),方便截图与演示 */ + initialPage?: string; + /** Android 原生壳通过 updateGlobalProps 传进来的内核地址 */ + apiBase?: string; + } +} + +declare module '*.svg' { + const url: string; + export default url; +} + +declare module '*.png' { + const url: string; + export default url; +} + +export {}; diff --git a/app/src/lynx-input.ts b/app/src/lynx-input.ts new file mode 100644 index 0000000..26356d9 --- /dev/null +++ b/app/src/lynx-input.ts @@ -0,0 +1,15 @@ +/** + * Lynx 的 /