豆包复刻:原生安卓(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。
This commit is contained in:
l
2026-10-09 14:09:36 +08:00
commit f056bcf45a
308 changed files with 46874 additions and 0 deletions

View File

@@ -0,0 +1,130 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose")
id("com.chaquo.python")
}
android {
namespace = "com.doubao.lynxclone"
compileSdk = 35
defaultConfig {
applicationId = "com.doubao.lynxclone"
minSdk = 24
/**
* ★ 为什么锁死在 28:
* Android 10(API 29) 起有 W^X 限制 —— targetSdk >= 29 的应用**不能执行自己数据目录里的二进制**。
* Termux(targetSdk=28)正是靠这个豁免,才能把 bash/python/node 解压到
* /data/data/<pkg>/files/usr 再 exec。我们要把 Termux 原生内置进来,就必须跟它一样。
* 代价:上不了应用商店;部分新系统行为按旧版走(对我们这种本地工具无所谓)。
*/
targetSdk = 28
versionCode = 3
versionName = "0.3.0"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
abiFilters += listOf("arm64-v8a", "x86_64")
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
packaging {
jniLibs {
/**
* ★ 必须为 true(等价于 manifest 里的 extractNativeLibs="true")。
* AGP 8.5+ 默认 useLegacyPackaging=false,此时原生库**不会解压到文件系统**,
* applicationInfo.nativeLibraryDir 里可能是个空目录 ——
* 而 Termux 的 bootstrap 正是以 .so 的形式放在那里被读出来的(Termux 自己也开这个开关)。
* 实测不开的话解压出来是 0 个文件。
*/
useLegacyPackaging = true
pickFirsts += listOf(
"lib/*/libc++_shared.so",
"**/libnapi.so",
"**/libnapi_adapter.so",
"META-INF/*.kotlin_module",
)
}
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
// bootstrap 是数据不是代码,压缩它没意义还拖慢解压
androidResources {
noCompress += listOf("bundle")
}
}
chaquopy {
defaultConfig {
version = "3.13"
buildPython(
providers.environmentVariable("DOUBAO_PYTHON313").getOrElse("C:\\Python313\\python.exe"),
)
/**
* ★ 这里刻意**不装任何第三方包**。
*
* 原因:Chaquopy 每次构建都要去 PyPI 拉包,网络一抖整个 APK 就构建不出来
* (实测 "Could not find a version that satisfies the requirement requests")。
* 而内核只用标准库(urllib/http.server/json),根本不需要 requests。
*
* 用户确实要 requests/httpx/numpy 这些时,走内置 Termux 更合适 —— 真 pip、真轮子:
* 在终端里执行 pkg install python && pip install requests
* 所以这里保持零依赖,换来"离线也能构建"。
*/
// pip { install("requests") }
}
sourceSets {
getByName("main") {
// Python 内核 + 内置工具(构建脚本会把 tools/*.py 也拷进来)
srcDir("../kernel")
}
}
}
dependencies {
// 原生 UI 用 Compose
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.material:material-icons-extended")
implementation("androidx.activity:activity-compose:1.9.3")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
// viewModel() 和 viewModelScope 都在这两个里
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
implementation("androidx.core:core-ktx:1.13.1")
// 跟本地内核通信 + 处理系统栏/输入法内边距
implementation("com.squareup.okhttp3:okhttp:4.12.0")
// 注意:Termux 的终端模拟器**没有发布到任何 Maven 仓库**(Maven Central 没有、JitPack 也不通),
// 所以它的源码是直接 vendor 进工程的:android/app/src/main/java/com/termux/**
// (Apache-2.0,见 assets/TERMUX_LICENSE.txt)
}

4
android/app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,4 @@
# Lynx 依赖较多反射,保守起见先不混淆
-keep class com.lynx.** { *; }
-keep class org.lynxsdk.** { *; }
-dontwarn com.lynx.**

View File

@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 内核默认跑在手机本地(APK 内嵌 CPython),远程模式才需要联网;两种情况都要 INTERNET -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- device 工具的定位能力(用户拒绝也不影响其它功能) -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 把命令交给 Termux 执行(对方需要在 termux.properties 里开 allow-external-apps) -->
<uses-permission android:name="com.termux.permission.RUN_COMMAND" />
<!-- 语音输入 / 通话要录音。朗读不需要(播音频不要权限) -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- 通话时想在被叫/接听场景抢音频焦点用得上;多数机型不加也行 -->
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<!-- Android 11+ 用于判断 Termux 是否安装 -->
<queries>
<package android:name="com.termux" />
<!-- 系统语音识别服务:不声明的话 Android 11+ 查不到可用引擎 -->
<intent>
<action android:name="android.speech.RecognitionService" />
</intent>
<!-- 系统 TTS 引擎:同上,用来判断"这台机器到底有没有 TTS" -->
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
</queries>
<!-- 加速度计/陀螺仪等传感器不需要权限 -->
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="false" />
<uses-feature android:name="android.hardware.sensor.gyroscope" android:required="false" />
<uses-feature android:name="android.hardware.location" android:required="false" />
<application
android:name=".DoubaoApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="false"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden|uiMode"
android:exported="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,22 @@
本 App 内置了 Termux 的组件,均来自开源项目 https://github.com/termux/termux-app (Apache License 2.0)。
具体包含:
1. 终端模拟器源码
- android/app/src/main/java/com/termux/terminal/**
- android/app/src/main/java/com/termux/view/**
(来自 termux-app 的 terminal-emulator 与 terminal-view 模块,v0.118.3)
2. 原生库
- android/app/src/main/jniLibs/<abi>/libtermux.so
pty 支持(forkpty 等 JNI 实现),TerminalSession 依赖它
- android/app/src/main/jniLibs/<abi>/libtermux-bootstrap.so
根文件系统(其实是个 zip,含 bash / apt / pkg 等 250+ 个可执行文件与 1146 条符号链接)
3. 安装逻辑
- android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt
(按 Termux 的 TermuxInstaller.java 移植:解压 + 用 sh 建符号链接)
Apache License 2.0 全文见 https://www.apache.org/licenses/LICENSE-2.0
Copyright (c) 2013-2024 Termux contributors

View File

@@ -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))
}
}
}

View File

@@ -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
}

View File

@@ -0,0 +1,121 @@
package com.doubao.lynxclone
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.lifecycle.lifecycleScope
import com.doubao.lynxclone.data.KernelClient
import com.doubao.lynxclone.termux.TermuxInstaller
import com.doubao.lynxclone.ui.AppRoot
import com.doubao.lynxclone.ui.theme.DoubaoTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* 原生 Compose 宿主。
*
* 启动顺序(都很关键):
* 1. 起本地 Python 内核(Chaquopy,跑在进程里,监听 127.0.0.1)
* 2. 后台解压内置 Termux 环境(95MB,首次十几秒;之后秒过)
* 3. 进主界面 —— 前两步都不阻塞 UI,装到哪一步界面上都看得见
*/
class MainActivity : ComponentActivity() {
private val client = KernelClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
var kernelUrl by mutableStateOf("")
var status by mutableStateOf("正在启动本地内核…")
var termuxReady by mutableStateOf(false)
var termuxStatus by mutableStateOf("")
setContent {
DoubaoTheme {
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
if (kernelUrl.isBlank()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(status, style = MaterialTheme.typography.bodyLarge)
}
} else {
AppRoot(
client = client,
termuxReady = termuxReady,
termuxStatus = termuxStatus,
onInstallTermux = { installTermux { msg -> termuxStatus = msg } },
)
}
}
}
}
// ① 内核
lifecycleScope.launch {
val port = withContext(Dispatchers.IO) {
runCatching { LocalKernel.ensureStarted(this@MainActivity) }.getOrNull()
}
if (port != null && port > 0) {
client.baseUrl = "http://127.0.0.1:$port"
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
// 否则内核里的 device 工具会返回"没有安卓原生桥"
withContext(Dispatchers.IO) {
runCatching { NativeBridge.register(NativeBridge(this@MainActivity)) }
}
withContext(Dispatchers.IO) { awaitHealthy(port) }
kernelUrl = client.baseUrl
} else {
status = "本地内核启动失败:${LocalKernel.lastFailure() ?: "未知原因"}"
}
}
// ② Termux 环境(不阻塞界面)
lifecycleScope.launch {
val ready = withContext(Dispatchers.IO) {
TermuxInstaller.install(this@MainActivity) { msg -> termuxStatus = msg }
}
termuxReady = ready
termuxStatus = if (ready) "Termux 环境就绪" else "Termux 环境未就绪"
}
}
private fun installTermux(onProgress: (String) -> Unit) {
lifecycleScope.launch {
val ready = withContext(Dispatchers.IO) {
TermuxInstaller.install(this@MainActivity, onProgress)
}
onProgress(if (ready) "已就绪" else "安装失败")
}
}
private fun awaitHealthy(port: Int): Boolean {
val deadline = System.currentTimeMillis() + 20_000
while (System.currentTimeMillis() < deadline) {
try {
val conn = java.net.URL("http://127.0.0.1:$port/api/health").openConnection() as java.net.HttpURLConnection
conn.connectTimeout = 1200
conn.readTimeout = 1200
val code = conn.responseCode
conn.disconnect()
if (code == 200) return true
} catch (_: Throwable) {
// 还没起来,继续等
}
Thread.sleep(300)
}
return false
}
}

View File

@@ -0,0 +1,371 @@
package com.doubao.lynxclone
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Location
import android.location.LocationManager
import android.net.Uri
import android.os.BatteryManager
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.provider.OpenableColumns
import com.chaquo.python.Python
import org.json.JSONArray
import org.json.JSONObject
import com.doubao.lynxclone.termux.TermuxShell
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* 暴露给 Python 内核的原生能力。
*
* Chaquopy 允许 Python 直接调这个类的方法(`from java import jclass` 那套),
* 所以内核里的 `device` 工具、剪贴板钩子、选文件钩子都落到这里。
*
* 线程约定:device() 可能阻塞几秒(采传感器、等定位),
* 它只会在内核的 HTTP 工作线程上被调用,**不会**卡住 UI 线程。
*/
class NativeBridge(private val activity: Activity) {
// ------------------------------------------------------------------ 设备能力
/** 统一入口:收一个 JSON 字符串,回一个 JSON 字符串 */
@Suppress("unused")
fun device(payloadJson: String): String {
val req = try {
JSONObject(payloadJson)
} catch (e: Exception) {
JSONObject()
}
val action = req.optString("action", "info")
return try {
when (action) {
"info" -> deviceInfo()
"battery" -> batteryInfo()
"location" -> locationInfo()
"sensors" -> sensorList()
"sensor" -> sensorSample(req.optString("sensor"), req.optDouble("duration", 1.5))
"clipboard_get" -> JSONObject().put("text", readClipboard())
"clipboard_set" -> {
setClipboard(req.optString("text"))
JSONObject().put("ok", true)
}
// 内置 Termux:完整 Linux 用户态(真 bash / 真 pkg / 真子进程)
"termux_available" -> JSONObject().put("installed", TermuxShell.isReady(activity))
"termux_run" -> TermuxShell.run(
activity,
req.optString("command"),
req.optString("cwd"),
(req.optDouble("timeout", 60.0) * 1000).toLong(),
)
else -> JSONObject().put("error", "未知 action:$action")
}
} catch (t: Throwable) {
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
}.toString()
}
private fun deviceInfo(): JSONObject {
val stat = StatFs(Environment.getDataDirectory().path)
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
val totalGb = stat.totalBytes / 1024.0 / 1024.0 / 1024.0
return JSONObject()
.put("platform", "Android")
.put("model", Build.MODEL)
.put("manufacturer", Build.MANUFACTURER)
.put("brand", Build.BRAND)
.put("device", Build.DEVICE)
.put("android", Build.VERSION.RELEASE)
.put("sdk", Build.VERSION.SDK_INT)
.put("abis", JSONArray(Build.SUPPORTED_ABIS.toList()))
.put("storage_free_gb", String.format("%.1f", freeGb))
.put("storage_total_gb", String.format("%.1f", totalGb))
.put("screen", screenInfo())
.put("battery", batteryInfo())
}
private fun screenInfo(): String {
val metrics = activity.resources.displayMetrics
return "${metrics.widthPixels}x${metrics.heightPixels} @${metrics.density}x"
}
private fun batteryInfo(): JSONObject {
val bm = activity.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager
return JSONObject()
.put("level_percent", bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: -1)
.put("charging", bm?.isCharging ?: false)
}
/** 定位:先拿最后已知位置,拿不到就等一次单次更新(最多 8 秒) */
private fun locationInfo(): JSONObject {
val lm = activity.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
?: return JSONObject().put("error", "没有 LocationManager")
val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
var best: Location? = null
for (p in providers) {
try {
if (!lm.isProviderEnabled(p)) continue
val loc = lm.getLastKnownLocation(p) ?: continue
if (best == null || loc.time > best!!.time) best = loc
} catch (t: SecurityException) {
return JSONObject().put("error", "缺少定位权限(ACCESS_FINE_LOCATION)")
} catch (_: Throwable) {
// 某些机型会抛 IllegalArgumentException,忽略继续
}
}
if (best == null) {
val latch = CountDownLatch(1)
var fresh: Location? = null
val listener = object : android.location.LocationListener {
override fun onLocationChanged(location: Location) {
fresh = location
latch.countDown()
}
// 老 API 要求实现,留着空实现
override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
}
try {
activity.runOnUiThread {
try {
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, listener)
} catch (_: Throwable) {
latch.countDown()
}
}
latch.await(8, TimeUnit.SECONDS)
} catch (_: Throwable) {
// 忽略
} finally {
try {
lm.removeUpdates(listener)
} catch (_: Throwable) {
// 忽略
}
}
best = fresh
}
if (best == null) {
return JSONObject()
.put("available", false)
.put("hint", "没拿到定位:确认已开定位开关、已授予权限、或在室内 GPS 信号差时稍后再试")
}
return JSONObject()
.put("available", true)
.put("latitude", best!!.latitude)
.put("longitude", best!!.longitude)
.put("accuracy_m", best!!.accuracy.toDouble())
.put("provider", best!!.provider)
.put("age_seconds", (System.currentTimeMillis() - best!!.time) / 1000.0)
}
private val keywordToType = mapOf(
"accelerometer" to Sensor.TYPE_ACCELEROMETER,
"gyroscope" to Sensor.TYPE_GYROSCOPE,
"magnetic" to Sensor.TYPE_MAGNETIC_FIELD,
"light" to Sensor.TYPE_LIGHT,
"pressure" to Sensor.TYPE_PRESSURE,
"proximity" to Sensor.TYPE_PROXIMITY,
"gravity" to Sensor.TYPE_GRAVITY,
"linear_acceleration" to Sensor.TYPE_LINEAR_ACCELERATION,
"rotation_vector" to Sensor.TYPE_ROTATION_VECTOR,
"step_counter" to Sensor.TYPE_STEP_COUNTER,
"humidity" to Sensor.TYPE_RELATIVE_HUMIDITY,
"temperature" to Sensor.TYPE_AMBIENT_TEMPERATURE,
"game_rotation_vector" to Sensor.TYPE_GAME_ROTATION_VECTOR,
)
private fun sensorManager(): SensorManager? =
activity.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
private fun sensorList(): JSONObject {
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
val arr = JSONArray()
for (s in sm.getSensorList(Sensor.TYPE_ALL)) {
val key = keywordToType.entries.firstOrNull { it.value == s.type }?.key
arr.put(
JSONObject()
.put("key", key ?: "type_${s.type}")
.put("name", s.name)
.put("vendor", s.vendor)
.put("type", s.type)
.put("power_ma", s.power.toDouble()),
)
}
return JSONObject().put("count", arr.length()).put("sensors", arr)
}
/** 采样:注册监听 duration 秒,返回样本序列与统计 */
private fun sensorSample(key: String, duration: Double): JSONObject {
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
val name = key.ifBlank { "accelerometer" }
val type = keywordToType[name] ?: return JSONObject()
.put("error", "不认识的传感器:$name(可用:${keywordToType.keys.joinToString(", ")})")
val sensor = sm.getDefaultSensor(type)
?: return JSONObject().put("error", "这台设备没有 $name 传感器")
val seconds = duration.coerceIn(0.2, 10.0)
val samples = mutableListOf<FloatArray>()
val latch = CountDownLatch(1)
val listener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
if (samples.size < 500) samples.add(event.values.copyOf())
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
}
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME)
try {
// 用 latch 等不到就超时,靠 await 的返回值判断即可
latch.await((seconds * 1000).toLong(), TimeUnit.MILLISECONDS)
} finally {
sm.unregisterListener(listener)
}
if (samples.isEmpty()) return JSONObject().put("error", "$name 在采样期内没出数据")
val dims = samples.first().size
val stats = JSONArray()
for (d in 0 until dims) {
val values = samples.map { it[d].toDouble() }
stats.put(
JSONObject()
.put("avg", values.average())
.put("min", values.min())
.put("max", values.max())
.put("last", values.last()),
)
}
val last = JSONArray()
samples.last().forEach { last.put(it.toDouble()) }
return JSONObject()
.put("sensor", name)
.put("unit", unitOf(name))
.put("sample_count", samples.size)
.put("seconds", seconds)
.put("axes", axisNames(dims))
.put("last", last)
.put("stats", stats)
}
private fun axisNames(dims: Int): JSONArray {
val names = listOf("x", "y", "z", "w")
val arr = JSONArray()
for (i in 0 until dims) arr.put(names.getOrElse(i) { "v$i" })
return arr
}
private fun unitOf(name: String): String = when (name) {
"accelerometer", "gravity", "linear_acceleration" -> "m/s^2"
"gyroscope" -> "rad/s"
"magnetic" -> "uT"
"light" -> "lx"
"pressure" -> "hPa"
"proximity" -> "cm"
"humidity" -> "%"
"temperature" -> "°C"
else -> ""
}
// ------------------------------------------------------------------ 剪贴板 / 选文件
@Suppress("unused")
fun setClipboard(text: String) {
activity.runOnUiThread {
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cm.setPrimaryClip(ClipData.newPlainText("doubao", text))
}
}
private fun readClipboard(): String {
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = cm.primaryClip ?: return ""
if (clip.itemCount == 0) return ""
return clip.getItemAt(0).coerceToText(activity).toString()
}
/** 内核请求"用户选个文件"时调用;把选中的文件复制到 App 私有目录再返回路径 */
@Volatile
private var pickLatch: CountDownLatch? = null
@Volatile
private var pickedUris: List<Uri> = emptyList()
@Suppress("unused")
fun pickFile(): Array<String> {
val latch = CountDownLatch(1)
pickLatch = latch
pickedUris = emptyList()
activity.runOnUiThread {
try {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
}
activity.startActivityForResult(intent, REQ_PICK)
} catch (t: Throwable) {
latch.countDown()
}
}
latch.await(PICK_TIMEOUT_S, TimeUnit.SECONDS)
pickLatch = null
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
}
/** MainActivity 的 onActivityResult 转进来 */
fun onPicked(data: Intent?) {
val uris = mutableListOf<Uri>()
data?.clipData?.let { clip ->
for (i in 0 until clip.itemCount) uris.add(clip.getItemAt(i).uri)
}
data?.data?.let { uris.add(it) }
pickedUris = uris
pickLatch?.countDown()
}
private fun copyIntoCache(uri: Uri): String? = try {
val name = displayName(uri) ?: "upload_${System.currentTimeMillis()}"
val dir = File(activity.cacheDir, "picked").apply { mkdirs() }
val dest = File(dir, name)
activity.contentResolver.openInputStream(uri)?.use { input ->
dest.outputStream().use { output -> input.copyTo(output) }
}
dest.absolutePath
} catch (t: Throwable) {
null
}
private fun displayName(uri: Uri): String? = try {
activity.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
}
} catch (t: Throwable) {
null
}
/** 安卓上没有"打开文件夹",直接返回提示(设置页会显示不可用) */
@Suppress("unused")
fun reveal(path: String): String? = null
companion object {
const val REQ_PICK = 0x4D31
private const val PICK_TIMEOUT_S = 120L
/** 内核起来后把 bridge 注册给 Python */
fun register(bridge: NativeBridge) {
val entry = Python.getInstance().getModule("doubao_entry")
entry.callAttr("set_android_bridge", bridge)
}
}
}

View File

@@ -0,0 +1,457 @@
package com.doubao.lynxclone.speech
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.media.AudioTrack
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.util.Base64
import android.util.Log
import java.io.File
import java.util.Locale
import java.util.UUID
/**
* 朗读。
*
* 两条路走同一个入口:
* - 云端音色(火山 / OpenAI):内核把音频合成好,以 base64 回来,这里写临时文件用 MediaPlayer 播;
* - 系统引擎:直接用 TextToSpeech,不联网、不要 Key。
*
* 为什么云端音频要落盘再播而不是喂内存:
* MediaPlayer 的 setDataSource 只认路径 / FileDescriptor / AssetFileDescriptor,
* 内存里的字节要么落盘、要么自己写个 MediaDataSource —— 落盘简单可靠,
* 而且能立刻知道"这段音频到底是不是有效文件"(大小、时长)。
*/
class Speaker(private val context: Context) {
private var player: MediaPlayer? = null
private var tts: TextToSpeech? = null
private var ttsReady = false
/** TTS 初始化是异步的:没就绪前先攒着,就绪后自动开口 */
private val pending = ArrayDeque<String>()
/** 播完(或被停掉)回调一次,界面用它复位"正在朗读"的状态 */
var onFinished: (() -> Unit)? = null
/** 出错回调:把原因交给界面显示,别静默失败 */
var onError: (String) -> Unit = {}
private var tempFile: File? = null
val isPlaying: Boolean
get() = player?.isPlaying == true
// ---------------------------------------------------------------- 云端音频
/** 播一段云端合成的音频(base64) */
fun playBase64(audioBase64: String, mime: String) {
stop()
val bytes = try {
Base64.decode(audioBase64, Base64.DEFAULT)
} catch (e: IllegalArgumentException) {
onError("音频解码失败:${e.message}")
return
}
if (bytes.isEmpty()) {
onError("内核返回了空音频")
return
}
// 用 mime 猜后缀:MediaPlayer 对未知扩展名会比较挑
val ext = when {
mime.contains("wav") -> "wav"
mime.contains("ogg") -> "ogg"
mime.contains("mp4") || mime.contains("aac") -> "m4a"
else -> "mp3"
}
val file = File(context.cacheDir, "tts-${UUID.randomUUID()}.$ext")
try {
file.writeBytes(bytes)
} catch (e: Exception) {
onError("写临时音频失败:${e.message}")
return
}
tempFile = file
try {
player = MediaPlayer().apply {
setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANT)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build(),
)
setDataSource(file.absolutePath)
setOnCompletionListener { finish() }
setOnErrorListener { _, what, extra ->
onError("播放失败(what=$what extra=$extra)")
finish()
true
}
prepare()
start()
}
} catch (e: Exception) {
onError("播放失败:${e.message}")
finish()
}
}
// ---------------------------------------------------------------- 系统 TTS
/**
* 用系统 TTS 念。会按句切分后再排队 ——
* TextToSpeech.speak 单次有长度上限(约 4000 字符),长回复整段塞进去会被截断。
*/
fun speakSystem(text: String) {
val chunks = splitSentences(text)
if (chunks.isEmpty()) return
ensureTts()
if (!ttsReady) {
pending.addAll(chunks)
return
}
enqueue(chunks)
}
private fun ensureTts() {
if (tts != null) return
tts = TextToSpeech(context) { status ->
if (status == TextToSpeech.SUCCESS) {
ttsReady = true
tts?.language = Locale.SIMPLIFIED_CHINESE
// 没有这个监听,队列念完了我们不会知道,"正在朗读"的状态就会一直卡着
tts?.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(utteranceId: String?) {}
override fun onDone(utteranceId: String?) {
// 只有最后一句念完才算真的结束
if (utteranceId == LAST_ID) finish()
}
@Deprecated("基类要求实现", ReplaceWith(""))
override fun onError(utteranceId: String?) {
onError("系统朗读出错")
finish()
}
override fun onError(utteranceId: String?, errorCode: Int) {
onError("系统朗读出错(code=$errorCode)")
finish()
}
})
// 初始化是异步的,就绪后把之前攒下的补上
val queued = pending.toList()
pending.clear()
if (queued.isNotEmpty()) enqueue(queued)
} else {
onError("系统语音引擎初始化失败(这台机器可能没装 TTS 引擎)")
}
}
}
private fun enqueue(chunks: List<String>) {
chunks.forEachIndexed { index, chunk ->
val isLast = index == chunks.lastIndex
// 全部用 QUEUE_ADD 排队,靠 utteranceId 分辨"最后一句"来收尾
tts?.speak(chunk, TextToSpeech.QUEUE_ADD, Bundle(), if (isLast) LAST_ID else "part$index")
}
}
// ---------------------------------------------------------------- 公共
fun stop() {
try {
player?.let {
if (it.isPlaying) it.stop()
it.release()
}
} catch (_: Exception) {
// 释放失败无所谓,下面会把引用清掉
}
player = null
try {
tts?.stop()
} catch (_: Exception) {
// 同上
}
pending.clear()
cleanup()
}
fun release() {
stop()
tts?.shutdown()
tts = null
ttsReady = false
onFinished = null
}
private fun finish() {
cleanup()
onFinished?.invoke()
}
private fun cleanup() {
tempFile?.delete()
tempFile = null
}
private companion object {
const val LAST_ID = "__doubao_last__"
}
}
/**
* 录音 → WAV。
*
* 采样率固定 16000 / 单声道 / 16bit:
* - 这是 Whisper 等识别服务最常见的输入格式,不用服务端再转;
* - 16k 单声道 30 秒也就 1 MB 左右,走手机流量没压力。
*
* 为什么不直接用 MediaRecorder:它只会吐 m4a/aac,还要额外解码;
* AudioRecord 直接给 PCM,套个 44 字节 WAV 头就能发。
*/
class Recorder(private val context: Context) {
private var record: AudioRecord? = null
private var thread: Thread? = null
private val pcm = ArrayList<ByteArray>()
private var total = 0
private var recording = false
private var peakLevel = 0
/** 录音中的音量(0~100),界面拿它画波形 */
val level: Int get() = peakLevel
val isRecording: Boolean get() = recording
/** 开始录音。返回 false 表示麦克风不可用(权限或占用) */
fun start(): Boolean {
if (recording) return false
val rate = SAMPLE_RATE
val minBuf = AudioRecord.getMinBufferSize(
rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
)
if (minBuf <= 0) return false
val bufSize = minBuf * 2
val rec = try {
AudioRecord(
MediaRecorder.AudioSource.VOICE_RECOGNITION,
rate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufSize,
)
} catch (e: Exception) {
Log.w(TAG, "AudioRecord 创建失败", e)
return false
}
if (rec.state != AudioRecord.STATE_INITIALIZED) {
rec.release()
return false
}
pcm.clear()
total = 0
peakLevel = 0
record = rec
recording = true
rec.startRecording()
thread = Thread {
val buf = ByteArray(bufSize)
while (recording) {
val n = rec.read(buf, 0, buf.size)
if (n <= 0) continue
pcm.add(buf.copyOf(n))
total += n
peakLevel = peakOf(buf, n)
}
}.also { it.start() }
return true
}
/** 结束录音并返回 WAV 字节;没录到东西返回 null */
fun stop(): ByteArray? {
if (!recording) return null
recording = false
try {
thread?.join(800)
} catch (_: InterruptedException) {
// 超时就算了,下面的数据照样能用
}
thread = null
try {
record?.stop()
} catch (_: Exception) {
// 没 start 成功时 stop 会抛,忽略
}
record?.release()
record = null
peakLevel = 0
if (total < SAMPLE_RATE / 4) return null // 不到 0.25 秒当没说话
val body = ByteArray(total)
var off = 0
for (chunk in pcm) {
System.arraycopy(chunk, 0, body, off, chunk.size)
off += chunk.size
}
pcm.clear()
return wavHeader(body.size) + body
}
fun cancel() {
recording = false
try {
thread?.join(300)
} catch (_: InterruptedException) {
// 忽略
}
thread = null
try {
record?.stop()
} catch (_: Exception) {
// 忽略
}
record?.release()
record = null
pcm.clear()
total = 0
peakLevel = 0
}
/** 取一小段里最大的振幅,映射成 0~100 */
private fun peakOf(buf: ByteArray, len: Int): Int {
var peak = 0
var i = 0
while (i + 1 < len) {
// 小端 16bit
val v = (buf[i].toInt() and 0xFF) or (buf[i + 1].toInt() shl 8)
val abs = if (v < 0) -v else v
if (abs > peak) peak = abs
i += 2
}
return (peak * 100 / 32768).coerceIn(0, 100)
}
/** 44 字节标准 WAV 头(PCM 16bit 单声道) */
private fun wavHeader(dataLen: Int): ByteArray {
val header = ByteArray(44)
fun putStr(offset: Int, s: String) {
for (i in s.indices) header[offset + i] = s[i].code.toByte()
}
fun putInt(offset: Int, v: Int) {
header[offset] = (v and 0xFF).toByte()
header[offset + 1] = ((v shr 8) and 0xFF).toByte()
header[offset + 2] = ((v shr 16) and 0xFF).toByte()
header[offset + 3] = ((v shr 24) and 0xFF).toByte()
}
fun putShort(offset: Int, v: Int) {
header[offset] = (v and 0xFF).toByte()
header[offset + 1] = ((v shr 8) and 0xFF).toByte()
}
putStr(0, "RIFF")
putInt(4, 36 + dataLen)
putStr(8, "WAVE")
putStr(12, "fmt ")
putInt(16, 16)
putShort(20, 1) // PCM
putShort(22, 1) // 单声道
putInt(24, SAMPLE_RATE)
putInt(28, SAMPLE_RATE * 2) // 字节率 = 采样率 * 声道 * 位深/8
putShort(32, 2) // 块对齐
putShort(34, 16) // 位深
putStr(36, "data")
putInt(40, dataLen)
return header
}
companion object {
const val SAMPLE_RATE = 16000
private const val TAG = "DoubaoRecorder"
}
}
/** 播放本地 PCM(暂时没用到,留着给"边合成边播"的流式方案) */
@Suppress("unused")
class PcmPlayer {
private var track: AudioTrack? = null
fun play(pcm: ByteArray) {
stop()
val t = AudioTrack.Builder()
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANT)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build(),
)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(Recorder.SAMPLE_RATE)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.build(),
)
.setBufferSizeInBytes(pcm.size.coerceAtLeast(4096))
.setTransferMode(AudioTrack.MODE_STATIC)
.build()
t.write(pcm, 0, pcm.size)
t.play()
track = t
}
fun stop() {
try {
track?.stop()
track?.release()
} catch (_: Exception) {
// 忽略
}
track = null
}
}
/** 把回复里的 markdown 剥掉再念 —— 否则会念出一堆星号和反引号 */
fun stripForSpeech(text: String): String {
var s = text
s = s.replace(Regex("```[\\s\\S]*?```"), "(代码块)")
s = s.replace(Regex("`([^`]*)`"), "$1")
s = s.replace(Regex("!\\[[^\\]]*\\]\\([^)]*\\)"), "")
s = s.replace(Regex("\\[([^\\]]*)\\]\\([^)]*\\)"), "$1")
s = s.replace(Regex("(?m)^#{1,6}\\s*"), "")
s = s.replace(Regex("\\*\\*([^*]*)\\*\\*"), "$1")
s = s.replace(Regex("(?m)^\\s*[-*+]\\s+"), "")
s = s.replace(Regex("\\*"), "")
s = s.replace(Regex("~~([^~]*)~~"), "$1")
return s.trim()
}
/** 按句切:中英文句末标点 + 换行,另外照顾超长无标点的段落 */
fun splitSentences(text: String, maxLen: Int = 180): List<String> {
val clean = stripForSpeech(text)
if (clean.isEmpty()) return emptyList()
val out = ArrayList<String>()
val sb = StringBuilder()
for (ch in clean) {
sb.append(ch)
val boundary = ch in "。!?!?;;\n"
if (boundary && sb.length >= 4) {
out.add(sb.toString().trim())
sb.setLength(0)
} else if (sb.length >= maxLen) {
out.add(sb.toString().trim())
sb.setLength(0)
}
}
if (sb.isNotBlank()) out.add(sb.toString().trim())
return out.filter { it.isNotBlank() }
}

View File

@@ -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"
}
}

View File

