Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
# CodePocket 更新日志

## [0.1.3] — 2026-11-26

项目级文本引用查找。0.0.27 解决了“从使用处跳到定义”,这一版补反向:从光标下的标识符列出它在整个 Python 项目里出现的位置。仍然是离线的 LSP-lite,不启动语言服务器,也不自动改名。

### 引用查找

- `ProjectSymbolIndex.references()` 返回 `Reference(path, name, line, column, preview, isDefinition)`;最多 200 条,扫 `.py` 文件上限 300 个、单文件 512KB,与定义索引共用预算。
- 按当前文件优先、路径、行号、列号排序;完整标识符边界匹配,`mycallback` / `callback_extra` 不会误命中 `callback`。
- 光标取词复用 `wordAt`;命令面板新增「查找引用」,非 Python 文件、光标不在标识符上、零结果都有明确提示。
- 新增 `ReferenceDialog`:文件、`Lx:y`、整行预览、定义标记;点击结果打开文件并跳到对应行。
- 结果明确标注“文本级”:注释、字符串、同名局部变量都会计入;不解析作用域、不做类型推断、不自动改名。

### 测试与构建

- 全量 JVM/Robolectric:**184 tests / 0 failures / 0 errors / 0 skipped**,45 个测试 XML。
- `lintRelease`:**0 errors / 27 warnings**。
- release APK 24,339,656 B;debug APK 43,457,810 B;versionCode 43 / versionName 0.1.3;签名证书与 0.1.2 相同;121 个 `.so` 全部 16KB LOAD 对齐。

### 边界

- 仍无 ARM64 真机验收;只有 x86_64 Android 15 模拟器的 UI 验收。
- 不做 rename/refactor,不把文本命中当语义引用;完整 LSP、Gradle/Java/Kotlin 构建和原生 wheel ABI 仍未做。

## [0.1.2] — 2026-11-25

引擎连接与慢设备启动修复。0.1.1 的真实运行暴露出:在极慢的 x86_64 软件模拟器上,`:engine` 进程冷启动超过 8 秒,主进程按旧超时判定失败,于是 Python 显示不可用;原生库、标准库和 C 扩展本身没有缺失。
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ Three runtimes are bundled inside the APK: a natively cross-compiled CPython 3.1
- **Sora Editor** code editor + 20-language TextMate syntax highlighting (3 runnable, 17 editable)
- **Static completion**: per-language keyword/builtin profiles + symbols from the current file (zero process overhead)
- **Python go-to-definition**: cursor symbol → project-wide `class` / `def` / module variable, with import-aware ranking (no LSP process)
- **Python find references (0.1.3)**: reverse text index for the symbol under the cursor; file, line:column, preview and definition tag, capped at 200 hits; explicitly not semantic, no rename
- **Find & replace** (count & jump) · **global search** (cross-file)
- **26-key symbol bar** · **pinch-to-zoom font size** · auto bracket closing · soft wrap · line number toggle
- **6 editor themes** (Darcula / Monokai / Tomorrow Night Blue / Solarized…)
Expand All @@ -106,6 +107,13 @@ Three runtimes are bundled inside the APK: a natively cross-compiled CPython 3.1
- **Python pdb debugger**: real stdlib `pdb`; breakpoints, next/step/continue, `p locals()`, stack, quit; quick-action bar in output panel
- **Offline by design**: no language server process, no model download, hard caps at 300 `.py` files / 512KB per file

### 项目级引用查找(0.1.3)
- **反向索引**:从光标标识符列出它在整个 Python 项目中的出现位置,和 0.0.27 的定义跳转互补;命令面板执行「查找引用」
- **可判读的结果**:显示文件、`Lx:y`、整行预览和「定义」标记,点击直接跳到对应行;只有 `.py`,最多 200 条
- **文本级,不冒充 LSP**:注释、字符串、同名局部变量都会计入;不解析作用域、不做类型推断、**不自动改名**
- **离线预算不变**:最多 300 个 `.py`、单文件 512KB,不启动语言服务器进程
- **测试**:5 个新增 JVM/Compose 用例;全量 184 tests 全绿