@@ -0,0 +1,409 @@
package com.doubao.lynxclone.termux
import android.content.Context
import android.util.Log
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipInputStream
/**
* 把 Termux 的根文件系统(bootstrap)装进应用私有目录。
*
* 这套逻辑是从 Termux 自己的 `TermuxInstaller.java` 移植过来的(Apache-2.0),
* 关键就三步:
* 1. 从 `lib/<abi>/libtermux-bootstrap.so` 读 zip(它其实就是个改了名的 zip,
* 放在 lib 目录是为了让系统在安装时原样解出来、不被压缩)
* 2. 逐条解压到 files/usr,并给 bin/ lib/ 下的文件加可执行位
* 3. 读 SYMLINKS.txt(格式 `目标←链接路径`),**用 /system/bin/sh 建符号链接**
* —— Java 的 File API 建不了符号链接,只能借 shell
*
* 为什么必须 targetSdk=28:Android 10 起 targetSdk>=29 的应用不允许执行自己数据目录里的二进制,
* 而 bash/python 全在这个目录里。Termux 自己也是锁 28 才活下来的。
*/
object TermuxInstaller {
private const val TAG = "DoubaoTermux"
private const val BOOTSTRAP_LIB = "libtermux-bootstrap.so"
private const val ARROW = "\u2190" // SYMLINKS.txt 里的分隔符
fun prefix(context: Context): File = File(context.filesDir, "usr")
fun home(context: Context): File = File(context.filesDir, "home")
fun bashPath(context: Context): String = File(prefix(context), "bin/bash").absolutePath
/** 装没装:看 bash 在不在(Termux 的 bootstrap 一定带 bash) */
fun isInstalled(context: Context): Boolean =
File(prefix(context), "bin/bash").exists() && File(prefix(context), "bin/login").exists()
/** 剩余没装的标记文件,避免半途失败后反复重来 */
private fun stampFile(context: Context) = File(context.filesDir, ".termux-bootstrap-ok")
/**
* 安装日志。
*
* 为什么要写文件而不是只打 Logcat:部分国产 ROM(实测 realme/ColorOS)会把应用自己打的
* log 全过滤掉,出问题时 adb logcat 里一条都看不到,只能靠落盘来诊断。
* 位置:files/termux-install.log,可以直接 `adb shell run-as <包名> cat files/termux-install.log`
*/
private fun logFile(context: Context) = File(context.filesDir, "termux-install.log")
fun trace(context: Context, message: String) { Log.i(TAG, message)
try {
logFile(context).appendText("${System.currentTimeMillis()} $message\n")
} catch (_: Throwable) {
// 落盘失败不影响主流程
}
}
/**
* 安装(幂等)。要在后台线程调用。progress 会报告阶段,给界面显示。
* @return true 表示装好(或本来就装好了)
*/
fun install(context: Context, progress: (String) -> Unit): Boolean {
trace(context, "install() 开始;isInstalled=${isInstalled(context)} stamp=${stampFile(context).exists()}")
if (stampFile(context).exists() && isInstalled(context)) {
// 已经装过也别直接返回:rc 文件是 App 生成的,升级 App 后要跟着更新
writeBashRc(context)
progress("Termux 环境已就绪")
return true
}
val prefix = prefix(context)
if (prefix.exists()) prefix.deleteRecursively()
prefix.mkdirs()
trace(context, "prefix 准备完成:$prefix")
return try {
progress("正在解压运行环境(约 95 MB,首次会慢一点)…")
trace(context, "开始解压 bootstrap")
val count = extractBootstrap(context, prefix)
trace(context, "解压结束,文件数=$count")
if (count < 50) {
progress("解压结果不对:只出来 $count 个文件")
return false
}
progress("正在建立符号链接…")
createSymlinks(prefix)
trace(context, "符号链接完成")
progress("正在准备目录…")
File(prefix, "tmp").mkdirs()
File(prefix, "var").mkdirs()
home(context).mkdirs()
writeBashRc(context)
progress("正在修正脚本的解释器路径…")
val fixed = fixShebangs(context)
trace(context, "改写了 $fixed 个脚本的 shebang")
val binCount = File(prefix, "bin").list()?.size ?: 0
stampFile(context).writeText("ok")
progress("Termux 环境安装完成($binCount 个命令)")
trace(context, "安装完成:files=$count bin=$binCount")
true
} catch (t: Throwable) {
trace(context, "安装失败:${t.javaClass.simpleName}: ${t.message}")
progress("安装失败:${t.message}")
false
}
}
/**
* 解压 bootstrap。
*
* ★ 这里有个坑:`libtermux-bootstrap.so` **不是纯 zip**,而是
* 「1328 字节的 ELF 头 + 一个完整 zip」(Android 要求 lib 下的 so 得像 ELF,
* Termux 就把 zip 接在 ELF 头后面)。
* `ZipInputStream` 是按本地文件头顺序扫的,在安卓上实测一个条目都读不出来;
* 而 `ZipFile` 走的是文件尾的中央目录,能直接跳过前面的 ELF 头 —— 所以先落盘再用 ZipFile。
*
* 注意注释里千万别写 "lib" 加斜杠星号那种通配(Kotlin 块注释会嵌套,会把后面代码全注释掉)。
*/
private fun extractBootstrap(context: Context, targetDir: File): Int {
val cacheZip = File(context.cacheDir, "termux-bootstrap.zip")
try {
// ① 从 APK 里把那份 .so 原样拷出来
val apk = File(context.applicationInfo.sourceDir)
val abi = android.os.Build.SUPPORTED_ABIS.firstOrNull() ?: "arm64-v8a"
val candidates = listOf(abi, "arm64-v8a", "x86_64")
var copied = false
java.util.zip.ZipFile(apk).use { apkZip ->
for (candidate in candidates) {
val entry = apkZip.getEntry("lib/$candidate/$BOOTSTRAP_LIB") ?: continue
Log.i(TAG, "bootstrap 来自 APK: lib/$candidate/$BOOTSTRAP_LIB (${entry.size} 字节)")
apkZip.getInputStream(entry).use { input ->
cacheZip.outputStream().use { out -> input.copyTo(out, 256 * 1024) }
}
copied = true
break
}
}
if (!copied) {
// 退路:有些打包方式会把 .so 解到 nativeLibraryDir
val fromLib = File(context.applicationInfo.nativeLibraryDir, BOOTSTRAP_LIB)
if (!fromLib.exists()) throw IllegalStateException("APK 里找不到 $BOOTSTRAP_LIB")
fromLib.copyTo(cacheZip, overwrite = true)
Log.i(TAG, "bootstrap 来自 nativeLibraryDir")
}
// ② 把 ELF 头切掉,得到纯 zip
//
// ★ 为什么必须切:安卓的 ZipFile **不会**像桌面 JVM 那样自动跳过前缀,
// 它按中央目录里记的偏移去读,读到文件开头是 ELF 就报
// "Entry at offset zero has invalid LFH signature 464c457f"
// (464c457f 就是 \x7FELF 的小端十六进制)。
// 模拟器上碰巧宽松能过,真机 Android 16 直接失败 —— 所以自己切最稳。
val pureZip = File(context.cacheDir, "termux-bootstrap-pure.zip")
val zipOffset = stripPrefix(cacheZip, pureZip)
trace(context, "ELF 前缀 ${zipOffset} 字节,已切掉")
// ③ 用 ZipFile 读纯 zip
var count = 0
var skipped = 0
java.util.zip.ZipFile(pureZip).use { zip ->
val entries = zip.entries()
while (entries.hasMoreElements()) {
val entry = entries.nextElement()
val name = entry.name
if (name.startsWith("..") || name.contains("../")) continue
val outFile = File(targetDir, name)
if (entry.isDirectory) {
outFile.mkdirs()
continue
}
val parent = outFile.parentFile
if (parent != null && !parent.exists()) parent.mkdirs()
// ★ 单个文件失败不能把整次安装毁掉:安卓上有个别人为拦的怪名字
// (比如 bin/su 会 ENOENT),跳过去照样能用。
try {
zip.getInputStream(entry).use { input ->
FileOutputStream(outFile).use { out -> input.copyTo(out, 256 * 1024) }
}
} catch (t: Throwable) {
skipped += 1
if (skipped <= 5) {
Log.w(
TAG,
"跳过 $name(${t.javaClass.simpleName}: ${t.message})" +
" parent=${parent?.absolutePath} exists=${parent?.exists()}" +
" isDir=${parent?.isDirectory}",
)
}
continue
}
// bin/ lib/ libexec/ 和根目录下的东西要可执行
val rel = name.replace('\\', '/')
if (rel.startsWith("bin/") || rel.startsWith("lib/") ||
rel.startsWith("libexec/") || !rel.contains('/')
) {
outFile.setExecutable(true, false)
}
count += 1
}
}
Log.i(TAG, "解压完成,$count 个文件(跳过 $skipped 个)")
pureZip.delete()
return count
} finally {
cacheZip.delete()
}
}
/**
* 把 `ELF 头 + zip` 切成纯 zip,返回被切掉的前缀长度。
* ZIP 的第一个本地文件头签名是 `PK\x03\x04`;ELF 头只有一千多字节,扫前 64KB 足够。
*/
private fun stripPrefix(src: File, dst: File): Long {
FileInputStream(src).use { input ->
val head = ByteArray(64 * 1024)
val n = input.read(head)
if (n <= 4) throw IllegalStateException("bootstrap 文件太小($n 字节)")
var offset = -1
for (i in 0 until n - 3) {
if (head[i] == 0x50.toByte() && head[i + 1] == 0x4b.toByte() &&
head[i + 2] == 0x03.toByte() && head[i + 3] == 0x04.toByte()
) {
offset = i
break
}
}
if (offset < 0) throw IllegalStateException("在文件头 64KB 里找不到 ZIP 签名(PK\\x03\\x04)")
FileOutputStream(dst).use { out ->
out.write(head, offset, n - offset)
input.copyTo(out, 256 * 1024)
}
return offset.toLong()
}
}
/**
* 建符号链接。Java 建不了 symlink,只能把上千条 ln -s 拼成脚本交给 /system/bin/sh 执行。
* SYMLINKS.txt 里的相对路径是相对 prefix 的,所以 cwd 必须设成 prefix。
*/
private fun createSymlinks(prefix: File) {
val symlinksFile = File(prefix, "SYMLINKS.txt")
if (!symlinksFile.exists()) {
Log.w(TAG, "没有 SYMLINKS.txt,跳过")
return
}
val commands = symlinksFile.readLines()
.filter { it.contains(ARROW) }
.map { line ->
val idx = line.indexOf(ARROW)
val target = line.substring(0, idx)
val link = line.substring(idx + ARROW.length)
"ln -sf '$target' '$link'"
}
symlinksFile.delete()
if (commands.isEmpty()) return
// 一次别塞太多,命令行有长度上限
commands.chunked(200).forEach { chunk ->
val script = chunk.joinToString(" ; ")
val proc = ProcessBuilder("/system/bin/sh", "-c", script)
.directory(prefix)
.redirectErrorStream(true)
.start()
val output = proc.inputStream.bufferedReader().readText()
val code = proc.waitFor()
if (code != 0) {
Log.w(TAG, "建链接返回 $code:${output.take(400)}")
}
}
}
/**
* 写一份我们自己的 bash rc。
*
* 为什么需要:Termux 的 bash 是带着编译期路径 `/data/data/com.termux/files/usr/etc/profile`
* 构建的,而我们的 prefix 是 `/data/user/0/<我们的包名>/files/usr`。
* termux-exec 只重写 **exec 的路径**,管不到 bash 自己 open("/etc/profile"),
* 所以登录式 bash 一启动就会报 "Permission denied"。
*
* ★ 这里**故意不去 source Termux 自带的 etc/profile**:
* 真机实测 source 之后 bash 会立刻退出,终端上只留一句 "[Process completed]"
* (那份 profile 里有一堆 dpkg/init 的假设,在别人的 prefix 下不成立)。
* 交互式终端真正需要的变量这里手工设全就够了。
*/
private fun writeBashRc(context: Context) {
val prefix = prefix(context).absolutePath
val home = home(context).absolutePath
val rc = File(prefix, "etc/doubao.bashrc")
rc.parentFile?.mkdirs()
rc.writeText(
"""
# 由豆包 App 生成:内置 Termux 的交互式 bash 配置(保持最小)
export PREFIX="$prefix"
export HOME="$home"
export TMPDIR="$prefix/tmp"
export PATH="$prefix/bin:$prefix/bin/applets:/system/bin:/system/xbin"
export LD_LIBRARY_PATH="$prefix/lib"
export LD_PRELOAD="$prefix/lib/libtermux-exec.so"
export TERM=xterm-256color
export LANG=en_US.UTF-8
export COLORTERM=truecolor
cd "${'$'}HOME" 2>/dev/null || cd /
export PS1='\[\e[32m\]\u@termux\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '
echo "豆包内置 Termux —— 试试 pkg install python"
""".trimIndent() + "\n",
Charsets.UTF_8,
)
trace(context, "已写入 bash rc: ${rc.absolutePath}")
}
/**
* 把脚本里 shebang 的硬编码前缀改成我们自己的。
*
* 为什么必须做:Termux 的 bin 下不少命令(getprop、pkg 之类)是 shell 脚本,
* 第一行写死了 `#!/data/data/com.termux/files/usr/bin/sh`。
* 那个路径属于**另一个包**,我们 exec 它会 EACCES ——
* 表现是 "bad interpreter: Permission denied"。
* termux-exec 只重写 execve 的参数,管不到内核解析 shebang 这一步,所以直接改文件最省事。
*/
private fun fixShebangs(context: Context): Int {
val prefix = prefix(context)
val oldPrefix = "/data/data/com.termux/files/usr"
val newPrefix = prefix.absolutePath
var fixed = 0
val dirs = listOf(File(prefix, "bin"), File(prefix, "libexec"), File(prefix, "libexec/termux-am"))
for (dir in dirs) {
val files = dir.listFiles() ?: continue
for (file in files) {
if (!file.isFile || file.length() > 512 * 1024) continue
val head = try {
file.inputStream().use { input ->
val buf = ByteArray(256)
val n = input.read(buf)
if (n <= 0) return@use "" else String(buf, 0, n, Charsets.UTF_8)
}
} catch (t: Throwable) {
continue
}
if (!head.startsWith("#!$oldPrefix")) continue
try {
val text = file.readText(Charsets.UTF_8)
file.writeText(text.replaceFirst(oldPrefix, newPrefix), Charsets.UTF_8)
file.setExecutable(true, false)
fixed += 1
} catch (t: Throwable) {
Log.w(TAG, "改 shebang 失败:${file.name}", t)
}
}
}
return fixed
}
/** 交互式终端应该跑的 shell(配我们自己的 rc) */
fun interactiveShellArgs(context: Context): Array<String> =
arrayOf("--rcfile", File(prefix(context), "etc/doubao.bashrc").absolutePath, "-i")
/** 装完之后给内核/工具用的环境变量(Termux 的标准一套) */
fun environment(context: Context): Map<String, String> {
val prefix = prefix(context).absolutePath
val home = home(context).absolutePath
val filesDir = context.filesDir.absolutePath
val legacy = "/data/data/${context.packageName}/files"
return mapOf(
"PREFIX" to prefix,
"HOME" to home,
"TMPDIR" to "$prefix/tmp",
"PATH" to "$prefix/bin:$prefix/bin/applets:/system/bin:/system/xbin",
"LD_LIBRARY_PATH" to "$prefix/lib",
// ★ 这个 LD_PRELOAD 是 Termux 能在 Android 上正常跑命令的关键:
// 它把二进制里写死的 /data/data/com.termux/files/usr 重写到我们自己的 prefix。
// 不开的话 bash 会去找别的 App 的 profile,报 Permission denied。
"LD_PRELOAD" to "$prefix/lib/libtermux-exec.so",
/**
* ★ 下面这两个是 termux-exec 用来确定"真实 prefix"的变量(从它的 .so 里扫出来的符号名):
* TERMUX__PREFIX —— 注意是**双下划线**,写成 TERMUX_PREFIX 它不认
* TERMUX_APP__DATA_DIR —— 应用数据目录
* 少一个路径重写就不生效,表现是 bash 去读 /data/data/com.termux/... 然后权限拒绝。
*/
"TERMUX__PREFIX" to prefix,
"TERMUX__ROOTFS" to "/",
"TERMUX_APP__DATA_DIR" to filesDir,
"TERMUX_APP__LEGACY_DATA_DIR" to legacy,
"TERMUX_APP__PACKAGE_NAME" to context.packageName,
"TERMUX_APP__APP_VERSION_NAME" to "0.3.0",
"TERMUX_IS_DEBUGGABLE_BUILD" to "1",
"LANG" to "en_US.UTF-8",
"LC_ALL" to "en_US.UTF-8",
"TERM" to "xterm-256color",
"TZ" to "Asia/Shanghai",
"ANDROID_ROOT" to "/system",
"ANDROID_DATA" to "/data",
"EXTERNAL_STORAGE" to "/sdcard",
"TERMUX_VERSION" to "0.118.3",
"TERMUX_MAIN_PACKAGE_FORMAT" to "debian",
)
}
}

View File

@@ -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}")
}
}
}

View File

@@ -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()
}

View File

@@ -0,0 +1,357 @@
package com.doubao.lynxclone.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.doubao.lynxclone.data.Agent
/**
* 智能体页(对应旧版 Lynx 的 Agents.tsx)。
*
* 几个取舍:
*
* 1. **列表点一下就"使用"**(照旧版)。编辑要按右边的笔,避免手滑把当前人设换掉。
* 当前使用中的那一项有「使用中」标记 —— 没有标记的话用户不知道现在到底是谁在回答。
*
* 2. **删除只给"自建"的智能体**。内核里 4 个内置智能体(豆包/代码搭子/文案师/数据分析)
* 删掉之后内核会重建默认列表,界面上会出现"删了又回来"的诡异现象;
* 旧版也是这么藏的(`!builtin` 才显示删除)。自建的才给删,删前再确认一次。
*
* 3. **「一句话介绍」实际上是内核的 tagline 字段**,而 AppViewModel.saveAgent 的形参叫
* greeting、KernelClient 又是透传 —— 现在这份内核(store.create_agent)只认 tagline,
* 所以这个输入框的内容**目前存不进去**。这是别人的文件里的契约不一致,
* 我按 UI 契约传参,同时在提示文案里写清楚,免得用户以为是自己没保存上。
*/
@Composable
fun AgentsScreen(vm: AppViewModel) {
var editing by remember { mutableStateOf<Agent?>(null) }
var creating by remember { mutableStateOf(false) }
var confirmDelete by remember { mutableStateOf<Agent?>(null) }
val activeId = vm.state.activeAgent?.id.orEmpty()
Column(Modifier.fillMaxSize()) {
ScreenHeader("智能体", onBack = { vm.screen = Screen.Chat }) {
TextButton(onClick = { creating = true }) { Text("新建", fontSize = 13.sp) }
}
Column(
Modifier
.weight(1f)
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.imePadding()
.padding(horizontal = 14.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Spacer(Modifier.height(2.dp))
SettingsCard {
FormHint("点一项就切换人设,之后所有新消息都按它回答;点右边的笔可以改。")
}
vm.state.agents.forEach { agent ->
AgentRow(
agent = agent,
active = agent.id == activeId,
onUse = { vm.useAgent(agent.id) },
onEdit = { editing = agent },
onDelete = { confirmDelete = agent },
)
}
if (vm.state.agents.isEmpty()) {
SettingsCard { FormHint("还没有智能体,点右上角「新建」加一个。") }
}
Button(
onClick = { creating = true },
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(24.dp),
contentPadding = PaddingValues(vertical = 12.dp),
) {
Icon(Icons.Filled.Add, null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("新建智能体", fontSize = 15.sp)
}
FormHint("每个智能体的系统提示词互相独立;聊天页顶部会显示当前用的是谁。")
Spacer(Modifier.height(20.dp))
}
}
/* ---------------- 新建 / 编辑 ---------------- */
if (creating || editing != null) {
val target = editing
AgentEditDialog(
agent = target,
onDismiss = { creating = false; editing = null },
onSave = { name, avatar, prompt, tagline ->
vm.saveAgent(target?.id, name, avatar, prompt, tagline) {
creating = false
editing = null
}
},
onDelete = if (target != null && !target.builtin) {
{ confirmDelete = target }
} else {
null
},
)
}
/* ---------------- 删除确认 ---------------- */
confirmDelete?.let { agent ->
AlertDialog(
onDismissRequest = { confirmDelete = null },
title = { Text("删除智能体", fontSize = 16.sp) },
text = { Text("确定删除「${agent.name}」吗?它的系统提示词也会一起删掉,不能撤销。", fontSize = 13.sp) },
confirmButton = {
TextButton(onClick = {
vm.deleteAgent(agent.id)
confirmDelete = null
// 正在编辑的就是被删的那个的话,把编辑框一起关掉,否则保存会 404
if (editing?.id == agent.id) editing = null
}) { Text("删除") }
},
dismissButton = { TextButton(onClick = { confirmDelete = null }) { Text("取消") } },
)
}
}
/* ------------------------------ 一行智能体 ------------------------------ */
@Composable
private fun AgentRow(
agent: Agent,
active: Boolean,
onUse: () -> Unit,
onEdit: () -> Unit,
onDelete: () -> Unit,
) {
Surface(
modifier = Modifier.fillMaxWidth().clickable(onClick = onUse),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surface,
border = BorderStroke(
1.dp,
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.6f),
),
) {
Row(
Modifier.fillMaxWidth().padding(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
AvatarCircle(name = agent.name, avatar = agent.avatar, size = 44)
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(agent.name, fontSize = 15.sp, fontWeight = FontWeight.Medium)
if (active) {
Spacer(Modifier.width(8.dp))
ActiveBadge()
}
if (agent.builtin) {
Spacer(Modifier.width(8.dp))
Text("内置", fontSize = 10.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
Text(
// 摘要:优先用一句话介绍,其次取系统提示词首行,都没有就说通用助手
agentSummary(agent),
fontSize = 12.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
)
}
TextButton(onClick = onEdit) { Text("编辑", fontSize = 12.sp) }
if (!agent.builtin) {
TextButton(onClick = onDelete) { Text("删除", fontSize = 12.sp) }
}
}
}
}
@Composable
private fun ActiveBadge() {
Surface(shape = RoundedCornerShape(6.dp), color = MaterialTheme.colorScheme.primaryContainer) {
Row(
Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
Icons.Filled.Check,
null,
modifier = Modifier.size(11.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer,
)
Spacer(Modifier.width(2.dp))
Text("使用中", fontSize = 10.sp, color = MaterialTheme.colorScheme.onPrimaryContainer)
}
}
}
/* ------------------------------ 编辑弹窗 ------------------------------ */
/**
* 编辑/新建弹窗。
*
* 为什么用"弹窗 + 本地草稿"而不是像旧版那样整页切换成编辑态:
* 手机屏幕小,整页切换会丢掉列表的上下文(改什么、改的是哪一个),
* 弹窗能一直看到背后列表;而且这几个页面都有返回箭头统一回聊天页的约定,
* 页面内再套一层编辑态会让"返回"语义变得含糊。
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun AgentEditDialog(
agent: Agent?,
onDismiss: () -> Unit,
onSave: (name: String, avatar: String, systemPrompt: String, greeting: String) -> Unit,
onDelete: (() -> Unit)?,
) {
var name by remember { mutableStateOf(agent?.name.orEmpty()) }
var avatar by remember { mutableStateOf(agent?.avatar ?: "doubao") }
var prompt by remember { mutableStateOf(agent?.systemPrompt.orEmpty()) }
var greeting by remember { mutableStateOf(agent?.greeting.orEmpty()) }
var error by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(if (agent == null) "新建智能体" else "编辑智能体", fontSize = 16.sp) },
text = {
Column(Modifier.verticalScroll(rememberScrollState())) {
FormLabel("头像")
FlowRow(
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
AvatarKeys.forEach { key ->
Box(Modifier.clickable { avatar = key }) {
// 选中态画在 AvatarCircle 的外圈上,不改变尺寸
AvatarCircle(name = "", avatar = key, size = 34, selected = avatar == key)
}
}
}
Spacer(Modifier.height(10.dp))
FormLabel("名称")
OutlinedTextField(
value = name,
onValueChange = { name = it },
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
placeholder = { Text("例如:翻译官", fontSize = 13.sp) },
singleLine = true,
textStyle = TextStyle(fontSize = 14.sp),
)
Spacer(Modifier.height(10.dp))
FormLabel("问候语 / 一句话介绍")
OutlinedTextField(
value = greeting,
onValueChange = { greeting = it },
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
placeholder = { Text("显示在列表里,也用作首屏问候", fontSize = 13.sp) },
singleLine = true,
textStyle = TextStyle(fontSize = 14.sp),
)
Text(
"列表摘要会显示这句;新会话首屏也用它打招呼。",
fontSize = 11.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(10.dp))
FormLabel("系统提示词")
OutlinedTextField(
value = prompt,
onValueChange = { prompt = it },
modifier = Modifier.fillMaxWidth().height(150.dp).padding(top = 6.dp),
placeholder = { Text("这个人设、规则、说话风格…", fontSize = 13.sp) },
textStyle = TextStyle(fontSize = 13.sp),
)
Text(
"和它聊天时,这段提示词会覆盖全局系统提示词。",
fontSize = 11.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (error.isNotBlank()) {
Text(error, fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
}
}
},
confirmButton = {
TextButton(onClick = {
if (name.isBlank()) {
error = "名称不能为空"
} else {
onSave(name.trim(), avatar, prompt, greeting.trim())
}
}) { Text("保存") }
},
dismissButton = {
Row {
if (onDelete != null) {
TextButton(onClick = onDelete) {
Icon(
Icons.Filled.DeleteOutline,
null,
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colorScheme.error,
)
Text("删除", color = MaterialTheme.colorScheme.error, fontSize = 13.sp)
}
}
TextButton(onClick = onDismiss) { Text("取消") }
}
},
)
}
/** 列表里那一行摘要文案 */
private fun agentSummary(agent: Agent): String = when {
agent.greeting.isNotBlank() -> agent.greeting
agent.systemPrompt.isNotBlank() -> agent.systemPrompt.lineSequence().firstOrNull { it.isNotBlank() } ?: "通用助手"
else -> "通用助手"
}

View File

@@ -0,0 +1,301 @@
package com.doubao.lynxclone.ui
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import com.doubao.lynxclone.data.Conversation
import com.doubao.lynxclone.data.KernelClient
/** 建 ViewModel 并把 client 注入进去(没上 DI 框架,手写个工厂就够) */
@Composable
fun rememberAppViewModel(client: KernelClient): AppViewModel =
viewModel(factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T = AppViewModel(client) as T
})
@Composable
fun AppRoot(
client: KernelClient,
termuxReady: Boolean,
termuxStatus: String,
onInstallTermux: () -> Unit,
) {
val vm = rememberAppViewModel(client)
LaunchedEffect(Unit) { vm.refresh() }
// 提示条 2.5 秒后自动消失
LaunchedEffect(vm.hint) {
if (vm.hint.isNotBlank()) {
kotlinx.coroutines.delay(2500)
vm.hint = ""
}
}
Box(
Modifier
.fillMaxSize()
.background(doubaoBg())
// edge-to-edge 下得自己吃系统栏/输入法内边距
.windowInsetsPadding(WindowInsets.safeDrawing),
) {
// 页面切换带淡入 + 轻微位移,不然是"啪"一下就换了
AnimatedContent(
targetState = vm.screen,
transitionSpec = {
val forward = targetState != Screen.Chat
val dir = if (forward) 1 else -1
(slideInHorizontally(tween(240)) { it / 14 * dir } + fadeIn(tween(200))) togetherWith
(slideOutHorizontally(tween(200)) { -it / 14 * dir } + fadeOut(tween(150)))
},
label = "screen",
) { screen ->
when (screen) {
Screen.Chat -> ChatScreen(vm)
Screen.Profile -> ProfileScreen(vm)
Screen.Settings -> SettingsScreen(vm)
Screen.Skills -> SkillsScreen(vm)
Screen.Agents -> AgentsScreen(vm)
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
}
}
// 抽屉:左边滑进来 + 遮罩淡入
AnimatedVisibility(
visible = vm.drawerOpen,
enter = slideInHorizontally(tween(260)) { -it } + fadeIn(tween(180)),
exit = slideOutHorizontally(tween(220)) { -it } + fadeOut(tween(150)),
) {
DrawerOverlay(vm)
}
if (vm.hint.isNotBlank()) {
Box(
Modifier
.align(Alignment.BottomCenter)
.padding(24.dp)
.clip(RoundedCornerShape(18.dp))
.background(Color(0xE61F2329))
.padding(horizontal = 16.dp, vertical = 10.dp),
) {
Text(vm.hint, color = Color.White, fontSize = 13.sp)
}
}
}
}
/* ------------------------------ 抽屉 ------------------------------ */
@Composable
private fun DrawerOverlay(vm: AppViewModel) {
Row(Modifier.fillMaxSize()) {
Column(
Modifier
.fillMaxHeight()
.width(300.dp)
.background(doubaoSurface()),
) {
Row(
Modifier.fillMaxWidth().padding(start = 20.dp, end = 16.dp, top = 18.dp, bottom = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text("豆包", fontSize = 26.sp, fontWeight = FontWeight.Bold, color = doubaoText())
Spacer(Modifier.weight(1f))
Icon(
Icons.Filled.Search, "搜索", tint = doubaoText(),
modifier = Modifier.size(22.dp).clickable { vm.showHint("搜索还没做") },
)
}
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
vm.screen = Screen.Agents; vm.drawerOpen = false
}
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
vm.screen = Screen.Skills; vm.drawerOpen = false
}
DrawerItem(Icons.Filled.Terminal, "终端") {
vm.screen = Screen.Terminal; vm.drawerOpen = false
}
DrawerItem(Icons.Filled.Settings, "设置") {
vm.screen = Screen.Settings; vm.drawerOpen = false
}
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
DrawerItem(
Icons.Filled.Memory, "模型",
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
) {
vm.modelPickerOpen = true
vm.drawerOpen = false
}
Spacer(Modifier.height(10.dp))
SectionLabel("置顶", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
LazyColumn(Modifier.weight(1f)) {
items(vm.state.conversations.size) { i ->
ConversationRow(vm, vm.state.conversations[i])
}
}
Row(
Modifier
.fillMaxWidth()
.clickable { vm.screen = Screen.Profile; vm.drawerOpen = false }
.padding(horizontal = 20.dp, vertical = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
Modifier.size(34.dp).clip(CircleShape).background(Doubao.Blue),
contentAlignment = Alignment.Center,
) {
Text(vm.settings.nickname.take(1), color = Color.White, fontSize = 14.sp)
}
Spacer(Modifier.width(10.dp))
Text(vm.settings.nickname, fontSize = 15.sp, color = doubaoText())
Spacer(Modifier.width(4.dp))
Icon(
Icons.Filled.ChevronRight, null,
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
)
}
}
Box(
Modifier
.weight(1f)
.fillMaxHeight()
.background(Doubao.Scrim)
.clickable { vm.drawerOpen = false },
)
}
}
@Composable
private fun DrawerItem(
icon: ImageVector,
label: String,
trailing: String = "",
onClick: () -> Unit,
) {
val source = remember { MutableInteractionSource() }
val pressed by source.collectIsPressedAsState()
val bg by animateColorAsState(
targetValue = if (pressed) doubaoCard() else Color.Transparent,
animationSpec = tween(120),
label = "itemBg",
)
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 2.dp)
.clip(RoundedCornerShape(12.dp))
.background(bg)
.clickable(interactionSource = source, indication = null, onClick = onClick)
.padding(horizontal = 10.dp, vertical = 13.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
Spacer(Modifier.width(14.dp))
Text(label, fontSize = 16.sp, color = doubaoText())
Spacer(Modifier.weight(1f))
if (trailing.isNotBlank()) {
Text(trailing, fontSize = 13.sp, color = doubaoTextSecondary())
Spacer(Modifier.width(4.dp))
Icon(
Icons.Filled.KeyboardArrowDown, null,
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
)
}
}
}
@Composable
private fun ConversationRow(vm: AppViewModel, conv: Conversation) {
val active = conv.id == vm.activeConversationId
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 2.dp)
.clip(RoundedCornerShape(14.dp))
.background(if (active) doubaoCard() else Color.Transparent)
.clickable { vm.openConversation(conv.id) }
.padding(horizontal = 10.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
Modifier.size(38.dp).clip(RoundedCornerShape(19.dp)).background(doubaoHeroRing()),
contentAlignment = Alignment.Center,
) {
Text(conv.title.take(1), color = Doubao.Blue, fontSize = 15.sp, fontWeight = FontWeight.Medium)
}
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(conv.title, fontSize = 15.sp, color = doubaoText(), maxLines = 1)
Text(
conv.preview.ifBlank { "还没有消息" },
fontSize = 12.sp,
color = doubaoTextSecondary(),
maxLines = 1,
)
}
Icon(
Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
modifier = Modifier.size(18.dp).clickable { vm.deleteConversation(conv) },
)
}
}
/* ------------------------------ 文案小工具 ------------------------------ */
fun shortModel(model: String): String = when {
model.isBlank() -> "未设置"
model.startsWith("ep-") -> "接入点 ${model.take(8)}"
model.startsWith("doubao-seed-2-1-pro") -> "豆包 Pro"
model.startsWith("doubao-seed-1-8") -> "豆包 1.8"
model.startsWith("doubao-seed-1-6") -> "豆包 1.6"
model.startsWith("doubao") -> "豆包"
model.startsWith("deepseek-r1") -> "DeepSeek R1"
model.startsWith("deepseek") -> "DeepSeek"
model.startsWith("gpt-5") -> if (model.contains("mini")) "GPT-5 mini" else "GPT-5"
model.startsWith("gpt-4o") -> if (model.contains("mini")) "GPT-4o mini" else "GPT-4o"
else -> if (model.length > 16) model.take(14) + "…" else model
}
fun thinkingLabel(level: String): String = when (level) {
"off" -> "快速"
"low" -> "低"
"medium" -> "中"
"high" -> "深度思考"
else -> "自动"
}

View File

@@ -0,0 +1,372 @@
package com.doubao.lynxclone.ui
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.doubao.lynxclone.data.Agent
import com.doubao.lynxclone.data.AppState
import com.doubao.lynxclone.data.Attachment
import com.doubao.lynxclone.data.ChatMessage
import com.doubao.lynxclone.data.Conversation
import com.doubao.lynxclone.data.KernelClient
import com.doubao.lynxclone.data.StreamEvent
import com.doubao.lynxclone.data.ToolTrace
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicBoolean
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应) */
enum class Screen { Chat, Profile, Settings, Skills, Agents, Terminal }
/**
* 全局状态。界面只读这里的状态、只调这里的方法,网络全在 KernelClient 里。
*/
class AppViewModel(val client: KernelClient) : ViewModel() {
var state by mutableStateOf(AppState())
private set
var screen by mutableStateOf(Screen.Chat)
var drawerOpen by mutableStateOf(false)
var loading by mutableStateOf(true)
var bootError by mutableStateOf("")
var hint by mutableStateOf("")
val messages = mutableStateListOf<ChatMessage>()
var activeConversationId by mutableStateOf("c_main")
var streaming by mutableStateOf(false)
private set
var draft by mutableStateOf("")
val attachments = mutableStateListOf<Attachment>()
/** 正在看「思考过程」的消息下标;-1 表示没开 */
var thinkingIndex by mutableStateOf(-1)
/** 模型 / 思考强度面板(底部升起) */
var modelPickerOpen by mutableStateOf(false)
private var chatJob: AtomicBoolean? = null
val settings get() = state.settings
val agents: List<Agent> get() = state.agents
val activeAgent: Agent? get() = state.activeAgent
fun refresh(onDone: (() -> Unit)? = null) {
viewModelScope.launch {
try {
state = withContext(Dispatchers.IO) { client.state() }
bootError = ""
} catch (e: Exception) {
bootError = e.message ?: "连不上内核"
} finally {
loading = false
onDone?.invoke()
}
}
}
fun showHint(text: String) {
hint = text
}
/** 点赞/点踩:只改本地状态(没接后端反馈接口),点同一个再点一次就取消 */
fun onFeedback(index: Int, kind: String) {
if (index !in messages.indices) return
val current = messages[index]
messages[index] = current.copy(feedback = if (current.feedback == kind) null else kind)
}
/**
* 自动朗读开关。
*
* 声音那边由 SpeechController 立即生效;这里负责**落盘**,
* 否则退出 App 再进来又变回关的,用户会以为没保存上。
*/
fun setAutoRead(on: Boolean) {
saveSettings(mapOf("speech" to mapOf("autoRead" to on)))
}
/* ------------------------------ 会话 ------------------------------ */
fun openConversation(id: String) {
activeConversationId = id
drawerOpen = false
screen = Screen.Chat
viewModelScope.launch {
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
messages.clear()
messages.addAll(list)
}
}
fun newTopic() {
viewModelScope.launch {
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
refresh()
if (conv != null) openConversation(conv.id) else {
messages.clear()
activeConversationId = ""
}
}
}
fun deleteConversation(conv: Conversation) {
viewModelScope.launch {
runCatching { withContext(Dispatchers.IO) { client.deleteConversation(conv.id) } }
refresh()
showHint("已删除「${conv.title}」")
}
}
/* ------------------------------ 发消息 ------------------------------ */
fun send() {
val text = draft.trim()
if (text.isEmpty() && attachments.isEmpty()) return
if (streaming) return
val files = attachments.toList()
draft = ""
attachments.clear()
runChat(text, files)
}
fun regenerate() {
if (streaming) return
val lastUser = messages.lastOrNull { it.role == "user" } ?: return
// 去掉最后一条助手回复再重来
while (messages.isNotEmpty() && messages.last().role != "user") messages.removeAt(messages.size - 1)
runChat(lastUser.content, emptyList())
}
private fun runChat(text: String, files: List<Attachment>) {
messages.add(ChatMessage(role = "user", content = text, attachments = files))
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
streaming = true
val cancel = AtomicBoolean(false)
chatJob = cancel
viewModelScope.launch {
try {
withContext(Dispatchers.IO) {
client.chat(
conversationId = activeConversationId.ifBlank { "c_main" },
message = text,
attachments = files,
agentId = activeAgent?.id,
cancelled = cancel,
) { event -> onStreamEvent(event) }
}
} catch (e: Exception) {
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { "出错了:${e.message}" }) }
showHint("出错了:${e.message}")
} finally {
streaming = false
chatJob = null
patchLast { it.copy(pending = false) }
refresh()
}
}
}
/** 事件回调可能在 IO 线程,统一切回主线程改状态 */
private fun onStreamEvent(event: StreamEvent) {
viewModelScope.launch {
when (event) {
is StreamEvent.Delta -> patchLast { it.copy(content = it.content + event.text) }
is StreamEvent.Reasoning -> patchLast { it.copy(reasoning = it.reasoning + event.text) }
is StreamEvent.ToolCall -> patchLast {
it.copy(toolTrace = it.toolTrace + ToolTrace(id = event.id, name = event.name))
}
is StreamEvent.ToolResult -> patchLast { msg ->
msg.copy(toolTrace = msg.toolTrace.map {
if (it.id == event.id) it.copy(ok = event.ok, result = event.result) else it
})
}
is StreamEvent.Failure -> {
val text = if (event.hint.isNotBlank()) "出错了:${event.message}|${event.hint}" else "出错了:${event.message}"
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { text }) }
showHint(text)
}
else -> Unit
}
}
}
private inline fun patchLast(fn: (ChatMessage) -> ChatMessage) {
for (i in messages.indices.reversed()) {
if (messages[i].role == "assistant") {
messages[i] = fn(messages[i])
return
}
}
}
/* ------------------------------ 设置 / 工具 ------------------------------ */
fun saveSettings(patch: Map<String, Any?>, onDone: (() -> Unit)? = null) {
viewModelScope.launch {
try {
val json = patchToJson(patch)
state = withContext(Dispatchers.IO) { client.saveSettings(json) }
showHint("已保存")
} catch (e: Exception) {
showHint("保存失败:${e.message}")
} finally {
onDone?.invoke()
}
}
}
fun setThinkingLevel(level: String) = saveSettings(mapOf("thinkingLevel" to level))
fun setModel(model: String) = saveSettings(mapOf("model" to model))
fun runTool(name: String, args: JSONObject, onResult: (Boolean, String) -> Unit) {
viewModelScope.launch {
try {
val res = withContext(Dispatchers.IO) { client.runTool(name, args) }
onResult(res.ok, if (res.ok) res.result.toString() else res.error)
} catch (e: Exception) {
onResult(false, e.message ?: "执行失败")
}
}
}
fun saveMcpConfig(text: String, onResult: (Boolean, String) -> Unit) {
viewModelScope.launch {
try {
val json = withContext(Dispatchers.IO) { client.saveMcpConfig(text) }
refresh()
val results = json.optJSONArray("results")
val summary = if (results != null) {
(0 until results.length()).joinToString(",") { i ->
val item = results.optJSONObject(i) ?: return@joinToString ""
val ok = item.optBoolean("ok")
"${item.optString("name")}${if (ok) "✓" else "✗" + item.optString("error")}"
}
} else ""
onResult(json.optBoolean("ok"), if (json.optBoolean("ok")) "已重连:$summary" else json.optString("error"))
} catch (e: Exception) {
onResult(false, e.message ?: "保存失败")
}
}
}
fun saveAgent(id: String?, name: String, avatar: String, systemPrompt: String, greeting: String, onDone: () -> Unit) {
viewModelScope.launch {
try {
val body = JSONObject()
.put("name", name)
.put("avatar", avatar)
.put("systemPrompt", systemPrompt)
// 内核字段叫 tagline;UI 上叫"一句话介绍"
.put("tagline", greeting)
withContext(Dispatchers.IO) {
if (id.isNullOrBlank()) client.createAgent(body) else client.updateAgent(id, body)
}
refresh()
onDone()
} catch (e: Exception) {
showHint("保存失败:${e.message}")
}
}
}
fun deleteAgent(id: String) {
viewModelScope.launch {
runCatching { withContext(Dispatchers.IO) { client.deleteAgent(id) } }
refresh()
}
}
fun useAgent(id: String) {
saveSettings(mapOf("activeAgentId" to id))
}
/* ------------------------------ 附件 ------------------------------ */
fun addAttachment(file: Attachment) {
if (attachments.none { it.id == file.id }) attachments.add(file)
}
fun removeAttachment(id: String) {
attachments.removeAll { it.id == id }
}
fun uploadAndAttach(name: String, mime: String, bytes: ByteArray) {
viewModelScope.launch {
try {
val file = withContext(Dispatchers.IO) { client.uploadFile(name, mime, bytes, false) }
if (file != null) {
addAttachment(file)
showHint("已添加 ${file.name}")
} else {
showHint("上传失败")
}
} catch (e: Exception) {
showHint("上传失败:${e.message}")
}
}
}
/** 从内核拉待处理附件(比如 Termux 里刚生成的文件) */
fun syncPendingUploads() {
viewModelScope.launch {
try {
val json = withContext(Dispatchers.IO) { client.state() }
state = json
} catch (_: Exception) {
}
}
}
/** 工具权限:切模式 / 勾白名单 */
fun saveSecurity(mode: String, allow: List<String>) {
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
saveSettings(mapOf("security" to json))
}
}
/**
* 把补丁 Map 转成 JSONObject。
*
* ★ 为什么必须显式递归转换,不能直接 `json.put(k, mapOf(...))`:
*
* Android 的 org.json **不会**把 `Map` 自动当成 JSON 对象 —— `put(String, Object)`
* 只是把 Map 原样塞进内部表,`toString()` 时按普通对象处理,
* 于是发出去的是 `{"speech":"{autoRead=true}"}`:值是**字符串**而不是对象。
*
* 内核那边 `speech` 本来是个 dict,被字符串覆盖之后,之后**每一次**读配置
* (`{**默认, **字符串}`)都会抛 TypeError,`/api/state` 从此一直返回
* `{"error":"'str' object is not a mapping"}`;而 App 把这个错误 JSON 解析成了
* 「全默认状态」且不抛异常 —— 表现就是:
* **点一下语音按钮,模型变"未设置"、昵称变"我"、会话列表全空,还弹"已保存"。**
*
* 这个坑很隐蔽:只有"嵌套对象"才会触发,而在此之前 App 从没发过嵌套补丁。
*/
fun patchToJson(patch: Map<String, Any?>): JSONObject {
val json = JSONObject()
for ((key, value) in patch) {
json.put(key, toJsonValue(value))
}
return json
}
private fun toJsonValue(value: Any?): Any = when (value) {
null -> JSONObject.NULL
is JSONObject, is JSONArray -> value
is Map<*, *> -> {
val obj = JSONObject()
for ((k, v) in value) obj.put(k.toString(), toJsonValue(v))
obj
}
is List<*> -> {
val arr = JSONArray()
for (item in value) arr.put(toJsonValue(item))
arr
}
else -> value
}

View File

@@ -0,0 +1,719 @@
package com.doubao.lynxclone.ui
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import android.Manifest
import android.content.pm.PackageManager
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import com.doubao.lynxclone.data.ChatMessage
import com.doubao.lynxclone.speech.SpeechController
import kotlinx.coroutines.delay
/**
* 对话页。
*
* 视觉对着豆包真机截图抠的:纯白底、顶部三段式(左右图标 + 居中智能体名)、
* 大头像 + 灰色问候气泡、白底描边快捷胶囊、输入框是大圆角描边胶囊、发送键是蓝色圆钮。
* 动效:气泡淡入上移、思考面板从底部升起、typing 三点跳动、按钮按下回弹。
*/
@Composable
fun ChatScreen(vm: AppViewModel) {
val agent = vm.activeAgent
val listState = rememberLazyListState()
val context = LocalContext.current
val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
try {
val name = uri.lastPathSegment?.substringAfterLast('/') ?: "upload"
val mime = context.contentResolver.getType(uri) ?: "application/octet-stream"
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
if (bytes != null) vm.uploadAndAttach(name, mime, bytes)
} catch (e: Exception) {
vm.showHint("读取文件失败:${e.message}")
}
}
val onPickFile: () -> Unit = { picker.launch("*/*") }
// ---------------- 语音 ----------------
val scope = rememberCoroutineScope()
val speech = remember { SpeechController(context, vm.client, scope) }
DisposableEffect(Unit) {
onDispose { speech.release() }
}
// 设置里的开关同步到控制器
LaunchedEffect(vm.state.speech.autoRead) { speech.autoRead = vm.state.speech.autoRead }
// 控制器自己产生的提示(云端失败、没听清…)也走统一的提示条
LaunchedEffect(speech.notice) {
if (speech.notice.isNotBlank()) {
vm.showHint(speech.notice)
speech.notice = ""
}
}
// 录音权限:用户第一次点麦克风时才要,不在启动时要
val micPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) speech.startRecording() else vm.showHint("没有录音权限,去系统设置里给一下")
}
val onMic: () -> Unit = {
when {
speech.recording -> speech.stopRecording { text -> vm.draft = text }
speech.transcribing -> vm.showHint("还在识别上一段…")
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)
== PackageManager.PERMISSION_GRANTED -> speech.startRecording()
else -> micPermission.launch(Manifest.permission.RECORD_AUDIO)
}
}
// 自动朗读:最后一条回复从「进行中」变成「已落地」时念出来
val lastMsg = vm.messages.lastOrNull()
val lastDoneKey = lastMsg?.let { "${vm.messages.size}:${it.pending}:${it.content.length}" }
LaunchedEffect(lastDoneKey) {
val msg = vm.messages.lastOrNull() ?: return@LaunchedEffect
if (msg.role == "assistant" && !msg.pending && !msg.error && msg.content.isNotBlank()) {
// 内容还在变(流式)时别念,等它稳定一下
delay(600)
val now = vm.messages.lastOrNull()
if (now === msg && !now.pending && now.content == msg.content) {
speech.maybeAutoRead(now.content, vm.messages.size - 1)
}
}
}
// 新消息 / 流式增量都滚到底
LaunchedEffect(vm.messages.size, vm.messages.lastOrNull()?.content?.length) {
if (vm.messages.isNotEmpty()) listState.animateScrollToItem(vm.messages.size - 1)
}
Column(Modifier.fillMaxSize().background(doubaoBg())) {
ChatHeader(vm, agent?.name ?: "豆包", speech)
LazyColumn(
state = listState,
modifier = Modifier.weight(1f).fillMaxWidth(),
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
if (vm.messages.isEmpty()) {
val tagline = agent?.greeting.orEmpty().trim()
val looksLikeSentence = tagline.length >= 12 &&
(tagline.endsWith("。") || tagline.endsWith("!") ||
tagline.endsWith("?") || tagline.contains(","))
val greeting =
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
item { AppearOnce { HeroSection(greeting) } }
}
items(vm.messages.size) { index ->
AppearOnce(offsetY = 10.dp) {
MessageItem(vm, index, vm.messages[index], speech)
}
}
}
if (vm.messages.isEmpty()) {
Row(
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())
.padding(horizontal = 16.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
listOf("对话", "AI创作", "出行用豆包", "豆包").forEach { label ->
DoubaoPill(text = label, onClick = { vm.draft = label })
}
}
}
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
InputBar(vm, onPickFile, onMic, speech)
}
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
AnimatedVisibility(
visible = thinkingVisible,
enter = slideInVertically(initialOffsetY = { it }) + fadeIn(tween(160)),
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(tween(160)),
) {
val index = vm.thinkingIndex
if (index in vm.messages.indices) ThinkingSheet(vm.messages[index]) { vm.thinkingIndex = -1 }
}
AnimatedVisibility(
visible = vm.modelPickerOpen,
enter = slideInVertically(initialOffsetY = { it }) + fadeIn(tween(160)),
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(tween(160)),
) {
ModelPickerSheet(vm) { vm.modelPickerOpen = false }
}
}
/* ------------------------------ 顶部栏 ------------------------------ */
@Composable
private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechController) {
Column(Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
HeaderIcon(Icons.Filled.Menu, "菜单") { vm.drawerOpen = true }
HeaderIcon(Icons.Filled.Edit, "新话题") { vm.newTopic() }
Spacer(Modifier.weight(1f))
// 中间这块点开就是「模型」,和豆包一样(豆包点的是 Agent 名)
Row(
Modifier
.clip(RoundedCornerShape(16.dp))
.clickable { vm.modelPickerOpen = true }
.padding(horizontal = 8.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
Modifier.size(24.dp).clip(CircleShape).background(doubaoHeroRing()),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
}
Spacer(Modifier.width(6.dp))
Text(agentName, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
Icon(Icons.Filled.ChevronRight, null, tint = doubaoText(), modifier = Modifier.size(18.dp))
}
Spacer(Modifier.weight(1f))
HeaderIcon(Icons.Filled.Call, "通话") { vm.showHint("通话模式还没做(方案在 README 里)") }
// 这个喇叭是「自动朗读」开关:开了之后每条新回复自动念
HeaderIcon(
if (speech.autoRead) Icons.Filled.VolumeUp else Icons.Filled.VolumeOff,
if (speech.autoRead) "自动朗读已开" else "自动朗读已关",
tint = if (speech.autoRead) Doubao.Blue else null,
) {
val next = !speech.autoRead
speech.autoRead = next
vm.setAutoRead(next)
vm.showHint(if (next) "新回复会自动朗读" else "已关闭自动朗读")
}
}
Text(
"AI 生成可能有误 注意核实",
modifier = Modifier.fillMaxWidth(),
fontSize = 10.sp,
color = doubaoTextSecondary(),
textAlign = TextAlign.Center,
)
}
}
@Composable
private fun HeaderIcon(
icon: ImageVector,
desc: String,
tint: androidx.compose.ui.graphics.Color? = null,
onClick: () -> Unit,
) {
val source = remember { MutableInteractionSource() }
val pressed by source.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.86f else 1f, tween(110), label = "hdr")
Box(
Modifier
.size(44.dp)
.scale(scale)
.clip(CircleShape)
.clickable(interactionSource = source, indication = null, onClick = onClick),
contentAlignment = Alignment.Center,
) {
Icon(icon, desc, tint = tint ?: doubaoText(), modifier = Modifier.size(22.dp))
}
}
/* ------------------------------ 空态大头像 ------------------------------ */
@Composable
private fun HeroSection(greeting: String) {
Column(
Modifier.fillMaxWidth().padding(top = 34.dp, bottom = 18.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Box(
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
}
Spacer(Modifier.height(20.dp))
Box(
Modifier
.clip(RoundedCornerShape(16.dp))
.background(doubaoBubble())
.padding(horizontal = 16.dp, vertical = 14.dp),
) {
Text(greeting, fontSize = 16.sp, lineHeight = 26.sp, color = doubaoText())
}
}
}
/* ------------------------------ 消息 ------------------------------ */
@Composable
private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: SpeechController) {
val clipboard = LocalClipboardManager.current
val speaking = speech.speakingIndex == index
if (msg.role == "user") {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
Column(horizontalAlignment = Alignment.End) {
msg.attachments.forEach { file ->
Box(
Modifier
.clip(RoundedCornerShape(12.dp))
.background(doubaoBubble())
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Filled.Image, null,
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
)
Spacer(Modifier.width(6.dp))
Text(file.name, fontSize = 13.sp, color = doubaoText(), maxLines = 1)
}
}
Spacer(Modifier.height(6.dp))
}
if (msg.content.isNotBlank()) {
Box(
Modifier
.widthIn(max = 288.dp)
.clip(RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp))
.background(Doubao.Blue)
.padding(horizontal = 14.dp, vertical = 11.dp),
) {
Text(msg.content, color = Color.White, fontSize = 16.sp, lineHeight = 25.sp)
}
}
}
}
return
}
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
val hasReasoning = msg.reasoning.isNotBlank()
val hasTrace = msg.toolTrace.isNotEmpty()
if (hasReasoning || hasTrace || msg.pending) {
Box(
Modifier
.clip(RoundedCornerShape(14.dp))
.background(doubaoCard())
.clickable { vm.thinkingIndex = index }
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.AutoAwesome, null, tint = Doubao.Blue, modifier = Modifier.size(15.dp))
Spacer(Modifier.width(6.dp))
Text(
when {
// 强度本身就叫"深度思考",拼上去会变成"深度思考 · 深度思考"
hasReasoning -> "深度思考"
hasTrace -> "执行过程"
else -> "深度思考中"
},
fontSize = 13.sp,
color = doubaoTextSecondary(),
)
Spacer(Modifier.width(6.dp))
if (hasReasoning || hasTrace) {
Icon(
Icons.Filled.ChevronRight, null,
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
)
} else {
TypingDots(dot = 4.dp)
}
}
}
Spacer(Modifier.height(8.dp))
}
msg.toolTrace.forEach { trace ->
var open by remember(trace.id) { mutableStateOf(false) }
Box(
Modifier
.fillMaxWidth()
.padding(bottom = 6.dp)
.clip(RoundedCornerShape(12.dp))
.background(doubaoCard())
.clickable { open = !open }
.padding(horizontal = 12.dp, vertical = 9.dp),
) {
Column {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.Build, null, tint = doubaoTextSecondary(), modifier = Modifier.size(14.dp))
Spacer(Modifier.width(6.dp))
Text(trace.name, fontSize = 13.sp, color = doubaoText())
Spacer(Modifier.weight(1f))
Text(
when (trace.ok) {
true -> "完成"
false -> "失败"
null -> "进行中"
},
fontSize = 11.sp,
color = if (trace.ok == false) Doubao.Error else Doubao.Blue,
)
Icon(
Icons.Filled.ChevronRight, null,
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
)
}
if (open && trace.result.isNotBlank()) {
Spacer(Modifier.height(6.dp))
Text(
trace.result.take(800),
fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary(),
)
}
}
}
}
Box(
Modifier
.widthIn(max = 300.dp)
.clip(RoundedCornerShape(4.dp, 18.dp, 18.dp, 18.dp))
.background(if (msg.error) Doubao.ErrorBg else doubaoBubble())
.padding(horizontal = 14.dp, vertical = 12.dp),
) {
when {
msg.content.isNotBlank() -> Text(
msg.content,
fontSize = 16.sp,
lineHeight = 26.sp,
color = if (msg.error) Doubao.Error else doubaoText(),
)
msg.pending -> TypingDots()
else -> Text("…", color = doubaoTextSecondary(), fontSize = 16.sp)
}
}
if (!msg.pending && msg.content.isNotBlank() && !msg.error) {
Spacer(Modifier.height(8.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
RoundIconButton(Icons.Filled.ContentCopy, "复制") {
clipboard.setText(AnnotatedString(msg.content))
vm.showHint("已复制")
}
Spacer(Modifier.width(10.dp))
if (speaking) {
// 正在念这条:按钮变蓝 + 图标换成停止,一眼看出"再点就是停"
RoundIconButton(
Icons.Filled.Stop, "停止朗读",
tint = Doubao.Blue,
bg = doubaoHeroRing(),
) { speech.stopSpeaking() }
} else {
RoundIconButton(Icons.Filled.VolumeUp, "朗读") { speech.speak(msg.content, index) }
}
Spacer(Modifier.width(10.dp))
RoundIconButton(
Icons.Filled.ThumbUp, "赞",
tint = if (msg.feedback == "up") Doubao.Blue else null,
) { vm.onFeedback(index, "up") }
Spacer(Modifier.width(10.dp))
RoundIconButton(
Icons.Filled.ThumbDown, "踩",
tint = if (msg.feedback == "down") Doubao.Blue else null,
) { vm.onFeedback(index, "down") }
Spacer(Modifier.width(10.dp))
RoundIconButton(Icons.Filled.Share, "分享") { vm.showHint("分享还没做") }
Spacer(Modifier.weight(1f))
RoundIconButton(Icons.Filled.Refresh, "重新生成") { vm.regenerate() }
}
}
}
}
/* ------------------------------ 附件 / 输入栏 ------------------------------ */
@Composable
private fun AttachmentStrip(vm: AppViewModel) {
Row(
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())
.padding(horizontal = 16.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
vm.attachments.forEach { file ->
Box(
Modifier
.clip(RoundedCornerShape(10.dp))
.background(doubaoCard())
.padding(horizontal = 10.dp, vertical = 7.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Filled.AttachFile, null,
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
)
Spacer(Modifier.width(5.dp))
Text(file.name, fontSize = 12.sp, color = doubaoText(), maxLines = 1)
Spacer(Modifier.width(8.dp))
Icon(
Icons.Filled.Close, "移除", tint = doubaoTextSecondary(),
modifier = Modifier.size(14.dp).clickable { vm.removeAttachment(file.id) },
)
}
}
}
}
}
@Composable
private fun InputBar(
vm: AppViewModel,
onPickFile: () -> Unit,
onMic: () -> Unit,
speech: SpeechController,
) {
val canSend = vm.draft.isNotBlank() || vm.attachments.isNotEmpty()
val sendSource = remember { MutableInteractionSource() }
val sendPressed by sendSource.collectIsPressedAsState()
val sendScale by animateFloatAsState(if (sendPressed) 0.88f else 1f, tween(110), label = "send")
// 录音时把输入框整条换成"正在听…",跟豆包按住说话一个观感
if (speech.recording || speech.transcribing) {
Row(
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Row(
Modifier
.weight(1f)
.height(52.dp)
.clip(RoundedCornerShape(26.dp))
.background(Doubao.Blue.copy(alpha = 0.08f))
.border(1.dp, Doubao.Blue, RoundedCornerShape(26.dp))
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
if (speech.transcribing) Icons.Filled.HourglassTop else Icons.Filled.Mic,
null, tint = Doubao.Blue, modifier = Modifier.size(20.dp),
)
Spacer(Modifier.width(10.dp))
Text(
if (speech.transcribing) "识别中…" else "正在听…",
fontSize = 15.sp,
color = Doubao.Blue,
)
Spacer(Modifier.width(12.dp))
// 简易波形:用实时音量画几根高低不同的柱子,能看出"在收音"
Row(
Modifier.weight(1f).height(24.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(3.dp),
) {
val amp = if (speech.transcribing) 8 else speech.level
repeat(18) { i ->
// 中间高两边低,再叠加实时音量,看着像声波
val shape = 1f - kotlin.math.abs(i - 8.5f) / 10f
val h = (6 + amp * shape * 0.16f).coerceIn(4f, 24f)
Box(
Modifier
.width(3.dp)
.height(h.dp)
.clip(RoundedCornerShape(2.dp))
.background(Doubao.Blue.copy(alpha = 0.35f + 0.5f * shape)),
)
}
}
}
Spacer(Modifier.width(8.dp))
Box(
Modifier
.size(40.dp)
.clip(CircleShape)
.background(Doubao.Blue)
.clickable { onMic() },
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Check, "完成", tint = Color.White, modifier = Modifier.size(20.dp))
}
}
return
}
Row(
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Row(
Modifier
.weight(1f)
.height(52.dp)
.clip(RoundedCornerShape(26.dp))
.background(doubaoSurface())
.border(1.dp, doubaoBorder(), RoundedCornerShape(26.dp))
.padding(horizontal = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
if (vm.attachments.isEmpty()) Icons.Filled.PhotoCamera else Icons.Filled.Add,
"附件",
tint = doubaoText(),
modifier = Modifier.size(22.dp).clickable(onClick = onPickFile),
)
Spacer(Modifier.width(10.dp))
Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
if (vm.draft.isEmpty()) {
Text("发消息或按住说话…", fontSize = 15.sp, color = Doubao.TextTertiary)
}
BasicTextField(
value = vm.draft,
onValueChange = { vm.draft = it },
modifier = Modifier.fillMaxWidth(),
textStyle = TextStyle(fontSize = 15.sp, color = doubaoText()),
cursorBrush = SolidColor(Doubao.Blue),
maxLines = 3,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { vm.send() }),
)
}
if (!canSend) {
Icon(
Icons.Filled.Mic, "语音输入", tint = doubaoText(),
modifier = Modifier.size(22.dp).clickable(onClick = onMic),
)
}
}
Spacer(Modifier.width(8.dp))
if (canSend) {
Box(
Modifier
.size(40.dp)
.scale(sendScale)
.clip(CircleShape)
.background(Doubao.Blue)
.clickable(interactionSource = sendSource, indication = null) { vm.send() },
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.ArrowUpward, "发送", tint = Color.White, modifier = Modifier.size(20.dp))
}
} else {
Box(
Modifier
.size(40.dp)
.clip(CircleShape)
.background(doubaoSurface())
.border(1.dp, doubaoBorder(), CircleShape)
.clickable(onClick = onPickFile),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Add, "更多", tint = doubaoText(), modifier = Modifier.size(22.dp))
}
}
}
}
/* ------------------------------ 思考过程弹层 ------------------------------ */
@Composable
private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
Box(
Modifier.fillMaxSize().background(Doubao.Scrim).clickable(onClick = onClose),
) {
Column(
Modifier
.align(Alignment.BottomCenter)
.fillMaxWidth()
.heightIn(max = 560.dp)
.clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp))
.background(doubaoSurface())
.clickable(enabled = false) {}
.padding(horizontal = 18.dp, vertical = 16.dp),
) {
// 顶上那条小横杠:一眼看出是从底部拉起来的
Box(
Modifier.align(Alignment.CenterHorizontally).width(36.dp).height(4.dp)
.clip(RoundedCornerShape(2.dp)).background(doubaoBorder()),
)
Spacer(Modifier.height(14.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
RoundIconButton(Icons.Filled.Close, "关闭", size = 30.dp, iconSize = 15.dp, onClick = onClose)
Spacer(Modifier.weight(1f))
Text("思考过程", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
Spacer(Modifier.weight(1f))
Spacer(Modifier.width(30.dp))
}
Spacer(Modifier.height(14.dp))
LazyColumn(Modifier.fillMaxWidth()) {
if (msg.toolTrace.isNotEmpty()) {
items(msg.toolTrace.size) { i ->
val trace = msg.toolTrace[i]
Row(Modifier.padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Filled.Build, null,
tint = doubaoTextSecondary(), modifier = Modifier.size(14.dp),
)
Spacer(Modifier.width(6.dp))
Text(
"${if (trace.ok == false) "失败" else "已调用"} ${trace.name}",
fontSize = 13.sp,
color = doubaoTextSecondary(),
)
}
}
}
item {
Text(
msg.reasoning.ifBlank { "这次没有返回思维链(模型不支持,或思考强度被关掉了)。" },
fontSize = 13.sp,
lineHeight = 21.sp,
color = doubaoTextSecondary(),
)
}
}
}
}
}

View File

@@ -0,0 +1,151 @@
package com.doubao.lynxclone.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.DeleteSweep
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.json.JSONObject
/**
* 命令控制台 —— 真 pty 用不了时的退路。
*
* 为什么需要:有些 ROM(实测 realme / Android 16)把 `/dev/pts` 挂成
* `mode=600,ptmxmode=000`,应用**分配不到从设备 pty**,
* 于是 Termux 的 TerminalSession 一起来就退出(终端上只剩一句 "[Process completed]")。
* 这不是 SELinux 拒绝,是挂载参数决定的,应用侧绕不过去。
*
* 但"跑命令"这件事本身不需要 pty:直接 ProcessBuilder 起 Termux 的 bash 就行。
* 所以这里给一个控制台:能敲命令、能看到输出、退出码和通道都显示出来,
* 只是没有全屏 TUI(vim/top)和交互式提示符。
*/
@Composable
fun CommandConsole(
onRun: (String, (Boolean, String) -> Unit) -> Unit,
modifier: Modifier = Modifier,
) {
data class Line(val text: String, val kind: String)
val lines = remember { mutableStateListOf<Line>() }
var draft by remember { mutableStateOf("") }
var busy by remember { mutableStateOf(false) }
val listState = rememberLazyListState()
LaunchedEffect(lines.size) {
if (lines.isNotEmpty()) listState.animateScrollToItem(lines.size - 1)
}
fun run(command: String) {
val cmd = command.trim()
if (cmd.isEmpty() || busy) return
lines.add(Line("$ $cmd", "cmd"))
draft = ""
busy = true
onRun(cmd) { ok, text ->
busy = false
if (ok) {
// 内核把 shell 的返回做成了 JSON 字符串,这里拆出来好看的排版
val rendered = try {
val json = JSONObject(text)
buildString {
append(json.optString("stdout"))
val err = json.optString("stderr")
if (err.isNotBlank()) append("\n[stderr] ").append(err)
append("\n[退出码 ${json.optInt("exit_code")}|通道 ${json.optString("via", "?")}]")
}
} catch (_: Exception) {
text
}
lines.add(Line(rendered.trimEnd(), "out"))
} else {
lines.add(Line(text, "err"))
}
}
}
Column(modifier.fillMaxSize()) {
Row(
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text("控制台模式", color = Color(0xFF8A93A0), fontSize = 12.sp)
Spacer(Modifier.weight(1f))
IconButton(onClick = { lines.clear() }) {
Icon(Icons.Filled.DeleteSweep, "清屏", tint = Color.White, modifier = Modifier.size(20.dp))
}
}
LazyColumn(state = listState, modifier = Modifier.weight(1f).fillMaxWidth()) {
items(lines) { line ->
Text(
line.text,
color = when (line.kind) {
"cmd" -> Color(0xFF7FD1A0)
"err" -> Color(0xFFFF8F8F)
else -> Color(0xFFD7DAE0)
},
fontSize = 12.sp,
fontFamily = FontFamily.Monospace,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
)
}
if (busy) {
item { Text("执行中…", color = Color(0xFF8A93A0), fontSize = 12.sp, modifier = Modifier.padding(12.dp)) }
}
}
// 常用命令,手机上打字麻烦
Row(
Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp),
) {
listOf(
"ls -la" to "pwd; ls -la",
"Python" to "python --version 2>/dev/null || echo 'pkg install python 后可装'",
"系统" to "uname -a",
"装东西" to "pkg install -y python",
).forEach { (label, cmd) ->
AssistChip(
onClick = { run(cmd) },
label = { Text(label, fontSize = 12.sp, color = Color(0xFFD7DAE0)) },
modifier = Modifier.padding(end = 6.dp),
)
}
}
Row(
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
OutlinedTextField(
value = draft,
onValueChange = { draft = it },
modifier = Modifier.weight(1f),
placeholder = { Text("输入命令…", fontSize = 13.sp) },
shape = RoundedCornerShape(20.dp),
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { run(draft) }),
)
Spacer(Modifier.width(8.dp))
FilledIconButton(onClick = { run(draft) }, enabled = !busy) {
Icon(Icons.Filled.ArrowUpward, "执行")
}
}
}
}