### 引擎连接修复(0.1.2)
- **慢设备绑定容错**:主进程等待 `:engine` Binder 的时间从 8 秒提高到 30 秒,冷启动慢的模拟器或低端机不再被误判成运行时损坏
- **准备预算**:首次准备标准库解压与 C 扩展抽取的总等待提高到 180 秒,期间仍显示进度;`:engine` 独立进程边界不变
Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ android {
applicationId = "com.devterminal"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
versionCode = 42
versionName = "0.1.2"
versionCode = 43
versionName = "0.1.3"
vectorDrawables { useSupportLibrary = true }
// 原生 CPython 引擎:同时打 arm64 与 x86_64(后者用于模拟器/ChromeOS)
ndk { abiFilters += listOf("arm64-v8a", "x86_64") }
Expand Down
104 changes: 99 additions & 5 deletions app/src/main/java/com/devterminal/language/ProjectSymbolIndex.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import com.devterminal.workspace.Workspace
* 项目级 Python 符号索引。
*
* 它不是 LSP:不启动进程、不做类型推断、不下载语言服务器。
* 目标只有两个,且都必须在手机上足够快:
* 目标只有三个,且都必须在手机上足够快:
* 1. 光标停在某个名字上时,找到它在项目里的定义;
* 2. 同名符号有多处时,列出文件、行号和签名让用户自己选。
* 2. 同名符号有多处时,列出文件、行号和签名让用户自己选;
* 3. 列出某个名字在项目内的文本级出现位置,不自动改名。
*
* 索引范围刻意收紧:只扫 .py、只读前 512KB、最多 300 个文件。
* 手机 IDE 里“全项目语义”不是刚需,卡顿才是。
Expand All @@ -23,6 +24,21 @@ class ProjectSymbolIndex(private val workspace: Workspace) {
val signature: String,
)

/**
* 一次文本级引用命中。
*
* 这不是语义引用:不区分局部变量、属性或字符串里的同名文本;
* 结果只用于“看它在项目里出现在哪”,不自动改名。
*/
data class Reference(
val path: String,
val name: String,
val line: Int,
val column: Int,
val preview: String,
val isDefinition: Boolean,
)

/**
* 查找定义。排序规则:
* 当前文件优先 → import 指向的模块优先 → 路径更短/行号更靠前。
Expand Down Expand Up @@ -64,6 +80,84 @@ class ProjectSymbolIndex(private val workspace: Workspace) {
return candidates
}

/**
* 查找标识符在项目内的文本级出现位置。
*
* 只扫 `.py`、前 512KB、最多 300 个文件;按当前文件优先、路径、行号排序。
* 不解析作用域,不区分注释/字符串里的同名文本;UI 必须明确标注这一点。
*/
fun references(
name: String,
fromPath: String,
limit: Int = 200,
): List<Reference> {
val query = name.trim()
if (query.isEmpty() || !query.matches(IDENTIFIER)) return emptyList()

val result = ArrayList<Reference>()
workspace.listFiles(maxDepth = 8, maxEntries = 600)
.asSequence()
.filter { it.endsWith(".py", ignoreCase = true) }
.take(MAX_FILES)
.forEach { path ->
if (result.size >= limit) return@forEach
val file = runCatching { workspace.resolve(path) }.getOrNull() ?: return@forEach
if (!file.isFile || file.length() > MAX_BYTES) return@forEach
val text = runCatching { file.readText() }.getOrNull() ?: return@forEach
collectReferences(path, text, query, limit, result)
}

return result.sortedWith(
compareBy(
{ if (it.path == fromPath) 0 else 1 },
{ it.path.length },
{ it.path },
{ it.line },
{ it.column },
)
).take(limit)
}

private fun collectReferences(
path: String,
text: String,
name: String,
limit: Int,
out: MutableList<Reference>,
) {
if (out.size >= limit) return
var lineNo = 1
for (line in text.lineSequence()) {
var from = 0
while (from <= line.length - name.length) {
val at = line.indexOf(name, from)
if (at < 0) break
val before = line.getOrNull(at - 1)
val after = line.getOrNull(at + name.length)
if (!isIdentifierPart(before) && !isIdentifierPart(after)) {
val trimmed = line.trimStart()
out += Reference(
path = path,
name = name,
line = lineNo,
column = at + 1,
preview = line.trim().take(MAX_SIGNATURE),
isDefinition = isDefinitionLine(trimmed, name),
)
if (out.size >= limit) return
}
from = at + name.length
}
lineNo++
}
}

private fun isDefinitionLine(trimmed: String, name: String): Boolean =
trimmed.startsWith("def $name(") ||
trimmed.startsWith("async def $name(") ||
trimmed.startsWith("class $name") ||
trimmed.startsWith("$name =")

/** 当前行、当前列(均为 1 基)下的标识符;不在标识符上则返回 null。 */
fun wordAt(text: String, line: Int, column: Int): String? {
val lines = text.split('\n')
Expand Down Expand Up @@ -129,15 +223,15 @@ class ProjectSymbolIndex(private val workspace: Workspace) {
}
}

private fun isIdentifierPart(ch: Char): Boolean =
ch.isLetterOrDigit() || ch == '_' || ch == '$'
private fun isIdentifierPart(ch: Char?): Boolean =
ch != null && (ch.isLetterOrDigit() || ch == '_' || ch == '$')

companion object {
private const val MAX_FILES = 300
private const val MAX_BYTES = 512L * 1024
private const val MAX_SIGNATURE = 160

private val IDENTIFIER = Regex("""[A-Za-z_]\w*""")
private val IDENTIFIER = Regex("""[\p{L}_][\p{L}\p{N}_]*""")
private val PY_CLASS = Regex("""^\s*class\s+([A-Za-z_]\w*)\s*(?:\([^)]*\))?\s*:""")
private val PY_DEF = Regex("""^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(""")
private val PY_ASSIGN = Regex("""^([A-Za-z_]\w*)\s*=(?!=)""")
Expand Down
16 changes: 16 additions & 0 deletions app/src/main/java/com/devterminal/ui/EditorScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,7 @@ fun EditorScreen(vm: EditorViewModel) {
"gsearch" -> overlay = Overlay.GlobalSearch
"symbols" -> { vm.loadSymbols(); overlay = Overlay.Symbols }
"definition" -> if (vm.findDefinition()) overlay = Overlay.Definitions
"references" -> if (vm.findReferences()) overlay = Overlay.References
"debug" -> vm.debugCurrent()
"models" -> { vm.refreshLocalModels(); overlay = Overlay.LocalModels }
"agentHistory" -> { vm.loadAgentSessions(); overlay = Overlay.AgentHistory }
Expand Down Expand Up @@ -956,6 +957,19 @@ fun EditorScreen(vm: EditorViewModel) {
)
}

if (overlay == Overlay.References) {
ReferenceDialog(
query = ui.referenceQuery,
matches = ui.referenceMatches,
loading = ui.referencesLoading,
onPick = { reference ->
vm.openReference(reference)
closeOverlay()
},
onDismiss = ::closeOverlay,
)
}

if (overlay == Overlay.GlobalSearch) {
GlobalSearchDialog(
query = gsearchQuery,
Expand Down Expand Up @@ -1416,6 +1430,8 @@ private fun buildCommands(
Icons.Filled.AccountTree) { onCommand("symbols") })
add(Command("definition", "跳转到定义", "光标下的 Python 符号 / 跨文件",
Icons.Filled.Search) { onCommand("definition") })
add(Command("references", "查找引用", "项目内文本级出现位置 / 不自动改名",
Icons.Filled.Search) { onCommand("references") })
if (ui.debugging) {
add(Command("debug-c", "调试:继续", "pdb c", Icons.Outlined.BugReport) { vm.sendDebugCommand("c") })
add(Command("debug-n", "调试:下一步", "pdb n", Icons.Outlined.BugReport) { vm.sendDebugCommand("n") })
Expand Down
70 changes: 70 additions & 0 deletions app/src/main/java/com/devterminal/ui/EditorViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ data class UiState(
val definitionQuery: String = "",
val definitionMatches: List<ProjectSymbolIndex.Definition> = emptyList(),
val definitionLoading: Boolean = false,
// ---------- 项目级引用(v0.1.3) ----------
val referenceQuery: String = "",
val referenceMatches: List<ProjectSymbolIndex.Reference> = emptyList(),
val referencesLoading: Boolean = false,
// ---------- Agent 会话恢复(v0.0.21) ----------
val agentRecovered: Boolean = false,
val agentSessions: List<AgentSessionMeta> = emptyList(),
Expand Down Expand Up @@ -2857,6 +2861,72 @@ class EditorViewModel(app: Application) : AndroidViewModel(app) {
openFile(file, targetLine = definition.line)
}

/**
* 光标下的 Python 标识符 → 项目内文本级引用。
*
* 与“跳转到定义”共用同一套索引上限,不启动 LSP。
* 结果包含当前文件、其它文件、注释与字符串里的同名文本;
* 这是刻意取舍:只帮用户看清“它还出现在哪”,不承诺语义正确,也不自动改名。
*/
fun findReferences(): Boolean {
val st = _ui.value
val file = st.currentFile ?: run {
_ui.update { it.copy(message = "先打开一个 Python 文件", messageSeq = it.messageSeq + 1) }
return false
}
if (file.extension.lowercase() != "py") {
_ui.update { it.copy(message = "当前仅支持 Python 引用查找", messageSeq = it.messageSeq + 1) }
return false
}
val root = currentProject ?: file.parentFile ?: return false
val name = ProjectSymbolIndex(LocalWorkspace(root)).wordAt(
st.editorText,
st.cursorLine,
st.cursorColumn,
) ?: run {
_ui.update { it.copy(message = "光标不在标识符上", messageSeq = it.messageSeq + 1) }
return false
}
val relative = runCatching {
file.relativeTo(root).path.replace(File.separatorChar, '/')
}.getOrElse { file.name }

_ui.update {
it.copy(
referenceQuery = name,
referenceMatches = emptyList(),
referencesLoading = true,
)
}
viewModelScope.launch {
val refs = withContext(Dispatchers.IO) {
runCatching {
ProjectSymbolIndex(LocalWorkspace(root)).references(name, relative)
}.getOrElse { emptyList() }
}
_ui.update {
it.copy(
referencesLoading = false,
referenceMatches = refs,
message = if (refs.isEmpty()) "没有找到“$name”的引用" else null,
messageSeq = if (refs.isEmpty()) it.messageSeq + 1 else it.messageSeq,
)
}
}
return true
}

/** 打开引用所在文件并定位到列(1 基行号;列仅用于提示,当前跳行即可)。 */
fun openReference(reference: ProjectSymbolIndex.Reference) {
val root = currentProject ?: _ui.value.currentFile?.parentFile ?: return
val file = File(root, reference.path)
if (!file.isFile) {
_ui.update { it.copy(message = "引用文件不存在:${reference.path}", messageSeq = it.messageSeq + 1) }
return
}
openFile(file, targetLine = reference.line)
}

// ---------- 导入 / 导出(SAF) ----------

/**
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/devterminal/ui/Overlay.kt
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ sealed interface Overlay {
/** 跨文件定义候选(Python,v0.0.27) */
data object Definitions : Overlay

/** 项目级文本引用(Python,v0.1.3) */
data object References : Overlay

/** 本地模型下载与管理 */
data object LocalModels : Overlay

Expand Down
Loading
Loading