View File

@@ -0,0 +1,214 @@
package com.doubao.lynxclone.ui
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* 豆包的视觉规范。
*
* 颜色和尺寸都是照着真机截图抠的 —— 之前直接用 Material3 默认值,
* 出来一股"原生 Android 模板"味,跟豆包一点都不像。
*/
object Doubao {
// ---- 主色与中性色 ----
val Blue = Color(0xFF2B7BFF)
val BluePressed = Color(0xFF1E63D6)
val TextPrimary = Color(0xFF1F2329)
val TextSecondary = Color(0xFF5A6472)
val TextTertiary = Color(0xFF9AA0A8)
val BubbleBot = Color(0xFFF2F3F5) // 助手气泡
val ChipBg = Color(0xFFFFFFFF) // 快捷入口
val CardBg = Color(0xFFF7F8FA)
val Divider = Color(0xFFEFF1F4)
val Border = Color(0xFFE5E7EB)
val HeroRing = Color(0xFFDCE9FF)
val Error = Color(0xFFE5484D)
val ErrorBg = Color(0xFFFDECEC)
/** 弹层背后的遮罩 */
val Scrim = Color(0x66000000)
// ---- 深色(真机深色模式下看截图对着调)----
val DarkBg = Color(0xFF101216)
val DarkSurface = Color(0xFF1A1D23)
val DarkBubble = Color(0xFF262A31)
val DarkText = Color(0xFFE8EAED)
val DarkTextSecondary = Color(0xFFA8AFBA)
val DarkBorder = Color(0xFF2E333B)
val DarkHeroRing = Color(0xFF1E355C)
}
/** 当前是不是深色主题(跟随系统) */
@Composable
fun isDark(): Boolean = androidx.compose.foundation.isSystemInDarkTheme()
@Composable
fun doubaoBg() = if (isDark()) Doubao.DarkBg else Color.White
@Composable
fun doubaoSurface() = if (isDark()) Doubao.DarkSurface else Color.White
@Composable
fun doubaoText() = if (isDark()) Doubao.DarkText else Doubao.TextPrimary
@Composable
fun doubaoTextSecondary() = if (isDark()) Doubao.DarkTextSecondary else Doubao.TextSecondary
@Composable
fun doubaoBubble() = if (isDark()) Doubao.DarkBubble else Doubao.BubbleBot
@Composable
fun doubaoBorder() = if (isDark()) Doubao.DarkBorder else Doubao.Border
@Composable
fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg
@Composable
fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing
/* ------------------------------ 动画 ------------------------------ */
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
@Composable
fun AppearOnce(
modifier: Modifier = Modifier,
offsetY: Dp = 14.dp,
durationMs: Int = 260,
content: @Composable () -> Unit,
) {
var shown by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { shown = true }
val progress by animateFloatAsState(
targetValue = if (shown) 1f else 0f,
animationSpec = tween(durationMs, easing = FastOutSlowInEasing),
label = "appear",
)
Box(
modifier.graphicsLayer {
alpha = progress
translationY = (1f - progress) * offsetY.toPx()
},
) { content() }
}
/** 按下去缩一下(按钮用) */
@Composable
fun pressScale(pressed: Boolean, to: Float = 0.94f): Float {
val scale by animateFloatAsState(
targetValue = if (pressed) to else 1f,
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
label = "press",
)
return scale
}
/** 「正在输入」的三个跳动小点 */
@Composable
fun TypingDots(color: Color = Doubao.TextTertiary, dot: Dp = 6.dp) {
val transition = rememberInfiniteTransition(label = "typing")
Row(verticalAlignment = Alignment.CenterVertically) {
repeat(3) { index ->
val alpha by transition.animateFloat(
initialValue = 0.25f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(520, easing = LinearEasing),
repeatMode = RepeatMode.Reverse,
// 依次错开,看着像波浪
initialStartOffset = StartOffset(index * 130),
),
label = "dot$index",
)
Box(
Modifier
.padding(end = 4.dp)
.size(dot)
.graphicsLayer { this.alpha = alpha }
.clip(CircleShape)
.background(color),
)
}
}
}
/* ------------------------------ 小部件 ------------------------------ */
/** 顶部/输入框上方的白底描边胶囊按钮(快捷入口、功能键) */
@Composable
fun DoubaoPill(
text: String? = null,
icon: ImageVector? = null,
onClick: () -> Unit,
modifier: Modifier = Modifier,
height: Dp = 40.dp,
) {
Box(
modifier
.height(height)
.clip(RoundedCornerShape(height / 2))
.background(doubaoSurface())
.border(1.dp, doubaoBorder(), RoundedCornerShape(height / 2))
.clickable(onClick = onClick)
.padding(horizontal = 16.dp),
contentAlignment = Alignment.Center,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
if (icon != null) {
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(16.dp))
if (text != null) Spacer(Modifier.width(5.dp))
}
if (text != null) {
Text(text, fontSize = 14.sp, color = doubaoText())
}
}
}
}
/**
* 圆形小图标按钮(消息下方的操作栏)。
* 注意 onClick 放最后一个参数:这样 `RoundIconButton(icon, "desc") { ... }` 的尾随 lambda 才落对地方。
*/
@Composable
fun RoundIconButton(
icon: ImageVector,
contentDescription: String,
size: Dp = 34.dp,
iconSize: Dp = 16.dp,
tint: Color? = null,
bg: Color? = null,
onClick: () -> Unit,
) {
Box(
Modifier
.size(size)
.clip(CircleShape)
.background(bg ?: doubaoCard())
.clickable(onClick = onClick),
contentAlignment = Alignment.Center,
) {
Icon(icon, contentDescription, tint = tint ?: doubaoTextSecondary(), modifier = Modifier.size(iconSize))
}
}
/** 分区标题(抽屉里的"置顶/最近") */
@Composable
fun SectionLabel(text: String, modifier: Modifier = Modifier) {
Text(
text,
modifier = modifier,
fontSize = 12.sp,
color = doubaoTextSecondary(),
fontWeight = FontWeight.Normal,
)
}

View File

@@ -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))
}
}
}
}

View File

@@ -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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,413 @@
package com.doubao.lynxclone.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.doubao.lynxclone.data.PythonTool
import org.json.JSONObject
/** 成功色的绿:主题色板里没有 success 槽位,单独定一个,别硬套 primary */
private val SuccessGreen = Color(0xFF3AA76D)
/**
* 技能 · 连接器页(对应旧版 Lynx 的 Skills.tsx)。三块:工具权限 / Python 工具 / MCP 服务。
*
* 几个刻意的做法:
*
* 1. **安全模式先存本地再点「应用」**。勾选白名单是个多步操作,每次点一下都发请求
* 等于把内核的 security 改了 N 次(中间态还可能是"限制模式 + 空白名单",
* 那一瞬间模型什么工具都用不了)。所以照旧版:本地改 draft,点应用才落盘。
*
* 2. **试运行参数走弹窗**而不是每行内嵌一个输入框。手机上内嵌输入框会把列表撑得很高,
* 还容易误触;弹窗一次只服务一个工具,焦点清楚。
*
* 3. **「重新连接」= 拿当前编辑器里的文本再存一次**。KernelClient 有 reconnectMcp(),
* 但 AppViewModel 没把它暴露出来(那是别人的文件,不动);而内核的
* PUT /api/mcp/config 本身就是"写盘 → disconnect_all → connect_all_enabled",
* 所以存一次当前文本 = 重连一次。副作用只是把同一份配置重写了一遍,没有风险。
*/
@Composable
fun SkillsScreen(vm: AppViewModel) {
val saved = vm.settings.security
var mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) }
var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) }
var runTarget by remember { mutableStateOf<PythonTool?>(null) }
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
val toolResults = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
var running by remember { mutableStateOf("") }
val savedMcpText = vm.state.mcpConfigText
val mcpText = remember { mutableStateOf(savedMcpText) }
var busy by remember { mutableStateOf("") }
var mcpMessage by remember { mutableStateOf("") }
// 内核那边配置变了(保存成功会刷新 state、或者别人改了文件后点刷新),
// 编辑器跟着走一遍;否则界面会一直显示旧文本,用户以为没保存上。
LaunchedEffect(savedMcpText) {
if (savedMcpText.isNotBlank()) mcpText.value = savedMcpText
}
Column(Modifier.fillMaxSize()) {
ScreenHeader("技能 · 连接器", onBack = { vm.screen = Screen.Chat }) {
// 右上角的刷新:内核里刚放进去的 *.py / MCP 状态,点一下就能重新发现
TextButton(onClick = { vm.refresh() }) { Text("刷新", fontSize = 13.sp) }
}
Column(
Modifier
.weight(1f)
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.imePadding()
.padding(horizontal = 14.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Spacer(Modifier.height(2.dp))
/* ==================== ① 工具权限 ==================== */
SettingsCard("工具权限") {
SegmentedOptions(
options = listOf("open" to "完全开放", "restricted" to "限制模式"),
selected = mode,
onSelect = { mode = it },
)
FormHint(
if (mode == "open") {
"完全开放:${vm.state.toolNames.size} 个工具都交给模型自由调用。"
} else {
"限制模式:只有勾选的工具可用,其余即使模型点名也会被拦下。已选 ${allow.size} 个。"
},
)
if (mode == "restricted") {
Spacer(Modifier.height(10.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
TextButton(onClick = { allow = vm.state.suggestedAllow.toSet() }) {
Text("只勾只读工具", fontSize = 13.sp)
}
TextButton(onClick = { allow = emptySet() }) {
Text("全部取消", fontSize = 13.sp)
}
}
if (vm.state.toolNames.isEmpty()) {
FormHint("内核还没上报工具名。先去「设置」确认工具目录,或者放一个 *.py 进 tools 目录。")
}
vm.state.toolNames.forEach { name ->
ToolAllowRow(
name = name,
checked = name in allow,
readOnly = name in vm.state.suggestedAllow,
onToggle = { on ->
allow = if (on) allow + name else allow - name
},
)
}
}
Spacer(Modifier.height(12.dp))
Button(
onClick = { vm.saveSecurity(mode, allow.toList()) },
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(24.dp),
contentPadding = PaddingValues(vertical = 12.dp),
) {
Text("应用权限设置", fontSize = 15.sp)
}
}
/* ==================== ② Python 工具 ==================== */
SettingsCard("Python 工具 · ${vm.state.tools.size} 个") {
if (vm.state.tools.isEmpty()) {
FormHint("没有发现工具。往 tools 目录里放一个 *.py,用 _protocol 暴露即可。")
}
vm.state.tools.forEach { tool ->
ToolItem(
tool = tool,
running = running == tool.name,
result = toolResults.value[tool.name].orEmpty(),
onRun = { runTarget = tool },
)
}
FormHint("试运行会真的执行这个工具(不受安全模式限制,因为是你手点的)。")
}
/* ==================== ③ MCP 服务 ==================== */
SettingsCard("MCP 服务") {
if (vm.state.mcp.isEmpty()) {
FormHint("还没有配置 MCP 服务。在下面的原始 JSON 里加一条就能接上。")
}
vm.state.mcp.forEach { server ->
Row(
Modifier.fillMaxWidth().padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(server.name, fontSize = 14.sp, fontWeight = FontWeight.Medium)
Spacer(Modifier.width(8.dp))
StatusBadge(server.connected)
}
Text(
buildString {
append(server.transport)
if (server.target.isNotBlank()) append(" · ${server.target}")
append(" · ${server.toolCount} 个工具")
},
fontSize = 11.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (server.error.isNotBlank()) {
Text(server.error, fontSize = 11.sp, color = MaterialTheme.colorScheme.error)
}
}
}
}
Spacer(Modifier.height(10.dp))
SectionTitle("原始 JSON")
FormField(
value = mcpText.value,
onValue = { mcpText.value = it },
placeholder = """{"servers":[]}""",
singleLine = false,
minLines = 6,
)
FormHint("支持 stdio / http / sse;路径里可以写 \${DOUBAO_DATA} 之类的占位符。")
Spacer(Modifier.height(12.dp))
Button(
onClick = {
busy = "save"
vm.saveMcpConfig(mcpText.value) { ok, msg ->
busy = ""
mcpMessage = if (ok) msg else "保存失败:$msg"
}
},
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(24.dp),
contentPadding = PaddingValues(vertical = 12.dp),
enabled = busy == "",
) {
Text(if (busy == "save") "保存中…" else "保存并重连", fontSize = 15.sp)
}
Spacer(Modifier.height(6.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
TextButton(
onClick = {
busy = "reconnect"
vm.saveMcpConfig(mcpText.value) { ok, msg ->
busy = ""
mcpMessage = if (ok) "已重连:$msg" else "重连失败:$msg"
}
},
enabled = busy == "",
) {
Text(if (busy == "reconnect") "重连中…" else "重新连接", fontSize = 13.sp)
}
TextButton(onClick = { mcpText.value = vm.state.mcpConfigText }) {
Text("重新读取", fontSize = 13.sp)
}
}
if (mcpMessage.isNotBlank()) {
ResultBox(mcpMessage)
}
}
Spacer(Modifier.height(20.dp))
}
}
/* 试运行参数的输入弹窗 */
runTarget?.let { tool ->
ToolRunDialog(
tool = tool,
initialArgs = toolArgs.value[tool.name].orEmpty(),
onDismiss = { runTarget = null },
onRun = { json ->
toolArgs.value = toolArgs.value + (tool.name to json)
runTarget = null
running = tool.name
val args = runCatching { JSONObject(json.ifBlank { "{}" }) }.getOrNull()
if (args == null) {
running = ""
toolResults.value = toolResults.value + (tool.name to "参数不是合法 JSON,请检查括号和引号。")
return@ToolRunDialog
}
vm.runTool(tool.name, args) { ok, text ->
running = ""
toolResults.value = toolResults.value + (
tool.name to if (ok) "返回:${preview(text)}" else "调用失败:$text"
)
}
},
)
}
}
/* ------------------------------ 零件 ------------------------------ */
@Composable
private fun ToolAllowRow(name: String, checked: Boolean, readOnly: Boolean, onToggle: (Boolean) -> Unit) {
Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(checked = checked, onCheckedChange = onToggle)
Text(name, fontSize = 13.sp, modifier = Modifier.weight(1f))
// 「只读」标签来自内核对工具名/描述的判断(suggestedAllow),点它等价于点行本身
if (readOnly) {
Surface(
shape = RoundedCornerShape(6.dp),
color = MaterialTheme.colorScheme.primaryContainer,
) {
Text(
"只读",
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
fontSize = 10.sp,
color = MaterialTheme.colorScheme.onPrimaryContainer,
)
}
}
}
}
@Composable
private fun ToolItem(tool: PythonTool, running: Boolean, result: String, onRun: () -> Unit) {
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Text(tool.name, fontSize = 14.sp, fontWeight = FontWeight.Medium)
if (tool.description.isNotBlank()) {
Text(tool.description, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text(tool.file, fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
TextButton(onClick = onRun, enabled = !running) {
Icon(Icons.Filled.PlayArrow, null, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(4.dp))
Text(if (running) "执行中…" else "试运行", fontSize = 13.sp)
}
if (result.isNotBlank()) ResultBox(result)
}
}
@Composable
private fun StatusBadge(connected: Boolean) {
val color = if (connected) SuccessGreen else MaterialTheme.colorScheme.onSurfaceVariant
Box(
Modifier
.clip(CircleShape)
.background(color.copy(alpha = 0.14f))
.padding(horizontal = 6.dp, vertical = 2.dp),
) {
Text(
if (connected) "已连接" else "未连接",
fontSize = 10.sp,
color = color,
)
}
}
@Composable
private fun ResultBox(text: String) {
Surface(
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
) {
Text(
text,
modifier = Modifier.padding(10.dp),
fontSize = 12.sp,
lineHeight = 18.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
/**
* 试运行参数弹窗。
* 空输入按 {} 处理 —— 很多工具没有必填参数,逼用户手打一对大括号很烦。
*/
@Composable
private fun ToolRunDialog(
tool: PythonTool,
initialArgs: String,
onDismiss: () -> Unit,
onRun: (String) -> Unit,
) {
var json by remember { mutableStateOf(initialArgs) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("试运行 ${tool.name}", fontSize = 16.sp) },
text = {
Column {
if (tool.description.isNotBlank()) {
Text(tool.description, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(Modifier.height(8.dp))
}
OutlinedTextField(
value = json,
onValueChange = { json = it },
modifier = Modifier.fillMaxWidth().height(130.dp),
placeholder = { Text("""参数 JSON,例如 {"expression":"1+1"}""", fontSize = 12.sp) },
textStyle = TextStyle(fontSize = 13.sp),
)
Text(
"留空 = 不带参数执行",
fontSize = 11.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
confirmButton = { TextButton(onClick = { onRun(json) }) { Text("试运行") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
)
}
/** 工具返回可能很长(比如抓了一整页网页),列表里只给预览 */
private fun preview(value: String): String =
if (value.length > 600) value.take(600) + "…" else value

View File

@@ -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),
)
}
}
}
}
}
}

View File

@@ -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,
)
}

View File

@@ -0,0 +1,108 @@
package com.termux.terminal;
/** A circular byte buffer allowing one producer and one consumer thread. */
final class ByteQueue {
private final byte[] mBuffer;
private int mHead;
private int mStoredBytes;
private boolean mOpen = true;
public ByteQueue(int size) {
mBuffer = new byte[size];
}
public synchronized void close() {
mOpen = false;
notify();
}
public synchronized int read(byte[] buffer, boolean block) {
while (mStoredBytes == 0 && mOpen) {
if (block) {
try {
wait();
} catch (InterruptedException e) {
// Ignore.
}
} else {
return 0;
}
}
if (!mOpen) return -1;
int totalRead = 0;
int bufferLength = mBuffer.length;
boolean wasFull = bufferLength == mStoredBytes;
int length = buffer.length;
int offset = 0;
while (length > 0 && mStoredBytes > 0) {
int oneRun = Math.min(bufferLength - mHead, mStoredBytes);
int bytesToCopy = Math.min(length, oneRun);
System.arraycopy(mBuffer, mHead, buffer, offset, bytesToCopy);
mHead += bytesToCopy;
if (mHead >= bufferLength) mHead = 0;
mStoredBytes -= bytesToCopy;
length -= bytesToCopy;
offset += bytesToCopy;
totalRead += bytesToCopy;
}
if (wasFull) notify();
return totalRead;
}
/**
* Attempt to write the specified portion of the provided buffer to the queue.
* <p/>
* Returns whether the output was totally written, false if it was closed before.
*/
public boolean write(byte[] buffer, int offset, int lengthToWrite) {
if (lengthToWrite + offset > buffer.length) {
throw new IllegalArgumentException("length + offset > buffer.length");
} else if (lengthToWrite <= 0) {
throw new IllegalArgumentException("length <= 0");
}
final int bufferLength = mBuffer.length;
synchronized (this) {
while (lengthToWrite > 0) {
while (bufferLength == mStoredBytes && mOpen) {
try {
wait();
} catch (InterruptedException e) {
// Ignore.
}
}
if (!mOpen) return false;
final boolean wasEmpty = mStoredBytes == 0;
int bytesToWriteBeforeWaiting = Math.min(lengthToWrite, bufferLength - mStoredBytes);
lengthToWrite -= bytesToWriteBeforeWaiting;
while (bytesToWriteBeforeWaiting > 0) {
int tail = mHead + mStoredBytes;
int oneRun;
if (tail >= bufferLength) {
// Buffer: [.............]
// ________________H_______T
// =>
// Buffer: [.............]
// ___________T____H
// onRun= _____----_
tail = tail - bufferLength;
oneRun = mHead - tail;
} else {
oneRun = bufferLength - tail;
}
int bytesToCopy = Math.min(oneRun, bytesToWriteBeforeWaiting);
System.arraycopy(buffer, offset, mBuffer, tail, bytesToCopy);
offset += bytesToCopy;
bytesToWriteBeforeWaiting -= bytesToCopy;
mStoredBytes += bytesToCopy;
}
if (wasEmpty) notify();
}
}
return true;
}
}

View File

@@ -0,0 +1,41 @@
package com.termux.terminal;
/**
* Native methods for creating and managing pseudoterminal subprocesses. C code is in jni/termux.c.
*/
final class JNI {
static {
System.loadLibrary("termux");
}
/**
* Create a subprocess. Differs from {@link ProcessBuilder} in that a pseudoterminal is used to communicate with the
* subprocess.
* <p/>
* Callers are responsible for calling {@link #close(int)} on the returned file descriptor.
*
* @param cmd The command to execute
* @param cwd The current working directory for the executed command
* @param args An array of arguments to the command
* @param envVars An array of strings of the form "VAR=value" to be added to the environment of the process
* @param processId A one-element array to which the process ID of the started process will be written.
* @return the file descriptor resulting from opening /dev/ptmx master device. The sub process will have opened the
* slave device counterpart (/dev/pts/$N) and have it as stdint, stdout and stderr.
*/
public static native int createSubprocess(String cmd, String cwd, String[] args, String[] envVars, int[] processId, int rows, int columns, int cellWidth, int cellHeight);
/** Set the window size for a given pty, which allows connected programs to learn how large their screen is. */
public static native void setPtyWindowSize(int fd, int rows, int cols, int cellWidth, int cellHeight);
/**
* Causes the calling thread to wait for the process associated with the receiver to finish executing.
*
* @return if >= 0, the exit status of the process. If < 0, the signal causing the process to stop negated.
*/
public static native int waitFor(int processId);
/** Close a file descriptor through the close(2) system call. */
public static native void close(int fileDescriptor);
}

View File

@@ -0,0 +1,373 @@
package com.termux.terminal;
import java.util.HashMap;
import java.util.Map;
import static android.view.KeyEvent.KEYCODE_BACK;
import static android.view.KeyEvent.KEYCODE_BREAK;
import static android.view.KeyEvent.KEYCODE_DEL;
import static android.view.KeyEvent.KEYCODE_DPAD_CENTER;
import static android.view.KeyEvent.KEYCODE_DPAD_DOWN;
import static android.view.KeyEvent.KEYCODE_DPAD_LEFT;
import static android.view.KeyEvent.KEYCODE_DPAD_RIGHT;
import static android.view.KeyEvent.KEYCODE_DPAD_UP;
import static android.view.KeyEvent.KEYCODE_ENTER;
import static android.view.KeyEvent.KEYCODE_ESCAPE;
import static android.view.KeyEvent.KEYCODE_F1;
import static android.view.KeyEvent.KEYCODE_F10;
import static android.view.KeyEvent.KEYCODE_F11;
import static android.view.KeyEvent.KEYCODE_F12;
import static android.view.KeyEvent.KEYCODE_F2;
import static android.view.KeyEvent.KEYCODE_F3;
import static android.view.KeyEvent.KEYCODE_F4;
import static android.view.KeyEvent.KEYCODE_F5;
import static android.view.KeyEvent.KEYCODE_F6;
import static android.view.KeyEvent.KEYCODE_F7;
import static android.view.KeyEvent.KEYCODE_F8;
import static android.view.KeyEvent.KEYCODE_F9;
import static android.view.KeyEvent.KEYCODE_FORWARD_DEL;
import static android.view.KeyEvent.KEYCODE_INSERT;
import static android.view.KeyEvent.KEYCODE_MOVE_END;
import static android.view.KeyEvent.KEYCODE_MOVE_HOME;
import static android.view.KeyEvent.KEYCODE_NUMPAD_0;
import static android.view.KeyEvent.KEYCODE_NUMPAD_1;
import static android.view.KeyEvent.KEYCODE_NUMPAD_2;
import static android.view.KeyEvent.KEYCODE_NUMPAD_3;
import static android.view.KeyEvent.KEYCODE_NUMPAD_4;
import static android.view.KeyEvent.KEYCODE_NUMPAD_5;
import static android.view.KeyEvent.KEYCODE_NUMPAD_6;
import static android.view.KeyEvent.KEYCODE_NUMPAD_7;
import static android.view.KeyEvent.KEYCODE_NUMPAD_8;
import static android.view.KeyEvent.KEYCODE_NUMPAD_9;
import static android.view.KeyEvent.KEYCODE_NUMPAD_ADD;
import static android.view.KeyEvent.KEYCODE_NUMPAD_COMMA;
import static android.view.KeyEvent.KEYCODE_NUMPAD_DIVIDE;
import static android.view.KeyEvent.KEYCODE_NUMPAD_DOT;
import static android.view.KeyEvent.KEYCODE_NUMPAD_ENTER;
import static android.view.KeyEvent.KEYCODE_NUMPAD_EQUALS;
import static android.view.KeyEvent.KEYCODE_NUMPAD_MULTIPLY;
import static android.view.KeyEvent.KEYCODE_NUMPAD_SUBTRACT;
import static android.view.KeyEvent.KEYCODE_NUM_LOCK;
import static android.view.KeyEvent.KEYCODE_PAGE_DOWN;
import static android.view.KeyEvent.KEYCODE_PAGE_UP;
import static android.view.KeyEvent.KEYCODE_SPACE;
import static android.view.KeyEvent.KEYCODE_SYSRQ;
import static android.view.KeyEvent.KEYCODE_TAB;
public final class KeyHandler {
public static final int KEYMOD_ALT = 0x80000000;
public static final int KEYMOD_CTRL = 0x40000000;
public static final int KEYMOD_SHIFT = 0x20000000;
public static final int KEYMOD_NUM_LOCK = 0x10000000;
private static final Map<String, Integer> TERMCAP_TO_KEYCODE = new HashMap<>();
static {
// terminfo: http://pubs.opengroup.org/onlinepubs/7990989799/xcurses/terminfo.html
// termcap: http://man7.org/linux/man-pages/man5/termcap.5.html
TERMCAP_TO_KEYCODE.put("%i", KEYMOD_SHIFT | KEYCODE_DPAD_RIGHT);
TERMCAP_TO_KEYCODE.put("#2", KEYMOD_SHIFT | KEYCODE_MOVE_HOME); // Shifted home
TERMCAP_TO_KEYCODE.put("#4", KEYMOD_SHIFT | KEYCODE_DPAD_LEFT);
TERMCAP_TO_KEYCODE.put("*7", KEYMOD_SHIFT | KEYCODE_MOVE_END); // Shifted end key
TERMCAP_TO_KEYCODE.put("k1", KEYCODE_F1);
TERMCAP_TO_KEYCODE.put("k2", KEYCODE_F2);
TERMCAP_TO_KEYCODE.put("k3", KEYCODE_F3);
TERMCAP_TO_KEYCODE.put("k4", KEYCODE_F4);
TERMCAP_TO_KEYCODE.put("k5", KEYCODE_F5);
TERMCAP_TO_KEYCODE.put("k6", KEYCODE_F6);
TERMCAP_TO_KEYCODE.put("k7", KEYCODE_F7);
TERMCAP_TO_KEYCODE.put("k8", KEYCODE_F8);
TERMCAP_TO_KEYCODE.put("k9", KEYCODE_F9);
TERMCAP_TO_KEYCODE.put("k;", KEYCODE_F10);
TERMCAP_TO_KEYCODE.put("F1", KEYCODE_F11);
TERMCAP_TO_KEYCODE.put("F2", KEYCODE_F12);
TERMCAP_TO_KEYCODE.put("F3", KEYMOD_SHIFT | KEYCODE_F1);
TERMCAP_TO_KEYCODE.put("F4", KEYMOD_SHIFT | KEYCODE_F2);
TERMCAP_TO_KEYCODE.put("F5", KEYMOD_SHIFT | KEYCODE_F3);
TERMCAP_TO_KEYCODE.put("F6", KEYMOD_SHIFT | KEYCODE_F4);
TERMCAP_TO_KEYCODE.put("F7", KEYMOD_SHIFT | KEYCODE_F5);
TERMCAP_TO_KEYCODE.put("F8", KEYMOD_SHIFT | KEYCODE_F6);
TERMCAP_TO_KEYCODE.put("F9", KEYMOD_SHIFT | KEYCODE_F7);
TERMCAP_TO_KEYCODE.put("FA", KEYMOD_SHIFT | KEYCODE_F8);
TERMCAP_TO_KEYCODE.put("FB", KEYMOD_SHIFT | KEYCODE_F9);
TERMCAP_TO_KEYCODE.put("FC", KEYMOD_SHIFT | KEYCODE_F10);
TERMCAP_TO_KEYCODE.put("FD", KEYMOD_SHIFT | KEYCODE_F11);
TERMCAP_TO_KEYCODE.put("FE", KEYMOD_SHIFT | KEYCODE_F12);
TERMCAP_TO_KEYCODE.put("kb", KEYCODE_DEL); // backspace key
TERMCAP_TO_KEYCODE.put("kd", KEYCODE_DPAD_DOWN); // terminfo=kcud1, down-arrow key
TERMCAP_TO_KEYCODE.put("kh", KEYCODE_MOVE_HOME);
TERMCAP_TO_KEYCODE.put("kl", KEYCODE_DPAD_LEFT);
TERMCAP_TO_KEYCODE.put("kr", KEYCODE_DPAD_RIGHT);
// K1=Upper left of keypad:
// t_K1 <kHome> keypad home key
// t_K3 <kPageUp> keypad page-up key
// t_K4 <kEnd> keypad end key
// t_K5 <kPageDown> keypad page-down key
TERMCAP_TO_KEYCODE.put("K1", KEYCODE_MOVE_HOME);
TERMCAP_TO_KEYCODE.put("K3", KEYCODE_PAGE_UP);
TERMCAP_TO_KEYCODE.put("K4", KEYCODE_MOVE_END);
TERMCAP_TO_KEYCODE.put("K5", KEYCODE_PAGE_DOWN);
TERMCAP_TO_KEYCODE.put("ku", KEYCODE_DPAD_UP);
TERMCAP_TO_KEYCODE.put("kB", KEYMOD_SHIFT | KEYCODE_TAB); // termcap=kB, terminfo=kcbt: Back-tab
TERMCAP_TO_KEYCODE.put("kD", KEYCODE_FORWARD_DEL); // terminfo=kdch1, delete-character key
TERMCAP_TO_KEYCODE.put("kDN", KEYMOD_SHIFT | KEYCODE_DPAD_DOWN); // non-standard shifted arrow down
TERMCAP_TO_KEYCODE.put("kF", KEYMOD_SHIFT | KEYCODE_DPAD_DOWN); // terminfo=kind, scroll-forward key
TERMCAP_TO_KEYCODE.put("kI", KEYCODE_INSERT);
TERMCAP_TO_KEYCODE.put("kN", KEYCODE_PAGE_UP);
TERMCAP_TO_KEYCODE.put("kP", KEYCODE_PAGE_DOWN);
TERMCAP_TO_KEYCODE.put("kR", KEYMOD_SHIFT | KEYCODE_DPAD_UP); // terminfo=kri, scroll-backward key
TERMCAP_TO_KEYCODE.put("kUP", KEYMOD_SHIFT | KEYCODE_DPAD_UP); // non-standard shifted up
TERMCAP_TO_KEYCODE.put("@7", KEYCODE_MOVE_END);
TERMCAP_TO_KEYCODE.put("@8", KEYCODE_NUMPAD_ENTER);
}
static String getCodeFromTermcap(String termcap, boolean cursorKeysApplication, boolean keypadApplication) {
Integer keyCodeAndMod = TERMCAP_TO_KEYCODE.get(termcap);
if (keyCodeAndMod == null) return null;
int keyCode = keyCodeAndMod;
int keyMod = 0;
if ((keyCode & KEYMOD_SHIFT) != 0) {
keyMod |= KEYMOD_SHIFT;
keyCode &= ~KEYMOD_SHIFT;
}
if ((keyCode & KEYMOD_CTRL) != 0) {
keyMod |= KEYMOD_CTRL;
keyCode &= ~KEYMOD_CTRL;
}
if ((keyCode & KEYMOD_ALT) != 0) {
keyMod |= KEYMOD_ALT;
keyCode &= ~KEYMOD_ALT;
}
if ((keyCode & KEYMOD_NUM_LOCK) != 0) {
keyMod |= KEYMOD_NUM_LOCK;
keyCode &= ~KEYMOD_NUM_LOCK;
}
return getCode(keyCode, keyMod, cursorKeysApplication, keypadApplication);
}
public static String getCode(int keyCode, int keyMode, boolean cursorApp, boolean keypadApplication) {
boolean numLockOn = (keyMode & KEYMOD_NUM_LOCK) != 0;
keyMode &= ~KEYMOD_NUM_LOCK;
switch (keyCode) {
case KEYCODE_DPAD_CENTER:
return "\015";
case KEYCODE_DPAD_UP:
return (keyMode == 0) ? (cursorApp ? "\033OA" : "\033[A") : transformForModifiers("\033[1", keyMode, 'A');
case KEYCODE_DPAD_DOWN:
return (keyMode == 0) ? (cursorApp ? "\033OB" : "\033[B") : transformForModifiers("\033[1", keyMode, 'B');
case KEYCODE_DPAD_RIGHT:
return (keyMode == 0) ? (cursorApp ? "\033OC" : "\033[C") : transformForModifiers("\033[1", keyMode, 'C');
case KEYCODE_DPAD_LEFT:
return (keyMode == 0) ? (cursorApp ? "\033OD" : "\033[D") : transformForModifiers("\033[1", keyMode, 'D');
case KEYCODE_MOVE_HOME:
// Note that KEYCODE_HOME is handled by the system and never delivered to applications.
// On a Logitech k810 keyboard KEYCODE_MOVE_HOME is sent by FN+LeftArrow.
return (keyMode == 0) ? (cursorApp ? "\033OH" : "\033[H") : transformForModifiers("\033[1", keyMode, 'H');
case KEYCODE_MOVE_END:
return (keyMode == 0) ? (cursorApp ? "\033OF" : "\033[F") : transformForModifiers("\033[1", keyMode, 'F');
// An xterm can send function keys F1 to F4 in two modes: vt100 compatible or
// not. Because Vim may not know what the xterm is sending, both types of keys
// are recognized. The same happens for the <Home> and <End> keys.
// normal vt100 ~
// <F1> t_k1 <Esc>[11~ <xF1> <Esc>OP *<xF1>-xterm*
// <F2> t_k2 <Esc>[12~ <xF2> <Esc>OQ *<xF2>-xterm*
// <F3> t_k3 <Esc>[13~ <xF3> <Esc>OR *<xF3>-xterm*
// <F4> t_k4 <Esc>[14~ <xF4> <Esc>OS *<xF4>-xterm*
// <Home> t_kh <Esc>[7~ <xHome> <Esc>OH *<xHome>-xterm*
// <End> t_@7 <Esc>[4~ <xEnd> <Esc>OF *<xEnd>-xterm*
case KEYCODE_F1:
return (keyMode == 0) ? "\033OP" : transformForModifiers("\033[1", keyMode, 'P');
case KEYCODE_F2:
return (keyMode == 0) ? "\033OQ" : transformForModifiers("\033[1", keyMode, 'Q');
case KEYCODE_F3:
return (keyMode == 0) ? "\033OR" : transformForModifiers("\033[1", keyMode, 'R');
case KEYCODE_F4:
return (keyMode == 0) ? "\033OS" : transformForModifiers("\033[1", keyMode, 'S');
case KEYCODE_F5:
return transformForModifiers("\033[15", keyMode, '~');
case KEYCODE_F6:
return transformForModifiers("\033[17", keyMode, '~');
case KEYCODE_F7:
return transformForModifiers("\033[18", keyMode, '~');
case KEYCODE_F8:
return transformForModifiers("\033[19", keyMode, '~');
case KEYCODE_F9:
return transformForModifiers("\033[20", keyMode, '~');
case KEYCODE_F10:
return transformForModifiers("\033[21", keyMode, '~');
case KEYCODE_F11:
return transformForModifiers("\033[23", keyMode, '~');
case KEYCODE_F12:
return transformForModifiers("\033[24", keyMode, '~');
case KEYCODE_SYSRQ:
return "\033[32~"; // Sys Request / Print
// Is this Scroll lock? case Cancel: return "\033[33~";
case KEYCODE_BREAK:
return "\033[34~"; // Pause/Break
case KEYCODE_ESCAPE:
case KEYCODE_BACK:
return "\033";
case KEYCODE_INSERT:
return transformForModifiers("\033[2", keyMode, '~');
case KEYCODE_FORWARD_DEL:
return transformForModifiers("\033[3", keyMode, '~');
case KEYCODE_PAGE_UP:
return "\033[5~";
case KEYCODE_PAGE_DOWN:
return "\033[6~";
case KEYCODE_DEL:
String prefix = ((keyMode & KEYMOD_ALT) == 0) ? "" : "\033";
// Just do what xterm and gnome-terminal does:
return prefix + (((keyMode & KEYMOD_CTRL) == 0) ? "\u007F" : "\u0008");
case KEYCODE_NUM_LOCK:
if (keypadApplication) {
return "\033OP";
} else {
return null;
}
case KEYCODE_SPACE:
// If ctrl is not down, return null so that it goes through normal input processing (which may e.g. cause a
// combining accent to be written):
return ((keyMode & KEYMOD_CTRL) == 0) ? null : "\0";
case KEYCODE_TAB:
// This is back-tab when shifted:
return (keyMode & KEYMOD_SHIFT) == 0 ? "\011" : "\033[Z";
case KEYCODE_ENTER:
return ((keyMode & KEYMOD_ALT) == 0) ? "\r" : "\033\r";
case KEYCODE_NUMPAD_ENTER:
return keypadApplication ? transformForModifiers("\033O", keyMode, 'M') : "\n";
case KEYCODE_NUMPAD_MULTIPLY:
return keypadApplication ? transformForModifiers("\033O", keyMode, 'j') : "*";
case KEYCODE_NUMPAD_ADD:
return keypadApplication ? transformForModifiers("\033O", keyMode, 'k') : "+";
case KEYCODE_NUMPAD_COMMA:
return ",";
case KEYCODE_NUMPAD_DOT:
if (numLockOn) {
return keypadApplication ? "\033On" : ".";
} else {
// DELETE
return transformForModifiers("\033[3", keyMode, '~');
}
case KEYCODE_NUMPAD_SUBTRACT:
return keypadApplication ? transformForModifiers("\033O", keyMode, 'm') : "-";
case KEYCODE_NUMPAD_DIVIDE:
return keypadApplication ? transformForModifiers("\033O", keyMode, 'o') : "/";
case KEYCODE_NUMPAD_0:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 'p') : "0";
} else {
// INSERT
return transformForModifiers("\033[2", keyMode, '~');
}
case KEYCODE_NUMPAD_1:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 'q') : "1";
} else {
// END
return (keyMode == 0) ? (cursorApp ? "\033OF" : "\033[F") : transformForModifiers("\033[1", keyMode, 'F');
}
case KEYCODE_NUMPAD_2:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 'r') : "2";
} else {
// DOWN
return (keyMode == 0) ? (cursorApp ? "\033OB" : "\033[B") : transformForModifiers("\033[1", keyMode, 'B');
}
case KEYCODE_NUMPAD_3:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 's') : "3";
} else {
// PGDN
return "\033[6~";
}
case KEYCODE_NUMPAD_4:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 't') : "4";
} else {
// LEFT
return (keyMode == 0) ? (cursorApp ? "\033OD" : "\033[D") : transformForModifiers("\033[1", keyMode, 'D');
}
case KEYCODE_NUMPAD_5:
return keypadApplication ? transformForModifiers("\033O", keyMode, 'u') : "5";
case KEYCODE_NUMPAD_6:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 'v') : "6";
} else {
// RIGHT
return (keyMode == 0) ? (cursorApp ? "\033OC" : "\033[C") : transformForModifiers("\033[1", keyMode, 'C');
}
case KEYCODE_NUMPAD_7:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 'w') : "7";
} else {
// HOME
return (keyMode == 0) ? (cursorApp ? "\033OH" : "\033[H") : transformForModifiers("\033[1", keyMode, 'H');
}
case KEYCODE_NUMPAD_8:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 'x') : "8";
} else {
// UP
return (keyMode == 0) ? (cursorApp ? "\033OA" : "\033[A") : transformForModifiers("\033[1", keyMode, 'A');
}
case KEYCODE_NUMPAD_9:
if (numLockOn) {
return keypadApplication ? transformForModifiers("\033O", keyMode, 'y') : "9";
} else {
// PGUP
return "\033[5~";
}
case KEYCODE_NUMPAD_EQUALS:
return keypadApplication ? transformForModifiers("\033O", keyMode, 'X') : "=";
}
return null;
}
private static String transformForModifiers(String start, int keymod, char lastChar) {
int modifier;
switch (keymod) {
case KEYMOD_SHIFT:
modifier = 2;
break;
case KEYMOD_ALT:
modifier = 3;
break;
case (KEYMOD_SHIFT | KEYMOD_ALT):
modifier = 4;
break;
case KEYMOD_CTRL:
modifier = 5;
break;
case KEYMOD_SHIFT | KEYMOD_CTRL:
modifier = 6;
break;
case KEYMOD_ALT | KEYMOD_CTRL:
modifier = 7;
break;
case KEYMOD_SHIFT | KEYMOD_ALT | KEYMOD_CTRL:
modifier = 8;
break;
default:
return start + lastChar;
}
return start + (";" + modifier) + lastChar;
}
}

View File

@@ -0,0 +1,80 @@
package com.termux.terminal;
import android.util.Log;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class Logger {
public static void logError(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logError(logTag, message);
else
Log.e(logTag, message);
}
public static void logWarn(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logWarn(logTag, message);
else
Log.w(logTag, message);
}
public static void logInfo(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logInfo(logTag, message);
else
Log.i(logTag, message);
}
public static void logDebug(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logDebug(logTag, message);
else
Log.d(logTag, message);
}
public static void logVerbose(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logVerbose(logTag, message);
else
Log.v(logTag, message);
}
public static void logStackTraceWithMessage(TerminalSessionClient client, String tag, String message, Throwable throwable) {
logError(client, tag, getMessageAndStackTraceString(message, throwable));
}
public static String getMessageAndStackTraceString(String message, Throwable throwable) {
if (message == null && throwable == null)
return null;
else if (message != null && throwable != null)
return message + ":\n" + getStackTraceString(throwable);
else if (throwable == null)
return message;
else
return getStackTraceString(throwable);
}
public static String getStackTraceString(Throwable throwable) {
if (throwable == null) return null;
String stackTraceString = null;
try {
StringWriter errors = new StringWriter();
PrintWriter pw = new PrintWriter(errors);
throwable.printStackTrace(pw);
pw.close();
stackTraceString = errors.toString();
errors.close();
} catch (IOException e) {
e.printStackTrace();
}
return stackTraceString;
}
}

View File

@@ -0,0 +1,497 @@
package com.termux.terminal;
import java.util.Arrays;
/**
* A circular buffer of {@link TerminalRow}:s which keeps notes about what is visible on a logical screen and the scroll
* history.
* <p>
* See {@link #externalToInternalRow(int)} for how to map from logical screen rows to array indices.
*/
public final class TerminalBuffer {
TerminalRow[] mLines;
/** The length of {@link #mLines}. */
int mTotalRows;
/** The number of rows and columns visible on the screen. */
int mScreenRows, mColumns;
/** The number of rows kept in history. */
private int mActiveTranscriptRows = 0;
/** The index in the circular buffer where the visible screen starts. */
private int mScreenFirstRow = 0;
/**
* Create a transcript screen.
*
* @param columns the width of the screen in characters.
* @param totalRows the height of the entire text area, in rows of text.
* @param screenRows the height of just the screen, not including the transcript that holds lines that have scrolled off
* the top of the screen.
*/
public TerminalBuffer(int columns, int totalRows, int screenRows) {
mColumns = columns;
mTotalRows = totalRows;
mScreenRows = screenRows;
mLines = new TerminalRow[totalRows];
blockSet(0, 0, columns, screenRows, ' ', TextStyle.NORMAL);
}
public String getTranscriptText() {
return getSelectedText(0, -getActiveTranscriptRows(), mColumns, mScreenRows).trim();
}
public String getTranscriptTextWithoutJoinedLines() {
return getSelectedText(0, -getActiveTranscriptRows(), mColumns, mScreenRows, false).trim();
}
public String getTranscriptTextWithFullLinesJoined() {
return getSelectedText(0, -getActiveTranscriptRows(), mColumns, mScreenRows, true, true).trim();
}
public String getSelectedText(int selX1, int selY1, int selX2, int selY2) {
return getSelectedText(selX1, selY1, selX2, selY2, true);
}
public String getSelectedText(int selX1, int selY1, int selX2, int selY2, boolean joinBackLines) {
return getSelectedText(selX1, selY1, selX2, selY2, joinBackLines, false);
}
public String getSelectedText(int selX1, int selY1, int selX2, int selY2, boolean joinBackLines, boolean joinFullLines) {
final StringBuilder builder = new StringBuilder();
final int columns = mColumns;
if (selY1 < -getActiveTranscriptRows()) selY1 = -getActiveTranscriptRows();
if (selY2 >= mScreenRows) selY2 = mScreenRows - 1;
for (int row = selY1; row <= selY2; row++) {
int x1 = (row == selY1) ? selX1 : 0;
int x2;
if (row == selY2) {
x2 = selX2 + 1;
if (x2 > columns) x2 = columns;
} else {
x2 = columns;
}
TerminalRow lineObject = mLines[externalToInternalRow(row)];
int x1Index = lineObject.findStartOfColumn(x1);
int x2Index = (x2 < mColumns) ? lineObject.findStartOfColumn(x2) : lineObject.getSpaceUsed();
if (x2Index == x1Index) {
// Selected the start of a wide character.
x2Index = lineObject.findStartOfColumn(x2 + 1);
}
char[] line = lineObject.mText;
int lastPrintingCharIndex = -1;
int i;
boolean rowLineWrap = getLineWrap(row);
if (rowLineWrap && x2 == columns) {
// If the line was wrapped, we shouldn't lose trailing space:
lastPrintingCharIndex = x2Index - 1;
} else {
for (i = x1Index; i < x2Index; ++i) {
char c = line[i];
if (c != ' ') lastPrintingCharIndex = i;
}
}
int len = lastPrintingCharIndex - x1Index + 1;
if (lastPrintingCharIndex != -1 && len > 0)
builder.append(line, x1Index, len);
boolean lineFillsWidth = lastPrintingCharIndex == x2Index - 1;
if ((!joinBackLines || !rowLineWrap) && (!joinFullLines || !lineFillsWidth)
&& row < selY2 && row < mScreenRows - 1) builder.append('\n');
}
return builder.toString();
}
public String getWordAtLocation(int x, int y) {
// Set y1 and y2 to the lines where the wrapped line starts and ends.
// I.e. if a line that is wrapped to 3 lines starts at line 4, and this
// is called with y=5, then y1 would be set to 4 and y2 would be set to 6.
int y1 = y;
int y2 = y;
while (y1 > 0 && !getSelectedText(0, y1 - 1, mColumns, y, true, true).contains("\n")) {
y1--;
}
while (y2 < mScreenRows && !getSelectedText(0, y, mColumns, y2 + 1, true, true).contains("\n")) {
y2++;
}
// Get the text for the whole wrapped line
String text = getSelectedText(0, y1, mColumns, y2, true, true);
// The index of x in text
int textOffset = (y - y1) * mColumns + x;
if (textOffset >= text.length()) {
// The click was to the right of the last word on the line, so
// there's no word to return
return "";
}
// Set x1 and x2 to the indices of the last space before x and the
// first space after x in text respectively
int x1 = text.lastIndexOf(' ', textOffset);
int x2 = text.indexOf(' ', textOffset);
if (x2 == -1) {
x2 = text.length();
}
if (x1 == x2) {
// The click was on a space, so there's no word to return
return "";
}
return text.substring(x1 + 1, x2);
}
public int getActiveTranscriptRows() {
return mActiveTranscriptRows;
}
public int getActiveRows() {
return mActiveTranscriptRows + mScreenRows;
}
/**
* Convert a row value from the public external coordinate system to our internal private coordinate system.
*
* <pre>
* - External coordinate system: -mActiveTranscriptRows to mScreenRows-1, with the screen being 0..mScreenRows-1.
* - Internal coordinate system: the mScreenRows lines starting at mScreenFirstRow comprise the screen, while the
* mActiveTranscriptRows lines ending at mScreenFirstRow-1 form the transcript (as a circular buffer).
*
* External ↔ Internal:
*
* [ ... ] [ ... ]
* [ -mActiveTranscriptRows ] [ mScreenFirstRow - mActiveTranscriptRows ]
* [ ... ] [ ... ]
* [ 0 (visible screen starts here) ] ↔ [ mScreenFirstRow ]
* [ ... ] [ ... ]
* [ mScreenRows-1 ] [ mScreenFirstRow + mScreenRows-1 ]
* </pre>
*
* @param externalRow a row in the external coordinate system.
* @return The row corresponding to the input argument in the private coordinate system.
*/
public int externalToInternalRow(int externalRow) {
if (externalRow < -mActiveTranscriptRows || externalRow > mScreenRows)
throw new IllegalArgumentException("extRow=" + externalRow + ", mScreenRows=" + mScreenRows + ", mActiveTranscriptRows=" + mActiveTranscriptRows);
final int internalRow = mScreenFirstRow + externalRow;
return (internalRow < 0) ? (mTotalRows + internalRow) : (internalRow % mTotalRows);
}
public void setLineWrap(int row) {
mLines[externalToInternalRow(row)].mLineWrap = true;
}
public boolean getLineWrap(int row) {
return mLines[externalToInternalRow(row)].mLineWrap;
}
public void clearLineWrap(int row) {
mLines[externalToInternalRow(row)].mLineWrap = false;
}
/**
* Resize the screen which this transcript backs. Currently, this only works if the number of columns does not
* change or the rows expand (that is, it only works when shrinking the number of rows).
*
* @param newColumns The number of columns the screen should have.
* @param newRows The number of rows the screen should have.
* @param cursor An int[2] containing the (column, row) cursor location.
*/
public void resize(int newColumns, int newRows, int newTotalRows, int[] cursor, long currentStyle, boolean altScreen) {
// newRows > mTotalRows should not normally happen since mTotalRows is TRANSCRIPT_ROWS (10000):
if (newColumns == mColumns && newRows <= mTotalRows) {
// Fast resize where just the rows changed.
int shiftDownOfTopRow = mScreenRows - newRows;
if (shiftDownOfTopRow > 0 && shiftDownOfTopRow < mScreenRows) {
// Shrinking. Check if we can skip blank rows at bottom below cursor.
for (int i = mScreenRows - 1; i > 0; i--) {
if (cursor[1] >= i) break;
int r = externalToInternalRow(i);
if (mLines[r] == null || mLines[r].isBlank()) {
if (--shiftDownOfTopRow == 0) break;
}
}
} else if (shiftDownOfTopRow < 0) {
// Negative shift down = expanding. Only move screen up if there is transcript to show:
int actualShift = Math.max(shiftDownOfTopRow, -mActiveTranscriptRows);
if (shiftDownOfTopRow != actualShift) {
// The new lines revealed by the resizing are not all from the transcript. Blank the below ones.
for (int i = 0; i < actualShift - shiftDownOfTopRow; i++)
allocateFullLineIfNecessary((mScreenFirstRow + mScreenRows + i) % mTotalRows).clear(currentStyle);
shiftDownOfTopRow = actualShift;
}
}
mScreenFirstRow += shiftDownOfTopRow;
mScreenFirstRow = (mScreenFirstRow < 0) ? (mScreenFirstRow + mTotalRows) : (mScreenFirstRow % mTotalRows);
mTotalRows = newTotalRows;
mActiveTranscriptRows = altScreen ? 0 : Math.max(0, mActiveTranscriptRows + shiftDownOfTopRow);
cursor[1] -= shiftDownOfTopRow;
mScreenRows = newRows;
} else {
// Copy away old state and update new:
TerminalRow[] oldLines = mLines;
mLines = new TerminalRow[newTotalRows];
for (int i = 0; i < newTotalRows; i++)
mLines[i] = new TerminalRow(newColumns, currentStyle);
final int oldActiveTranscriptRows = mActiveTranscriptRows;
final int oldScreenFirstRow = mScreenFirstRow;
final int oldScreenRows = mScreenRows;
final int oldTotalRows = mTotalRows;
mTotalRows = newTotalRows;
mScreenRows = newRows;
mActiveTranscriptRows = mScreenFirstRow = 0;
mColumns = newColumns;
int newCursorRow = -1;
int newCursorColumn = -1;
int oldCursorRow = cursor[1];
int oldCursorColumn = cursor[0];
boolean newCursorPlaced = false;
int currentOutputExternalRow = 0;
int currentOutputExternalColumn = 0;
// Loop over every character in the initial state.
// Blank lines should be skipped only if at end of transcript (just as is done in the "fast" resize), so we
// keep track how many blank lines we have skipped if we later on find a non-blank line.
int skippedBlankLines = 0;
for (int externalOldRow = -oldActiveTranscriptRows; externalOldRow < oldScreenRows; externalOldRow++) {
// Do what externalToInternalRow() does but for the old state:
int internalOldRow = oldScreenFirstRow + externalOldRow;
internalOldRow = (internalOldRow < 0) ? (oldTotalRows + internalOldRow) : (internalOldRow % oldTotalRows);
TerminalRow oldLine = oldLines[internalOldRow];
boolean cursorAtThisRow = externalOldRow == oldCursorRow;
// The cursor may only be on a non-null line, which we should not skip:
if (oldLine == null || (!(!newCursorPlaced && cursorAtThisRow)) && oldLine.isBlank()) {
skippedBlankLines++;
continue;
} else if (skippedBlankLines > 0) {
// After skipping some blank lines we encounter a non-blank line. Insert the skipped blank lines.
for (int i = 0; i < skippedBlankLines; i++) {
if (currentOutputExternalRow == mScreenRows - 1) {
scrollDownOneLine(0, mScreenRows, currentStyle);
} else {
currentOutputExternalRow++;
}
currentOutputExternalColumn = 0;
}
skippedBlankLines = 0;
}
int lastNonSpaceIndex = 0;
boolean justToCursor = false;
if (cursorAtThisRow || oldLine.mLineWrap) {
// Take the whole line, either because of cursor on it, or if line wrapping.
lastNonSpaceIndex = oldLine.getSpaceUsed();
if (cursorAtThisRow) justToCursor = true;
} else {
for (int i = 0; i < oldLine.getSpaceUsed(); i++)
// NEWLY INTRODUCED BUG! Should not index oldLine.mStyle with char indices
if (oldLine.mText[i] != ' '/* || oldLine.mStyle[i] != currentStyle */)
lastNonSpaceIndex = i + 1;
}
int currentOldCol = 0;
long styleAtCol = 0;
for (int i = 0; i < lastNonSpaceIndex; i++) {
// Note that looping over java character, not cells.
char c = oldLine.mText[i];
int codePoint = (Character.isHighSurrogate(c)) ? Character.toCodePoint(c, oldLine.mText[++i]) : c;
int displayWidth = WcWidth.width(codePoint);
// Use the last style if this is a zero-width character:
if (displayWidth > 0) styleAtCol = oldLine.getStyle(currentOldCol);
// Line wrap as necessary:
if (currentOutputExternalColumn + displayWidth > mColumns) {
setLineWrap(currentOutputExternalRow);
if (currentOutputExternalRow == mScreenRows - 1) {
if (newCursorPlaced) newCursorRow--;
scrollDownOneLine(0, mScreenRows, currentStyle);
} else {
currentOutputExternalRow++;
}
currentOutputExternalColumn = 0;
}
int offsetDueToCombiningChar = ((displayWidth <= 0 && currentOutputExternalColumn > 0) ? 1 : 0);
int outputColumn = currentOutputExternalColumn - offsetDueToCombiningChar;
setChar(outputColumn, currentOutputExternalRow, codePoint, styleAtCol);
if (displayWidth > 0) {
if (oldCursorRow == externalOldRow && oldCursorColumn == currentOldCol) {
newCursorColumn = currentOutputExternalColumn;
newCursorRow = currentOutputExternalRow;
newCursorPlaced = true;
}
currentOldCol += displayWidth;
currentOutputExternalColumn += displayWidth;
if (justToCursor && newCursorPlaced) break;
}
}
// Old row has been copied. Check if we need to insert newline if old line was not wrapping:
if (externalOldRow != (oldScreenRows - 1) && !oldLine.mLineWrap) {
if (currentOutputExternalRow == mScreenRows - 1) {
if (newCursorPlaced) newCursorRow--;
scrollDownOneLine(0, mScreenRows, currentStyle);
} else {
currentOutputExternalRow++;
}
currentOutputExternalColumn = 0;
}
}
cursor[0] = newCursorColumn;
cursor[1] = newCursorRow;
}
// Handle cursor scrolling off screen:
if (cursor[0] < 0 || cursor[1] < 0) cursor[0] = cursor[1] = 0;
}
/**
* Block copy lines and associated metadata from one location to another in the circular buffer, taking wraparound
* into account.
*
* @param srcInternal The first line to be copied.
* @param len The number of lines to be copied.
*/
private void blockCopyLinesDown(int srcInternal, int len) {
if (len == 0) return;
int totalRows = mTotalRows;
int start = len - 1;
// Save away line to be overwritten:
TerminalRow lineToBeOverWritten = mLines[(srcInternal + start + 1) % totalRows];
// Do the copy from bottom to top.
for (int i = start; i >= 0; --i)
mLines[(srcInternal + i + 1) % totalRows] = mLines[(srcInternal + i) % totalRows];
// Put back overwritten line, now above the block:
mLines[(srcInternal) % totalRows] = lineToBeOverWritten;
}
/**
* Scroll the screen down one line. To scroll the whole screen of a 24 line screen, the arguments would be (0, 24).
*
* @param topMargin First line that is scrolled.
* @param bottomMargin One line after the last line that is scrolled.
* @param style the style for the newly exposed line.
*/
public void scrollDownOneLine(int topMargin, int bottomMargin, long style) {
if (topMargin > bottomMargin - 1 || topMargin < 0 || bottomMargin > mScreenRows)
throw new IllegalArgumentException("topMargin=" + topMargin + ", bottomMargin=" + bottomMargin + ", mScreenRows=" + mScreenRows);
// Copy the fixed topMargin lines one line down so that they remain on screen in same position:
blockCopyLinesDown(mScreenFirstRow, topMargin);
// Copy the fixed mScreenRows-bottomMargin lines one line down so that they remain on screen in same
// position:
blockCopyLinesDown(externalToInternalRow(bottomMargin), mScreenRows - bottomMargin);
// Update the screen location in the ring buffer:
mScreenFirstRow = (mScreenFirstRow + 1) % mTotalRows;
// Note that the history has grown if not already full:
if (mActiveTranscriptRows < mTotalRows - mScreenRows) mActiveTranscriptRows++;
// Blank the newly revealed line above the bottom margin:
int blankRow = externalToInternalRow(bottomMargin - 1);
if (mLines[blankRow] == null) {
mLines[blankRow] = new TerminalRow(mColumns, style);
} else {
mLines[blankRow].clear(style);
}
}
/**
* Block copy characters from one position in the screen to another. The two positions can overlap. All characters
* of the source and destination must be within the bounds of the screen, or else an InvalidParameterException will
* be thrown.
*
* @param sx source X coordinate
* @param sy source Y coordinate
* @param w width
* @param h height
* @param dx destination X coordinate
* @param dy destination Y coordinate
*/
public void blockCopy(int sx, int sy, int w, int h, int dx, int dy) {
if (w == 0) return;
if (sx < 0 || sx + w > mColumns || sy < 0 || sy + h > mScreenRows || dx < 0 || dx + w > mColumns || dy < 0 || dy + h > mScreenRows)
throw new IllegalArgumentException();
boolean copyingUp = sy > dy;
for (int y = 0; y < h; y++) {
int y2 = copyingUp ? y : (h - (y + 1));
TerminalRow sourceRow = allocateFullLineIfNecessary(externalToInternalRow(sy + y2));
allocateFullLineIfNecessary(externalToInternalRow(dy + y2)).copyInterval(sourceRow, sx, sx + w, dx);
}
}
/**
* Block set characters. All characters must be within the bounds of the screen, or else and
* InvalidParemeterException will be thrown. Typically this is called with a "val" argument of 32 to clear a block
* of characters.
*/
public void blockSet(int sx, int sy, int w, int h, int val, long style) {
if (sx < 0 || sx + w > mColumns || sy < 0 || sy + h > mScreenRows) {
throw new IllegalArgumentException(
"Illegal arguments! blockSet(" + sx + ", " + sy + ", " + w + ", " + h + ", " + val + ", " + mColumns + ", " + mScreenRows + ")");
}
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
setChar(sx + x, sy + y, val, style);
}
public TerminalRow allocateFullLineIfNecessary(int row) {
return (mLines[row] == null) ? (mLines[row] = new TerminalRow(mColumns, 0)) : mLines[row];
}
public void setChar(int column, int row, int codePoint, long style) {
if (row < 0 || row >= mScreenRows || column < 0 || column >= mColumns)
throw new IllegalArgumentException("TerminalBuffer.setChar(): row=" + row + ", column=" + column + ", mScreenRows=" + mScreenRows + ", mColumns=" + mColumns);
row = externalToInternalRow(row);
allocateFullLineIfNecessary(row).setChar(column, codePoint, style);
}
public long getStyleAt(int externalRow, int column) {
return allocateFullLineIfNecessary(externalToInternalRow(externalRow)).getStyle(column);
}
/** Support for http://vt100.net/docs/vt510-rm/DECCARA and http://vt100.net/docs/vt510-rm/DECCARA */
public void setOrClearEffect(int bits, boolean setOrClear, boolean reverse, boolean rectangular, int leftMargin, int rightMargin, int top, int left,
int bottom, int right) {
for (int y = top; y < bottom; y++) {
TerminalRow line = mLines[externalToInternalRow(y)];
int startOfLine = (rectangular || y == top) ? left : leftMargin;
int endOfLine = (rectangular || y + 1 == bottom) ? right : rightMargin;
for (int x = startOfLine; x < endOfLine; x++) {
long currentStyle = line.getStyle(x);
int foreColor = TextStyle.decodeForeColor(currentStyle);
int backColor = TextStyle.decodeBackColor(currentStyle);
int effect = TextStyle.decodeEffect(currentStyle);
if (reverse) {
// Clear out the bits to reverse and add them back in reversed:
effect = (effect & ~bits) | (bits & ~effect);
} else if (setOrClear) {
effect |= bits;
} else {
effect &= ~bits;
}
line.mStyle[x] = TextStyle.encode(foreColor, backColor, effect);
}
}
}
public void clearTranscript() {
if (mScreenFirstRow < mActiveTranscriptRows) {
Arrays.fill(mLines, mTotalRows + mScreenFirstRow - mActiveTranscriptRows, mTotalRows, null);
Arrays.fill(mLines, 0, mScreenFirstRow, null);
} else {
Arrays.fill(mLines, mScreenFirstRow - mActiveTranscriptRows, mScreenFirstRow, null);
}
mActiveTranscriptRows = 0;
}
}

View File

@@ -0,0 +1,126 @@
package com.termux.terminal;
import java.util.Map;
import java.util.Properties;
/**
* Color scheme for a terminal with default colors, which may be overridden (and then reset) from the shell using
* Operating System Control (OSC) sequences.
*
* @see TerminalColors
*/
public final class TerminalColorScheme {
/** http://upload.wikimedia.org/wikipedia/en/1/15/Xterm_256color_chart.svg, but with blue color brighter. */
private static final int[] DEFAULT_COLORSCHEME = {
// 16 original colors. First 8 are dim.
0xff000000, // black
0xffcd0000, // dim red
0xff00cd00, // dim green
0xffcdcd00, // dim yellow
0xff6495ed, // dim blue
0xffcd00cd, // dim magenta
0xff00cdcd, // dim cyan
0xffe5e5e5, // dim white
// Second 8 are bright:
0xff7f7f7f, // medium grey
0xffff0000, // bright red
0xff00ff00, // bright green
0xffffff00, // bright yellow
0xff5c5cff, // light blue
0xffff00ff, // bright magenta
0xff00ffff, // bright cyan
0xffffffff, // bright white
// 216 color cube, six shades of each color:
0xff000000, 0xff00005f, 0xff000087, 0xff0000af, 0xff0000d7, 0xff0000ff, 0xff005f00, 0xff005f5f, 0xff005f87, 0xff005faf, 0xff005fd7, 0xff005fff,
0xff008700, 0xff00875f, 0xff008787, 0xff0087af, 0xff0087d7, 0xff0087ff, 0xff00af00, 0xff00af5f, 0xff00af87, 0xff00afaf, 0xff00afd7, 0xff00afff,
0xff00d700, 0xff00d75f, 0xff00d787, 0xff00d7af, 0xff00d7d7, 0xff00d7ff, 0xff00ff00, 0xff00ff5f, 0xff00ff87, 0xff00ffaf, 0xff00ffd7, 0xff00ffff,
0xff5f0000, 0xff5f005f, 0xff5f0087, 0xff5f00af, 0xff5f00d7, 0xff5f00ff, 0xff5f5f00, 0xff5f5f5f, 0xff5f5f87, 0xff5f5faf, 0xff5f5fd7, 0xff5f5fff,
0xff5f8700, 0xff5f875f, 0xff5f8787, 0xff5f87af, 0xff5f87d7, 0xff5f87ff, 0xff5faf00, 0xff5faf5f, 0xff5faf87, 0xff5fafaf, 0xff5fafd7, 0xff5fafff,
0xff5fd700, 0xff5fd75f, 0xff5fd787, 0xff5fd7af, 0xff5fd7d7, 0xff5fd7ff, 0xff5fff00, 0xff5fff5f, 0xff5fff87, 0xff5fffaf, 0xff5fffd7, 0xff5fffff,
0xff870000, 0xff87005f, 0xff870087, 0xff8700af, 0xff8700d7, 0xff8700ff, 0xff875f00, 0xff875f5f, 0xff875f87, 0xff875faf, 0xff875fd7, 0xff875fff,
0xff878700, 0xff87875f, 0xff878787, 0xff8787af, 0xff8787d7, 0xff8787ff, 0xff87af00, 0xff87af5f, 0xff87af87, 0xff87afaf, 0xff87afd7, 0xff87afff,
0xff87d700, 0xff87d75f, 0xff87d787, 0xff87d7af, 0xff87d7d7, 0xff87d7ff, 0xff87ff00, 0xff87ff5f, 0xff87ff87, 0xff87ffaf, 0xff87ffd7, 0xff87ffff,
0xffaf0000, 0xffaf005f, 0xffaf0087, 0xffaf00af, 0xffaf00d7, 0xffaf00ff, 0xffaf5f00, 0xffaf5f5f, 0xffaf5f87, 0xffaf5faf, 0xffaf5fd7, 0xffaf5fff,
0xffaf8700, 0xffaf875f, 0xffaf8787, 0xffaf87af, 0xffaf87d7, 0xffaf87ff, 0xffafaf00, 0xffafaf5f, 0xffafaf87, 0xffafafaf, 0xffafafd7, 0xffafafff,
0xffafd700, 0xffafd75f, 0xffafd787, 0xffafd7af, 0xffafd7d7, 0xffafd7ff, 0xffafff00, 0xffafff5f, 0xffafff87, 0xffafffaf, 0xffafffd7, 0xffafffff,
0xffd70000, 0xffd7005f, 0xffd70087, 0xffd700af, 0xffd700d7, 0xffd700ff, 0xffd75f00, 0xffd75f5f, 0xffd75f87, 0xffd75faf, 0xffd75fd7, 0xffd75fff,
0xffd78700, 0xffd7875f, 0xffd78787, 0xffd787af, 0xffd787d7, 0xffd787ff, 0xffd7af00, 0xffd7af5f, 0xffd7af87, 0xffd7afaf, 0xffd7afd7, 0xffd7afff,
0xffd7d700, 0xffd7d75f, 0xffd7d787, 0xffd7d7af, 0xffd7d7d7, 0xffd7d7ff, 0xffd7ff00, 0xffd7ff5f, 0xffd7ff87, 0xffd7ffaf, 0xffd7ffd7, 0xffd7ffff,
0xffff0000, 0xffff005f, 0xffff0087, 0xffff00af, 0xffff00d7, 0xffff00ff, 0xffff5f00, 0xffff5f5f, 0xffff5f87, 0xffff5faf, 0xffff5fd7, 0xffff5fff,
0xffff8700, 0xffff875f, 0xffff8787, 0xffff87af, 0xffff87d7, 0xffff87ff, 0xffffaf00, 0xffffaf5f, 0xffffaf87, 0xffffafaf, 0xffffafd7, 0xffffafff,
0xffffd700, 0xffffd75f, 0xffffd787, 0xffffd7af, 0xffffd7d7, 0xffffd7ff, 0xffffff00, 0xffffff5f, 0xffffff87, 0xffffffaf, 0xffffffd7, 0xffffffff,
// 24 grey scale ramp:
0xff080808, 0xff121212, 0xff1c1c1c, 0xff262626, 0xff303030, 0xff3a3a3a, 0xff444444, 0xff4e4e4e, 0xff585858, 0xff626262, 0xff6c6c6c, 0xff767676,
0xff808080, 0xff8a8a8a, 0xff949494, 0xff9e9e9e, 0xffa8a8a8, 0xffb2b2b2, 0xffbcbcbc, 0xffc6c6c6, 0xffd0d0d0, 0xffdadada, 0xffe4e4e4, 0xffeeeeee,
// COLOR_INDEX_DEFAULT_FOREGROUND, COLOR_INDEX_DEFAULT_BACKGROUND and COLOR_INDEX_DEFAULT_CURSOR:
0xffffffff, 0xff000000, 0xffffffff};
public final int[] mDefaultColors = new int[TextStyle.NUM_INDEXED_COLORS];
public TerminalColorScheme() {
reset();
}
private void reset() {
System.arraycopy(DEFAULT_COLORSCHEME, 0, mDefaultColors, 0, TextStyle.NUM_INDEXED_COLORS);
}
public void updateWith(Properties props) {
reset();
boolean cursorPropExists = false;
for (Map.Entry<Object, Object> entries : props.entrySet()) {
String key = (String) entries.getKey();
String value = (String) entries.getValue();
int colorIndex;
if (key.equals("foreground")) {
colorIndex = TextStyle.COLOR_INDEX_FOREGROUND;
} else if (key.equals("background")) {
colorIndex = TextStyle.COLOR_INDEX_BACKGROUND;
} else if (key.equals("cursor")) {
colorIndex = TextStyle.COLOR_INDEX_CURSOR;
cursorPropExists = true;
} else if (key.startsWith("color")) {
try {
colorIndex = Integer.parseInt(key.substring(5));
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid property: '" + key + "'");
}
} else {
throw new IllegalArgumentException("Invalid property: '" + key + "'");
}
int colorValue = TerminalColors.parse(value);
if (colorValue == 0)
throw new IllegalArgumentException("Property '" + key + "' has invalid color: '" + value + "'");
mDefaultColors[colorIndex] = colorValue;
}
if (!cursorPropExists)
setCursorColorForBackground();
}
/**
* If the "cursor" color is not set by user, we need to decide on the appropriate color that will
* be visible on the current terminal background. White will not be visible on light backgrounds
* and black won't be visible on dark backgrounds. So we find the perceived brightness of the
* background color and if its below the threshold (too dark), we use white cursor and if its
* above (too bright), we use black cursor.
*/
public void setCursorColorForBackground() {
int backgroundColor = mDefaultColors[TextStyle.COLOR_INDEX_BACKGROUND];
int brightness = TerminalColors.getPerceivedBrightnessOfColor(backgroundColor);
if (brightness > 0) {
if (brightness < 130)
mDefaultColors[TextStyle.COLOR_INDEX_CURSOR] = 0xffffffff;
else
mDefaultColors[TextStyle.COLOR_INDEX_CURSOR] = 0xff000000;
}
}
}

View File

@@ -0,0 +1,96 @@
package com.termux.terminal;
import android.graphics.Color;
/** Current terminal colors (if different from default). */
public final class TerminalColors {
/** Static data - a bit ugly but ok for now. */
public static final TerminalColorScheme COLOR_SCHEME = new TerminalColorScheme();
/**
* The current terminal colors, which are normally set from the color theme, but may be set dynamically with the OSC
* 4 control sequence.
*/
public final int[] mCurrentColors = new int[TextStyle.NUM_INDEXED_COLORS];
/** Create a new instance with default colors from the theme. */
public TerminalColors() {
reset();
}
/** Reset a particular indexed color with the default color from the color theme. */
public void reset(int index) {
mCurrentColors[index] = COLOR_SCHEME.mDefaultColors[index];
}
/** Reset all indexed colors with the default color from the color theme. */
public void reset() {
System.arraycopy(COLOR_SCHEME.mDefaultColors, 0, mCurrentColors, 0, TextStyle.NUM_INDEXED_COLORS);
}
/**
* Parse color according to http://manpages.ubuntu.com/manpages/intrepid/man3/XQueryColor.3.html
* <p/>
* Highest bit is set if successful, so return value is 0xFF${R}${G}${B}. Return 0 if failed.
*/
static int parse(String c) {
try {
int skipInitial, skipBetween;
if (c.charAt(0) == '#') {
// #RGB, #RRGGBB, #RRRGGGBBB or #RRRRGGGGBBBB. Most significant bits.
skipInitial = 1;
skipBetween = 0;
} else if (c.startsWith("rgb:")) {
// rgb:<red>/<green>/<blue> where <red>, <green>, <blue> := h | hh | hhh | hhhh. Scaled.
skipInitial = 4;
skipBetween = 1;
} else {
return 0;
}
int charsForColors = c.length() - skipInitial - 2 * skipBetween;
if (charsForColors % 3 != 0) return 0; // Unequal lengths.
int componentLength = charsForColors / 3;
double mult = 255 / (Math.pow(2, componentLength * 4) - 1);
int currentPosition = skipInitial;
String rString = c.substring(currentPosition, currentPosition + componentLength);
currentPosition += componentLength + skipBetween;
String gString = c.substring(currentPosition, currentPosition + componentLength);
currentPosition += componentLength + skipBetween;
String bString = c.substring(currentPosition, currentPosition + componentLength);
int r = (int) (Integer.parseInt(rString, 16) * mult);
int g = (int) (Integer.parseInt(gString, 16) * mult);
int b = (int) (Integer.parseInt(bString, 16) * mult);
return 0xFF << 24 | r << 16 | g << 8 | b;
} catch (NumberFormatException | IndexOutOfBoundsException e) {
return 0;
}
}
/** Try parse a color from a text parameter and into a specified index. */
public void tryParseColor(int intoIndex, String textParameter) {
int c = parse(textParameter);
if (c != 0) mCurrentColors[intoIndex] = c;
}
/**
* Get the perceived brightness of the color based on its RGB components.
*
* https://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx
* http://alienryderflex.com/hsp.html
*
* @param color The color code int.
* @return Returns value between 0-255.
*/
public static int getPerceivedBrightnessOfColor(int color) {
return (int)
Math.floor(Math.sqrt(
Math.pow(Color.red(color), 2) * 0.241 +
Math.pow(Color.green(color), 2) * 0.691 +
Math.pow(Color.blue(color), 2) * 0.068
));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
package com.termux.terminal;
import java.nio.charset.StandardCharsets;
/** A client which receives callbacks from events triggered by feeding input to a {@link TerminalEmulator}. */
public abstract class TerminalOutput {
/** Write a string using the UTF-8 encoding to the terminal client. */
public final void write(String data) {
if (data == null) return;
byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
write(bytes, 0, bytes.length);
}
/** Write bytes to the terminal client. */
public abstract void write(byte[] data, int offset, int count);
/** Notify the terminal client that the terminal title has changed. */
public abstract void titleChanged(String oldTitle, String newTitle);
/** Notify the terminal client that text should be copied to clipboard. */
public abstract void onCopyTextToClipboard(String text);
/** Notify the terminal client that text should be pasted from clipboard. */
public abstract void onPasteTextFromClipboard();
/** Notify the terminal client that a bell character (ASCII 7, bell, BEL, \a, ^G)) has been received. */
public abstract void onBell();
public abstract void onColorsChanged();
}

View File

@@ -0,0 +1,283 @@
package com.termux.terminal;
import java.util.Arrays;
/**
* A row in a terminal, composed of a fixed number of cells.
* <p>
* The text in the row is stored in a char[] array, {@link #mText}, for quick access during rendering.
*/
public final class TerminalRow {
private static final float SPARE_CAPACITY_FACTOR = 1.5f;
/**
* Max combining characters that can exist in a column, that are separate from the base character
* itself. Any additional combining characters will be ignored and not added to the column.
*
* There does not seem to be limit in unicode standard for max number of combination characters
* that can be combined but such characters are primarily under 10.
*
* "Section 3.6 Combination" of unicode standard contains combining characters info.
* - https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf
* - https://en.wikipedia.org/wiki/Combining_character#Unicode_ranges
* - https://stackoverflow.com/questions/71237212/what-is-the-maximum-number-of-unicode-combined-characters-that-may-be-needed-to
*
* UAX15-D3 Stream-Safe Text Format limits to max 30 combining characters.
* > The value of 30 is chosen to be significantly beyond what is required for any linguistic or technical usage.
* > While it would have been feasible to chose a smaller number, this value provides a very wide margin,
* > yet is well within the buffer size limits of practical implementations.
* - https://unicode.org/reports/tr15/#Stream_Safe_Text_Format
* - https://stackoverflow.com/a/11983435/14686958
*
* We choose the value 15 because it should be enough for terminal based applications and keep
* the memory usage low for a terminal row, won't affect performance or cause terminal to
* lag or hang, and will keep malicious applications from causing harm. The value can be
* increased if ever needed for legitimate applications.
*/
private static final int MAX_COMBINING_CHARACTERS_PER_COLUMN = 15;
/** The number of columns in this terminal row. */
private final int mColumns;
/** The text filling this terminal row. */
public char[] mText;
/** The number of java chars used in {@link #mText}. */
private short mSpaceUsed;
/** If this row has been line wrapped due to text output at the end of line. */
boolean mLineWrap;
/** The style bits of each cell in the row. See {@link TextStyle}. */
final long[] mStyle;
/** If this row might contain chars with width != 1, used for deactivating fast path */
boolean mHasNonOneWidthOrSurrogateChars;
/** Construct a blank row (containing only whitespace, ' ') with a specified style. */
public TerminalRow(int columns, long style) {
mColumns = columns;
mText = new char[(int) (SPARE_CAPACITY_FACTOR * columns)];
mStyle = new long[columns];
clear(style);
}
/** NOTE: The sourceX2 is exclusive. */
public void copyInterval(TerminalRow line, int sourceX1, int sourceX2, int destinationX) {
mHasNonOneWidthOrSurrogateChars |= line.mHasNonOneWidthOrSurrogateChars;
final int x1 = line.findStartOfColumn(sourceX1);
final int x2 = line.findStartOfColumn(sourceX2);
boolean startingFromSecondHalfOfWideChar = (sourceX1 > 0 && line.wideDisplayCharacterStartingAt(sourceX1 - 1));
final char[] sourceChars = (this == line) ? Arrays.copyOf(line.mText, line.mText.length) : line.mText;
int latestNonCombiningWidth = 0;
for (int i = x1; i < x2; i++) {
char sourceChar = sourceChars[i];
int codePoint = Character.isHighSurrogate(sourceChar) ? Character.toCodePoint(sourceChar, sourceChars[++i]) : sourceChar;
if (startingFromSecondHalfOfWideChar) {
// Just treat copying second half of wide char as copying whitespace.
codePoint = ' ';
startingFromSecondHalfOfWideChar = false;
}
int w = WcWidth.width(codePoint);
if (w > 0) {
destinationX += latestNonCombiningWidth;
sourceX1 += latestNonCombiningWidth;
latestNonCombiningWidth = w;
}
setChar(destinationX, codePoint, line.getStyle(sourceX1));
}
}
public int getSpaceUsed() {
return mSpaceUsed;
}
/** Note that the column may end of second half of wide character. */
public int findStartOfColumn(int column) {
if (column == mColumns) return getSpaceUsed();
int currentColumn = 0;
int currentCharIndex = 0;
while (true) { // 0<2 1 < 2
int newCharIndex = currentCharIndex;
char c = mText[newCharIndex++]; // cci=1, cci=2
boolean isHigh = Character.isHighSurrogate(c);
int codePoint = isHigh ? Character.toCodePoint(c, mText[newCharIndex++]) : c;
int wcwidth = WcWidth.width(codePoint); // 1, 2
if (wcwidth > 0) {
currentColumn += wcwidth;
if (currentColumn == column) {
while (newCharIndex < mSpaceUsed) {
// Skip combining chars.
if (Character.isHighSurrogate(mText[newCharIndex])) {
if (WcWidth.width(Character.toCodePoint(mText[newCharIndex], mText[newCharIndex + 1])) <= 0) {
newCharIndex += 2;
} else {
break;
}
} else if (WcWidth.width(mText[newCharIndex]) <= 0) {
newCharIndex++;
} else {
break;
}
}
return newCharIndex;
} else if (currentColumn > column) {
// Wide column going past end.
return currentCharIndex;
}
}
currentCharIndex = newCharIndex;
}
}
private boolean wideDisplayCharacterStartingAt(int column) {
for (int currentCharIndex = 0, currentColumn = 0; currentCharIndex < mSpaceUsed; ) {
char c = mText[currentCharIndex++];
int codePoint = Character.isHighSurrogate(c) ? Character.toCodePoint(c, mText[currentCharIndex++]) : c;
int wcwidth = WcWidth.width(codePoint);
if (wcwidth > 0) {
if (currentColumn == column && wcwidth == 2) return true;
currentColumn += wcwidth;
if (currentColumn > column) return false;
}
}
return false;
}
public void clear(long style) {
Arrays.fill(mText, ' ');
Arrays.fill(mStyle, style);
mSpaceUsed = (short) mColumns;
mHasNonOneWidthOrSurrogateChars = false;
}
// https://github.com/steven676/Android-Terminal-Emulator/commit/9a47042620bec87617f0b4f5d50568535668fe26
public void setChar(int columnToSet, int codePoint, long style) {
if (columnToSet < 0 || columnToSet >= mStyle.length)
throw new IllegalArgumentException("TerminalRow.setChar(): columnToSet=" + columnToSet + ", codePoint=" + codePoint + ", style=" + style);
mStyle[columnToSet] = style;
final int newCodePointDisplayWidth = WcWidth.width(codePoint);
// Fast path when we don't have any chars with width != 1
if (!mHasNonOneWidthOrSurrogateChars) {
if (codePoint >= Character.MIN_SUPPLEMENTARY_CODE_POINT || newCodePointDisplayWidth != 1) {
mHasNonOneWidthOrSurrogateChars = true;
} else {
mText[columnToSet] = (char) codePoint;
return;
}
}
final boolean newIsCombining = newCodePointDisplayWidth <= 0;
boolean wasExtraColForWideChar = (columnToSet > 0) && wideDisplayCharacterStartingAt(columnToSet - 1);
if (newIsCombining) {
// When standing at second half of wide character and inserting combining:
if (wasExtraColForWideChar) columnToSet--;
} else {
// Check if we are overwriting the second half of a wide character starting at the previous column:
if (wasExtraColForWideChar) setChar(columnToSet - 1, ' ', style);
// Check if we are overwriting the first half of a wide character starting at the next column:
boolean overwritingWideCharInNextColumn = newCodePointDisplayWidth == 2 && wideDisplayCharacterStartingAt(columnToSet + 1);
if (overwritingWideCharInNextColumn) setChar(columnToSet + 1, ' ', style);
}
char[] text = mText;
final int oldStartOfColumnIndex = findStartOfColumn(columnToSet);
final int oldCodePointDisplayWidth = WcWidth.width(text, oldStartOfColumnIndex);
// Get the number of elements in the mText array this column uses now
int oldCharactersUsedForColumn;
if (columnToSet + oldCodePointDisplayWidth < mColumns) {
int oldEndOfColumnIndex = findStartOfColumn(columnToSet + oldCodePointDisplayWidth);
oldCharactersUsedForColumn = oldEndOfColumnIndex - oldStartOfColumnIndex;
} else {
// Last character.
oldCharactersUsedForColumn = mSpaceUsed - oldStartOfColumnIndex;
}
// If MAX_COMBINING_CHARACTERS_PER_COLUMN already exist in column, then ignore adding additional combining characters.
if (newIsCombining) {
int combiningCharsCount = WcWidth.zeroWidthCharsCount(mText, oldStartOfColumnIndex, oldStartOfColumnIndex + oldCharactersUsedForColumn);
if (combiningCharsCount >= MAX_COMBINING_CHARACTERS_PER_COLUMN)
return;
}
// Find how many chars this column will need
int newCharactersUsedForColumn = Character.charCount(codePoint);
if (newIsCombining) {
// Combining characters are added to the contents of the column instead of overwriting them, so that they
// modify the existing contents.
// FIXME: Unassigned characters also get width=0.
newCharactersUsedForColumn += oldCharactersUsedForColumn;
}
int oldNextColumnIndex = oldStartOfColumnIndex + oldCharactersUsedForColumn;
int newNextColumnIndex = oldStartOfColumnIndex + newCharactersUsedForColumn;
final int javaCharDifference = newCharactersUsedForColumn - oldCharactersUsedForColumn;
if (javaCharDifference > 0) {
// Shift the rest of the line right.
int oldCharactersAfterColumn = mSpaceUsed - oldNextColumnIndex;
if (mSpaceUsed + javaCharDifference > text.length) {
// We need to grow the array
char[] newText = new char[text.length + mColumns];
System.arraycopy(text, 0, newText, 0, oldNextColumnIndex);
System.arraycopy(text, oldNextColumnIndex, newText, newNextColumnIndex, oldCharactersAfterColumn);
mText = text = newText;
} else {
System.arraycopy(text, oldNextColumnIndex, text, newNextColumnIndex, oldCharactersAfterColumn);
}
} else if (javaCharDifference < 0) {
// Shift the rest of the line left.
System.arraycopy(text, oldNextColumnIndex, text, newNextColumnIndex, mSpaceUsed - oldNextColumnIndex);
}
mSpaceUsed += javaCharDifference;
// Store char. A combining character is stored at the end of the existing contents so that it modifies them:
//noinspection ResultOfMethodCallIgnored - since we already now how many java chars is used.
Character.toChars(codePoint, text, oldStartOfColumnIndex + (newIsCombining ? oldCharactersUsedForColumn : 0));
if (oldCodePointDisplayWidth == 2 && newCodePointDisplayWidth == 1) {
// Replace second half of wide char with a space. Which mean that we actually add a ' ' java character.
if (mSpaceUsed + 1 > text.length) {
char[] newText = new char[text.length + mColumns];
System.arraycopy(text, 0, newText, 0, newNextColumnIndex);
System.arraycopy(text, newNextColumnIndex, newText, newNextColumnIndex + 1, mSpaceUsed - newNextColumnIndex);
mText = text = newText;
} else {
System.arraycopy(text, newNextColumnIndex, text, newNextColumnIndex + 1, mSpaceUsed - newNextColumnIndex);
}
text[newNextColumnIndex] = ' ';
++mSpaceUsed;
} else if (oldCodePointDisplayWidth == 1 && newCodePointDisplayWidth == 2) {
if (columnToSet == mColumns - 1) {
throw new IllegalArgumentException("Cannot put wide character in last column");
} else if (columnToSet == mColumns - 2) {
// Truncate the line to the second part of this wide char:
mSpaceUsed = (short) newNextColumnIndex;
} else {
// Overwrite the contents of the next column, which mean we actually remove java characters. Due to the
// check at the beginning of this method we know that we are not overwriting a wide char.
int newNextNextColumnIndex = newNextColumnIndex + (Character.isHighSurrogate(mText[newNextColumnIndex]) ? 2 : 1);
int nextLen = newNextNextColumnIndex - newNextColumnIndex;
// Shift the array leftwards.
System.arraycopy(text, newNextNextColumnIndex, text, newNextColumnIndex, mSpaceUsed - newNextNextColumnIndex);
mSpaceUsed -= nextLen;
}
}
}
boolean isBlank() {
for (int charIndex = 0, charLen = getSpaceUsed(); charIndex < charLen; charIndex++)
if (mText[charIndex] != ' ') return false;
return true;
}
public final long getStyle(int column) {
return mStyle[column];
}
}

View File

@@ -0,0 +1,372 @@
package com.termux.terminal;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
/**
* A terminal session, consisting of a process coupled to a terminal interface.
* <p>
* The subprocess will be executed by the constructor, and when the size is made known by a call to
* {@link #updateSize(int, int, int, int)} terminal emulation will begin and threads will be spawned to handle the subprocess I/O.
* All terminal emulation and callback methods will be performed on the main thread.
* <p>
* The child process may be exited forcefully by using the {@link #finishIfRunning()} method.
* <p>
* NOTE: The terminal session may outlive the EmulatorView, so be careful with callbacks!
*/
public final class TerminalSession extends TerminalOutput {
private static final int MSG_NEW_INPUT = 1;
private static final int MSG_PROCESS_EXITED = 4;
public final String mHandle = UUID.randomUUID().toString();
TerminalEmulator mEmulator;
/**
* A queue written to from a separate thread when the process outputs, and read by main thread to process by
* terminal emulator.
*/
final ByteQueue mProcessToTerminalIOQueue = new ByteQueue(4096);
/**
* A queue written to from the main thread due to user interaction, and read by another thread which forwards by
* writing to the {@link #mTerminalFileDescriptor}.
*/
final ByteQueue mTerminalToProcessIOQueue = new ByteQueue(4096);
/** Buffer to write translate code points into utf8 before writing to mTerminalToProcessIOQueue */
private final byte[] mUtf8InputBuffer = new byte[5];
/** Callback which gets notified when a session finishes or changes title. */
TerminalSessionClient mClient;
/** The pid of the shell process. 0 if not started and -1 if finished running. */
int mShellPid;
/** The exit status of the shell process. Only valid if ${@link #mShellPid} is -1. */
int mShellExitStatus;
/**
* The file descriptor referencing the master half of a pseudo-terminal pair, resulting from calling
* {@link JNI#createSubprocess(String, String, String[], String[], int[], int, int, int, int)}.
*/
private int mTerminalFileDescriptor;
/** Set by the application for user identification of session, not by terminal. */
public String mSessionName;
final Handler mMainThreadHandler = new MainThreadHandler();
private final String mShellPath;
private final String mCwd;
private final String[] mArgs;
private final String[] mEnv;
private final Integer mTranscriptRows;
private static final String LOG_TAG = "TerminalSession";
public TerminalSession(String shellPath, String cwd, String[] args, String[] env, Integer transcriptRows, TerminalSessionClient client) {
this.mShellPath = shellPath;
this.mCwd = cwd;
this.mArgs = args;
this.mEnv = env;
this.mTranscriptRows = transcriptRows;
this.mClient = client;
}
/**
* @param client The {@link TerminalSessionClient} interface implementation to allow
* for communication between {@link TerminalSession} and its client.
*/
public void updateTerminalSessionClient(TerminalSessionClient client) {
mClient = client;
if (mEmulator != null)
mEmulator.updateTerminalSessionClient(client);
}
/** Inform the attached pty of the new size and reflow or initialize the emulator. */
public void updateSize(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
if (mEmulator == null) {
initializeEmulator(columns, rows, cellWidthPixels, cellHeightPixels);
} else {
JNI.setPtyWindowSize(mTerminalFileDescriptor, rows, columns, cellWidthPixels, cellHeightPixels);
mEmulator.resize(columns, rows, cellWidthPixels, cellHeightPixels);
}
}
/** The terminal title as set through escape sequences or null if none set. */
public String getTitle() {
return (mEmulator == null) ? null : mEmulator.getTitle();
}
/**
* Set the terminal emulator's window size and start terminal emulation.
*
* @param columns The number of columns in the terminal window.
* @param rows The number of rows in the terminal window.
*/
public void initializeEmulator(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
mEmulator = new TerminalEmulator(this, columns, rows, cellWidthPixels, cellHeightPixels, mTranscriptRows, mClient);
int[] processId = new int[1];
mTerminalFileDescriptor = JNI.createSubprocess(mShellPath, mCwd, mArgs, mEnv, processId, rows, columns, cellWidthPixels, cellHeightPixels);
mShellPid = processId[0];
final FileDescriptor terminalFileDescriptorWrapped = wrapFileDescriptor(mTerminalFileDescriptor, mClient);
new Thread("TermSessionInputReader[pid=" + mShellPid + "]") {
@Override
public void run() {
try (InputStream termIn = new FileInputStream(terminalFileDescriptorWrapped)) {
final byte[] buffer = new byte[4096];
while (true) {
int read = termIn.read(buffer);
if (read == -1) return;
if (!mProcessToTerminalIOQueue.write(buffer, 0, read)) return;
mMainThreadHandler.sendEmptyMessage(MSG_NEW_INPUT);
}
} catch (Exception e) {
// Ignore, just shutting down.
}
}
}.start();
new Thread("TermSessionOutputWriter[pid=" + mShellPid + "]") {
@Override
public void run() {
final byte[] buffer = new byte[4096];
try (FileOutputStream termOut = new FileOutputStream(terminalFileDescriptorWrapped)) {
while (true) {
int bytesToWrite = mTerminalToProcessIOQueue.read(buffer, true);
if (bytesToWrite == -1) return;
termOut.write(buffer, 0, bytesToWrite);
}
} catch (IOException e) {
// Ignore.
}
}
}.start();
new Thread("TermSessionWaiter[pid=" + mShellPid + "]") {
@Override
public void run() {
int processExitCode = JNI.waitFor(mShellPid);
mMainThreadHandler.sendMessage(mMainThreadHandler.obtainMessage(MSG_PROCESS_EXITED, processExitCode));
}
}.start();
}
/** Write data to the shell process. */
@Override
public void write(byte[] data, int offset, int count) {
if (mShellPid > 0) mTerminalToProcessIOQueue.write(data, offset, count);
}
/** Write the Unicode code point to the terminal encoded in UTF-8. */
public void writeCodePoint(boolean prependEscape, int codePoint) {
if (codePoint > 1114111 || (codePoint >= 0xD800 && codePoint <= 0xDFFF)) {
// 1114111 (= 2**16 + 1024**2 - 1) is the highest code point, [0xD800,0xDFFF] is the surrogate range.
throw new IllegalArgumentException("Invalid code point: " + codePoint);
}
int bufferPosition = 0;
if (prependEscape) mUtf8InputBuffer[bufferPosition++] = 27;
if (codePoint <= /* 7 bits */0b1111111) {
mUtf8InputBuffer[bufferPosition++] = (byte) codePoint;
} else if (codePoint <= /* 11 bits */0b11111111111) {
/* 110xxxxx leading byte with leading 5 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11000000 | (codePoint >> 6));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
} else if (codePoint <= /* 16 bits */0b1111111111111111) {
/* 1110xxxx leading byte with leading 4 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11100000 | (codePoint >> 12));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 6) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
} else { /* We have checked codePoint <= 1114111 above, so we have max 21 bits = 0b111111111111111111111 */
/* 11110xxx leading byte with leading 3 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11110000 | (codePoint >> 18));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 12) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 6) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
}
write(mUtf8InputBuffer, 0, bufferPosition);
}
public TerminalEmulator getEmulator() {
return mEmulator;
}
/** Notify the {@link #mClient} that the screen has changed. */
protected void notifyScreenUpdate() {
mClient.onTextChanged(this);
}
/** Reset state for terminal emulator state. */
public void reset() {
mEmulator.reset();
notifyScreenUpdate();
}
/** Finish this terminal session by sending SIGKILL to the shell. */
public void finishIfRunning() {
if (isRunning()) {
try {
Os.kill(mShellPid, OsConstants.SIGKILL);
} catch (ErrnoException e) {
Logger.logWarn(mClient, LOG_TAG, "Failed sending SIGKILL: " + e.getMessage());
}
}
}
/** Cleanup resources when the process exits. */
void cleanupResources(int exitStatus) {
synchronized (this) {
mShellPid = -1;
mShellExitStatus = exitStatus;
}
// Stop the reader and writer threads, and close the I/O streams
mTerminalToProcessIOQueue.close();
mProcessToTerminalIOQueue.close();
JNI.close(mTerminalFileDescriptor);
}
@Override
public void titleChanged(String oldTitle, String newTitle) {
mClient.onTitleChanged(this);
}
public synchronized boolean isRunning() {
return mShellPid != -1;
}
/** Only valid if not {@link #isRunning()}. */
public synchronized int getExitStatus() {
return mShellExitStatus;
}
@Override
public void onCopyTextToClipboard(String text) {
mClient.onCopyTextToClipboard(this, text);
}
@Override
public void onPasteTextFromClipboard() {
mClient.onPasteTextFromClipboard(this);
}
@Override
public void onBell() {
mClient.onBell(this);
}
@Override
public void onColorsChanged() {
mClient.onColorsChanged(this);
}
public int getPid() {
return mShellPid;
}
/** Returns the shell's working directory or null if it was unavailable. */
public String getCwd() {
if (mShellPid < 1) {
return null;
}
try {
final String cwdSymlink = String.format("/proc/%s/cwd/", mShellPid);
String outputPath = new File(cwdSymlink).getCanonicalPath();
String outputPathWithTrailingSlash = outputPath;
if (!outputPath.endsWith("/")) {
outputPathWithTrailingSlash += '/';
}
if (!cwdSymlink.equals(outputPathWithTrailingSlash)) {
return outputPath;
}
} catch (IOException | SecurityException e) {
Logger.logStackTraceWithMessage(mClient, LOG_TAG, "Error getting current directory", e);
}
return null;
}
private static FileDescriptor wrapFileDescriptor(int fileDescriptor, TerminalSessionClient client) {
FileDescriptor result = new FileDescriptor();
try {
Field descriptorField;
try {
descriptorField = FileDescriptor.class.getDeclaredField("descriptor");
} catch (NoSuchFieldException e) {
// For desktop java:
descriptorField = FileDescriptor.class.getDeclaredField("fd");
}
descriptorField.setAccessible(true);
descriptorField.set(result, fileDescriptor);
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
Logger.logStackTraceWithMessage(client, LOG_TAG, "Error accessing FileDescriptor#descriptor private field", e);
System.exit(1);
}
return result;
}
@SuppressLint("HandlerLeak")
class MainThreadHandler extends Handler {
final byte[] mReceiveBuffer = new byte[4 * 1024];
@Override
public void handleMessage(Message msg) {
int bytesRead = mProcessToTerminalIOQueue.read(mReceiveBuffer, false);
if (bytesRead > 0) {
mEmulator.append(mReceiveBuffer, bytesRead);
notifyScreenUpdate();
}
if (msg.what == MSG_PROCESS_EXITED) {
int exitCode = (Integer) msg.obj;
cleanupResources(exitCode);
String exitDescription = "\r\n[Process completed";
if (exitCode > 0) {
// Non-zero process exit.
exitDescription += " (code " + exitCode + ")";
} else if (exitCode < 0) {
// Negated signal.
exitDescription += " (signal " + (-exitCode) + ")";
}
exitDescription += " - press Enter]";
byte[] bytesToWrite = exitDescription.getBytes(StandardCharsets.UTF_8);
mEmulator.append(bytesToWrite, bytesToWrite.length);
notifyScreenUpdate();
mClient.onSessionFinished(TerminalSession.this);
}
}
}
}

View File

@@ -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);
}

View File

@@ -0,0 +1,90 @@
package com.termux.terminal;
/**
* <p>
* Encodes effects, foreground and background colors into a 64 bit long, which are stored for each cell in a terminal
* row in {@link TerminalRow#mStyle}.
* </p>
* <p>
* The bit layout is:
* </p>
* - 16 flags (11 currently used).
* - 24 for foreground color (only 9 first bits if a color index).
* - 24 for background color (only 9 first bits if a color index).
*/
public final class TextStyle {
public final static int CHARACTER_ATTRIBUTE_BOLD = 1;
public final static int CHARACTER_ATTRIBUTE_ITALIC = 1 << 1;
public final static int CHARACTER_ATTRIBUTE_UNDERLINE = 1 << 2;
public final static int CHARACTER_ATTRIBUTE_BLINK = 1 << 3;
public final static int CHARACTER_ATTRIBUTE_INVERSE = 1 << 4;
public final static int CHARACTER_ATTRIBUTE_INVISIBLE = 1 << 5;
public final static int CHARACTER_ATTRIBUTE_STRIKETHROUGH = 1 << 6;
/**
* The selective erase control functions (DECSED and DECSEL) can only erase characters defined as erasable.
* <p>
* This bit is set if DECSCA (Select Character Protection Attribute) has been used to define the characters that
* come after it as erasable from the screen.
* </p>
*/
public final static int CHARACTER_ATTRIBUTE_PROTECTED = 1 << 7;
/** Dim colors. Also known as faint or half intensity. */
public final static int CHARACTER_ATTRIBUTE_DIM = 1 << 8;
/** If true (24-bit) color is used for the cell for foreground. */
private final static int CHARACTER_ATTRIBUTE_TRUECOLOR_FOREGROUND = 1 << 9;
/** If true (24-bit) color is used for the cell for foreground. */
private final static int CHARACTER_ATTRIBUTE_TRUECOLOR_BACKGROUND= 1 << 10;
public final static int COLOR_INDEX_FOREGROUND = 256;
public final static int COLOR_INDEX_BACKGROUND = 257;
public final static int COLOR_INDEX_CURSOR = 258;
/** The 256 standard color entries and the three special (foreground, background and cursor) ones. */
public final static int NUM_INDEXED_COLORS = 259;
/** Normal foreground and background colors and no effects. */
final static long NORMAL = encode(COLOR_INDEX_FOREGROUND, COLOR_INDEX_BACKGROUND, 0);
static long encode(int foreColor, int backColor, int effect) {
long result = effect & 0b111111111;
if ((0xff000000 & foreColor) == 0xff000000) {
// 24-bit color.
result |= CHARACTER_ATTRIBUTE_TRUECOLOR_FOREGROUND | ((foreColor & 0x00ffffffL) << 40L);
} else {
// Indexed color.
result |= (foreColor & 0b111111111L) << 40;
}
if ((0xff000000 & backColor) == 0xff000000) {
// 24-bit color.
result |= CHARACTER_ATTRIBUTE_TRUECOLOR_BACKGROUND | ((backColor & 0x00ffffffL) << 16L);
} else {
// Indexed color.
result |= (backColor & 0b111111111L) << 16L;
}
return result;
}
public static int decodeForeColor(long style) {
if ((style & CHARACTER_ATTRIBUTE_TRUECOLOR_FOREGROUND) == 0) {
return (int) ((style >>> 40) & 0b111111111L);
} else {
return 0xff000000 | (int) ((style >>> 40) & 0x00ffffffL);
}
}
public static int decodeBackColor(long style) {
if ((style & CHARACTER_ATTRIBUTE_TRUECOLOR_BACKGROUND) == 0) {
return (int) ((style >>> 16) & 0b111111111L);
} else {
return 0xff000000 | (int) ((style >>> 16) & 0x00ffffffL);
}
}
public static int decodeEffect(long style) {
return (int) (style & 0b11111111111);
}
}

View File

@@ -0,0 +1,566 @@
package com.termux.terminal;
/**
* Implementation of wcwidth(3) for Unicode 15.
*
* Implementation from https://github.com/jquast/wcwidth but we return 0 for unprintable characters.
*
* IMPORTANT:
* Must be kept in sync with the following:
* https://github.com/termux/wcwidth
* https://github.com/termux/libandroid-support
* https://github.com/termux/termux-packages/tree/master/packages/libandroid-support
*/
public final class WcWidth {
// From https://github.com/jquast/wcwidth/blob/master/wcwidth/table_zero.py
// from https://github.com/jquast/wcwidth/pull/64
// at commit 1b9b6585b0080ea5cb88dc9815796505724793fe (2022-12-16):
private static final int[][] ZERO_WIDTH = {
{0x00300, 0x0036f}, // Combining Grave Accent ..Combining Latin Small Le
{0x00483, 0x00489}, // Combining Cyrillic Titlo..Combining Cyrillic Milli
{0x00591, 0x005bd}, // Hebrew Accent Etnahta ..Hebrew Point Meteg
{0x005bf, 0x005bf}, // Hebrew Point Rafe ..Hebrew Point Rafe
{0x005c1, 0x005c2}, // Hebrew Point Shin Dot ..Hebrew Point Sin Dot
{0x005c4, 0x005c5}, // Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot
{0x005c7, 0x005c7}, // Hebrew Point Qamats Qata..Hebrew Point Qamats Qata
{0x00610, 0x0061a}, // Arabic Sign Sallallahou ..Arabic Small Kasra
{0x0064b, 0x0065f}, // Arabic Fathatan ..Arabic Wavy Hamza Below
{0x00670, 0x00670}, // Arabic Letter Superscrip..Arabic Letter Superscrip
{0x006d6, 0x006dc}, // Arabic Small High Ligatu..Arabic Small High Seen
{0x006df, 0x006e4}, // Arabic Small High Rounde..Arabic Small High Madda
{0x006e7, 0x006e8}, // Arabic Small High Yeh ..Arabic Small High Noon
{0x006ea, 0x006ed}, // Arabic Empty Centre Low ..Arabic Small Low Meem
{0x00711, 0x00711}, // Syriac Letter Superscrip..Syriac Letter Superscrip
{0x00730, 0x0074a}, // Syriac Pthaha Above ..Syriac Barrekh
{0x007a6, 0x007b0}, // Thaana Abafili ..Thaana Sukun
{0x007eb, 0x007f3}, // Nko Combining Short High..Nko Combining Double Dot
{0x007fd, 0x007fd}, // Nko Dantayalan ..Nko Dantayalan
{0x00816, 0x00819}, // Samaritan Mark In ..Samaritan Mark Dagesh
{0x0081b, 0x00823}, // Samaritan Mark Epentheti..Samaritan Vowel Sign A
{0x00825, 0x00827}, // Samaritan Vowel Sign Sho..Samaritan Vowel Sign U
{0x00829, 0x0082d}, // Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa
{0x00859, 0x0085b}, // Mandaic Affrication Mark..Mandaic Gemination Mark
{0x00898, 0x0089f}, // Arabic Small High Word A..Arabic Half Madda Over M
{0x008ca, 0x008e1}, // Arabic Small High Farsi ..Arabic Small High Sign S
{0x008e3, 0x00902}, // Arabic Turned Damma Belo..Devanagari Sign Anusvara
{0x0093a, 0x0093a}, // Devanagari Vowel Sign Oe..Devanagari Vowel Sign Oe
{0x0093c, 0x0093c}, // Devanagari Sign Nukta ..Devanagari Sign Nukta
{0x00941, 0x00948}, // Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai
{0x0094d, 0x0094d}, // Devanagari Sign Virama ..Devanagari Sign Virama
{0x00951, 0x00957}, // Devanagari Stress Sign U..Devanagari Vowel Sign Uu
{0x00962, 0x00963}, // Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo
{0x00981, 0x00981}, // Bengali Sign Candrabindu..Bengali Sign Candrabindu
{0x009bc, 0x009bc}, // Bengali Sign Nukta ..Bengali Sign Nukta
{0x009c1, 0x009c4}, // Bengali Vowel Sign U ..Bengali Vowel Sign Vocal
{0x009cd, 0x009cd}, // Bengali Sign Virama ..Bengali Sign Virama
{0x009e2, 0x009e3}, // Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal
{0x009fe, 0x009fe}, // Bengali Sandhi Mark ..Bengali Sandhi Mark
{0x00a01, 0x00a02}, // Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi
{0x00a3c, 0x00a3c}, // Gurmukhi Sign Nukta ..Gurmukhi Sign Nukta
{0x00a41, 0x00a42}, // Gurmukhi Vowel Sign U ..Gurmukhi Vowel Sign Uu
{0x00a47, 0x00a48}, // Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai
{0x00a4b, 0x00a4d}, // Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama
{0x00a51, 0x00a51}, // Gurmukhi Sign Udaat ..Gurmukhi Sign Udaat
{0x00a70, 0x00a71}, // Gurmukhi Tippi ..Gurmukhi Addak
{0x00a75, 0x00a75}, // Gurmukhi Sign Yakash ..Gurmukhi Sign Yakash
{0x00a81, 0x00a82}, // Gujarati Sign Candrabind..Gujarati Sign Anusvara
{0x00abc, 0x00abc}, // Gujarati Sign Nukta ..Gujarati Sign Nukta
{0x00ac1, 0x00ac5}, // Gujarati Vowel Sign U ..Gujarati Vowel Sign Cand
{0x00ac7, 0x00ac8}, // Gujarati Vowel Sign E ..Gujarati Vowel Sign Ai
{0x00acd, 0x00acd}, // Gujarati Sign Virama ..Gujarati Sign Virama
{0x00ae2, 0x00ae3}, // Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca
{0x00afa, 0x00aff}, // Gujarati Sign Sukun ..Gujarati Sign Two-circle
{0x00b01, 0x00b01}, // Oriya Sign Candrabindu ..Oriya Sign Candrabindu
{0x00b3c, 0x00b3c}, // Oriya Sign Nukta ..Oriya Sign Nukta
{0x00b3f, 0x00b3f}, // Oriya Vowel Sign I ..Oriya Vowel Sign I
{0x00b41, 0x00b44}, // Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic
{0x00b4d, 0x00b4d}, // Oriya Sign Virama ..Oriya Sign Virama
{0x00b55, 0x00b56}, // Oriya Sign Overline ..Oriya Ai Length Mark
{0x00b62, 0x00b63}, // Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic
{0x00b82, 0x00b82}, // Tamil Sign Anusvara ..Tamil Sign Anusvara
{0x00bc0, 0x00bc0}, // Tamil Vowel Sign Ii ..Tamil Vowel Sign Ii
{0x00bcd, 0x00bcd}, // Tamil Sign Virama ..Tamil Sign Virama
{0x00c00, 0x00c00}, // Telugu Sign Combining Ca..Telugu Sign Combining Ca
{0x00c04, 0x00c04}, // Telugu Sign Combining An..Telugu Sign Combining An
{0x00c3c, 0x00c3c}, // Telugu Sign Nukta ..Telugu Sign Nukta
{0x00c3e, 0x00c40}, // Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii
{0x00c46, 0x00c48}, // Telugu Vowel Sign E ..Telugu Vowel Sign Ai
{0x00c4a, 0x00c4d}, // Telugu Vowel Sign O ..Telugu Sign Virama
{0x00c55, 0x00c56}, // Telugu Length Mark ..Telugu Ai Length Mark
{0x00c62, 0x00c63}, // Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali
{0x00c81, 0x00c81}, // Kannada Sign Candrabindu..Kannada Sign Candrabindu
{0x00cbc, 0x00cbc}, // Kannada Sign Nukta ..Kannada Sign Nukta
{0x00cbf, 0x00cbf}, // Kannada Vowel Sign I ..Kannada Vowel Sign I
{0x00cc6, 0x00cc6}, // Kannada Vowel Sign E ..Kannada Vowel Sign E
{0x00ccc, 0x00ccd}, // Kannada Vowel Sign Au ..Kannada Sign Virama
{0x00ce2, 0x00ce3}, // Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal
{0x00d00, 0x00d01}, // Malayalam Sign Combining..Malayalam Sign Candrabin
{0x00d3b, 0x00d3c}, // Malayalam Sign Vertical ..Malayalam Sign Circular
{0x00d41, 0x00d44}, // Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc
{0x00d4d, 0x00d4d}, // Malayalam Sign Virama ..Malayalam Sign Virama
{0x00d62, 0x00d63}, // Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc
{0x00d81, 0x00d81}, // Sinhala Sign Candrabindu..Sinhala Sign Candrabindu
{0x00dca, 0x00dca}, // Sinhala Sign Al-lakuna ..Sinhala Sign Al-lakuna
{0x00dd2, 0x00dd4}, // Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti
{0x00dd6, 0x00dd6}, // Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga
{0x00e31, 0x00e31}, // Thai Character Mai Han-a..Thai Character Mai Han-a
{0x00e34, 0x00e3a}, // Thai Character Sara I ..Thai Character Phinthu
{0x00e47, 0x00e4e}, // Thai Character Maitaikhu..Thai Character Yamakkan
{0x00eb1, 0x00eb1}, // Lao Vowel Sign Mai Kan ..Lao Vowel Sign Mai Kan
{0x00eb4, 0x00ebc}, // Lao Vowel Sign I ..Lao Semivowel Sign Lo
{0x00ec8, 0x00ece}, // Lao Tone Mai Ek ..(nil)
{0x00f18, 0x00f19}, // Tibetan Astrological Sig..Tibetan Astrological Sig
{0x00f35, 0x00f35}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung
{0x00f37, 0x00f37}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung
{0x00f39, 0x00f39}, // Tibetan Mark Tsa -phru ..Tibetan Mark Tsa -phru
{0x00f71, 0x00f7e}, // Tibetan Vowel Sign Aa ..Tibetan Sign Rjes Su Nga
{0x00f80, 0x00f84}, // Tibetan Vowel Sign Rever..Tibetan Mark Halanta
{0x00f86, 0x00f87}, // Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags
{0x00f8d, 0x00f97}, // Tibetan Subjoined Sign L..Tibetan Subjoined Letter
{0x00f99, 0x00fbc}, // Tibetan Subjoined Letter..Tibetan Subjoined Letter
{0x00fc6, 0x00fc6}, // Tibetan Symbol Padma Gda..Tibetan Symbol Padma Gda
{0x0102d, 0x01030}, // Myanmar Vowel Sign I ..Myanmar Vowel Sign Uu
{0x01032, 0x01037}, // Myanmar Vowel Sign Ai ..Myanmar Sign Dot Below
{0x01039, 0x0103a}, // Myanmar Sign Virama ..Myanmar Sign Asat
{0x0103d, 0x0103e}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M
{0x01058, 0x01059}, // Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal
{0x0105e, 0x01060}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M
{0x01071, 0x01074}, // Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah
{0x01082, 0x01082}, // Myanmar Consonant Sign S..Myanmar Consonant Sign S
{0x01085, 0x01086}, // Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan
{0x0108d, 0x0108d}, // Myanmar Sign Shan Counci..Myanmar Sign Shan Counci
{0x0109d, 0x0109d}, // Myanmar Vowel Sign Aiton..Myanmar Vowel Sign Aiton
{0x0135d, 0x0135f}, // Ethiopic Combining Gemin..Ethiopic Combining Gemin
{0x01712, 0x01714}, // Tagalog Vowel Sign I ..Tagalog Sign Virama
{0x01732, 0x01733}, // Hanunoo Vowel Sign I ..Hanunoo Vowel Sign U
{0x01752, 0x01753}, // Buhid Vowel Sign I ..Buhid Vowel Sign U
{0x01772, 0x01773}, // Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U
{0x017b4, 0x017b5}, // Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa
{0x017b7, 0x017bd}, // Khmer Vowel Sign I ..Khmer Vowel Sign Ua
{0x017c6, 0x017c6}, // Khmer Sign Nikahit ..Khmer Sign Nikahit
{0x017c9, 0x017d3}, // Khmer Sign Muusikatoan ..Khmer Sign Bathamasat
{0x017dd, 0x017dd}, // Khmer Sign Atthacan ..Khmer Sign Atthacan
{0x0180b, 0x0180d}, // Mongolian Free Variation..Mongolian Free Variation
{0x0180f, 0x0180f}, // Mongolian Free Variation..Mongolian Free Variation
{0x01885, 0x01886}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal
{0x018a9, 0x018a9}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal
{0x01920, 0x01922}, // Limbu Vowel Sign A ..Limbu Vowel Sign U
{0x01927, 0x01928}, // Limbu Vowel Sign E ..Limbu Vowel Sign O
{0x01932, 0x01932}, // Limbu Small Letter Anusv..Limbu Small Letter Anusv
{0x01939, 0x0193b}, // Limbu Sign Mukphreng ..Limbu Sign Sa-i
{0x01a17, 0x01a18}, // Buginese Vowel Sign I ..Buginese Vowel Sign U
{0x01a1b, 0x01a1b}, // Buginese Vowel Sign Ae ..Buginese Vowel Sign Ae
{0x01a56, 0x01a56}, // Tai Tham Consonant Sign ..Tai Tham Consonant Sign
{0x01a58, 0x01a5e}, // Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign
{0x01a60, 0x01a60}, // Tai Tham Sign Sakot ..Tai Tham Sign Sakot
{0x01a62, 0x01a62}, // Tai Tham Vowel Sign Mai ..Tai Tham Vowel Sign Mai
{0x01a65, 0x01a6c}, // Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B
{0x01a73, 0x01a7c}, // Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue
{0x01a7f, 0x01a7f}, // Tai Tham Combining Crypt..Tai Tham Combining Crypt
{0x01ab0, 0x01ace}, // Combining Doubled Circum..Combining Latin Small Le
{0x01b00, 0x01b03}, // Balinese Sign Ulu Ricem ..Balinese Sign Surang
{0x01b34, 0x01b34}, // Balinese Sign Rerekan ..Balinese Sign Rerekan
{0x01b36, 0x01b3a}, // Balinese Vowel Sign Ulu ..Balinese Vowel Sign Ra R
{0x01b3c, 0x01b3c}, // Balinese Vowel Sign La L..Balinese Vowel Sign La L
{0x01b42, 0x01b42}, // Balinese Vowel Sign Pepe..Balinese Vowel Sign Pepe
{0x01b6b, 0x01b73}, // Balinese Musical Symbol ..Balinese Musical Symbol
{0x01b80, 0x01b81}, // Sundanese Sign Panyecek ..Sundanese Sign Panglayar
{0x01ba2, 0x01ba5}, // Sundanese Consonant Sign..Sundanese Vowel Sign Pan
{0x01ba8, 0x01ba9}, // Sundanese Vowel Sign Pam..Sundanese Vowel Sign Pan
{0x01bab, 0x01bad}, // Sundanese Sign Virama ..Sundanese Consonant Sign
{0x01be6, 0x01be6}, // Batak Sign Tompi ..Batak Sign Tompi
{0x01be8, 0x01be9}, // Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee
{0x01bed, 0x01bed}, // Batak Vowel Sign Karo O ..Batak Vowel Sign Karo O
{0x01bef, 0x01bf1}, // Batak Vowel Sign U For S..Batak Consonant Sign H
{0x01c2c, 0x01c33}, // Lepcha Vowel Sign E ..Lepcha Consonant Sign T
{0x01c36, 0x01c37}, // Lepcha Sign Ran ..Lepcha Sign Nukta
{0x01cd0, 0x01cd2}, // Vedic Tone Karshana ..Vedic Tone Prenkha
{0x01cd4, 0x01ce0}, // Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash
{0x01ce2, 0x01ce8}, // Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda
{0x01ced, 0x01ced}, // Vedic Sign Tiryak ..Vedic Sign Tiryak
{0x01cf4, 0x01cf4}, // Vedic Tone Candra Above ..Vedic Tone Candra Above
{0x01cf8, 0x01cf9}, // Vedic Tone Ring Above ..Vedic Tone Double Ring A
{0x01dc0, 0x01dff}, // Combining Dotted Grave A..Combining Right Arrowhea
{0x020d0, 0x020f0}, // Combining Left Harpoon A..Combining Asterisk Above
{0x02cef, 0x02cf1}, // Coptic Combining Ni Abov..Coptic Combining Spiritu
{0x02d7f, 0x02d7f}, // Tifinagh Consonant Joine..Tifinagh Consonant Joine
{0x02de0, 0x02dff}, // Combining Cyrillic Lette..Combining Cyrillic Lette
{0x0302a, 0x0302d}, // Ideographic Level Tone M..Ideographic Entering Ton
{0x03099, 0x0309a}, // Combining Katakana-hirag..Combining Katakana-hirag
{0x0a66f, 0x0a672}, // Combining Cyrillic Vzmet..Combining Cyrillic Thous
{0x0a674, 0x0a67d}, // Combining Cyrillic Lette..Combining Cyrillic Payer
{0x0a69e, 0x0a69f}, // Combining Cyrillic Lette..Combining Cyrillic Lette
{0x0a6f0, 0x0a6f1}, // Bamum Combining Mark Koq..Bamum Combining Mark Tuk
{0x0a802, 0x0a802}, // Syloti Nagri Sign Dvisva..Syloti Nagri Sign Dvisva
{0x0a806, 0x0a806}, // Syloti Nagri Sign Hasant..Syloti Nagri Sign Hasant
{0x0a80b, 0x0a80b}, // Syloti Nagri Sign Anusva..Syloti Nagri Sign Anusva
{0x0a825, 0x0a826}, // Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign
{0x0a82c, 0x0a82c}, // Syloti Nagri Sign Altern..Syloti Nagri Sign Altern
{0x0a8c4, 0x0a8c5}, // Saurashtra Sign Virama ..Saurashtra Sign Candrabi
{0x0a8e0, 0x0a8f1}, // Combining Devanagari Dig..Combining Devanagari Sig
{0x0a8ff, 0x0a8ff}, // Devanagari Vowel Sign Ay..Devanagari Vowel Sign Ay
{0x0a926, 0x0a92d}, // Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop
{0x0a947, 0x0a951}, // Rejang Vowel Sign I ..Rejang Consonant Sign R
{0x0a980, 0x0a982}, // Javanese Sign Panyangga ..Javanese Sign Layar
{0x0a9b3, 0x0a9b3}, // Javanese Sign Cecak Telu..Javanese Sign Cecak Telu
{0x0a9b6, 0x0a9b9}, // Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku
{0x0a9bc, 0x0a9bd}, // Javanese Vowel Sign Pepe..Javanese Consonant Sign
{0x0a9e5, 0x0a9e5}, // Myanmar Sign Shan Saw ..Myanmar Sign Shan Saw
{0x0aa29, 0x0aa2e}, // Cham Vowel Sign Aa ..Cham Vowel Sign Oe
{0x0aa31, 0x0aa32}, // Cham Vowel Sign Au ..Cham Vowel Sign Ue
{0x0aa35, 0x0aa36}, // Cham Consonant Sign La ..Cham Consonant Sign Wa
{0x0aa43, 0x0aa43}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina
{0x0aa4c, 0x0aa4c}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina
{0x0aa7c, 0x0aa7c}, // Myanmar Sign Tai Laing T..Myanmar Sign Tai Laing T
{0x0aab0, 0x0aab0}, // Tai Viet Mai Kang ..Tai Viet Mai Kang
{0x0aab2, 0x0aab4}, // Tai Viet Vowel I ..Tai Viet Vowel U
{0x0aab7, 0x0aab8}, // Tai Viet Mai Khit ..Tai Viet Vowel Ia
{0x0aabe, 0x0aabf}, // Tai Viet Vowel Am ..Tai Viet Tone Mai Ek
{0x0aac1, 0x0aac1}, // Tai Viet Tone Mai Tho ..Tai Viet Tone Mai Tho
{0x0aaec, 0x0aaed}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
{0x0aaf6, 0x0aaf6}, // Meetei Mayek Virama ..Meetei Mayek Virama
{0x0abe5, 0x0abe5}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
{0x0abe8, 0x0abe8}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
{0x0abed, 0x0abed}, // Meetei Mayek Apun Iyek ..Meetei Mayek Apun Iyek
{0x0fb1e, 0x0fb1e}, // Hebrew Point Judeo-spani..Hebrew Point Judeo-spani
{0x0fe00, 0x0fe0f}, // Variation Selector-1 ..Variation Selector-16
{0x0fe20, 0x0fe2f}, // Combining Ligature Left ..Combining Cyrillic Titlo
{0x101fd, 0x101fd}, // Phaistos Disc Sign Combi..Phaistos Disc Sign Combi
{0x102e0, 0x102e0}, // Coptic Epact Thousands M..Coptic Epact Thousands M
{0x10376, 0x1037a}, // Combining Old Permic Let..Combining Old Permic Let
{0x10a01, 0x10a03}, // Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo
{0x10a05, 0x10a06}, // Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O
{0x10a0c, 0x10a0f}, // Kharoshthi Vowel Length ..Kharoshthi Sign Visarga
{0x10a38, 0x10a3a}, // Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo
{0x10a3f, 0x10a3f}, // Kharoshthi Virama ..Kharoshthi Virama
{0x10ae5, 0x10ae6}, // Manichaean Abbreviation ..Manichaean Abbreviation
{0x10d24, 0x10d27}, // Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas
{0x10eab, 0x10eac}, // Yezidi Combining Hamza M..Yezidi Combining Madda M
{0x10efd, 0x10eff}, // (nil) ..(nil)
{0x10f46, 0x10f50}, // Sogdian Combining Dot Be..Sogdian Combining Stroke
{0x10f82, 0x10f85}, // Old Uyghur Combining Dot..Old Uyghur Combining Two
{0x11001, 0x11001}, // Brahmi Sign Anusvara ..Brahmi Sign Anusvara
{0x11038, 0x11046}, // Brahmi Vowel Sign Aa ..Brahmi Virama
{0x11070, 0x11070}, // Brahmi Sign Old Tamil Vi..Brahmi Sign Old Tamil Vi
{0x11073, 0x11074}, // Brahmi Vowel Sign Old Ta..Brahmi Vowel Sign Old Ta
{0x1107f, 0x11081}, // Brahmi Number Joiner ..Kaithi Sign Anusvara
{0x110b3, 0x110b6}, // Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai
{0x110b9, 0x110ba}, // Kaithi Sign Virama ..Kaithi Sign Nukta
{0x110c2, 0x110c2}, // Kaithi Vowel Sign Vocali..Kaithi Vowel Sign Vocali
{0x11100, 0x11102}, // Chakma Sign Candrabindu ..Chakma Sign Visarga
{0x11127, 0x1112b}, // Chakma Vowel Sign A ..Chakma Vowel Sign Uu
{0x1112d, 0x11134}, // Chakma Vowel Sign Ai ..Chakma Maayyaa
{0x11173, 0x11173}, // Mahajani Sign Nukta ..Mahajani Sign Nukta
{0x11180, 0x11181}, // Sharada Sign Candrabindu..Sharada Sign Anusvara
{0x111b6, 0x111be}, // Sharada Vowel Sign U ..Sharada Vowel Sign O
{0x111c9, 0x111cc}, // Sharada Sandhi Mark ..Sharada Extra Short Vowe
{0x111cf, 0x111cf}, // Sharada Sign Inverted Ca..Sharada Sign Inverted Ca
{0x1122f, 0x11231}, // Khojki Vowel Sign U ..Khojki Vowel Sign Ai
{0x11234, 0x11234}, // Khojki Sign Anusvara ..Khojki Sign Anusvara
{0x11236, 0x11237}, // Khojki Sign Nukta ..Khojki Sign Shadda
{0x1123e, 0x1123e}, // Khojki Sign Sukun ..Khojki Sign Sukun
{0x11241, 0x11241}, // (nil) ..(nil)
{0x112df, 0x112df}, // Khudawadi Sign Anusvara ..Khudawadi Sign Anusvara
{0x112e3, 0x112ea}, // Khudawadi Vowel Sign U ..Khudawadi Sign Virama
{0x11300, 0x11301}, // Grantha Sign Combining A..Grantha Sign Candrabindu
{0x1133b, 0x1133c}, // Combining Bindu Below ..Grantha Sign Nukta
{0x11340, 0x11340}, // Grantha Vowel Sign Ii ..Grantha Vowel Sign Ii
{0x11366, 0x1136c}, // Combining Grantha Digit ..Combining Grantha Digit
{0x11370, 0x11374}, // Combining Grantha Letter..Combining Grantha Letter
{0x11438, 0x1143f}, // Newa Vowel Sign U ..Newa Vowel Sign Ai
{0x11442, 0x11444}, // Newa Sign Virama ..Newa Sign Anusvara
{0x11446, 0x11446}, // Newa Sign Nukta ..Newa Sign Nukta
{0x1145e, 0x1145e}, // Newa Sandhi Mark ..Newa Sandhi Mark
{0x114b3, 0x114b8}, // Tirhuta Vowel Sign U ..Tirhuta Vowel Sign Vocal
{0x114ba, 0x114ba}, // Tirhuta Vowel Sign Short..Tirhuta Vowel Sign Short
{0x114bf, 0x114c0}, // Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara
{0x114c2, 0x114c3}, // Tirhuta Sign Virama ..Tirhuta Sign Nukta
{0x115b2, 0x115b5}, // Siddham Vowel Sign U ..Siddham Vowel Sign Vocal
{0x115bc, 0x115bd}, // Siddham Sign Candrabindu..Siddham Sign Anusvara
{0x115bf, 0x115c0}, // Siddham Sign Virama ..Siddham Sign Nukta
{0x115dc, 0x115dd}, // Siddham Vowel Sign Alter..Siddham Vowel Sign Alter
{0x11633, 0x1163a}, // Modi Vowel Sign U ..Modi Vowel Sign Ai
{0x1163d, 0x1163d}, // Modi Sign Anusvara ..Modi Sign Anusvara
{0x1163f, 0x11640}, // Modi Sign Virama ..Modi Sign Ardhacandra
{0x116ab, 0x116ab}, // Takri Sign Anusvara ..Takri Sign Anusvara
{0x116ad, 0x116ad}, // Takri Vowel Sign Aa ..Takri Vowel Sign Aa
{0x116b0, 0x116b5}, // Takri Vowel Sign U ..Takri Vowel Sign Au
{0x116b7, 0x116b7}, // Takri Sign Nukta ..Takri Sign Nukta
{0x1171d, 0x1171f}, // Ahom Consonant Sign Medi..Ahom Consonant Sign Medi
{0x11722, 0x11725}, // Ahom Vowel Sign I ..Ahom Vowel Sign Uu
{0x11727, 0x1172b}, // Ahom Vowel Sign Aw ..Ahom Sign Killer
{0x1182f, 0x11837}, // Dogra Vowel Sign U ..Dogra Sign Anusvara
{0x11839, 0x1183a}, // Dogra Sign Virama ..Dogra Sign Nukta
{0x1193b, 0x1193c}, // Dives Akuru Sign Anusvar..Dives Akuru Sign Candrab
{0x1193e, 0x1193e}, // Dives Akuru Virama ..Dives Akuru Virama
{0x11943, 0x11943}, // Dives Akuru Sign Nukta ..Dives Akuru Sign Nukta
{0x119d4, 0x119d7}, // Nandinagari Vowel Sign U..Nandinagari Vowel Sign V
{0x119da, 0x119db}, // Nandinagari Vowel Sign E..Nandinagari Vowel Sign A
{0x119e0, 0x119e0}, // Nandinagari Sign Virama ..Nandinagari Sign Virama
{0x11a01, 0x11a0a}, // Zanabazar Square Vowel S..Zanabazar Square Vowel L
{0x11a33, 0x11a38}, // Zanabazar Square Final C..Zanabazar Square Sign An
{0x11a3b, 0x11a3e}, // Zanabazar Square Cluster..Zanabazar Square Cluster
{0x11a47, 0x11a47}, // Zanabazar Square Subjoin..Zanabazar Square Subjoin
{0x11a51, 0x11a56}, // Soyombo Vowel Sign I ..Soyombo Vowel Sign Oe
{0x11a59, 0x11a5b}, // Soyombo Vowel Sign Vocal..Soyombo Vowel Length Mar
{0x11a8a, 0x11a96}, // Soyombo Final Consonant ..Soyombo Sign Anusvara
{0x11a98, 0x11a99}, // Soyombo Gemination Mark ..Soyombo Subjoiner
{0x11c30, 0x11c36}, // Bhaiksuki Vowel Sign I ..Bhaiksuki Vowel Sign Voc
{0x11c38, 0x11c3d}, // Bhaiksuki Vowel Sign E ..Bhaiksuki Sign Anusvara
{0x11c3f, 0x11c3f}, // Bhaiksuki Sign Virama ..Bhaiksuki Sign Virama
{0x11c92, 0x11ca7}, // Marchen Subjoined Letter..Marchen Subjoined Letter
{0x11caa, 0x11cb0}, // Marchen Subjoined Letter..Marchen Vowel Sign Aa
{0x11cb2, 0x11cb3}, // Marchen Vowel Sign U ..Marchen Vowel Sign E
{0x11cb5, 0x11cb6}, // Marchen Sign Anusvara ..Marchen Sign Candrabindu
{0x11d31, 0x11d36}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign
{0x11d3a, 0x11d3a}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign
{0x11d3c, 0x11d3d}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign
{0x11d3f, 0x11d45}, // Masaram Gondi Vowel Sign..Masaram Gondi Virama
{0x11d47, 0x11d47}, // Masaram Gondi Ra-kara ..Masaram Gondi Ra-kara
{0x11d90, 0x11d91}, // Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign
{0x11d95, 0x11d95}, // Gunjala Gondi Sign Anusv..Gunjala Gondi Sign Anusv
{0x11d97, 0x11d97}, // Gunjala Gondi Virama ..Gunjala Gondi Virama
{0x11ef3, 0x11ef4}, // Makasar Vowel Sign I ..Makasar Vowel Sign U
{0x11f00, 0x11f01}, // (nil) ..(nil)
{0x11f36, 0x11f3a}, // (nil) ..(nil)
{0x11f40, 0x11f40}, // (nil) ..(nil)
{0x11f42, 0x11f42}, // (nil) ..(nil)
{0x13440, 0x13440}, // (nil) ..(nil)
{0x13447, 0x13455}, // (nil) ..(nil)
{0x16af0, 0x16af4}, // Bassa Vah Combining High..Bassa Vah Combining High
{0x16b30, 0x16b36}, // Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta
{0x16f4f, 0x16f4f}, // Miao Sign Consonant Modi..Miao Sign Consonant Modi
{0x16f8f, 0x16f92}, // Miao Tone Right ..Miao Tone Below
{0x16fe4, 0x16fe4}, // Khitan Small Script Fill..Khitan Small Script Fill
{0x1bc9d, 0x1bc9e}, // Duployan Thick Letter Se..Duployan Double Mark
{0x1cf00, 0x1cf2d}, // Znamenny Combining Mark ..Znamenny Combining Mark
{0x1cf30, 0x1cf46}, // Znamenny Combining Tonal..Znamenny Priznak Modifie
{0x1d167, 0x1d169}, // Musical Symbol Combining..Musical Symbol Combining
{0x1d17b, 0x1d182}, // Musical Symbol Combining..Musical Symbol Combining
{0x1d185, 0x1d18b}, // Musical Symbol Combining..Musical Symbol Combining
{0x1d1aa, 0x1d1ad}, // Musical Symbol Combining..Musical Symbol Combining
{0x1d242, 0x1d244}, // Combining Greek Musical ..Combining Greek Musical
{0x1da00, 0x1da36}, // Signwriting Head Rim ..Signwriting Air Sucking
{0x1da3b, 0x1da6c}, // Signwriting Mouth Closed..Signwriting Excitement
{0x1da75, 0x1da75}, // Signwriting Upper Body T..Signwriting Upper Body T
{0x1da84, 0x1da84}, // Signwriting Location Hea..Signwriting Location Hea
{0x1da9b, 0x1da9f}, // Signwriting Fill Modifie..Signwriting Fill Modifie
{0x1daa1, 0x1daaf}, // Signwriting Rotation Mod..Signwriting Rotation Mod
{0x1e000, 0x1e006}, // Combining Glagolitic Let..Combining Glagolitic Let
{0x1e008, 0x1e018}, // Combining Glagolitic Let..Combining Glagolitic Let
{0x1e01b, 0x1e021}, // Combining Glagolitic Let..Combining Glagolitic Let
{0x1e023, 0x1e024}, // Combining Glagolitic Let..Combining Glagolitic Let
{0x1e026, 0x1e02a}, // Combining Glagolitic Let..Combining Glagolitic Let
{0x1e08f, 0x1e08f}, // (nil) ..(nil)
{0x1e130, 0x1e136}, // Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T
{0x1e2ae, 0x1e2ae}, // Toto Sign Rising Tone ..Toto Sign Rising Tone
{0x1e2ec, 0x1e2ef}, // Wancho Tone Tup ..Wancho Tone Koini
{0x1e4ec, 0x1e4ef}, // (nil) ..(nil)
{0x1e8d0, 0x1e8d6}, // Mende Kikakui Combining ..Mende Kikakui Combining
{0x1e944, 0x1e94a}, // Adlam Alif Lengthener ..Adlam Nukta
{0xe0100, 0xe01ef}, // Variation Selector-17 ..Variation Selector-256
};
// https://github.com/jquast/wcwidth/blob/master/wcwidth/table_wide.py
// from https://github.com/jquast/wcwidth/pull/64
// at commit 1b9b6585b0080ea5cb88dc9815796505724793fe (2022-12-16):
private static final int[][] WIDE_EASTASIAN = {
{0x01100, 0x0115f}, // Hangul Choseong Kiyeok ..Hangul Choseong Filler
{0x0231a, 0x0231b}, // Watch ..Hourglass
{0x02329, 0x0232a}, // Left-pointing Angle Brac..Right-pointing Angle Bra
{0x023e9, 0x023ec}, // Black Right-pointing Dou..Black Down-pointing Doub
{0x023f0, 0x023f0}, // Alarm Clock ..Alarm Clock
{0x023f3, 0x023f3}, // Hourglass With Flowing S..Hourglass With Flowing S
{0x025fd, 0x025fe}, // White Medium Small Squar..Black Medium Small Squar
{0x02614, 0x02615}, // Umbrella With Rain Drops..Hot Beverage
{0x02648, 0x02653}, // Aries ..Pisces
{0x0267f, 0x0267f}, // Wheelchair Symbol ..Wheelchair Symbol
{0x02693, 0x02693}, // Anchor ..Anchor
{0x026a1, 0x026a1}, // High Voltage Sign ..High Voltage Sign
{0x026aa, 0x026ab}, // Medium White Circle ..Medium Black Circle
{0x026bd, 0x026be}, // Soccer Ball ..Baseball
{0x026c4, 0x026c5}, // Snowman Without Snow ..Sun Behind Cloud
{0x026ce, 0x026ce}, // Ophiuchus ..Ophiuchus
{0x026d4, 0x026d4}, // No Entry ..No Entry
{0x026ea, 0x026ea}, // Church ..Church
{0x026f2, 0x026f3}, // Fountain ..Flag In Hole
{0x026f5, 0x026f5}, // Sailboat ..Sailboat
{0x026fa, 0x026fa}, // Tent ..Tent
{0x026fd, 0x026fd}, // Fuel Pump ..Fuel Pump
{0x02705, 0x02705}, // White Heavy Check Mark ..White Heavy Check Mark
{0x0270a, 0x0270b}, // Raised Fist ..Raised Hand
{0x02728, 0x02728}, // Sparkles ..Sparkles
{0x0274c, 0x0274c}, // Cross Mark ..Cross Mark
{0x0274e, 0x0274e}, // Negative Squared Cross M..Negative Squared Cross M
{0x02753, 0x02755}, // Black Question Mark Orna..White Exclamation Mark O
{0x02757, 0x02757}, // Heavy Exclamation Mark S..Heavy Exclamation Mark S
{0x02795, 0x02797}, // Heavy Plus Sign ..Heavy Division Sign
{0x027b0, 0x027b0}, // Curly Loop ..Curly Loop
{0x027bf, 0x027bf}, // Double Curly Loop ..Double Curly Loop
{0x02b1b, 0x02b1c}, // Black Large Square ..White Large Square
{0x02b50, 0x02b50}, // White Medium Star ..White Medium Star
{0x02b55, 0x02b55}, // Heavy Large Circle ..Heavy Large Circle
{0x02e80, 0x02e99}, // Cjk Radical Repeat ..Cjk Radical Rap
{0x02e9b, 0x02ef3}, // Cjk Radical Choke ..Cjk Radical C-simplified
{0x02f00, 0x02fd5}, // Kangxi Radical One ..Kangxi Radical Flute
{0x02ff0, 0x02ffb}, // Ideographic Description ..Ideographic Description
{0x03000, 0x0303e}, // Ideographic Space ..Ideographic Variation In
{0x03041, 0x03096}, // Hiragana Letter Small A ..Hiragana Letter Small Ke
{0x03099, 0x030ff}, // Combining Katakana-hirag..Katakana Digraph Koto
{0x03105, 0x0312f}, // Bopomofo Letter B ..Bopomofo Letter Nn
{0x03131, 0x0318e}, // Hangul Letter Kiyeok ..Hangul Letter Araeae
{0x03190, 0x031e3}, // Ideographic Annotation L..Cjk Stroke Q
{0x031f0, 0x0321e}, // Katakana Letter Small Ku..Parenthesized Korean Cha
{0x03220, 0x03247}, // Parenthesized Ideograph ..Circled Ideograph Koto
{0x03250, 0x04dbf}, // Partnership Sign ..Cjk Unified Ideograph-4d
{0x04e00, 0x0a48c}, // Cjk Unified Ideograph-4e..Yi Syllable Yyr
{0x0a490, 0x0a4c6}, // Yi Radical Qot ..Yi Radical Ke
{0x0a960, 0x0a97c}, // Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo
{0x0ac00, 0x0d7a3}, // Hangul Syllable Ga ..Hangul Syllable Hih
{0x0f900, 0x0faff}, // Cjk Compatibility Ideogr..(nil)
{0x0fe10, 0x0fe19}, // Presentation Form For Ve..Presentation Form For Ve
{0x0fe30, 0x0fe52}, // Presentation Form For Ve..Small Full Stop
{0x0fe54, 0x0fe66}, // Small Semicolon ..Small Equals Sign
{0x0fe68, 0x0fe6b}, // Small Reverse Solidus ..Small Commercial At
{0x0ff01, 0x0ff60}, // Fullwidth Exclamation Ma..Fullwidth Right White Pa
{0x0ffe0, 0x0ffe6}, // Fullwidth Cent Sign ..Fullwidth Won Sign
{0x16fe0, 0x16fe4}, // Tangut Iteration Mark ..Khitan Small Script Fill
{0x16ff0, 0x16ff1}, // Vietnamese Alternate Rea..Vietnamese Alternate Rea
{0x17000, 0x187f7}, // (nil) ..(nil)
{0x18800, 0x18cd5}, // Tangut Component-001 ..Khitan Small Script Char
{0x18d00, 0x18d08}, // (nil) ..(nil)
{0x1aff0, 0x1aff3}, // Katakana Letter Minnan T..Katakana Letter Minnan T
{0x1aff5, 0x1affb}, // Katakana Letter Minnan T..Katakana Letter Minnan N
{0x1affd, 0x1affe}, // Katakana Letter Minnan N..Katakana Letter Minnan N
{0x1b000, 0x1b122}, // Katakana Letter Archaic ..Katakana Letter Archaic
{0x1b132, 0x1b132}, // (nil) ..(nil)
{0x1b150, 0x1b152}, // Hiragana Letter Small Wi..Hiragana Letter Small Wo
{0x1b155, 0x1b155}, // (nil) ..(nil)
{0x1b164, 0x1b167}, // Katakana Letter Small Wi..Katakana Letter Small N
{0x1b170, 0x1b2fb}, // Nushu Character-1b170 ..Nushu Character-1b2fb
{0x1f004, 0x1f004}, // Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon
{0x1f0cf, 0x1f0cf}, // Playing Card Black Joker..Playing Card Black Joker
{0x1f18e, 0x1f18e}, // Negative Squared Ab ..Negative Squared Ab
{0x1f191, 0x1f19a}, // Squared Cl ..Squared Vs
{0x1f200, 0x1f202}, // Square Hiragana Hoka ..Squared Katakana Sa
{0x1f210, 0x1f23b}, // Squared Cjk Unified Ideo..Squared Cjk Unified Ideo
{0x1f240, 0x1f248}, // Tortoise Shell Bracketed..Tortoise Shell Bracketed
{0x1f250, 0x1f251}, // Circled Ideograph Advant..Circled Ideograph Accept
{0x1f260, 0x1f265}, // Rounded Symbol For Fu ..Rounded Symbol For Cai
{0x1f300, 0x1f320}, // Cyclone ..Shooting Star
{0x1f32d, 0x1f335}, // Hot Dog ..Cactus
{0x1f337, 0x1f37c}, // Tulip ..Baby Bottle
{0x1f37e, 0x1f393}, // Bottle With Popping Cork..Graduation Cap
{0x1f3a0, 0x1f3ca}, // Carousel Horse ..Swimmer
{0x1f3cf, 0x1f3d3}, // Cricket Bat And Ball ..Table Tennis Paddle And
{0x1f3e0, 0x1f3f0}, // House Building ..European Castle
{0x1f3f4, 0x1f3f4}, // Waving Black Flag ..Waving Black Flag
{0x1f3f8, 0x1f43e}, // Badminton Racquet And Sh..Paw Prints
{0x1f440, 0x1f440}, // Eyes ..Eyes
{0x1f442, 0x1f4fc}, // Ear ..Videocassette
{0x1f4ff, 0x1f53d}, // Prayer Beads ..Down-pointing Small Red
{0x1f54b, 0x1f54e}, // Kaaba ..Menorah With Nine Branch
{0x1f550, 0x1f567}, // Clock Face One Oclock ..Clock Face Twelve-thirty
{0x1f57a, 0x1f57a}, // Man Dancing ..Man Dancing
{0x1f595, 0x1f596}, // Reversed Hand With Middl..Raised Hand With Part Be
{0x1f5a4, 0x1f5a4}, // Black Heart ..Black Heart
{0x1f5fb, 0x1f64f}, // Mount Fuji ..Person With Folded Hands
{0x1f680, 0x1f6c5}, // Rocket ..Left Luggage
{0x1f6cc, 0x1f6cc}, // Sleeping Accommodation ..Sleeping Accommodation
{0x1f6d0, 0x1f6d2}, // Place Of Worship ..Shopping Trolley
{0x1f6d5, 0x1f6d7}, // Hindu Temple ..Elevator
{0x1f6dc, 0x1f6df}, // (nil) ..Ring Buoy
{0x1f6eb, 0x1f6ec}, // Airplane Departure ..Airplane Arriving
{0x1f6f4, 0x1f6fc}, // Scooter ..Roller Skate
{0x1f7e0, 0x1f7eb}, // Large Orange Circle ..Large Brown Square
{0x1f7f0, 0x1f7f0}, // Heavy Equals Sign ..Heavy Equals Sign
{0x1f90c, 0x1f93a}, // Pinched Fingers ..Fencer
{0x1f93c, 0x1f945}, // Wrestlers ..Goal Net
{0x1f947, 0x1f9ff}, // First Place Medal ..Nazar Amulet
{0x1fa70, 0x1fa7c}, // Ballet Shoes ..Crutch
{0x1fa80, 0x1fa88}, // Yo-yo ..(nil)
{0x1fa90, 0x1fabd}, // Ringed Planet ..(nil)
{0x1fabf, 0x1fac5}, // (nil) ..Person With Crown
{0x1face, 0x1fadb}, // (nil) ..(nil)
{0x1fae0, 0x1fae8}, // Melting Face ..(nil)
{0x1faf0, 0x1faf8}, // Hand With Index Finger A..(nil)
{0x20000, 0x2fffd}, // Cjk Unified Ideograph-20..(nil)
{0x30000, 0x3fffd}, // Cjk Unified Ideograph-30..(nil)
};
private static boolean intable(int[][] table, int c) {
// First quick check f|| Latin1 etc. characters.
if (c < table[0][0]) return false;
// Binary search in table.
int bot = 0;
int top = table.length - 1; // (int)(size / sizeof(struct interval) - 1);
while (top >= bot) {
int mid = (bot + top) / 2;
if (table[mid][1] < c) {
bot = mid + 1;
} else if (table[mid][0] > c) {
top = mid - 1;
} else {
return true;
}
}
return false;
}
/** Return the terminal display width of a code point: 0, 1 || 2. */
public static int width(int ucs) {
if (ucs == 0 ||
ucs == 0x034F ||
(0x200B <= ucs && ucs <= 0x200F) ||
ucs == 0x2028 ||
ucs == 0x2029 ||
(0x202A <= ucs && ucs <= 0x202E) ||
(0x2060 <= ucs && ucs <= 0x2063)) {
return 0;
}
// C0/C1 control characters
// Termux change: Return 0 instead of -1.
if (ucs < 32 || (0x07F <= ucs && ucs < 0x0A0)) return 0;
// combining characters with zero width
if (intable(ZERO_WIDTH, ucs)) return 0;
return intable(WIDE_EASTASIAN, ucs) ? 2 : 1;
}
/** The width at an index position in a java char array. */
public static int width(char[] chars, int index) {
char c = chars[index];
return Character.isHighSurrogate(c) ? width(Character.toCodePoint(c, chars[index + 1])) : width(c);
}
/**
* The zero width characters count like combining characters in the `chars` array from start
* index to end index (exclusive).
*/
public static int zeroWidthCharsCount(char[] chars, int start, int end) {
if (start < 0 || start >= chars.length)
return 0;
int count = 0;
for (int i = start; i < end && i < chars.length;) {
if (Character.isHighSurrogate(chars[i])) {
if (width(Character.toCodePoint(chars[i], chars[i + 1])) <= 0) {
count++;
}
i += 2;
} else {
if (width(chars[i]) <= 0) {
count++;
}
i++;
}
}
return count;
}
}

View File

@@ -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();
}
}

View File

@@ -0,0 +1,249 @@
package com.termux.view;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import com.termux.terminal.TerminalBuffer;
import com.termux.terminal.TerminalEmulator;
import com.termux.terminal.TerminalRow;
import com.termux.terminal.TextStyle;
import com.termux.terminal.WcWidth;
/**
* Renderer of a {@link TerminalEmulator} into a {@link Canvas}.
* <p/>
* Saves font metrics, so needs to be recreated each time the typeface or font size changes.
*/
public final class TerminalRenderer {
final int mTextSize;
final Typeface mTypeface;
private final Paint mTextPaint = new Paint();
/** The width of a single mono spaced character obtained by {@link Paint#measureText(String)} on a single 'X'. */
final float mFontWidth;
/** The {@link Paint#getFontSpacing()}. See http://www.fampennings.nl/maarten/android/08numgrid/font.png */
final int mFontLineSpacing;
/** The {@link Paint#ascent()}. See http://www.fampennings.nl/maarten/android/08numgrid/font.png */
private final int mFontAscent;
/** The {@link #mFontLineSpacing} + {@link #mFontAscent}. */
final int mFontLineSpacingAndAscent;
private final float[] asciiMeasures = new float[127];
public TerminalRenderer(int textSize, Typeface typeface) {
mTextSize = textSize;
mTypeface = typeface;
mTextPaint.setTypeface(typeface);
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(textSize);
mFontLineSpacing = (int) Math.ceil(mTextPaint.getFontSpacing());
mFontAscent = (int) Math.ceil(mTextPaint.ascent());
mFontLineSpacingAndAscent = mFontLineSpacing + mFontAscent;
mFontWidth = mTextPaint.measureText("X");
StringBuilder sb = new StringBuilder(" ");
for (int i = 0; i < asciiMeasures.length; i++) {
sb.setCharAt(0, (char) i);
asciiMeasures[i] = mTextPaint.measureText(sb, 0, 1);
}
}
/** Render the terminal to a canvas with at a specified row scroll, and an optional rectangular selection. */
public final void render(TerminalEmulator mEmulator, Canvas canvas, int topRow,
int selectionY1, int selectionY2, int selectionX1, int selectionX2) {
final boolean reverseVideo = mEmulator.isReverseVideo();
final int endRow = topRow + mEmulator.mRows;
final int columns = mEmulator.mColumns;
final int cursorCol = mEmulator.getCursorCol();
final int cursorRow = mEmulator.getCursorRow();
final boolean cursorVisible = mEmulator.shouldCursorBeVisible();
final TerminalBuffer screen = mEmulator.getScreen();
final int[] palette = mEmulator.mColors.mCurrentColors;
final int cursorShape = mEmulator.getCursorStyle();
if (reverseVideo)
canvas.drawColor(palette[TextStyle.COLOR_INDEX_FOREGROUND], PorterDuff.Mode.SRC);
float heightOffset = mFontLineSpacingAndAscent;
for (int row = topRow; row < endRow; row++) {
heightOffset += mFontLineSpacing;
final int cursorX = (row == cursorRow && cursorVisible) ? cursorCol : -1;
int selx1 = -1, selx2 = -1;
if (row >= selectionY1 && row <= selectionY2) {
if (row == selectionY1) selx1 = selectionX1;
selx2 = (row == selectionY2) ? selectionX2 : mEmulator.mColumns;
}
TerminalRow lineObject = screen.allocateFullLineIfNecessary(screen.externalToInternalRow(row));
final char[] line = lineObject.mText;
final int charsUsedInLine = lineObject.getSpaceUsed();
long lastRunStyle = 0;
boolean lastRunInsideCursor = false;
boolean lastRunInsideSelection = false;
int lastRunStartColumn = -1;
int lastRunStartIndex = 0;
boolean lastRunFontWidthMismatch = false;
int currentCharIndex = 0;
float measuredWidthForRun = 0.f;
for (int column = 0; column < columns; ) {
final char charAtIndex = line[currentCharIndex];
final boolean charIsHighsurrogate = Character.isHighSurrogate(charAtIndex);
final int charsForCodePoint = charIsHighsurrogate ? 2 : 1;
final int codePoint = charIsHighsurrogate ? Character.toCodePoint(charAtIndex, line[currentCharIndex + 1]) : charAtIndex;
final int codePointWcWidth = WcWidth.width(codePoint);
final boolean insideCursor = (cursorX == column || (codePointWcWidth == 2 && cursorX == column + 1));
final boolean insideSelection = column >= selx1 && column <= selx2;
final long style = lineObject.getStyle(column);
// Check if the measured text width for this code point is not the same as that expected by wcwidth().
// This could happen for some fonts which are not truly monospace, or for more exotic characters such as
// smileys which android font renders as wide.
// If this is detected, we draw this code point scaled to match what wcwidth() expects.
final float measuredCodePointWidth = (codePoint < asciiMeasures.length) ? asciiMeasures[codePoint] : mTextPaint.measureText(line,
currentCharIndex, charsForCodePoint);
final boolean fontWidthMismatch = Math.abs(measuredCodePointWidth / mFontWidth - codePointWcWidth) > 0.01;
if (style != lastRunStyle || insideCursor != lastRunInsideCursor || insideSelection != lastRunInsideSelection || fontWidthMismatch || lastRunFontWidthMismatch) {
if (column == 0) {
// Skip first column as there is nothing to draw, just record the current style.
} else {
final int columnWidthSinceLastRun = column - lastRunStartColumn;
final int charsSinceLastRun = currentCharIndex - lastRunStartIndex;
int cursorColor = lastRunInsideCursor ? mEmulator.mColors.mCurrentColors[TextStyle.COLOR_INDEX_CURSOR] : 0;
boolean invertCursorTextColor = false;
if (lastRunInsideCursor && cursorShape == TerminalEmulator.TERMINAL_CURSOR_STYLE_BLOCK) {
invertCursorTextColor = true;
}
drawTextRun(canvas, line, palette, heightOffset, lastRunStartColumn, columnWidthSinceLastRun,
lastRunStartIndex, charsSinceLastRun, measuredWidthForRun,
cursorColor, cursorShape, lastRunStyle, reverseVideo || invertCursorTextColor || lastRunInsideSelection);
}
measuredWidthForRun = 0.f;
lastRunStyle = style;
lastRunInsideCursor = insideCursor;
lastRunInsideSelection = insideSelection;
lastRunStartColumn = column;
lastRunStartIndex = currentCharIndex;
lastRunFontWidthMismatch = fontWidthMismatch;
}
measuredWidthForRun += measuredCodePointWidth;
column += codePointWcWidth;
currentCharIndex += charsForCodePoint;
while (currentCharIndex < charsUsedInLine && WcWidth.width(line, currentCharIndex) <= 0) {
// Eat combining chars so that they are treated as part of the last non-combining code point,
// instead of e.g. being considered inside the cursor in the next run.
currentCharIndex += Character.isHighSurrogate(line[currentCharIndex]) ? 2 : 1;
}
}
final int columnWidthSinceLastRun = columns - lastRunStartColumn;
final int charsSinceLastRun = currentCharIndex - lastRunStartIndex;
int cursorColor = lastRunInsideCursor ? mEmulator.mColors.mCurrentColors[TextStyle.COLOR_INDEX_CURSOR] : 0;
boolean invertCursorTextColor = false;
if (lastRunInsideCursor && cursorShape == TerminalEmulator.TERMINAL_CURSOR_STYLE_BLOCK) {
invertCursorTextColor = true;
}
drawTextRun(canvas, line, palette, heightOffset, lastRunStartColumn, columnWidthSinceLastRun, lastRunStartIndex, charsSinceLastRun,
measuredWidthForRun, cursorColor, cursorShape, lastRunStyle, reverseVideo || invertCursorTextColor || lastRunInsideSelection);
}
}
private void drawTextRun(Canvas canvas, char[] text, int[] palette, float y, int startColumn, int runWidthColumns,
int startCharIndex, int runWidthChars, float mes, int cursor, int cursorStyle,
long textStyle, boolean reverseVideo) {
int foreColor = TextStyle.decodeForeColor(textStyle);
final int effect = TextStyle.decodeEffect(textStyle);
int backColor = TextStyle.decodeBackColor(textStyle);
final boolean bold = (effect & (TextStyle.CHARACTER_ATTRIBUTE_BOLD | TextStyle.CHARACTER_ATTRIBUTE_BLINK)) != 0;
final boolean underline = (effect & TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE) != 0;
final boolean italic = (effect & TextStyle.CHARACTER_ATTRIBUTE_ITALIC) != 0;
final boolean strikeThrough = (effect & TextStyle.CHARACTER_ATTRIBUTE_STRIKETHROUGH) != 0;
final boolean dim = (effect & TextStyle.CHARACTER_ATTRIBUTE_DIM) != 0;
if ((foreColor & 0xff000000) != 0xff000000) {
// Let bold have bright colors if applicable (one of the first 8):
if (bold && foreColor >= 0 && foreColor < 8) foreColor += 8;
foreColor = palette[foreColor];
}
if ((backColor & 0xff000000) != 0xff000000) {
backColor = palette[backColor];
}
// Reverse video here if _one and only one_ of the reverse flags are set:
final boolean reverseVideoHere = reverseVideo ^ (effect & (TextStyle.CHARACTER_ATTRIBUTE_INVERSE)) != 0;
if (reverseVideoHere) {
int tmp = foreColor;
foreColor = backColor;
backColor = tmp;
}
float left = startColumn * mFontWidth;
float right = left + runWidthColumns * mFontWidth;
mes = mes / mFontWidth;
boolean savedMatrix = false;
if (Math.abs(mes - runWidthColumns) > 0.01) {
canvas.save();
canvas.scale(runWidthColumns / mes, 1.f);
left *= mes / runWidthColumns;
right *= mes / runWidthColumns;
savedMatrix = true;
}
if (backColor != palette[TextStyle.COLOR_INDEX_BACKGROUND]) {
// Only draw non-default background.
mTextPaint.setColor(backColor);
canvas.drawRect(left, y - mFontLineSpacingAndAscent + mFontAscent, right, y, mTextPaint);
}
if (cursor != 0) {
mTextPaint.setColor(cursor);
float cursorHeight = mFontLineSpacingAndAscent - mFontAscent;
if (cursorStyle == TerminalEmulator.TERMINAL_CURSOR_STYLE_UNDERLINE) cursorHeight /= 4.;
else if (cursorStyle == TerminalEmulator.TERMINAL_CURSOR_STYLE_BAR) right -= ((right - left) * 3) / 4.;
canvas.drawRect(left, y - cursorHeight, right, y, mTextPaint);
}
if ((effect & TextStyle.CHARACTER_ATTRIBUTE_INVISIBLE) == 0) {
if (dim) {
int red = (0xFF & (foreColor >> 16));
int green = (0xFF & (foreColor >> 8));
int blue = (0xFF & foreColor);
// Dim color handling used by libvte which in turn took it from xterm
// (https://bug735245.bugzilla-attachments.gnome.org/attachment.cgi?id=284267):
red = red * 2 / 3;
green = green * 2 / 3;
blue = blue * 2 / 3;
foreColor = 0xFF000000 + (red << 16) + (green << 8) + blue;
}
mTextPaint.setFakeBoldText(bold);
mTextPaint.setUnderlineText(underline);
mTextPaint.setTextSkewX(italic ? -0.35f : 0.f);
mTextPaint.setStrikeThruText(strikeThrough);
mTextPaint.setColor(foreColor);
// The text alignment is the default Paint.Align.LEFT.
canvas.drawTextRun(text, startCharIndex, runWidthChars, startCharIndex, runWidthChars, left, y - mFontLineSpacingAndAscent, false, mTextPaint);
}
if (savedMatrix) canvas.restore();
}
public float getFontWidth() {
return mFontWidth;
}
public int getFontLineSpacing() {
return mFontLineSpacing;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
package com.termux.view;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.termux.terminal.TerminalSession;
/**
* The interface for communication between {@link TerminalView} and its client. It allows for getting
* various configuration options from the client and for sending back data to the client like logs,
* key events, both hardware and IME (which makes it different from that available with
* {@link View#setOnKeyListener(View.OnKeyListener)}, etc. It must be set for the
* {@link TerminalView} through {@link TerminalView#setTerminalViewClient(TerminalViewClient)}.
*/
public interface TerminalViewClient {
/**
* Callback function on scale events according to {@link ScaleGestureDetector#getScaleFactor()}.
*/
float onScale(float scale);
/**
* On a single tap on the terminal if terminal mouse reporting not enabled.
*/
void onSingleTapUp(MotionEvent e);
boolean shouldBackButtonBeMappedToEscape();
boolean shouldEnforceCharBasedInput();
boolean shouldUseCtrlSpaceWorkaround();
boolean isTerminalViewSelected();
void copyModeChanged(boolean copyMode);
boolean onKeyDown(int keyCode, KeyEvent e, TerminalSession session);
boolean onKeyUp(int keyCode, KeyEvent e);
boolean onLongPress(MotionEvent event);
boolean readControlKey();
boolean readAltKey();
boolean readShiftKey();
boolean readFnKey();
boolean onCodePoint(int codePoint, boolean ctrlDown, TerminalSession session);
void onEmulatorSet();
void logError(String tag, String message);
void logWarn(String tag, String message);
void logInfo(String tag, String message);
void logDebug(String tag, String message);
void logVerbose(String tag, String message);
void logStackTraceWithMessage(String tag, String message, Exception e);
void logStackTrace(String tag, Exception e);
}

View File

@@ -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();
}

View File

@@ -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();
}
}

View File

@@ -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;
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp"
android:height="24dp"
android:viewportWidth="132"
android:viewportHeight="66">
<path
android:pathData="M52.3,1.6c-5.7,2.1 -12.9,8.6 -16,14.8 -2.2,4.1 -2.8,6.9 -3.1,14.3 -0.6,12.6 1.3,17.8 9.3,25.8 8,8 13.2,9.9 25.8,9.3 11.1,-0.5 17.3,-3.2 23.5,-10.3 6.5,-7.4 7.2,-10.8 7.2,-34.7l0,-20.8 -21.2,0.1c-16.1,-0 -22.3,0.4 -25.5,1.5z"
android:fillColor="#2196F3"
android:strokeColor="#00000000"/>
</vector>

View File

@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp"
android:height="24dp"
android:viewportWidth="132"
android:viewportHeight="66">
<path
android:pathData="M33,20.8c0,23.9 0.7,27.3 7.2,34.7 6.2,7.1 12.4,9.8 23.5,10.3 12.6,0.6 17.8,-1.3 25.8,-9.3 8,-8 9.9,-13.2 9.3,-25.8 -0.5,-11.1 -3.2,-17.3 -10.3,-23.5 -7.4,-6.5 -10.8,-7.2 -34.7,-7.2l-20.8,-0 0,20.8z"
android:fillColor="#2196F3"
android:strokeColor="#00000000"/>
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">豆包</string>
</resources>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
来自 Termux 的 terminal-view 模块(Apache-2.0)。
单独放一个文件,避免和本 App 自己的 strings.xml 互相覆盖。
-->
<resources>
<string name="paste_text">粘贴</string>
<string name="copy_text">复制</string>
<string name="text_selection_more">更多…</string>
</resources>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 用系统 Material 主题,省掉 AppCompat 依赖 -->
<style name="AppTheme" parent="@android:style/Theme.Material.Light.NoActionBar">
<item name="android:windowBackground">@android:color/white</item>
<item name="android:statusBarColor">#FFFFFF</item>
<item name="android:windowLightStatusBar">true</item>
</style>
</resources>