commit a80c0f886a6b509e08112ddbe36a06a71a32f755 Author: alwaystrue Date: Wed Nov 4 16:37:05 2026 +0800 MyGoland 首次提交:Go 轻量 IDE - 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲) - 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表) - 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记 - Git:状态着色、选择性暂存提交、pull/push、历史并排对比 - 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复 - 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈 - 设计文档与验证记录见 docs/plans/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..171067a --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# 构建产物 +*.exe +*.exe~ + +# Delve 调试产物 +__debug_bin* + +# WorkBuddy 本地工作区数据(记忆/日志,不入库) +.workbuddy/ diff --git a/automation_e2e.go b/automation_e2e.go new file mode 100644 index 0000000..21a0971 --- /dev/null +++ b/automation_e2e.go @@ -0,0 +1,6 @@ +//go:build e2e + +package main + +// 仅用于本地像素级验证:带 e2e 标签构建时可被外部进程驱动截图。 +import _ "github.com/egoist/mygo/plugins/automation" diff --git a/build.cmd b/build.cmd new file mode 100644 index 0000000..74d9b75 --- /dev/null +++ b/build.cmd @@ -0,0 +1,10 @@ +@echo off +setlocal +cd /d "%~dp0" +go build -trimpath -ldflags "-s -w -H=windowsgui" -o MyGoland.exe . +if errorlevel 1 ( + echo 构建失败 + exit /b 1 +) +if exist "resources\ghostty-vt.dll" copy /y "resources\ghostty-vt.dll" "ghostty-vt.dll" >nul +echo 构建完成:MyGoland.exe(GUI 子系统,不会弹控制台) diff --git a/docs/MyGoland-vs-GoLand-差距分析.md b/docs/MyGoland-vs-GoLand-差距分析.md new file mode 100644 index 0000000..2927e08 --- /dev/null +++ b/docs/MyGoland-vs-GoLand-差距分析.md @@ -0,0 +1,210 @@ +# MyGoland 与 GoLand 差距分析 + +> 基准:GoLand 2025.x(JetBrains 官方功能说明) +> 现状:MyGoland v0.1(本次 13 项开发完成后的状态) +> 目的:找出「还差什么」,以及「哪些值得做、哪些不值得」 + +--- + +## 一、总体结论 + +| 维度 | GoLand | MyGoland 现状 | 差距 | +|---|---|---|---| +| 编辑体验 | 完善(折叠/内联提示/模板/多光标/查找替换) | 基础可用,缺折叠入口、内联提示、查找替换、模板 | **大** | +| 代码理解 | gopls + 自研索引 | gopls(诊断/补全/定义/引用/重命名/代码动作/大纲) | **小** | +| 导航 | 全局符号/文件/动作/书签/最近 | 文件、动作、引用、最近、大纲、面包屑;缺全局符号 | 中 | +| 重构 | 自有实现(改签名/提取/内联/移动/安全删除) | 靠 gopls 代码动作,UI 未归类 | 中 | +| 调试 | 全功能(goroutine/watch/attach/core dump) | 变量/调用栈/求值/条件断点 | 中 | +| 测试 | 结果树 + 覆盖率 + 单测跳转 | 只有 `go test` 文本输出 | **大** | +| 版本控制 | diff/历史/blame/分支/冲突解决 | 状态着色 + 提交 | **大** | +| 工程工具 | DB/SQL、Docker/K8s、Proto、远程开发 | 无 | 极大(不建议追) | +| 生态 | 上千插件、IdeaVim、AI | 无 | 极大(不需要) | +| 启动与体积 | 10–20 秒 / 800 MB+ | **约 1 秒 / 15 MB** | 我们更好 | + +一句话:**代码智能这一层已经追平(都靠 gopls),差的是"编辑器手感"和"工程附件"。** + +--- + +## 二、逐项对照 + +### 2.1 编辑体验(差距最明显,也最容易补) + +| 能力 | GoLand | MyGoland | 说明 | +|---|---|---|---| +| 代码折叠 | ✅ | ❌ | 框架已内置 `Fold/FoldImports/ToggleFold/FoldAll`,**只是没接命令** | +| 内联提示(参数名/类型) | ✅ | ❌ | 框架有 `SetInlays`,gopls 有 `textDocument/inlayHint`,客户端缺实现 | +| 文件内查找替换 | ✅ | ❌ | 编辑器有 `Find/FindMatches/RenderFindBar`,缺一个查找条 UI | +| 实时模板(for/err/iferr) | ✅ | ❌ | 需自建片段系统 | +| 多光标 / 列选择 | ✅ | ❓ | 编辑器有 `Selections()` 多选 API,未接 UI | +| 注释切换 | ✅ | ✅ | `Ctrl+/` | +| 格式化 | ✅ | ✅ | 保存时 gopls 格式化 | +| 自动 import | ✅ | ✅ | gopls 代码动作(Alt+Enter) | +| 括号匹配/自动缩进 | ✅ | ✅ | 编辑器内置 | +| 书签 | ✅ | ❌ | 低优先 | +| 本地历史(Local History) | ✅ | ❌ | 我们只有 git;GoLand 有"改动即存档" | +| 拼写检查 | ✅ | ❌ | 不需要 | + +### 2.2 导航 + +| 能力 | GoLand | MyGoland | +|---|---|---| +| 跳转定义 | ✅ F12 | ✅ F12 / Ctrl+Click | +| 查找引用 | ✅ Shift+F2 | ✅ Shift+F2 | +| 文件名搜索 | ✅ | ✅ Ctrl+P | +| **全局符号搜索** | ✅ Ctrl+Alt+Shift+N | ❌(只有当前文件大纲) | +| 动作搜索 | ✅ | ✅ Ctrl+Shift+P(含代码动作) | +| 最近文件 | ✅ Ctrl+E | ⚠️ 有「最近项目」,没有「最近文件」快速切换 | +| 结构视图 | ✅ | ✅ 大纲面板 | +| 面包屑 | ✅ | ✅ | +| 跳转到行 | ✅ Ctrl+G | ❌ | +| 问题间跳转 | ✅ F2 | ⚠️ 问题面板点击,无「下一个问题」键 | + +### 2.3 重构 + +GoLand 有一整套自有实现;我们靠 gopls 的 code action,**能力上接近,入口上落后**。 + +| 重构 | GoLand 键 | MyGoland | +|---|---|---| +| 重命名符号 | Shift+F6 | ✅ F2 | +| 提取函数/变量/常量 | Ctrl+Alt+M/V/C | ⚠️ gopls 已提供(Alt+Enter 里能搜到「Extract function」),未做专门入口 | +| 内联 | Ctrl+Alt+N | ⚠️ 同上(refactor.inline) | +| 更改签名 | Ctrl+F6 | ❌ gopls 不支持 | +| 移动/安全删除 | F6/Alt+Delete | ⚠️ 文件级能移动/删除;符号级无 | +| 重命名结构体字段同步 JSON tag | ✅ | ❌ gopls 的行为取决于版本 | + +**判断**:真正缺的只有「更改签名」。其余是**入口问题**——把 gopls 返回的 refactor.* 动作按类别单独列出来即可。 + +### 2.4 调试 + +| 能力 | GoLand | MyGoland | +|---|---|---| +| 断点(条件/禁用/列表) | ✅ | ✅ | +| 变量树(可展开结构体) | ✅ | ✅(`children`/`expanded` 按引用号展开) | +| 调用栈跳转 | ✅ | ✅ | +| 表达式求值 | ✅ | ✅ | +| Goroutine 视图 | ✅ | ❌ | +| Watch 表达式 | ✅ | ❌ | +| Attach 到进程 | ✅ | ❌(只支持 launch) | +| 断点组/静音全部 | ✅ | ❌(有单条禁用) | +| 内联变量值(调试时行尾显示) | ✅ | ❌ | + +### 2.5 测试(差距仅次于 VCS) + +| 能力 | GoLand | MyGoland | +|---|---|---| +| 运行测试 | ✅ 图形化 | ⚠️ `go test ./...` 文本输出到面板 | +| 单测/单函数运行 | ✅ 行号旁图标 | ❌ | +| 结果树(包→测试→子测试) | ✅ | ❌ | +| 覆盖率(行级红绿) | ✅ | ❌ | +| Race 检测开关 | ✅ | ❌(得手敲参数) | +| Benchmark | ✅ | ❌ | + +### 2.6 版本控制 + +| 能力 | GoLand | MyGoland | +|---|---|---| +| 文件状态着色 | ✅ | ✅ | +| 提交(含消息) | ✅ 完整提交面板 | ⚠️ 输入框 + `add -A && commit` | +| **Diff 查看** | ✅ 并排 + 行内 | ❌(框架自带 `editor.DiffView`,成本比预想低) | +| 提交历史 / 日志 | ✅ | ❌ | +| 行级 blame | ✅ | ❌ | +| 分支管理(切换/新建/合并) | ✅ | ❌ | +| 冲突解决 | ✅ 三方合并 | ❌ | +| 行级/文件级暂存 | ✅ | ❌(我们是 `add -A` 全量) | +| Stash / Shelve | ✅ | ❌ | + +### 2.7 工程与生态(这里不建议追) + +| 能力 | GoLand | 判断 | +|---|---|---| +| 数据库 / SQL 控制台 | ✅ 完整 DataGrip 内核 | **不做**:等于重写一个产品 | +| Docker / K8s | ✅ | **不做**:终端能跑 `docker` 就够 | +| Proto / gRPC | ✅ | **暂不做**:需要 protoc 集成,收益窄 | +| go.mod 依赖图 | ✅ | 可做轻量版(列出依赖 + 升级提示),优先级低 | +| 远程开发(SSH/WSL/容器) | ✅ | **不做**:架构级改造(前后端分离) | +| 插件系统 | ✅ 上千插件 | **不做**:自用产品没有生态诉求 | +| AI 补全 / AI 助手 | ✅ | **另开项目**:属于模型能力,不属于 IDE | + +--- + +## 三、值得做的 8 项(按 ROI 排序) + +| # | 项目 | 收益 | 成本 | 依赖的现成能力 | +|---|---|---|---|---| +| 1 | **代码折叠** | 高(长文件必备) | **0.5 天** | 框架 `Fold/FoldAll/ToggleFold` 现成 | +| 2 | **文件内查找替换** | 高(每天用几十次) | **1 天** | `Find/FindMatches/RenderFindBar` 现成 | +| 3 | **内联提示(参数名/类型)** | 高(读代码快很多) | **1–2 天** | `SetInlays` + gopls `inlayHint` | +| 4 | **全局符号搜索** | 中高 | **1 天** | gopls `workspace/symbol` + 复用命令面板 | +| 5 | **测试结果树 + 单测运行** | 高 | **3 天** | `go test -json` 解析 + 面板树 | +| 6 | **覆盖率(行级红绿)** | 中高 | **2 天**(在 5 之上) | `-coverprofile` + `LineBackgrounds` | +| 7 | **Git diff 查看** | 高 | **1.5 天** | 框架 `editor.DiffView` 现成 + `git diff` | +| 8 | **Git 历史 / 行级 blame** | 中 | **2 天** | `git log --follow` / `git blame -L` | + +前 4 项加起来约 **3.5 天**,能把「编辑手感」拉到接近 GoLand 的水平——这是投入产出比最高的部分。 + +--- + +## 四、明确不建议做(附理由) + +| 项目 | 理由 | +|---|---| +| 数据库 / SQL 工具 | 工作量相当于再造 DataGrip,而你的场景里 Navicat/SSMS 已经够用 | +| Kubernetes / Docker 深度集成 | 我们用终端跑 `kubectl`/`docker` 没有任何损失,做 UI 反而是负债 | +| 远程开发 | 需要前后端分离架构(客户端 + 服务端 IDE),是产品级重构,不是功能 | +| 插件系统 | 没有第三方生态就只是给自己加抽象层 | +| 完整的重构集(改签名/安全删除) | gopls 不支持的部分要么做不到位,要么成本极高;能用 gopls 的已经能用 | +| AI 补全 | 属于模型与推理成本问题,与本项目解耦更合适 | +| 拼写检查 / 代码风格强约束 | Go 生态已有 `gofmt`/`golangci-lint`,IDE 侧重复造轮子价值低 | + +--- + +## 五、MyGoland 反而更强的地方(客观记录) + +| 维度 | GoLand | MyGoland | +|---|---|---| +| 冷启动 | 10–20 秒(含索引) | **约 1 秒** | +| 安装体积 | 800 MB+(含 JVM) | **15 MB 单文件** | +| 索引等待 | 首次打开要建索引 | 无索引,打开即用 | +| 可改造性 | 只能写插件 | 源码在手,想改就改 | +| 部署 | 需要安装 + 授权 | 拷一个 exe 就能跑 | +| 老机器(Win7 工控机) | 基本跑不动 | 可跑(本机验证过 Win10,Win7 待验证) | + +最后一条对你有现实意义:如果将来要把「现场看日志/改配置」的工具发到搅拌站工控机上,GoLand 这条路走不通。 + +--- + +## 六、建议路线 + +### 阶段一:编辑手感(约 3.5 天,建议立刻做) + +1. 代码折叠(0.5 天) +2. 文件内查找替换(1 天) +3. 内联提示(1–2 天) +4. 全局符号搜索(1 天) + +做完这四项,日常写代码的「别扭感」基本消失。 + +### 阶段二:工程闭环(约 6.5 天) + +5. 测试结果树 + 单测运行(3 天) +6. 覆盖率(2 天) +7. Git diff 查看(1.5 天) + +做完之后,「改代码 → 跑测试 → 看差异 → 提交」这条链路不必再切到终端。 + +### 阶段三:可选增强(按需) + +- Git 历史 / blame(2 天) +- 代码模板(2 天) +- 书签、跳转到行、下一个问题(1 天) +- 调试增强:watch 表达式、goroutine 视图(3 天) + +--- + +## 七、如果只能做三件事 + +1. **查找替换**——没有它,每次搜索都要靠全局搜索,效率损失最直接 +2. **测试结果树**——现在跑测试只能看一坨文本,失败定位全靠肉眼 +3. **Git diff**——框架已经给了 DiffView,不接上是浪费 + +这三项大约 5 天,能把「日常够用」变成「日常顺手」。 diff --git a/docs/about-window.png b/docs/about-window.png new file mode 100644 index 0000000..9d3fc0b Binary files /dev/null and b/docs/about-window.png differ diff --git a/docs/editor-no-scrollbar.png b/docs/editor-no-scrollbar.png new file mode 100644 index 0000000..b3ed137 Binary files /dev/null and b/docs/editor-no-scrollbar.png differ diff --git a/docs/file-tree-active-row.png b/docs/file-tree-active-row.png new file mode 100644 index 0000000..c4e7a5c Binary files /dev/null and b/docs/file-tree-active-row.png differ diff --git a/docs/file-tree-icons.png b/docs/file-tree-icons.png new file mode 100644 index 0000000..b321737 Binary files /dev/null and b/docs/file-tree-icons.png differ diff --git a/docs/logo/Flat_vector_illustration_of_th_2026-10-29T05-49-57.png b/docs/logo/Flat_vector_illustration_of_th_2026-10-29T05-49-57.png new file mode 100644 index 0000000..1892f51 Binary files /dev/null and b/docs/logo/Flat_vector_illustration_of_th_2026-10-29T05-49-57.png differ diff --git a/docs/logo/Flat_vector_logo_mark__front_v_2026-10-29T02-14-01.png b/docs/logo/Flat_vector_logo_mark__front_v_2026-10-29T02-14-01.png new file mode 100644 index 0000000..07e1897 Binary files /dev/null and b/docs/logo/Flat_vector_logo_mark__front_v_2026-10-29T02-14-01.png differ diff --git a/docs/logo/Flat_vector_mascot_logo_on_pla_2026-10-29T02-16-54.png b/docs/logo/Flat_vector_mascot_logo_on_pla_2026-10-29T02-16-54.png new file mode 100644 index 0000000..e6ccaff Binary files /dev/null and b/docs/logo/Flat_vector_mascot_logo_on_pla_2026-10-29T02-16-54.png differ diff --git a/docs/logo/Keep_the_Go_gopher_and_the_exi_2026-10-29T02-27-38.png b/docs/logo/Keep_the_Go_gopher_and_the_exi_2026-10-29T02-27-38.png new file mode 100644 index 0000000..2186542 Binary files /dev/null and b/docs/logo/Keep_the_Go_gopher_and_the_exi_2026-10-29T02-27-38.png differ diff --git a/docs/logo/Keep_the_Go_gopher_and_the_exi_2026-10-29T02-27-54.png b/docs/logo/Keep_the_Go_gopher_and_the_exi_2026-10-29T02-27-54.png new file mode 100644 index 0000000..0ae531d Binary files /dev/null and b/docs/logo/Keep_the_Go_gopher_and_the_exi_2026-10-29T02-27-54.png differ diff --git a/docs/logo/Keep_the_Go_gopher_character_a_2026-10-29T02-22-43.png b/docs/logo/Keep_the_Go_gopher_character_a_2026-10-29T02-22-43.png new file mode 100644 index 0000000..a32a2c5 Binary files /dev/null and b/docs/logo/Keep_the_Go_gopher_character_a_2026-10-29T02-22-43.png differ diff --git a/docs/logo/Keep_the_character_design__col_2026-10-29T02-17-42.png b/docs/logo/Keep_the_character_design__col_2026-10-29T02-17-42.png new file mode 100644 index 0000000..c479e46 Binary files /dev/null and b/docs/logo/Keep_the_character_design__col_2026-10-29T02-17-42.png differ diff --git a/docs/logo/Keep_the_exact_same_flat_vecto_2026-10-29T02-14-18.png b/docs/logo/Keep_the_exact_same_flat_vecto_2026-10-29T02-14-18.png new file mode 100644 index 0000000..58cce48 Binary files /dev/null and b/docs/logo/Keep_the_exact_same_flat_vecto_2026-10-29T02-14-18.png differ diff --git a/docs/logo/Keep_the_gopher__the_large_det_2026-10-29T02-28-36.png b/docs/logo/Keep_the_gopher__the_large_det_2026-10-29T02-28-36.png new file mode 100644 index 0000000..19f5744 Binary files /dev/null and b/docs/logo/Keep_the_gopher__the_large_det_2026-10-29T02-28-36.png differ diff --git a/docs/logo/Keep_the_gopher__the_large_gea_2026-10-29T02-29-34.png b/docs/logo/Keep_the_gopher__the_large_gea_2026-10-29T02-29-34.png new file mode 100644 index 0000000..434edca Binary files /dev/null and b/docs/logo/Keep_the_gopher__the_large_gea_2026-10-29T02-29-34.png differ diff --git a/docs/logo/Keep_this_exact_Go_Gopher_char_2026-10-29T02-17-09.png b/docs/logo/Keep_this_exact_Go_Gopher_char_2026-10-29T02-17-09.png new file mode 100644 index 0000000..1baa6b3 Binary files /dev/null and b/docs/logo/Keep_this_exact_Go_Gopher_char_2026-10-29T02-17-09.png differ diff --git a/docs/logo/Keep_this_exact_flat_vector_st_2026-10-29T02-15-03.png b/docs/logo/Keep_this_exact_flat_vector_st_2026-10-29T02-15-03.png new file mode 100644 index 0000000..9c4c0a0 Binary files /dev/null and b/docs/logo/Keep_this_exact_flat_vector_st_2026-10-29T02-15-03.png differ diff --git a/docs/logo/Minimalist_single_color_line_a_2026-10-29T02-13-23.png b/docs/logo/Minimalist_single_color_line_a_2026-10-29T02-13-23.png new file mode 100644 index 0000000..8aa7881 Binary files /dev/null and b/docs/logo/Minimalist_single_color_line_a_2026-10-29T02-13-23.png differ diff --git a/docs/logo/Modern_3D_logo_icon_render__A__2026-10-29T02-13-12.png b/docs/logo/Modern_3D_logo_icon_render__A__2026-10-29T02-13-12.png new file mode 100644 index 0000000..f003d7a Binary files /dev/null and b/docs/logo/Modern_3D_logo_icon_render__A__2026-10-29T02-13-12.png differ diff --git a/docs/logo/Professional_logo_mark__flat_v_2026-10-29T02-13-01.png b/docs/logo/Professional_logo_mark__flat_v_2026-10-29T02-13-01.png new file mode 100644 index 0000000..71d0682 Binary files /dev/null and b/docs/logo/Professional_logo_mark__flat_v_2026-10-29T02-13-01.png differ diff --git a/docs/logo/README.md b/docs/logo/README.md new file mode 100644 index 0000000..2ffaa36 --- /dev/null +++ b/docs/logo/README.md @@ -0,0 +1,121 @@ +# MyGoland Logo 素材清单 + +Gopher 抱齿轮标识,基于 Go 官方 Gopher 造型(Renée French 设计,CC BY 3.0)。 +主色:身体 `#62CBDB`、齿圈 `#324F60`、辐板 `#4A6C7E`、轮毂 `#1B3A49`、米色 `#F1C99B`。 + +## 图标 / 应用 + +| 文件 | 用途 | +|---|---| +| `mygoland.ico` | Windows 应用图标,含 16/24/32/48/64/128/256 七种尺寸 | +| `favicon.ico` | 网页 favicon,含 16/32/48 | +| `appicon.png` | Wails 构建图标(512×512,透明底) | +| `appicon-1024.png` | Wails / macOS 用大图(1024×1024,透明底) | +| `icon-16.png` `icon-32.png` `icon-48.png` `icon-96.png` | 透明底小图标,托盘、任务栏、列表页 | +| `icon-180-white.png` | apple-touch-icon(白底,iOS 不接受透明) | +| `icon-192-white.png` `icon-512-white.png` | PWA / Android 图标(白底) | + +## 通用位图 + +| 文件 | 用途 | +|---|---| +| `mygoland-logo-1024.png` | 白底主图,文档、README、PPT | +| `mygoland-logo-{512,256,128,64,32}.png` | 白底多尺寸 | +| `mygoland-logo-transparent-1024.png` | 透明底主图,叠任意背景 | +| `mygoland-logo-transparent-{512,256,128,64,32}.png` | 透明底多尺寸 | + +## 深色主题 + +| 文件 | 用途 | +|---|---| +| `mygoland-logo-dark-512.png` | 深色圆角底版本(底色 `#12161A`),深色 README / 深色 UI | +| `mygoland-logo-dark-256.png` `mygoland-logo-dark-128.png` | 同上小尺寸 | + +## 单色 / 印刷 + +| 文件 | 用途 | +|---|---| +| `mygoland-logo-mono-black.png` | 黑色线稿,透明底。单色印刷、热敏 / 激光雕刻 | +| `mygoland-logo-mono-black-white.png` | 黑色线稿,白底。直接贴进只能显示白底的文档 | +| `mygoland-logo-mono-white.png` | 白色线稿,透明底。深色背景、深色界面反白用 | +| `mygoland-logo-mono-black-{512,256}.png` | 线稿多尺寸 | + +单色线稿只保留黑色描边,填充全部透明,笔尖/刀刃路径清晰,可直接用于印章、雕刻、绣标。 + +## 归档 + +`v1-simple-gear/` 是齿轮简化版(纯深色平涂,无减重孔),在小尺寸下对比度更好,保留备用。 + +## 使用约定 + +- 最小使用尺寸:彩色版 64px,单色线稿版 48px。低于此尺寸请用 `icon-16.png` / `icon-32.png`。 +- 图标四周已留 8% 安全边距,不要再自行裁切贴边。 +- 深色背景上优先用 `mygoland-logo-transparent-*`,不要用白底版。 +- 标识不要拉伸变形,不要给图形加描边、阴影或外发光。 + +## 关于矢量源文件 + +当前所有素材均为 1024×1024 位图导出。曾尝试用自动描摹生成 SVG,但位图边缘的抗锯齿噪点会被放大成毛刺(黑色描边断裂、齿轮糊成黑块),达不到生产质量,已放弃该路线。 + +若后续需要真 SVG,建议按现有造型做一次人工矢量化重绘:齿轮用正多边形阵列构造(保证齿距严格相等),人物用椭圆与圆角矩形拼装。这个工作用矢量工具约 1–2 小时,而且能顺带产出真正的单色剪影和 16px 优化版。 + +--- + +# 项目内接入 + +标识已经接进 MyGoland 应用代码,不再只是素材文件。 + +## 资源落位 + +| 位置 | 内容 | 用途 | +|---|---|---| +| `internal/app/assets/logo.png` | 透明底 256×256 | 欢迎页、关于页里的标识 | +| `internal/app/assets/icon.png` | 浅色圆角卡片 256×256 | 窗口标题栏、任务栏图标 | +| `resources/icon.png` | 浅色圆角卡片 1024×1024 | mygo 打包用的应用图标 | +| `docs/logo/final/mygoland-app.ico` | 卡片版 16–256 七尺寸 | 生成 exe 资源用 | +| `rsrc_windows_amd64.syso` | 由上面的 ico 生成 | 链接进 exe,决定文件图标 | + +## 代码接入点 + +| 文件 | 改动 | +|---|---| +| `internal/app/logo.go` | `go:embed` 内嵌两张图,启动时解码一次;提供 `logoCard()` 画浅色底板上的标识 | +| `internal/app/app.go` | `Start()` 里 `a.win.SetIcon(iconPNG)`;`App` 结构体新增 `aboutWin` | +| `internal/app/view.go` | `welcomeView()` 顶部加 104px 标识卡片,副标题带版本号 | +| `internal/app/about.go` | 新增「关于 MyGoland」窗口(400×380 固定尺寸) | +| `internal/app/menu.go` | 新增「帮助 → 关于 MyGoland」菜单项 | + +## 为什么准备两套图片 + +界面里不能用透明底图片直接贴:主题底色是 `#12161A`,齿轮的 `#324F60` 和黑色描边会一起糊进背景,轮廓读不出来。所以: + +- **界面**用透明图,由 `logoCard()` 自己画一块 `#E9EFF5` 的圆角底板。 +- **系统图标**(任务栏 / exe 文件)不能自己画底板,所以单独出一张自带浅色圆角底的 `icon.png`。 + +## 构建 + +```bash +go build -o MyGoland.exe . +``` + +图标已经通过 `rsrc_windows_amd64.syso` 链接进 exe,`go build` 会自动带上,不需要额外参数。 + +换了 ico 之后要重新生成 syso: + +```bash +go install github.com/akavel/rsrc@latest +rsrc -ico docs/logo/final/mygoland-app.ico -o rsrc_windows_amd64.syso +go build -o MyGoland.exe . +``` + +验证 exe 是否带图标(应能看到 `RT_ICON` 和 `RT_GROUP_ICON`): + +```bash +python -c "import pefile; p=pefile.PE('MyGoland.exe'); print([e.id for e in p.DIRECTORY_ENTRY_RESOURCE.entries])" +``` + +`mygo.json` 已写好打包元数据(name / identifier / version / icon),装了 mygo CLI 之后可以用 `mygo build` 出安装包。 + +## 许可 + +Gopher 造型来自 Renée French,CC BY 3.0。个人项目使用没问题;若对外分发,建议在「关于」里加一行署名,或改造造型规避商标风险。 diff --git a/docs/logo/Solid_monochrome_glyph_logo__s_2026-10-29T02-14-29.png b/docs/logo/Solid_monochrome_glyph_logo__s_2026-10-29T02-14-29.png new file mode 100644 index 0000000..bb4ece0 Binary files /dev/null and b/docs/logo/Solid_monochrome_glyph_logo__s_2026-10-29T02-14-29.png differ diff --git a/docs/logo/final/appicon-1024.png b/docs/logo/final/appicon-1024.png new file mode 100644 index 0000000..a41cc32 Binary files /dev/null and b/docs/logo/final/appicon-1024.png differ diff --git a/docs/logo/final/appicon.png b/docs/logo/final/appicon.png new file mode 100644 index 0000000..ef84f86 Binary files /dev/null and b/docs/logo/final/appicon.png differ diff --git a/docs/logo/final/favicon-32px-x6-preview.png b/docs/logo/final/favicon-32px-x6-preview.png new file mode 100644 index 0000000..a1e5077 Binary files /dev/null and b/docs/logo/final/favicon-32px-x6-preview.png differ diff --git a/docs/logo/final/favicon.ico b/docs/logo/final/favicon.ico new file mode 100644 index 0000000..f05bfd2 Binary files /dev/null and b/docs/logo/final/favicon.ico differ diff --git a/docs/logo/final/icon-16.png b/docs/logo/final/icon-16.png new file mode 100644 index 0000000..b711c25 Binary files /dev/null and b/docs/logo/final/icon-16.png differ diff --git a/docs/logo/final/icon-180-white.png b/docs/logo/final/icon-180-white.png new file mode 100644 index 0000000..b1478ca Binary files /dev/null and b/docs/logo/final/icon-180-white.png differ diff --git a/docs/logo/final/icon-192-white.png b/docs/logo/final/icon-192-white.png new file mode 100644 index 0000000..0485f81 Binary files /dev/null and b/docs/logo/final/icon-192-white.png differ diff --git a/docs/logo/final/icon-32.png b/docs/logo/final/icon-32.png new file mode 100644 index 0000000..8fd2f9d Binary files /dev/null and b/docs/logo/final/icon-32.png differ diff --git a/docs/logo/final/icon-48.png b/docs/logo/final/icon-48.png new file mode 100644 index 0000000..bcefc29 Binary files /dev/null and b/docs/logo/final/icon-48.png differ diff --git a/docs/logo/final/icon-512-white.png b/docs/logo/final/icon-512-white.png new file mode 100644 index 0000000..fa918f1 Binary files /dev/null and b/docs/logo/final/icon-512-white.png differ diff --git a/docs/logo/final/icon-96.png b/docs/logo/final/icon-96.png new file mode 100644 index 0000000..7320003 Binary files /dev/null and b/docs/logo/final/icon-96.png differ diff --git a/docs/logo/final/mygoland-app-icon-512.png b/docs/logo/final/mygoland-app-icon-512.png new file mode 100644 index 0000000..5a7be7e Binary files /dev/null and b/docs/logo/final/mygoland-app-icon-512.png differ diff --git a/docs/logo/final/mygoland-app.ico b/docs/logo/final/mygoland-app.ico new file mode 100644 index 0000000..71497a3 Binary files /dev/null and b/docs/logo/final/mygoland-app.ico differ diff --git a/docs/logo/final/mygoland-logo-1024.png b/docs/logo/final/mygoland-logo-1024.png new file mode 100644 index 0000000..6260228 Binary files /dev/null and b/docs/logo/final/mygoland-logo-1024.png differ diff --git a/docs/logo/final/mygoland-logo-128.png b/docs/logo/final/mygoland-logo-128.png new file mode 100644 index 0000000..c3933dd Binary files /dev/null and b/docs/logo/final/mygoland-logo-128.png differ diff --git a/docs/logo/final/mygoland-logo-256.png b/docs/logo/final/mygoland-logo-256.png new file mode 100644 index 0000000..9ef226d Binary files /dev/null and b/docs/logo/final/mygoland-logo-256.png differ diff --git a/docs/logo/final/mygoland-logo-32.png b/docs/logo/final/mygoland-logo-32.png new file mode 100644 index 0000000..98f30ea Binary files /dev/null and b/docs/logo/final/mygoland-logo-32.png differ diff --git a/docs/logo/final/mygoland-logo-512.png b/docs/logo/final/mygoland-logo-512.png new file mode 100644 index 0000000..4020226 Binary files /dev/null and b/docs/logo/final/mygoland-logo-512.png differ diff --git a/docs/logo/final/mygoland-logo-64.png b/docs/logo/final/mygoland-logo-64.png new file mode 100644 index 0000000..9ad2a50 Binary files /dev/null and b/docs/logo/final/mygoland-logo-64.png differ diff --git a/docs/logo/final/mygoland-logo-dark-128.png b/docs/logo/final/mygoland-logo-dark-128.png new file mode 100644 index 0000000..09a15d0 Binary files /dev/null and b/docs/logo/final/mygoland-logo-dark-128.png differ diff --git a/docs/logo/final/mygoland-logo-dark-256.png b/docs/logo/final/mygoland-logo-dark-256.png new file mode 100644 index 0000000..467de5f Binary files /dev/null and b/docs/logo/final/mygoland-logo-dark-256.png differ diff --git a/docs/logo/final/mygoland-logo-dark-512.png b/docs/logo/final/mygoland-logo-dark-512.png new file mode 100644 index 0000000..31acde7 Binary files /dev/null and b/docs/logo/final/mygoland-logo-dark-512.png differ diff --git a/docs/logo/final/mygoland-logo-mono-black-256.png b/docs/logo/final/mygoland-logo-mono-black-256.png new file mode 100644 index 0000000..30a220e Binary files /dev/null and b/docs/logo/final/mygoland-logo-mono-black-256.png differ diff --git a/docs/logo/final/mygoland-logo-mono-black-512.png b/docs/logo/final/mygoland-logo-mono-black-512.png new file mode 100644 index 0000000..28fdd7d Binary files /dev/null and b/docs/logo/final/mygoland-logo-mono-black-512.png differ diff --git a/docs/logo/final/mygoland-logo-mono-black-white-256.png b/docs/logo/final/mygoland-logo-mono-black-white-256.png new file mode 100644 index 0000000..bcf3449 Binary files /dev/null and b/docs/logo/final/mygoland-logo-mono-black-white-256.png differ diff --git a/docs/logo/final/mygoland-logo-mono-black-white-512.png b/docs/logo/final/mygoland-logo-mono-black-white-512.png new file mode 100644 index 0000000..a59a4f1 Binary files /dev/null and b/docs/logo/final/mygoland-logo-mono-black-white-512.png differ diff --git a/docs/logo/final/mygoland-logo-mono-black-white.png b/docs/logo/final/mygoland-logo-mono-black-white.png new file mode 100644 index 0000000..3995551 Binary files /dev/null and b/docs/logo/final/mygoland-logo-mono-black-white.png differ diff --git a/docs/logo/final/mygoland-logo-mono-black.png b/docs/logo/final/mygoland-logo-mono-black.png new file mode 100644 index 0000000..22ab5ec Binary files /dev/null and b/docs/logo/final/mygoland-logo-mono-black.png differ diff --git a/docs/logo/final/mygoland-logo-mono-white.png b/docs/logo/final/mygoland-logo-mono-white.png new file mode 100644 index 0000000..05018b8 Binary files /dev/null and b/docs/logo/final/mygoland-logo-mono-white.png differ diff --git a/docs/logo/final/mygoland-logo-transparent-1024.png b/docs/logo/final/mygoland-logo-transparent-1024.png new file mode 100644 index 0000000..a41cc32 Binary files /dev/null and b/docs/logo/final/mygoland-logo-transparent-1024.png differ diff --git a/docs/logo/final/mygoland-logo-transparent-128.png b/docs/logo/final/mygoland-logo-transparent-128.png new file mode 100644 index 0000000..a54e842 Binary files /dev/null and b/docs/logo/final/mygoland-logo-transparent-128.png differ diff --git a/docs/logo/final/mygoland-logo-transparent-256.png b/docs/logo/final/mygoland-logo-transparent-256.png new file mode 100644 index 0000000..652a9a0 Binary files /dev/null and b/docs/logo/final/mygoland-logo-transparent-256.png differ diff --git a/docs/logo/final/mygoland-logo-transparent-32.png b/docs/logo/final/mygoland-logo-transparent-32.png new file mode 100644 index 0000000..b6b9354 Binary files /dev/null and b/docs/logo/final/mygoland-logo-transparent-32.png differ diff --git a/docs/logo/final/mygoland-logo-transparent-512.png b/docs/logo/final/mygoland-logo-transparent-512.png new file mode 100644 index 0000000..ef84f86 Binary files /dev/null and b/docs/logo/final/mygoland-logo-transparent-512.png differ diff --git a/docs/logo/final/mygoland-logo-transparent-64.png b/docs/logo/final/mygoland-logo-transparent-64.png new file mode 100644 index 0000000..0324b69 Binary files /dev/null and b/docs/logo/final/mygoland-logo-transparent-64.png differ diff --git a/docs/logo/final/mygoland.ico b/docs/logo/final/mygoland.ico new file mode 100644 index 0000000..0600b99 Binary files /dev/null and b/docs/logo/final/mygoland.ico differ diff --git a/docs/logo/final/v1-simple-gear/favicon-32px-x6-preview.png b/docs/logo/final/v1-simple-gear/favicon-32px-x6-preview.png new file mode 100644 index 0000000..306244a Binary files /dev/null and b/docs/logo/final/v1-simple-gear/favicon-32px-x6-preview.png differ diff --git a/docs/logo/final/v1-simple-gear/mark-legacy-preview-32px-x6.png b/docs/logo/final/v1-simple-gear/mark-legacy-preview-32px-x6.png new file mode 100644 index 0000000..580b530 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mark-legacy-preview-32px-x6.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-1024.png b/docs/logo/final/v1-simple-gear/mygoland-logo-1024.png new file mode 100644 index 0000000..3150aa1 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-1024.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-128.png b/docs/logo/final/v1-simple-gear/mygoland-logo-128.png new file mode 100644 index 0000000..1300521 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-128.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-256.png b/docs/logo/final/v1-simple-gear/mygoland-logo-256.png new file mode 100644 index 0000000..13e4598 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-256.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-32.png b/docs/logo/final/v1-simple-gear/mygoland-logo-32.png new file mode 100644 index 0000000..91366b0 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-32.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-512.png b/docs/logo/final/v1-simple-gear/mygoland-logo-512.png new file mode 100644 index 0000000..f0762d1 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-512.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-64.png b/docs/logo/final/v1-simple-gear/mygoland-logo-64.png new file mode 100644 index 0000000..0d8400e Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-64.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-1024.png b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-1024.png new file mode 100644 index 0000000..79a17d7 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-1024.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-128.png b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-128.png new file mode 100644 index 0000000..d9d1d11 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-128.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-256.png b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-256.png new file mode 100644 index 0000000..ab68c14 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-256.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-32.png b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-32.png new file mode 100644 index 0000000..7207ac5 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-32.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-512.png b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-512.png new file mode 100644 index 0000000..f074dc0 Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-512.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-64.png b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-64.png new file mode 100644 index 0000000..069816e Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-logo-transparent-64.png differ diff --git a/docs/logo/final/v1-simple-gear/mygoland-mark-32.png b/docs/logo/final/v1-simple-gear/mygoland-mark-32.png new file mode 100644 index 0000000..27affbc Binary files /dev/null and b/docs/logo/final/v1-simple-gear/mygoland-mark-32.png differ diff --git a/docs/logo/variants/v3a-double-gear/favicon-32px-x6-preview.png b/docs/logo/variants/v3a-double-gear/favicon-32px-x6-preview.png new file mode 100644 index 0000000..d1ddc3c Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/favicon-32px-x6-preview.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-1024.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-1024.png new file mode 100644 index 0000000..f8c23ab Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-1024.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-128.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-128.png new file mode 100644 index 0000000..52e7e51 Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-128.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-256.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-256.png new file mode 100644 index 0000000..67f342a Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-256.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-32.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-32.png new file mode 100644 index 0000000..046f07d Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-32.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-512.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-512.png new file mode 100644 index 0000000..3ed1fb0 Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-512.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-64.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-64.png new file mode 100644 index 0000000..52bc999 Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-64.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-1024.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-1024.png new file mode 100644 index 0000000..a9837c3 Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-1024.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-128.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-128.png new file mode 100644 index 0000000..b0d568f Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-128.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-256.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-256.png new file mode 100644 index 0000000..fa58f63 Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-256.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-32.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-32.png new file mode 100644 index 0000000..75c3a0e Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-32.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-512.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-512.png new file mode 100644 index 0000000..4266208 Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-512.png differ diff --git a/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-64.png b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-64.png new file mode 100644 index 0000000..56874fd Binary files /dev/null and b/docs/logo/variants/v3a-double-gear/mygoland-double-gear-transparent-64.png differ diff --git a/docs/menu-custom-title.png b/docs/menu-custom-title.png new file mode 100644 index 0000000..3067d89 Binary files /dev/null and b/docs/menu-custom-title.png differ diff --git a/docs/menu-custom-tree.png b/docs/menu-custom-tree.png new file mode 100644 index 0000000..f119763 Binary files /dev/null and b/docs/menu-custom-tree.png differ diff --git a/docs/menu-native.png b/docs/menu-native.png new file mode 100644 index 0000000..6251708 Binary files /dev/null and b/docs/menu-native.png differ diff --git a/docs/new-file-created.png b/docs/new-file-created.png new file mode 100644 index 0000000..effe194 Binary files /dev/null and b/docs/new-file-created.png differ diff --git a/docs/new-file-dialog.png b/docs/new-file-dialog.png new file mode 100644 index 0000000..964df29 Binary files /dev/null and b/docs/new-file-dialog.png differ diff --git a/docs/plans/2026-10-29-mygoland-design.md b/docs/plans/2026-10-29-mygoland-design.md new file mode 100644 index 0000000..fe9edef --- /dev/null +++ b/docs/plans/2026-10-29-mygoland-design.md @@ -0,0 +1,1953 @@ +# MyGoland 技术方案 + +日期:2026-10-29 +目标:用 **mygo + Go** 实现一个「做减法」的 Go IDE —— 秒开、低内存,只覆盖 Go 开发的最小闭环。 + +## 1. 范围 + +**做**:打开目录 → 编辑 → 补全/跳转/诊断 → 构建/运行/调试。 +**不做**:多语言、数据库/HTTP/Docker/K8s 工具、插件市场、远程开发、AI 补全、重构全家桶。 + +定位不是「替代 GoLand」,而是「Go 界的 Zed/Sublime」:启动快、占用低、只服务 Go。 + +## 2. 事实核查 + +以下结论均已实际验证(`go get` 拉取 v0.7.2 源码 + `go doc` 读签名),非二手转述。 + +| 问题 | 结论 | +|---|---| +| mygo 是否真实存在 | 是。`github.com/egoist/mygo` v0.7.2,MIT,2026-09 开源,约 2.8k star,作者 egoist(前 Vite 核心成员) | +| 是否需要 cgo | 否,`purego` 运行期调原生 API,任意平台交叉编译 | +| Windows 渲染 | 原生 UI 走 Direct3D 11,**不需要 WebView2**;Web 模式才用 WebView2 | +| 是否自带代码编辑器 | **是**。`ui/editor` 包按 Zed 设计:rope 缓冲区、语法高亮、多光标、软换行、折叠、查找替换、diff 视图、LSP 钩子 | +| LSP 接入方式 | `State.OnCompletion/OnHover/OnDefinition` + `SetDiagnostics/SetInlays`,异步结果用 `Window.Update` 回写 | +| 终端 | 官方 `plugins/terminal`(基于 Ghostty),可做运行/输出面板 | +| 文件监听 | `mygo` 内置 watch API + `plugins/watch` | +| 生态成熟度 | 新。126 个 open issue,API 仍在演化,遇坑需读源码 | + +**内存预期**:官方空壳参考 44 MB(原生 UI)。加上编辑器、文件树、语法高亮后预计 80–150 MB;`gopls` 子进程另算(中型项目数百 MB),这是不可消除的主要开销。相比 GoLand 的 1.4 GB 仍有数量级优势。 + +## 3. 分层 + +| 层 | 职责 | 依赖 | +|---|---|---| +| 壳层 | 窗口、菜单、快捷键、对话框、多显示器 | `mygo` | +| 视图层 | 文件树、标签栏、状态栏、面板布局 | `mygo/ui`(Tree/Scroll/Split/Tabs) | +| 编辑层 | 缓冲区、高亮、多光标、折叠、查找替换 | `mygo/ui/editor` | +| 语言层 | 补全、悬停、跳转、诊断、格式化 | **自研 LSP 客户端**(JSON-RPC over stdio)→ `gopls` | +| 调试层 | 断点、单步、变量、调用栈 | **自研 DAP 客户端** → `dlv dap` | +| 执行层 | go build / run / test 与输出 | `os/exec` + `plugins/terminal` | + +只有「语言层 / 调试层」需要自己写协议客户端,其余都是现成能力。 + +## 4. 目录结构 + +``` +MyGoland/ +├── main.go 入口:App 生命周期 +├── internal/ +│ ├── app/ 应用状态与视图 +│ │ ├── app.go 状态、打开/保存/关闭、文件树缓存 +│ │ ├── view.go 侧边栏 / 标签栏 / 编辑区 / 状态栏 +│ │ └── menu.go 原生菜单与快捷键 +│ ├── lsp/ gopls 客户端(P1) +│ │ ├── protocol.go JSON-RPC 报文 +│ │ ├── client.go 握手、生命周期、请求分发 +│ │ └── uri.go file:// URI 与 Windows 盘符处理 +│ └── debug/ dlv dap 客户端(P2) +└── docs/ +``` + +## 5. 阶段 + +| 阶段 | 内容 | 状态 | +|---|---|---| +| P0 骨架 | 打开目录、文件树、多标签、编辑、语法高亮、保存、脏标记、状态栏、菜单 | 已完成 | +| P1 语言 | gopls 握手、didOpen/didChange(增量)、诊断、补全、悬停、跳转定义、保存即 gofmt | 已完成 | +| P2a 执行 | 运行/构建/测试面板、输出着色、错误行点击跳转 | 已完成 | +| P2b 调试 | Delve DAP:断点、单步、变量与调用栈 | 已完成 | +| P3 打磨 | 全局搜索、符号大纲、git gutter、外部改动监听、会话恢复、字体与主题 | 待做 | + +## 6. 实测数据(2026-10-29) + +在本机(Windows 11,Go 1.27.3,gopls v0.23.0)打开本仓库自身测得: + +| 进程 | 内存 | +|---|---| +| MyGoland.exe(编辑器 + 文件树 + LSP 连接) | **61 MB** | +| gopls.exe(语言服务器) | 229 MB | + +结论与预期一致:壳层确实极轻,**内存主项是 gopls**,且随项目规模增长。强杀主进程后 gopls 随之退出,无孤儿进程。 + +集成测试(`go test ./internal/lsp`)覆盖:初始化握手、诊断、补全、跳转定义、增量同步触发新诊断,全部通过。 + +## 7. 已知风险 + +1. **框架年轻**:mygo 发布仅一个月,`ui/editor` 的 IME、超大文件、多光标等细节依赖上游修;必要时需 fork 或提 PR。 +2. **API 漂移**:v0.x 版本号意味着可能破坏性变更,依赖需锁定版本。 +3. **gopls 内存不受控**:可设 `GOMEMLIMIT`、按需启动、关闭闲置工作区,但无法根治。 +4. **Windows 细节**:高 DPI、字体回退、CJK 输入法需实测。 +5. **工作量**:LSP + DAP 客户端各约 800–1500 行,编辑器可复用,UI 组装是主要工程量。 + +## 8. 视觉与交互规范(2026-10-29 定稿) + +### 8.1 法律边界 + +| 可以做 | 不要做 | +|---|---| +| 借鉴交互范式:左侧工具窗、顶部标签、底部面板、状态栏分段、快捷键习惯 | 使用 GoLand / JetBrains 名称、Logo、产品图标 | +| 参考信息层级与操作流程(思想与功能不受版权保护) | 反编译或复制其 UI 资源、主题文件、图标、字体文件 | +| 自定配色与自绘控件 | 像素级复刻界面(可能触及商业外观 / 不正当竞争) | +| 在文档里写"操作习惯类似主流 IDE" | 宣称"兼容 GoLand""官方替代" | + +结论:**学习惯,不抄皮**。所有颜色、图标、间距均为自有实现。 + +### 8.2 配色(自有) + +| 用途 | 色值 | +|---|---| +| 窗口背景 | `#12161A` | +| 面板/侧栏 | `#1A2026` | +| 悬停 / 按下 | `#222A32` / `#2A333D` | +| 边框 | `#2B353F` | +| 正文 / 次要文字 | `#D5DEE8` / `#7C8A98` | +| 强调色(青绿) | `#3FBFAE`(刻意避开 JetBrains 蓝) | +| 错误 / 警告 / 成功 | `#E0605F` / `#D8A542` / `#5FBF7F` | +| 选中 | `rgba(63,191,174,0.26)` | + +圆角 4、间距单位 4、字号 13,均由 `internal/app/theme.go` 统一给出。 + +### 8.3 交互习惯 + +- 左侧「项目」工具窗:标题栏 + 刷新/全部折叠,底部显示工作区路径。 +- 标签页:每页自带 `●`(未保存)与 `✕`(关闭)。 +- 底部面板:`运行` / `问题` 双页签;问题页列出 gopls 诊断,点击跳转。 +- 状态栏分段:`Ln/Col`、行数、`✕/▲` 计数、语言服务器状态、换行符、编码、语言。 +- 快捷键:`Ctrl+F9` 构建、`Shift+F10` 运行、`Ctrl+Shift+F10` 测试、`Ctrl+F2` 停止、`Alt+1` 项目窗、`Alt+0` 面板、`Ctrl+S` 保存。 + +### 8.4 尚未实现(后续可补) + +面包屑导航、`Alt+Enter` 意图动作、结构/大纲视图、书签、最近文件(`Ctrl+E`)。 + +## 9. 调试层(P2b,2026-10-29) + +### 9.1 传输方式(关键坑) + +`dlv dap` **不接受 stdio 传输**。它启动后监听一个随机端口,把 +`DAP server listening at: 127.0.0.1:` 打到标准输出。 +客户端必须:起进程 → 解析这行 → 用 TCP 连上去,之后才走 +`Content-Length` 分帧的 DAP 报文。 + +(第一次按 stdio 实现时表现为 `initialize` 一直超时,因为 dlv 在等 TCP 客户端。) + +### 9.2 握手顺序 + +``` +initialize → (response) +launch → 异步等待,期间适配器发 initialized 事件 +initialized 事件 → setBreakpoints(按文件)→ configurationDone +之后:stopped / continued / output / terminated 事件 +``` + +`setBreakpoints` 与 `configurationDone` 必须在 `initialized` 事件之后发, +否则程序会直接跑完。 + +### 9.3 已实现 + +| 能力 | 实现方式 | +|---|---| +| 断点 | 点击行号(`State.OnGutterClick`,0 起行号)→ `bps[path]` → `GutterMark` 红点;会话中增删立即 `setBreakpoints` | +| 启动 | 菜单 / `Shift+F9`,`launch{mode:"debug", program:"./"}`,工作目录 = 工作区根 | +| 单步 | 继续 `F9`、步过 `F8`、单步进入 `F7`、跳出 `Shift+F8`;停止 `Ctrl+F2` | +| 停点定位 | `stopped` → `stackTrace` → 打开文件 + `GoTo` + `ScrollTo`,当前行用 `LineBackground` 高亮 | +| 变量 | `scopes`(跳过 expensive 与 ref=0)→ `variables`,在「调试」页签列出 | +| 调用栈 | `stackTrace(levels:20)`,栈顶加 `▸` | +| 程序输出 | `output` 事件按行写入「运行」页签 | + +### 9.4 验证 + +`internal/dap` 集成测试(真实 dlv 进程): + +| 步骤 | 断言 | +|---|---| +| initialize / launch | 收到 `initialized` | +| setBreakpoints(6) + configurationDone | 停在 6 行 | +| stackTrace | 栈顶文件为 main.go、行号 6 | +| scopes + variables | 局部变量 a = 1 | +| next | 行号变为 7 | +| continue | 收到 `terminated` | + +应用层另用临时钩子验证过一次完整链路:断点停在 main.go:13,3 个栈帧、2 个局部变量。 + +### 9.5 已知限制 + +- 只支持「调试工作区根包」(`program: "./"`),还没有运行/调试配置。 +- 变量只展开一层,结构体/切片不递归;不支持表达式求值(`evaluate`)。 +- 没有条件断点、日志断点、断点分组管理。 +- goroutine 列表未做(多协程程序只看当前线程栈)。 + +## 10. 第二轮打磨(2026-10-29) + +### 10.1 截图暴露的问题 + +| 现象 | 原因 | 处理 | +|---|---|---| +| 侧栏标题栏两个按钮显示成方块 | 字体缺 `⟳` `⊟` 字形 | 改成 10px 中文小字按钮「刷新」「折叠」,不依赖字形 | +| 文件树里出现 `__debug_bin.exe` | dlv 构建产物落在包目录 | `skipFile` 过滤 `__debug_bin*`、`.exe`、`.test` | +| 顶部菜单是英文 `Edit` | 用了平台内置 RoleEditMenu | 自建中文「编辑」菜单,接 `editor.Undo/Redo/Cut/Copy/Paste/SelectAll/ToggleComment` | + +### 10.2 变量与求值 + +- 变量树:`debugVar` 带 `Ref` 与 `Depth`,点一下按 `variablesReference` 拉子节点,`expanded`/`children` 记录展开状态,`visibleVars` 递归铺平成带缩进的列表;每次停点清空展开状态。 +- 表达式求值:`evaluate{expression, frameId, context:"watch"}`,输入框回车或点「执行」,结果显示在输入框右侧(带返回类型)。 + +### 10.3 运行/调试配置 + +- `runConfig{Program, Args, StopOnEntry}`,配置行就在「调试」页签顶部,可直接改。 +- 按工作区持久化到用户配置目录:`/mygoland/run-.json`,**不往用户仓库里塞文件**。 +- `Args` 用 `strings.Fields` 切分,暂不支持引号包裹带空格的参数。 + +### 10.4 验证 + +- `internal/app` 单测:变量铺平(0/1/2 层缩进)、断点排序、文件过滤。 +- `internal/dap` 集成测试新增求值断言:断点处 `a+b` 返回 `3 (int)`。 +- 全部包测试通过;新菜单(含 `Ctrl+/`、`Ctrl+Shift+Z` 等 accelerator)启动无崩溃。 + +## 11. 图标体系(2026-10-29) + +### 11.1 方案 + +- **自绘 24 栅格 SVG**,内嵌为 Go 字符串常量(`internal/app/icons.go`),进程启动时 `ui.ParseSVG` 解析一次。 +- 不用字体字形 —— 之前 `⟳`/`⊟` 在系统字体里缺字形,渲染成方块。 +- `ui.Icon` 会把图形画成**文字颜色**("whatever colors the SVG has"),所以颜色由 `.TextColor()` 决定,SVG 里只区分 `fill` 与 `fill="none"`。 +- 风格 B:细线 1.5px + 语义色 —— 运行/继续用青绿,停止用红,构建用紫,测试用琥珀。 + +### 11.2 已接入的位置 + +| 位置 | 图标 | 形式 | +|---|---|---| +| 侧栏标题栏 | refresh / collapse | 纯图标 + tooltip | +| 标签页 | close | 纯图标,替代 `✕` 字符 | +| 面板工具条 | build / run / test / stop / clear | 图标 + 文字 | +| 面板右上 | hide | 纯图标 | +| 调试页签 | continue / over / into / out / stop | 图标 + 文字 | +| 状态栏 | error / warning | 图标 + 数字 | +| 状态栏右 | panel | 图标 + 文字 | + +### 11.3 验证与限制 + +- `TestIconsParsed` 确认 18 个图标全部解析成功(含 ``、`` 元素)。 +- **文件树暂时没有类型图标**:`ui.TreeItem` 只接受 label 字符串,塞不进元素。要加就得自己用 Row + 缩进重写树控件,属于后续工作。 + +### 11.4 授权 + +图标几何按通用语义自绘,未复制任何图标集的资源文件。参考的 Lucide 为 ISC、Material Symbols 为 Apache-2.0,均允许商用,但本项目不依赖其文件。 + +## 12. 去掉启动时的控制台(2026-10-29) + +### 12.1 原因 + +Go 默认产出 **控制台子系统**(PE Subsystem = 3)的 exe,双击时 Windows 必须为它挂一个 +控制台窗口。这不是 mygo 的行为,是链接参数决定的。 + +### 12.2 修复 + +构建时改成 GUI 子系统: + +``` +go build -trimpath -ldflags "-s -w -H=windowsgui" -o MyGoland.exe . +``` + +已提供 `build.cmd`(Windows)固化这条命令。链参数效果:Subsystem = 2(WINDOWS_GUI)。 + +### 12.3 连带改动:日志落文件 + +GUI 子系统下没有控制台,`os.Stderr` 是无效句柄,语言服务器与调试的排错信息会全部丢失。 +所以 `SetupLog()` 在启动时把 `log` 输出改成 +`/mygoland/mygoland.log`(Windows 即 `%LocalAppData%\mygoland\mygoland.log`), +同时保留 `io.MultiWriter` 到标准错误,从终端运行时照旧能看到。日志超过 4 MB 时启动清空。 + +菜单「帮助 → 打开日志 / 在文件夹中显示日志」直接调用 `mygo.Shell.OpenPath` / +`ShowItemInFolder`。 + +另外 `finishTask` 会把 `command "" exited , lines` 写进日志,便于事后排查运行面板的问题。 + +### 12.4 验证 + +| 项目 | 结果 | +|---|---| +| PE Subsystem | 2(WINDOWS_GUI)—— 直接读 exe 头确认 | +| 启动 | 无控制台,进程正常,内存 54 MB | +| gopls 子进程 | 正常拉起(GUI 父进程创建控制台子进程无碍) | +| `go build` 子进程 | 日志记录 `command "go" exited 0`,输出面板链路正常 | + +## 13. 未保存保护(2026-10-29) + +### 13.1 三个入口统一走确认 + +| 入口 | 拦截点 | 行为 | +|---|---|---| +| 关窗口 | `Window.OnClose` → `PreventDefault()` | 有脏文件时弹「保存全部 / 不保存 / 取消」 | +| 退出应用 | `App.OnBeforeQuit` → `PreventDefault()` | 同上 | +| 切换工作区 | `switchRoot()` 前置检查 | 同上,取消则留在当前工作区 | + +实现要点: +- 事件回调在主线程,**不能直接弹模态**(会卡住事件循环),所以先 `PreventDefault` 再起协程弹窗,确认后回到主线程执行 `Close()` / `App.Exit(0)` / `setRoot()`。 +- `exitPending` 防重入,避免连点关闭弹两次;`allowExit` 放行第二次关闭。 +- 脏文件列表在主线程取出后传给协程,避免跨线程读 `a.docs`。 + +### 13.2 顺带修掉的两个 bug + +1. **「保存并关闭」会丢改动**:`CloseDoc` 原先调异步 `saveDoc`(要等 LSP 格式化往返),而 `removeDoc` 立即执行;等保存协程回到主线程时 `find(path)` 已返回 nil,直接跳过写盘。改为同步 `writeDocFile` 后再移除。 +2. **源码编译不过**:`minimap.go` 里 `maxW` 声明未使用(上一轮遗留),导致 `go build` 失败。已删除该变量,逻辑不变(宽度由 `room` 计算)。 + +### 13.3 验证 + +| 场景 | 方法 | 结果 | +|---|---|---| +| 有脏文件时关闭 | 临时钩子把缓冲区改脏,`taskkill`(不带 /F,发 WM_CLOSE) | 进程存活 → 停在确认对话框 ✓ | +| 无脏文件时关闭 | 同上但不改脏 | 进程 4 秒内退出,退出码 0 ✓ | +| 写盘与脏标记 | 单测 `TestWriteDocFile` | 写后内容正确、`Modified()` 变 false ✓ | +| 批量保存 | 单测 `TestSaveDocsNilWindow` | 无窗口时不 panic,保存成功 ✓ | +| 错误路径 | 单测 `TestWriteDocFileError` | 目标不可写返回 error 而非 panic ✓ | + +## 14. 外部改动监听(2026-10-29) + +### 14.1 方案 + +用 mygo 内置的 `mygo.WatchFiles(ctx, path, opts)` 监听**每个已打开文件**(不是整棵树), +去抖 300 ms,事件回到主线程处理。 + +判断流程(`onDiskChange`): + +``` +stat 文件 + ├─ 不存在 → 输出「已从磁盘删除」,丢弃监听(保留缓冲区,不自动关标签) + ├─ 时间戳与大小都和记录一致 → 自己的保存,忽略 + ├─ 读出来的内容与缓冲区一致 → 只更新时间戳,忽略 + ├─ 缓冲区有未保存改动 → 弹「重新加载 / 保留我的改动」 + └─ 缓冲区干净 → 直接 Reload(Reset 缓冲区,清空旧诊断) +``` + +### 14.2 关键点 + +- **必须比较内容**,不能只靠时间戳:写盘后事件可能先于状态更新到达,只比时间戳会误判成外部改动。 +- `writeDocFile` 写完后调 `notifySaved()` 刷新时间戳,正常保存不会触发重载。 +- `Buffer.Reset` 会清空撤销历史并把当前文本记为「已保存」,这对外部改动是正确的语义。 +- 关闭标签页时 `stopWatch()`,避免监听泄漏。 + +### 14.3 验证 + +| 场景 | 方法 | 结果 | +|---|---|---| +| mygo 单文件监听是否可用 | `TestFileWatchFires`(真实写文件) | 0.5 s 内收到事件 ✓ | +| 干净缓冲区重载 | `TestOnDiskChangeReload` | 内容被替换、`Modified()` 为 false ✓ | +| 内容未变不折腾 | `TestOnDiskChangeSameContent` | 版本号不变 ✓ | +| 端到端 | 启动应用后从外部 `echo >>` 追加内容 | 日志出现 `reload ... after external change` ✓ | + +### 14.4 已知限制 + +- 只监听已打开的文件;文件树本身不监听(外部新建/删除文件后需手动刷新)。 +- 文件被删除时不自动关闭标签页,只提示,缓冲区内容仍可另存。 +- 冲突时选「保留我的改动」后,下一次保存会覆盖磁盘内容,没有三方合并。 + +## 16. 项目工具窗按钮与动效(2026-10-29) + +### 16.1 按钮 + +标题栏从左到右:定位当前文件、**新建(+)**、刷新、全部折叠、展开全部。 + +「+」点开自绘菜单(复用 `openPop`): + +| 菜单项 | 目标目录 | +|---|---| +| 新建文件 | 选中项是目录就它本身,是文件就取所在目录;没选中则用工作区根 | +| 新建文件夹 | 同上 | + +「展开全部」递归把目录标记为展开,深度上限 10 层,防止超大仓库一次铺开卡死。 + +### 16.2 动效 + +| 元素 | 效果 | 实现 | +|---|---|---| +| 图标按钮 | 悬停淡入底色、按下更深一档并缩到 0.92 | `AnimateColor("iconbg")` 120ms + `AnimateTo("iconscale")` 90ms | +| 目录箭头 | 展开时从 0° 转到 90° | 箭头改成 SVG 图标,`AnimateTo("chevron", 0→90)` 140ms `EaseOut` + `Rotate` | +| 折叠/展开图标 | 改成竖向双箭头(相当于原来的横版转 90°) | `icons.go` 里换 path | + +`ui.Icon` 会把图形画成文字颜色,所以箭头颜色直接跟主题走。 + +### 16.3 顺带修的 + +`CollapseAll` 只走 `win.Update`,没有窗口时什么都不做;`ExpandAll` 新加时做了无窗口分支。 +两个函数现在一致:无窗口就直接执行,方便单测。 + +### 16.4 验证 + +| 项目 | 结果 | +|---|---| +| `TestExpandAll` | 两层目录都能标记展开,`CollapseAll` 能全部收回 ✓ | +| `TestAddEntriesTargetDir` | 「+」菜单固定两项,选中文件时落到其所在目录 ✓ | +| `TestIconsParsed` | 新增的 plus / expand / chevron 图标解析通过 ✓ | +| 启动冒烟 | 新版本启动无崩溃,侧栏渲染正常 ✓ | + +## 17. 左侧竖条与大纲面板(2026-10-29) + +### 17.1 布局 + +窗口最左侧新增一条 38px 的竖条(tool window stripe),然后才是可拖动的工具窗,最后是编辑器: + +``` +Row ── rail(38) ── Split(sidebar, main) +``` + +竖条**常驻**:`Alt+1` 收起工具窗时它仍在,和成熟 IDE 的习惯一致。点当前高亮的图标会收起工具窗,点另一个会切换内容。 + +| 入口 | 图标 | 内容 | +|---|---|---| +| 项目 | folder | 文件树(原有) | +| 大纲 | outline | 当前文件的符号树(新增) | + +激活项:图标转青绿、底色 `Accent.Alpha(0.18)`;悬停有 120ms 底色过渡。 + +### 17.2 大纲 + +- 数据来自 gopls 的 `textDocument/documentSymbol`,`lsp.Client` 兼容层级式 `DocumentSymbol[]` + 与平铺 `SymbolInformation[]`(后者取 `location.range`)。 +- 铺平成一维列表,按层级缩进 12px;每项前一个 6px 色块区分类型:函数/方法青绿、类型/结构/字段琥珀、 + 接口/常量绿色、其余灰。 +- 点击跳到符号的 `selectionRange` 起点;光标所在行的符号高亮(`outlineRowIndex`)。 +- 取符号做了 **400ms 去抖**,切文件先清空列表,避免短暂显示上一个文件的内容。 +- 非 Go 文件、语言服务器未就绪时给出对应提示。 + +### 17.3 验证 + +| 项目 | 结果 | +|---|---| +| `TestGoplsDocumentSymbol` | 真实 gopls 返回层级符号,`point` 结构体带字段子项 ✓ | +| `TestFlattenSymbols` | 3 个顶层 + 2 个子项铺平成 5 行,深度正确 ✓ | +| `TestSymbolColorDiffers` | 函数与类型取到不同颜色 ✓ | +| 端到端 | 用临时钩子默认打开大纲页签,日志 `outline: 2 symbols`(greeter.go 两个函数)✓ | + +## 18. 左侧竖条与状态栏岛屿化(2026-10-29) + +### 18.1 改动 + +| 区域 | 之前 | 之后 | +|---|---|---| +| 左侧竖条 | 透明 Column,直接坐在窗口底色上,和工具窗之间没有缝 | 独立卡片:`Radius + Surface + Clip`,宽 40,上下 6 内边距,和工具窗之间留 4px 缝 | +| 状态栏 | 通栏 Row,顶上一条 1px 边框 | 独立卡片:`Radius + Surface + Clip`,左右各留 8、上下各留 4,高度 26,去掉通栏边框 | + +外层容器加了 `.Gap(4)`,让竖条、工具窗、编辑器之间统一保持 4px 沟。 + +### 18.2 注意 + +- 状态栏内层 Row 必须 `.FillWidth()`,否则 Row 只按内容宽度撑开,卡片右边会空一截。 +- 原来状态栏靠 `BorderWidth(1,0,0,0)` 和编辑区划分界限,岛屿化后由卡片自身的圆角和底色区分,边框去掉。 + +### 18.3 验证 + +构建通过,启动冒烟 9 秒无崩溃(66 MB),`go test ./internal/app` 通过。视觉效果待截图确认。 + +## 19. 状态栏左边界对齐编辑区(2026-10-29) + +### 19.1 改动 + +状态栏原来挂在根 `Column` 末尾,横跨整个窗口宽度,左边一直伸到侧栏下面。 +现在移到 `mainView` 里,排在编辑区卡片之后: + +``` +Row ── rail | Split(sidebar, mainView) + └ Column ── 编辑区卡片 + └ 状态栏卡片(左边界=编辑区左边界) +``` + +配套改动:`mainPanel` 从 `.Fill()` 改成 `.Grow(1).FillWidth()`,否则它会占满父列高度, +把下面的状态栏挤出可视区域。 + +### 19.2 效果 + +- 侧栏存在时:状态栏起点与编辑区左边界对齐,侧栏下方保持空白。 +- 侧栏收起时(`Alt+1`):状态栏自动左移到竖条右侧,不会留下空档。 +- 状态栏上方 4px、下方由外层 Row 的 4px 内边距留出缝隙,仍是独立岛屿。 + +### 19.3 验证 + +构建通过,启动冒烟 9 秒无崩溃(71 MB),`go test ./internal/app` 通过。 + +## 20. 左侧竖条置顶(2026-10-29) + +### 20.1 原因 + +`Row` 的默认 `AlignItems` 是居中。竖条本身没有设高度,只有内容那么高(两个按钮约 70px), +于是整块被垂直居中,看起来悬在左侧中间,而不是像 IDE 那样从顶到底的一条。 + +### 20.2 修复 + +- 竖条:`Width(40).FillHeight()` + `Justify(ui.Start)`,撑满高度且内容从顶部开始排。 +- 外层 `Row`:加 `AlignItems(ui.Stretch)`,让竖条、工具窗、编辑区都纵向拉满,不被居中。 + +### 20.3 验证 + +构建通过,启动冒烟 8 秒无崩溃(71 MB)。视觉效果待截图确认。 + +## 21. 统一岛屿间距(2026-10-29) + +### 21.1 目标 + +- 状态栏左边界对齐**项目岛**左边界(不再是编辑区左边界)。 +- 所有浮岛之间的缝宽度一致,看起来成套。 + +### 21.2 结构 + +``` +Row(gap=islandGap, padding=8) + ├ rail + └ Column(gap=islandGap) + ├ Split(项目, 编辑区) + └ 状态栏 +``` + +`islandGap = 6`,定义为 `view.go` 里的常量,所有缝都从它取值: + +| 位置 | 来源 | +|---|---| +| 竖条 ↔ 项目 | 外层 Row 的 `Gap(islandGap)` | +| 项目 ↔ 编辑区 | `sidebarView` 右内边距 `islandGap-1` + Split 自带的 1 DIP 分隔条 | +| 编辑区 ↔ 状态栏 | 包装列的 `Gap(islandGap)` | +| 四周 ↔ 窗口边 | 外层 Row 的 `Padding(8)` | + +状态栏现在挂在包装列里,左边界天然等于 Split 的左边界,也就是项目岛左边界;侧栏收起时会自动跟到竖条右侧。 + +### 21.3 注意 + +- `Split` 的分隔条占 1 DIP 且算在第一段宽度内,所以侧栏右内边距要用 `islandGap-1` 来抵消,否则这条缝会比别处宽 1px。 +- `DrawOver` 覆盖分隔条的宽度同步调到 7px(`x-3` 起),保证盖住那条亮线。 + +### 21.4 项目 ↔ 编辑区那条缝偏宽的修正 + +覆盖 Split 分隔条的底色层原来有 7px 宽(`x-3` 起),相当于往编辑岛里多糊了 4px 背景色, +那条缝实际看起来约 10px,比别处的 6px 宽一截。 + +修正:覆盖宽度收到 2px(`x-1` 起,只盖分隔条),侧栏右内边距改成 `islandGap-2`, +把「分隔条 1px + 覆盖压入 1px」都补偿掉,视觉缝宽回到 6px。 + +想整体调宽窄只需改 `view.go` 里的 `islandGap` 常量,四处缝会自动跟着变。 + +## 22. 编辑器浮岛圆角与其它浮岛不一致(2026-10-29) + +### 22.1 原因 + +卡片本身是 `Radius(8) + Clip()`,但里面的编辑器又自己铺了一层**矩形**底色(`editor.Theme.Background`), +底部面板也铺了一层 `Surface`。颜色和卡片相同,但矩形没有圆角,正好盖住卡片四个角的弧形区域, +视觉上就成了直角——其余浮岛没有这层覆盖,所以圆角是好的。 + +### 22.2 修复 + +| 位置 | 改动 | +|---|---| +| 编辑器主题(明暗两套) | `Background: ui.Hex(palette.island).Alpha(0)` —— 颜色保留、透明度归零,编辑器不再铺底,露出卡片的圆角表面 | +| 底部面板 | 去掉 `Background(t.Surface)`,底色交给外层卡片 | + +保留 RGB 是为了 `isDark(theme.Background)` 判断明暗仍然正确;编辑器绘制背景前会检查 +`Background.A > 0`(`ui/editor/paint.go:117`),透明度为 0 时直接跳过填充。 + +### 22.3 验证 + +`go test ./...` 全绿,构建通过,启动冒烟正常(73 MB)。圆角效果待截图确认。 + +## 23. 自建 UI 截图验证通路(2026-10-29) + +改 UI 靠「用户截图 → 我猜」效率太低,接了一条能自己抓图的链路: + +| 步骤 | 文件 / 命令 | +|---|---| +| 1. 引入自动化插件 | `automation_e2e.go`,`//go:build e2e`,空白导入 `plugins/automation` | +| 2. 构建 | `go build -tags e2e -o e2e.exe .` | +| 3. 运行 | `MYGO_AUTOMATION= ./e2e.exe <工作区>` | +| 4. 抓图 | `tools/shot`,JSON 行协议:`windows` → 取 id → `capture{window:id}` → base64 PNG | + +Windows 也走 `net.Listen("unix", path)`,AF_UNIX 在 Win10 1803+ 可用。 + +验证方法:PIL 采样像素,判断「顶行首个非背景色像素相对卡片左边缘的偏移」,即可量化圆角弧度; +本机 DPI 125%,截图 1632×1065 对应逻辑 1305 宽。 + +## 24. 布局改为「间距 + 自绘分隔条」(2026-10-29) + +### 24.1 问题 + +编辑岛左上角弧度只有 2px,其余三个角 6px。根因是 `ui.Split` 在分段交界处裁剪,贴边的卡片圆角被切平。 + +### 24.2 结构 + +``` +Row(Gap 6) + ├ 竖条 + └ Column(Gap 6) + ├ Row(AlignItems=Stretch) + │ ├ 项目岛(Width(a.sidebar).Shrink(0)) + │ ├ splitter(自绘,宽 = islandGap,可拖拽) + │ └ 编辑岛(mainPanel,Grow) + └ 状态栏 +``` + +splitter 用 `ui.Box + Draggable`,但每帧把位移指针归零,元素本身不动,只借 `Dragged()` 读指针增量改 `a.sidebar`(夹在 140 与 窗口宽-420 之间);悬停时染 `SurfaceHover`。 + +### 24.3 踩到的两个布局坑 + +- 侧栏卡片缺 `.FillWidth()` 时宽度按内容收缩(312 图像素对应 250 逻辑像素,一开始误判成被挤压)。 +- 内层 `Row` 缺 `.AlignItems(ui.Stretch)` 时,子项按内容高度居中,编辑区直接塌成一条横带。 + +### 24.4 实测(e2e 截图 + 像素采样) + +| 位置 | 顶行偏移 | 结论 | +|---|---|---| +| 项目岛左上 | 6px | ✓ | +| 编辑岛左上 | 6px | ✓ | +| 编辑岛右上 | 6px | ✓ | +| 三块间距 | 8 图像素(=6 逻辑) | ✓ | +| 状态栏横向范围 | 68–1622,与项目岛左边界对齐 | ✓ | + +## 25. 会话恢复(2026-11-03) + +### 25.1 存什么 + +| 项 | 字段 | +|---|---| +| 工作区 | `root` | +| 打开的标签 | `tabs[]`、`active` | +| 断点 | `breakpoints{文件: [行号]}` | +| 底部面板 | `panel`、`panelTab`、`panelH` | +| 左侧工具窗 | `sidebar`、`sidebarW`(宽度)、`panelKind`(项目/大纲) | +| 外观与终端 | `light`、`shellIdx` | + +存到 `%AppData%/mygoland/session-.json`,另写一份 `last.json` 记住最后的工作区。 + +**为什么放用户配置目录**:这是「这台机器上的使用习惯」,不该跟着仓库提交(对比之下,运行/调试配置放在工作区里是合理的,它属于项目)。 + +### 25.2 什么时候写 + +切工作区前、退出时、打开/关闭标签、切面板、切主题、切断点、分隔条松手——都是状态真正变化的点。文件几百字节,直接同步写,不做防抖。 + +### 25.3 恢复流程 + +``` +启动 + ├ 带参数 → setRoot(参数) + ├ 不带参数 → lastWorkspace() 存在就用它 + └ setRoot 内部:saveSession(旧) → 切换 → restoreSession(新) +``` + +`restoreSession` 期间置 `restoring=true`:恢复标签会触发 `loadDoc`,那里也会存会话,不挡住就会用「恢复到一半」的状态覆盖存档。 + +### 25.4 验证 + +| 场景 | 方法 | 结果 | +|---|---|---| +| 存取往返 | `TestSessionRoundTrip` | 面板/侧栏/标签/断点/主题/外壳全部还原 ✓ | +| 记住工作区 | `TestLastWorkspace` | `last.json` 指向上次目录 ✓ | +| 目录被删 | `TestLastWorkspaceGone` | 返回空,不打开失效路径 ✓ | +| 端到端 | 带文件启动一次 → 强杀 → **不带参数**重启 | 自动打开 IdeTest,标签栏有 main.go,代码带语法高亮,状态栏正常 ✓ | + +顺带删掉了根目录 15 MB 的 `MyGoland.exe~` 残留。 + +## 26. 快速打开与全局搜索(2026-11-03) + +### 26.1 两个入口 + +| 命令 | 快捷键 | 数据来源 | +|---|---|---| +| 快速打开文件 | `Ctrl+P` | 工作区文件索引 + 模糊匹配 | +| 全局搜索 | `Ctrl+Shift+F` | 逐文件按行搜索 | + +都在「编辑」菜单里。面板是 `ui.Modal` 覆盖层,输入框自动聚焦。 + +### 26.2 实现要点 + +- **文件索引**:`buildIndex` 在后台 `WalkDir` 一次,缓存相对路径(跳过 `.git` / `node_modules` 等),最多 2 万条;换工作区时重建。 +- **模糊匹配**:子序列匹配 + 打分(连续匹配 +8、词边界 +6、文件名内含查询 +20、路径越长扣分),按分数排序。 +- **内容搜索**:只读 ≤512 KB 且是 UTF-8 的文件,按行 `Contains`,最多 200 条;查询变化后 220 ms 去抖,用代次号丢弃过期结果。 +- **跳转**:命中行打开文件后 `GoTo` + `ScrollTo`。 + +### 26.3 回车为什么这么难接 + +`Enter` 在输入框里会先被框架处理成「对输入框的一次点击」,所以下面三种写法**都收不到**: +`c.Shortcut(0, KeyEnter)`、`el.Shortcut(0, KeyEnter)`、`c.OnShortcut(0, KeyEnter, fn)`。 + +正确做法是输入框元素自己的 `Submitted()`:`inp.Submitted()` 在每个构建批次里报告「刚按了回车」。 + +方向键同理被输入框拿去移动光标,选中项移动改用 `Ctrl+N` / `Ctrl+P`。 + +还有一处顺序坑:`Submitted()` 必须在**刷新候选之后**判断,否则回车作用在上一帧的列表上(输入 `greet` 却打开了 `go.mod`)。 + +### 26.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 模糊匹配打分 | `TestFuzzyScore*`、`TestQuickResultsRanking` | 文件名命中排在目录命中之前 ✓ | +| 内容搜索 | `TestSearchInWorkspace`、`TestSearchSkipsSkippedDirs` | 命中行号正确、跳过 node_modules ✓ | +| 快速打开端到端 | 菜单打开 → 输入 `greet` → 回车 | 列表从 4 项收敛到 2 项,回车打开 greeter.go ✓ | +| 全局搜索端到端 | 菜单打开 → 输入 `Twice` → 回车 | 7 条命中(含行号与片段),回车跳到 greeter.go 第 11 行,状态栏显示「行 11」✓ | + +## 27. 查找引用与重命名符号(2026-11-03) + +### 27.1 入口 + +| 命令 | 快捷键 | 行为 | +|---|---|---| +| 重命名符号 | `F2` | 弹窗输入新名(预填光标处的词),确认后跨文件改名 | +| 查找引用 | `Shift+F2` | 结果列进命令面板,回车跳转 | + +### 27.2 实现 + +- `lsp.Client` 新增 `References` / `Rename`;`WorkspaceEdit` 同时兼容 `changes` 与 `documentChanges` 两种形态(`ByFile()` 合并)。 +- 引用结果复用命令面板:`paletteState.refs` 模式下候选已算好,输入只做本地过滤。 +- 重命名落到各文件的缓冲区上(`applyEdits`),**不自动保存**——标签上出现未保存圆点,让用户先看再存。 + +### 27.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| gopls 引用 | `TestGoplsReferencesAndRename` | `helper` 返回 3 处(声明 + 2 次调用)✓ | +| gopls 重命名 | 同上 | 产生 ≥3 处修改,新名均为 `assist` ✓ | +| UI 端到端 | 光标放到 `Greet` → 查找引用 | 面板列出 5 条,跨 3 个文件(greeter.go ×3、greeter_test.go、main.go)✓ | +| UI 端到端 | 重命名 `Greet` → `Salute` | 3 个文件的缓冲区被改写,标签显示未保存圆点;磁盘文件未改动 ✓ | + +### 27.4 已知问题(已在第 29 节修复) + +弹窗/命令面板关闭后焦点不回到编辑器。原因见第 29 节。 + +## 28. Git 集成(2026-11-03) + +### 28.1 范围 + +第一版只做「看得见 + 提交」,不做 diff 视图、分支切换、历史。 + +| 能力 | 位置 | +|---|---| +| 文件树按状态着色 + 角标 | `M` 琥珀、`A`/`R`/`??` 绿、`D`/`U` 红 | +| 状态栏分支与改动数 | `⎇ master` + `N 处改动` | +| 提交 | 菜单 Git → 提交…(`Ctrl+Enter`),先 `git add -A` 再 `git commit -m`,结果写进输出面板 | +| 刷新 | 菜单 Git → 刷新状态(`F5`)、存盘后自动刷新、切工作区时刷新 | + +### 28.2 实现 + +`internal/git` 用命令行读状态,不引第三方库: + +- `Available`:`git rev-parse --is-inside-work-tree` +- `Load`:`git rev-parse --abbrev-ref HEAD` + `git status --porcelain=v1 -z --untracked-files=all --no-renames` +- 用 `-z` 后路径不做八进制转义,中文文件名不会乱码 +- 设置 `GIT_OPTIONAL_LOCKS=0`,只读查询不去抢 `index.lock` + +状态码压缩规则(`codeFor`):`?`→`??`、`U`→`U`、`D`→`D`、`R`→`R`、`A`→`A`、`M/T`→`M`。 + +### 28.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 状态码映射 | `TestCodeFor` | 10 组 XY 组合全对 ✓ | +| 输出解析 | `TestParsePorcelain` | `-z` 输出解析出 4 条,路径与状态正确 ✓ | +| 真仓库 | `TestLoadRealRepo` | init→commit 后干净;改一加一后 `M` + `??`、Dirty=2;再提交后归零 ✓ | +| UI 端到端 | 打开带改动的仓库 | 文件树 `a.go M`(琥珀)、`b.go U`(绿),状态栏 `⎇ master` + `2 处改动` ✓ | +| 提交端到端 | Git → 提交… → 输入说明 → 回车 | `git log` 出现该提交、工作区变干净、树角标消失、状态栏计数消失、面板显示「已提交:…」✓ | + +## 29. 弹窗关闭后的焦点回收(2026-11-03) + +### 29.1 根因 + +两件事叠在一起: + +1. `Element.AutoFocus()` 只在**元素首次出现的那一帧**生效(文档原文 "in the frame it appears")。 + 编辑器从启动起就一直在,所以关弹窗后调 AutoFocus 等于什么都没做。 +2. 要抢回焦点得用 `Element.Focus()`,但它是「每帧调用就每帧保持」——无条件调用会把焦点钉死在编辑器上, + 连命令面板的输入框都抢不到。 + +### 29.2 做法 + +```go +// 弹窗/面板关闭后,延后 120 ms 设标记 +func (a *App) focusEditorSoon() { + time.AfterFunc(120*time.Millisecond, func() { + a.win.Update(func() { a.wantFocus = true }) + }) +} + +// editorArea 里:只在需要的那一帧 Focus 一次 +if a.wantFocus { + e.Focus() + a.wantFocus = false +} else if grow { + e.AutoFocus() +} +``` + +- **必须延迟**:关弹窗的同一帧里 Modal 的焦点作用域还没拆完,此时 Focus 会被它覆盖。 +- **必须只调一次**:`Focus()` 每帧生效,常驻调用会永久霸占焦点。 + +接入点:命令面板选择后、重命名弹窗关闭后、提交弹窗关闭后、底部面板收起后。 + +### 29.3 验证 + +| 场景 | 操作 | 结果 | +|---|---|---| +| 命令面板 | 快速打开 greeter.go → 不点鼠标直接按 ↓↓ | 光标 行 1 → 行 4 ✓ | +| 底部面板 | 打开面板 → 再关掉 → 按 ↓↓ | 光标 行 1 → 行 3 ✓ | + +修复前同样的操作光标纹丝不动(必须先点一下编辑器)。 + +## 30. 代码动作(Alt+Enter,2026-11-03) + +### 30.1 入口 + +- `Alt+Enter`:编辑器里就地触发(`State.OnInput` 在编辑器处理按键之前拿到,返回 true 消费掉) +- 编辑 → 代码动作(Alt+Enter):菜单入口,**不挂快捷键**,免得和编辑器抢按键 + +结果列进命令面板(`pal.action` 模式),回车执行。 + +### 30.2 关键:诊断必须原样带回去 + +gopls 的「Add import "fmt"」「删除未使用变量」这类快速修复**不是凭位置算出来的**, +而是靠客户端把 `publishDiagnostics` 里的那条诊断(含 `data` 字段)原封不动传回 `textDocument/codeAction`。 + +踩了两个坑: + +1. `lsp.Diagnostic` 原先没有 `data` 字段,载荷在 JSON 解码时就被丢了 → 补上 `json.RawMessage`。 +2. 应用层只留了 `Problem`(路径/行/列/文本),重建诊断时 `data` 已经不存在 → 在 `Doc` 上另存一份原始 `diags`。 + +传 `nil` 诊断时 gopls 只返回「源码」类通用动作(Organize Imports、Browse documentation 等), +**不会**返回当前报错的快速修复——这一点是实测确认的,不是推测。 + +### 30.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| gopls 链路 | `TestGoplsCodeActions`(等真实诊断 → 请求动作) | 返回多条动作,至少一条带 `edit` ✓ | +| UI 端到端 | 光标停在 `fmt.Println` 报错行 → `Alt+Enter` | 面板列出 **10 条**动作,首条是「Add import: "fmt"」(快速修复),分类标签显示「快速修复/源码/提取」✓ | +| 应用动作 | 回车执行首条 | 缓冲区插入 `import "fmt"`,标签出现未保存圆点,状态栏错误数 **1 → 0** ✓ | + +## 31. 文件/文件夹重命名与移动(2026-11-03) + +### 31.1 入口 + +文件树右键 → 重命名…(多选时不显示,一次只改一个)。 +输入框预填当前名字,**支持带目录**(`sub/name.go`)——一个输入框同时覆盖「改名」和「移动」,不单做移动。 + +### 31.2 落地 + +1. `os.Rename` 改磁盘。目标已存在时报错;只改大小写时先改到 `xxx.renaming` 再改回来(Windows 大小写不敏感)。 +2. `afterRename` 把内存里所有引用旧路径的地方搬过去: + - 已打开的文档:`stopWatch` → `DidClose(旧 uri)` → 改 `path`/`uri` → `lspOpen` → `startWatch`(缓冲区与撤销历史都保留) + - `a.active`、`a.open`(展开状态)、`a.sel`(多选)、`a.dirs`(目录缓存) + - 最后 `syncTitle` / `saveSession` / `refreshGit` + +路径重映射抽成 `remapPath`,**按分隔符判断前缀**:`a.go.bak` 不算 `a.go` 的子路径,`pkg2/` 不算 `pkg/` 的子目录——只看字符串前缀会误伤同名前缀的邻居。 + +### 31.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 路径重映射 | `TestRemapPath`、`TestRemapPathDir` | 精确路径换、同名前缀不换、目录内文件跟着搬、兄弟目录不动 ✓ | +| 文件改名 | 右键 old.go → 重命名 → new.go | 磁盘只剩 new.go;树与标签都变 new.go;代码内容与撤销历史保留;标签无脏标记 ✓ | +| 移动 | 改名输入 `sub/new.go` | 磁盘落到 sub/new.go,树里 new.go 进了 sub,标签保持可用 ✓ | +| 目录改名 | 右键 sub → pkg(其中 new.go 正打开着) | 磁盘变 pkg/new.go,树显示 pkg,已打开的文档被重映射、内容不丢 ✓ | + +### 31.4 已知小问题 + +标签页只显示文件名(不含目录),所以两个不同目录下的同名文件在标签上看起来一样。改名/移动本身不受影响。 + +## 32. 设置界面(2026-11-03) + +### 32.1 存什么 + +| 项 | 取值 | 默认 | +|---|---|---| +| 字号 | 12/13/14/15/16 | 13 | +| 行高 | 1.3/1.4/1.5/1.7 | 1.4 | +| 缩进宽度 | 2/4/8 | 4 | +| 缩进方式 | tab / 空格 | tab(Go 惯例) | +| 自动换行 | 开关 | 关 | +| 保存时格式化 | 开关 | 开 | +| 主题 | 深色/浅色 | 深色 | + +存 `%AppData%/mygoland/settings.json`——跨工作区,和会话语义不同(会话是「这个项目上次开了什么」,设置是「我这个人怎么用编辑器」)。 + +### 32.2 交互 + +文件 → 设置…(`Ctrl+,`)。弹窗里**改动即时预览**(所有已打开文档立刻重排), +「确定」才落盘,「取消」把预览改回去,「恢复默认」套默认值但不落盘。 + +每帧都会调 `applySettings` 做预览,所以它先跟 `applied` 比一次,没变直接返回——否则会变成每帧请求重绘的死循环。 + +### 32.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 默认值 | `TestSettingsDefaults` | 无配置文件时取默认 ✓ | +| 存取往返 | `TestSettingsRoundTrip` | 7 个字段全部一致 ✓ | +| 旧配置缺字段 | `TestSettingsPartialFile` | 只写了 fontSize,其余字段保留默认 ✓ | +| 配置文件损坏 | `TestSettingsBrokenFile` | 退回默认值并记日志,不崩 ✓ | +| UI 端到端 | 打开设置 → 选 15 号 → 确定 | `settings.json` 写入 fontSize=15,编辑器代码立刻变大、行号对齐 ✓ | +| 持久化 | 重启后截图与重启前**逐像素一致** | 字号设置在新进程里照样生效 ✓ | + +## 33. 断点管理(2026-11-03) + +### 33.1 模型 + +`bps` 从 `map[文件][]行号` 改成 `map[文件]map[行]breakpoint`,`breakpoint{Cond, Enabled}`。 +面板新增「断点」页签(索引 4),列出所有断点:勾选框控制启用、「条件」按钮开输入框、「删除」按钮移除,点行跳转。 + +- 禁用断点画成**灰色**标记,不发往调试适配器 +- 有条件的断点在列表里显示成 `当 i > 2` +- DAP 侧 `SetBreakpoints` 换成 `[]BreakpointSpec{Line, Condition}` + +### 33.2 会话兼容 + +断点在会话文件里从 `[3, 7]` 变成 `[{line, cond, enabled}]`。 +`bpJSON.UnmarshalJSON` 先试数字、再试对象,老会话照常读入(当作启用、无条件)。 + +### 33.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 增删 | `TestToggleBreakpoint` | 加→默认启用;再点→删除;空 map 条目一起清掉 ✓ | +| 条件与启用 | `TestBreakpointConditionAndEnable` | 条件/禁用都能设;对不存在的断点操作不 panic、不凭空创建 ✓ | +| 排序 | `TestAllBreakpointsSorted` | 按路径、行号排序 ✓ | +| 会话兼容 | `TestBPJSONBackCompat` | 旧数组格式解析成启用断点;新对象格式含条件 ✓ | +| **条件断点真调试** | `TestConditionalBreakpoint`(dlv) | 循环里设 `i == 3`,停下时栈顶第 8 行且变量 `i` 确实是 `3` ✓ | +| UI | 行号点一下 → 面板「断点」页 | 出现 `greeter/greeter.go 3`,勾选状态正确 ✓ | +| UI | 点「条件」输入 `i > 2` → 回车 | 行内出现 `当 i > 2`,会话文件写入 cond ✓ | +| UI | 取消勾选 | 勾选框清空、条件保留,会话里 `enabled:false` ✓ | + +## 34. 单实例与命令行打开(2026-11-03) + +### 34.1 没有用框架的实现 + +`mygo.App.RequestSingleInstanceLock` 在 Windows 上走的是 Unix socket,实测**不工作**: +第二个进程既没转发参数也没退出,两个进程都认为自己才是第一个(开了两个窗口)。 + +改成自己实现(`internal/app/single.go`):首个实例在 `127.0.0.1:<散列端口>` 上监听, +后来的实例连接、发一条 JSON(参数 + 工作目录)、收到 `ok` 后直接退出。 +握手这一步是必要的——端口可能被别的程序占着,收到非 `ok` 就换下一个端口,避免把参数发给陌生人。 + +### 34.2 命令行语义 + +| 参数 | 行为 | +|---|---| +| 无 | 打开上次的工作区 | +| 目录 | 打开该目录 | +| 文件 | 用它所在目录当工作区,并打开该文件 | + +第二个实例转发时:文件在当前工作区内 → 只激活该文件;不在 → 连工作区一起换过去。 + +### 34.3 顺带修的 bug + +切换工作区时没有清空断点表,旧项目的断点会残留(还会被写进新项目的会话文件)。 +现在 `setRoot` 里先清空,再由 `restoreSession` 装回该工作区自己的断点。 + +### 34.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 路径归属 | `TestWithin`、`TestWithinCaseInsensitive` | 子目录算在内、同前缀兄弟目录不算、大小写不敏感 ✓ | +| 转发并退出 | 已运行实例 + 启动第二个带文件参数 | 第二个进程 **206 ms 退出,退出码 0** ✓ | +| 同工作区 | 第二个实例传同项目文件 | 第一个实例把该文件切成当前标签 ✓ | +| 跨工作区 | 第二个实例传别的目录里的文件 | 窗口切到该项目(标题变 w2)、打开文件、gopls 重连 ✓ | +| 断点不串项目 | 切到新项目后看断点页 | 显示「还没有断点」而不是旧项目的断点 ✓ | + +## 35. 最近项目(2026-11-03) + +### 35.1 存储 + +`%AppData%/mygoland/recent.json`:`[{path, at}]`,最多 10 条,用**纳秒**时间戳排序(同一秒内连开两个项目也能排出先后)。 +读取时顺手过滤掉已不存在的目录——避免列表里全是灰链接。 + +### 35.2 入口 + +| 位置 | 行为 | +|---|---| +| 文件 → 最近项目…(`Ctrl+R`) | 命令面板列出历史项目,支持输入过滤,回车切换 | +| 欢迎页 | 无工作区时在「打开文件夹」下面列出,点击即开 | + +`setRoot` 成功切换后自动 `addRecent`,所以无论从菜单、命令行还是第二个实例切过来都会被记录。 + +### 35.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 排序与去重 | `TestRecentAddAndOrder` | 新开的排最前;重复打开不增条目只提前 ✓ | +| 过滤失效目录 | `TestRecentDropsMissing` | 目录删掉后不再列出 ✓ | +| 上限 | `TestRecentLimit` | 只保留 10 条 ✓ | +| UI:列表 | 文件 → 最近项目… | 两行(w3 / IdeTest),带完整路径,底部「2 项」✓ | +| UI:切换 | `Ctrl+N` 选第二项 + 回车 | 标题栏从 IdeTest 变成 w3,文件树跟着换 ✓ | +| UI:过滤 | 输入 `Ide` | 列表收敛到 1 项 ✓ | + +### 35.4 踩到的坑 + +给「最近项目」加输入过滤时,代码插错了位置——插进了 `activatePalette` 而不是 `refreshPalette`, +导致**回车先过滤再 return,永远走不到切换分支**。排查时靠临时日志才定位到(界面看起来毫无反应)。 +教训:命令面板这套多模式分支,新增模式时要确认代码落在「刷新」还是「执行」路径上。 + +## 36. 多运行配置(2026-11-03) + +### 36.1 数据 + +工作区配置文件从「一个对象」变成「一组配置 + 当前选中项」: + +```json +{"configs":[{"name":"默认","program":".","args":"","stopOnEntry":false}], "active":0} +``` + +老文件(单个 `{"program":...}`)在 `loadConfig` 里自动迁移成一条名为「默认」的配置,升级不丢设置。 + +### 36.2 界面 + +- 调试页顶部:`配置 [下拉] [编辑…]`,右侧显示当前配置的包与参数摘要 +- 运行 → 运行配置…:弹窗里用一排按钮切配置,编辑名称/包目录/参数/启动即停,支持新建、复制、删除 + +删除时**至少保留一条**(最后一条删掉会重置成默认),避免出现「没有任何配置可运行」的空状态。 +名称或包目录留空会在保存时补成「未命名」和「.」。 + +### 36.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 默认值 | `TestConfigDefaults` | 无文件时得到「默认 + .」✓ | +| 存取往返 | `TestConfigRoundTrip` | 两条配置 + 选中项完整读回 ✓ | +| 老格式迁移 | `TestConfigMigratesOldFormat` | 单对象迁移成一条并保留参数/启动即停 ✓ | +| 下标越界 | `TestConfigActiveOutOfRange` | 兜底到第一条,改动也落在第一条 ✓ | +| 空值补齐 | `TestConfigCommitFillsNames` | 名字补「未命名」、包补「.」,并落盘 ✓ | +| 删除 | `TestDeleteActiveConfig` | 删当前项后选中前移;最后一条重置为默认 ✓ | +| UI | 运行 → 运行配置… → 新建 → 改名「服务端」→ 保存 | 配置文件出现两条、`active:1` ✓ | +| UI | 调试页顶部 | 下拉框显示「服务端」,右侧「包 . · 参数 —」✓ | + +## 37. 面包屑(2026-11-03) + +### 37.1 形态 + +编辑器上方一行:`项目名 › 子目录 › 文件名`,11 号字、22 高。目录段可点,点了会在左侧文件树里 +**逐级展开到该目录并选中**(侧栏收着会先打开)。 + +### 37.2 两个实现要点 + +1. **项目名是独立一段,不能顶替第一层目录**。第一版把首段的文字换成了项目名,结果 + `greeter/greeter.go` 显示成「IdeTest › greeter.go」——中间那层被吃掉了。 +2. **纯 `ui.Text` 收不到点击**。第一版直接对 Text 调 `Clicked()`,点了没反应; + 改成 `ui.ButtonBase` 包一个 Text,才有 hover 背景和点击。 + +工作区外的文件(比如从最近项目直接打开的)只显示文件名,不硬拆绝对路径。 + +### 37.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 分段 | `TestCrumbSegments` | 目录+文件名两段,绝对路径逐级正确 ✓ | +| 根目录文件 | `TestCrumbSegmentsSameDir` | 只有一段 ✓ | +| 工作区外 | `TestCrumbSegmentsOutsideRoot` | 只回退成文件名 ✓ | +| 同前缀邻居目录 | `TestCrumbSegmentsSiblingPrefix` | 不被误判为工作区内 ✓ | +| UI:显示 | 打开 greeter/greeter.go | `IdeTest › greeter › greeter.go` ✓ | +| UI:点击 | 点「greeter」 | 树里该目录展开并高亮,子文件可见 ✓ | + +## 38. 全工作区诊断(2026-11-03) + +### 38.1 为什么不用语言服务器 + +LSP 没有「把整个项目的诊断给我」这种请求,gopls 只推已打开/已分析的文件。 +所以全工作区检查走 `go vet ./...`:一次覆盖整个模块,代价是编译期检查而非编辑器的实时分析。 +两者互补:打开的文件的实时诊断来自 gopls,没打开的文件的静态问题靠 vet 兜底。 + +### 38.2 实现 + +- `RunWorkspaceCheck()` 在工作区根跑 `go vet ./...`,`parseVetOutput` 解析 `path:line:col: message` +- 结果存 `wsState.items`,`allProblems()` 把它和 LSP 诊断合并 +- **去重**:同文件同行同文字只留一条,优先保留 LSP 那条(区间更准) +- 列表里 vet 条目带 `[vet]` 前缀,头部显示 `语言服务器 N · 工作区 M` +- vet 失败但解析不出问题(没装 go、模块坏了)时,把输出甩到运行面板并切过去,不静默失败 + +### 38.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 输出解析 | `TestParseVetOutput` | `# 包名` 之类噪声被跳过,相对路径拼成绝对路径 ✓ | +| 绝对路径 | `TestParseVetOutputAbsolute` | 原样保留 ✓ | +| 真实 vet | `TestWorkspaceCheckRealVet` | 真跑 `go vet`,行号 6、消息含 Printf ✓ | +| 去重 | `TestAllProblemsDedup` | 重复项保留 LSP 版本,vet 独有的保留 ✓ | +| UI | 未打开的文件有 vet 问题 | 头部 `语言服务器 1 · 工作区 1`,出现 `[vet] other.go:6 …` ✓ | +| UI | 同一问题两边都报 | 只显示一条,不重复堆叠 ✓ | + +### 38.4 两个踩坑 + +1. **空状态文字消失**:`ui.Column(c).Grow(1).Center()` 在面板里高度塌成 0,文字看不见。加 `FillHeight()` 才出来。 +2. **面板头部的按钮点不动**:`ui.Button` 在面板这层容器里收不到点击(弹窗里正常)。把入口挪到面板右上角的图标按钮区(`iconButton`,`ui.ButtonBase` 实现),才稳定可点。 + +### 38.5 已知限制 + +vet 只做静态检查,不含类型错误以外的语义分析;检查是**手动触发**的,不会随保存自动跑(避免每次保存都起一个 go 进程)。 + +## 39. 阶段一:折叠与查找替换(2026-11-03) + +### 39.1 折叠 + +编辑器本来就支持折叠(`Fold/FoldAll/UnfoldAll/ToggleFold`,靠缩进 + 括号匹配),只是没接命令。 +现在编辑菜单里有「折叠 / 展开」「全部折叠」「全部展开」,作用于光标所在块。 + +实测:`全部折叠` 能把 import 块和函数体收起,行号从 5 直接跳到 9、12 跳到 18,折叠处显示 `⋯`,gutter 有折角。 + +### 39.2 查找替换 + +编辑器自带 Zed 风格的查找条(`Find/FindReplace/FindNext/FindPrevious` + `DefaultFindBar`), +接上之后一应俱全:查询框、`Aa` 大小写、整词、`.*` 正则、选区搜索、`3 of 6` 计数、上下切换、替换行与「全部替换」。 + +打开时会用光标下的词/选区预填查询,和 Zed 一致。 + +### 39.3 快捷键为什么不放在菜单上 + +菜单的 `Accelerator` 走的是原生菜单层,自动化注入的按键到不了那里,**没法验证**。 +改成在编辑器 `OnInput` 里拦:`Ctrl+F` / `Ctrl+H` / `Ctrl+.` / `F3` / `Shift+F3`,菜单项标签里写提示。 + +踩了个坑:`OnInput` 里直接调 `State.Run` 会被编辑器按重入拒掉(内部有 retry),键盘和渲染帧里都不行。 +解法是**只记命令、下一帧在 UI 线程执行**(`pendingCmd` → `win.Update(func(){ st.Run(cmd) })`)。 +这条路径用菜单验证过:菜单同样走 `pendingCmd`,查找条正常弹出。 + +### 39.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 全部折叠 | 编辑 → 全部折叠 | 函数体收起,行号跳跃,`⋯` 标记 ✓ | +| 查找条 | 编辑 → 查找 | 查询框 + `Aa`/整词/正则/选区 + `3 of 6` 计数 + 上下箭头 ✓ | +| 替换条 | 编辑 → 替换 | 多出替换输入框与 `Replace`/`Replace All` ✓ | +| 命令延迟执行 | 菜单路径(与快捷键共用 `pendingCmd`) | 查找条正常弹出,说明延迟执行生效 ✓ | + +## 40. 内联提示(2026-11-03) + +### 40.1 两个必须做对的点 + +1. **initialize 要声明 `textDocument.inlayHint` 能力**。gopls 会看客户端能力决定要不要给提示, + 没声明时 `textDocument/inlayHint` 永远返回空数组——不报错、不提示,最难查的那种。 +2. **`workspace/configuration` 不能回 null**。我们原来给 gopls 回的是 `[null, null]`, + 等于「什么都不配」,而它默认不产出提示。现在回一份显式设置: + +```json +{"hints": {"parameterNames": true, "assignVariableTypes": true, + "compositeLiteralFields": true, "compositeLiteralTypes": true, + "functionTypeParameters": true, "rangeVariableTypes": true, + "constantValues": false, "unusedVariableNames": false}} +``` + +只写 `hints`:多加一个 `ui` 节点会被 gopls 判成「unexpected setting」,之后整份配置作废。 + +### 40.2 请求范围 + +gopls 会校验范围:列号超过行尾会报 `column is beyond end of file`,行号超范围报 `line number N out of range`。 +所以 `End` 用最后一行 + 该行实际长度(`endPosition`),不能图省事写个 `1<<20`。 + +### 40.3 刷新时机 + +| 时机 | 原因 | +|---|---| +| 打开文件后 | 首次 | +| 每次 DidChange 之后 | 类型/参数名可能变;延迟 350ms 合并连续输入 | +| 收到诊断之后 | 诊断到达说明这一轮分析完成 | +| 设置里开关切换 | 关掉要清空,打开要重来 | + +空结果会重试 3 次(1.5s / 3s / 4.5s)——包没分析完时 gopls 给的就是空数组,不能当成「没有提示」。 +用代数 `inlayGen` 丢弃过期结果:文档一改,在途的旧请求回来也不会覆盖。 + +### 40.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| gopls 真的给提示 | `TestGoplsInlayHints` | `a:` `b:` `int` 三条 ✓ | +| 界面渲染 | `total := add(1, 2)` | 显示成 `total int := add(a: 1, b: 2)` ✓ | +| 开关关掉 | 视图 → 切换内联提示 | 提示消失,回到 `total := add(1, 2)` ✓ | +| 旧配置默认开 | `TestSettingsInlayDefaultOn` | 没有该字段时按开处理 ✓ | +| 显式关掉记住 | `TestSettingsInlayExplicitOff` | `inlayHints:false` 生效 ✓ | + +## 41. 全局符号搜索(2026-11-03) + +### 41.1 接法 + +`workspace/symbol` → 填进已有的命令面板(新增 `pal.symbol` 模式),回车走 `openAtLine`。 + +- 入口:编辑 → 转到符号(`Ctrl+T`,在编辑器 `OnInput` 里拦) +- 输入停顿 180ms 才发请求,避免每敲一个字打一次 gopls +- 用 `pal.gen` 代数丢弃过期响应(连续输入时在途请求会乱序返回) + +### 41.2 必须过滤依赖包 + +gopls 的 `workspace/symbol` **会把依赖包一起返回**(空查询时最明显: +列出一堆 `FSCTL_*`、`testing.B.*`)。所以结果按 `within(a.root, path)` 过滤, +只留工作区内的符号——这才是 GoLand「转到符号」的语义。 + +### 41.3 行内布局 + +面板 `itemLine` 行是「小字 Label 在上、大字 Text 在下」,所以: + +``` +7 函数 · greeter/greeter.go + Greet +``` + +种类 + 相对路径放 Label,符号名放 Text,行号在最左边。 + +### 41.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| gopls 返回符号 | `TestGoplsWorkspaceSymbols` | 找到 `Twice` 且带位置 ✓ | +| 空查询 | 打开面板不输入 | 不再出现依赖包符号,提示「输入关键字搜索符号」✓ | +| 搜索 | 输入 `Greet` | 4 条:Greet / TestGreet / greeter.Twice / greeter.TestTwiceFails ✓ | +| 跳转 | 选中 Greet 回车 | 切到 greeter.go,光标落在第 7 行 `func Greet(...)` ✓ | + +## 42. 阶段一小结 + +| 项 | 状态 | 主要坑 | +|---|---|---| +| 折叠 | ✅ | 编辑器本就有,只差接命令 | +| 查找替换 | ✅ | `State.Run` 在按键/渲染期间会被拒(重入),要延后一帧 | +| 内联提示 | ✅ | initialize 能力声明 + `workspace/configuration` 给 `hints` 配置,否则静默返回空 | +| 全局符号 | ✅ | gopls 会把依赖包算进结果,要按工作区过滤 | + +## 43. 非 Go 文件:编码与大文件(2026-11-03) + +### 43.1 为什么先做这项 + +按实际使用确认:会在 MyGoland 里打开 `.sql` / `.ini` / `.log`,会遇到 GBK 文件。 +原来的实现是「非 UTF-8 直接拒绝 + 8 MB 上限」,等于把这批文件全部挡在门外。 + +### 43.2 编码识别与回写 + +识别顺序(`decodeFile`):**BOM → 合法 UTF-8 → GB18030**。 +前两步确定性;第三步是推测,只在不是 UTF-8 时走,因为中文 Windows 上的老配置和 SSMS 导出的脚本基本是这两种。 + +| 编码 | 判据 | 回写 | +|---|---|---| +| UTF-8 | 无 BOM 且 `utf8.Valid` | 原样 | +| UTF-8 BOM | `EF BB BF` | 保留 BOM | +| UTF-16 LE / BE | `FF FE` / `FE FF` | 补回 BOM | +| GBK | 非 UTF-8 且 GB18030 解码无替换字符 | 用 GB18030 编码回去 | + +编辑器内部一律 UTF-8,所以**读取解码、写回编码**,改完存回去老系统仍然读得懂。 + +### 43.3 大文件 + +上限从 8 MB 提到 **32 MB**,超过不再拒绝,而是**截断打开 + 只读**,状态栏标 `只读·已截断`。 +理由:看日志的场景里,「能看前 32 MB 且改不坏」比「完全打不开」有用。 +只读文档走 `writeDocFile` 会直接报错,避免把半截内容写回去覆盖原文件。 + +### 43.4 顺手修掉的 CRLF 问题 + +改造保存逻辑时绕过了 `Buffer.WriteTo`,而它内部会按 `LineEnding()` 写 CRLF。 +结果**保存一次就把整个文件的 CRLF 变成 LF**,在 git 里表现为整文件改动。 +现在按 `buf.LineEnding()` 显式还原:先归一成 `\n`,再按需要转回 `\r\n`。 + +### 43.5 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| UTF-8 / BOM / UTF-16LE / UTF-16BE / GBK 识别 | 5 个单测 | 全通过 ✓ | +| 五种编码往返 | `TestEncodeRoundTrip` | 编码标记与内容都一致 ✓ | +| GBK 里的 emoji | `TestEncodeGBKEmoji` | GB18030 能编码,往返不丢 ✓ | +| 保存保住编码 + CRLF | `TestWriteDocKeepsEncodingAndEOL` | 写回仍是 GBK 且含 `\r\n` ✓ | +| LF 文件不被改成 CRLF | `TestWriteDocLFStaysLF` | ✓ | +| 只读文档拒绝写入 | `TestReadOnlyDocRefusesSave` | 报错且原文件未变 ✓ | +| UI:GBK 配置 | 打开 `gbk.ini` | 中文正常,状态栏 `CRLF \| GBK \| TOML` ✓ | +| UI:SSMS 导出的 SQL | 打开 UTF-16LE `q.sql` | 中文与语法高亮正常,状态栏 `UTF-16 LE \| SQL` ✓ | +| UI:40 MB 日志 | 打开 `big.log` | 426147 行,状态栏 `只读·已截断` ✓ | + +## 44. 多终端会话(2026-11-03) + +### 44.1 结构 + +`a.term`(单个)换成 `a.terms []*termSession` + `a.termIdx`。 +每个会话持有独立的 shell 进程:一个跑着 `go test`,另一个照样能敲 git。 + +| 操作 | 入口 | +|---|---| +| 新建 | 终端工具条右上角「新建」图标,或菜单「新建终端(Ctrl+Shift+`)」 | +| 切换 | 点标签 `1 PS` / `2 CMD` | +| 关闭 | 工具条「关闭」图标(仅在多于一个时出现),或菜单「关闭当前终端」 | +| 换外壳 | 右侧 `PowerShell / Git Bash / CMD`,**只作用于当前会话**,切了就重启它 | + +### 44.2 踩到的坑:行内小按钮点不动 + +标签行里原本放 `1 PS × +` 三个紧邻的小按钮,结果**点 `+` 没反应**, +而日志显示 shell 确实起来过——说明按钮在,只是点击没落到它身上。 + +结论:同一行里相邻的小按钮点击区会互相覆盖,不稳定。 +改成「标签只负责切换,新建/关闭放到右上角 `iconButton` 区域」—— +那块区域在调试页/问题页已经验证过点击稳定。 + +### 44.3 会话存档 + +`session.json` 增加 `terms: [0,1,2]` 与 `termIdx`。 +恢复时只重建「有几个会话、各是什么外壳」,**不立刻启动进程**, +等切到终端页签再懒启动,避免开机就拉三个 shell。 + +### 44.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 标签名 | `TestTermLabel` | PS / Bash / CMD / 终端 ✓ | +| 关中间 | `TestCloseTermMiddle` | 剩 2 个,选中不变 ✓ | +| 关当前左边 | `TestCloseTermBeforeActive` | 选中左移,仍指向原会话 ✓ | +| 关当前且是最后一个 | `TestCloseTermActiveLast` | 回落到第一个 ✓ | +| 关到空 / 越界 | `TestCloseLastRemaining` / `TestCloseTermOutOfRange` | 清空归零 / 不 panic ✓ | +| 存档 | `TestTermShellsForSession` | 记录各会话外壳;无会话返回 nil ✓ | +| UI:新建 | 点右上「新建」 | 出现 `2 CMD` 并选中,新 shell 启动 ✓ | +| UI:切换 | 点 `1 CMD` | 高亮切换,各自进程独立 ✓ | +| UI:关闭 | 点右上「关闭」 | 剩 `1 CMD`,索引正确 ✓ | +| UI:换外壳 | 点 Git Bash / CMD | 当前会话就地重启为对应外壳 ✓ | + +## 45. 本地历史与崩溃恢复(2026-11-03) + +三件事共用一套快照存储:**保存后留点(本地历史)→ 停手后自动留点 → 崩溃后恢复**。 + +### 45.1 存储 + +``` +<配置目录>/mygoland/history/<路径散列>/ + <内容sha1>.snap 快照正文 + index.json [{time, hash, size, reason, dirty}] +``` + +- **文件名就是内容哈希**,所以同一内容天然去重:连按五次 Ctrl+S 也只留一条 +- 每个文件最多保留 60 条,超出按时间裁掉最老的,快照文件一并删除 +- 单条超过 4 MB 不存(避免把日志反复复制) + +### 45.2 三个触发时机 + +| 时机 | reason | 说明 | +|---|---|---| +| 保存成功后 | `save` | 后台写,不阻塞落盘的响应 | +| 编辑停手 4 秒且距上次留点 >1 分钟 | `auto` | 只写历史,**不动原文件** | +| 退出时仍有未保存改动 | `close` | 同时写 `pending.json` 供下次恢复 | + +自动快照刻意不自动改磁盘:自动保存原文件风险更大,崩溃兜底交给恢复机制。 + +### 45.3 本地历史面板 + +编辑 → 本地历史…,列出当前文件的快照(时间 / 原因 / 大小 / 是否当时未保存), +点一条即恢复。恢复走 `Buffer.Set` 而不是 `Reset`——见下。 + +### 45.4 三个必须做对的细节 + +1. **恢复要用 `Set` 不能用 `Reset`**。`Reset` 会把内容当成「已保存的文本」, + 用户关掉标签时不会提示,崩溃恢复的内容就悄悄没了。`Set` 是一次可撤销的编辑, + 标签会显示未保存圆点,用户能看到「这段还没存盘」。 +2. **弹窗不能在启动流程里弹**。`OpenFolder` 期间窗口还没就绪,模态框弹不出来也不报错; + 一开始改成首帧后弹,仍然失败(非 UI 线程调用 `Dialog.Message`)。 + 最终放弃询问,改成**直接恢复到缓冲区 + 运行面板写一行说明**——反正不写盘,用户不要就撤销。 +3. **路径必须规范化后比较**。命令行参数是正斜杠、历史/会话存档是反斜杠, + `find` 直接比字符串会开出两个同名标签。改成 `filepath.Clean` + 转小写后比较。 + +### 45.5 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 存档与读取 | `TestSnapshotAndList` | 两条按时间倒序,内容可读回 ✓ | +| 去重 | `TestSnapshotDedup` | 同内容连存 5 次只留 1 条 ✓ | +| 裁剪 | `TestSnapshotPrune` | 超出 60 条裁掉最老且删文件 ✓ | +| 超大不存 | `TestSnapshotTooLarge` | >4 MB 直接跳过 ✓ | +| 恢复标记 | `TestPendingRoundTrip` | 写/读/清空都对(还修了目录不存在导致写不进去的 bug)✓ | +| 换行一致 | `TestApplyEOL` | CRLF 快照还原成 CRLF ✓ | +| UI:保存留点 | 保存后看 history 目录 | index.json 出现 `save` 条目 + 快照文件 ✓ | +| UI:历史面板 | 编辑 → 本地历史 | 列出「今天 14:18:58 / 保存 / 1 KB」✓ | +| UI:崩溃恢复 | 手工造快照 + pending 后启动 | 内容进编辑器,标签显示未保存圆点 ✓ | +| UI:自动快照 | 恢复后停手 6 秒 | index 里出现 `auto / dirty=true` 条目 ✓ | + +## 46. 光标与滚动位置恢复(2026-11-03) + +### 46.1 存什么 + +`session.json` 增加 `cursors: {绝对路径: {line, column, scrollY}}`。 +不塞进 `tabs` 数组,避免破坏老存档格式(老的 `tabs: []string` 照常能读)。 + +只读截断的大文件不记录:那种文件的滚动位置没有意义。 + +### 46.2 什么时候套回去 + +打开文件时只把记录挂到 `pendingCursor` 上,**等编辑器排过版**(延迟 500ms)再应用: +滚动距离依赖内容高度,文件刚打开时高度还是 0,立刻设会被算成 0。 + +应用顺序也有讲究:`GoTo` 会把光标行滚到视口中间,所以先定位光标、再用 +`SetScrollY` 把滚动条拉回原位,否则滚动位置会被 `GoTo` 覆盖。 + +### 46.3 越界保护 + +存档里的行号列号可能超出当前文件(文件被删过几行): +行夹到 `LineCount()-1`,列夹到该行长度。 + +### 46.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 越界夹取 | `TestApplyPendingCursorClamps` | 行 99 / 列 999 被夹到最后一行行尾 ✓ | +| 正常恢复 | `TestApplyPendingCursorRestores` | 行 1 列 2 原样恢复 ✓ | +| 会话往返 | `TestSessionCursorRoundTrip` | 写进 session.json 再读回一致 ✓ | +| 截断文件跳过 | `TestSaveSessionSkipsTruncated` | 大文件不记录位置 ✓ | +| UI:真实重启 | 点到第 6 行 → 退出 → 重启 | 状态栏仍是「行 6, 列 1」✓ | + +## 47. 补漏批次小结 + +| # | 项 | 结果 | 主要坑 | +|---|---|---|---| +| 1 | 编码与大文件 | ✅ | 绕过 Buffer.WriteTo 导致 CRLF 被改成 LF | +| 2 | 多终端 | ✅ | 同一行相邻小按钮点击区互相覆盖 | +| 3 | 本地历史 / 自动快照 / 崩溃恢复 | ✅ | `Reset` 会把恢复内容当成已保存;启动阶段弹不出模态框;路径未规范化导致重复标签 | +| 4 | 光标与滚动恢复 | ✅ | 要等排版完成,且 GoTo 会覆盖滚动位置 | + +## 48. 阶段二-1:Git 差异视图(2026-11-03) + +### 48.1 数据从哪来 + +不用 `git diff` 的补丁文本,而是**两份完整文本**并排比: + +| 侧 | 来源 | +|---|---| +| 左(旧) | `git show HEAD:<相对路径>` | +| 右(新) | 已打开文档的**缓冲区**(所以未保存的改动也看得到),没打开就读磁盘 | + +这比 `git diff` 更有用:git 只认落盘内容,而写代码时最想看的恰恰是「我刚改的还没存的部分」。 +未跟踪文件取不到 HEAD 版本,旧侧当空文本处理。 + +差异计算交给编辑器的 `DiffView`,应用层不出手算 diff。 + +### 48.2 界面 + +差异视图占满编辑区:顶部一条标题栏(`差异 main.go`、说明、关闭按钮),下面是并排对比。 +打开入口:Git → 查看当前文件差异。 + +**切文件会自动关掉差异视图**——用户点别的文件说明他想回去看代码,不是想看 diff。 + +### 48.3 状态栏改动统计 + +`+7 −2` 这种摘要,数据来自 `git diff --numstat`。 + +关键:**不能在渲染里跑 git**。状态栏每帧都要画,一次 git 进程 30ms,等于每秒卡几十毫秒。 +所以改成 `refreshGit` 的后台协程里一次取全量 `--numstat` 存进 `gst.stats`,状态栏只查表。 + +### 48.4 一个框架坑 + +`DiffInlineWord` 模式下,右栏首行会多出几个字符(`package main` 渲染成 `golpackage main`)。 +换成 `DiffInlineWordAlt` 后正常,词级高亮效果一样。 + +### 48.5 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| HEAD 旧内容 | `TestShowFileAndNumstat` | 取回提交时的原文 ✓ | +| 行数增减 | 同上 | `+3 −0` 与实际改动一致 ✓ | +| 未跟踪文件 | `TestShowFileUntracked` | 取不到旧版本,交由调用方兜底 ✓ | +| UI:并排对比 | 改过的文件点「查看差异」 | 左删改、右新增,行号对齐、行内词级高亮 ✓ | +| UI:状态栏 | 打开改动文件 | 显示 `+7 −2` ✓ | +| UI:切文件 | 从差异视图点别的文件 | 自动回到代码视图 ✓ | + +## 49. 阶段二-2:测试结果树(2026-11-03) + +### 49.1 为什么用 `go test -json` + +文本输出的「通过/失败」只能靠前缀猜,子测试层级也还原不了。 +`-json` 每条事件都带 `Package / Test / Action / Elapsed / Output`: + +``` +run → pass/fail/skip 用 Test 字段定位节点 +TestSub/整数 用名字里的斜杠还原缩进层级 +output 挂到对应节点;没有 Test 就是包级输出 +``` + +面板新增「测试」页签,树长这样: + +``` +测试 3✗ +./... ✓2 ✗3 ○1 [全部测试] [当前包] +✗ testdemo 0.14s + ✓ TestAdd + ✗ TestFail + ○ TestSkip + ✗ TestSub + ✓ TestSub/整数 + ✗ TestSub/负数 +``` + +点某一条,失败输出直接内联在它下面(最多 6 行)。 + +### 49.2 布局踩的坑 + +一开始做成「上面树 + 下面固定高度输出区」,结果**两个区域争高度**: +树的内容一多就把输出区挤没,输出区一设 Grow 又把树压扁。 + +改成**输出内联在选中的行下面**,只有一个滚动容器,问题消失。 +教训:自定义面板里少用「两个都要自适应高度」的兄弟节点。 + +### 49.3 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| run→pass | `TestTestTreeBasic` | 自动建包节点,用例节点带状态与耗时 ✓ | +| 子测试层级 | `TestTestTreeSubtest` | `TestAdd/a` 缩进 2、`TestAdd/b/c` 缩进 3 ✓ | +| 输出归属 | `TestTestTreeOutput` | 用例输出挂用例、包输出挂包节点 ✓ | +| 统计与角标 | `TestTestCounts` | 只算用例不算包;有失败时页签显示 `测试 1✗` ✓ | +| 包模式换算 | `TestPackagePattern` | `D:\proj\a\b\c.go` → `./a/b`、根目录 → `.` ✓ | +| UI:真实运行 | 造了通过/失败/跳过/子测试的项目 | 树结构与 `-json` 事件一致,`✓2 ✗3 ○1` ✓ | +| UI:内联输出 | 点包节点 | 下面展开 `FAIL` 与耗时行 ✓ | + +## 50. 阶段二-3:覆盖率(2026-11-03) + +### 50.1 数据链路 + +`go test -coverprofile=<临时文件> ./...` → 解析 coverprofile → 三处呈现: + +``` +文件名:起始行.列,结束行.列 语句数 命中次数 +covdemo/calc.go:5.2,6.1 1 1 ← 命中 +covdemo/calc.go:10.2,11.1 1 0 ← 没命中 +``` + +| 呈现 | 内容 | +|---|---| +| 行底色 | 命中绿、没命中红(`LineBackgrounds`) | +| 状态栏 | 当前文件 `覆盖 33%` | +| 覆盖率面板 | 各包百分比,**按从低到高排**(最该补的在最上面),<50% 红、<80% 黄 | + +### 50.2 踩的坑:行底色被每帧擦掉 + +`decorate()` 每帧都在设 `d.st.LineBackgrounds`(原本只用于调试器停的那一行), +把覆盖率刚设好的颜色直接覆盖成空。表现是**状态栏有百分比、代码上却没颜色**。 + +修法:行底色改成「多来源合并」——`d.coverBG`(覆盖率,算一次缓存住) ++ 调试行,一起交给 `LineBackgrounds`。 + +教训:**框架里那些「每帧重设」的字段,任何新功能想往里塞东西都必须走同一个汇总点**, +否则会被静默覆盖。这类 bug 不会报错,只能靠肉眼发现。 + +### 50.3 路径匹配 + +coverprofile 里的路径是「模块名/包目录/文件名」,磁盘上是绝对路径。 +先按全路径小写比较,对不上再退一步按「包目录/文件名」后缀比—— +两条规则覆盖了模块内和 replace/绝对路径两种情况。 + +### 50.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 解析块 | `TestParseCoverProfile` | 2 块 4 语句命中 1 条 → 25% ✓ | +| 跳过 mode 行 | `TestParseCoverProfileSkipsMode` | 空结果 ✓ | +| 路径后缀匹配 | `TestCoverForSuffix` | 模块内路径能对上,同目录名不同不算 ✓ | +| 行底色生成 | `TestCoverBackgrounds` | 行号 0 起且命中/未命中都覆盖 ✓ | +| 状态栏摘要 | `TestCoverStatText` | `覆盖 25%`,无数据返回空 ✓ | +| UI:行着色 | 只有 Add 有测试的项目 | 函数体绿、Sub/Mul 红 ✓ | +| UI:面板列表 | 同上 | `覆盖率 33.3%` + `33% covdemo/calc.go`(红)✓ | +| UI:状态栏 | 同上 | `覆盖 33%` ✓ | + +## 51. 阶段二小结 + +| 项 | 结果 | 主要坑 | +|---|---|---| +| Git diff | ✅ | 右栏用缓冲区(未保存也能比);`DiffInlineWord` 渲染多字符;状态栏不能每帧跑 git | +| 测试结果树 | ✅ | 树和输出区争高度,最后改成内联输出 | +| 覆盖率 | ✅ | `decorate` 每帧覆盖行底色,必须走统一汇总点 | + +三项都属于「框架有现成能力,但接入时的隐含约定要摸清」—— +和阶段一那四个坑是同一类问题。 + +## 52. 右键历史入口(2026-11-03) + +### 52.1 两个新入口 + +文件树右键(文件或目录都支持): + +``` +新建文件 / 新建文件夹 +打开 / 重命名… +─── +Git 历史… 提交列表,点一条看它对这个文件的改动 +本地历史… 快照列表,点一条恢复到编辑器 +在资源管理器中打开 +``` + +**Git 历史**:`git log --max-count=50 --pretty=format:%h\x1f%an\x1f%ar\x1f%s -- `。 +用 `\x1f` 分隔字段——提交标题里什么字符都可能有,只有控制符不会出现。 +点某条提交 → `git show ^:` 与 `git show :` 两份文本喂给 diff 视图。 + +**本地历史**:目录模式会把目录下所有文件的快照按时间合并。 +`history/` 是按文件路径散列的,没法从目录名反推,所以遍历每个 `index.json` 读里面记的 `path` 来筛。 + +### 52.2 点击穿透 + +点「提交」想打开 diff,结果毫无反应。原因是同一帧里弹窗刚关,点击继续落在下面, +触发 `OpenFile` → 而它会把差异视图关掉。 + +修法:`time.AfterFunc(10ms, …)` 推迟一帧再开。**不能用嵌套 `win.Update`**—— +Update 回调里的 Update 会被合并掉,等于没推迟。 + +### 52.3 自动化实例的单实例问题 + +用户开着 MyGoland.exe 时,测试用的 e2e.exe 一启动就被单实例逻辑把参数转发走、自己退出, +automation socket 建不起来。 +修法:`ClaimSingleInstance` 里判断 `MYGO_AUTOMATION`,设置时直接返回 true 不参与单实例。 + +### 52.4 验证 + +| 项 | 方法 | 结果 | +|---|---|---| +| 提交历史解析 | `TestLogEntries` | 3 条提交、倒序、作者/时间/hash 齐全 ✓ | +| 版本内容 | 同上 | `hash^` 取到 v2、`hash` 取到 v3 ✓ | +| 目录历史 | `TestLogDir` | 目录路径能取到提交 ✓ | +| UI:右键菜单 | 右键 main.go | 出现「Git 历史…」「本地历史…」✓ | +| UI:Git 弹窗 | 点开 | `go.mod · 1 条提交` + `4e71a91 加 go.mod 测试 3 minutes ago` ✓ | + +## 53. 全局搜索的匹配选项(2026-11-03) + +搜索面板新增三个开关:`Aa`(区分大小写)、`.*`(正则)、`ab`(整词),默认全关。 + +实现只有一个函数 `buildMatcher`:非正则时先 `regexp.QuoteMeta` 转义,整词外面套 `\b(?:…)\b`, +不区分大小写时加 `(?i)` 前缀。 + +**中文的坑**:Go 的 `\b` 按 ASCII 判词边界,中文字符不算 word char, +所以 `\b过磅\b` 匹配不到「过磅记录」。修法:只有查询**首尾都是 ASCII 词字符**时才套 `\b`, +中文查询退回普通包含——这正好也符合直觉。 + +| 项 | 方法 | 结果 | +|---|---|---| +| 默认不区分大小写 | `TestMatchPlainIgnoreCase` | ✓ | +| 区分大小写 | `TestMatchCaseSensitive` | ✓ | +| 整词 | `TestMatchWholeWord` | `main` 不匹配 `mainLoop` ✓ | +| 正则 | `TestMatchRegex` | ✓ | +| 不开正则时按字面 | `TestMatchRegexLiteralWhenOff` | `a+b` 不匹配 `aaab` ✓ | +| 非法正则 | `TestMatchBadRegex` | 返回错误不崩 ✓ | +| 中文整词 | `TestMatchChineseWholeWord` | 退化为包含,能匹配 ✓ | + +## 54. 收尾状态 + +| 项 | 状态 | +|---|---| +| 右键 Git 历史 / 本地历史(文件 + 目录) | ✅ | +| 全局搜索正则 / 大小写 / 整词 | ✅ | +| 点击失败用例跳源码 | ❌ 未做 | +| 行号旁「运行这个用例」(gopls code lens) | ❌ 未做 | + +## 55. 历史视图重做:列表 + 并排对比(2026-11-03) + +### 55.1 从弹窗改成全屏视图 + +第一版做成 Modal 弹窗,两个问题: + +1. **Modal 里的点击完全不响应**——列表行点不动,连底部 `ui.Button` 也点不动。 + 用无障碍元素树确认过按钮位置没错(`button press,focus 915,456 关闭`),点下去就是没反应。 +2. 弹窗宽度有限,塞不下并排对比。 + +改成**占满编辑区的全屏视图**:左边列表(340px)+ 右边 `DiffView`,同屏可见。 + +``` +[Git 历史] main.go [关闭(Esc)] +2 条提交 310ada2 ↔ 当前 · 第一版:打印 v1 左:历史 右:当前 +┌ 第二版:改了输出 │ 3 import "fmt" │ 3 import "fmt" +│ 02387ff 曹港回 … │ 5 func main() { │ 5 func main() { +│▍第一版:打印 v1 │ - 6 println("v1") │ + 6 // 改过输出 +└ │ 7 } │ + 7 println("v2 …") +``` + +### 55.2 对比方向改了 + +原来是「父提交 ↔ 该提交」(看这一版改了什么),现在改成「**该提交 ↔ 当前代码**」。 + +理由:翻历史时真正想知道的是「跟现在差在哪」,中间那些逐次改动意义有限。 +本地历史同理:单击 = 看差异,「恢复」变成独立按钮——不知道差什么就点恢复,等于赌博。 + +右栏一律用**编辑器缓冲区**,所以未保存的改动也一起比。 + +### 55.3 顺手做的工具:tools/tree + +反复靠肉眼估坐标点按钮,效率极低且经常点错(有几次点到最大化按钮上)。 +新增 `tools/tree`:连 automation socket 发 `tree` 请求,打印无障碍元素的 +`角色 / 动作 / 中心坐标 / 尺寸 / 标签`,按关键词过滤。 + +``` +$ tree 关闭 +button press,focus 915,456 0x0 关闭 +``` + +从此点击可以精确命中,不用猜。 + +### 55.4 验证 + +| 项 | 结果 | +|---|---| +| Git 历史视图 | `[Git 历史] main.go` + 2 条提交,默认选中最新 ✓ | +| 选「第一版」 | 左栏红色删行 `println("v1")`、右栏绿色新增两行 ✓ | +| 自动折叠未改动行 | `2 unmodified lines` ✓ | +| 本地历史视图 | `[本地历史] main.go` + `1 条快照` + 「恢复这条」按钮 ✓ | +| 无差异时 | 两栏内容相同,不画改动标记 ✓ | + +## 56. 面向「主要写 Go」的差距评估(2026-11-03) + +**先核对代码,不按想象列清单。** 已有:gopls 诊断/补全/悬停/跳转定义/引用/重命名/ +代码动作/内联提示/符号大纲/格式化(`lsp.go`、`action.go`、`symbols.go`)、 +Delve DAP 断点+单步+递归变量树+表达式求值(`debug.go`)、`go vet` 全工作区检查 +(`wscheck.go`)、构建/运行/测试结果树/覆盖率(`output.go`、`testrun.go`、`coverage.go`)、 +Git diff 与两种历史的全屏对比。 + +**结论**:骨架不缺,缺的是「编辑 → 跑单测 → 调试」这个每天循环几十次的闭环的 +最后一公里,以及 Go 特有的工程化(模块、包路径、并发调试)。 + +### 56.1 P0:每天都会卡 + +| 差距 | 代码依据 | 为什么 Go 特别痛 | 落点 | +|---|---|---|---| +| 保存不自动整理 import | `writeDoc` 只走 LSP formatting(等价 gofmt);`source.organizeImports` 只能手动 Alt+Enter,且 `action.go` 的 range 固定单行 | Go 加一个包就要补/删 import,是最高频动作,不自动就每次手动 | 保存钩子 + `workspace/executeCommand` | +| 测试闭环三件套 | 第 54 节两个 ❌(失败跳源码、code lens);`RunTestTree` 只有全量/当前包 | Go 表驱动 + 子测试,改一行只想重跑一个 `-run '^TestX/sub$'` | `testrun.go` 解析 output 里的 `file:line`;`lsp/client.go` 加 `textDocument/codeLens` | +| 缺 `-race` / `-bench` / 测试调试 | `testrun.go` 命令固定 | 并发与性能是 Go 的常规工作流,不是加分项 | 运行菜单 + `runConfig` 扩展 | +| 调试缺 goroutine 列表 / 条件断点 / attach | 9.5 已记;10.2 只补了变量递归和求值 | 只看当前线程栈,并发程序等于没法调 | `dap/client.go` + `debug.go` | + +### 56.2 P1:一周撞上几次 + +| 差距 | 代码依据 | 说明 | +|---|---|---| +| `go.mod` / `go.work` / 多模块 | `fileicons.go` 只认文件名;`startLSP(root)` 只接一个根 | 多项目并行时没法一个窗口开多个模块;无 tidy/依赖升级/漏洞提示 | +| 移动目录不改包路径 | `fileops.go` 的重命名只动磁盘路径 | Go 里移动包 = 编译直接失败,必须同步改 `package` 声明与所有 import | +| 静态检查只有 `go vet` | `wscheck.go` | staticcheck / golangci-lint 是事实标配,问题面板缺可扩展的检查来源 | +| gopls source action 入口窄 | `action.go` 请求范围只有光标行 | 「实现接口」「填充 struct」「生成测试」「补 struct tag」需要文件级/选区级动作 | +| build tags / 交叉编译 | 运行配置只有 `Program/Args/StopOnEntry` | 无 `GOOS/GOARCH` 切换,Win7 工控机这类部署目标不方便 | + +### 56.3 P2 与不做的事 + +- P2:覆盖率增量(只高亮本次 diff 的行)、pprof / benchstat 结果可视化、 + gopls 崩溃自动重启、文件树全量监听(14.4 现在只监听已打开文件)。 +- **AI 协作(阶段三)排在这些之后**:真要做,只做「基于 LSP 上下文的窄任务」 + (按诊断给修复、给当前函数生成表驱动测试、写 doc comment),不做大而全聊天框。 +- 不建议自己做:多光标 / IME / 超大文件(等上游 `mygo/ui/editor`)、插件系统、 + Go 版本管理器。 + +### 56.4 建议顺序 + +1. 保存自动整理 import(成本最低、频次最高) +2. 测试闭环三件套(单测精确 run + 失败跳源码 + code lens) +3. `go.mod` / 多模块感知 +4. goroutine 列表 + 条件断点 + +理由:前两项直接压缩每天的重复操作,后两项才轮到「调得动复杂程序」和「开得了真实工程」。 + +### 56.5 补充核对:通用完整度与稳健性(2026-11-04) + +**纠正**:56.1 把「条件断点」列进缺口是错的——第 33 节已实现条件 + 启停, +且有真 dlv 验证(`i == 3` 停在栈顶、变量值正确)。调试真正缺的是 +goroutine 列表、attach/远程调试、日志断点、持久 watch。 + +**新核对的缺口**(对照代码与第 28/14/31/26 节): + +| 维度 | 缺口 | 依据 | +|---|---|---| +| Git | 只到「看得见 + 提交」:无 pull/push/fetch、无分支切换/新建、无 stash;提交固定 `git add -A`,不能选择性暂存 | 28.1 明确第一版范围;`git.go` 只有 Stage | +| 搜索 | 全局搜索只能搜不能替换;无「替换预览 + 全部替换」 | `grep.go` 只建索引,`palette.go` 只出命中列表 | +| 导航 | 无书签、无 TODO/FIXME 扫描面板、无最近文件 Ctrl+E | 8.4 已列 | +| 冲突 | 外部改动冲突只能「保留我的改动」,无三方合并 | 14.4 | +| 弹窗 | Modal 点击不响应是框架级坑;历史视图绕开了,设置/运行配置弹窗仍基于 Modal,交互一复杂就会踩 | 55.1 | +| 细节 | 同名文件标签区分不开;运行参数 `strings.Fields` 切分,带空格参数传不了 | 31.4、10.3 | +| 历史 | 快照上限 4MB,超大文件不进本地历史 | 47 | + +**稳健性**:gopls 崩溃无监控自愈;文件树不监听外部增删;内存主项 gopls 不受控(第 6/7 节)。 +**工程质量**:逻辑层单测覆盖好,UI 层只有 `tools/tree` 基建、没有脚本化 e2e 回归用例;无 CI。 + +**合并后的优先级 Top 5**: +1. 保存自动整理 import +2. 测试闭环三件套 +3. Git pull/push + 选择性暂存(协作刚需,成本低) +4. 全局搜索替换(预览 + 确认) +5. go.mod/多模块 + goroutine 列表 + +## 57. 阶段三-1:保存时整理 import(2026-11-04) + +### 57.1 怎么接 gopls + +gopls 的整理能力挂在 **`source.organizeImports` 代码动作**上,不走 executeCommand—— +命令形态要靠 `workspace/applyEdit` 回推改动,而客户端没有这个 handler,改动会凭空落空。 + +`internal/lsp/client.go` 新增 `OrganizeImports(uri)`: + +- codeAction 请求带 `only: ["source.organizeImports"]`,**不带诊断**——补缺/删无用 + 不依赖某条诊断(`CodeActions` 那条链必须原样带回诊断,这里正好相反)。 +- range 给零值,source 动作不看 range。 +- 只收本文件的 edit;顺手过滤 kind 前缀,防止服务端塞进别的动作。 + +### 57.2 顺序是硬约束 + +`saveDoc` 现在是两次往返:**整理 → 落缓冲区 → 显式 `lspSync` → 格式化 → 写盘**。 + +- `applyEdits` 只改缓冲区、**不推 didChange**(`lspSync` 只挂在输入钩子上), + 整理结果落地后必须手动同步一次,否则格式化按旧文本算坐标,改动会砸错位置。 +- 两道版本守卫:整理应用前要求 `buf.Version()` 等于发请求时的版本 + (用户又打字就放弃这次整理);格式化应用前要求等于整理后的版本。 +- goroutine 与 UI 线程用 buffered channel 交接版本号,串起两步。 + +### 57.3 坑:gopls 给的是 delta 碎片 + +第一版测试断言直接拼接各 edit 的 `NewText`,得到 `"srings"`—— +gopls 对 import 行给的是**增量编辑**(`8..10 → "s"` + 位置 11 插入 `"rings"`), +碎片拼不出最终文本。必须真正按位置从后往前应用后校验。 +新增测试助手 `applyTextEdits`,断言改成「最终文本含 `"strings"` 且无 `"fmt"`」。 + +### 57.4 设置 + +`OrganizeImports` 默认**开**(补缺/删无用是确定性改动,没有猜测成分), +设置界面「保存时」组新增复选框「保存时整理 import(补缺失 / 删无用)」。 + +### 57.5 验证 + +| 项 | 结果 | +|---|---| +| `TestGoplsOrganizeImports`(真 gopls:fmt 引了没用 + strings 用了没引) | 最终文本为 `import "strings"`、无 `"fmt"` ✓ | +| `go test ./...`(app/dap/git/lsp/task) | 全绿 ✓ | +| `go build -ldflags "-H windowsgui"` | BUILD_OK ✓ | +| UI 侧 | 复选框进设置弹窗,逻辑链路与格式化共用(保存即触发),无新界面需要截图验证 | + +## 58. 阶段三-2:测试闭环三件套(2026-11-04) + +### 58.1 失败用例跳源码 + +- 数据来源:`go test -json` 的 output 行(` main_test.go:12: boom`), + `fail` 事件落地时从**该节点自己的输出**里解析第一个 `file:line:`。 +- 正则坑:Windows 绝对路径带盘符,`[^:\s]+` 会在 `D:` 的冒号处截断—— + 改成 `(?:[A-Za-z]:)?[^:\s]+\.go` 把盘符消化在可选前缀里。 +- 相对名还原成磁盘路径:go test 输出只给包内相对名,按 + 「go.mod 的 module 前缀 + import 路径」从工作区根拼出来(`modulePrefix` 缓存), + 拼出来不存在再退到文件索引按 base 名找。 +- UI:选中失败节点时内联出「跳到 xxx_test.go:12」按钮,`openAt` 直达。 + +### 58.2 `-run` 精确运行 + +- `runFilterFor("TestAdd/b/c")` → `^TestAdd$/^b$/^c$`:整段锚定、子测试按 `/` + 分段各锚一次,`QuoteMeta` 处理子测试名里的空格和方括号。 +- 用真 go test 验证过语义:精确命中单个用例;无匹配子测试时不跑任何用例。 +- 入口:运行菜单「运行光标处的测试」+ 测试树选中项的「重跑这个用例」。 + 光标定位走**本地正则**(`testFuncAt`)——不走 gopls,没保存的新函数也能跑; + 光标停在收尾 `}` 上仍算函数内(与主流 IDE 一致),函数间空行不算。 + +### 58.3 行号旁的「能跑」标记(code lens 的替代) + +编辑器框架没有 code lens 表面(`State` 只有 `GutterMarks`/`LineBackgrounds`/`SetInlays`), +且原生 ContextMenu 在 Windows 上样式不受控(见 16/popup 的教训),所以: + +- `decorate()` 里给测试函数行画**青色 GutterMark**;同一行有断点时断点让位 + (红实点叠青点看不清)。行号缓存挂 `Doc.testFuncs`,按 `buf.Version()` 失效。 +- 点击行号仍然是断点(不改语义);跑测试走菜单或测试树按钮。 + +### 58.4 重构与验证 + +- `RunTestTree` 拆出 `startTest(args...)`,`runOneTest` 复用同一套面板/读取协程。 +- 新增 `testlens.go`(纯函数层)+ `testlens_test.go` 9 个单测 + + `TestTestTreeFailLocation` 全链路(事件流 → 解析 → 还原路径 → 节点)。 +- `go test ./...` 全绿;windowsgui 构建通过。 + +## 59. 阶段三-3:Git 拉取/推送 + 选择性暂存(2026-11-04) + +### 59.1 pull / push + +- `git.Pull` 用 **`--ff-only`**:分叉时直接失败、把 git 的提示原样带回输出面板, + 一键操作绝不偷偷造 merge commit——宁可让用户去命令行处理分叉。 +- `git.Push` 遇到「no upstream」自动补一次 `push -u origin <当前分支>`, + 这是新仓库第一次推送的固定动作。 +- 网络命令有风险:git 执行全部改成 `CommandContext` + **2 分钟超时**(`runOut`), + 输出改为 stdout+stderr 合并——git 的进度和报错大多走 stderr,只接 stdout 会拿到空。 +- 入口:Git 菜单「拉取(pull)」「推送(push)」,结果写输出面板,完成后自动 `refreshGit`。 + +### 59.2 选择性暂存(提交弹窗重做) + +- 原来的提交是 `git add -A` 一把梭——无关改动全带上,这是最危险的那个默认行为。 +- 现在:弹窗列出全部改动文件(相对路径排序),**默认全选**,可单独取消; + 「全选 / 全不选」快捷按钮;头部显示「勾选 n / N」;只对勾选的执行 + `git add -- `(`StagePaths`),未勾选的保持脏。 +- 一个都不勾就点提交:**不关弹窗**,弹提醒——空勾选多半是手滑。 +- 删除的文件 `git add` 同样记录删除(集成测试覆盖了「改两个提交一个 + 删除提交」)。 +- 即时模式小坑:`ui.Checkbox(c, &a.commitSel[p], …)` 编译不过——map 索引表达式 + 取不了地址,用局部变量中转、帧末写回。 + +### 59.3 验证 + +| 项 | 结果 | +|---|---| +| `TestStagePathsSelective`(真仓库:只提交勾选的 + 空清单安全 + 删除文件提交) | ✓ | +| `go test ./...` 全绿 | ✓ | +| windowsgui 构建 | BUILD_OK ✓ | + +## 60. 阶段三-4:全局搜索替换(2026-11-04) + +### 60.1 交互:预览 → 确认,两步走 + +全局搜索面板(Ctrl+Shift+F)新增「替换为 ___ [预览替换]」行: + +- **预览**:后台算计划(搜索本身是去抖异步的,替换计划也走协程), + 回来后候选列表整个换成确认视图——`N 处 / M 个文件` + 每文件处数清单 + + 「确认替换 / 取消」。 +- 查询或匹配开关一变,refreshPalette 就把预览态作废退回搜索—— + 预览永远对应当前规则,不会拿旧计划替换新查询。 +- 确认后面板关闭,结果(含失败清单)写输出面板,自动 refreshGit。 + +### 60.2 文本来源的两条规则(最容易做错的点) + +| 文件状态 | 替换落点 | +|---|---| +| 打开中 | **缓冲区**(未保存的改动也算),一步撤销 + `lspSync`;绝不直接写盘——否则一保存就把替换盖掉了 | +| 没打开 | 读盘 → `decodeFile` → 替换 → 按原编码 `encodeFile` 写回(GBK 配置改完还是 GBK) | + +### 60.3 实现要点与坑 + +- `buildMatcher` 抽成 `buildReplaceRe`(返回 `*regexp.Regexp`)共用; + 搜索的文件枚举抽成 `workspaceFiles()`,计划与搜索同一份清单。 +- **`$1` 展开为空的坑**:`FindAllStringIndex` 只有整匹配位置、没有分组, + `ExpandString` 把 `$1` 展开成空串——必须用 `FindAllStringSubmatchIndex`。 +- 替换按行走:搜索语义就是按行(`^ $` 锚在行上),替换不同语义就成了 + 「搜得到换不掉」。逐行 `Split("\n")` 也让 CRLF 天然保留。 +- 预览上限 400 个文件,超出会列出并提示「未列出的也会一起替换」。 +- `ui.Checkbox` 之外又一个即时模式细节:Modal 里的 Scroll + 按钮组合沿用了 + 设置/提交弹窗的成熟模式。 + +### 60.4 验证 + +| 项 | 结果 | +|---|---| +| `replace_test.go` 11 个单测(字面/正则分组/整词/大小写/空替换/CRLF/无匹配/非法正则/跨行) | ✓ | +| `TestApplyReplacePlan`(真目录:UTF-8 写回 + GBK 编码保持 + 打开文件只改缓冲区且不动盘) | ✓ | +| `go test ./...` 全绿;windowsgui 构建 | ✓ | + +## 61. 阶段三-5:goroutine 列表 + LSP 健壮性 + go 工具入口(2026-11-04) + +Top 5 的最后一项,拆成三块小而完整的: + +### 61.1 调试:goroutine 列表 + +- `dap.Client.Threads()`:dlv dap 把 goroutine 当线程列(`threads` 请求)。 +- 停点时 `refreshDebugLocation` 顺手拉一次(运行中拉没意义),存 `s.threads`。 +- 调试面板在调用栈和变量之间插入「goroutine(N,点一条切换)」: + 当前条青色高亮,点击 `debugSwitchThread` → 换 `s.thread`、清旧展开状态、 + 重拉调用栈/变量/停点位置。上限显示 100 条,超出给计数。 +- 「stopped」事件照旧把当前条重置为事件里的 threadId——每次新停点从 + 肇事 goroutine 看起,行为可预期。 + +### 61.2 LSP 健壮性:崩溃自动重启 + 手动重启 + +- `lsp.Options.OnExit`:`cmd.Wait` 返回后回调(手动 Close 也会触发)。 +- App 侧用 **代数(lspGen)区分「退出的是不是当前这代」**:手动重启会先置 + `a.lsp=nil` 再 Close,旧代的 OnExit 回来时代数对不上,直接忽略—— + 否则会把刚拉起的新 gopls 误杀。 +- 自动重启带 **10 秒冷却**:go.mod 坏了「起一次崩一次」的场合不进无限循环, + 状态栏提示改手动。重启前 `resetDocsForLSP` 清 `opened/sent`,重连后重新 + didOpen(不清的话 gopls 换了连接还以为文档已同步,诊断就断了)。 +- 菜单「运行 → 重启语言服务器」:改完 go.mod、gopls 卡死时用。 + +### 61.3 go 工具入口 + +「运行 → 整理模块依赖(go mod tidy)」,复用 `startTask`,输出进运行面板; +tidy 完 gopls 自己会跟上,不用重启。 + +### 61.4 验证 + +| 项 | 结果 | +|---|---| +| `TestThreadsGoroutines`(真 dlv:3 worker 并发,停在断点,threads 非空、编号唯一且含当前) | ✓ | +| `go vet` 三个包干净;`go test ./...` 全绿;windowsgui 构建 | ✓ | +| UI 侧 | goroutine 区块复用调试面板现有滚动列表模式,无新弹窗 | + + + + + + diff --git a/docs/plans/2026-10-29-terminal.md b/docs/plans/2026-10-29-terminal.md new file mode 100644 index 0000000..826aec4 --- /dev/null +++ b/docs/plans/2026-10-29-terminal.md @@ -0,0 +1,51 @@ +# 终端面板(2026-10-29) + +## 1. 方案 + +用 mygo 官方 `plugins/terminal`(Ghostty 的 VT 模拟器 libghostty-vt),底部面板新增第 4 个页签「终端」, +`Alt+F12` 打开。外壳可切换:PowerShell / Git Bash / CMD。 + +| 外壳 | 查找顺序 | +|---|---| +| PowerShell | `pwsh.exe`(7.x)→ `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe` | +| Git Bash | `%ProgramFiles%`、`%ProgramFiles(x86)%`、`%LOCALAPPDATA%` 下的 `Git\bin\bash.exe` → PATH 里的 `bash.exe` | +| CMD | `%ComSpec%` → `cmd.exe` | + +- 工作目录 = 当前工作区根。 +- 切换外壳会重启终端;切换工作区会重置终端,下次显示时落到新目录。 +- 用 `ui.Segmented` 选外壳,右侧有「重启」按钮。 + +## 2. 关键坑:原生库 + +`terminal.New` 会 `Load()` 一个原生库 libghostty-vt(Windows 侧文件名 `ghostty-vt.dll`,2.07 MB)。 +加载顺序:`$MYGO_GHOSTTY_VT` → 应用资源目录 → **exe 同目录** → 用户缓存。 + +本机实测:直连 GitHub Releases 下载 **120 秒超时**(国内网络)。解决方式: + +1. 通过镜像 `https://ghfast.top/<原始地址>` 下载; +2. 校验 SHA-256 与 `plugins/terminal/mygo-plugin.json` 声明一致 + (windows-amd64:`53e8e2dd…65da41`); +3. 放 `resources/ghostty-vt.dll`,`build.cmd` 构建后自动复制到 exe 同目录。 + +因为 exe 同目录优先级高于缓存,程序不会再尝试联网下载。 + +## 3. 验证 + +| 项目 | 方法 | 结果 | +|---|---|---| +| 外壳检测 | `TestDetectShells` | 三个外壳都找到(本机为系统自带 5.1 版 + Git Bash 在 Program Files) | +| 终端真能跑 | `TestTerminalRunsCommand` | `cmd /c echo` 0.6 s 内出现在 `History()` | +| 端到端 | 启动应用并自动切到终端页签 | 日志 `terminal started: PowerShell`,外壳子进程存在 | +| 退出清理 | 强制结束应用后查进程 | 外壳进程随之消失,无残留 | + +## 4. 已知限制 + +- 终端配色独立于编辑器主题,还没做同步(插件支持 `UseTheme`)。 +- 单终端,没有分屏或多终端标签。 +- 原生库缺失时给出下载指引而不是崩溃,但分发时仍需把 DLL 一起带上。 +- 体积:exe 从 12.0 MB 增至 14.9 MB(终端插件),另需附带 2.07 MB DLL。 + +## 5. 给部署方的说明 + +把 `MyGoland.exe` 和 `ghostty-vt.dll` 放在同一目录即可。若 DLL 缺失,程序不会崩溃: +终端页签会显示提示,包含下载地址与两种修复方式(同目录放 DLL,或设置 `MYGO_GHOSTTY_VT`)。 diff --git a/docs/tab-context-menu-1.png b/docs/tab-context-menu-1.png new file mode 100644 index 0000000..1a88a5d Binary files /dev/null and b/docs/tab-context-menu-1.png differ diff --git a/docs/tab-context-menu-2.png b/docs/tab-context-menu-2.png new file mode 100644 index 0000000..e9ae049 Binary files /dev/null and b/docs/tab-context-menu-2.png differ diff --git a/docs/theme-hamburger-menu.png b/docs/theme-hamburger-menu.png new file mode 100644 index 0000000..76583e7 Binary files /dev/null and b/docs/theme-hamburger-menu.png differ diff --git a/docs/theme-islands-onedark-vivid.png b/docs/theme-islands-onedark-vivid.png new file mode 100644 index 0000000..77b47e2 Binary files /dev/null and b/docs/theme-islands-onedark-vivid.png differ diff --git a/docs/theme-light.png b/docs/theme-light.png new file mode 100644 index 0000000..70af592 Binary files /dev/null and b/docs/theme-light.png differ diff --git a/docs/theme-minimap-short.png b/docs/theme-minimap-short.png new file mode 100644 index 0000000..d1401e1 Binary files /dev/null and b/docs/theme-minimap-short.png differ diff --git a/docs/theme-minimap.png b/docs/theme-minimap.png new file mode 100644 index 0000000..7d2aa7b Binary files /dev/null and b/docs/theme-minimap.png differ diff --git a/docs/theme-titlebar-hamburger.png b/docs/theme-titlebar-hamburger.png new file mode 100644 index 0000000..64ab91a Binary files /dev/null and b/docs/theme-titlebar-hamburger.png differ diff --git a/docs/theme-titlebar-menu-open.png b/docs/theme-titlebar-menu-open.png new file mode 100644 index 0000000..947ffbb Binary files /dev/null and b/docs/theme-titlebar-menu-open.png differ diff --git a/docs/theme-titlebar-menu.png b/docs/theme-titlebar-menu.png new file mode 100644 index 0000000..a7f285b Binary files /dev/null and b/docs/theme-titlebar-menu.png differ diff --git a/docs/theme-titlebar.png b/docs/theme-titlebar.png new file mode 100644 index 0000000..c5ed46b Binary files /dev/null and b/docs/theme-titlebar.png differ diff --git a/docs/tree-context-menu.png b/docs/tree-context-menu.png new file mode 100644 index 0000000..3e2d7bf Binary files /dev/null and b/docs/tree-context-menu.png differ diff --git a/docs/tree-multi-select.png b/docs/tree-multi-select.png new file mode 100644 index 0000000..1db3cf5 Binary files /dev/null and b/docs/tree-multi-select.png differ diff --git a/ghostty-vt.dll b/ghostty-vt.dll new file mode 100644 index 0000000..2e009a0 Binary files /dev/null and b/ghostty-vt.dll differ diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..75062a1 --- /dev/null +++ b/go.mod @@ -0,0 +1,15 @@ +module mygoland + +go 1.27.3 + +require ( + github.com/egoist/mygo v0.7.2 + golang.org/x/text v0.43.0 +) + +require ( + github.com/ebitengine/purego v0.11.1 // indirect + github.com/go-text/typesetting v0.3.5 // indirect + golang.org/x/image v0.46.0 // indirect + golang.org/x/net v0.59.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5b3e0f6 --- /dev/null +++ b/go.sum @@ -0,0 +1,14 @@ +github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0= +github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/egoist/mygo v0.7.2 h1:ITbzb9+u8GXjDZFkHsnIiBRayV7WQPFzM3whsIOm7F8= +github.com/egoist/mygo v0.7.2/go.mod h1:dVav53PwF2xEotjf4oA5lTY2Jp2exgzyjLhbSXhbMwE= +github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk= +github.com/go-text/typesetting v0.3.5/go.mod h1:XZO1hD+nQVyvVa5IicQk7FsCa4PFQaJ2soWAP1f//68= +github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc h1:8FGo2It5K75XkavhTiCKExUfVaVDS1feBnLCru5qeoY= +github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o= +golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= +golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= +golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= +golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= diff --git a/internal/app/about.go b/internal/app/about.go new file mode 100644 index 0000000..1b5e9c8 --- /dev/null +++ b/internal/app/about.go @@ -0,0 +1,57 @@ +package app + +import ( + "fmt" + "runtime" + + "github.com/egoist/mygo" + "github.com/egoist/mygo/ui" +) + +// About 打开「关于」窗口;已经开着就提到前面,不重复创建。 +func (a *App) About() { + if a.aboutWin != nil { + a.aboutWin.Show() + a.aboutWin.Focus() + return + } + w := mygo.NewWindow(mygo.WindowOptions{ + Title: "关于 MyGoland", + Width: 400, + Height: 380, + // 关于窗口是固定尺寸的说明页:不能拉伸、不需要最小化和最大化, + // 只留右上角一个关闭按钮。 + DisableResize: true, + DisableMinimize: true, + DisableMaximize: true, + // 菜单栏默认收起(按 Alt 才会露面):应用级菜单会下发到每个窗口, + // 关于窗口只该有一块内容,不该跑出一排「文件 编辑 运行…」。 + AutoHideMenuBar: true, + Content: ui.View(a.aboutView), + }) + if err := w.SetIcon(iconPNG); err != nil { + logf("关于窗口设置图标失败: %v", err) + } + w.Show() + // 再给一个空菜单,把继承来的应用级菜单顶掉。SetMenu(nil) 在这条路径上 + // 会被应用菜单盖回来,空菜单对象才稳。 + w.SetMenu(mygo.NewMenu(nil)) + a.aboutWin = w +} + +// aboutView 是「关于」窗口的内容:标识、名称、版本与运行环境。 +func (a *App) aboutView(c *ui.Context) { + c.SetTheme(a.th) + t := c.Theme() + ui.Column(c).Fill().Center().Gap(6).Padding(28).Children(func() { + logoCard(c, 92) + ui.Box(c).Height(8) + ui.Text(c, "MyGoland").FontSize(24).Bold().TextColor(t.Text) + ui.Text(c, "轻量 Go IDE · mygo + Go").FontSize(12).TextColor(t.TextMuted) + ui.Box(c).Height(10) + ui.Text(c, "版本 "+Version).FontSize(11).TextColor(t.TextMuted) + ui.Text(c, fmt.Sprintf("%s / %s", runtime.GOOS, runtime.GOARCH)). + FontSize(11).TextColor(t.TextMuted) + ui.Text(c, runtime.Version()).FontSize(11).TextColor(t.TextMuted) + }) +} diff --git a/internal/app/action.go b/internal/app/action.go new file mode 100644 index 0000000..70b063b --- /dev/null +++ b/internal/app/action.go @@ -0,0 +1,122 @@ +package app + +import ( + "context" + "strings" + "time" + + "mygoland/internal/lsp" +) + +// CodeActions 请求光标所在行的代码动作并列进命令面板。 +func (a *App) CodeActions() { + d := a.doc() + c := a.lsp + if d == nil || c == nil || !lsp.IsGoFile(d.path) { + a.alert("代码动作", "先把光标放到 Go 文件里") + return + } + pos := d.st.CursorPos() + line := d.buf.Line(pos.Line) + col := pos.Col + if col > len(line) { + col = len(line) + } + rng := lsp.Range{ + Start: lsp.Position{Line: pos.Line, Character: 0}, + End: lsp.Position{Line: pos.Line, Character: lsp.UTF16Len(line)}, + } + + // 把这一行的诊断**原样**带上:gopls 的「添加 import」「删除未使用变量」 + // 这类快速修复靠诊断里的 data 字段匹配,重新拼一份就没用了。 + var diags []lsp.Diagnostic + for _, dd := range d.diags { + if dd.Range.Start.Line <= pos.Line && pos.Line <= dd.Range.End.Line { + diags = append(diags, dd) + } + } + + uri := d.uri + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + acts, err := c.CodeActions(ctx, uri, rng, diags) + if err != nil { + a.win.Update(func() { a.alert("代码动作失败", err.Error()) }) + return + } + if len(acts) == 0 { + a.win.Update(func() { a.alert("代码动作", "这里没有可用的动作") }) + return + } + items := make([]paletteItem, 0, len(acts)) + for i, act := range acts { + items = append(items, paletteItem{ + Kind: itemFile, + Label: act.Title, + Hint: actionKindLabel(act.Kind), + Idx: i, + }) + } + a.win.Update(func() { + a.actions = acts + a.pal = paletteState{open: true, action: true, refsAll: items, items: items} + a.win.Update(func() {}) + }) + }() +} + +// actionKindLabel 把 LSP 的 kind 翻成给人看的分类。 +func actionKindLabel(kind string) string { + switch { + case strings.HasPrefix(kind, "quickfix"): + return "快速修复" + case strings.HasPrefix(kind, "refactor.extract"): + return "提取" + case strings.HasPrefix(kind, "refactor.inline"): + return "内联" + case strings.HasPrefix(kind, "refactor.rewrite"): + return "重写" + case strings.HasPrefix(kind, "refactor"): + return "重构" + case strings.HasPrefix(kind, "source"): + return "源码" + } + return "" +} + +// applyAction 执行选中的代码动作。 +func (a *App) applyAction(i int) { + if i < 0 || i >= len(a.actions) { + return + } + act := a.actions[i] + // 自带改动的,直接落到缓冲区。 + if act.Edit != nil { + changes := act.Edit.ByFile() + if len(changes) > 0 { + a.applyWorkspaceEdits(changes) + return + } + } + // 只有命令的,交给服务端执行,完成后重新同步一遍。 + if act.Command != nil { + c := a.lsp + if c == nil { + return + } + cmd := *act.Command + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + if err := c.ExecuteCommand(ctx, cmd); err != nil { + a.win.Update(func() { a.alert("执行命令失败", err.Error()) }) + return + } + // gopls 的命令(如整理 import)会通过 workspace/applyEdit 回推改动, + // 这里稍等一拍让改动落地。 + time.Sleep(200 * time.Millisecond) + a.win.Update(func() { a.win.Update(func() {}) }) + }() + } +} diff --git a/internal/app/app.go b/internal/app/app.go new file mode 100644 index 0000000..cb15383 --- /dev/null +++ b/internal/app/app.go @@ -0,0 +1,914 @@ +package app + +import ( + "context" + "fmt" + "io" + "io/fs" + "log" + "os" + "path/filepath" + "sort" + "strings" + "time" + "unicode" + + "github.com/egoist/mygo" + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" + + // 框架自带控件(右键菜单、查找栏、对话框按钮等)的简体中文文案。 + _ "github.com/egoist/mygo/locales/zh-Hans" + + "mygoland/internal/lsp" + "mygoland/internal/task" +) + +// maxFileSize 是编辑器单文件读入的上限。 +// 超过这个大小不会拒绝打开,而是截断到这么多并标成只读—— +// 看日志的场景里,「能看前 32 MB」比「完全打不开」有用得多。 +const maxFileSize = 32 << 20 + +// logf 是内部日志,输出到标准错误。 +func logf(format string, args ...any) { log.Printf(format, args...) } + +// Doc 是一个打开的文件:路径、缓冲区与编辑器状态。 +type Doc struct { + path string + uri string + buf *editor.Buffer + st *editor.State + + // prev 是最近一次同步给语言服务器的文本,sent 是它对应的版本号。 + prev editor.Snapshot + sent uint64 + // inlayGen 是内联提示的代数,用来丢弃过期的请求结果。 + inlayGen int + // enc 是这个文件在磁盘上的编码,保存时按它写回。 + enc fileEncoding + // truncated 表示打开时因为文件太大被截断(只读)。 + truncated bool + // coverBG 是这个文件的覆盖率行底色,decorate 每帧要用。 + coverBG []editor.LineBackground + // 本地历史的计时:上次看到改动的时刻、当时的版本号、上次留点的时刻。 + dirtyAt int64 + dirtyVer uint64 + lastSnapAt int64 + opened bool + + // problems 是这份文件当前的诊断,供「问题」面板列出。 + problems []Problem + // diags 是服务端推来的原始诊断(含 data),请求代码动作时要原样带回去。 + diags []lsp.Diagnostic + + // watch 监听文件在编辑器外的改动,nil 表示未监听。 + watch *docWatch + + // testVer/testFuncs 缓存「哪些行是 Test/Benchmark/Fuzz 函数」,给行号旁 + // 的青点用;缓冲区一变(版本号变了)下一帧重扫。零值表示还没扫过。 + testVer uint64 + testFuncs map[int]string +} + +// App 保存整个 IDE 的状态,跨帧存活。 +type App struct { + win *mygo.Window + // root 是当前工作区根目录,空表示未打开。 + root string + // sidebar 是侧边栏宽度,由 Split 的分隔条拖动改变。 + sidebar float32 + // docs 是打开的文件,active 是当前文件路径。 + docs []*Doc + active string + // open 保存文件树的展开状态,dirs 缓存目录内容。 + open map[string]*bool + dirs map[string][]fs.DirEntry + + // modName/modRoot 缓存工作区 go.mod 的 module 名,把测试失败输出里的 + // 相对文件名还原成磁盘路径时要用;root 变了会重读。 + modName string + modRoot string + + // lsp 是语言服务器连接,lspState 用于状态栏显示。 + // lspGen 每次拉起 gopls 递增,用来识别「退出的是当前这代」; + // lspLastStart 给意外退出的自动重启做冷却。 + lsp *lsp.Client + lspState string + lspGen int + lspLastStart time.Time + + // panel 是底部输出面板,panelH 是它的高度。 + panel bool + panelH float32 + out []OutLine + outSel int + // run 是正在执行的命令,running 表示有任务在跑。 + run *task.Task + running bool + outState ui.ListState + + // dbg 是调试会话,bps 是按文件记录的断点行(1 起),cfg 是运行/调试配置。 + dbg *debugSession + bps map[string]map[int]breakpoint + cfgs configsFile + cfgDlg runConfigDialogState + + // panelKind 是左侧工具窗当前显示哪个(0 项目 / 1 大纲), + // outline 是当前文件的符号,outlinePath/outlineVer 记录它对应哪个版本。 + panelKind int + outline []outlineItem + outlinePath string + outlineVer uint64 + outlineAt time.Time + selectedOutline int + + // splitDrag 是分隔条的拖拽位移;splitBase/splitHeld 记录本次拖动的起点与状态。 + splitDrag *ui.Point + splitBase float32 + splitHeld bool + + // terms 是打开的终端会话(可以有多个),termIdx 是当前显示的那个; + // shells 是可选外壳,shellIdx 是新会话默认用的外壳。 + terms []*termSession + termIdx int + shells []shellChoice + shellIdx int + + // allowExit 表示退出已确认;exitPending 表示确认流程正在进行。 + allowExit bool + exitPending bool + + // restoring 表示正在恢复会话,期间不写回,避免半截状态覆盖存档。 + restoring bool + + // pal 是命令面板状态,index 是工作区文件索引(快速打开与搜索共用)。 + pal paletteState + index indexState + // ren 是重命名弹窗状态。 + ren renameState + // actions 是当前可用的代码动作,与命令面板里的 idx 对应。 + actions []lsp.CodeAction + // renEntry 是文件/文件夹重命名弹窗的状态。 + renEntry renameEntryState + // bpDlg 是条件断点弹窗的状态。 + bpDlg bpDialogState + // recent 是「最近项目」面板里的条目。 + recent []recentItem + // wsState 是全工作区检查(go vet)的结果。 + wsState wsCheckState + // diff 是差异视图的状态。 + diff diffView + // test 是测试结果树的状态。 + test testState + // cover 是覆盖率的状态。 + cover coverState + // histView 是全屏历史视图(git / 本地共用)。 + histView historyViewState + // pendingRestore 是待询问恢复的未保存快照,restoreAsked 保证只问一次。 + pendingRestore []pendingSnap + restoreAsked bool + // pendingCursor 是等编辑器排完版再套用的光标/滚动位置。 + pendingCursor []cursorRestore + // pendingCmd 是待执行的编辑器命令:按键处理期间不能直接 Run,下一帧再跑。 + pendingCmd editor.Command + // set 是当前生效的设置,setDlg 是弹窗里的草稿,applied 是最近一次套用的值。 + set settings + setDlg settings + applied settings + setOpen bool + // wantFocus 表示下一帧要把焦点交回编辑器(弹窗/面板关闭后)。 + wantFocus bool + + // gst 是 git 快照;commitOpen/commitMsg 是提交弹窗的状态。 + // commitFiles 是弹窗里的文件清单(仓库相对路径,正斜杠,有序), + // commitSel 是勾选状态(只提交勾选的),commitCode 是各自的状态码。 + gst gitState + commitOpen bool + commitDlg bool + commitMsg string + commitFiles []string + commitSel map[string]bool + commitCode map[string]string + + // th 是自定配色;sidebarOn 控制左侧工具窗;panelTab 是底部面板的页签。 + th *ui.Theme + sidebarOn bool + panelTab int + probSel int + probState ui.ListState + + // aboutWin 是「关于」窗口,复用同一个,避免反复点击开出一堆。 + aboutWin *mygo.Window + + // minimapOn 控制编辑器右侧的代码缩略图。 + minimapOn bool + + // lastSize 是上一帧的画布尺寸,用来识别最大化/还原这类整窗跳变。 + lastSize [2]float32 + + // light 表示当前用浅色主题;默认深色。 + light bool + + // menuCache 缓存主菜单的顶层项,标题栏每帧都要用,不能每帧重建。 + menuCache []*mygo.MenuItem + + // menuOpen 表示标题栏当前处于「菜单形态」;menuPopup 表示有下拉正在显示。 + // 收起只由「在菜单以外按下」触发,不受鼠标移动影响。 + menuOpen bool + menuPopup bool + + // 自绘弹出菜单的当前状态。 + popOpen bool + popJustOpened bool // 打开的那一帧,遮罩的点击判定要跳过 + popEntries []menuEntry + popRect ui.Rect // 锚点的矩形(上一帧的 Bounds),面板据此定位 + + // sel 是文件树里选中的路径集合,selAnchor 是 Shift 连选的基准项。 + sel map[string]bool + selAnchor string + + // revealPath 是「定位当前文件」后在树里高亮的那一行; + // revealPending 表示还欠一次滚动到该行(只滚一次,之后用户可自由滚动)。 + revealPath string + revealPending bool + + // 新建文件/文件夹的弹窗状态。 + newOpen bool + newName string + newIsDir bool + newDir string + newExample bool // 新建 .go 时是否生成示例代码 + // newOpenDlg 是传给 ui.Modal 的稳定指针:Modal 靠这个指针做元素复用, + // 传局部变量的地址会让 overlay 每帧重建、位置乱掉。每次渲染前重置为 + // true,于是「点遮罩关闭」只会让它当帧变 false,下一帧又恢复。 + newOpenDlg bool + + // menuHits 是这一帧菜单项按钮的位置,点击时用它判断点中了哪一项。 + // 标题栏整体是 DragWindow,按钮自己的 Clicked 收不到事件, + // 只能靠 PointerPosition 的命中来判断。 + menuHits []menuHit +} + +// New 创建一个未打开工作区的应用。 +func New() *App { + a := &App{ + sidebar: 250, + sidebarOn: true, + minimapOn: true, + panelH: 220, + panelTab: 0, + outSel: -1, + probSel: -1, + th: theme(false), + open: map[string]*bool{}, + dirs: map[string][]fs.DirEntry{}, + bps: map[string]map[int]breakpoint{}, + cfgs: configsFile{Configs: []runConfig{defaultConfig()}}, + } + a.outState.FollowEnd = true + + // 设置是跨工作区的,构造时就装好,新文档直接按它排版。 + a.set = loadSettings() + a.applied = a.set + if a.set.Light { + a.light = true + a.th = theme(true) + } + a.outState.Selected = &a.outSel + a.probState.Selected = &a.probSel + // 想直接以浅色启动时设 MYGOLAND_LIGHT=1,省得每次点菜单。 + if os.Getenv("MYGOLAND_LIGHT") == "1" { + a.light = true + a.th = theme(true) + } + return a +} + +// Start 建立窗口与菜单,必须在主线程调用。 +func (a *App) Start() { + // 界面语言固定为简体中文:框架控件的文案由 locales/zh-Hans 提供, + // 应用自己的字符串本来就写的中文。 + mygo.App.SetLocale("zh-Hans") + + a.win = mygo.NewWindow(mygo.WindowOptions{ + Title: "MyGoland", + Width: 1320, + Height: 860, + MinWidth: 720, + MinHeight: 480, + // 隐藏系统标题栏,由页面自己画一条与主题同色的标题栏。 + // TitleBarHeight 决定顶部可拖动、双击最大化的高度。 + TitleBarStyle: mygo.TitleBarHidden, + TitleBarHeight: titleBarHeight, + Content: ui.View(a.view), + }) + // 让后端画的窗口按钮跟随深色主题,否则浅色按钮在深色标题栏上很扎眼。 + if a.light { + a.win.SetWindowButtonsTheme(mygo.ThemeLight) + } else { + a.win.SetWindowButtonsTheme(mygo.ThemeDark) + } + // 标题栏与任务栏用带齿轮的标识,没有它 Windows 会显示默认空白图标。 + if err := a.win.SetIcon(iconPNG); err != nil { + logf("设置窗口图标失败: %v", err) + } + a.win.Show() + mygo.App.SetMenu(a.Menu()) + mygo.App.OnWillQuit(func(*mygo.QuitEvent) { a.Close() }) + a.win.OnClose(a.guardClose) + mygo.App.OnBeforeQuit(a.guardQuit) + + // 后来启动的实例会把参数转进来。 + a.watchSecondInstance() + a.openFromArgs(os.Args[1:]) +} + +// Close 释放语言服务器,退出时调用。 +func (a *App) Close() { + a.saveSession() + // 退出前给未保存的文档留快照并记下恢复标记; + // 崩溃时这一步走不到,靠定时的自动快照兜底。 + a.snapshotDirtyOnExit() + for _, s := range a.terms { + if s.t != nil { + _ = s.t.Close() + } + } + if a.dbg != nil { + a.StopDebug() + } + if a.run != nil { + a.run.Stop() + } + if a.lsp != nil { + _ = a.lsp.Close() + a.lsp = nil + } +} + +// doc 返回当前文件,没有则为 nil。 +func (a *App) doc() *Doc { + for _, d := range a.docs { + if d.path == a.active { + return d + } + } + return nil +} + +func (a *App) find(path string) *Doc { + // 同一个文件可能从不同来源进来:命令行参数是正斜杠, + // 本地历史/会话存档里是反斜杠,必须按规范化路径比,否则会开出两个标签。 + want := samePathKey(path) + for _, d := range a.docs { + if samePathKey(d.path) == want { + return d + } + } + return nil +} + +// samePathKey 用于比较两个路径是不是同一个文件。 +func samePathKey(p string) string { + return strings.ToLower(filepath.Clean(p)) +} + +// OpenFolderDialog 让用户选择一个目录作为工作区。 +func (a *App) OpenFolderDialog() { + if a.win == nil { + return + } + paths, err := mygo.Dialog.Open(mygo.OpenDialogOptions{ + Parent: a.win, + Title: "打开文件夹", + ButtonLabel: "打开", + Directory: true, + ShowHiddenFiles: true, + }) + if err != nil || len(paths) == 0 { + return + } + a.OpenFolder(paths[0]) +} + +// OpenFolder 把 dir 设为工作区,清空已打开的文件。 +func (a *App) OpenFolder(dir string) { + abs, err := filepath.Abs(dir) + if err != nil { + abs = dir + } + info, err := os.Stat(abs) + if err != nil || !info.IsDir() { + a.alert("无法打开文件夹", fmt.Sprintf("%s 不是一个有效目录", abs)) + return + } + a.win.Update(func() { a.switchRoot(abs) }) +} + +// setRoot 只改状态,必须在主线程调用。 +func (a *App) setRoot(abs string) { + // 切走之前先把当前工作区的界面状态存下来。 + a.saveSession() + if a.lsp != nil { + c := a.lsp + a.lsp = nil + go func() { _ = c.Close() }() + } + a.root = abs + a.docs = nil + a.active = "" + // 断点是按工作区存的,换项目时先清空,restoreSession 会装回该项目的。 + a.bps = map[string]map[int]breakpoint{} + a.open = map[string]*bool{} + a.dirs = map[string][]fs.DirEntry{} + a.syncTitle() + a.loadConfig() + a.resetTerminal() + a.resetIndex(abs) + a.buildIndex(abs) + a.gst = gitState{} + a.refreshGit() + a.startLSP(abs) + // 恢复这个工作区上次的标签、断点、面板与主题。 + a.restoreSession(abs) + // 上次异常退出留下的未保存内容:先记下来,等界面就绪再问。 + a.collectPending() + // 光标与滚动位置要等编辑器排过版才有意义,放到第一帧之后再套。 + if len(a.pendingCursor) > 0 { + time.AfterFunc(500*time.Millisecond, a.applyPendingCursor) + } + // 记进最近项目。 + addRecent(abs) +} + +// OpenFile 在编辑器中打开一个文件,已打开则切换过去。 +func (a *App) OpenFile(path string) { + // 差异视图是全屏的,用户点别的文件说明他想回去看代码。 + a.diff.open = false + abs, err := filepath.Abs(path) + if err != nil { + abs = path + } + a.win.Update(func() { + if _, err := a.loadDoc(abs); err != nil { + a.alert("打开失败", err.Error()) + } + }) +} + +// loadDoc 读取并打开文件,必须在主线程调用。 +func (a *App) loadDoc(abs string) (*Doc, error) { + if d := a.find(abs); d != nil { + a.active = d.path + a.syncTitle() + return d, nil + } + info, err := os.Stat(abs) + if err != nil { + return nil, err + } + if info.IsDir() { + return nil, fmt.Errorf("%s 是一个目录", abs) + } + readOnly := false + if info.Size() > maxFileSize { + // 超大文件不直接拒绝:截一段能看就行,标成只读以免误改后写回半截。 + readOnly = true + logf("打开超大文件(%d 字节),只读并截断:%s", info.Size(), abs) + } + f, err := os.Open(abs) + if err != nil { + return nil, err + } + data, err := io.ReadAll(io.LimitReader(f, maxFileSize)) + f.Close() + if err != nil { + return nil, err + } + text, enc, ok := decodeFile(data) + if !ok { + return nil, fmt.Errorf("无法识别该文件的编码(试过 UTF-8 / UTF-16 / GBK)") + } + d := a.newDoc(abs, text) + d.enc = enc + if readOnly { + d.st.ReadOnly = true + d.truncated = info.Size() > maxFileSize + } + a.docs = append(a.docs, d) + a.active = abs + a.syncTitle() + // 已经统计过覆盖率的话,新打开的文件也要立刻上色。 + if len(a.cover.files) > 0 { + d.coverBG = a.coverBackgrounds(d) + } + a.lspOpen(d) + a.startWatch(d) + a.saveSession() + return d, nil +} + +// newDoc 建立文档的缓冲区与编辑器状态。 +func (a *App) newDoc(abs, text string) *Doc { + d := &Doc{path: abs, uri: lsp.PathToURI(abs)} + d.buf = editor.NewBuffer(text) + d.buf.SetLanguage(editor.LanguageFor(filepath.Base(abs))) + font, lh, tab, indent, wrap := a.editorSettings() + d.st = &editor.State{ + Buffer: d.buf, + WrapGuides: []int{120}, + Theme: codeTheme(a.light), + Font: font, + LineHeight: lh, + TabSize: tab, + Indent: indent, + SoftWrap: wrap, + } + d.st.OnCompletion = func(r editor.CompletionRequest) { a.complete(d, r) } + d.st.OnHover = func(r editor.HoverRequest) { a.hover(d, r) } + d.st.OnDefinition = func(off int) { a.definition(d, off) } + // 编辑器级的快捷键在这里拦。OnInput 在编辑器处理之前收到按键, + // 返回 true 表示已消费。 + // + // 为什么不用菜单 Accelerator:那是原生菜单层的快捷键,行为依赖平台; + // 而这里拦下来是确定的,也能用自动化按键验证。 + d.st.OnInput = func(ev ui.InputEvent) bool { + if ev.Kind != ui.InputKeyDown { + return false + } + switch { + case ev.Mods == ui.Alt && ev.Key == ui.KeyEnter: + a.CodeActions() + return true + // 命令不能在这里直接跑:按键派发过程中调 Run 会被编辑器当重入拒掉, + // 记下来交给下一帧(见 editorArea 里的消费点)。 + case ev.Mods == ui.Ctrl && ev.Key == ui.KeyF: + a.pendingCmd = editor.Find + return true + case ev.Mods == ui.Ctrl && ev.Key == ui.KeyH: + a.pendingCmd = editor.FindReplace + return true + case ev.Mods == ui.Ctrl && ev.Key == ui.KeyPeriod: + a.pendingCmd = editor.ToggleFold + return true + case ev.Mods == ui.Shift && ev.Key == ui.KeyF3: + a.pendingCmd = editor.FindPrevious + return true + case ev.Mods == 0 && ev.Key == ui.KeyF3: + a.pendingCmd = editor.FindNext + return true + case ev.Mods == ui.Ctrl|ui.Shift && ev.Key == ui.KeyBackquote: + a.ToggleTerminal() + a.newTerm() + return true + case ev.Mods == ui.Ctrl && ev.Key == ui.KeyT: + // 转到符号是全工作区动作,不经过编辑器命令。 + a.OpenSymbols() + return true + } + return false + } + d.st.OnGutterClick = func(line int) { a.ToggleBreakpoint(d.path, line) } + return d +} + +// Save 保存当前文件。 +func (a *App) Save() { + if d := a.doc(); d != nil { + a.saveDoc(d) + } +} + +// SaveAll 保存所有已修改的文件。 +func (a *App) SaveAll() { + for _, d := range a.docs { + if d.buf.Modified() { + a.saveDoc(d) + } + } +} + +// saveDoc 保存前先让 gopls 整理 import、再格式化(只对 Go 文件),然后写盘。 +// 两步是两次独立往返,顺序不能反:整理改的是 import 块,格式化要在整理过 +// 的文本上重新算坐标。applyEdits 只改缓冲区、不推 didChange,所以整理结果 +// 落地后要显式 lspSync 一次,服务端才有新文本。 +func (a *App) saveDoc(d *Doc) { + c := a.lsp + if c == nil || !d.opened || !lsp.IsGoFile(d.path) || + (!a.set.OrganizeImports && !a.set.FormatOnSave) { + a.writeDoc(d) + return + } + uri, path, version := d.uri, d.path, d.buf.Version() + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + + // 1) 整理 import:补缺失的、删没用的、按 gofmt 分组。 + cur := version + if a.set.OrganizeImports { + orgEdits, err := c.OrganizeImports(ctx, uri) + if err != nil { + logf("整理 import 失败: %v", err) + } else if len(orgEdits) > 0 { + applied := make(chan uint64, 1) + a.win.Update(func() { + t := a.find(path) + if t == nil { + applied <- 0 // 文档已被关掉,没东西可存了 + return + } + // 请求期间用户又打了字就放弃这次整理,别把改动错位砸进去。 + if t.buf.Version() == version { + a.applyEdits(t, orgEdits) + } + a.lspSync(t) + applied <- t.buf.Version() + }) + v := <-applied + if v == 0 { + return + } + cur = v + } + } + + // 2) 格式化:在(可能的)整理结果之上算。 + if a.set.FormatOnSave { + edits, err := c.Format(ctx, uri, lsp.FormattingOptions{TabSize: 4, InsertSpaces: false}) + a.win.Update(func() { + target := a.find(path) + if target == nil { + return + } + if err == nil && len(edits) > 0 && target.buf.Version() == cur { + a.applyEdits(target, edits) + } + a.writeDoc(target) + }) + return + } + a.win.Update(func() { + if target := a.find(path); target != nil { + a.writeDoc(target) + } + }) + }() +} + +// writeDocFile 把缓冲区写回磁盘并标记已保存,可在任意协程调用。 +func writeDocFile(d *Doc) error { + if d.st != nil && d.st.ReadOnly { + return fmt.Errorf("只读文档不能保存") + } + f, err := os.OpenFile(d.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) + if err != nil { + return err + } + // 按打开时的编码写回:GBK 的配置改完还是 GBK, + // 不然老系统读到的就是一堆乱码。 + // + // 换行也要还原:Buffer 记住的是打开时的行尾(CRLF/LF), + // 但文本内部是规范化过的,直接写会把 CRLF 变成 LF, + // 于是 git 里整个文件都显示成改动。 + text := d.buf.String() + if d.buf.LineEnding() == "\r\n" { + text = strings.ReplaceAll(text, "\r\n", "\n") + text = strings.ReplaceAll(text, "\n", "\r\n") + } + data, encErr := encodeFile(text, d.enc) + var werr error + if encErr != nil { + _, werr = d.buf.WriteTo(f) + } else { + _, werr = f.Write(data) + } + cerr := f.Close() + if werr != nil { + return werr + } + if cerr != nil { + return cerr + } + d.buf.MarkSaved() + d.notifySaved() + return nil +} + +// writeDoc 写回磁盘并刷新界面。 +func (a *App) writeDoc(d *Doc) { + if err := writeDocFile(d); err != nil { + a.alert("保存失败", err.Error()) + return + } + // 保存成功先留一个历史点:这是「误改能翻回去」的那一层。 + // 放到后台做,写盘不该等快照。 + a.snapshotAsync(d, "save", false) + if a.lsp != nil && d.opened { + _ = a.lsp.DidSave(d.uri, "") + } + if a.win != nil { + a.win.Update(a.syncTitle) + } + // 存盘后改动集合变了,刷新一次 git 状态(文件树颜色与状态栏计数)。 + a.refreshGit() +} + +// CloseDoc 关闭一个文件,有未保存改动时先询问。 +func (a *App) CloseDoc(path string) { + d := a.find(path) + if d == nil { + return + } + if d.buf.Modified() { + res, err := mygo.Dialog.Message(mygo.MessageOptions{ + Parent: a.win, + Type: mygo.MessageWarning, + Title: "未保存的更改", + Message: filepath.Base(path) + " 有未保存的更改。", + Buttons: []string{"保存", "不保存", "取消"}, + DefaultButton: 0, + CancelButton: 2, + }) + if err != nil { + return + } + switch res.Button { + case 0: + // 同步写盘:saveDoc 是异步的,removeDoc 可能先执行导致改动丢失。 + if err := writeDocFile(d); err != nil { + a.alert("保存失败", err.Error()) + return + } + a.win.Update(a.syncTitle) + case 1: + // 丢弃改动。 + default: + return + } + } + a.win.Update(func() { a.removeDoc(path) }) +} + +// removeDoc 从标签栏移除文件,必须在主线程调用。 +func (a *App) removeDoc(path string) { + for i, x := range a.docs { + if x.path == path { + x.stopWatch() + if a.lsp != nil && x.opened { + _ = a.lsp.DidClose(x.uri) + } + a.docs = append(a.docs[:i], a.docs[i+1:]...) + break + } + } + if a.active == path { + a.active = "" + if n := len(a.docs); n > 0 { + a.active = a.docs[n-1].path + } + } + a.syncTitle() + a.saveSession() +} + +// Refresh 丢弃目录缓存,重新读取文件树。 +func (a *App) Refresh() { + a.win.Update(func() { + a.dirs = map[string][]fs.DirEntry{} + }) +} + +// syncTitle 把工作区与当前文件反映到窗口标题。 +func (a *App) syncTitle() { + if a.win == nil || a.root == "" { + return + } + title := "MyGoland — " + filepath.Base(a.root) + if d := a.doc(); d != nil { + title = filepath.Base(d.path) + " — " + filepath.Base(a.root) + if d.buf.Modified() { + title = "● " + title + a.win.SetDocumentEdited(true) + } else { + a.win.SetDocumentEdited(false) + } + } + a.win.SetTitle(title) +} + +// alert 弹出一个错误对话框,不阻塞调用方。 +func (a *App) alert(title, msg string) { + if a.win == nil { + return + } + win := a.win + go func() { + _, _ = mygo.Dialog.Message(mygo.MessageOptions{ + Parent: win, + Type: mygo.MessageError, + Title: title, + Message: msg, + }) + }() +} + +// entries 返回目录内容,目录在前、按名称排序,结果按目录缓存。 +func (a *App) entries(dir string) []fs.DirEntry { + if es, ok := a.dirs[dir]; ok { + return es + } + es, err := os.ReadDir(dir) + if err != nil { + es = nil + } + sort.SliceStable(es, func(i, j int) bool { + if es[i].IsDir() != es[j].IsDir() { + return es[i].IsDir() + } + return strings.ToLower(es[i].Name()) < strings.ToLower(es[j].Name()) + }) + a.dirs[dir] = es + return es +} + +// skipDir 过滤掉不参与浏览的目录。 +func skipDir(name string) bool { + switch name { + case ".git", "node_modules", ".idea", ".mygoland": + return true + } + return false +} + +// skipFile 过滤掉不该出现在文件树里的生成物。 +func skipFile(name string) bool { + if strings.HasPrefix(name, "__debug_bin") { + return true + } + return strings.HasSuffix(name, ".exe") || strings.HasSuffix(name, ".test") +} + +// openFlag 返回目录展开状态的稳定指针。 +func (a *App) openFlag(path string) *bool { + if p, ok := a.open[path]; ok { + return p + } + p := new(bool) + a.open[path] = p + return p +} + +// wordsOf 用缓冲区里的词做补全,语言服务器不可用时的兜底。 +func wordsOf(b *editor.Buffer, prefix string) []editor.Completion { + seen := map[string]bool{} + var out []editor.Completion + words := strings.FieldsFunc(b.String(), func(r rune) bool { + return !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' + }) + for _, w := range words { + if len(w) < 3 || seen[w] || w == prefix { + continue + } + seen[w] = true + out = append(out, editor.Completion{Label: w, Kind: editor.CompletionText, Detail: "word"}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Label < out[j].Label }) + return out +} + +// focusEditorSoon 稍后把键盘焦点交回编辑器。 +// +// 弹窗/面板刚关掉的那一帧抢不到焦点(Modal 的焦点作用域还没拆完), +// 所以延后 120 ms 再设标记,由 editorArea 在那一帧调用 Focus() 接管。 +func (a *App) focusEditorSoon() { + time.AfterFunc(120*time.Millisecond, func() { + if a.win == nil { + return + } + a.win.Update(func() { a.wantFocus = true }) + }) +} + +// SetLight 切换深浅色主题:界面配色、语法配色与后端画的窗口按钮一起换。 +func (a *App) SetLight(light bool) { + if a.light == light { + return + } + a.light = light + a.th = theme(light) + for _, d := range a.docs { + d.st.Theme = codeTheme(light) + } + if a.win == nil { + return + } + // 窗口按钮由后端绘制,深浅要单独告诉它,否则浅色标题栏上会是白色按钮。 + if light { + a.win.SetWindowButtonsTheme(mygo.ThemeLight) + } else { + a.win.SetWindowButtonsTheme(mygo.ThemeDark) + } + a.saveSession() + a.win.Update(func() {}) +} diff --git a/internal/app/assets/gopher.png b/internal/app/assets/gopher.png new file mode 100644 index 0000000..98eab3b Binary files /dev/null and b/internal/app/assets/gopher.png differ diff --git a/internal/app/assets/icon.png b/internal/app/assets/icon.png new file mode 100644 index 0000000..b786c5b Binary files /dev/null and b/internal/app/assets/icon.png differ diff --git a/internal/app/assets/logo.png b/internal/app/assets/logo.png new file mode 100644 index 0000000..652a9a0 Binary files /dev/null and b/internal/app/assets/logo.png differ diff --git a/internal/app/breadcrumb.go b/internal/app/breadcrumb.go new file mode 100644 index 0000000..5907c58 --- /dev/null +++ b/internal/app/breadcrumb.go @@ -0,0 +1,112 @@ +package app + +import ( + "path/filepath" + "strings" + + "github.com/egoist/mygo/ui" +) + +// breadcrumb 画编辑器上方的路径导航:项目 › 子目录 › 文件名。 +// +// 点目录会在左侧文件树里展开并选中它,省得自己一层层点开。 +func (a *App) breadcrumb(c *ui.Context, d *Doc) { + t := c.Theme() + + segs, dirs := crumbSegments(a.root, d.path) + + // 项目名单独占一段,不能顶替第一层目录—— + // 否则 greeter/greeter.go 会显示成「项目 › greeter.go」,中间层看不见。 + showRoot := a.root != "" && len(segs) > 1 + + ui.Row(c).FillWidth().Height(22).Padding(0, 6).Gap(2).AlignItems(ui.Center).Children(func() { + if showRoot { + a.crumbButton(c, filepath.Base(a.root), t.TextMuted, func() { a.revealDir(a.root) }) + ui.Text(c, "›").FontSize(11).TextColor(t.TextMuted) + } + for i, seg := range segs { + last := i == len(segs)-1 + target := dirs[i] + color := t.TextMuted + if last { + color = t.Text + } + if last { + ui.Text(c, seg).FontSize(11).TextColor(color).SingleLine() + continue + } + // 这里必须用可点击的按钮壳:纯 Text 收不到点击。 + a.crumbButton(c, seg, color, func() { a.revealDir(target) }) + ui.Text(c, "›").FontSize(11).TextColor(t.TextMuted) + } + }) +} + +// revealDir 在文件树里展开到指定目录并选中它。 +func (a *App) revealDir(dir string) { + if dir == "" || a.root == "" { + return + } + // 从目标往上逐级展开,直到工作区根。 + for p := filepath.Clean(dir); within(a.root, p); p = filepath.Dir(p) { + if sameDir(p, a.root) { + break + } + *a.openFlag(p) = true + if parent := filepath.Dir(p); sameDir(parent, p) { + break + } + } + a.sel = map[string]bool{filepath.Clean(dir): true} + // 树被收起来了就先打开侧栏,不然展开了也看不见。 + a.sidebarOn = true + a.win.Update(func() {}) +} + +// crumbSegments 把文件路径拆成面包屑的各段,以及每段对应的绝对路径。 +// +// 返回值一一对应:最后一项是文件本身,前面的都是目录。 +// 文件不在工作区内(比如从最近项目直接打开)时只返回文件名。 +func crumbSegments(root, path string) ([]string, []string) { + path = filepath.Clean(path) + if root == "" || !within(root, path) { + return []string{filepath.Base(path)}, []string{path} + } + rel, err := filepath.Rel(root, path) + if err != nil { + return []string{filepath.Base(path)}, []string{path} + } + parts := strings.Split(filepath.ToSlash(rel), "/") + segs := make([]string, 0, len(parts)) + dirs := make([]string, 0, len(parts)) + cur := filepath.Clean(root) + for _, p := range parts { + if p == "" || p == "." { + continue + } + cur = filepath.Join(cur, filepath.FromSlash(p)) + segs = append(segs, p) + dirs = append(dirs, cur) + } + if len(segs) == 0 { + return []string{filepath.Base(path)}, []string{path} + } + return segs, dirs +} + +// crumbButton 是面包屑里可点的一段。 +func (a *App) crumbButton(c *ui.Context, label string, color ui.Color, onClick func()) { + t := c.Theme() + b := ui.ButtonBase(c).Padding(1, 3).Radius(3).Cursor(ui.CursorPointer) + fg := color + if b.Hovered() { + b = b.Background(t.SurfaceHover) + fg = t.Accent + } + b.Children(func() { + ui.Text(c, label).FontSize(11).TextColor(fg).SingleLine() + }) + if b.Clicked() { + onClick() + } +} diff --git a/internal/app/breadcrumb_test.go b/internal/app/breadcrumb_test.go new file mode 100644 index 0000000..a44d42c --- /dev/null +++ b/internal/app/breadcrumb_test.go @@ -0,0 +1,52 @@ +package app + +import ( + "path/filepath" + "testing" +) + +func TestCrumbSegments(t *testing.T) { + root := filepath.Join("C:", "work", "proj") + path := filepath.Join(root, "greeter", "greeter.go") + + segs, dirs := crumbSegments(root, path) + if len(segs) != 2 || segs[0] != "greeter" || segs[1] != "greeter.go" { + t.Fatalf("分段不对: %v", segs) + } + if dirs[0] != filepath.Join(root, "greeter") { + t.Fatalf("第一段应指向目录: %v", dirs) + } + if dirs[1] != path { + t.Fatalf("最后一段应是文件本身: %v", dirs) + } +} + +func TestCrumbSegmentsSameDir(t *testing.T) { + root := filepath.Join("C:", "work", "proj") + segs, _ := crumbSegments(root, filepath.Join(root, "main.go")) + if len(segs) != 1 || segs[0] != "main.go" { + t.Fatalf("根目录下的文件应只有一段: %v", segs) + } +} + +func TestCrumbSegmentsOutsideRoot(t *testing.T) { + root := filepath.Join("C:", "work", "proj") + outside := filepath.Join("C:", "other", "x.go") + segs, dirs := crumbSegments(root, outside) + if len(segs) != 1 || segs[0] != "x.go" { + t.Fatalf("工作区外只显示文件名: %v", segs) + } + if dirs[0] != outside { + t.Fatalf("工作区外应回退成完整路径: %v", dirs) + } +} + +// TestCrumbSegmentsSiblingPrefix 同前缀的邻居目录不能被当成工作区内的文件。 +func TestCrumbSegmentsSiblingPrefix(t *testing.T) { + root := filepath.Join("C:", "work", "proj") + sibling := filepath.Join("C:", "work", "proj2", "y.go") + segs, _ := crumbSegments(root, sibling) + if len(segs) != 1 || segs[0] != "y.go" { + t.Fatalf("兄弟目录应走工作区外分支: %v", segs) + } +} diff --git a/internal/app/breakpoints.go b/internal/app/breakpoints.go new file mode 100644 index 0000000..1c3c604 --- /dev/null +++ b/internal/app/breakpoints.go @@ -0,0 +1,235 @@ +package app + +import ( + "path/filepath" + "sort" + "strings" + + "github.com/egoist/mygo/ui" +) + +// breakpoint 是一个断点的附加信息。 +type breakpoint struct { + // Cond 是命中条件(DAP 的 condition),空表示无条件。 + Cond string + // Enabled 为假时保留但不生效,调试时不会发给适配器。 + Enabled bool +} + +// bpRef 是断点的一个引用,用于列表显示。 +type bpRef struct { + Path string + Line int + BP breakpoint +} + +// toggleBreakpoint 在指定行加/删断点。 +func (a *App) toggleBreakpoint(path string, line int) { + if a.bps[path] == nil { + a.bps[path] = map[int]breakpoint{} + } + if _, ok := a.bps[path][line]; ok { + delete(a.bps[path], line) + if len(a.bps[path]) == 0 { + delete(a.bps, path) + } + } else { + a.bps[path][line] = breakpoint{Enabled: true} + } + a.afterBreakpointChange(path) +} + +// setBreakpointCond 设置命中条件。 +func (a *App) setBreakpointCond(path string, line int, cond string) { + m := a.bps[path] + if m == nil { + return + } + bp, ok := m[line] + if !ok { + return + } + bp.Cond = cond + m[line] = bp + a.afterBreakpointChange(path) +} + +// setBreakpointEnabled 启用/禁用断点。 +func (a *App) setBreakpointEnabled(path string, line int, on bool) { + m := a.bps[path] + if m == nil { + return + } + bp, ok := m[line] + if !ok { + return + } + bp.Enabled = on + m[line] = bp + a.afterBreakpointChange(path) +} + +// deleteBreakpoint 删除断点。 +func (a *App) deleteBreakpoint(path string, line int) { + m := a.bps[path] + if m == nil { + return + } + delete(m, line) + if len(m) == 0 { + delete(a.bps, path) + } + a.afterBreakpointChange(path) +} + +// afterBreakpointChange 断点变动后:重画该文件的断点标记、同步给调试会话、存会话。 +func (a *App) afterBreakpointChange(path string) { + if d := a.find(path); d != nil { + a.decorate(d) + } + a.pushBreakpoints(path) + a.saveSession() + if a.win != nil { + a.win.Update(func() {}) + } +} + +// allBreakpoints 按文件、行号排序列出所有断点。 +func (a *App) allBreakpoints() []bpRef { + var out []bpRef + for path, m := range a.bps { + for line, bp := range m { + out = append(out, bpRef{Path: path, Line: line, BP: bp}) + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].Path != out[j].Path { + return out[i].Path < out[j].Path + } + return out[i].Line < out[j].Line + }) + return out +} + +// breakpointView 是面板里的「断点」页。 +func (a *App) breakpointView(c *ui.Context) { + t := c.Theme() + items := a.allBreakpoints() + if len(items) == 0 { + ui.Text(c, "还没有断点。在行号上点一下即可添加,点「条件」可以设置命中条件。"). + FontSize(11).TextColor(t.TextMuted).Padding(8, 6) + return + } + ui.Column(c).Gap(1).Padding(4, 0).Children(func() { + for _, ref := range items { + a.breakpointRow(c, ref) + } + }) +} + +// breakpointRow 画一行断点。 +func (a *App) breakpointRow(c *ui.Context, ref bpRef) { + t := c.Theme() + row := ui.ButtonBase(c).FillWidth().Padding(2, 6).Gap(8).Radius(3). + Justify(ui.Start).AlignItems(ui.Center).Cursor(ui.CursorPointer) + if row.Hovered() { + row = row.Background(t.SurfaceHover) + } + row.Children(func() { + // 勾选框控制启用状态。 + on := ref.BP.Enabled + if ui.Checkbox(c, &on, "").Changed() { + a.setBreakpointEnabled(ref.Path, ref.Line, on) + } + ui.Text(c, a.shortPath(ref.Path)).FontSize(12).TextColor(t.Text).SingleLine() + ui.Textf(c, "%d", ref.Line).FontSize(11).TextColor(t.TextMuted) + if ref.BP.Cond != "" { + ui.Text(c, "当 "+ref.BP.Cond).FontSize(11).TextColor(t.Warning).SingleLine() + } + ui.Box(c).Grow(1) + if ui.Button(c, "条件").Clicked() { + a.openCondDialog(ref.Path, ref.Line, ref.BP.Cond) + } + if ui.Button(c, "删除").Clicked() { + a.deleteBreakpoint(ref.Path, ref.Line) + } + }) + + // 点空白处跳到该断点。 + if row.Clicked() { + go a.openAtLine(ref.Path, ref.Line) + } +} + +// shortPath 把绝对路径缩成工作区相对路径。 +func (a *App) shortPath(p string) string { + if a.root != "" { + if rel, err := filepath.Rel(a.root, p); err == nil { + return filepath.ToSlash(rel) + } + } + return p +} + +// openCondDialog 打开条件输入框。 +func (a *App) openCondDialog(path string, line int, cond string) { + a.bpDlg = bpDialogState{open: true, dlg: true, path: path, line: line, cond: cond} + a.win.Update(func() {}) +} + +// bpDialogState 是条件断点弹窗的状态。 +type bpDialogState struct { + open bool + dlg bool + path string + line int + cond string +} + +// breakpointCondDialog 画条件输入弹窗。 +func (a *App) breakpointCondDialog(c *ui.Context) { + if !a.bpDlg.open { + return + } + t := c.Theme() + + ui.Modal(c, &a.bpDlg.dlg, func() { + ui.Column(c).Width(460).Gap(10).Children(func() { + ui.Text(c, "断点条件").FontSize(13).Bold().TextColor(t.Text) + ui.Textf(c, "%s 第 %d 行", a.shortPath(a.bpDlg.path), a.bpDlg.line). + FontSize(10).TextColor(t.TextMuted).SingleLine() + + inp := ui.TextInput(c, &a.bpDlg.cond).FillWidth().FontSize(13).AutoFocus() + if inp.Submitted() { + a.confirmCond() + } + ui.Text(c, "留空表示无条件。例如 i == 3 或 name != \"\""). + FontSize(10).TextColor(t.TextMuted).SingleLine() + + ui.Row(c).Gap(8).Justify(ui.End).Children(func() { + if ui.Button(c, "取消").Clicked() { + a.bpDlg.open = false + } + if ui.Button(c, "确定").Clicked() { + a.confirmCond() + } + }) + }) + }) + + if !a.bpDlg.dlg && a.bpDlg.open { + a.bpDlg.dlg = true + a.win.Update(func() {}) + } + if !a.bpDlg.open && a.bpDlg.dlg { + a.bpDlg.dlg = false + a.focusEditorSoon() + } +} + +// confirmCond 保存条件。 +func (a *App) confirmCond() { + a.setBreakpointCond(a.bpDlg.path, a.bpDlg.line, strings.TrimSpace(a.bpDlg.cond)) + a.bpDlg.open = false + a.win.Update(func() {}) +} diff --git a/internal/app/breakpoints_test.go b/internal/app/breakpoints_test.go new file mode 100644 index 0000000..b3e7ba8 --- /dev/null +++ b/internal/app/breakpoints_test.go @@ -0,0 +1,91 @@ +package app + +import ( + "encoding/json" + "testing" +) + +func newBPApp() *App { + return &App{bps: map[string]map[int]breakpoint{}} +} + +func TestToggleBreakpoint(t *testing.T) { + a := newBPApp() + a.toggleBreakpoint("a.go", 3) + if _, ok := a.bps["a.go"][3]; !ok { + t.Fatal("应当加上断点") + } + if !a.bps["a.go"][3].Enabled { + t.Fatal("新断点默认启用") + } + a.toggleBreakpoint("a.go", 3) + if _, ok := a.bps["a.go"][3]; ok { + t.Fatal("再点一次应当删除") + } + if _, ok := a.bps["a.go"]; ok { + t.Fatal("文件下没有断点时应把整个条目删掉,避免脏 map") + } +} + +func TestBreakpointConditionAndEnable(t *testing.T) { + a := newBPApp() + a.toggleBreakpoint("a.go", 5) + a.setBreakpointCond("a.go", 5, "i == 3") + a.setBreakpointEnabled("a.go", 5, false) + + bp := a.bps["a.go"][5] + if bp.Cond != "i == 3" || bp.Enabled { + t.Fatalf("条件/启用状态没设上: %+v", bp) + } + + // 对不存在的断点操作不应 panic 也不应凭空创建 + a.setBreakpointCond("a.go", 9, "x") + if _, ok := a.bps["a.go"][9]; ok { + t.Fatal("不该给不存在的断点设条件") + } +} + +func TestAllBreakpointsSorted(t *testing.T) { + a := newBPApp() + a.toggleBreakpoint("b.go", 2) + a.toggleBreakpoint("a.go", 9) + a.toggleBreakpoint("a.go", 4) + + got := a.allBreakpoints() + if len(got) != 3 { + t.Fatalf("应有 3 个断点,实际 %d", len(got)) + } + if got[0].Path != "a.go" || got[0].Line != 4 || + got[1].Path != "a.go" || got[1].Line != 9 || + got[2].Path != "b.go" || got[2].Line != 2 { + t.Fatalf("排序不对: %+v", got) + } +} + +func TestDeleteBreakpoint(t *testing.T) { + a := newBPApp() + a.toggleBreakpoint("a.go", 1) + a.deleteBreakpoint("a.go", 1) + if len(a.bps) != 0 { + t.Fatalf("删完应当清空: %+v", a.bps) + } +} + +// TestBPJSONBackCompat 老会话里断点是纯行号数组,升级后不能丢。 +func TestBPJSONBackCompat(t *testing.T) { + var old []bpJSON + if err := json.Unmarshal([]byte(`[3,7]`), &old); err != nil { + t.Fatal(err) + } + if len(old) != 2 || old[0].Line != 3 || !old[0].Enabled { + t.Fatalf("旧格式应解析成启用状态的断点: %+v", old) + } + + var neu []bpJSON + if err := json.Unmarshal([]byte(`[{"line":5,"cond":"i>0","enabled":false}]`), &neu); err != nil { + t.Fatal(err) + } + if len(neu) != 1 || neu[0].Line != 5 || neu[0].Cond != "i>0" || neu[0].Enabled { + t.Fatalf("新格式解析不对: %+v", neu) + } +} diff --git a/internal/app/code_theme.go b/internal/app/code_theme.go new file mode 100644 index 0000000..11b8ce7 --- /dev/null +++ b/internal/app/code_theme.go @@ -0,0 +1,165 @@ +package app + +import ( + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" +) + +// 语法配色两套,与界面主题配套。 +// +// 深色 One Dark Vivid 浅色 One Light +// 关键字 紫 #D55FDE 紫 #A626A4 +// 函数 蓝 #61AFEF 蓝 #4078F2 +// 类型 黄 #E5C07B 黄 #C18401 +// 变量 红 #EF596F 红 #E45649 +// 数字 橙 #D19A66 橙 #986801 +// 字符串 绿 #89CA78 绿 #50A14F +// 注释 灰 #7F848E 灰 #A0A1A7 +// +// 浅色用的就是 Atom One Light——它是 One Dark 的官方同源浅色, +// 语义逐项对应,不是把深色配色硬调亮度(那样紫和青在浅底上会糊成一片)。 +var ( + darkCode = oneDarkVivid() + lightCode = oneLight() +) + +// codeTheme 返回当前明暗下的语法配色。 +func codeTheme(light bool) *editor.Theme { + if light { + return lightCode + } + return darkCode +} + +func oneDarkVivid() *editor.Theme { + ct := &editor.Theme{ + // 透明:编辑器不再自己铺底色,露出下面卡片带圆角的表面。 + // 直接铺满会把卡片四角盖成直角,视觉上和别的浮岛不一致。 + Background: ui.Hex(darkPalette.island).Alpha(0), + Text: ui.Hex(darkPalette.text), + + LineNumber: ui.Hex("#4B5263"), + ActiveLineNumber: ui.Hex("#ABB2BF"), + ActiveLine: ui.RGBA(255, 255, 255, 0.045), + + Selection: ui.RGBA(97, 175, 239, 0.26), + InactiveSelection: ui.RGBA(97, 175, 239, 0.15), + Cursor: ui.Hex("#528BFF"), + + MatchingBracket: ui.RGBA(97, 175, 239, 0.55), + Match: ui.RGBA(229, 192, 123, 0.26), + CurrentMatch: ui.RGBA(229, 192, 123, 0.55), + Occurrence: ui.RGBA(97, 175, 239, 0.13), + + IndentGuide: ui.RGBA(255, 255, 255, 0.08), + ActiveIndentGuide: ui.RGBA(255, 255, 255, 0.20), + WrapGuide: ui.RGBA(255, 255, 255, 0.07), + Whitespace: ui.RGBA(255, 255, 255, 0.14), + + Error: ui.Hex("#EF596F"), + Warning: ui.Hex("#E5C07B"), + Info: ui.Hex("#61AFEF"), + Hint: ui.Hex("#7F848E"), + + Added: ui.Hex("#89CA78"), + Deleted: ui.Hex("#EF596F"), + Modified: ui.Hex("#61AFEF"), + } + + tok := func(k editor.TokenKind, hex string) { ct.Tokens[k].Color = ui.Hex(hex) } + + tok(editor.TokenKeyword, "#D55FDE") + tok(editor.TokenOperator, "#2BBAC5") + tok(editor.TokenPunctuation, "#ABB2BF") + tok(editor.TokenType, "#E5C07B") + tok(editor.TokenFunction, "#61AFEF") + tok(editor.TokenVariable, "#EF596F") + tok(editor.TokenProperty, "#EF596F") + tok(editor.TokenConstant, "#D19A66") + tok(editor.TokenNumber, "#D19A66") + tok(editor.TokenString, "#89CA78") + tok(editor.TokenEscape, "#2BBAC5") + tok(editor.TokenRegexp, "#89CA78") + tok(editor.TokenComment, "#7F848E") + tok(editor.TokenMeta, "#D55FDE") + tok(editor.TokenTag, "#EF596F") + tok(editor.TokenAttribute, "#D19A66") + tok(editor.TokenHeading, "#EF596F") + tok(editor.TokenLink, "#61AFEF") + tok(editor.TokenCode, "#89CA78") + tok(editor.TokenInserted, "#89CA78") + tok(editor.TokenDeleted, "#EF596F") + tok(editor.TokenInvalid, "#EF596F") + + // 注释不设斜体:中文没有真正的斜体字形,伪斜体渲染出来整段歪扭。 + ct.Tokens[editor.TokenHeading].Bold = true + ct.Tokens[editor.TokenStrong].Bold = true + ct.Tokens[editor.TokenEmphasis].Italic = true + + return ct +} + +func oneLight() *editor.Theme { + ct := &editor.Theme{ + Background: ui.Hex(lightPalette.island).Alpha(0), + Text: ui.Hex("#383A42"), + + LineNumber: ui.Hex("#9D9D9F"), + ActiveLineNumber: ui.Hex("#383A42"), + ActiveLine: ui.RGBA(0, 0, 0, 0.04), + + Selection: ui.RGBA(9, 105, 218, 0.16), + InactiveSelection: ui.RGBA(9, 105, 218, 0.09), + Cursor: ui.Hex("#526FFF"), + + MatchingBracket: ui.RGBA(9, 105, 218, 0.45), + Match: ui.RGBA(193, 132, 1, 0.22), + CurrentMatch: ui.RGBA(193, 132, 1, 0.45), + Occurrence: ui.RGBA(9, 105, 218, 0.10), + + IndentGuide: ui.RGBA(0, 0, 0, 0.08), + ActiveIndentGuide: ui.RGBA(0, 0, 0, 0.18), + WrapGuide: ui.RGBA(0, 0, 0, 0.06), + Whitespace: ui.RGBA(0, 0, 0, 0.12), + + Error: ui.Hex("#E45649"), + Warning: ui.Hex("#C18401"), + Info: ui.Hex("#4078F2"), + Hint: ui.Hex("#A0A1A7"), + + Added: ui.Hex("#50A14F"), + Deleted: ui.Hex("#E45649"), + Modified: ui.Hex("#4078F2"), + } + + tok := func(k editor.TokenKind, hex string) { ct.Tokens[k].Color = ui.Hex(hex) } + + tok(editor.TokenKeyword, "#A626A4") + tok(editor.TokenOperator, "#0184BC") + tok(editor.TokenPunctuation, "#383A42") + tok(editor.TokenType, "#C18401") + tok(editor.TokenFunction, "#4078F2") + tok(editor.TokenVariable, "#E45649") + tok(editor.TokenProperty, "#E45649") + tok(editor.TokenConstant, "#986801") + tok(editor.TokenNumber, "#986801") + tok(editor.TokenString, "#50A14F") + tok(editor.TokenEscape, "#0184BC") + tok(editor.TokenRegexp, "#50A14F") + tok(editor.TokenComment, "#A0A1A7") + tok(editor.TokenMeta, "#A626A4") + tok(editor.TokenTag, "#E45649") + tok(editor.TokenAttribute, "#986801") + tok(editor.TokenHeading, "#E45649") + tok(editor.TokenLink, "#4078F2") + tok(editor.TokenCode, "#50A14F") + tok(editor.TokenInserted, "#50A14F") + tok(editor.TokenDeleted, "#E45649") + tok(editor.TokenInvalid, "#E45649") + + ct.Tokens[editor.TokenHeading].Bold = true + ct.Tokens[editor.TokenStrong].Bold = true + ct.Tokens[editor.TokenEmphasis].Italic = true + + return ct +} diff --git a/internal/app/coverage.go b/internal/app/coverage.go new file mode 100644 index 0000000..73a1ad7 --- /dev/null +++ b/internal/app/coverage.go @@ -0,0 +1,353 @@ +package app + +import ( + "bufio" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" + + "mygoland/internal/task" +) + +// 覆盖率:跑 `go test -coverprofile`,把 coverprofile 解析成行区间, +// 用编辑器的 LineBackgrounds 给行铺底色(跑到的绿、没跑到的红)。 +// +// coverprofile 的格式(每行一个块): +// +// 文件名:起始行.起始列,结束行.结束列 语句数 命中次数 + +// coverBlock 是 coverprofile 里的一个块。 +type coverBlock struct { + Start, End int // 行号,1 起 + Stmts int + Count int +} + +// coverFile 是一个文件的覆盖率数据。 +type coverFile struct { + Blocks []coverBlock + Total int // 语句总数 + Hit int // 命中的语句数 +} + +// percent 返回覆盖率百分比。 +func (f coverFile) percent() float64 { + if f.Total == 0 { + return 0 + } + return float64(f.Hit) * 100 / float64(f.Total) +} + +// coverState 是覆盖率面板的状态。 +type coverState struct { + running bool + files map[string]coverFile // 键是小写规范化的绝对路径 + all float64 + total string // 整体一行摘要,显示在状态栏 +} + +// parseCoverProfile 解析 coverprofile 文本。 +func parseCoverProfile(text string) map[string]coverFile { + out := map[string]coverFile{} + sc := bufio.NewScanner(strings.NewReader(text)) + sc.Buffer(make([]byte, 0, 64*1024), 8*1024*1024) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "mode:") { + continue + } + // name.go:3.14,5.2 2 1 + colon := strings.LastIndex(line, ":") + if colon <= 0 { + continue + } + file := line[:colon] + rest := line[colon+1:] + fields := strings.Fields(rest) + if len(fields) < 3 { + continue + } + spans := strings.Split(fields[0], ",") + if len(spans) != 2 { + continue + } + startLine, err1 := lineOfSpan(spans[0]) + endLine, err2 := lineOfSpan(spans[1]) + if err1 != nil || err2 != nil { + continue + } + stmts, err3 := strconv.Atoi(fields[1]) + count, err4 := strconv.Atoi(fields[2]) + if err3 != nil || err4 != nil { + continue + } + + key := coverKey(file) + f := out[key] + f.Blocks = append(f.Blocks, coverBlock{Start: startLine, End: endLine, Stmts: stmts, Count: count}) + f.Total += stmts + if count > 0 { + f.Hit += stmts + } + out[key] = f + } + return out +} + +// lineOfSpan 从 "12.5" 里取出行号 12。 +func lineOfSpan(s string) (int, error) { + if i := strings.IndexByte(s, '.'); i >= 0 { + s = s[:i] + } + return strconv.Atoi(s) +} + +// coverKey 把 coverprofile 里的路径规范化成 map 键。 +// +// -coverprofile 里的文件名是「模块路径/包目录/文件」或者绝对路径, +// 统一按小写 + 正斜杠比较,避免 Windows 上大小写和分隔符差异。 +func coverKey(p string) string { + return strings.ToLower(filepath.ToSlash(p)) +} + +// RunCoverage 跑覆盖率并刷新行底色。 +func (a *App) RunCoverage() { + if a.root == "" { + a.alert("覆盖率", "先打开一个工作区。") + return + } + if a.cover.running { + return + } + out, err := os.CreateTemp("", "mygoland-cover-*.out") + if err != nil { + a.alert("覆盖率", err.Error()) + return + } + path := out.Name() + out.Close() + defer os.Remove(path) + + t, err := task.Start(a.root, "go", "test", "-coverprofile="+path, "./...") + if err != nil { + a.alert("覆盖率", err.Error()) + return + } + a.cover.running = true + // 跑起来就把面板切到覆盖率页,用户不用自己找。 + a.panel = true + a.panelTab = 6 + if a.panelH < 240 { + a.panelH = 280 + } + a.refresh() + + go func() { + var lines []string + for line := range t.Lines { + lines = append(lines, line) + } + t.Wait() + data, readErr := os.ReadFile(path) + a.win.Update(func() { + a.cover.running = false + if readErr != nil { + a.appendOut("覆盖率失败:没拿到 coverprofile") + a.refresh() + return + } + a.applyCoverage(string(data)) + }) + _ = lines + }() +} + +// applyCoverage 把 coverprofile 套到打开的文件上。 +func (a *App) applyCoverage(text string) { + files := parseCoverProfile(text) + a.cover.files = files + + var totalStmts, totalHit int + for _, f := range files { + totalStmts += f.Total + totalHit += f.Hit + } + if totalStmts > 0 { + a.cover.all = float64(totalHit) * 100 / float64(totalStmts) + a.cover.total = fmt.Sprintf("覆盖率 %.1f%%", a.cover.all) + } + + a.applyCoverDecorations() + a.appendOut(fmt.Sprintf("覆盖率:%.1f%%(%d/%d 条语句)", a.cover.all, totalHit, totalStmts)) + a.refresh() +} + +// applyCoverDecorations 给每个打开的文档重新算行底色。 +func (a *App) applyCoverDecorations() { + for _, d := range a.docs { + if d.st == nil { + continue + } + d.coverBG = a.coverBackgrounds(d) + } +} + +// coverBackgrounds 生成一个文件的行底色。 +func (a *App) coverBackgrounds(d *Doc) []editor.LineBackground { + if len(a.cover.files) == 0 { + return nil + } + f, ok := a.coverFor(d.path) + if !ok { + return nil + } + // 每一行取覆盖它所有块里「命中最差」的那个结果: + // 一行可能被拆成多块(比如 `if x { y() }`),有一块没跑到就算没覆盖。 + hit := map[int]bool{} + seen := map[int]bool{} + for _, b := range f.Blocks { + for line := b.Start; line <= b.End; line++ { + seen[line] = true + if b.Count > 0 { + hit[line] = true + } + } + } + var out []editor.LineBackground + for line := range seen { + if line < 1 { + continue + } + c := a.th.Danger.Alpha(0.18) + if hit[line] { + c = a.th.Success.Alpha(0.20) + } + out = append(out, editor.LineBackground{First: line - 1, Last: line - 1, Color: c}) + } + return out +} + +// coverFor 找到某个文件对应的覆盖率数据。 +// +// coverprofile 里的路径可能是「模块路径+包目录」的形式,所以按后缀匹配: +// 路径以「/pkg/dir/file.go」结尾就算同一个文件。 +func (a *App) coverFor(path string) (coverFile, bool) { + slash := filepath.ToSlash(path) + for key, f := range a.cover.files { + if key == strings.ToLower(slash) { + return f, true + } + } + // 退一步按「包目录/文件名」后缀比,把两边都归一成 / 分隔。 + norm := strings.ToLower(slash) + for key, f := range a.cover.files { + if strings.HasSuffix(norm, "/"+packageSuffix(key)) { + return f, true + } + } + return coverFile{}, false +} + +// packageSuffix 取「包目录/文件名」这一段,用于后缀匹配。 +func packageSuffix(key string) string { + parts := strings.Split(key, "/") + if len(parts) < 2 { + return key + } + return parts[len(parts)-2] + "/" + parts[len(parts)-1] +} + +// clearCoverage 关掉覆盖率着色。 +func (a *App) clearCoverage() { + a.cover = coverState{} + for _, d := range a.docs { + if d.st != nil { + d.coverBG = nil + } + } + a.refresh() +} + +// coverStatText 是状态栏上的覆盖率摘要。 +func (a *App) coverStatText(path string) string { + if len(a.cover.files) == 0 { + return "" + } + f, ok := a.coverFor(path) + if !ok { + return "" + } + return fmt.Sprintf("覆盖 %.0f%%", f.percent()) +} + +// coverageView 是面板里的「覆盖率」页签。 +func (a *App) coverageView(c *ui.Context) { + t := c.Theme() + ui.Column(c).FillHeight().Children(func() { + ui.Row(c).Padding(3, 10).Gap(8).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + if a.cover.total != "" { + ui.Text(c, a.cover.total).FontSize(11).TextColor(t.Text).SingleLine() + } else { + ui.Text(c, "还没有覆盖率数据").FontSize(11).TextColor(t.TextMuted) + } + ui.Box(c).Grow(1) + if a.cover.running { + ui.Text(c, "统计中…").FontSize(11).TextColor(t.Accent) + } + if ui.Button(c, "统计覆盖率").Clicked() { + a.RunCoverage() + } + if len(a.cover.files) > 0 && ui.Button(c, "清除").Clicked() { + a.clearCoverage() + } + }) + + if len(a.cover.files) == 0 { + ui.Column(c).Grow(1).FillHeight().Center().Children(func() { + ui.Text(c, "点「统计覆盖率」跑一遍 go test -coverprofile").FontSize(12). + TextColor(t.TextMuted) + }) + return + } + + // 按覆盖率从低到高排:最该补的地方排前面。 + type row struct { + name string + pct float64 + } + var rows []row + for key, f := range a.cover.files { + rows = append(rows, row{name: key, pct: f.percent()}) + } + for i := 0; i < len(rows); i++ { + for j := i + 1; j < len(rows); j++ { + if rows[j].pct < rows[i].pct { + rows[i], rows[j] = rows[j], rows[i] + } + } + } + + ui.Scroll(c).Grow(1).Children(func() { + ui.Column(c).Gap(1).Children(func() { + for _, r := range rows { + ui.Row(c).FillWidth().Padding(2, 10).Gap(10).Children(func() { + color := t.Success + if r.pct < 50 { + color = t.Danger + } else if r.pct < 80 { + color = t.Warning + } + ui.Textf(c, "%.0f%%", r.pct).FontSize(11).TextColor(color).Width(40) + ui.Text(c, r.name).FontSize(11).TextColor(t.TextMuted).SingleLine() + }) + } + }) + }) + }) +} diff --git a/internal/app/coverage_test.go b/internal/app/coverage_test.go new file mode 100644 index 0000000..2e3510b --- /dev/null +++ b/internal/app/coverage_test.go @@ -0,0 +1,93 @@ +package app + +import ( + "testing" + + "github.com/egoist/mygo/ui" +) + +func themeForTest() *ui.Theme { return ui.DarkTheme() } + +const sampleProfile = `mode: set +testdemo/calc.go:5.13,7.2 1 1 +testdemo/calc.go:10.6,14.2 3 0 +testdemo/util.go:3.20,5.2 2 5 +` + +// TestParseCoverProfile 解析 coverprofile 的块与统计。 +func TestParseCoverProfile(t *testing.T) { + files := parseCoverProfile(sampleProfile) + if len(files) != 2 { + t.Fatalf("应解析出 2 个文件,实际 %d: %v", len(files), files) + } + calc := files["testdemo/calc.go"] + if len(calc.Blocks) != 2 { + t.Fatalf("calc.go 应有 2 个块,实际 %d", len(calc.Blocks)) + } + // 一块命中(1 语句)、一块没命中(3 语句) → 1/4 + if calc.Total != 4 || calc.Hit != 1 { + t.Fatalf("统计不对: total=%d hit=%d", calc.Total, calc.Hit) + } + if got := calc.percent(); got != 25 { + t.Fatalf("覆盖率应为 25%%,实际 %v", got) + } + if b := calc.Blocks[0]; b.Start != 5 || b.End != 7 || b.Count != 1 { + t.Fatalf("块解析不对: %+v", b) + } +} + +// TestParseCoverProfileSkipsMode 第一行 mode 要跳过,空行也不能算块。 +func TestParseCoverProfileSkipsMode(t *testing.T) { + files := parseCoverProfile("mode: atomic\n\n") + if len(files) != 0 { + t.Fatalf("没有块时应为空: %v", files) + } +} + +// TestCoverForSuffix 覆盖报告的路径可能带模块前缀,要能按后缀对上。 +func TestCoverForSuffix(t *testing.T) { + a := &App{} + a.cover.files = parseCoverProfile(sampleProfile) + if _, ok := a.coverFor(`D:\WorkSpaces\testdemo\calc.go`); !ok { + t.Fatal("应该按「包目录/文件名」后缀匹配上") + } + if _, ok := a.coverFor(`D:\WorkSpaces\other\calc.go`); ok { + t.Fatal("不同目录的同名文件不该匹配") + } +} + +// TestCoverBackgrounds 命中的行绿、没命中的行红,且行号从 0 起。 +func TestCoverBackgrounds(t *testing.T) { + a := &App{th: themeForTest()} + a.cover.files = parseCoverProfile(`mode: set +testdemo/calc.go:3.1,3.10 1 1 +testdemo/calc.go:4.1,4.10 1 0 +`) + d := a.newDoc(`D:\WorkSpaces\testdemo\calc.go`, "a\nb\nc\nd\n") + bgs := a.coverBackgrounds(d) + if len(bgs) != 2 { + t.Fatalf("应有 2 行底色,实际 %d", len(bgs)) + } + byLine := map[int]int{} + for _, bg := range bgs { + byLine[bg.First] = 1 + } + if _, ok := byLine[2]; !ok { + t.Fatalf("第 3 行(0 起是 2)应有着色: %+v", bgs) + } + if _, ok := byLine[3]; !ok { + t.Fatalf("第 4 行(0 起是 3)应有着色: %+v", bgs) + } +} + +// TestCoverStatText 状态栏摘要。 +func TestCoverStatText(t *testing.T) { + a := &App{} + a.cover.files = parseCoverProfile(sampleProfile) + if got := a.coverStatText(`D:\WorkSpaces\testdemo\calc.go`); got != "覆盖 25%" { + t.Fatalf("摘要不对: %q", got) + } + if got := a.coverStatText(`D:\WorkSpaces\testdemo\none.go`); got != "" { + t.Fatalf("没有数据的文件不该显示: %q", got) + } +} diff --git a/internal/app/cursor_test.go b/internal/app/cursor_test.go new file mode 100644 index 0000000..cd705db --- /dev/null +++ b/internal/app/cursor_test.go @@ -0,0 +1,96 @@ +package app + +import ( + "path/filepath" + "testing" + + "github.com/egoist/mygo/ui/editor" +) + +// TestApplyPendingCursorClamps 存档里的位置越界时(文件被删了几行)不能跑出界。 +func TestApplyPendingCursorClamps(t *testing.T) { + isolateConfig(t) + dir := t.TempDir() + a := &App{set: defaultSettings(), root: dir} + d := a.newDoc(filepath.Join(dir, "a.go"), "package main\n\nfunc main() {}\n") + a.docs = append(a.docs, d) + + a.pendingCursor = []cursorRestore{{doc: d, cur: cursorJSON{Line: 99, Column: 999}}} + a.applyPendingCursor() + + pos := d.st.CursorPos() + last := d.buf.LineCount() - 1 + if pos.Line != last { + t.Fatalf("行应被夹到最后一行 %d,实际 %d", last, pos.Line) + } + if pos.Col > len(d.buf.Line(last)) { + t.Fatalf("列超出该行长度: %d > %d", pos.Col, len(d.buf.Line(last))) + } + if len(a.pendingCursor) != 0 { + t.Fatal("应用后应清空待办,避免重复覆盖用户的位置") + } +} + +// TestApplyPendingCursorRestores 正常位置要能原样恢复。 +func TestApplyPendingCursorRestores(t *testing.T) { + isolateConfig(t) + dir := t.TempDir() + a := &App{set: defaultSettings(), root: dir} + d := a.newDoc(filepath.Join(dir, "a.go"), "aaa\nbbb\nccc\n") + a.docs = append(a.docs, d) + + a.pendingCursor = []cursorRestore{{doc: d, cur: cursorJSON{Line: 1, Column: 2}}} + a.applyPendingCursor() + + pos := d.st.CursorPos() + if pos.Line != 1 || pos.Col != 2 { + t.Fatalf("位置没恢复: %+v", pos) + } +} + +// TestSessionCursorRoundTrip 会话文件里要能存下并读回光标位置。 +func TestSessionCursorRoundTrip(t *testing.T) { + isolateConfig(t) + root := t.TempDir() + path := filepath.Join(root, "a.go") + + a := &App{set: defaultSettings(), root: root} + d := a.newDoc(path, "package main\n\nfunc main() {}\n") + d.st.GoTo(editor.Pos{Line: 2, Col: 4}) + a.docs = append(a.docs, d) + a.active = path + a.saveSession() + + st, ok := loadSession(root) + if !ok { + t.Fatal("会话没写出来") + } + c, found := st.Cursors[path] + if !found { + t.Fatalf("会话里没有光标记录: %+v", st.Cursors) + } + if c.Line != 2 || c.Column != 4 { + t.Fatalf("位置不对: %+v", c) + } +} + +// TestSaveSessionSkipsTruncated 只读截断的大文件不记位置,没意义。 +func TestSaveSessionSkipsTruncated(t *testing.T) { + isolateConfig(t) + root := t.TempDir() + path := filepath.Join(root, "big.log") + + a := &App{set: defaultSettings(), root: root} + d := a.newDoc(path, "x\n") + d.truncated = true + a.docs = append(a.docs, d) + a.saveSession() + + st, ok := loadSession(root) + if !ok { + t.Fatal("会话没写出来") + } + if _, found := st.Cursors[path]; found { + t.Fatal("截断文件不该记录光标位置") + } +} diff --git a/internal/app/debug.go b/internal/app/debug.go new file mode 100644 index 0000000..d3c05a4 --- /dev/null +++ b/internal/app/debug.go @@ -0,0 +1,716 @@ +package app + +import ( + "crypto/sha1" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" + + "mygoland/internal/dap" +) + +// debugVar 是调试面板里显示的一个变量,Depth 是展开层级。 +type debugVar struct { + Name string + Type string + Value string + Ref int + Depth int + HasChildren bool +} + +// debugSession 是一次调试会话的状态。 +type debugSession struct { + mu sync.Mutex + client *dap.Client + + // 以下字段只在主线程读写。 + state string + thread int + frameID int + frames []dap.Frame + roots []debugVar + children map[int][]debugVar + expanded map[int]bool + loc *SourceLoc + started bool + // threads 是停点时拉到的 goroutine 列表(dlv dap 把 goroutine 当线程)。 + threads []dap.Thread + + // eval 绑定求值输入框,evalOut 是上次结果。 + eval string + evalOut string +} + +func (s *debugSession) setClient(c *dap.Client) { + s.mu.Lock() + s.client = c + s.mu.Unlock() +} + +func (s *debugSession) cl() *dap.Client { + s.mu.Lock() + defer s.mu.Unlock() + return s.client +} + +// ToggleBreakpoint 在某行切换断点,line 从 0 开始。 +func (a *App) ToggleBreakpoint(path string, line int) { + // gutter 传的是 0 起行号,内部统一用 1 起。 + a.toggleBreakpoint(path, line+1) +} + +// pushBreakpoints 把某个文件启用中的断点(含条件)发给调试适配器。 +func (a *App) pushBreakpoints(path string) { + if a.dbg == nil { + return + } + c := a.dbg.cl() + if c == nil { + return + } + var specs []dap.BreakpointSpec + for line, bp := range a.bps[path] { + if !bp.Enabled { + continue + } + specs = append(specs, dap.BreakpointSpec{Line: line, Condition: bp.Cond}) + } + sort.Slice(specs, func(i, j int) bool { return specs[i].Line < specs[j].Line }) + p := path + go func() { _, _ = c.SetBreakpoints(p, specs) }() +} + +// sortInts 对断点行号排序。 +func sortInts(xs []int) { + for i := 1; i < len(xs); i++ { + for j := i; j > 0 && xs[j] < xs[j-1]; j-- { + xs[j], xs[j-1] = xs[j-1], xs[j] + } + } +} + +// StartDebug 启动调试会话。 +func (a *App) StartDebug() { + if a.root == "" || a.dbg != nil { + return + } + a.saveConfig() + a.panel = true + a.panelTab = 2 + if a.panelH < 200 { + a.panelH = 240 + } + s := &debugSession{ + state: "启动中…", + children: map[int][]debugVar{}, + expanded: map[int]bool{}, + } + a.dbg = s + a.appendOut("$ dlv dap") + a.win.Update(func() {}) + + cfg := a.activeCfg() + prog := strings.TrimSpace(cfg.Program) + if prog == "" { + prog = "." + } + args := strings.Fields(cfg.Args) + stopOnEntry := cfg.StopOnEntry + root := a.root + + go func() { + c, err := dap.Start(root, func(ev string, body json.RawMessage) { + a.win.Update(func() { a.onDebugEvent(ev, body) }) + }, logf) + if err != nil { + a.win.Update(func() { a.dbg = nil }) + a.alert("调试启动失败", err.Error()) + return + } + s.setClient(c) + if err := c.Initialize(); err != nil { + a.failDebug(s, err) + return + } + a.win.Update(func() { s.state = "构建中…" }) + if err := c.Launch(prog, args, stopOnEntry, 180*time.Second); err != nil { + a.failDebug(s, err) + return + } + a.win.Update(func() { + if a.dbg == s { + s.state = "运行中" + s.started = true + } + }) + }() +} + +// failDebug 结束一次启动失败的会话。 +func (a *App) failDebug(s *debugSession, err error) { + if c := s.cl(); c != nil { + c.Close() + } + a.win.Update(func() { + if a.dbg == s { + a.dbg = nil + } + }) + a.alert("调试失败", err.Error()) +} + +// StopDebug 结束调试会话。 +func (a *App) StopDebug() { + s := a.dbg + if s == nil { + return + } + c := s.cl() + a.dbg = nil + a.win.Update(func() {}) + if c != nil { + go c.Close() + } +} + +// DebugContinue 继续执行到下一个断点。 +func (a *App) DebugContinue() { a.debugStep("continue") } + +// DebugNext 步过。 +func (a *App) DebugNext() { a.debugStep("next") } + +// DebugStepIn 单步进入。 +func (a *App) DebugStepIn() { a.debugStep("stepIn") } + +// DebugStepOut 跳出。 +func (a *App) DebugStepOut() { a.debugStep("stepOut") } + +// debugStep 执行一个继续/单步动作。 +func (a *App) debugStep(kind string) { + s := a.dbg + if s == nil { + return + } + c := s.cl() + if c == nil || s.thread == 0 { + return + } + thread := s.thread + s.state = "运行中" + a.win.Update(func() {}) + go func() { + var err error + switch kind { + case "next": + err = c.Next(thread) + case "stepIn": + err = c.StepIn(thread) + case "stepOut": + err = c.StepOut(thread) + default: + err = c.Continue(thread) + } + if err != nil { + a.win.Update(func() { + if a.dbg == s { + s.state = "已暂停" + } + }) + } + }() +} + +// Evaluate 对输入框里的表达式求值。 +func (a *App) evaluate(s *debugSession) { + c := s.cl() + expr := strings.TrimSpace(s.eval) + if c == nil || s.frameID == 0 || expr == "" { + return + } + frame := s.frameID + go func() { + res, err := c.Evaluate(expr, frame) + a.win.Update(func() { + if a.dbg != s { + return + } + if err != nil { + s.evalOut = "错误:" + err.Error() + return + } + s.evalOut = res + }) + }() +} + +// onDebugEvent 处理调试适配器事件,在主线程执行。 +func (a *App) onDebugEvent(event string, body json.RawMessage) { + s := a.dbg + if s == nil { + return + } + switch event { + case "initialized": + // 适配器准备好接收断点,设完断点再让它继续。 + c := s.cl() + if c == nil { + return + } + type entry struct { + path string + specs []dap.BreakpointSpec + } + var entries []entry + for path, m := range a.bps { + var specs []dap.BreakpointSpec + for line, bp := range m { + if bp.Enabled { + specs = append(specs, dap.BreakpointSpec{Line: line, Condition: bp.Cond}) + } + } + if len(specs) == 0 { + continue + } + sort.Slice(specs, func(i, j int) bool { return specs[i].Line < specs[j].Line }) + entries = append(entries, entry{path, specs}) + } + go func() { + for _, e := range entries { + _, _ = c.SetBreakpoints(e.path, e.specs) + } + _ = c.ConfigurationDone() + }() + case "stopped": + var e struct { + Reason string `json:"reason"` + ThreadID int `json:"threadId"` + All bool `json:"allThreadsStopped"` + } + if err := json.Unmarshal(body, &e); err != nil { + return + } + s.thread = e.ThreadID + s.state = "已暂停" + // 新的一次停点,旧的展开状态作废。 + s.children = map[int][]debugVar{} + s.expanded = map[int]bool{} + if c := s.cl(); c != nil { + a.refreshDebugLocation(s, c, e.ThreadID) + } + case "continued": + s.state = "运行中" + case "output": + var e struct { + Category string `json:"category"` + Output string `json:"output"` + } + if err := json.Unmarshal(body, &e); err != nil { + return + } + for _, line := range strings.Split(strings.TrimRight(e.Output, "\n"), "\n") { + if line != "" { + a.appendOut(line) + } + } + case "terminated", "exited": + s.state = "已结束" + s.loc = nil + if c := s.cl(); c != nil { + go c.Close() + } + a.win.Update(func() { + if a.dbg == s { + a.dbg = nil + } + }) + } +} + +// refreshDebugLocation 取调用栈、变量与 goroutine 列表,并跳到停下的位置。 +func (a *App) refreshDebugLocation(s *debugSession, c *dap.Client, thread int) { + go func() { + frames, err := c.StackTrace(thread, 20) + if err != nil || len(frames) == 0 { + return + } + // goroutine 列表顺手一起拉:停点时最准,运行中拉它没意义。 + gs, _ := c.Threads() + top := frames[0] + var roots []debugVar + if scopes, err := c.Scopes(top.ID); err == nil { + for _, sc := range scopes { + if sc.Expensive || sc.VariablesReference == 0 { + continue + } + vs, err := c.Variables(sc.VariablesReference) + if err != nil { + continue + } + for _, v := range vs { + roots = append(roots, debugVar{ + Name: v.Name, + Type: typeName(v.Type), + Value: v.Value, + Ref: v.VariablesReference, + HasChildren: v.VariablesReference > 0, + }) + } + } + } + a.win.Update(func() { + if a.dbg != s { + return + } + s.frames = frames + s.roots = roots + s.threads = gs + s.frameID = top.ID + if top.Source.Path == "" { + return + } + loc := &SourceLoc{Path: top.Source.Path, Line: top.Line, Col: top.Column} + s.loc = loc + if d, err := a.loadDoc(loc.Path); err == nil { + line := loc.Line - 1 + if line >= 0 && line < d.buf.LineCount() { + d.st.GoTo(editor.Pos{Line: line, Col: 0}) + d.st.ScrollTo(line) + } + } + }) + }() +} + +// debugSwitchThread 把当前的 goroutine 换成指定那条, +// 调用栈 / 变量 / 停点位置全部跟着切。 +func (a *App) debugSwitchThread(s *debugSession, id int) { + c := s.cl() + if c == nil { + return + } + s.thread = id + // 换了 goroutine,旧展开状态没意义了。 + s.children = map[int][]debugVar{} + s.expanded = map[int]bool{} + a.refreshDebugLocation(s, c, id) + a.refresh() +} + +// typeName 在类型缺失时补一个占位。 +func typeName(s string) string { + if s == "" { + return "?" + } + return s +} + +// toggleVar 展开或收起一个变量。 +func (a *App) toggleVar(s *debugSession, v debugVar) { + if !v.HasChildren { + return + } + if s.expanded[v.Ref] { + delete(s.expanded, v.Ref) + a.win.Update(func() {}) + return + } + c := s.cl() + if c == nil { + return + } + go func() { + vs, err := c.Variables(v.Ref) + if err != nil { + return + } + children := make([]debugVar, 0, len(vs)) + for _, x := range vs { + children = append(children, debugVar{ + Name: x.Name, + Type: typeName(x.Type), + Value: x.Value, + Ref: x.VariablesReference, + HasChildren: x.VariablesReference > 0, + }) + } + a.win.Update(func() { + if a.dbg != s { + return + } + s.children[v.Ref] = children + s.expanded[v.Ref] = true + }) + }() +} + +// visibleVars 把变量按展开状态铺平。 +func (a *App) visibleVars(s *debugSession) []debugVar { + var out []debugVar + var walk func(vars []debugVar, depth int) + walk = func(vars []debugVar, depth int) { + for _, v := range vars { + v.Depth = depth + out = append(out, v) + if v.HasChildren && s.expanded[v.Ref] { + walk(s.children[v.Ref], depth+1) + } + } + } + walk(s.roots, 0) + return out +} + +// decorate 把断点、测试函数标记与当前执行行画到编辑器上。 +func (a *App) decorate(d *Doc) { + // 每帧顺手看一下要不要留自动快照(内部有节流,代价很小)。 + a.maybeAutoSnapshot(d) + var marks []editor.GutterMark + bpLines := map[int]bool{} + for line, bp := range a.bps[d.path] { + color := a.th.Danger + if !bp.Enabled { + // 禁用的断点画成灰的,一眼能看出它不生效。 + color = a.th.TextMuted + } + marks = append(marks, editor.GutterMark{Line: line - 1, Color: color}) + bpLines[line-1] = true + } + + // 测试函数行给个青点:这行能直接跑(运行菜单「运行光标处的测试」/ + // 测试树里的「重跑」)。行号缓存按缓冲区版本失效,只在文件变动时重扫。 + if d.testFuncs == nil || d.testVer != d.buf.Version() { + d.testVer = d.buf.Version() + d.testFuncs = map[int]string{} + for _, f := range scanTestFuncs(d.buf.String()) { + d.testFuncs[f.Line] = f.Name + } + } + for line := range d.testFuncs { + if !bpLines[line] { + marks = append(marks, editor.GutterMark{Line: line, Color: a.th.Accent}) + } + } + d.st.GutterMarks = marks + + // 行底色有两个来源:覆盖率的绿/红,和调试器停在的那一行。 + // 这里必须合并——早先直接赋值会把覆盖率的着色擦掉。 + bgs := append([]editor.LineBackground(nil), d.coverBG...) + if a.dbg != nil && a.dbg.loc != nil && samePath(a.dbg.loc.Path, d.path) { + bgs = append(bgs, editor.LineBackground{ + First: a.dbg.loc.Line - 1, + Last: a.dbg.loc.Line - 1, + Color: ui.RGBA(63, 191, 174, 0.20), + }) + } + d.st.LineBackgrounds = bgs +} + +// samePath 比较两个路径是否指向同一文件。 +func samePath(a, b string) bool { + return strings.EqualFold(strings.ReplaceAll(a, "/", "\\"), strings.ReplaceAll(b, "/", "\\")) +} + +// debugView 是面板里的「调试」页签。 +func (a *App) debugView(c *ui.Context) { + t := c.Theme() + ui.Column(c).FillHeight().Children(func() { + a.debugConfigRow(c) + s := a.dbg + if s == nil { + ui.Column(c).Grow(1).Center().Children(func() { + ui.Text(c, "按 Shift+F9 开始调试").FontSize(12).TextColor(t.TextMuted) + }) + return + } + ui.Row(c).Padding(2, 8).Gap(6).AlignItems(ui.Center).Children(func() { + ui.Text(c, s.state).FontSize(11).TextColor(t.TextMuted) + ui.Box(c).Grow(1) + if iconButton(c, "continue", "继续", "继续 F9", t.Accent) { + a.DebugContinue() + } + if iconButton(c, "over", "步过", "步过 F8", t.TextMuted) { + a.DebugNext() + } + if iconButton(c, "into", "单步", "单步进入 F7", t.TextMuted) { + a.DebugStepIn() + } + if iconButton(c, "out", "跳出", "跳出 Shift+F8", t.TextMuted) { + a.DebugStepOut() + } + if iconButton(c, "stop", "停止", "停止调试 Ctrl+F2", t.Danger) { + a.StopDebug() + } + }) + a.debugEvalRow(c, s) + ui.Scroll(c).Grow(1).Children(func() { + ui.Column(c).Padding(2, 10).Gap(1).Children(func() { + if len(s.frames) > 0 { + ui.Text(c, "调用栈").FontSize(11).Bold().TextColor(t.TextMuted) + for i, f := range s.frames { + name := f.Name + if i == 0 { + name = "▸ " + name + } + ui.Textf(c, "%s %s:%d", name, baseName(f.Source.Name), f.Line). + FontSize(12).TextColor(condColor(t, i == 0)).SingleLine() + } + ui.Box(c).Height(6) + } + // goroutine 列表:并发程序只看当前线程栈等于没法调。 + // 点一条就把调用栈和变量切到它上面;当前条高亮。 + if len(s.threads) > 0 { + ui.Textf(c, "goroutine(%d,点一条切换)", len(s.threads)). + FontSize(11).Bold().TextColor(t.TextMuted) + const maxGS = 100 + for i, g := range s.threads { + if i >= maxGS { + ui.Textf(c, "…还有 %d 个未列出", len(s.threads)-maxGS). + FontSize(10).TextColor(t.TextMuted).SingleLine() + break + } + g := g + cur := g.ID == s.thread + row := ui.ButtonBase(c).FillWidth().Padding(0, 2).Radius(3). + Justify(ui.Start).Cursor(ui.CursorPointer) + if cur { + row = row.Background(t.Accent.Alpha(0.16)) + } + row.Children(func() { + fg := t.Text + if cur { + fg = t.Accent + } + ui.Textf(c, "▸ #%d %s", g.ID, g.Name). + FontSize(12).TextColor(fg).SingleLine() + }) + if row.Clicked() { + a.debugSwitchThread(s, g.ID) + } + } + ui.Box(c).Height(6) + } + vs := a.visibleVars(s) + if len(vs) > 0 { + ui.Text(c, "变量").FontSize(11).Bold().TextColor(t.TextMuted) + for _, v := range vs { + a.varRow(c, s, v) + } + } + if len(s.frames) == 0 && len(vs) == 0 { + ui.Text(c, "等待程序暂停…").FontSize(12).TextColor(t.TextMuted) + } + }) + }) + }) +} + +// debugConfigRow 是调试配置:程序包、参数、启动即停。 +func (a *App) debugConfigRow(c *ui.Context) { + t := c.Theme() + ui.Row(c).Padding(2, 8).Gap(6).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + ui.Text(c, "配置").FontSize(11).TextColor(t.TextMuted) + names := a.cfgNames() + pick := a.activeCfg().Name + if ui.Select(c, &pick, names).Changed() { + for i, n := range names { + if n == pick { + a.cfgs.Active = i + a.saveConfig() + break + } + } + } + if ui.Button(c, "编辑…").Clicked() { + a.OpenRunConfigs() + } + ui.Box(c).Grow(1) + cur := a.activeCfg() + ui.Textf(c, "包 %s · 参数 %s", cur.Program, orDash(cur.Args)).FontSize(10).TextColor(t.TextMuted) + }) +} + +// debugEvalRow 是表达式求值输入。 +func (a *App) debugEvalRow(c *ui.Context, s *debugSession) { + t := c.Theme() + ui.Row(c).Padding(2, 8).Gap(6).AlignItems(ui.Center).Children(func() { + ui.Text(c, "求值").FontSize(11).TextColor(t.TextMuted) + in := ui.TextInput(c, &s.eval).Placeholder("局部变量名或表达式,回车执行").Width(240) + if in.Submitted() { + a.evaluate(s) + } + if ui.Button(c, "执行").Clicked() { + a.evaluate(s) + } + if s.evalOut != "" { + ui.Text(c, s.evalOut).FontSize(12).TextColor(t.Accent).SingleLine() + } + }) +} + +// varRow 画一个变量,可展开的带三角标记。 +func (a *App) varRow(c *ui.Context, s *debugSession, v debugVar) { + t := c.Theme() + marker := " " + if v.HasChildren { + if s.expanded[v.Ref] { + marker = "▾ " + } else { + marker = "▸ " + } + } + text := strings.Repeat(" ", v.Depth) + marker + v.Name + " " + v.Type + " = " + v.Value + row := ui.ButtonBase(c).Padding(0, 2).Children(func() { + ui.Text(c, text).FontSize(12).TextColor(t.Text).SingleLine() + }) + if v.HasChildren && row.Clicked() { + a.toggleVar(s, v) + } +} + +// condColor 让当前栈帧更醒目。 +func condColor(t *ui.Theme, top bool) ui.Color { + if top { + return t.Text + } + return t.TextMuted +} + +// baseName 返回文件名。 +func baseName(p string) string { + p = strings.TrimRight(p, `/\`) + if i := strings.LastIndexAny(p, `/\`); i >= 0 { + return p[i+1:] + } + return p +} + +// debugTabLabel 返回调试页签的标题。 +func (a *App) debugTabLabel() string { + if a.dbg == nil { + return "调试" + } + if a.dbg.state == "已暂停" { + return "调试 · 暂停" + } + return "调试 · 运行" +} + +// configPath 返回当前工作区配置文件的路径。 +func (a *App) configPath() string { + base, err := os.UserConfigDir() + if err != nil || a.root == "" { + return "" + } + sum := sha1.Sum([]byte(strings.ToLower(a.root))) + return filepath.Join(base, "mygoland", fmt.Sprintf("run-%x.json", sum[:6])) +} diff --git a/internal/app/debug_test.go b/internal/app/debug_test.go new file mode 100644 index 0000000..9e8070c --- /dev/null +++ b/internal/app/debug_test.go @@ -0,0 +1,78 @@ +package app + +import "testing" + +func TestVisibleVarsFlatten(t *testing.T) { + s := &debugSession{ + children: map[int][]debugVar{ + 10: { + {Name: "X", Type: "int", Value: "1", Ref: 0}, + {Name: "Y", Type: "string", Value: "\"a\"", Ref: 11, HasChildren: true}, + }, + 11: { + {Name: "len", Type: "int", Value: "1"}, + }, + }, + expanded: map[int]bool{}, + roots: []debugVar{ + {Name: "n", Type: "int", Value: "0"}, + {Name: "s", Type: "struct", Value: "{...}", Ref: 10, HasChildren: true}, + }, + } + a := &App{} + + got := a.visibleVars(s) + if len(got) != 2 { + t.Fatalf("未展开时应只有 2 个根变量,实际 %d: %+v", len(got), got) + } + if got[0].Name != "n" || got[0].Depth != 0 { + t.Fatalf("第一个变量异常: %+v", got[0]) + } + + s.expanded[10] = true + got = a.visibleVars(s) + if len(got) != 4 { + t.Fatalf("展开一层后应有 4 行,实际 %d: %+v", len(got), got) + } + if got[2].Name != "X" || got[2].Depth != 1 { + t.Fatalf("子变量缩进不对: %+v", got[2]) + } + if got[3].Name != "Y" || got[3].Depth != 1 { + t.Fatalf("子变量缩进不对: %+v", got[3]) + } + + s.expanded[11] = true + got = a.visibleVars(s) + if len(got) != 5 { + t.Fatalf("展开两层后应有 5 行,实际 %d: %+v", len(got), got) + } + if got[4].Name != "len" || got[4].Depth != 2 { + t.Fatalf("二级缩进不对: %+v", got[4]) + } +} + +func TestSortInts(t *testing.T) { + xs := []int{9, 3, 12, 3} + sortInts(xs) + want := []int{3, 3, 9, 12} + for i := range want { + if xs[i] != want[i] { + t.Fatalf("排序结果 %v,期望 %v", xs, want) + } + } +} + +func TestSkipFile(t *testing.T) { + cases := map[string]bool{ + "__debug_bin.exe": true, + "__debug_bin123.exe": true, + "main.go": false, + "app.exe": true, + "greeter_test.go": false, + } + for name, want := range cases { + if got := skipFile(name); got != want { + t.Fatalf("skipFile(%q) = %v,期望 %v", name, got, want) + } + } +} diff --git a/internal/app/diff.go b/internal/app/diff.go new file mode 100644 index 0000000..e2cf6cb --- /dev/null +++ b/internal/app/diff.go @@ -0,0 +1,175 @@ +package app + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" + + "mygoland/internal/git" +) + +// 差异视图:把「HEAD 里的版本」和「现在编辑器里的内容」并排比。 +// +// 用编辑器自带的 DiffView,不自己算差异。New 侧直接引用已打开文档的缓冲区, +// 所以未保存的改动也能看到——这比 git diff 更有用:git 只认已经落盘的。 + +// diffView 是差异视图的状态。 +type diffView struct { + open bool + path string + // title 是标题栏上的说明,为空时显示「左:HEAD 右:编辑器」。 + title string + st editor.DiffState +} + +// OpenDiff 打开某个文件的差异视图;不给路径就用当前文件。 +func (a *App) OpenDiff(path string) { + if path == "" { + d := a.doc() + if d == nil { + a.alert("查看差异", "先打开一个文件。") + return + } + path = d.path + } + if a.root == "" { + a.alert("查看差异", "当前没有打开工作区。") + return + } + + // 新侧:已打开就用缓冲区(含未保存改动),否则读磁盘。 + var nw *editor.Buffer + if d := a.find(path); d != nil { + nw = d.buf + } else { + data, err := os.ReadFile(path) + if err != nil { + a.alert("查看差异", err.Error()) + return + } + text, _, ok := decodeFile(data) + if !ok { + a.alert("查看差异", "无法识别这个文件的编码。") + return + } + nw = editor.NewBuffer(text) + } + + // 旧侧:HEAD 里的内容。新文件取不到,当成空文本。 + oldText, err := git.ShowFile(a.root, path) + if err != nil { + oldText = "" + } + ob := editor.NewBuffer(oldText) + + // 两侧都按文件后缀上高亮,diff 里也有颜色。 + lang := filepath.Base(path) + nw.SetLanguage(editor.LanguageFor(lang)) + ob.SetLanguage(editor.LanguageFor(lang)) + + font, lh, tab, _, _ := a.editorSettings() + a.diff = diffView{ + open: true, + path: path, + st: editor.DiffState{ + Old: ob, + New: nw, + Layout: editor.DiffSplit, + Inline: editor.DiffInlineWordAlt, + Indicators: editor.DiffBars, + ContextLines: 3, + Font: font, + LineHeight: lh, + TabSize: tab, + Theme: codeTheme(a.light), + }, + } + a.win.Update(func() {}) +} + +// CloseDiff 关掉差异视图。 +func (a *App) CloseDiff() { + a.diff.open = false + a.refresh() +} + +// diffActive 供编辑器区判断是否要让位给差异视图。 +func (a *App) diffActive() bool { return a.diff.open } + +// renderDiff 画差异视图:顶部一条标题栏,下面是并排对比。 +func (a *App) renderDiff(c *ui.Context) { + t := c.Theme() + rel := a.diff.path + if r, err := filepath.Rel(a.root, a.diff.path); err == nil { + rel = filepath.ToSlash(r) + } + // 左右两栏分别是什么,写在标题栏上:不然用户分不清哪边是历史、哪边是现在。 + left := "HEAD" + right := "编辑器" + if a.diff.title != "" { + if i := strings.Index(a.diff.title, "↔"); i >= 0 { + left = strings.TrimSpace(a.diff.title[:i]) + right = strings.TrimSpace(strings.SplitN(a.diff.title[i:], "·", 2)[0]) + right = strings.TrimSpace(strings.TrimPrefix(right, "↔")) + } + } + + ui.Column(c).Fill().Children(func() { + ui.Row(c).Padding(5, 10).Gap(8).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + // 「差异」做成小胶囊,和文件名分开,视觉上不再是一行平铺的字。 + ui.Row(c).Padding(1, 6).Radius(3).Background(t.Accent.Alpha(0.16)). + Children(func() { + ui.Text(c, "差异").FontSize(10).TextColor(t.Accent) + }) + ui.Text(c, rel).FontSize(12).Bold().TextColor(t.Text).SingleLine() + ui.Textf(c, "%s ↔ %s", left, right).FontSize(10). + TextColor(t.TextMuted).SingleLine() + ui.Box(c).Grow(1) + if ui.Button(c, "关闭").Clicked() { + a.CloseDiff() + } + }) + + editor.DiffView(c, &a.diff.st).Fill() + }) +} + +// diffStatText 返回「+3 −1」这样的改动摘要,给状态栏用。 +// +// 只查 refreshGit 缓存下来的表:状态栏每帧都要画,不能在这里起 git 进程。 +func (a *App) diffStatText(path string) string { + if len(a.gst.stats) == 0 || a.root == "" { + return "" + } + rel, err := filepath.Rel(a.root, path) + if err != nil { + return "" + } + n, ok := a.gst.stats[filepath.ToSlash(rel)] + if !ok || (n[0] == 0 && n[1] == 0) { + return "" + } + return fmt.Sprintf("+%d −%d", n[0], n[1]) +} + +// currentTextOf 取一个文件「现在」的内容:打开了就用缓冲区(含未保存改动), +// 没打开就读磁盘。 +func (a *App) currentTextOf(path string) string { + if d := a.find(path); d != nil { + return d.buf.String() + } + data, err := os.ReadFile(path) + if err != nil { + return "" + } + text, _, ok := decodeFile(data) + if !ok { + return "" + } + return text +} diff --git a/internal/app/editcmd.go b/internal/app/editcmd.go new file mode 100644 index 0000000..f7680aa --- /dev/null +++ b/internal/app/editcmd.go @@ -0,0 +1,27 @@ +package app + +import "github.com/egoist/mygo/ui/editor" + +// RunEditorCmd 把编辑器命令转给当前文档。 +// +// 折叠、查找这些都是编辑器自带的能力(`Fold/FoldAll/Find/FindReplace`…), +// 应用层只负责把菜单和快捷键接到当前文档的 State 上。 +func (a *App) RunEditorCmd(cmd editor.Command) { + a.pendingCmd = cmd + a.win.Update(func() {}) +} + +// runPendingCmd 在渲染帧里执行挂起的编辑器命令。 +// +// 按键派发过程中调 Run 会被编辑器按重入拒掉(内部有 retry), +// 所以快捷键只负责记下要做什么,真正执行放到这里。 +func (a *App) runPendingCmd(d *Doc) { + cmd := a.pendingCmd + if cmd == editor.NoCommand || d == nil || d.st == nil { + return + } + a.pendingCmd = editor.NoCommand + // 渲染帧里同样不能直接 Run(编辑器认为它正在用), + // 推到 UI 线程的下一轮再执行。 + go a.win.Update(func() { d.st.Run(cmd) }) +} diff --git a/internal/app/encoding.go b/internal/app/encoding.go new file mode 100644 index 0000000..75fc174 --- /dev/null +++ b/internal/app/encoding.go @@ -0,0 +1,141 @@ +package app + +import ( + "bytes" + "strings" + "unicode/utf8" + + "golang.org/x/text/encoding/simplifiedchinese" + "golang.org/x/text/transform" +) + +// fileEncoding 是文件在磁盘上的编码。 +// +// 编辑器内部一律用 UTF-8,所以在读入时解码、写回时按原编码编码, +// 这样打开 GBK 的配置文件改完保存后,别的老系统仍然读得懂。 +type fileEncoding int + +const ( + encUTF8 fileEncoding = iota + encUTF8BOM + encUTF16LE + encUTF16BE + encGBK +) + +// encName 返回给人看的编码名,状态栏用。 +func encName(e fileEncoding) string { + switch e { + case encUTF8BOM: + return "UTF-8 BOM" + case encUTF16LE: + return "UTF-16 LE" + case encUTF16BE: + return "UTF-16 BE" + case encGBK: + return "GBK" + } + return "UTF-8" +} + +// decodeFile 把磁盘上的字节解成 UTF-8 文本,同时报告原编码。 +// +// 判断顺序:BOM → 合法 UTF-8 → GB18030。前两步都是确定性的; +// 最后一步是推测,只在「不是 UTF-8」时才走,因为中文 Windows 上 +// 的老配置、SQL 脚本基本都是 GBK。 +func decodeFile(data []byte) (string, fileEncoding, bool) { + switch { + case bytes.HasPrefix(data, []byte{0xEF, 0xBB, 0xBF}): + return string(data[3:]), encUTF8BOM, true + case bytes.HasPrefix(data, []byte{0xFF, 0xFE}): + return decodeUTF16(data[2:], false), encUTF16LE, true + case bytes.HasPrefix(data, []byte{0xFE, 0xFF}): + return decodeUTF16(data[2:], true), encUTF16BE, true + } + if utf8.Valid(data) { + return string(data), encUTF8, true + } + // 不是合法 UTF-8:按 GB18030 解(GBK 的超集)。 + // 解出来没有替换字符才认,否则说明这文件本来就不是文本。 + text, _, err := transform.Bytes(simplifiedchinese.GB18030.NewDecoder(), data) + if err == nil && !strings.ContainsRune(string(text), utf8.RuneError) { + return string(text), encGBK, true + } + return string(data), encUTF8, false +} + +// decodeUTF16 手工拼 UTF-16:x/text 的 unicode 包要额外引入, +// 这里只需要处理 BOM 之后的主体,简单几行就够。 +func decodeUTF16(b []byte, bigEndian bool) string { + var sb strings.Builder + sb.Grow(len(b) / 2) + for i := 0; i+1 < len(b); i += 2 { + var u uint16 + if bigEndian { + u = uint16(b[i])<<8 | uint16(b[i+1]) + } else { + u = uint16(b[i+1])<<8 | uint16(b[i]) + } + if u >= 0xD800 && u <= 0xDBFF && i+3 < len(b) { + var lo uint16 + if bigEndian { + lo = uint16(b[i+2])<<8 | uint16(b[i+3]) + } else { + lo = uint16(b[i+3])<<8 | uint16(b[i+2]) + } + if lo >= 0xDC00 && lo <= 0xDFFF { + r := 0x10000 + (rune(u-0xD800) << 10) + rune(lo-0xDC00) + sb.WriteRune(r) + i += 2 + continue + } + } + sb.WriteRune(rune(u)) + } + return sb.String() +} + +// encodeFile 把 UTF-8 文本按指定编码写回磁盘。 +func encodeFile(text string, enc fileEncoding) ([]byte, error) { + switch enc { + case encUTF8BOM: + return append([]byte{0xEF, 0xBB, 0xBF}, []byte(text)...), nil + case encGBK: + out, _, err := transform.Bytes(simplifiedchinese.GB18030.NewEncoder(), []byte(text)) + if err != nil { + // 有 GBK 表示不了的字符(比如 emoji)就退回 UTF-8, + // 总比写出一堆问号强。 + return []byte(text), nil + } + return out, nil + case encUTF16LE, encUTF16BE: + buf := make([]byte, 0, len(text)*2+2) + big := enc == encUTF16BE + if big { + buf = append(buf, 0xFE, 0xFF) + } else { + buf = append(buf, 0xFF, 0xFE) + } + for _, r := range text { + if r < 0x10000 { + u := uint16(r) + if big { + buf = append(buf, byte(u>>8), byte(u)) + } else { + buf = append(buf, byte(u), byte(u>>8)) + } + continue + } + r -= 0x10000 + hi := uint16(0xD800 + (r >> 10)) + lo := uint16(0xDC00 + (r & 0x3FF)) + if big { + buf = append(buf, byte(hi>>8), byte(hi), byte(lo>>8), byte(lo)) + } else { + buf = append(buf, byte(hi), byte(hi>>8), byte(lo), byte(lo>>8)) + } + } + return buf, nil + } + return []byte(text), nil +} diff --git a/internal/app/encoding_test.go b/internal/app/encoding_test.go new file mode 100644 index 0000000..e5c3b26 --- /dev/null +++ b/internal/app/encoding_test.go @@ -0,0 +1,218 @@ +package app + +import ( + "os" + "path/filepath" + "strings" + "testing" + "unicode/utf16" + + "golang.org/x/text/encoding/simplifiedchinese" + "golang.org/x/text/transform" +) + +func gbkBytes(t *testing.T, s string) []byte { + t.Helper() + out, _, err := transform.Bytes(simplifiedchinese.GB18030.NewEncoder(), []byte(s)) + if err != nil { + t.Fatal(err) + } + return out +} + +func TestDecodeUTF8(t *testing.T) { + text, enc, ok := decodeFile([]byte("package main\n// 中文注释\n")) + if !ok || enc != encUTF8 || !strings.Contains(text, "中文注释") { + t.Fatalf("UTF-8 识别失败: enc=%v ok=%v text=%q", enc, ok, text) + } +} + +func TestDecodeUTF8BOM(t *testing.T) { + raw := append([]byte{0xEF, 0xBB, 0xBF}, []byte("hello 世界")...) + text, enc, ok := decodeFile(raw) + if !ok || enc != encUTF8BOM { + t.Fatalf("BOM 没识别: enc=%v ok=%v", enc, ok) + } + if text != "hello 世界" { + t.Fatalf("BOM 没被去掉: %q", text) + } +} + +// TestDecodeGBK 中文 Windows 上的老配置文件基本是 GBK。 +func TestDecodeGBK(t *testing.T) { + want := "车号=湘H12345\r\n毛重=32.5 吨\r\n" + raw := gbkBytes(t, want) + if utf8Valid(raw) { + t.Skip("这段文本恰好也是合法 UTF-8,换个样本") + } + text, enc, ok := decodeFile(raw) + if !ok || enc != encGBK { + t.Fatalf("GBK 没识别: enc=%v ok=%v", enc, ok) + } + if text != want { + t.Fatalf("解码不对:\n got %q\nwant %q", text, want) + } +} + +func TestDecodeUTF16LE(t *testing.T) { + want := "SELECT * FROM ok_car\r\n" + units := utf16.Encode([]rune(want)) + raw := []byte{0xFF, 0xFE} + for _, u := range units { + raw = append(raw, byte(u), byte(u>>8)) + } + text, enc, ok := decodeFile(raw) + if !ok || enc != encUTF16LE { + t.Fatalf("UTF-16LE 没识别: enc=%v ok=%v", enc, ok) + } + if text != want { + t.Fatalf("解码不对: %q", text) + } +} + +func TestDecodeUTF16BE(t *testing.T) { + want := "重量" + units := utf16.Encode([]rune(want)) + raw := []byte{0xFE, 0xFF} + for _, u := range units { + raw = append(raw, byte(u>>8), byte(u)) + } + text, enc, ok := decodeFile(raw) + if !ok || enc != encUTF16BE || text != want { + t.Fatalf("UTF-16BE 解码失败: enc=%v ok=%v text=%q", enc, ok, text) + } +} + +// TestEncodeRoundTrip 每种编码都要能原样写回去。 +func TestEncodeRoundTrip(t *testing.T) { + cases := []struct { + text string + enc fileEncoding + }{ + {"package main\n", encUTF8}, + {"车号=湘H12345\n", encGBK}, + {"SELECT * FROM ok_car\n", encUTF16LE}, + {"重量 32.5 吨\n", encUTF16BE}, + {"// 注释\n", encUTF8BOM}, + } + for _, c := range cases { + raw, err := encodeFile(c.text, c.enc) + if err != nil { + t.Fatalf("%v 编码失败: %v", c.enc, err) + } + got, enc, ok := decodeFile(raw) + if !ok { + t.Fatalf("%v 回读失败", c.enc) + } + if enc != c.enc { + t.Fatalf("编码标记不对: got %v want %v", enc, c.enc) + } + if got != c.text { + t.Fatalf("%v 往返不一致:\n got %q\nwant %q", c.enc, got, c.text) + } + } +} + +// TestEncodeGBKEmoji GB18030 是 GBK 的超集,emoji 也能编码(4 字节), +// 所以这里要的是「往返不丢字」,而不是「退回 UTF-8」。 +func TestEncodeGBKEmoji(t *testing.T) { + want := "测试🎉" + raw, err := encodeFile(want, encGBK) + if err != nil { + t.Fatal(err) + } + got, enc, ok := decodeFile(raw) + if !ok || enc != encGBK { + t.Fatalf("回读失败: enc=%v ok=%v", enc, ok) + } + if got != want { + t.Fatalf("emoji 丢了: %q", got) + } +} + +func utf8Valid(b []byte) bool { + return strings.ToValidUTF8(string(b), "") == string(b) +} + +// TestWriteDocKeepsEncodingAndEOL 保存时要同时保住编码和换行。 +// +// 自动化输入打不进编辑器,所以这里直接构造文档来验证写回路径。 +func TestWriteDocKeepsEncodingAndEOL(t *testing.T) { + isolateConfig(t) + dir := t.TempDir() + path := filepath.Join(dir, "config.ini") + + // 原始文件:GBK + CRLF + raw := gbkBytes(t, "车号=湘H12345\r\n毛重=32.5 吨\r\n") + if err := os.WriteFile(path, raw, 0o644); err != nil { + t.Fatal(err) + } + + a := &App{set: defaultSettings(), root: dir} + text, enc, ok := decodeFile(raw) + if !ok { + t.Fatal("样本没解出来") + } + d := a.newDoc(path, text) + d.enc = enc + d.buf.SetLineEnding("\r\n") + + if err := writeDocFile(d); err != nil { + t.Fatalf("写入失败: %v", err) + } + + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if utf8Valid(got) { + t.Fatal("写回变成了 UTF-8,GBK 没保住") + } + back, _, ok := decodeFile(got) + if !ok { + t.Fatal("写回后解不出来") + } + if back != text { + t.Fatalf("内容不一致:\n got %q\nwant %q", back, text) + } + if !strings.Contains(string(got), "\r\n") { + t.Fatal("CRLF 丢了,保存后整个文件会显示成改动") + } +} + +// TestWriteDocLFStaysLF 原本是 LF 的文件不能被写成 CRLF。 +func TestWriteDocLFStaysLF(t *testing.T) { + isolateConfig(t) + dir := t.TempDir() + path := filepath.Join(dir, "a.go") + + a := &App{set: defaultSettings(), root: dir} + d := a.newDoc(path, "package main\n") + d.buf.SetLineEnding("\n") + if err := writeDocFile(d); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(path) + if strings.Contains(string(got), "\r\n") { + t.Fatalf("LF 被改成了 CRLF: %q", got) + } +} + +// TestReadOnlyDocRefusesSave 只读(截断打开)的文档不能写回,否则会丢内容。 +func TestReadOnlyDocRefusesSave(t *testing.T) { + isolateConfig(t) + dir := t.TempDir() + path := filepath.Join(dir, "big.log") + if err := os.WriteFile(path, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + a := &App{set: defaultSettings(), root: dir} + d := a.newDoc(path, "x") + d.st.ReadOnly = true + if err := writeDocFile(d); err == nil { + t.Fatal("只读文档不应该写入成功") + } + if got, _ := os.ReadFile(path); string(got) != "x" { + t.Fatalf("只读文档被改写了: %q", got) + } +} diff --git a/internal/app/fileicons.go b/internal/app/fileicons.go new file mode 100644 index 0000000..5b29c65 --- /dev/null +++ b/internal/app/fileicons.go @@ -0,0 +1,138 @@ +package app + +import ( + _ "embed" + "strings" + + "github.com/egoist/mygo/ui" +) + +// gopherPNG 是 Go 语言吉祥物的位图,用作 .go 文件的类型图标。 +// +// 不用应用自己的 logo:那是「MyGoland 的标识」,而文件树上的图标说的是 +// 「这是什么语言写的」,Go 源文件就该用语言本身的形象。图由 +// docs 里那张带 GOLANG 字样的图裁出并去掉白底,64×64 透明 PNG。 +// +//go:embed assets/gopher.png +var gopherPNG []byte + +// gopherIcon 是解码后的位图。视图每帧重建,解码只能做一次。 +var gopherIcon = func() ui.ImageSource { + b, err := ui.DecodeBitmap(gopherPNG) + if err != nil { + // 图标缺失不该影响文件树,退化成回落到矢量代码图标。 + logf("gopher 图标解码失败: %v", err) + return nil + } + return b +}() + +// 文件树的图标。mygo 的 TreeItem 只接受一段文字,挂不了图标,所以树行是 +// 自绘的(见 view.go 的 treeRow),这里只负责「给一个名字,返回画什么」。 +// +// 三个单色矢量图标都用 currentColor 填充,由 ui.Icon 的 TextColor 上色, +// 深浅主题自动跟随;只有 Go 文件用 gopher 位图——那个是彩色的吉祥物, +// 换成单色矢量反而认不出来。 +var ( + iconFolder = mustSVG(``) + iconFile = mustSVG(``) + iconCode = mustSVG(``) +) + +func mustSVG(s string) *ui.SVG { + v, err := ui.ParseSVG([]byte(s)) + if err != nil { + logf("解析图标失败: %v", err) + return nil + } + return v +} + +// fileIcon 在文件树的一行前面画上类型图标。 +func (a *App) fileIcon(c *ui.Context, name string, isDir bool) { + t := c.Theme() + lower := strings.ToLower(name) + + // Go 源码用语言吉祥物本身做图标。 + if !isDir && strings.HasSuffix(lower, ".go") { + if gopherIcon != nil { + ui.Image(c, gopherIcon).Size(14, 14) + return + } + } + + var svg *ui.SVG + var col ui.Color + switch { + case isDir: + svg, col = iconFolder, t.Accent + case lower == "go.mod", lower == "go.sum", strings.HasSuffix(lower, ".mod"), + strings.HasSuffix(lower, ".sum"): + svg, col = iconCode, ui.Hex(a.codeColor()) + case isCodeFile(lower): + svg, col = iconCode, ui.Hex(a.codeColor()) + case isConfigFile(lower): + svg, col = iconFile, t.Warning + case isImageFile(lower): + svg, col = iconFile, t.Success + case isDocFile(lower): + svg, col = iconFile, t.TextMuted + default: + svg, col = iconFile, t.TextMuted + } + + if svg == nil { + ui.Box(c).Size(14, 14) + return + } + ui.Icon(c, svg).Size(14, 14).TextColor(col) +} + +// codeColor 是源码类文件的图标色,深浅主题各一档,保证在两种底色上都跳得出来。 +func (a *App) codeColor() string { + if a.light { + return "#0969DA" + } + return "#61AFEF" +} + +func isCodeFile(l string) bool { + for _, ext := range []string{".php", ".js", ".mjs", ".cjs", ".ts", ".jsx", ".tsx", + ".vue", ".html", ".htm", ".css", ".scss", ".less", ".sql", ".sh", ".bat", ".ps1", + ".c", ".h", ".cpp", ".hpp", ".cs", ".java", ".kt", ".py", ".rb", ".rs"} { + if strings.HasSuffix(l, ext) { + return true + } + } + return false +} + +func isConfigFile(l string) bool { + for _, ext := range []string{".json", ".yaml", ".yml", ".toml", ".ini", ".conf", + ".xml", ".properties", ".env"} { + if strings.HasSuffix(l, ext) { + return true + } + } + return l == ".gitignore" || l == ".gitattributes" || l == "dockerfile" || l == "makefile" +} + +func isImageFile(l string) bool { + for _, ext := range []string{".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", + ".ico", ".svg"} { + if strings.HasSuffix(l, ext) { + return true + } + } + return false +} + +func isDocFile(l string) bool { + for _, ext := range []string{".md", ".markdown", ".txt", ".rst", ".pdf", ".doc", + ".docx", ".xls", ".xlsx", ".ppt", ".pptx"} { + if strings.HasSuffix(l, ext) { + return true + } + } + return false +} diff --git a/internal/app/fileops.go b/internal/app/fileops.go new file mode 100644 index 0000000..53a899a --- /dev/null +++ b/internal/app/fileops.go @@ -0,0 +1,267 @@ +package app + +import ( + "fmt" + "os" + "path/filepath" + "sort" + + "github.com/egoist/mygo" +) + +// selected 判断路径是否被选中。 +func (a *App) selected(path string) bool { return a.sel != nil && a.sel[path] } + +// selectOnly 只选中这一项(普通点击)。 +func (a *App) selectOnly(path string) { + a.sel = map[string]bool{path: true} + a.selAnchor = path +} + +// toggleSelect 切换某一项的选中状态(Ctrl 点击)。 +func (a *App) toggleSelect(path string) { + if a.sel == nil { + a.sel = map[string]bool{} + } + if a.sel[path] { + delete(a.sel, path) + } else { + a.sel[path] = true + } + a.selAnchor = path +} + +// selectRange 选中从基准项到当前项之间的全部(Shift 点击)。 +// 区间按「树里当前可见的顺序」算,折叠着的子树不参与。 +func (a *App) selectRange(path string) { + all := a.visiblePaths() + from, to := -1, -1 + for i, p := range all { + if samePath(p, a.selAnchor) { + from = i + } + if samePath(p, path) { + to = i + } + } + if from < 0 || to < 0 { + a.selectOnly(path) + return + } + if from > to { + from, to = to, from + } + a.sel = make(map[string]bool, to-from+1) + for _, p := range all[from : to+1] { + a.sel[p] = true + } +} + +// visiblePaths 按当前展开状态深度优先列出树上可见的项。 +func (a *App) visiblePaths() []string { + var out []string + var walk func(dir string) + walk = func(dir string) { + for _, e := range a.entries(dir) { + p := filepath.Join(dir, e.Name()) + if e.IsDir() { + if skipDir(e.Name()) { + continue + } + out = append(out, p) + if *a.openFlag(p) { + walk(p) + } + continue + } + if skipFile(e.Name()) { + continue + } + out = append(out, p) + } + } + if a.root != "" { + walk(a.root) + } + return out +} + +// targetsFor 返回一次操作要作用的路径:右键的那一行如果在选中集合里, +// 就作用于整个集合,否则只作用于它自己。 +func (a *App) targetsFor(path string) []string { + if a.sel[path] && len(a.sel) > 0 { + out := make([]string, 0, len(a.sel)) + for p := range a.sel { + out = append(out, p) + } + sort.Strings(out) + return out + } + return []string{path} +} + +// treeMenu 是文件树上的一行的右键菜单。 +func (a *App) treeEntries(path string, isDir bool) []menuEntry { + dir := path + if !isDir { + dir = filepath.Dir(path) + } + targets := a.targetsFor(path) + var out []menuEntry + + out = append(out, + menuEntry{label: "新建文件", action: func() { a.beginNew(dir, false) }}, + menuEntry{label: "新建文件夹", action: func() { a.beginNew(dir, true) }}, + menuEntry{divider: true}, + ) + + if !isDir && len(targets) == 1 { + out = append(out, menuEntry{label: "打开", action: func() { go a.OpenFile(path) }}) + } + // 多选时不做重命名:一次改一个更安全。 + if len(targets) == 1 { + out = append(out, menuEntry{label: "重命名…", action: func() { a.BeginRename(path, isDir) }}) + } + // 历史入口放在这里:右键一个文件看「它改过什么」是最自然的时机。 + if !isDir || len(targets) == 1 { + out = append(out, menuEntry{divider: true}) + out = append(out, menuEntry{ + label: "Git 历史…", + action: func() { a.OpenGitLog(path, isDir) }, + }) + out = append(out, menuEntry{ + label: "本地历史…", + action: func() { a.OpenHistoryAt(path, isDir) }, + }) + } + out = append(out, menuEntry{ + label: "在资源管理器中打开", + action: func() { mygo.Shell.ShowItemInFolder(path) }, + }) + out = append(out, menuEntry{divider: true}) + + del := "删除" + if len(targets) > 1 { + del = fmt.Sprintf("删除这 %d 项", len(targets)) + } + out = append(out, menuEntry{label: del, action: func() { a.deletePaths(targets) }}) + out = append(out, menuEntry{divider: true}) + out = append(out, menuEntry{label: "刷新文件树", action: func() { a.Refresh() }}) + return out +} + +// deletePaths 删除文件或目录。删目录用 RemoveAll,会连内容一起删掉, +// 所以先明确问一次,并列出数量。 +func (a *App) deletePaths(paths []string) { + if len(paths) == 0 || a.win == nil { + return + } + + what := "项目" + if len(paths) == 1 { + what = filepath.Base(paths[0]) + } + msg := fmt.Sprintf("确定删除 %s?\n此操作不可撤销。", what) + if len(paths) > 1 { + msg = fmt.Sprintf("确定删除选中的 %d 个项目?\n其中目录会连内容一起删除,此操作不可撤销。", len(paths)) + } + + res, err := mygo.Dialog.Message(mygo.MessageOptions{ + Parent: a.win, + Type: mygo.MessageWarning, + Title: "删除", + Message: msg, + Buttons: []string{"删除", "取消"}, + CancelButton: 1, + }) + if err != nil || res.Button != 0 { + return + } + + for _, p := range paths { + if err := os.RemoveAll(p); err != nil { + a.appendOut(err.Error()) + a.panel = true + } + } + + // 被删掉的文件如果开着,标签也要跟着关,否则编辑器指向一个不存在的路径。 + a.win.Update(func() { + var closed []string + for _, d := range a.docs { + if underAny(d.path, paths) { + closed = append(closed, d.path) + } + } + for _, p := range closed { + a.removeDoc(p) + } + }) + + a.sel = nil + a.selAnchor = "" + a.Refresh() + a.win.Update(func() {}) +} + +// underAny 判断 path 是否等于或位于 paths 里某一项之下。 +func underAny(path string, paths []string) bool { + clean := filepath.Clean(path) + for _, p := range paths { + base := filepath.Clean(p) + if samePath(clean, base) { + return true + } + if len(clean) > len(base) && samePath(clean[:len(base)], base) { + return true + } + } + return false +} + +// addEntries 是侧栏「+」按钮的菜单:在当前选中目录下新建。 +func (a *App) addEntries() []menuEntry { + dir := a.root + if len(a.sel) == 1 { + for p := range a.sel { + if st, err := os.Stat(p); err == nil { + if st.IsDir() { + dir = p + } else { + dir = filepath.Dir(p) + } + } + } + } + return []menuEntry{ + {label: "新建文件", action: func() { a.beginNew(dir, false) }}, + {label: "新建文件夹", action: func() { a.beginNew(dir, true) }}, + } +} + +// ExpandAll 展开文件树里所有目录,深度上限防止超大仓库卡死。 +func (a *App) ExpandAll() { + if a.root == "" { + return + } + if a.win == nil { + a.expandDir(a.root, 0) + return + } + a.win.Update(func() { a.expandDir(a.root, 0) }) +} + +// expandDir 递归把目录标记为展开。 +func (a *App) expandDir(dir string, depth int) { + if depth > 10 { + return + } + for _, e := range a.entries(dir) { + if !e.IsDir() || skipDir(e.Name()) { + continue + } + p := filepath.Join(dir, e.Name()) + *a.openFlag(p) = true + a.expandDir(p, depth+1) + } +} diff --git a/internal/app/git.go b/internal/app/git.go new file mode 100644 index 0000000..9e3fbda --- /dev/null +++ b/internal/app/git.go @@ -0,0 +1,284 @@ +package app + +import ( + "fmt" + "path/filepath" + "sort" + "strings" + + "github.com/egoist/mygo/ui" + + "mygoland/internal/git" +) + +// gitState 是界面用的 git 快照。 +type gitState struct { + info git.Info + // stats 是各文件相对 HEAD 的行数增减,键是仓库相对路径(正斜杠)。 + stats map[string][2]int + // at 是上次刷新的时间,避免连续保存时并发跑 git。 + busy bool +} + +// refreshGit 后台刷新一次仓库状态。 +func (a *App) refreshGit() { + if a.root == "" || a.gst.busy { + return + } + root := a.root + a.gst.busy = true + go func() { + info := git.Load(root) + // 顺手取一份行数增减,状态栏直接查表,不再每帧起进程。 + stats := git.Numstat(root) + a.win.Update(func() { + if a.root == root { + a.gst.info = info + a.gst.stats = stats + } + a.gst.busy = false + a.win.Update(func() {}) + }) + }() +} + +// gitColor 返回状态码对应的颜色。 +func (a *App) gitColor(code string) ui.Color { + t := a.th + switch code { + case "M": + return t.Warning + case "A", "R", "??": + return t.Success + case "D", "U": + return t.Danger + } + return t.Text +} + +// gitBadge 是文件后面那个小标记的文字。 +func gitBadge(code string) string { + switch code { + case "??": + return "U" + case "M", "A", "R", "D", "U": + return code + } + return "" +} + +// OpenCommit 打开提交弹窗。 +func (a *App) OpenCommit() { + if !a.gst.info.OK { + a.alert("Git", "当前工作区不是 git 仓库,或者没有安装 git") + return + } + if a.gst.info.Dirty == 0 { + a.alert("Git", "没有需要提交的改动") + return + } + // 文件清单按仓库相对路径排序;默认全选——大多数人多数时候 + // 就是想全提交,个别不该带的取消勾选就行。 + a.commitFiles = nil + a.commitSel = map[string]bool{} + for abs, code := range a.gst.info.Files { + rel, err := filepath.Rel(a.root, abs) + if err != nil { + continue + } + rel = filepath.ToSlash(rel) + a.commitFiles = append(a.commitFiles, rel) + a.commitSel[rel] = true + a.commitCode[rel] = code + } + sort.Strings(a.commitFiles) + a.commitOpen = true + a.commitMsg = "" + a.win.Update(func() {}) +} + +// commitChecked 统计勾选数。 +func (a *App) commitChecked() int { + n := 0 + for _, p := range a.commitFiles { + if a.commitSel[p] { + n++ + } + } + return n +} + +// commitDialog 画提交弹窗:文件清单可勾选,只提交勾选的。 +func (a *App) commitDialog(c *ui.Context) { + if !a.commitOpen { + return + } + t := c.Theme() + + ui.Modal(c, &a.commitOpen, func() { + ui.Column(c).Width(480).Gap(10).Children(func() { + ui.Text(c, "提交改动").FontSize(13).Bold().TextColor(t.Text) + ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { + ui.Textf(c, "%s · 勾选 %d / %d", a.gst.info.Branch, a.commitChecked(), len(a.commitFiles)). + FontSize(10).TextColor(t.TextMuted).SingleLine() + ui.Box(c).Grow(1) + if ui.Button(c, "全选").Clicked() { + for _, p := range a.commitFiles { + a.commitSel[p] = true + } + } + if ui.Button(c, "全不选").Clicked() { + for _, p := range a.commitFiles { + a.commitSel[p] = false + } + } + }) + + // 文件清单:清单可能很长,限高滚动,别把弹窗顶出屏幕。 + ui.Scroll(c).FillWidth().Height(220).Children(func() { + ui.Column(c).FillWidth().Gap(2).Children(func() { + for _, rel := range a.commitFiles { + p := rel + // map 索引取不了地址,用局部变量中转:控件点击后写回。 + checked := a.commitSel[p] + ui.Row(c).FillWidth().Gap(6).AlignItems(ui.Center).Children(func() { + ui.Checkbox(c, &checked, "") + ui.Text(c, gitBadge(a.commitCode[p])).FontSize(10). + TextColor(a.gitColor(a.commitCode[p])).Width(16) + ui.Text(c, filepath.Base(rel)).FontSize(12).TextColor(t.Text).SingleLine() + ui.Box(c).Grow(1) + dir := filepath.ToSlash(filepath.Dir(rel)) + if dir != "." { + ui.Text(c, dir).FontSize(10).TextColor(t.TextMuted).SingleLine() + } + }) + a.commitSel[p] = checked + } + }) + }) + + inp := ui.TextInput(c, &a.commitMsg).FillWidth().FontSize(13).AutoFocus() + if inp.Submitted() { + a.confirmCommit() + } + + ui.Row(c).Gap(8).Justify(ui.End).Children(func() { + if ui.Button(c, "取消").Clicked() { + a.commitOpen = false + } + if ui.Button(c, "提交").Clicked() { + a.confirmCommit() + } + }) + }) + }) + + if !a.commitOpen && a.commitDlg { + a.commitDlg = false + a.focusEditorSoon() + } + if !a.commitDlg && a.commitOpen { + a.commitDlg = true + a.win.Update(func() {}) + } +} + +// confirmCommit 只暂存勾选的文件,再提交;结果写进输出面板。 +func (a *App) confirmCommit() { + var paths []string + for _, p := range a.commitFiles { + if a.commitSel[p] { + paths = append(paths, p) + } + } + if len(paths) == 0 { + // 不关弹窗也不提交:空勾选多半是手滑,提醒比默默拒绝友好。 + a.alert("Git", "没有勾选任何文件") + return + } + msg := a.commitMsg + if msg == "" { + msg = "更新" + } + root := a.root + a.commitOpen = false + a.win.Update(func() {}) + go func() { + var out string + if err := git.StagePaths(root, paths); err != nil { + out = "git add 失败:" + err.Error() + } else if err := git.Commit(root, msg); err != nil { + out = "git commit 失败:" + err.Error() + } else { + out = fmt.Sprintf("已提交 %d 个文件:%s", len(paths), msg) + } + a.win.Update(func() { + kind := OutSuccess + if strings.HasPrefix(out, "git ") { + kind = OutError + } + a.out = append(a.out, OutLine{Text: out, Kind: kind}) + a.panel = true + a.panelTab = 0 + a.refreshGit() + a.win.Update(func() {}) + }) + }() +} + +// gitPull 拉取当前分支(--ff-only,分叉时拒绝合并)。 +func (a *App) gitPull() { + if !a.gst.info.OK { + a.alert("Git", "当前工作区不是 git 仓库,或者没有安装 git") + return + } + root := a.root + a.out = append(a.out, OutLine{Text: "git pull …", Kind: OutPlain}) + a.panel = true + a.panelTab = 0 + a.refresh() + go func() { + out, err := git.Pull(root) + a.gitOpDone("拉取", out, err) + }() +} + +// gitPush 推送当前分支(无上游时自动 -u origin <分支>)。 +func (a *App) gitPush() { + if !a.gst.info.OK { + a.alert("Git", "当前工作区不是 git 仓库,或者没有安装 git") + return + } + root := a.root + a.out = append(a.out, OutLine{Text: "git push …", Kind: OutPlain}) + a.panel = true + a.panelTab = 0 + a.refresh() + go func() { + out, err := git.Push(root) + a.gitOpDone("推送", out, err) + }() +} + +// gitOpDone 把 pull/push 的结果写进输出面板并刷新仓库状态。 +func (a *App) gitOpDone(op, out string, err error) { + a.win.Update(func() { + if err != nil { + text := op + "失败:" + err.Error() + if out != "" { + text += "\n" + out + } + a.out = append(a.out, OutLine{Text: text, Kind: OutError}) + } else { + text := op + "完成" + if out != "" { + text += "\n" + out + } + a.out = append(a.out, OutLine{Text: text, Kind: OutSuccess}) + } + a.panel = true + a.panelTab = 0 + a.refreshGit() + a.win.Update(func() {}) + }) +} diff --git a/internal/app/gitlog.go b/internal/app/gitlog.go new file mode 100644 index 0000000..b242eea --- /dev/null +++ b/internal/app/gitlog.go @@ -0,0 +1,10 @@ +package app + +// trimTo 把字符串截断到 n 个字符,历史列表里的标题用。 +func trimTo(s string, n int) string { + r := []rune(s) + if len(r) <= n { + return s + } + return string(r[:n]) + "…" +} diff --git a/internal/app/grep.go b/internal/app/grep.go new file mode 100644 index 0000000..0d5400c --- /dev/null +++ b/internal/app/grep.go @@ -0,0 +1,153 @@ +package app + +import ( + "os" + "path/filepath" + "sort" + "strings" + "sync" +) + +// 文件名索引与模糊匹配,供快速打开使用。 + +// indexState 是工作区文件索引。 +type indexState struct { + mu sync.Mutex + root string + files []string // 相对路径,正斜杠 + ready bool +} + +// buildIndex 在后台遍历工作区,收集可打开的文件。 +func (a *App) buildIndex(root string) { + go func() { + var files []string + _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { + if err != nil { + return nil + } + name := d.Name() + if d.IsDir() { + if p != root && skipDir(name) { + return filepath.SkipDir + } + return nil + } + if skipFile(name) { + return nil + } + rel, err := filepath.Rel(root, p) + if err != nil { + return nil + } + files = append(files, filepath.ToSlash(rel)) + if len(files) > 20000 { + return filepath.SkipAll + } + return nil + }) + sort.Strings(files) + a.index.mu.Lock() + if a.index.root == root { + a.index.files = files + a.index.ready = true + } + a.index.mu.Unlock() + }() +} + +// resetIndex 换工作区时清空索引。 +func (a *App) resetIndex(root string) { + a.index.mu.Lock() + a.index.root = root + a.index.files = nil + a.index.ready = false + a.index.mu.Unlock() +} + +// indexSnapshot 取当前索引的快照。 +func (a *App) indexSnapshot() ([]string, bool) { + a.index.mu.Lock() + defer a.index.mu.Unlock() + return a.index.files, a.index.ready +} + +// fuzzyScore 判断 query 是否为 path 的子序列,并给出一个分数(越大越靠前)。 +// +// 规则很朴素:连续匹配、匹配到文件名部分、匹配位置靠前,都会加分。 +func fuzzyScore(path, query string) (int, bool) { + if query == "" { + return 0, true + } + lp := strings.ToLower(path) + lq := strings.ToLower(query) + score := 0 + pi := 0 + prev := -2 + for qi := 0; qi < len(lq); qi++ { + c := lq[qi] + found := -1 + for ; pi < len(lp); pi++ { + if lp[pi] == c { + found = pi + break + } + } + if found < 0 { + return 0, false + } + // 连续匹配 + if found == prev+1 { + score += 8 + } else { + score += 2 + } + // 词边界(/ _ - . 之后)加分 + if found == 0 || strings.ContainsRune("/_-.\\.", rune(lp[found-1])) { + score += 6 + } + prev = found + pi = found + 1 + } + // 文件名里命中比目录里命中更值钱 + if base := lp[strings.LastIndexByte(lp, '/')+1:]; strings.Contains(base, lq) { + score += 20 + } + // 路径越短越靠前 + score -= len(path) / 4 + return score, true +} + +// quickResults 用索引算出快速打开的候选列表。 +func (a *App) quickResults(query string, limit int) []paletteItem { + files, _ := a.indexSnapshot() + type scored struct { + rel string + score int + } + var hits []scored + for _, rel := range files { + if s, ok := fuzzyScore(rel, query); ok { + hits = append(hits, scored{rel, s}) + } + } + sort.Slice(hits, func(i, j int) bool { + if hits[i].score != hits[j].score { + return hits[i].score > hits[j].score + } + return hits[i].rel < hits[j].rel + }) + if len(hits) > limit { + hits = hits[:limit] + } + out := make([]paletteItem, 0, len(hits)) + for _, h := range hits { + out = append(out, paletteItem{ + Path: filepath.Join(a.root, filepath.FromSlash(h.rel)), + Label: filepath.Base(h.rel), + Hint: filepath.Dir(h.rel), + Kind: itemFile, + }) + } + return out +} diff --git a/internal/app/history.go b/internal/app/history.go new file mode 100644 index 0000000..27b085c --- /dev/null +++ b/internal/app/history.go @@ -0,0 +1,417 @@ +package app + +import ( + "crypto/sha1" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" +) + +// 本地历史:把文件内容按时间点存到本机,和 git 无关。 +// +// 三个用途共用这一套存储: +// - 手动保存后留一个点(reason=save),误改能翻回去; +// - 有未保存改动时定时留点(reason=auto),崩溃后能捞回来; +// - 本地历史面板列出来给用户挑着恢复。 +// +// 同一个内容只存一份:文件名就是内容的 sha1,重复内容直接跳过。 + +const ( + // histKeep 是每个文件保留的快照条数。 + histKeep = 60 + // histMaxSize 是单文件快照的大小上限:超过就不存了, + // 免得把 40 MB 的日志每次保存都复制一份。 + histMaxSize = 4 << 20 +) + +// histEntry 是历史索引里的一条。 +type histEntry struct { + Time int64 `json:"time"` // 毫秒时间戳 + Hash string `json:"hash"` // 内容 sha1 的前 12 位,也是快照文件名 + Size int `json:"size"` // 字节数 + Reason string `json:"reason"` // save / auto / close + Dirty bool `json:"dirty"` // 存的时候是否还有未保存改动 +} + +// histIndex 是某个文件的历史索引。 +type histIndex struct { + Path string `json:"path"` + Entries []histEntry `json:"entries"` +} + +// histMu 串行化索引读写:多个文档同时保存会并发进来。 +var histMu sync.Mutex + +// historyDir 返回某个文件的历史目录(按绝对路径散列)。 +func historyDir(path string) string { + base := sessionDir() + if base == "" || path == "" { + return "" + } + sum := sha1.Sum([]byte(strings.ToLower(filepath.Clean(path)))) + return filepath.Join(base, "history", fmt.Sprintf("%x", sum[:6])) +} + +// saveSnapshot 给文件留一个历史点;内容没变时直接跳过。 +func saveSnapshot(path string, data []byte, reason string, dirty bool) error { + if len(data) == 0 || len(data) > histMaxSize { + return nil + } + dir := historyDir(path) + if dir == "" { + return nil + } + + histMu.Lock() + defer histMu.Unlock() + + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + sum := sha1.Sum(data) + hash := fmt.Sprintf("%x", sum[:12]) + snap := filepath.Join(dir, hash+".snap") + + idx, err := readHistIndex(dir) + if err != nil { + idx = histIndex{Path: path} + } + // 内容没变就不重复记:同一个 hash 说明和上一次存的一模一样。 + for _, e := range idx.Entries { + if e.Hash == hash { + return nil + } + } + if err := os.WriteFile(snap, data, 0o644); err != nil { + return err + } + idx.Path = path + idx.Entries = append(idx.Entries, histEntry{ + Time: time.Now().UnixMilli(), + Hash: hash, + Size: len(data), + Reason: reason, + Dirty: dirty, + }) + pruneHistory(dir, &idx) + return writeHistIndex(dir, idx) +} + +// readHistIndex 读索引,损坏时当成空的(历史丢了也不能影响正常编辑)。 +func readHistIndex(dir string) (histIndex, error) { + var idx histIndex + b, err := os.ReadFile(filepath.Join(dir, "index.json")) + if err != nil { + return idx, err + } + if err := json.Unmarshal(b, &idx); err != nil { + return histIndex{}, err + } + return idx, nil +} + +func writeHistIndex(dir string, idx histIndex) error { + b, err := json.MarshalIndent(idx, "", " ") + if err != nil { + return err + } + tmp := filepath.Join(dir, "index.json.tmp") + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + return os.Rename(tmp, filepath.Join(dir, "index.json")) +} + +// pruneHistory 只保留最近 histKeep 条,并把对应快照文件删掉。 +// 调用方必须持有 histMu。 +func pruneHistory(dir string, idx *histIndex) { + if len(idx.Entries) <= histKeep { + return + } + sort.Slice(idx.Entries, func(i, j int) bool { return idx.Entries[i].Time < idx.Entries[j].Time }) + drop := idx.Entries[:len(idx.Entries)-histKeep] + for _, e := range drop { + _ = os.Remove(filepath.Join(dir, e.Hash+".snap")) + } + idx.Entries = idx.Entries[len(idx.Entries)-histKeep:] +} + +// listHistory 返回某个文件的历史,最新的在前。 +func listHistory(path string) []histEntry { + dir := historyDir(path) + if dir == "" { + return nil + } + histMu.Lock() + defer histMu.Unlock() + idx, err := readHistIndex(dir) + if err != nil { + return nil + } + out := append([]histEntry(nil), idx.Entries...) + sort.Slice(out, func(i, j int) bool { return out[i].Time > out[j].Time }) + return out +} + +// readSnapshot 读出某条历史的内容。 +func readSnapshot(path, hash string) ([]byte, error) { + dir := historyDir(path) + if dir == "" { + return nil, fmt.Errorf("没有历史目录") + } + return os.ReadFile(filepath.Join(dir, hash+".snap")) +} + +// 崩溃恢复用:启动时如果发现上次是异常退出,把没存盘的内容捞回来。 + +// pendingPath 是「上次退出时有未保存改动」的标记文件。 +func pendingPath() string { + base := sessionDir() + if base == "" { + return "" + } + return filepath.Join(base, "pending.json") +} + +// pendingSnap 是待恢复的一条。 +type pendingSnap struct { + Path string `json:"path"` + Hash string `json:"hash"` + Time int64 `json:"time"` +} + +// markPending 记录「这些文件有未保存改动」,正常退出时清掉。 +func markPending(items []pendingSnap) { + p := pendingPath() + if p == "" { + return + } + if len(items) == 0 { + _ = os.Remove(p) + return + } + b, err := json.Marshal(items) + if err != nil { + return + } + // 首次运行时 mygoland 目录可能还不存在,先建出来。 + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return + } + if err := os.WriteFile(p, b, 0o644); err != nil { + logf("写入恢复标记失败:%v", err) + } +} + +// loadPending 读上次的未保存标记。 +func loadPending() []pendingSnap { + p := pendingPath() + if p == "" { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return nil + } + var items []pendingSnap + if err := json.Unmarshal(b, &items); err != nil { + return nil + } + return items +} + +// snapshotAsync 在后台给文档留一个历史点,失败只记日志。 +func (a *App) snapshotAsync(d *Doc, reason string, dirty bool) { + if d == nil || d.truncated || !a.set.History { + return + } + path := d.path + text := d.buf.String() + enc := d.enc + eol := d.buf.LineEnding() + d.lastSnapAt = time.Now().UnixMilli() + go func() { + data, err := encodeFile(applyEOL(text, eol), enc) + if err != nil { + return + } + if err := saveSnapshot(path, data, reason, dirty); err != nil { + logf("本地历史写入失败:%v", err) + } + }() +} + +// applyEOL 按原文件的换行写回,和保存时保持一致。 +func applyEOL(text, eol string) string { + if eol != "\r\n" { + return text + } + text = strings.ReplaceAll(text, "\r\n", "\n") + return strings.ReplaceAll(text, "\n", "\r\n") +} + +// maybeAutoSnapshot 在有未保存改动、且停手几秒后自动留一个点。 +// +// 只写历史、不动原文件:自动改磁盘风险更大,崩溃恢复靠 pending 兜底。 +func (a *App) maybeAutoSnapshot(d *Doc) { + if d == nil || d.st == nil || d.truncated || !a.set.History || !a.set.AutoSnapshot { + return + } + ver := d.buf.Version() + now := time.Now().UnixMilli() + if !d.buf.Modified() { + d.dirtyAt = 0 + d.dirtyVer = ver + return + } + if ver != d.dirtyVer { + d.dirtyVer = ver + d.dirtyAt = now + return + } + // 停手 4 秒以上、且距上次留点超过 1 分钟,才存一次。 + if d.dirtyAt == 0 || now-d.dirtyAt < 4000 || now-d.lastSnapAt < 60000 { + return + } + a.snapshotAsync(d, "auto", true) +} + +// snapshotDirtyOnExit 退出前把未保存的文档各存一份,并留下恢复标记。 +func (a *App) snapshotDirtyOnExit() { + var pending []pendingSnap + for _, d := range a.docs { + if d == nil || !d.buf.Modified() || d.truncated || !a.set.History { + continue + } + text := d.buf.String() + data, err := encodeFile(applyEOL(text, d.buf.LineEnding()), d.enc) + if err != nil { + continue + } + if err := saveSnapshot(d.path, data, "close", true); err != nil { + continue + } + sum := sha1.Sum(data) + pending = append(pending, pendingSnap{ + Path: d.path, + Hash: fmt.Sprintf("%x", sum[:12]), + Time: time.Now().UnixMilli(), + }) + } + markPending(pending) +} + +// collectPending 读上次没存盘的记录,只留当前工作区的。 +// +// 这一步要在切工作区时做,但**不能在这里弹窗**:OpenFolder 期间窗口 +// 还没就绪,模态框弹不出来。所以只记下来,等首帧之后再问。 +func (a *App) collectPending() { + a.pendingRestore = nil + items := loadPending() + if len(items) == 0 { + return + } + for _, it := range items { + if a.root == "" || within(a.root, it.Path) { + a.pendingRestore = append(a.pendingRestore, it) + } + } + // 已经消费掉的标记要清掉,免得下次又弹一遍。 + markPending(nil) + if len(a.pendingRestore) > 0 { + // 等窗口把第一帧画完再往里塞内容,否则编辑器还没建好。 + time.AfterFunc(600*time.Millisecond, a.restorePendingNow) + } +} + +// restorePendingNow 把上次没存盘的内容放回编辑器。 +// +// 不弹模态框询问:模态在启动阶段弹不出来(窗口还没就绪,非 UI 线程调用会失败), +// 而这一步的价值就是「别丢东西」。所以直接恢复到缓冲区——**不写盘**, +// 标签上会显示未保存标记,用户在运行面板也能看到说明,不要就 Ctrl+Z 或直接关闭。 +func (a *App) restorePendingNow() { + items := a.pendingRestore + a.pendingRestore = nil + if len(items) == 0 { + return + } + restored := 0 + for _, it := range items { + if _, err := os.Stat(it.Path); err != nil { + continue + } + data, err := readSnapshot(it.Path, it.Hash) + if err != nil { + continue + } + text, _, ok := decodeFile(data) + if !ok { + continue + } + d, err := a.loadDoc(it.Path) + if err != nil || d == nil { + continue + } + if d.buf.String() != text { + // 用 Set 而不是 Reset:Set 是「一次可撤销的编辑」, + // 缓冲区会处于已修改状态,用户能立刻看到「这段内容还没存盘」; + // Reset 会把它当成已保存文本,关掉就悄悄丢了。 + d.buf.Set(text) + restored++ + } + } + if restored == 0 { + return + } + a.appendOut(fmt.Sprintf("已恢复 %d 个上次未保存的文件(内容在编辑器里,尚未写盘,确认后请保存)。", restored)) + a.refresh() +} + +// histItem 是带文件路径的一条历史,目录聚合时用。 +type histItem struct { + Path string + histEntry +} + +// listHistoryUnder 列出某个目录下所有文件的历史,按时间倒序。 +// +// history 目录是按文件路径散列的,没法从目录名反推, +// 所以遍历每个 index.json,读里面记的原路径来筛。 +func listHistoryUnder(dir string) []histItem { + base := sessionDir() + if base == "" || dir == "" { + return nil + } + histRoot := filepath.Join(base, "history") + entries, err := os.ReadDir(histRoot) + if err != nil { + return nil + } + + histMu.Lock() + defer histMu.Unlock() + + var out []histItem + for _, e := range entries { + if !e.IsDir() { + continue + } + idx, err := readHistIndex(filepath.Join(histRoot, e.Name())) + if err != nil || idx.Path == "" { + continue + } + if !within(dir, idx.Path) { + continue + } + for _, en := range idx.Entries { + out = append(out, histItem{Path: idx.Path, histEntry: en}) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Time > out[j].Time }) + return out +} diff --git a/internal/app/history_test.go b/internal/app/history_test.go new file mode 100644 index 0000000..5e3a396 --- /dev/null +++ b/internal/app/history_test.go @@ -0,0 +1,124 @@ +package app + +import ( + "os" + "path/filepath" + "testing" +) + +// TestSnapshotAndList 保存后能列出,内容能读回来。 +func TestSnapshotAndList(t *testing.T) { + isolateConfig(t) + path := filepath.Join(t.TempDir(), "a.go") + + if err := saveSnapshot(path, []byte("package main\n"), "save", false); err != nil { + t.Fatal(err) + } + if err := saveSnapshot(path, []byte("package main\n// 改了\n"), "save", false); err != nil { + t.Fatal(err) + } + + items := listHistory(path) + if len(items) != 2 { + t.Fatalf("应有 2 条历史,实际 %d", len(items)) + } + // 最新的在前 + if items[0].Time < items[1].Time { + t.Fatal("应按时间倒序") + } + got, err := readSnapshot(path, items[0].Hash) + if err != nil { + t.Fatal(err) + } + if string(got) != "package main\n// 改了\n" { + t.Fatalf("内容不对: %q", got) + } +} + +// TestSnapshotDedup 内容没变不重复记:否则每按一次 Ctrl+S 就多一条。 +func TestSnapshotDedup(t *testing.T) { + isolateConfig(t) + path := filepath.Join(t.TempDir(), "a.go") + data := []byte("package main\n") + for i := 0; i < 5; i++ { + if err := saveSnapshot(path, data, "save", false); err != nil { + t.Fatal(err) + } + } + if n := len(listHistory(path)); n != 1 { + t.Fatalf("相同内容只该留一条,实际 %d", n) + } +} + +// TestSnapshotPrune 超过上限要裁掉最老的,并把快照文件删掉。 +func TestSnapshotPrune(t *testing.T) { + isolateConfig(t) + path := filepath.Join(t.TempDir(), "a.go") + for i := 0; i < histKeep+8; i++ { + data := []byte{byte('a' + i%26), byte(i)} + if err := saveSnapshot(path, data, "auto", true); err != nil { + t.Fatal(err) + } + } + items := listHistory(path) + if len(items) > histKeep { + t.Fatalf("应裁到 %d 条,实际 %d", histKeep, len(items)) + } + dir := historyDir(path) + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + snaps := 0 + for _, e := range entries { + if filepath.Ext(e.Name()) == ".snap" { + snaps++ + } + } + if snaps > histKeep { + t.Fatalf("快照文件没清干净: %d 个", snaps) + } +} + +// TestSnapshotTooLarge 超大内容不存历史,避免把日志反复复制。 +func TestSnapshotTooLarge(t *testing.T) { + isolateConfig(t) + path := filepath.Join(t.TempDir(), "big.log") + big := make([]byte, histMaxSize+1) + for i := range big { + big[i] = 'x' + } + if err := saveSnapshot(path, big, "save", false); err != nil { + t.Fatal(err) + } + if n := len(listHistory(path)); n != 0 { + t.Fatalf("超大内容不该留历史,实际 %d 条", n) + } +} + +// TestPendingRoundTrip 未保存标记能写能读能清。 +func TestPendingRoundTrip(t *testing.T) { + isolateConfig(t) + if got := loadPending(); len(got) != 0 { + t.Fatal("初始应为空") + } + markPending([]pendingSnap{{Path: "C:/x/a.go", Hash: "abc", Time: 1}}) + got := loadPending() + if len(got) != 1 || got[0].Hash != "abc" { + t.Fatalf("读回来的不对: %+v", got) + } + markPending(nil) + if got := loadPending(); len(got) != 0 { + t.Fatalf("清空后应为空: %+v", got) + } +} + +// TestApplyEOL 快照里的换行要和原文件一致。 +func TestApplyEOL(t *testing.T) { + if got := applyEOL("a\nb\n", "\r\n"); got != "a\r\nb\r\n" { + t.Fatalf("CRLF 还原不对: %q", got) + } + if got := applyEOL("a\nb\n", "\n"); got != "a\nb\n" { + t.Fatalf("LF 不该改: %q", got) + } +} diff --git a/internal/app/historyui.go b/internal/app/historyui.go new file mode 100644 index 0000000..9c19578 --- /dev/null +++ b/internal/app/historyui.go @@ -0,0 +1,65 @@ +package app + +import ( + "fmt" + "path/filepath" + "time" +) + +// restoreFromHistory 把某一条历史的内容放回编辑器。 +// +// 只改缓冲区、不写盘:恢复完让用户自己对比、自己决定保存。 +func (a *App) restoreFromHistory(path string, e histEntry) { + d := a.find(path) + if d == nil { + // 目录模式里恢复的文件可能还没打开,先打开再说。 + var err error + d, err = a.loadDoc(path) + if err != nil { + a.alert("恢复失败", err.Error()) + return + } + } + data, err := readSnapshot(path, e.Hash) + if err != nil { + a.alert("恢复失败", err.Error()) + return + } + text, _, ok := decodeFile(data) + if !ok { + a.alert("恢复失败", "这条历史的内容无法解码。") + return + } + // 用 Set 而不是 Reset:恢复出来的内容必须是「未保存」状态。 + d.buf.Set(text) + a.histView.open = false + a.appendOut(fmt.Sprintf("已从本地历史恢复 %s(%s),尚未保存。", + filepath.Base(path), historyTime(e.Time))) + a.panel = true + a.panelTab = 0 + a.panelH = 160 + a.refresh() +} + +// historyTime 把毫秒时间戳格式化成「今天 14:02:33」这种。 +func historyTime(ms int64) string { + t := time.UnixMilli(ms) + now := time.Now() + if t.Format("2006-01-02") == now.Format("2006-01-02") { + return t.Format("今天 15:04:05") + } + return t.Format("01-02 15:04") +} + +// historyReason 把存储里的原因翻成给人看的词。 +func historyReason(r string) string { + switch r { + case "save": + return "保存" + case "auto": + return "自动" + case "close": + return "退出时未保存" + } + return r +} diff --git a/internal/app/historyview.go b/internal/app/historyview.go new file mode 100644 index 0000000..bc17b48 --- /dev/null +++ b/internal/app/historyview.go @@ -0,0 +1,366 @@ +package app + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" + + "mygoland/internal/git" +) + +// 历史视图:左边列表,右边「选中的那条 ↔ 当前代码」,全屏铺在编辑区。 +// +// 为什么不用弹窗:Modal 覆盖层里的点击(包括按钮)在我们的自动化验证下完全不响应, +// 而且弹窗宽度有限,看不到并排对比。做成全屏视图后,左列表 + 右差异同屏, +// 「这条历史跟现在差在哪」一眼就能看到,这正是看历史时真正要的信息。 + +// histMode 是历史视图的模式。 +type histMode int + +const ( + histGit histMode = iota + histLocal +) + +// historyViewState 是全屏历史视图的状态。 +type historyViewState struct { + open bool + mode histMode + path string + isDir bool + // git 模式的提交,local 模式的快照。 + commits []git.LogEntry + items []histItem + sel int + err string + // 右侧对比的当前内容与标题。 + title string + diff editor.DiffState + blank bool // 还没有可对比的内容 +} + +// OpenHistoryView 打开某个文件/目录的历史视图。 +func (a *App) OpenHistoryView(path string, isDir bool, mode histMode) { + st := historyViewState{open: true, mode: mode, path: path, isDir: isDir, blank: true} + if mode == histLocal { + if isDir { + st.items = listHistoryUnder(path) + } else { + for _, e := range listHistory(path) { + st.items = append(st.items, histItem{Path: path, histEntry: e}) + } + } + } + a.histView = st + a.refresh() + + if mode == histGit { + root, p := a.root, path + go func() { + commits, err := git.Log(root, p, 50) + a.win.Update(func() { + if !a.histView.open || a.histView.path != p || a.histView.mode != histGit { + return + } + if err != nil { + a.histView.err = err.Error() + } else { + a.histView.commits = commits + // 默认选中最新一条,右侧立刻有内容,不用先点一下。 + if len(commits) > 0 { + a.previewHistorySel() + } + } + a.refresh() + }) + }() + } else if len(st.items) > 0 { + a.previewHistorySel() + } +} + +// OpenGitLog 打开某个文件/目录的 git 历史视图。 +func (a *App) OpenGitLog(path string, isDir bool) { + if a.root == "" { + a.alert("Git 历史", "当前没有打开工作区。") + return + } + if !git.Available(a.root) { + a.alert("Git 历史", "这个工作区不是 git 仓库。") + return + } + a.OpenHistoryView(path, isDir, histGit) +} + +// closeHistoryView 关掉历史视图。 +func (a *App) closeHistoryView() { + a.histView.open = false + a.refresh() +} + +// previewHistorySel 把当前选中的那条和当前代码比,填右侧。 +func (a *App) previewHistorySel() { + v := &a.histView + if v.isDir { + return + } + var left, title string + switch v.mode { + case histGit: + if v.sel < 0 || v.sel >= len(v.commits) { + return + } + c := v.commits[v.sel] + text, err := git.ShowAt(a.root, c.Hash, v.path) + if err != nil { + v.blank = true + v.title = c.Hash + " 里没有这个文件" + return + } + left = text + title = c.Hash + " ↔ 当前 · " + trimTo(c.Subject, 34) + case histLocal: + if v.sel < 0 || v.sel >= len(v.items) { + return + } + it := v.items[v.sel] + data, err := readSnapshot(it.Path, it.Hash) + if err != nil { + v.blank = true + v.title = "读取快照失败" + return + } + text, _, ok := decodeFile(data) + if !ok { + v.blank = true + v.title = "快照内容无法解码" + return + } + left = text + title = historyTime(it.Time) + " " + historyReason(it.Reason) + " ↔ 当前" + } + right := a.currentTextOf(v.path) + a.fillHistDiff(v, left, right, title) +} + +// fillHistDiff 造左右两份缓冲区给 DiffView。 +func (a *App) fillHistDiff(v *historyViewState, left, right, title string) { + ob := editor.NewBuffer(left) + nb := editor.NewBuffer(right) + lang := filepath.Base(v.path) + ob.SetLanguage(editor.LanguageFor(lang)) + nb.SetLanguage(editor.LanguageFor(lang)) + + font, lh, tab, _, _ := a.editorSettings() + v.title = title + v.blank = false + v.diff = editor.DiffState{ + Old: ob, + New: nb, + Layout: editor.DiffSplit, + Inline: editor.DiffInlineWordAlt, + Indicators: editor.DiffBars, + ContextLines: 3, + Font: font, + LineHeight: lh, + TabSize: tab, + Theme: codeTheme(a.light), + } +} + +// historyView 画全屏历史视图。 +func (a *App) historyView(c *ui.Context) { + t := c.Theme() + v := &a.histView + rel := v.path + if r, err := filepath.Rel(a.root, v.path); err == nil { + rel = filepath.ToSlash(r) + } + if v.isDir { + rel += "/" + } + + ui.Column(c).Fill().Children(func() { + // 顶部:模式标签 + 路径 + 关闭 + ui.Row(c).Padding(5, 10).Gap(8).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + label := "Git 历史" + if v.mode == histLocal { + label = "本地历史" + } + ui.Row(c).Padding(1, 6).Radius(3).Background(t.Accent.Alpha(0.16)). + Children(func() { + ui.Text(c, label).FontSize(10).TextColor(t.Accent) + }) + ui.Text(c, rel).FontSize(12).Bold().TextColor(t.Text).SingleLine() + ui.Box(c).Grow(1) + if ui.Button(c, "关闭(Esc)").Clicked() { + a.closeHistoryView() + } + }) + + ui.Row(c).Grow(1).AlignItems(ui.Stretch).Children(func() { + // 左:列表 + ui.Column(c).Width(340).Children(func() { + ui.Row(c).Padding(4, 8).Gap(6).AlignItems(ui.Center).Children(func() { + n := len(v.commits) + if v.mode == histLocal { + n = len(v.items) + } + unit := "条提交" + if v.mode == histLocal { + unit = "条快照" + } + ui.Textf(c, "%d %s", n, unit).FontSize(10).TextColor(t.TextMuted) + ui.Box(c).Grow(1) + if v.mode == histLocal && !v.isDir && len(v.items) > 0 { + if ui.Button(c, "恢复这条").Clicked() { + it := v.items[v.sel] + a.restoreFromHistory(it.Path, it.histEntry) + } + } + }) + ui.Box(c).FillWidth().Height(1).Background(t.Border) + + switch { + case v.err != "": + ui.Column(c).Padding(8, 10).Children(func() { + ui.Text(c, v.err).FontSize(11).TextColor(t.Danger).SingleLine() + }) + case len(v.commits) == 0 && len(v.items) == 0: + ui.Column(c).Grow(1).Center().Children(func() { + ui.Text(c, "没有记录").FontSize(12).TextColor(t.TextMuted) + }) + default: + ui.Scroll(c).Grow(1).Children(func() { + ui.Column(c).Gap(1).Padding(4, 4).Children(func() { + if v.mode == histGit { + a.histGitRows(c) + } else { + a.histLocalRows(c) + } + }) + }) + } + }) + + ui.Box(c).Width(1).FillHeight().Background(t.Border) + + // 右:对比 + ui.Column(c).Grow(1).Children(func() { + ui.Row(c).Padding(4, 10).Gap(8).AlignItems(ui.Center).Children(func() { + if v.title != "" { + ui.Text(c, v.title).FontSize(10).TextColor(t.TextMuted).SingleLine() + } + ui.Box(c).Grow(1) + if !v.blank { + ui.Text(c, "左:历史 右:当前").FontSize(10).TextColor(t.TextMuted) + } + }) + ui.Box(c).FillWidth().Height(1).Background(t.Border) + if v.blank { + ui.Column(c).Grow(1).Center().Children(func() { + msg := "选一条看它和当前代码的差异" + if v.isDir { + msg = "目录只列提交;点具体文件看差异" + } + ui.Text(c, msg).FontSize(12).TextColor(t.TextMuted) + }) + } else { + editor.DiffView(c, &v.diff).Fill() + } + }) + }) + }) +} + +// histGitRows 画 git 提交行。 +func (a *App) histGitRows(c *ui.Context) { + t := c.Theme() + v := &a.histView + for i, cm := range v.commits { + idx, entry := i, cm + active := idx == v.sel + bg := ui.RGBA(0, 0, 0, 0) + if active { + bg = t.SurfaceHover + } + row := ui.ButtonBase(c).FillWidth().Height(40).Padding(0, 6).Radius(4). + Background(bg).Cursor(ui.CursorPointer) + row.Children(func() { + ui.Row(c).FillWidth().Gap(8).AlignItems(ui.Center).Children(func() { + mark := ui.RGBA(0, 0, 0, 0) + if active { + mark = t.Accent + } + ui.Box(c).Width(2).Height(24).Background(mark).Radius(1) + ui.Column(c).Grow(1).Gap(1).Children(func() { + ui.Text(c, entry.Subject).FontSize(12).TextColor(t.Text).SingleLine() + ui.Textf(c, "%s %s %s", entry.Hash, entry.Author, entry.When). + FontSize(10).TextColor(t.TextMuted).SingleLine() + }) + }) + }) + if row.Clicked() { + v.sel = idx + a.previewHistorySel() + a.refresh() + } + } +} + +// histLocalRows 画本地快照行。 +func (a *App) histLocalRows(c *ui.Context) { + t := c.Theme() + v := &a.histView + for i, it := range v.items { + idx, item := i, it + active := idx == v.sel + bg := ui.RGBA(0, 0, 0, 0) + if active { + bg = t.SurfaceHover + } + row := ui.ButtonBase(c).FillWidth().Height(40).Padding(0, 6).Radius(4). + Background(bg).Cursor(ui.CursorPointer) + row.Children(func() { + ui.Row(c).FillWidth().Gap(8).AlignItems(ui.Center).Children(func() { + mark := ui.RGBA(0, 0, 0, 0) + if active { + mark = t.Accent + } + ui.Box(c).Width(2).Height(24).Background(mark).Radius(1) + ui.Column(c).Grow(1).Gap(1).Children(func() { + name := historyTime(item.Time) + if v.isDir { + name = filepath.Base(item.Path) + " · " + name + } + ui.Text(c, name).FontSize(12).TextColor(t.Text).SingleLine() + meta := fmt.Sprintf("%s · %d KB", historyReason(item.Reason), (item.Size+1023)/1024) + if item.Dirty { + meta += " · 未保存" + } + ui.Text(c, meta).FontSize(10).TextColor(t.TextMuted).SingleLine() + }) + }) + }) + if row.Clicked() { + v.sel = idx + a.previewHistorySel() + a.refresh() + } + } +} + +// histViewActive 供编辑区判断是否要让位。 +func (a *App) histViewActive() bool { return a.histView.open } + +// 让旧的弹窗入口改走全屏视图。 +func (a *App) OpenHistoryAt(path string, isDir bool) { + a.OpenHistoryView(path, isDir, histLocal) +} + +// ensure 引用 strings,避免未使用(渲染里用到了 TrimPrefix 之类)。 +var _ = strings.TrimSpace diff --git a/internal/app/icons.go b/internal/app/icons.go new file mode 100644 index 0000000..adbe511 --- /dev/null +++ b/internal/app/icons.go @@ -0,0 +1,107 @@ +package app + +import ( + "time" + + "github.com/egoist/mygo/ui" +) + +// 图标全部内嵌为 SVG,24 栅格自绘,不依赖任何字体字形。 +// +// ui.Icon 会把图形画成文字颜色,所以 SVG 里的颜色只是占位: +// 需要实心的形状写 fill,线框形状保持 fill="none"。 +var iconMarkup = map[string]string{ + "folder": ``, + "refresh": ``, + "collapse": ``, + "expand": ``, + "plus": ``, + "outline": ``, + "chevron": ``, + // 靶心加十字准星:定位当前文件在树里的位置。 + "locate": ``, + "build": ``, + "run": ``, + "test": ``, + "stop": ``, + "clear": ``, + "hide": ``, + "panel": ``, + "continue": ``, + "over": ``, + "into": ``, + "out": ``, + "close": ``, + "error": ``, + "warning": ``, + "debug": ``, +} + +// icons 是解析好的图标,进程启动时建一次。 +var icons = map[string]*ui.SVG{} + +func init() { + for name, body := range iconMarkup { + src := `` + body + `` + svg, err := ui.ParseSVG([]byte(src)) + if err != nil { + logf("图标 %s 解析失败: %v", name, err) + continue + } + icons[name] = svg + } +} + +// icon 画一个图标,size 是像素高度,color 是颜色。 +func icon(c *ui.Context, name string, size float32, color ui.Color) ui.Element { + svg := icons[name] + if svg == nil { + return ui.Box(c).Width(size).Height(size) + } + return ui.Icon(c, svg).Width(size).Height(size).TextColor(color) +} + +// iconButtonEl 是带图标的按钮,带悬停与按下的过渡动效。 +func iconButtonEl(c *ui.Context, name, label, tip string, color ui.Color) ui.Element { + t := c.Theme() + if color == (ui.Color{}) { + color = t.Text + } + base := ui.ButtonBase(c).Padding(2, 5).Radius(4) + + // 悬停淡入一层底色,按下再深一档并轻微缩小。 + bgTarget := ui.RGBA(0, 0, 0, 0) + switch { + case base.Pressed(): + bgTarget = t.SurfacePressed + case base.Hovered(): + bgTarget = t.SurfaceHover + } + bg := base.AnimateColor("iconbg", bgTarget, ui.Animation{Duration: 120 * time.Millisecond}) + base = base.Background(bg) + + scaleTarget := float32(1) + if base.Pressed() { + scaleTarget = 0.92 + } + scale := base.AnimateTo("iconscale", scaleTarget, ui.Animation{Duration: 90 * time.Millisecond}) + base = base.Scale(scale, scale) + + base.Children(func() { + ui.Row(c).Gap(4).AlignItems(ui.Center).Children(func() { + icon(c, name, 13, color) + if label != "" { + ui.Text(c, label).FontSize(11).TextColor(color) + } + }) + }) + if tip != "" { + base = base.Tooltip(tip) + } + return base +} + +// iconButton 只需要知道是否被点时用。 +func iconButton(c *ui.Context, name, label, tip string, color ui.Color) bool { + return iconButtonEl(c, name, label, tip, color).Clicked() +} diff --git a/internal/app/icons_test.go b/internal/app/icons_test.go new file mode 100644 index 0000000..5b5d183 --- /dev/null +++ b/internal/app/icons_test.go @@ -0,0 +1,14 @@ +package app + +import "testing" + +func TestIconsParsed(t *testing.T) { + for name := range iconMarkup { + if icons[name] == nil { + t.Fatalf("图标 %s 没有解析成功", name) + } + } + if len(icons) != len(iconMarkup) { + t.Fatalf("图标数量不一致: 解析 %d,定义 %d", len(icons), len(iconMarkup)) + } +} diff --git a/internal/app/inlay.go b/internal/app/inlay.go new file mode 100644 index 0000000..779146b --- /dev/null +++ b/internal/app/inlay.go @@ -0,0 +1,99 @@ +package app + +import ( + "context" + "strings" + "time" + + "github.com/egoist/mygo/ui/editor" + + "mygoland/internal/lsp" +) + +// inlayDelay 是请求内联提示前的等待:连续输入时不该每一帧都问一次 gopls。 +const inlayDelay = 350 * time.Millisecond + +// scheduleInlays 安排一次内联提示刷新。 +// +// 用代数(gen)来丢弃过期结果:每次请求都会拿到一个新的 gen, +// 回来时如果 d.inlayGen 已经变了,说明这期间文档又改过,结果作废。 +func (a *App) scheduleInlays(d *Doc) { + if a.lsp == nil || d == nil || d.st == nil || !lsp.IsGoFile(d.path) { + return + } + if !a.inlaysOn() { + d.st.SetInlays(nil) + return + } + d.inlayGen++ + gen := d.inlayGen + time.AfterFunc(inlayDelay, func() { a.requestInlays(d, gen) }) +} + +// requestInlays 向 gopls 要一次提示并交给编辑器。 +// +// gopls 在包还没分析完时会返回空结果,所以空结果要重试几次: +// 打开大项目时分析可能要一两秒。 +func (a *App) requestInlays(d *Doc, gen int) { + a.requestInlaysTry(d, gen, 0) +} + +func (a *App) requestInlaysTry(d *Doc, gen, attempt int) { + if a.lsp == nil || d.inlayGen != gen { + return + } + text := d.buf.String() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + // 范围必须落在文档之内:gopls 会校验,给个超大列号会报 + // 「column is beyond end of file」。用最后一行的实际长度最稳。 + hints, err := a.lsp.InlayHints(ctx, d.uri, lsp.Range{ + Start: lsp.Position{Line: 0, Character: 0}, + End: endPosition(text), + }) + if err != nil { + return + } + if len(hints) == 0 && attempt < 3 { + // 还没分析完,过一会儿再问。 + delay := time.Duration(attempt+1) * 1500 * time.Millisecond + time.AfterFunc(delay, func() { a.requestInlaysTry(d, gen, attempt+1) }) + return + } + ins := make([]editor.Inlay, 0, len(hints)) + for _, h := range hints { + label := h.Label.Text() + if label == "" { + continue + } + // 协议用 padding 表达「和前后留个空格」,这里翻成真实的空格。 + if h.PaddingLeft { + label = " " + label + } + if h.PaddingRight { + label += " " + } + ins = append(ins, editor.Inlay{ + Offset: lsp.PositionToOffset(text, h.Position), + Text: label, + }) + } + + a.win.Update(func() { + if d.inlayGen != gen { + return + } + d.st.SetInlays(ins) + }) +} + +// endPosition 返回文本末尾的位置(最后一行 + 该行长度)。 +func endPosition(text string) lsp.Position { + lines := strings.Split(text, "\n") + last := len(lines) - 1 + if last < 0 { + return lsp.Position{} + } + return lsp.Position{Line: last, Character: len(lines[last])} +} diff --git a/internal/app/log.go b/internal/app/log.go new file mode 100644 index 0000000..abbf2e4 --- /dev/null +++ b/internal/app/log.go @@ -0,0 +1,44 @@ +package app + +import ( + "io" + "log" + "os" + "path/filepath" +) + +// logMaxSize 是日志文件的上限,超过则在启动时清空重来。 +const logMaxSize = 4 << 20 + +// logPath 是当前日志文件路径,为空表示没启用文件日志。 +var logPath string + +// SetupLog 把日志同时写到用户缓存目录与标准错误。 +// +// GUI 子系统(-H=windowsgui)下没有控制台,标准错误是无效句柄, +// 所以必须落文件,否则语言服务器与调试的排错信息全丢。 +func SetupLog() string { + dir, err := os.UserCacheDir() + if err != nil { + return "" + } + dir = filepath.Join(dir, "mygoland") + if err := os.MkdirAll(dir, 0o755); err != nil { + return "" + } + p := filepath.Join(dir, "mygoland.log") + if st, err := os.Stat(p); err == nil && st.Size() > logMaxSize { + _ = os.Remove(p) + } + f, err := os.OpenFile(p, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + return "" + } + log.SetFlags(log.LstdFlags | log.Lmicroseconds) + log.SetOutput(io.MultiWriter(f, os.Stderr)) + logPath = p + return p +} + +// LogPath 返回日志文件路径。 +func LogPath() string { return logPath } diff --git a/internal/app/logo.go b/internal/app/logo.go new file mode 100644 index 0000000..de2a72b --- /dev/null +++ b/internal/app/logo.go @@ -0,0 +1,65 @@ +package app + +import ( + _ "embed" + "log" + + "github.com/egoist/mygo/ui" +) + +// Version 显示在「关于」窗口里。 +const Version = "0.1.0" + +// logoPNG 是打包进二进制的应用标识,由 docs/logo/final/icon-256.png 复制而来。 +// +// 用 256×256 而不是 1024:界面最大只显示到 112,2 倍屏需要 224, +// 256 够用,同时把可执行文件里的死重量控制在 60 KB 以内。 +// +//go:embed assets/logo.png +var logoPNG []byte + +// iconPNG 是窗口与任务栏用的图标:同一套图形,但垫了浅色圆角底板。 +// 任务栏在深色模式下是 #1F1F1F 左右,透明底图片里的深藏青齿轮和黑描边 +// 会直接糊进背景,所以系统图标必须自带底色。 +// +//go:embed assets/icon.png +var iconPNG []byte + +// logo 是解码后的位图。视图每帧重建,解码只能做一次。 +var logo = decodeLogo() + +func decodeLogo() ui.ImageSource { + b, err := ui.DecodeBitmap(logoPNG) + if err != nil { + // 图标缺失不该让 IDE 起不来,退化成不画图标。 + log.Printf("logo 解码失败,界面将不显示标识: %v", err) + return nil + } + return b +} + +// logoCard 画一块浅色圆角底板,把标识放在中间,size 是整块卡片的边长。 +// +// 不能直接把透明底图片贴在深色主题上:齿轮是 #324F60 的深藏青, +// 黑色描边落在 #12161A 的背景上会糊成一片,轮廓读不出来。 +// 垫一块 #E9EFF5 的浅色板之后,图形和描边都能完整保住, +// 观感也更像一个应用图标。 +func logoCard(c *ui.Context, size float32) { + inner := size * 0.80 + pad := (size - inner) / 2 + + // 深色下用浅色板把图形托出来;浅色下同样一块浅底就不明显了, + // 改成比面板略灰的底 + 一圈细边,让标识仍有边界。 + t := c.Theme() + col := ui.Column(c).Size(size, size).Center().Padding(pad).Radius(size * 0.22) + if t.Dark { + col = col.Background(ui.Hex("#E9EFF5")) + } else { + col = col.Background(ui.Hex("#F1F4F8")).BorderWidth(1).BorderColor(t.Border) + } + col.Children(func() { + if logo != nil { + ui.Image(c, logo).Size(inner, inner) + } + }) +} diff --git a/internal/app/lsp.go b/internal/app/lsp.go new file mode 100644 index 0000000..72b1ab2 --- /dev/null +++ b/internal/app/lsp.go @@ -0,0 +1,469 @@ +package app + +import ( + "context" + "sort" + "strings" + "time" + + "github.com/egoist/mygo/ui/editor" + + "mygoland/internal/lsp" +) + +// requestTimeout 是单个语言服务器请求的上限。 +const requestTimeout = 10 * time.Second + +// startLSP 在工作区打开后异步拉起 gopls。 +func (a *App) startLSP(root string) { + a.lspGen++ + gen := a.lspGen + a.lspLastStart = time.Now() + a.lspState = "gopls 启动中…" + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second) + defer cancel() + c, err := lsp.Start(ctx, lsp.Options{ + Root: root, + Logf: func(format string, args ...any) { + // 语言服务器日志只写标准错误,避免污染界面。 + logf("lsp: "+format, args...) + }, + OnDiagnostics: func(uri string, version int, ds []lsp.Diagnostic) { + if a.win == nil { + return + } + a.win.Update(func() { a.applyDiagnostics(uri, version, ds) }) + }, + OnExit: func() { a.onLSPExit(root, gen) }, + }) + a.win.Update(func() { + if err != nil { + a.lsp = nil + a.lspState = "gopls 不可用(" + firstLine(err.Error()) + ")" + return + } + a.lsp = c + a.lspState = "gopls 就绪" + for _, d := range a.docs { + a.lspOpen(d) + } + }) + }() +} + +// onLSPExit gopls 进程退出。手动重启/关闭时 a.lsp 已换人或代数已变,直接忽略; +// 真是意外崩溃就自动重启——但 10 秒内刚起过又死的(比如 go.mod 坏了导致 +// 起一次崩一次)不再自动拉,免得无限重启循环,交给菜单手动处理。 +func (a *App) onLSPExit(root string, gen int) { + a.win.Update(func() { + if a.root != root || gen != a.lspGen || a.lsp == nil { + return + } + a.lsp = nil + if time.Since(a.lspLastStart) < 10*time.Second { + a.lspState = "gopls 已退出(菜单「重启语言服务器」可手动拉起)" + a.refresh() + return + } + a.lspState = "gopls 意外退出,正在重启…" + a.resetDocsForLSP() + a.startLSP(root) + a.refresh() + }) +} + +// resetDocsForLSP 清掉文档的已同步标记:重连后所有 Go 文件要重新 didOpen +//(prev 快照由 lspOpen 重新设)。须在主线程调用。 +func (a *App) resetDocsForLSP() { + for _, d := range a.docs { + if lsp.IsGoFile(d.path) { + d.opened = false + d.sent = 0 + } + } +} + +// restartLSP 手动重启语言服务器:改了 go.mod、gopls 卡死、缓存抽风时用。 +func (a *App) restartLSP() { + if a.root == "" { + return + } + if c := a.lsp; c != nil { + a.lsp = nil + go c.Close() + } + a.resetDocsForLSP() + a.startLSP(a.root) + a.refresh() +} + +// RunModTidy 整理模块依赖,输出走运行面板;tidy 完 gopls 会自己跟上。 +func (a *App) RunModTidy() { + a.startTask("go mod tidy", "go", "mod", "tidy") +} + +// lspOpen 把文档同步给语言服务器。 +func (a *App) lspOpen(d *Doc) { + if a.lsp == nil || d.opened || !lsp.IsGoFile(d.path) { + return + } + d.opened = true + d.sent = d.buf.Version() + d.prev = d.buf.Snapshot() + _ = a.lsp.DidOpen(d.uri, "go", int(d.sent), d.prev.String()) + // 打开之后要等 gopls 分析完才会有提示,但请求本身是异步的,先发出去, + // 服务端会等到有结果再回。 + a.scheduleInlays(d) +} + +// lspSync 把缓冲区的增量改动推给语言服务器,须在主线程调用。 +func (a *App) lspSync(d *Doc) { + if a.lsp == nil || !lsp.IsGoFile(d.path) { + return + } + if !d.opened { + a.lspOpen(d) + return + } + ver := d.buf.Version() + if ver == d.sent { + return + } + old := d.prev.String() + cur := d.buf.String() + change, text, ok := lsp.DiffChange(old, cur) + if !ok { + d.sent = ver + d.prev = d.buf.Snapshot() + return + } + d.sent = ver + d.prev = d.buf.Snapshot() + _ = a.lsp.DidChange(d.uri, int(ver), []lsp.ContentChange{{ + Range: &change, + Text: text, + }}) + // 文本变了,提示里的类型/参数名也可能变。 + a.scheduleInlays(d) +} + +// applyDiagnostics 把 LSP 诊断转成编辑器诊断,须在主线程调用。 +func (a *App) applyDiagnostics(uri string, version int, ds []lsp.Diagnostic) { + var d *Doc + for _, x := range a.docs { + if x.uri == uri { + d = x + break + } + } + if d == nil { + return + } + ver := uint64(version) + var text string + switch { + case ver == 0 || ver == d.buf.Version(): + text = d.buf.String() + ver = d.buf.Version() + case d.prev.Version() == ver: + text = d.prev.String() + default: + // 诊断对应的版本已经过期,丢弃以免位置错乱。 + return + } + // 原样留一份:请求代码动作时要把服务端给的诊断(含 data)带回去。 + d.diags = append([]lsp.Diagnostic(nil), ds...) + out := make([]editor.Diagnostic, 0, len(ds)) + probs := make([]Problem, 0, len(ds)) + for _, x := range ds { + sev := severityOf(x.Severity) + out = append(out, editor.Diagnostic{ + Start: lsp.PositionToOffset(text, x.Range.Start), + End: lsp.PositionToOffset(text, x.Range.End), + Severity: sev, + Message: x.Message, + Source: x.Source, + }) + probs = append(probs, Problem{ + Path: d.path, + Line: x.Range.Start.Line + 1, + Col: x.Range.Start.Character + 1, + Text: x.Message, + Severity: sev, + }) + } + d.problems = probs + d.st.SetDiagnostics(ver, out) + // 诊断到了通常说明这轮分析结束,顺手要一次内联提示。 + a.scheduleInlays(d) +} + +// severityOf 把 LSP 严重级别映射到编辑器。 +func severityOf(s int) editor.Severity { + switch s { + case 2: + return editor.SeverityWarning + case 3: + return editor.SeverityInfo + case 4: + return editor.SeverityHint + } + return editor.SeverityError +} + +// complete 向语言服务器要补全,结果回到主线程显示。 +func (a *App) complete(d *Doc, r editor.CompletionRequest) { + c := a.lsp + if c == nil { + d.st.ShowCompletions(r.Offset-len(r.Prefix), wordsOf(d.buf, r.Prefix)) + return + } + at := r.Offset - len(r.Prefix) + pos := positionAt(d, r.Offset) + version := r.Version + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + items, err := c.Completion(ctx, d.uri, pos) + if err != nil || len(items) == 0 { + // 语言服务器还没准备好或没有建议时,退回词表补全。 + a.win.Update(func() { + if d.buf.Version() != version { + return + } + d.st.ShowCompletions(at, wordsOf(d.buf, r.Prefix)) + }) + return + } + out := make([]editor.Completion, 0, len(items)) + for _, it := range items { + out = append(out, toEditorCompletion(it)) + } + a.win.Update(func() { + if d.buf.Version() != version { + return + } + d.st.ShowCompletions(at, out) + }) + }() +} + +// toEditorCompletion 把 LSP 补全项映射到编辑器补全项。 +func toEditorCompletion(it lsp.CompletionItem) editor.Completion { + insert := it.InsertText + if it.TextEdit != nil && it.TextEdit.NewText != "" { + insert = it.TextEdit.NewText + } + if insert == "" { + insert = it.Label + } + return editor.Completion{ + Label: it.Label, + Detail: it.Detail, + Kind: completionKind(it.Kind), + Insert: insert, + Documentation: it.DocumentationText(), + FilterText: it.FilterText, + } +} + +// completionKind 映射 LSP 补全类型。 +func completionKind(k int) editor.CompletionKind { + switch k { + case 1: + return editor.CompletionText + case 2: + return editor.CompletionMethod + case 3, 4: + return editor.CompletionFunction + case 5: + return editor.CompletionField + case 6, 12: + return editor.CompletionVariable + case 7, 8, 22, 25: + return editor.CompletionType + case 9: + return editor.CompletionModule + case 10, 11: + return editor.CompletionField + case 13, 14: + return editor.CompletionKeyword + case 15: + return editor.CompletionSnippet + case 20, 21: + return editor.CompletionConstant + } + return editor.CompletionText +} + +// hover 请求悬停信息。 +func (a *App) hover(d *Doc, r editor.HoverRequest) { + c := a.lsp + if c == nil { + return + } + pos := positionAt(d, r.Offset) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + h, err := c.Hover(ctx, d.uri, pos) + if err != nil || h == nil { + return + } + text := strings.TrimSpace(markdownToText(h.Text())) + if text == "" { + return + } + a.win.Update(func() { + start, end := wordBounds(d, r.Offset) + if h.Range != nil { + cur := d.buf.String() + start = lsp.PositionToOffset(cur, h.Range.Start) + end = lsp.PositionToOffset(cur, h.Range.End) + } + d.st.ShowHover(start, end, text, nil) + }) + }() +} + +// definition 跳转到定义。 +func (a *App) definition(d *Doc, offset int) { + c := a.lsp + if c == nil { + return + } + pos := positionAt(d, offset) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + locs, err := c.Definition(ctx, d.uri, pos) + if err != nil || len(locs) == 0 { + return + } + loc := locs[0] + path := lsp.URIToPath(loc.URI) + if path == "" { + return + } + a.win.Update(func() { a.openAt(path, loc.Range.Start) }) + }() +} + +// openAt 在指定位置打开文件,用于跳转定义。 +func (a *App) openAt(path string, pos lsp.Position) { + d, err := a.loadDoc(path) + if err != nil { + a.alert("无法打开", err.Error()) + return + } + line := pos.Line + if line >= d.buf.LineCount() { + line = d.buf.LineCount() - 1 + } + col := lsp.UTF16ToByte(d.buf.Line(line), pos.Character) + d.st.GoTo(editor.Pos{Line: line, Col: col}) + d.st.ScrollTo(line) +} + +// formatCurrent 格式化当前文档。 +func (a *App) FormatCurrent() { + d := a.doc() + if d == nil { + return + } + c := a.lsp + if c == nil || !lsp.IsGoFile(d.path) { + return + } + uri, path := d.uri, d.path + version := d.buf.Version() + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + edits, err := c.Format(ctx, uri, lsp.FormattingOptions{TabSize: 4, InsertSpaces: false}) + if err != nil || len(edits) == 0 { + return + } + a.win.Update(func() { + target := a.find(path) + if target == nil || target.buf.Version() != version { + return + } + a.applyEdits(target, edits) + }) + }() +} + +// applyEdits 应用一组文本修改,整个过程算一步撤销。 +func (a *App) applyEdits(d *Doc, edits []lsp.TextEdit) { + if len(edits) == 0 { + return + } + text := d.buf.String() + type span struct { + start, end int + text string + } + spans := make([]span, 0, len(edits)) + for _, e := range edits { + spans = append(spans, span{ + start: lsp.PositionToOffset(text, e.Range.Start), + end: lsp.PositionToOffset(text, e.Range.End), + text: e.NewText, + }) + } + sort.Slice(spans, func(i, j int) bool { return spans[i].start > spans[j].start }) + d.buf.Transact(func() { + for _, s := range spans { + d.buf.Edit(editor.Edit{Start: s.start, End: s.end, Text: s.text}) + } + }) +} + +// positionAt 把字节偏移转成 LSP 位置。 +func positionAt(d *Doc, off int) lsp.Position { + p := d.buf.Pos(off) + line := d.buf.Line(p.Line) + col := p.Col + if col > len(line) { + col = len(line) + } + return lsp.Position{Line: p.Line, Character: lsp.UTF16Len(line[:col])} +} + +// wordBounds 返回光标处单词的字节区间。 +func wordBounds(d *Doc, off int) (int, int) { + isWord := func(b byte) bool { + return b == '_' || b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' + } + p := d.buf.Pos(off) + line := d.buf.Line(p.Line) + if p.Col > len(line) { + return off, off + } + a, z := p.Col, p.Col + for a > 0 && isWord(line[a-1]) { + a-- + } + for z < len(line) && isWord(line[z]) { + z++ + } + start := off - (p.Col - a) + return start, start + (z - a) +} + +// markdownToText 粗略去掉 markdown 标记,让悬停内容更好读。 +func markdownToText(s string) string { + s = strings.ReplaceAll(s, "```go\n", "") + s = strings.ReplaceAll(s, "```", "") + return s +} + +// firstLine 取错误信息的第一行。 +func firstLine(s string) string { + if i := strings.IndexByte(s, '\n'); i >= 0 { + return s[:i] + } + return s +} diff --git a/internal/app/menu.go b/internal/app/menu.go new file mode 100644 index 0000000..614338a --- /dev/null +++ b/internal/app/menu.go @@ -0,0 +1,275 @@ +package app + +import ( + "github.com/egoist/mygo" + "github.com/egoist/mygo/ui/editor" +) + +// Menu 构建应用菜单;在 Start 之后调用。 +// 仍然注册给窗口,是为了让 Accelerator(Ctrl+S 这类)继续生效—— +// 菜单栏本身在隐藏标题栏下不显示,界面里用的是标题栏上的横向菜单。 +func (a *App) Menu() *mygo.Menu { + return mygo.NewMenu(a.menuItems()) +} + +// menuItems 返回主菜单的顶层项。标题栏的横向菜单与汉堡弹窗共用这一份, +// 避免两处各写一套、改了一处忘另一处。 +// +// 第一项不再是 RoleAppMenu:Windows 上它不显示,平铺到标题栏里会变成一个 +// 点不动的空项。 +func (a *App) menuItems() []*mygo.MenuItem { + if a.menuCache != nil { + return a.menuCache + } + a.menuCache = []*mygo.MenuItem{ + {Label: "文件", Submenu: []*mygo.MenuItem{ + {Label: "打开文件夹…", Accelerator: "CmdOrCtrl+O", Click: func(*mygo.MenuItem, *mygo.Window) { + go a.OpenFolderDialog() + }}, + mygo.Separator(), + {Label: "保存", Accelerator: "CmdOrCtrl+S", Click: func(*mygo.MenuItem, *mygo.Window) { + a.Save() + }}, + {Label: "全部保存", Accelerator: "CmdOrCtrl+Alt+S", Click: func(*mygo.MenuItem, *mygo.Window) { + a.SaveAll() + }}, + mygo.Separator(), + {Label: "关闭标签页", Accelerator: "CmdOrCtrl+W", Click: func(*mygo.MenuItem, *mygo.Window) { + if d := a.doc(); d != nil { + go a.CloseDoc(d.path) + } + }}, + mygo.Separator(), + {Label: "最近项目…", Accelerator: "CmdOrCtrl+R", Click: func(*mygo.MenuItem, *mygo.Window) { + a.OpenRecent() + }}, + {Label: "设置…", Accelerator: "CmdOrCtrl+,", Click: func(*mygo.MenuItem, *mygo.Window) { + a.OpenSettings() + }}, + mygo.Separator(), + {Label: "退出", Role: mygo.RoleQuit}, + }}, + {Label: "编辑", Submenu: []*mygo.MenuItem{ + {Label: "快速打开文件", Accelerator: "CmdOrCtrl+P", Click: func(*mygo.MenuItem, *mygo.Window) { + a.OpenQuick() + }}, + {Label: "转到符号(Ctrl+T)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.OpenSymbols() + }}, + {Label: "全局搜索", Accelerator: "CmdOrCtrl+Shift+F", Click: func(*mygo.MenuItem, *mygo.Window) { + a.OpenSearch() + }}, + mygo.Separator(), + {Label: "本地历史…", Click: func(*mygo.MenuItem, *mygo.Window) { + if d := a.doc(); d != nil { + a.OpenHistoryView(d.path, false, histLocal) + } + }}, + mygo.Separator(), + {Label: "查找(Ctrl+F)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunEditorCmd(editor.Find) + }}, + {Label: "替换(Ctrl+H)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunEditorCmd(editor.FindReplace) + }}, + {Label: "查找下一个(F3)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunEditorCmd(editor.FindNext) + }}, + {Label: "查找上一个(Shift+F3)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunEditorCmd(editor.FindPrevious) + }}, + mygo.Separator(), + {Label: "折叠 / 展开(Ctrl+.)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunEditorCmd(editor.ToggleFold) + }}, + {Label: "全部折叠", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunEditorCmd(editor.FoldAll) + }}, + {Label: "全部展开", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunEditorCmd(editor.UnfoldAll) + }}, + mygo.Separator(), + {Label: "重命名符号", Accelerator: "F2", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RenameSymbol() + }}, + {Label: "查找引用", Accelerator: "Shift+F2", Click: func(*mygo.MenuItem, *mygo.Window) { + a.FindReferences() + }}, + // 不挂快捷键:Alt+Enter 由编辑器自己接(见 newDoc 里的 OnInput), + // 这里挂上会和编辑器抢按键。 + {Label: "代码动作(Alt+Enter)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.CodeActions() + }}, + mygo.Separator(), + {Label: "撤销", Accelerator: "CmdOrCtrl+Z", Click: func(*mygo.MenuItem, *mygo.Window) { + a.editCommand(editor.Undo) + }}, + {Label: "重做", Accelerator: "CmdOrCtrl+Shift+Z", Click: func(*mygo.MenuItem, *mygo.Window) { + a.editCommand(editor.Redo) + }}, + mygo.Separator(), + {Label: "剪切", Accelerator: "CmdOrCtrl+X", Click: func(*mygo.MenuItem, *mygo.Window) { + a.editCommand(editor.Cut) + }}, + {Label: "复制", Accelerator: "CmdOrCtrl+C", Click: func(*mygo.MenuItem, *mygo.Window) { + a.editCommand(editor.Copy) + }}, + {Label: "粘贴", Accelerator: "CmdOrCtrl+V", Click: func(*mygo.MenuItem, *mygo.Window) { + a.editCommand(editor.Paste) + }}, + mygo.Separator(), + {Label: "全选", Accelerator: "CmdOrCtrl+A", Click: func(*mygo.MenuItem, *mygo.Window) { + a.editCommand(editor.SelectAll) + }}, + {Label: "切换行注释", Accelerator: "CmdOrCtrl+/", Click: func(*mygo.MenuItem, *mygo.Window) { + a.editCommand(editor.ToggleComment) + }}, + mygo.Separator(), + {Label: "格式化文档", Accelerator: "CmdOrCtrl+Alt+L", Click: func(*mygo.MenuItem, *mygo.Window) { + a.FormatCurrent() + }}, + }}, + {Label: "运行", Submenu: []*mygo.MenuItem{ + {Label: "构建", Accelerator: "Ctrl+F9", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunBuild() + }}, + {Label: "运行配置…", Click: func(*mygo.MenuItem, *mygo.Window) { + a.OpenRunConfigs() + }}, + mygo.Separator(), + {Label: "运行", Accelerator: "Shift+F10", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunProgram() + }}, + {Label: "测试(结果树)", Accelerator: "Ctrl+Shift+F10", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunTestTree("") + }}, + {Label: "测试当前包", Click: func(*mygo.MenuItem, *mygo.Window) { + a.runCurrentPackageTests() + }}, + {Label: "运行光标处的测试", Click: func(*mygo.MenuItem, *mygo.Window) { + a.runTestAtCursor() + }}, + {Label: "统计覆盖率", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunCoverage() + }}, + mygo.Separator(), + {Label: "开始调试", Accelerator: "Shift+F9", Click: func(*mygo.MenuItem, *mygo.Window) { + a.StartDebug() + }}, + {Label: "继续", Accelerator: "F9", Click: func(*mygo.MenuItem, *mygo.Window) { + a.DebugContinue() + }}, + {Label: "步过", Accelerator: "F8", Click: func(*mygo.MenuItem, *mygo.Window) { + a.DebugNext() + }}, + {Label: "单步进入", Accelerator: "F7", Click: func(*mygo.MenuItem, *mygo.Window) { + a.DebugStepIn() + }}, + {Label: "跳出", Accelerator: "Shift+F8", Click: func(*mygo.MenuItem, *mygo.Window) { + a.DebugStepOut() + }}, + mygo.Separator(), + {Label: "停止", Accelerator: "Ctrl+F2", Click: func(*mygo.MenuItem, *mygo.Window) { + if a.dbg != nil { + a.StopDebug() + return + } + a.StopTask() + }}, + mygo.Separator(), + {Label: "整理模块依赖(go mod tidy)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.RunModTidy() + }}, + {Label: "重启语言服务器", Click: func(*mygo.MenuItem, *mygo.Window) { + a.restartLSP() + }}, + mygo.Separator(), + {Label: "清空输出", Click: func(*mygo.MenuItem, *mygo.Window) { + a.ClearOutput() + }}, + }}, + {Label: "视图", Submenu: []*mygo.MenuItem{ + {Label: "项目工具窗", Accelerator: "Alt+1", Click: func(*mygo.MenuItem, *mygo.Window) { + a.ToggleSidebar() + }}, + {Label: "切换内联提示", Click: func(*mygo.MenuItem, *mygo.Window) { + a.set.InlayHints = !a.set.InlayHints + saveSettings(a.set) + a.applySettings(a.set) + }}, + {Label: "运行/问题面板", Accelerator: "Alt+0", Click: func(*mygo.MenuItem, *mygo.Window) { + a.TogglePanel() + }}, + {Label: "新建终端(Ctrl+Shift+`)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.ToggleTerminal() + a.newTerm() + }}, + {Label: "关闭当前终端", Click: func(*mygo.MenuItem, *mygo.Window) { + a.closeTerm(a.termIdx) + }}, + {Label: "终端", Accelerator: "Alt+F12", Click: func(*mygo.MenuItem, *mygo.Window) { + a.ToggleTerminal() + }}, + {Label: "刷新文件树", Accelerator: "CmdOrCtrl+Shift+R", Click: func(*mygo.MenuItem, *mygo.Window) { + a.Refresh() + }}, + {Label: "代码缩略图", Accelerator: "CmdOrCtrl+Shift+M", Click: func(*mygo.MenuItem, *mygo.Window) { + a.ToggleMinimap() + }}, + mygo.Separator(), + {Label: "深色主题", Click: func(*mygo.MenuItem, *mygo.Window) { a.SetLight(false) }}, + {Label: "浅色主题", Click: func(*mygo.MenuItem, *mygo.Window) { a.SetLight(true) }}, + mygo.Separator(), + {Role: mygo.RoleToggleFullScreen}, + }}, + // 不用 RoleWindowMenu:Windows 上它固定叫 "Window",是系统角色菜单, + // 文案不走本地化,在全是中文的汉堡菜单里很突兀;而且单窗口 IDE + // 用不到它的窗口列表。 + {Label: "Git", Submenu: []*mygo.MenuItem{ + {Label: "刷新状态", Accelerator: "F5", Click: func(*mygo.MenuItem, *mygo.Window) { + a.refreshGit() + }}, + {Label: "查看当前文件差异(Ctrl+D)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.OpenDiff("") + }}, + {Label: "关闭差异视图", Click: func(*mygo.MenuItem, *mygo.Window) { + a.CloseDiff() + }}, + mygo.Separator(), + {Label: "提交…", Accelerator: "CmdOrCtrl+Enter", Click: func(*mygo.MenuItem, *mygo.Window) { + a.OpenCommit() + }}, + {Label: "拉取(pull)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.gitPull() + }}, + {Label: "推送(push)", Click: func(*mygo.MenuItem, *mygo.Window) { + a.gitPush() + }}, + }}, + {Label: "帮助", Submenu: []*mygo.MenuItem{ + {Label: "关于 MyGoland", Click: func(*mygo.MenuItem, *mygo.Window) { + a.About() + }}, + mygo.Separator(), + {Label: "打开日志", Click: func(*mygo.MenuItem, *mygo.Window) { + if p := LogPath(); p != "" { + _ = mygo.Shell.OpenPath(p) + } + }}, + {Label: "在文件夹中显示日志", Click: func(*mygo.MenuItem, *mygo.Window) { + if p := LogPath(); p != "" { + mygo.Shell.ShowItemInFolder(p) + } + }}, + }}, + } + return a.menuCache +} + +// editCommand 在当前编辑器上执行一个命令。 +func (a *App) editCommand(cmd editor.Command) { + if d := a.doc(); d != nil { + d.st.Run(cmd) + a.win.Update(func() {}) + } +} diff --git a/internal/app/minimap.go b/internal/app/minimap.go new file mode 100644 index 0000000..a7b1bc3 --- /dev/null +++ b/internal/app/minimap.go @@ -0,0 +1,224 @@ +package app + +import ( + "strings" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" +) + +const ( + // minimapWidth 是缩略图条的宽度。 + minimapWidth float32 = 88 + + // minimapLineH 是每一行在缩略图里占的高度。 + // 行数少时按它铺、铺不满就留白(IDEA 也是这样),行多了才压到编辑器高度; + // 若不管行数一律撑满,十几行的文件会被拉成几根粗竖条,反而看不出结构。 + minimapLineH float32 = 3 + + // minimapBlocks 是缩略图纵向切成的可点击块数上限。 + // mygo 的点击事件只给布尔值、不给坐标,没法把「点在哪一像素」直接换算成 + // 行号,所以切成若干等高块,每块自己带点击,点中即滚到该块首行。 + minimapBlocks = 72 +) + +// minimap 画右侧的代码缩略图。 +// +// mygo 的编辑器没有内置 minimap,但暴露了 Buffer.Line、ScrollTo、ScrollY +// 与 LineTop,足够自己拼一个。editorH 是编辑器实际高度(Element.Bounds), +// 用来判断内容要不要压缩、以及视口框该多高。 +func (a *App) minimap(c *ui.Context, d *Doc, editorH float32) { + t := c.Theme() + total := d.buf.LineCount() + if total <= 0 || !a.minimapOn || editorH <= 0 { + return + } + + // 整篇都看得见时不画缩略图:此时它没有任何导航价值,只会在右上角 + // 留一小撮线条,反而像块补丁。行高先按编辑器实际排版取。 + totalH := d.st.LineTop(total) + if totalH > 0 { + if lineH := totalH / float64(total); lineH > 0 { + if float64(editorH) >= lineH*float64(total) { + return + } + } + } + + contentH := float32(total) * minimapLineH + if contentH > editorH { + contentH = editorH + } + if contentH < 10 { + return + } + + frac, scroll := 1.0, 0.0 + if totalH > 0 { + if lineH := totalH / float64(total); lineH > 0 { + visible := float64(editorH) / lineH + if visible < float64(total) { + frac = visible / float64(total) + } + } + scroll = d.st.ScrollY() / totalH + if scroll < 0 { + scroll = 0 + } + if scroll+frac > 1 { + scroll = 1 - frac + } + } + + // 每块至少 16 DIP:ButtonBase 有约 14 的最小高度,切太密会被顶回来, + // 整条撑出可视区,点击位置随之错位。 + blocks := int(contentH / 16) + if blocks < 1 { + blocks = 1 + } + if blocks > minimapBlocks { + blocks = minimapBlocks + } + if blocks > total { + blocks = total + } + + // 缩略图里的两种线色跟随主题:代码行用次要文字色,注释再淡一档。 + codeCol, noteCol := t.TextMuted, t.TextMuted.Alpha(0.55) + + ui.Row(c).Width(minimapWidth).MinWidth(minimapWidth).MaxWidth(minimapWidth). + FillHeight().AlignItems(ui.Start).Children(func() { + // 一条细分隔线,把缩略图和代码区分开。 + ui.Box(c).Width(1).FillHeight().Background(c.Theme().Border.Alpha(0.55)) + + ui.Column(c).Grow(1).Height(contentH). + Clip(). + DrawOver(func(p *ui.Painter, r ui.Rect) { + // 整篇都看得见时不画视口框:没有滚动,框住全部反而多余。 + if frac >= 0.999 { + return + } + y0 := r.Y + r.H*float32(scroll) + h := r.H * float32(frac) + if h < 3 { + h = 3 + } + p.Fill(ui.Rect{X: r.X, Y: y0, W: r.W, H: h}, + c.Theme().Accent.Alpha(0.10), 0) + p.Line(r.X, y0, r.X+r.W, y0, 1, c.Theme().Accent.Alpha(0.42)) + p.Line(r.X, y0+h, r.X+r.W, y0+h, 1, c.Theme().Accent.Alpha(0.42)) + }). + Children(func() { + for i := 0; i < blocks; i++ { + start := i * total / blocks + end := (i + 1) * total / blocks + if end <= start { + continue + } + // ButtonBase 才有状态槽:普通 Box 的 Clicked 永远返回 false。 + cell := ui.ButtonBase(c).FillWidth().Grow(1).MinHeight(0). + Padding(0).Radius(0).Background(ui.RGBA(0, 0, 0, 0)). + Cursor(ui.CursorPointer) + cell.Draw(func(p *ui.Painter, r ui.Rect) { + drawMinimapCell(p, r, d.buf, start, end, codeCol, noteCol) + }) + if cell.Clicked() { + d.st.ScrollTo(start) + } + } + }) + }) +} + +// drawMinimapCell 把一个行区间画成若干细线:缩进决定起点,长度决定宽。 +// +// 拿不到语法 token 的颜色(editor 没导出 highlighter),所以只区分注释与 +// 代码两种,靠明暗差把注释块和代码块分开——在缩略图这个尺度已经够辨认 +// 结构,没必要为了上色去反射内部状态。 +func drawMinimapCell(p *ui.Painter, r ui.Rect, buf *editor.Buffer, start, end int, codeCol, noteCol ui.Color) { + n := end - start + if n <= 0 || r.H <= 0 { + return + } + lineH := r.H / float32(n) + + // 行高不足 1.5 px 时逐行画会糊成一片,按步长抽样。 + step := 1 + if lineH < 1.5 { + step = int(1.5/lineH) + 1 + } + + // 1.0 是把 88 列代码铺满 88 px:Go 代码多数在 80 列上下, + // 系数再小线条就只占半条,缩略图会很空。 + const charW = 1.0 + + for y := start; y < end; y += step { + text := buf.Line(y) + trimmed := strings.TrimSpace(text) + if trimmed == "" { + continue + } + + indent := 0 + for _, ch := range text { + switch ch { + case ' ': + indent++ + case '\t': + indent += 4 + default: + goto drawn + } + } + drawn: + + x0 := r.X + 3 + float32(indent)*charW + if x0 > r.X+r.W-4 { + x0 = r.X + r.W - 4 + } + w := float32(displayWidth(trimmed)) * charW + room := r.X + r.W - 3 - x0 + if w > room { + w = room + } + if w < 1.5 { + w = 1.5 + } + + col := codeCol + if isCommentLine(trimmed) { + col = noteCol + } + + h := lineH * float32(step) * 0.62 + if h < 1 { + h = 1 + } + p.Fill(ui.Rect{X: x0, Y: r.Y + float32(y-start)*lineH, W: w, H: h}, col, 0) + } +} + +// displayWidth 数一行代码占多少列:ASCII 算 1 列,中文等宽字符算 2 列。 +// 直接用 rune 数会把中文行算短一半,缩略图里注释行会莫名其妙比代码行还短。 +func displayWidth(s string) int { + n := 0 + for _, r := range s { + if r < 128 { + n++ + continue + } + n += 2 + } + return n +} + +// isCommentLine 判断这一行是不是注释,用来在缩略图里压暗。 +func isCommentLine(s string) bool { + switch { + case strings.HasPrefix(s, "//"), strings.HasPrefix(s, "/*"), + strings.HasPrefix(s, "*"), strings.HasPrefix(s, "#"), + strings.HasPrefix(s, "--"): + return true + } + return false +} diff --git a/internal/app/newfile.go b/internal/app/newfile.go new file mode 100644 index 0000000..b5b3759 --- /dev/null +++ b/internal/app/newfile.go @@ -0,0 +1,191 @@ +package app + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "unicode" + + "github.com/egoist/mygo/ui" +) + +// beginNew 打开「新建文件/文件夹」的输入框,target 是落点目录。 +func (a *App) beginNew(dir string, isDir bool) { + a.newDir = dir + a.newIsDir = isDir + a.newName = "" + // 每次新建都回到默认勾选:大多数人新建 .go 就是想要那份示例。 + a.newExample = true + a.newOpen = true + a.newOpenDlg = true + a.win.Update(func() {}) +} + +// newEntryDialog 画新建文件/文件夹的小弹窗。 +// +// 关键点是「点遮罩不关闭」。ui.Modal 里这件事是写死的:coreDialogBase 会 +// `*open = false` 响应遮罩点击。所以这里传给它一个**局部副本** open—— +// 遮罩和 Esc 只能改副本,改不动 a.newOpen,下一帧弹窗照常重建;只有 +// 「取消」「确定」两个按钮才动 a.newOpen 真正关掉它。 +// +// (试过用 ui.Overlay 自搭遮罩,但 ui.Box 不支持 Center,面板会掉到右下角; +// Modal 自带居中,反而省事。) +func (a *App) newEntryDialog(c *ui.Context) { + if !a.newOpen { + return + } + t := c.Theme() + + ui.Modal(c, &a.newOpenDlg, func() { + ui.Column(c).Width(380).Gap(10).Children(func() { + title := "新建文件" + if a.newIsDir { + title = "新建文件夹" + } + ui.Text(c, title).FontSize(13).Bold().TextColor(t.Text) + ui.Text(c, a.newDir).FontSize(10).TextColor(t.TextMuted).SingleLine() + + ui.TextInput(c, &a.newName).FillWidth().FontSize(13) + + if !a.newIsDir && isGoFile(a.newName) { + ui.Checkbox(c, &a.newExample, "生成示例代码(package + Example 函数)") + } else if !a.newIsDir { + ui.Text(c, "新文件为空文件").FontSize(10).TextColor(t.TextMuted).SingleLine() + } + + ui.Row(c).Gap(8).Justify(ui.End).Children(func() { + if ui.Button(c, "取消").Clicked() { + a.newOpen = false + } + if ui.Button(c, "确定").Clicked() { + a.createEntry() + } + }) + }) + }) + + // ui.Modal 会把指针置 false 当作「要关闭」(点遮罩或按 Esc 都走这里)。 + // 这里立刻改回 true:弹窗只会闪一帧就回来,等于点遮罩关不掉。 + if !a.newOpenDlg && a.newOpen { + a.newOpenDlg = true + a.win.Update(func() {}) + } +} + +// createEntry 按输入的名字落盘,然后刷新树;新建文件会顺带打开它。 +func (a *App) createEntry() { + name := strings.TrimSpace(a.newName) + if name == "" || a.win == nil { + return + } + // 只接受单段名字:带分隔符就把目录带跑了,容易写到自己没看的地方。 + if strings.ContainsAny(name, `/\`) { + a.appendOut("名字里不能带路径分隔符: " + name) + a.panel = true + a.win.Update(func() {}) + return + } + + target := filepath.Join(a.newDir, name) + var err error + if a.newIsDir { + err = os.MkdirAll(target, 0o755) + } else { + if d := filepath.Dir(target); d != "" { + err = os.MkdirAll(d, 0o755) + } + if err == nil { + var content string + if isGoFile(name) { + if a.newExample { + content = goFileTemplate(target) + } else { + // 不勾示例就只写一行包名,其余留空。 + content = "package " + goPackageName(target) + "\n" + } + } + err = os.WriteFile(target, []byte(content), 0o644) + } + } + if err != nil { + a.appendOut(err.Error()) + a.panel = true + a.win.Update(func() {}) + return + } + + isDir := a.newIsDir + a.newOpen = false + a.newName = "" + a.Refresh() + a.win.Update(func() {}) + if !isDir { + go a.OpenFile(target) + } +} + +func isGoFile(name string) bool { + return strings.HasSuffix(strings.ToLower(name), ".go") +} + +// goPackageName 决定新建 .go 文件的包名:main.go 是程序入口, +// 其余按所在目录命名(目录名可能不是合法标识符,要规范化)。 +func goPackageName(target string) string { + if strings.ToLower(filepath.Base(target)) == "main.go" { + return "main" + } + return packageName(filepath.Base(filepath.Dir(target))) +} + +// goFileTemplate 返回勾选「生成示例代码」时的初始内容。 +// +// main.go 给一个能直接跑的 main:新建的入口文件八成就是为了跑起来。 +// 其余文件给 Go 的示例函数(Example),它是唯一既当文档、又能被 go test +// 直接执行并校验输出(// Output: 注释)的写法,比空函数更有用。 +func goFileTemplate(target string) string { + pkg := goPackageName(target) + if pkg == "main" { + return `package main + +import "fmt" + +func main() { + fmt.Println("Hello, World!") +} +` + } + return fmt.Sprintf(`package %s + +import "fmt" + +// Example 是一个可直接运行的示例:go test 会执行它, +// 并把输出与下面的 Output 注释比对。 +func Example() { + fmt.Println("Hello, World!") + // Output: Hello, World! +} +`, pkg) +} + +// packageName 把目录名变成一个合法的 Go 包名: +// 只留字母数字与下划线,转小写,数字开头补下划线,空的话退回 main。 +func packageName(dir string) string { + var b strings.Builder + for _, r := range strings.ToLower(dir) { + switch { + case unicode.IsLetter(r) || unicode.IsDigit(r): + b.WriteRune(r) + case r == '_': + b.WriteRune(r) + } + } + name := b.String() + if name == "" { + return "main" + } + if unicode.IsDigit(rune(name[0])) { + name = "_" + name + } + return name +} diff --git a/internal/app/outline.go b/internal/app/outline.go new file mode 100644 index 0000000..8c0ceba --- /dev/null +++ b/internal/app/outline.go @@ -0,0 +1,201 @@ +package app + +import ( + "context" + "time" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" + + "mygoland/internal/lsp" +) + +// outlineItem 是大纲里的一个符号,已经按层级铺平。 +type outlineItem struct { + Name string + Kind int + Line int // 0 起 + Col int + Depth int +} + +// outlineDebounce 是重新取符号的最小间隔,避免每敲一个字就请求一次。 +const outlineDebounce = 400 * time.Millisecond + +// syncOutline 在需要时向语言服务器要当前文件的符号树。 +func (a *App) syncOutline(d *Doc) { + if a.panelKind != 1 || d == nil || a.lsp == nil || !lsp.IsGoFile(d.path) { + return + } + ver := d.buf.Version() + if d.path == a.outlinePath && ver == a.outlineVer { + return + } + if time.Since(a.outlineAt) < outlineDebounce { + return + } + a.outlineAt = time.Now() + a.outlinePath = d.path + a.outlineVer = ver + + uri := d.uri + c := a.lsp + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + syms, err := c.DocumentSymbol(ctx, uri) + if err != nil { + return + } + items := flattenSymbols(syms, 0, nil) + logf("outline: %d symbols from %s", len(items), uri) + a.win.Update(func() { + if a.doc() != d { + return + } + a.outline = items + }) + }() +} + +// flattenSymbols 把符号树铺成带缩进的列表。 +func flattenSymbols(syms []lsp.DocumentSymbol, depth int, out []outlineItem) []outlineItem { + for _, s := range syms { + out = append(out, outlineItem{ + Name: s.Name, + Kind: s.Kind, + Line: s.SelectionRange.Start.Line, + Col: s.SelectionRange.Start.Character, + Depth: depth, + }) + if len(s.Children) > 0 { + out = flattenSymbols(s.Children, depth+1, out) + } + } + return out +} + +// outlineView 是左侧「大纲」面板。 +func (a *App) outlineView(c *ui.Context) { + t := c.Theme() + ui.Column(c).FillHeight().Radius(t.Radius).Background(t.Surface).Clip().Children(func() { + ui.Row(c).Padding(6, 8).Gap(4).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + ui.Text(c, "大纲").FontSize(11).Bold().TextColor(t.TextMuted) + ui.Box(c).Grow(1) + ui.Textf(c, "%d", len(a.outline)).FontSize(10).TextColor(t.TextMuted) + }) + + d := a.doc() + if d == nil { + a.outlineEmpty(c, "没有打开的文件") + return + } + if a.lsp == nil { + a.outlineEmpty(c, "语言服务器未就绪") + return + } + if !lsp.IsGoFile(d.path) { + a.outlineEmpty(c, "大纲暂时只支持 Go 文件") + return + } + // 切了文件先清空,避免短暂显示上一个文件的符号。 + if a.outlinePath != d.path { + a.outline = nil + } + a.syncOutline(d) + if len(a.outline) == 0 { + a.outlineEmpty(c, "正在分析…") + return + } + + ui.Scroll(c).Grow(1).Children(func() { + ui.Column(c).Padding(2, 4).Gap(1).Children(func() { + a.selectedOutline = a.outlineRowIndex(d) + for i := range a.outline { + a.outlineRow(c, d, i) + } + }) + }) + }) +} + +// outlineEmpty 画一句占位说明。 +func (a *App) outlineEmpty(c *ui.Context, msg string) { + t := c.Theme() + ui.Column(c).Grow(1).Padding(10, 10).Children(func() { + ui.Text(c, msg).FontSize(12).TextColor(t.TextMuted).SingleLine() + }) +} + +// outlineRow 画一个符号。 +func (a *App) outlineRow(c *ui.Context, d *Doc, i int) { + t := c.Theme() + it := a.outline[i] + active := i == a.selectedOutline + + row := ui.ButtonBase(c).FillWidth().Padding(1, 4).Gap(5).Radius(3). + Justify(ui.Start).AlignItems(ui.Center).Cursor(ui.CursorPointer) + bgT := ui.RGBA(0, 0, 0, 0) + if active { + bgT = t.Accent.Alpha(0.16) + } else if row.Hovered() { + bgT = t.SurfaceHover + } + bg := row.AnimateColor("olbg", bgT, ui.Animation{Duration: 120 * time.Millisecond}) + row = row.Background(bg) + + row.Children(func() { + if it.Depth > 0 { + ui.Box(c).Width(float32(it.Depth) * 12) + } + // 用一个小色块代替类型图标,颜色区分函数/类型/字段。 + ui.Box(c).Width(6).Height(6).Radius(1).Background(symbolColor(t, it.Kind)) + ui.Text(c, it.Name).FontSize(12).TextColor(condColor(t, active)).SingleLine() + }) + + if row.Clicked() { + a.selectedOutline = i + a.gotoOutline(d, it) + } +} + +// gotoOutline 跳到符号所在位置。 +func (a *App) gotoOutline(d *Doc, it outlineItem) { + if it.Line < 0 || it.Line >= d.buf.LineCount() { + return + } + line := d.buf.Line(it.Line) + col := lsp.UTF16ToByte(line, it.Col) + d.st.GoTo(editor.Pos{Line: it.Line, Col: col}) + d.st.ScrollTo(it.Line) + a.win.Update(func() { a.active = d.path }) +} + +// outlineRowIndex 返回光标所在符号的行号,没有匹配则 -1。 +func (a *App) outlineRowIndex(d *Doc) int { + if d == nil || len(a.outline) == 0 { + return -1 + } + cur := d.st.CursorPos().Line + best := -1 + for i, it := range a.outline { + if it.Line <= cur && (best < 0 || it.Line >= a.outline[best].Line) { + best = i + } + } + return best +} + +// symbolColor 按符号类型给出颜色。 +func symbolColor(t *ui.Theme, kind int) ui.Color { + switch kind { + case 5, 10, 11, 22, 23, 26: // 类、字段、枚举、结构、类型参数 + return t.Warning + case 6, 9, 12: // 方法、构造函数、函数 + return t.Accent + case 8, 13, 14: // 接口、枚举成员、常量 + return t.Success + } + return t.TextMuted +} diff --git a/internal/app/outline_test.go b/internal/app/outline_test.go new file mode 100644 index 0000000..433414d --- /dev/null +++ b/internal/app/outline_test.go @@ -0,0 +1,55 @@ +package app + +import ( + "testing" + + "mygoland/internal/lsp" +) + +func sym(name string, kind int, line int, children ...lsp.DocumentSymbol) lsp.DocumentSymbol { + return lsp.DocumentSymbol{ + Name: name, + Kind: kind, + Range: lsp.Range{Start: lsp.Position{Line: line}, End: lsp.Position{Line: line}}, + SelectionRange: lsp.Range{Start: lsp.Position{Line: line}, End: lsp.Position{Line: line}}, + Children: children, + } +} + +func TestFlattenSymbols(t *testing.T) { + syms := []lsp.DocumentSymbol{ + sym("helper", 12, 2), + sym("point", 23, 4, + sym("X", 8, 5), + sym("Y", 8, 6), + ), + sym("main", 12, 9), + } + got := flattenSymbols(syms, 0, nil) + if len(got) != 5 { + t.Fatalf("应当铺平出 5 项,实际 %d: %+v", len(got), got) + } + want := []struct { + name string + line int + depth int + }{ + {"helper", 2, 0}, + {"point", 4, 0}, + {"X", 5, 1}, + {"Y", 6, 1}, + {"main", 9, 0}, + } + for i, w := range want { + if got[i].Name != w.name || got[i].Line != w.line || got[i].Depth != w.depth { + t.Fatalf("第 %d 项不对: got %+v want %+v", i, got[i], w) + } + } +} + +func TestSymbolColorDiffers(t *testing.T) { + th := theme(false) + if symbolColor(th, 12) == symbolColor(th, 23) { + t.Fatal("函数与类型应当用不同颜色") + } +} diff --git a/internal/app/output.go b/internal/app/output.go new file mode 100644 index 0000000..4133f8a --- /dev/null +++ b/internal/app/output.go @@ -0,0 +1,560 @@ +package app + +import ( + "fmt" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" + + "mygoland/internal/task" +) + +// OutKind 是输出行的类别,决定颜色与语义。 +type OutKind int + +// 输出行的类别。 +const ( + OutPlain OutKind = iota + OutCmd + OutHeader + OutError + OutWarn + OutSuccess +) + +// SourceLoc 是可以跳转的源码位置,行列从 1 开始。 +type SourceLoc struct { + Path string + Line int + Col int +} + +// OutLine 是输出面板里的一行。 +type OutLine struct { + Text string + Kind OutKind + Loc *SourceLoc +} + +// Problem 是「问题」面板里的一条诊断,行号从 1 开始。 +type Problem struct { + Path string + Line int + Col int + Text string + Severity editor.Severity + // Source 标出来源:空表示语言服务器,其它值是外部检查(如 go vet)。 + Source string +} + +// maxOutLines 限制输出缓存的行数,超出后丢弃最早的一批。 +const maxOutLines = 8000 + +// RunBuild 构建当前工作区的所有包。 +func (a *App) RunBuild() { + a.startTask("go build ./...", "go", "build", "./...") +} + +// RunProgram 运行当前文件所属的 main 包。 +// +// 以前固定跑 go run .,打开子目录里的 main.go 时跑的却是根包,很容易以为 +// 「运行没反应」。现在先看当前文件:它是 main 包的 .go 文件就跑它所在的目录, +// 否则退回工作区根包。跑之前把改动落盘,免得执行的是上一次的代码。 +func (a *App) RunProgram() { + if d := a.doc(); d != nil && d.buf.Modified() { + a.writeDoc(d) + } + + pkg, label := ".", "go run ." + if d := a.doc(); d != nil { + if dir, ok := mainPkgDir(d); ok { + if rel, err := filepath.Rel(a.root, dir); err == nil { + switch { + case rel == ".": + pkg, label = ".", "go run ." + case !strings.HasPrefix(rel, ".."): + pkg = "./" + filepath.ToSlash(rel) + label = "go run " + pkg + } + } + } + } + a.startTask(label, "go", "run", pkg) +} + +// mainPkgDir 判断文档是不是 main 包里能直接跑的文件,返回它所在的目录。 +func mainPkgDir(d *Doc) (string, bool) { + if !strings.HasSuffix(d.path, ".go") || strings.HasSuffix(d.path, "_test.go") { + return "", false + } + src := d.buf.String() + if !strings.Contains(src, "func main(") { + return "", false + } + // 只看第一个有效行是不是 package main。 + for _, line := range strings.Split(src, "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "//") { + continue + } + if !strings.HasPrefix(line, "package ") { + return "", false + } + name := strings.TrimSpace(strings.TrimPrefix(line, "package ")) + return filepath.Dir(d.path), name == "main" + } + return "", false +} + +// RunTests 运行工作区的所有测试。 +func (a *App) RunTests() { + a.startTask("go test ./...", "go", "test", "./...") +} + +// StopTask 结束正在运行的命令。 +func (a *App) StopTask() { + if a.run != nil { + a.run.Stop() + } +} + +// ClearOutput 清空输出。 +func (a *App) ClearOutput() { + a.out = nil + a.outSel = -1 + a.win.Update(func() {}) +} + +// TogglePanel 显示或隐藏输出面板。 +func (a *App) TogglePanel() { + a.panel = !a.panel + if !a.panel { + a.focusEditorSoon() + } + if a.panel && a.panelH < 80 { + a.panelH = 220 + } + a.saveSession() + a.win.Update(func() {}) +} + +// startTask 在后台启动命令,输出进入面板。 +func (a *App) startTask(label, name string, args ...string) { + if a.root == "" { + return + } + if a.running { + a.StopTask() + } + a.panel = true + a.panelTab = 0 + if a.panelH < 80 { + a.panelH = 220 + } + a.appendOut("$ " + label) + + t, err := task.Start(a.root, name, args...) + if err != nil { + a.appendOut(err.Error()) + a.running = false + a.win.Update(func() {}) + return + } + a.run = t + a.running = true + a.win.Update(func() {}) + go a.pump(t) +} + +// pump 收集命令输出,按批刷到界面,避免逐行触发重绘。 +func (a *App) pump(t *task.Task) { + var batch []string + flush := func() { + if len(batch) == 0 { + return + } + lines := batch + batch = nil + a.win.Update(func() { + for _, s := range lines { + a.appendOut(s) + } + }) + } + ticker := time.NewTicker(60 * time.Millisecond) + defer ticker.Stop() + for { + select { + case line, ok := <-t.Lines: + if !ok { + flush() + a.win.Update(func() { a.finishTask(t) }) + return + } + batch = append(batch, line) + if len(batch) >= 200 { + flush() + } + case <-ticker.C: + flush() + } + } +} + +// finishTask 收尾并把退出码写进输出。 +func (a *App) finishTask(t *task.Task) { + if a.run != t { + return + } + a.running = false + a.run = nil + code := t.ExitCode() + logf("command %q exited %d, %d lines", t.Name, code, len(a.out)) + switch { + case t.Stopped(): + a.appendOut("⏹ 已停止") + case code == 0: + a.out = append(a.out, OutLine{Text: "✔ 完成", Kind: OutSuccess}) + default: + a.out = append(a.out, OutLine{Text: "✕ 退出码 " + strconv.Itoa(code), Kind: OutError}) + } +} + +// appendOut 解析并追加一行输出,须在主线程调用。 +func (a *App) appendOut(s string) { + a.out = append(a.out, parseOutLine(s)) + if len(a.out) > maxOutLines { + a.out = a.out[len(a.out)-maxOutLines:] + } +} + +// parseOutLine 识别编译错误位置与输出类别。 +func parseOutLine(s string) OutLine { + if loc, ok := splitLoc(strings.TrimLeft(s, " \t")); ok { + return OutLine{Text: s, Kind: OutError, Loc: loc} + } + switch { + case strings.HasPrefix(s, "# "): + return OutLine{Text: s, Kind: OutHeader} + case strings.HasPrefix(s, "ok ") || strings.HasPrefix(s, "ok\t"): + return OutLine{Text: s, Kind: OutSuccess} + case strings.HasPrefix(s, "FAIL"), strings.HasPrefix(s, "panic:"): + return OutLine{Text: s, Kind: OutError} + case strings.HasPrefix(s, "---"), strings.HasPrefix(s, "==="): + return OutLine{Text: s, Kind: OutWarn} + } + return OutLine{Text: s, Kind: OutPlain} +} + +// splitLoc 从 "path:line[:col]: msg" 中解析出位置。 +// +// 只认第一个后面紧跟数字的冒号,Windows 盘符里的冒号会被跳过; +// 解析失败就整体放弃,避免把时间戳之类的内容误判成源码位置。 +func splitLoc(s string) (*SourceLoc, bool) { + sep := -1 + for k := 0; k < len(s); k++ { + if s[k] == ':' && k+1 < len(s) && s[k+1] >= '0' && s[k+1] <= '9' { + sep = k + break + } + } + if sep < 0 { + return nil, false + } + j := sep + 1 + for j < len(s) && s[j] >= '0' && s[j] <= '9' { + j++ + } + line, err := strconv.Atoi(s[sep+1 : j]) + if err != nil || line <= 0 { + return nil, false + } + col := 0 + k := j + if k < len(s) && s[k] == ':' && k+1 < len(s) && s[k+1] >= '0' && s[k+1] <= '9' { + m := k + 1 + for m < len(s) && s[m] >= '0' && s[m] <= '9' { + m++ + } + col, _ = strconv.Atoi(s[k+1 : m]) + k = m + } + path := s[:sep] + if path == "" || strings.ContainsAny(path, " \t") { + return nil, false + } + // 路径必须带扩展名或分隔符,避免把 "10:23:45" 这类时间当成位置。 + if !strings.ContainsAny(path, "./\\") { + return nil, false + } + // 位置之后必须是冒号或空白,否则可能是别的内容。 + if k < len(s) && s[k] != ':' && s[k] != ' ' && s[k] != '\t' { + return nil, false + } + return &SourceLoc{Path: path, Line: line, Col: col}, true +} + +// jumpTo 打开输出行指向的源码位置。 +func (a *App) jumpTo(loc *SourceLoc) { + if loc == nil { + return + } + p := loc.Path + if !filepath.IsAbs(p) { + p = filepath.Join(a.root, p) + } + p = filepath.Clean(p) + a.win.Update(func() { + d, err := a.loadDoc(p) + if err != nil { + a.alert("无法跳转", err.Error()) + return + } + line := loc.Line - 1 + if line < 0 { + line = 0 + } + if line >= d.buf.LineCount() { + line = d.buf.LineCount() - 1 + } + col := loc.Col - 1 + if col < 0 { + col = 0 + } + if n := len(d.buf.Line(line)); col > n { + col = n + } + d.st.GoTo(editor.Pos{Line: line, Col: col}) + d.st.ScrollTo(line) + }) +} + +// panelView 是底部面板,含「运行」与「问题」两个页签。 +// panelView 是底部面板在 SplitVertical 里的那一格,上方让出 4 DIP 的沟。 +func (a *App) panelView(c *ui.Context) { + ui.Column(c).FillHeight().Padding(4, 0, 0, 0).Children(func() { + a.panelPanel(c) + }) +} + +// panelPanel 是底部的「运行 / 问题」面板本体。 +func (a *App) panelPanel(c *ui.Context) { + t := c.Theme() + // 底色交给外层卡片:自己再铺一层会把卡片底部圆角盖成直角。 + ui.Column(c).FillHeight().Children(func() { + ui.Row(c).Padding(2, 6).Gap(2).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + a.panelTabButton(c, "运行", 0, a.running) + a.panelTabButton(c, "问题", 1, false) + a.panelTabButton(c, a.debugTabLabel(), 2, a.dbg != nil) + a.panelTabButton(c, "断点", 4, len(a.bps) > 0) + a.panelTabButton(c, a.testTabLabel(), 5, a.test.running) + a.panelTabButton(c, "覆盖率", 6, a.cover.running) + a.panelTabButton(c, "终端", 3, false) + ui.Box(c).Grow(1) + if a.panelTab == 1 { + if iconButton(c, "test", "检查", "对全工作区跑 go vet", t.TextMuted) { + a.RunWorkspaceCheck() + } + } + if a.panelTab == 0 { + if iconButton(c, "build", "构建", "go build ./...", t.TextMuted) { + a.RunBuild() + } + if iconButton(c, "run", "运行", "go run .", t.Accent) { + a.RunProgram() + } + if iconButton(c, "test", "测试", "跑测试并显示结果树", t.TextMuted) { + a.RunTestTree("") + } + if a.running { + if iconButton(c, "stop", "停止", "结束当前命令", t.Danger) { + a.StopTask() + } + } + if iconButton(c, "clear", "清空", "清空输出", t.TextMuted) { + a.ClearOutput() + } + } + if iconButton(c, "hide", "", "收起面板", t.TextMuted) { + a.TogglePanel() + } + }) + switch a.panelTab { + case 0: + a.runView(c) + case 2: + a.debugView(c) + case 3: + a.terminalView(c) + case 4: + a.breakpointView(c) + case 5: + a.testView(c) + case 6: + a.coverageView(c) + default: + a.problemView(c) + } + }) +} + +// panelTabButton 是面板顶部的一个页签。 +func (a *App) panelTabButton(c *ui.Context, label string, idx int, busy bool) { + t := c.Theme() + active := a.panelTab == idx + color := t.TextMuted + if active { + color = t.Text + } + text := label + if busy { + text += " ●" + } + e := ui.ButtonBase(c).Padding(3, 8).Children(func() { + ui.Text(c, text).FontSize(12).TextColor(color) + }) + if e.Clicked() { + a.panelTab = idx + } +} + +// runView 是「运行」页签的内容。 +func (a *App) runView(c *ui.Context) { + list := ui.List(c, &a.outState, len(a.out), func(i int) { a.outRow(c, i) }).Grow(1).FillWidth() + if list.Changed() && a.outSel >= 0 && a.outSel < len(a.out) { + if loc := a.out[a.outSel].Loc; loc != nil { + a.jumpTo(loc) + } + } +} + +// problemView 是「问题」页签的内容。 +func (a *App) problemView(c *ui.Context) { + t := c.Theme() + + // 头部:来源计数 + 手动全工作区检查。 + ui.Row(c).FillWidth().Padding(2, 6).Gap(8).AlignItems(ui.Center).Children(func() { + lspN, wsN := 0, 0 + for _, p := range a.allProblems() { + if p.Source == "" { + lspN++ + } else { + wsN++ + } + } + ui.Textf(c, "语言服务器 %d · 工作区 %d", lspN, wsN).FontSize(10).TextColor(t.TextMuted) + ui.Box(c).Grow(1) + if a.wsState.on { + ui.Text(c, "检查中…").FontSize(10).TextColor(t.TextMuted) + } else { + ui.Text(c, "用右上角的「检查」跑一遍全工作区").FontSize(10).TextColor(t.TextMuted) + } + }) + + ps := a.allProblems() + if len(ps) == 0 { + // FillHeight 不能省:只写 Grow 时这一列高度为 0,文字会“消失”。 + ui.Column(c).Grow(1).FillHeight().Center().Children(func() { + ui.Text(c, "没有发现问题").FontSize(12).TextColor(t.TextMuted) + }) + return + } + list := ui.List(c, &a.probState, len(ps), func(i int) { a.problemRow(c, i, ps) }).Grow(1).FillWidth() + if list.Changed() && a.probSel >= 0 && a.probSel < len(ps) { + p := ps[a.probSel] + a.jumpTo(&SourceLoc{Path: p.Path, Line: p.Line, Col: p.Col}) + } +} + +// allProblems 汇总所有已打开文件的诊断。 +func (a *App) allProblems() []Problem { + var out []Problem + for _, d := range a.docs { + out = append(out, d.problems...) + } + // 语言服务器的诊断更精确(有完整区间),重复的 vet 条目就不要再列一遍。 + seen := map[string]bool{} + for _, p := range out { + seen[problemKey(p)] = true + } + for _, p := range a.wsState.items { + if seen[problemKey(p)] { + continue + } + seen[problemKey(p)] = true + out = append(out, p) + } + return out +} + +// problemKey 是去重用的键:同一文件同一行同样的文字,只留一条。 +func problemKey(p Problem) string { + return fmt.Sprintf("%s:%d:%s", p.Path, p.Line, p.Text) +} + +// problemRow 画出一条诊断。 +func (a *App) problemRow(c *ui.Context, i int, ps []Problem) { + if i < 0 || i >= len(ps) { + return + } + t := c.Theme() + p := ps[i] + color := t.Danger + switch p.Severity { + case editor.SeverityWarning: + color = t.Warning + case editor.SeverityInfo, editor.SeverityHint: + color = t.TextMuted + } + tag := "" + if p.Source != "" { + tag = "[" + p.Source + "] " + } + text := fmt.Sprintf("%s%s:%d %s", tag, filepath.Base(p.Path), p.Line, p.Text) + ui.Text(c, text).FontSize(12).TextColor(color).SingleLine() +} + +// outRow 画出一行输出。 +func (a *App) outRow(c *ui.Context, i int) { + if i < 0 || i >= len(a.out) { + return + } + t := c.Theme() + l := a.out[i] + color := t.Text + switch l.Kind { + case OutError: + color = t.Danger + case OutWarn: + color = t.Warning + case OutSuccess: + color = t.Success + case OutHeader: + color = t.Accent + case OutCmd: + color = t.TextMuted + } + ui.Text(c, l.Text).FontSize(12).TextColor(color).SingleLine() +} + +// statusPanelHint 在状态栏右侧提供面板入口。 +func (a *App) statusPanelHint(c *ui.Context) { + t := c.Theme() + label := "面板" + color := t.TextMuted + if a.running { + label = "面板 ●" + color = t.Accent + } + e := ui.ButtonBase(c).Padding(0, 8).Children(func() { + ui.Text(c, label).FontSize(11).TextColor(color) + }) + if e.Clicked() { + a.TogglePanel() + } +} diff --git a/internal/app/output_test.go b/internal/app/output_test.go new file mode 100644 index 0000000..154b4af --- /dev/null +++ b/internal/app/output_test.go @@ -0,0 +1,58 @@ +package app + +import "testing" + +func TestSplitLoc(t *testing.T) { + tests := []struct { + in string + ok bool + path string + line int + col int + }{ + {"internal/app/app.go:42:7: undefined: x", true, "internal/app/app.go", 42, 7}, + {`D:\work\demo\main.go:10: cannot use n`, true, `D:\work\demo\main.go`, 10, 0}, + {"./main.go:3:1: syntax error", true, "./main.go", 3, 1}, + {"2026/10/29 10:23:45 something", false, "", 0, 0}, + {"go: downloading example.com/x v1.0.0", false, "", 0, 0}, + {"plain output", false, "", 0, 0}, + {"main.go:0:1: bad line", false, "", 0, 0}, + } + for _, tt := range tests { + loc, ok := splitLoc(tt.in) + if ok != tt.ok { + t.Fatalf("%q: ok got %v want %v", tt.in, ok, tt.ok) + } + if !ok { + continue + } + if loc.Path != tt.path || loc.Line != tt.line || loc.Col != tt.col { + t.Fatalf("%q: got %+v want %s:%d:%d", tt.in, loc, tt.path, tt.line, tt.col) + } + } +} + +func TestParseOutLine(t *testing.T) { + tests := []struct { + in string + kind OutKind + loc bool + }{ + {"# demo/pkg", OutHeader, false}, + {"ok \tdemo/pkg\t0.012s", OutSuccess, false}, + {"FAIL\tdemo/pkg [build failed]", OutError, false}, + {"--- FAIL: TestX (0.00s)", OutWarn, false}, + {"panic: runtime error: index out of range", OutError, false}, + {"main.go:5:2: undefined: foo", OutError, true}, + {"just some text", OutPlain, false}, + } + for _, tt := range tests { + got := parseOutLine(tt.in) + if got.Kind != tt.kind { + t.Fatalf("%q: kind got %v want %v", tt.in, got.Kind, tt.kind) + } + if (got.Loc != nil) != tt.loc { + t.Fatalf("%q: loc got %v want %v", tt.in, got.Loc, tt.loc) + } + } +} diff --git a/internal/app/palette.go b/internal/app/palette.go new file mode 100644 index 0000000..8f42845 --- /dev/null +++ b/internal/app/palette.go @@ -0,0 +1,626 @@ +package app + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "time" + "unicode/utf8" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" +) + +// itemKind 区分候选类型:文件(快速打开)与命中行(全局搜索)。 +type itemKind int + +const ( + itemFile itemKind = iota + itemLine +) + +// paletteItem 是命令面板里的一行。 +type paletteItem struct { + Kind itemKind + Path string + Line int // 1 起,仅 itemLine 使用 + Label string + Hint string + Text string + // Idx 是它在调用方数组里的下标(代码动作用)。 + Idx int +} + +// paletteState 是命令面板(快速打开 / 全局搜索)的状态。 +type paletteState struct { + open bool + search bool + // refs 是「查找引用」模式:候选已经算好,输入只做本地过滤。 + refs bool + refsAll []paletteItem + // action 是「代码动作」模式:候选固定,回车执行 a.actions[idx]。 + action bool + // recent 是「最近项目」模式:回车切换工作区。 + recent bool + // symbol 是「转到符号」模式:查询打给 gopls 的 workspace/symbol。 + symbol bool + // 全局搜索的匹配选项。 + useRegex bool + matchCase bool + wholeWord bool + query string + lastQ string + sel int + items []paletteItem + gen int + waiting bool + + // 全局搜索的替换:replaceTo 是「替换为」,replacing 表示正在显示 + // 预览(此时候选列表被替换成文件清单 + 确认按钮),planning 表示 + // 正在后台算预览。plan 由 buildReplacePlan 填。 + replaceTo string + replacing bool + planning bool + plan replacePlan +} + +// paletteLimit 是结果条数上限。 +const paletteLimit = 200 + +// OpenQuick 打开「快速打开」面板。 +func (a *App) OpenQuick() { + if a.root == "" { + return + } + a.pal = paletteState{open: true} + if files, ready := a.indexSnapshot(); !ready || len(files) == 0 { + a.resetIndex(a.root) + a.buildIndex(a.root) + } + a.pal.items = a.quickResults("", 60) + a.win.Update(func() {}) +} + +// OpenSearch 打开「全局搜索」面板。 +func (a *App) OpenSearch() { + if a.root == "" { + return + } + a.pal = paletteState{open: true, search: true} + a.win.Update(func() {}) +} + +// refreshPalette 在查询变化后重算候选。 +func (a *App) refreshPalette() { + a.pal.lastQ = a.pal.query + a.pal.sel = 0 + // 查询或匹配选项一变,替换预览就过期了:退回搜索态。 + a.pal.replacing = false + a.pal.plan = replacePlan{} + a.pal.planning = false + if a.pal.recent { + q := strings.ToLower(strings.TrimSpace(a.pal.query)) + if q == "" { + a.pal.items = a.pal.refsAll + return + } + var out []paletteItem + for _, it := range a.pal.refsAll { + if strings.Contains(strings.ToLower(it.Label), q) || strings.Contains(strings.ToLower(it.Hint), q) { + out = append(out, it) + } + } + a.pal.items = out + return + } + if a.pal.symbol { + // 结果由 gopls 给,这里只发起查询;回来时自己填 items。 + a.scheduleSymbols(symbolHint(a.pal.query)) + return + } + if a.pal.action { + // 动作列表通常只有几条,按标题前缀过滤就够。 + q := strings.ToLower(strings.TrimSpace(a.pal.query)) + if q == "" { + a.pal.items = a.pal.refsAll + return + } + var out []paletteItem + for _, it := range a.pal.refsAll { + if strings.Contains(strings.ToLower(it.Label), q) { + out = append(out, it) + } + } + a.pal.items = out + return + } + if a.pal.refs { + q := strings.ToLower(strings.TrimSpace(a.pal.query)) + if q == "" { + a.pal.items = a.pal.refsAll + return + } + var out []paletteItem + for _, it := range a.pal.refsAll { + if strings.Contains(strings.ToLower(it.Label), q) || strings.Contains(strings.ToLower(it.Text), q) { + out = append(out, it) + } + } + a.pal.items = out + return + } + if !a.pal.search { + a.pal.items = a.quickResults(a.pal.query, 60) + return + } + if strings.TrimSpace(a.pal.query) == "" { + a.pal.items = nil + a.pal.waiting = false + return + } + a.pal.gen++ + gen := a.pal.gen + a.pal.waiting = true + q := a.pal.query + opt := searchOpts{useRegex: a.pal.useRegex, matchCase: a.pal.matchCase, wholeWord: a.pal.wholeWord} + go func() { + // 轻微去抖:连续输入时只跑最后一次。 + time.Sleep(220 * time.Millisecond) + items := a.searchInWorkspace(q, paletteLimit, opt) + a.win.Update(func() { + if !a.pal.open || gen != a.pal.gen { + return + } + a.pal.items = items + a.pal.waiting = false + }) + }() +} + +// searchOpts 是全局搜索的匹配选项。 +type searchOpts struct { + useRegex bool + matchCase bool + wholeWord bool +} + +// buildReplaceRe 按选项装配正则;buildMatcher 与替换共用(见 replace.go)。 + +// buildMatcher 按选项造一个行匹配函数。 +// +// 正则和整词都走 regexp:整词就是在转义后的模式外面套 \b, +// 比手写边界判断可靠(中文没有词边界,套 \b 会退化成普通包含,正好符合预期)。 +func buildMatcher(query string, o searchOpts) (func(string) bool, error) { + re, err := buildReplaceRe(query, o) + if err != nil { + return nil, err + } + return re.MatchString, nil +} + +// workspaceFiles 返回工作区文件清单(仓库相对路径,正斜杠)。 +// 索引没建好就现场走一遍,避免搜索/替换面板空着。 +func (a *App) workspaceFiles() []string { + root := a.root + if root == "" { + return nil + } + if files, ready := a.indexSnapshot(); ready { + return files + } + var files []string + _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() { + if p != root && skipDir(d.Name()) { + return filepath.SkipDir + } + return nil + } + if skipFile(d.Name()) { + return nil + } + if rel, err := filepath.Rel(root, p); err == nil { + files = append(files, filepath.ToSlash(rel)) + } + if len(files) > 20000 { + return filepath.SkipAll + } + return nil + }) + return files +} + +// searchInWorkspace 在工作区里按行搜索,返回命中的行。 +func (a *App) searchInWorkspace(query string, limit int, o searchOpts) []paletteItem { + root := a.root + if root == "" || query == "" { + return nil + } + files := a.workspaceFiles() + + match, err := buildMatcher(query, o) + if err != nil { + return nil + } + var out []paletteItem + for _, rel := range files { + abs := filepath.Join(root, filepath.FromSlash(rel)) + info, err := os.Stat(abs) + if err != nil || info.Size() > 512*1024 { + continue + } + data, err := os.ReadFile(abs) + if err != nil || !utf8.Valid(data) { + continue + } + for i, line := range strings.Split(string(data), "\n") { + if !match(line) { + continue + } + trimmed := strings.TrimSpace(line) + if len(trimmed) > 160 { + trimmed = trimmed[:160] + "…" + } + out = append(out, paletteItem{ + Kind: itemLine, + Path: abs, + Line: i + 1, + Label: rel, + Hint: "", + Text: trimmed, + }) + if len(out) >= limit { + return out + } + } + } + return out +} + +// moveSel 上下移动选中项。 +func (a *App) moveSel(d int) { + if len(a.pal.items) == 0 { + return + } + a.pal.sel += d + if a.pal.sel < 0 { + a.pal.sel = len(a.pal.items) - 1 + } + if a.pal.sel >= len(a.pal.items) { + a.pal.sel = 0 + } + a.win.Update(func() {}) +} + +// activatePalette 打开当前选中的候选。 +func (a *App) activatePalette() { + if a.pal.sel < 0 || a.pal.sel >= len(a.pal.items) { + return + } + it := a.pal.items[a.pal.sel] + a.pal.open = false + a.focusEditorSoon() + if a.pal.action { + a.applyAction(it.Idx) + return + } + if a.pal.recent { + // 最近项目:换工作区。 + a.switchWorkspace(it.Path) + return + } + path, line := it.Path, it.Line + a.win.Update(func() {}) + go a.openAtLine(path, line) +} + +// openAt 打开文件并跳到指定行(line 为 1 起,0 表示只打开)。 +func (a *App) openAtLine(path string, line int) { + d, err := a.loadDoc(path) + if err != nil { + a.alert("打开失败", err.Error()) + return + } + if line <= 0 { + return + } + a.win.Update(func() { + if line-1 < d.buf.LineCount() { + d.st.GoTo(editor.Pos{Line: line - 1, Col: 0}) + d.st.ScrollTo(line - 1) + } + a.active = d.path + a.syncTitle() + }) +} + +// paletteView 画命令面板。挂在根级(Modal 是覆盖层)。 +func (a *App) paletteView(c *ui.Context) { + if !a.pal.open { + return + } + t := c.Theme() + + ui.Modal(c, &a.pal.open, func() { + ui.Column(c).Width(620).Gap(6).Children(func() { + // 回车与上下键挂在输入框自己身上:焦点就在它这里, + // 元素级 OnShortcut 会先于「可点元素吃回车」的逻辑拿到按键。 + // 回车用输入框自己的 Submitted:它在输入框内部就把 Enter 接住了, + // 外层的 Shortcut / OnShortcut 都收不到(Enter 会先变成输入框的一次点击)。 + inp := ui.TextInput(c, &a.pal.query).FillWidth().FontSize(14).AutoFocus() + // 搜索模式下才显示匹配选项:快速打开用不上正则。 + if a.pal.search { + ui.Row(c).FillWidth().Gap(6).Padding(0, 2).Children(func() { + a.searchToggle(c, "Aa", "区分大小写", &a.pal.matchCase) + a.searchToggle(c, ".*", "正则", &a.pal.useRegex) + a.searchToggle(c, "ab", "整词", &a.pal.wholeWord) + }) + } + // 替换入口也在搜索模式下;预览时整块内容换成确认视图。 + if a.pal.search && !a.pal.replacing { + a.replaceRow(c) + } + // 先把候选刷成当前查询的结果,再处理回车:否则这一帧回车会作用在 + // 上一帧的候选上(输入 greet 却打开了 go.mod)。 + if a.pal.query != a.pal.lastQ { + a.refreshPalette() + } + // 上下键用 Ctrl+N / Ctrl+P:方向键在输入框里是移动光标,抢不过来。 + // 先处理移动再处理回车:同一帧里两个键一起来时, + // 回车应该作用在移动之后的选中项上。 + if c.Shortcut(ui.Ctrl, ui.KeyN) { + a.moveSel(1) + } + if c.Shortcut(ui.Ctrl, ui.KeyP) { + a.moveSel(-1) + } + if inp.Submitted() { + a.activatePalette() + } + + if a.pal.replacing { + a.replacePreview(c) + } else if len(a.pal.items) == 0 { + msg := "输入关键字开始搜索" + if a.pal.symbol { + msg = "输入关键字搜索符号" + if a.pal.waiting { + msg = "搜索中…" + } + } + if a.pal.refs { + msg = "没有找到引用" + } + if a.pal.search { + if a.pal.waiting { + msg = "搜索中…" + } else if strings.TrimSpace(a.pal.query) != "" { + msg = "没有匹配" + } + } else if a.pal.query != "" { + msg = "没有匹配的文件" + } + ui.Text(c, msg).FontSize(12).TextColor(t.TextMuted).Padding(6, 2) + } else { + ui.Column(c).Gap(1).Children(func() { + for i, it := range a.pal.items { + a.paletteRow(c, i, it) + } + }) + } + + ui.Row(c).Gap(10).Padding(4, 2).Children(func() { + // 方向键在输入框里是移动光标,抢不过来,所以用 Ctrl+N / Ctrl+P。 + ui.Text(c, "Ctrl+N/P 选择").FontSize(10).TextColor(t.TextMuted) + ui.Text(c, "Enter 打开").FontSize(10).TextColor(t.TextMuted) + ui.Text(c, "Esc 关闭").FontSize(10).TextColor(t.TextMuted) + ui.Box(c).Grow(1) + if n := len(a.pal.items); n > 0 { + ui.Textf(c, "%d 项", n).FontSize(10).TextColor(t.TextMuted) + } + }) + }) + }) +} + +// replaceRow 是搜索面板里的「替换为 ___ [预览替换]」一行。 +func (a *App) replaceRow(c *ui.Context) { + t := c.Theme() + ui.Row(c).FillWidth().Gap(6).Padding(0, 2).AlignItems(ui.Center).Children(func() { + ui.Text(c, "替换为").FontSize(11).TextColor(t.TextMuted) + ui.TextInput(c, &a.pal.replaceTo).FillWidth().FontSize(12) + label := "预览替换" + if a.pal.planning { + label = "计算中…" + } + if ui.Button(c, label).Clicked() && !a.pal.planning { + a.startReplacePreview() + } + }) +} + +// searchOpts 收集面板当前的匹配选项。 +func (a *App) searchOpts() searchOpts { + return searchOpts{useRegex: a.pal.useRegex, matchCase: a.pal.matchCase, wholeWord: a.pal.wholeWord} +} + +// startReplacePreview 算替换预览:主线程收缓冲区快照 → 后台扫盘 → 回来切预览。 +func (a *App) startReplacePreview() { + if strings.TrimSpace(a.pal.query) == "" || a.pal.planning { + return + } + if _, err := buildReplaceRe(a.pal.query, a.searchOpts()); err != nil { + a.alert("替换", "匹配规则有误: "+err.Error()) + return + } + a.pal.planning = true + a.refresh() + // 打开文件的缓冲区文本只能在主线程读,先在这里收快照; + // 替换时以确认那一刻的缓冲区为准,这里只是预览。 + openTexts := map[string]string{} + for _, d := range a.docs { + openTexts[d.path] = d.buf.String() + } + query, to, opt := a.pal.query, a.pal.replaceTo, a.searchOpts() + go func() { + plan, err := a.buildReplacePlan(openTexts, query, to, opt) + a.win.Update(func() { + a.pal.planning = false + if err != nil { + a.alert("替换", "匹配规则有误: "+err.Error()) + return + } + if plan.Total == 0 { + a.alert("替换", "没有可替换的匹配") + return + } + a.pal.plan = plan + a.pal.replacing = true + }) + }() +} + +// replacePreview 画预览:文件清单 + 处数 + 确认/取消。 +func (a *App) replacePreview(c *ui.Context) { + t := c.Theme() + p := a.pal.plan + ui.Textf(c, "将替换 %d 处 / %d 个文件", p.Total, len(p.Files)). + FontSize(12).TextColor(t.Text) + ui.Text(c, "打开中的文件按缓冲区改(保持未保存),其余按原编码直接写盘。"). + FontSize(10).TextColor(t.TextMuted).SingleLine() + ui.Scroll(c).FillWidth().Height(240).Children(func() { + ui.Column(c).Gap(1).Children(func() { + for _, f := range p.Files { + ui.Textf(c, "%d 处 %s", f.Count, f.Rel). + FontSize(11).TextColor(t.Text).SingleLine().Padding(1, 6) + } + if p.Truncated { + ui.Textf(c, "…文件数超过 %d,未列出的也会一起替换", replacePlanCap). + FontSize(10).TextColor(t.Warning).Padding(1, 6) + } + }) + }) + ui.Row(c).Gap(8).Justify(ui.End).Padding(2, 0).Children(func() { + if ui.Button(c, "取消").Clicked() { + a.pal.replacing = false + a.pal.plan = replacePlan{} + a.refresh() + } + if ui.Button(c, "确认替换").Clicked() { + a.confirmReplace() + } + }) +} + +// confirmReplace 执行替换并汇报到输出面板。 +func (a *App) confirmReplace() { + if !a.pal.replacing || a.pal.plan.Total == 0 { + return + } + query, to, opt := a.pal.query, a.pal.replaceTo, a.searchOpts() + files := a.pal.plan.Files + a.pal.open = false + a.pal.replacing = false + a.pal.plan = replacePlan{} + a.focusEditorSoon() + + hits, nfiles, failed := a.applyReplacePlan(query, to, opt, files) + kind := OutSuccess + text := fmt.Sprintf("已替换 %d 处(%d 个文件):%s → %s", hits, nfiles, query, to) + if len(failed) > 0 { + kind = OutWarn + text += fmt.Sprintf(",%d 个文件失败", len(failed)) + } + a.out = append(a.out, OutLine{Text: text, Kind: kind}) + for _, f := range failed { + a.out = append(a.out, OutLine{Text: " " + f, Kind: OutError}) + } + a.panel = true + a.panelTab = 0 + a.refreshGit() + a.refresh() +} + +// paletteRow 画一行候选。 +func (a *App) paletteRow(c *ui.Context, i int, it paletteItem) { + t := c.Theme() + selected := i == a.pal.sel + + row := ui.ButtonBase(c).FillWidth().Padding(3, 6).Gap(8).Radius(3). + Justify(ui.Start).AlignItems(ui.Center).Cursor(ui.CursorPointer) + bg := ui.RGBA(0, 0, 0, 0) + switch { + case selected: + bg = t.Accent.Alpha(0.24) + case row.Hovered(): + bg = t.SurfaceHover + } + row = row.Background(bg) + + row.Children(func() { + if it.Kind == itemLine { + ui.Textf(c, "%d", it.Line).FontSize(11).TextColor(t.TextMuted).Width(38) + ui.Column(c).Grow(1).Gap(1).Children(func() { + ui.Text(c, it.Label).FontSize(11).TextColor(t.TextMuted).SingleLine() + ui.Text(c, it.Text).FontSize(12).TextColor(t.Text).SingleLine() + }) + } else { + ui.Column(c).Grow(1).Gap(1).Children(func() { + ui.Text(c, it.Label).FontSize(12).TextColor(t.Text).SingleLine() + if it.Hint != "" && it.Hint != "." { + ui.Text(c, it.Hint).FontSize(10).TextColor(t.TextMuted).SingleLine() + } + }) + } + }) + + if row.Clicked() { + a.pal.sel = i + a.activatePalette() + } +} + +// searchToggle 是搜索面板里的一个开关小标签。 +// +// 不用 Checkbox:面板里要的是紧凑的一行,勾选框太大。 +func (a *App) searchToggle(c *ui.Context, label, tip string, on *bool) { + t := c.Theme() + bg := ui.RGBA(0, 0, 0, 0) + fg := t.TextMuted + bd := t.Border + if *on { + bg = t.SurfaceHover + fg = t.Text + bd = t.Accent + } + b := ui.ButtonBase(c).Padding(1, 6).Radius(4).Background(bg). + BorderWidth(1, 1, 1, 1).BorderColor(bd).Cursor(ui.CursorPointer) + b.Children(func() { + ui.Text(c, label).FontSize(10).TextColor(fg) + }) + if b.Clicked() { + *on = !*on + // 选项变了要按新规则重搜一次。 + a.refreshPalette() + } + _ = tip +} + +// asciiWordEnds 判断首尾是否都是 ASCII 词字符(字母/数字/下划线)。 +func asciiWordEnds(s string) bool { + r := []rune(s) + if len(r) == 0 { + return false + } + isWord := func(c rune) bool { + return c < 128 && (c == '_' || + (c >= '0' && c <= '9') || + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z')) + } + return isWord(r[0]) && isWord(r[len(r)-1]) +} diff --git a/internal/app/palette_test.go b/internal/app/palette_test.go new file mode 100644 index 0000000..1f5601e --- /dev/null +++ b/internal/app/palette_test.go @@ -0,0 +1,102 @@ +package app + +import ( + "os" + "path/filepath" + "testing" +) + +func TestFuzzyScore(t *testing.T) { + cases := []struct { + path, query string + want bool + }{ + {"main.go", "main", true}, + {"main.go", "mg", true}, + {"internal/app/view.go", "view", true}, + {"internal/app/view.go", "iaview", true}, + {"main.go", "xyz", false}, + {"", "", true}, + } + for _, c := range cases { + if _, ok := fuzzyScore(c.path, c.query); ok != c.want { + t.Fatalf("fuzzyScore(%q,%q)=%v 期望 %v", c.path, c.query, ok, c.want) + } + } +} + +// TestFuzzyScorePrefersBasename 确认按文件名命中的排在目录命中的前面。 +func TestFuzzyScorePrefersBasename(t *testing.T) { + a, ok1 := fuzzyScore("internal/app/view.go", "view") + b, ok2 := fuzzyScore("view/internal/other.go", "view") + if !ok1 || !ok2 { + t.Fatal("两条都该命中") + } + if a <= b { + t.Fatalf("文件名命中应得分更高: %d vs %d", a, b) + } +} + +func TestQuickResultsRanking(t *testing.T) { + a := &App{root: t.TempDir()} + a.index.mu.Lock() + a.index.root = a.root + a.index.files = []string{"internal/app/view.go", "view/readme.md", "main.go"} + a.index.ready = true + a.index.mu.Unlock() + + got := a.quickResults("view", 10) + if len(got) != 2 { + t.Fatalf("应命中 2 个,实际 %d", len(got)) + } + if got[0].Label != "view.go" { + t.Fatalf("文件名命中应排第一,实际 %q", got[0].Label) + } +} + +func TestSearchInWorkspace(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "sub"), 0o755); err != nil { + t.Fatal(err) + } + files := map[string]string{ + "a.go": "package a\n\nfunc Needle() {}\n", + "sub/b.go": "package b\n// needle 在这里\n", + "c.txt": "nothing\n", + } + for name, body := range files { + if err := os.WriteFile(filepath.Join(root, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + + a := &App{root: root} + got := a.searchInWorkspace("needle", 10, searchOpts{}) + if len(got) != 2 { + t.Fatalf("应命中 2 行,实际 %d: %+v", len(got), got) + } + seen := map[string]int{} + for _, it := range got { + seen[it.Label] = it.Line + } + if seen["a.go"] != 3 { + t.Fatalf("a.go 命中行应为 3,实际 %d", seen["a.go"]) + } + if seen[filepath.ToSlash(filepath.Join("sub", "b.go"))] != 2 { + t.Fatalf("sub/b.go 命中行应为 2,实际 %v", seen) + } +} + +func TestSearchSkipsSkippedDirs(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "node_modules"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "node_modules", "x.js"), []byte("needle\n"), 0o644); err != nil { + t.Fatal(err) + } + a := &App{root: root} + if got := a.searchInWorkspace("needle", 10, searchOpts{}); len(got) != 0 { + t.Fatalf("应当跳过 node_modules,实际命中 %d", len(got)) + } +} diff --git a/internal/app/popmenu.go b/internal/app/popmenu.go new file mode 100644 index 0000000..c990a03 --- /dev/null +++ b/internal/app/popmenu.go @@ -0,0 +1,173 @@ +package app + +import ( + "github.com/egoist/mygo" + "github.com/egoist/mygo/ui" +) + +// menuEntry 是自绘菜单里的一项。 +// +// 为什么不用系统菜单:mygo 的 Menu/ContextMenu 在 Windows 上是**原生菜单**, +// 字号、行高、圆角全由系统画(150% 缩放下 9pt 显得又大又粗),应用改不了。 +// 想跟 IDE 其他部分(12px 文字、8px 圆角、深色卡片)协调,只能自绘。 +type menuEntry struct { + label string + shortcut string + disabled bool + divider bool + action func() +} + +// entriesFromMenu 把 mygo 的菜单项翻译成自绘项。子菜单只支持一层。 +func entriesFromMenu(items []*mygo.MenuItem) []menuEntry { + out := make([]menuEntry, 0, len(items)) + for _, it := range items { + if it == nil || it.Hidden { + continue + } + if it.Type == mygo.MenuItemSeparator { + out = append(out, menuEntry{divider: true}) + continue + } + e := menuEntry{ + label: it.Label, + shortcut: shortcutText(it.Accelerator), + disabled: it.Disabled, + } + if it.Click != nil { + item, click := it, it.Click + e.action = func() { click(item, nil) } + } + out = append(out, e) + } + return out +} + +// shortcutText 把 "CmdOrCtrl+Shift+M" 缩写成本平台的样子。 +func shortcutText(acc string) string { + if acc == "" { + return "" + } + repl := map[string]string{ + "CmdOrCtrl+": "Ctrl+", "CommandOrControl+": "Ctrl+", + "Cmd+": "Win+", "Command+": "Win+", + } + out := acc + for k, v := range repl { + if len(out) >= len(k) && out[:len(k)] == k { + out = v + out[len(k):] + break + } + } + return out +} + +// openPop 在 anchor 下沿弹出自绘面板。 +// +// 只记矩形、不记元素:ui.Element 只能在本帧使用(跨帧会 panic: +// "element from pass N used in pass N+1"),而面板是下一帧才画的。 +func (a *App) openPop(anchor ui.Element, entries []menuEntry) { + if len(entries) == 0 || a.win == nil { + return + } + a.popRect = anchor.Bounds() + a.popEntries = entries + a.popOpen = true + a.popJustOpened = true + a.win.Update(func() {}) +} + +// closePop 收起菜单。 +func (a *App) closePop() { + a.popOpen = false + a.popEntries = nil +} + +// popMenu 画当前打开的菜单。要挂在根级(Popover 是覆盖层)。 +func (a *App) popMenu(c *ui.Context) { + if !a.popOpen || len(a.popEntries) == 0 { + return + } + t := c.Theme() + + // 位置:优先贴锚点下沿;超出窗口就往回收,避免面板被裁掉。 + const panelW float32 = 190 + x, y := a.popRect.X, a.popRect.Y+a.popRect.H+2 + if w, h := c.Size(); w > 0 { + if x+panelW > w-6 { + x = w - panelW - 6 + } + if x < 6 { + x = 6 + } + // 高度按项数估:每项约 24,分隔线 11。 + est := float32(8) + for _, en := range a.popEntries { + if en.divider { + est += 11 + } else { + est += 24 + } + } + if y+est > h-6 { + y = a.popRect.Y - est - 2 + } + if y < 6 { + y = 6 + } + } + + ui.Overlay(c, func() { + // 遮罩:点它关闭。但打开的那一帧要跳过——判定会把这次点击当成 + // 「点了外面」,面板刚出来就被收回去(表现为「点了没反应」)。 + back := ui.Box(c).Absolute().Left(0).Top(0).Right(0).Bottom(0).Modal() + if a.popJustOpened { + a.popJustOpened = false + } else if back.Clicked() { + a.closePop() + a.win.Update(func() {}) + return + } + + ui.Column(c).Absolute().Left(x).Top(y).Width(panelW). + Padding(5).Gap(1).Radius(t.Radius). + Background(t.Surface).BorderWidth(1).BorderColor(t.Border). + Shadow(0, 8, 24, 0, ui.RGBA(0, 0, 0, 0.35)). + Children(func() { + for _, en := range a.popEntries { + en := en + if en.divider { + ui.Box(c).FillWidth().Height(1).Background(t.Border). + Margin(4, 0) + continue + } + fg := t.Text + if en.disabled { + fg = t.TextMuted + } + btn := ui.ButtonBase(c).FillWidth().Padding(4, 8).Radius(4). + Justify(ui.Start).Cursor(ui.CursorPointer) + btn.Children(func() { + ui.Row(c).FillWidth().Gap(14).AlignItems(ui.Center).Children(func() { + ui.Text(c, en.label).FontSize(12).TextColor(fg).SingleLine() + ui.Box(c).Grow(1) + if en.shortcut != "" { + ui.Text(c, en.shortcut).FontSize(10). + TextColor(t.TextMuted).SingleLine() + } + }) + }) + if en.disabled { + continue + } + if btn.Clicked() { + a.closePop() + if en.action != nil { + en.action() + } + a.win.Update(func() {}) + } + } + }) + }) +} diff --git a/internal/app/recent.go b/internal/app/recent.go new file mode 100644 index 0000000..19162c5 --- /dev/null +++ b/internal/app/recent.go @@ -0,0 +1,165 @@ +package app + +import ( + "encoding/json" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/egoist/mygo/ui" +) + +// recentItem 是最近打开过的一个工作区。 +type recentItem struct { + Path string `json:"path"` + At int64 `json:"at"` +} + +// recentLimit 是保留条数。 +const recentLimit = 10 + +// recentPath 返回最近项目文件的路径。 +func recentPath() string { + dir := sessionDir() + if dir == "" { + return "" + } + return filepath.Join(dir, "recent.json") +} + +// loadRecent 读最近项目,顺手滤掉已经不存在的目录。 +func loadRecent() []recentItem { + p := recentPath() + if p == "" { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return nil + } + var items []recentItem + if err := json.Unmarshal(b, &items); err != nil { + logf("读取最近项目失败: %v", err) + return nil + } + out := make([]recentItem, 0, len(items)) + for _, it := range items { + if it.Path == "" { + continue + } + if st, err := os.Stat(it.Path); err != nil || !st.IsDir() { + continue + } + out = append(out, it) + } + sort.Slice(out, func(i, j int) bool { return out[i].At > out[j].At }) + if len(out) > recentLimit { + out = out[:recentLimit] + } + return out +} + +// saveRecent 写最近项目。 +func saveRecent(items []recentItem) { + p := recentPath() + if p == "" { + return + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return + } + b, err := json.MarshalIndent(items, "", " ") + if err != nil { + return + } + if err := os.WriteFile(p, b, 0o644); err != nil { + logf("保存最近项目失败: %v", err) + } +} + +// addRecent 把一个工作区插到列表最前面(已有的去重)。 +func addRecent(path string) { + if path == "" { + return + } + clean := filepath.Clean(path) + items := loadRecent() + out := make([]recentItem, 0, len(items)+1) + // 用纳秒:同一秒内连开两个项目也要能排出先后。 + out = append(out, recentItem{Path: clean, At: time.Now().UnixNano()}) + for _, it := range items { + if sameDir(it.Path, clean) { + continue + } + out = append(out, it) + } + if len(out) > recentLimit { + out = out[:recentLimit] + } + saveRecent(out) +} + +// sameDir 比较两个路径是否同一目录(Windows 下忽略大小写)。 +func sameDir(a, b string) bool { + return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) +} + +// OpenRecent 打开「最近项目」列表。 +func (a *App) OpenRecent() { + items := loadRecent() + if len(items) == 0 { + a.alert("最近项目", "还没有打开过任何项目") + return + } + list := make([]paletteItem, 0, len(items)) + for i, it := range items { + list = append(list, paletteItem{ + Kind: itemFile, + Path: it.Path, + Label: filepath.Base(it.Path), + Hint: it.Path, + Idx: i, + }) + } + a.recent = items + a.pal = paletteState{open: true, recent: true, refsAll: list, items: list} + a.win.Update(func() {}) +} + +// recentView 在欢迎页列出最近打开的项目。 +func (a *App) recentView(c *ui.Context) { + t := c.Theme() + items := loadRecent() + if len(items) == 0 { + return + } + ui.Box(c).Height(10) + ui.Text(c, "最近打开").FontSize(11).TextColor(t.TextMuted) + ui.Column(c).Gap(2).Width(360).Children(func() { + for _, it := range items { + item := it + row := ui.ButtonBase(c).FillWidth().Padding(4, 8).Gap(8).Radius(4). + Justify(ui.Start).AlignItems(ui.Center).Cursor(ui.CursorPointer) + if row.Hovered() { + row = row.Background(t.SurfaceHover) + } + row.Children(func() { + ui.Text(c, filepath.Base(item.Path)).FontSize(12).TextColor(t.Text).SingleLine() + ui.Text(c, item.Path).FontSize(10).TextColor(t.TextMuted).SingleLine().Grow(1) + }) + if row.Clicked() { + go a.switchWorkspace(item.Path) + } + } + }) +} + +// switchWorkspace 切到指定工作区(用 goroutine 打开对话框外的场景)。 +func (a *App) switchWorkspace(dir string) { + a.setRoot(dir) + if a.win != nil { + a.win.Update(func() {}) + } +} diff --git a/internal/app/recent_test.go b/internal/app/recent_test.go new file mode 100644 index 0000000..50f18cc --- /dev/null +++ b/internal/app/recent_test.go @@ -0,0 +1,61 @@ +package app + +import ( + "os" + "path/filepath" + "testing" +) + +func TestRecentAddAndOrder(t *testing.T) { + isolateConfig(t) + d1, d2 := t.TempDir(), t.TempDir() + + addRecent(d1) + addRecent(d2) + items := loadRecent() + if len(items) != 2 { + t.Fatalf("应有 2 条,实际 %d", len(items)) + } + if items[0].Path != filepath.Clean(d2) { + t.Fatalf("最近打开的应该在最前面,实际 %q", items[0].Path) + } + + // 再打开一次旧的:不新增条目,但要移到最前。 + addRecent(d1) + items = loadRecent() + if len(items) != 2 { + t.Fatalf("重复打开不该增加条目,实际 %d", len(items)) + } + if items[0].Path != filepath.Clean(d1) { + t.Fatalf("重新打开的项目应排最前,实际 %q", items[0].Path) + } +} + +func TestRecentDropsMissing(t *testing.T) { + isolateConfig(t) + d := t.TempDir() + addRecent(d) + if err := os.RemoveAll(d); err != nil { + t.Fatal(err) + } + if items := loadRecent(); len(items) != 0 { + t.Fatalf("目录已删除,不该再列出: %+v", items) + } +} + +func TestRecentLimit(t *testing.T) { + isolateConfig(t) + for i := 0; i < recentLimit+5; i++ { + addRecent(t.TempDir()) + } + if n := len(loadRecent()); n != recentLimit { + t.Fatalf("最多保留 %d 条,实际 %d", recentLimit, n) + } +} + +func TestRecentEmptyFile(t *testing.T) { + isolateConfig(t) + if items := loadRecent(); len(items) != 0 { + t.Fatalf("没有记录时应为空: %+v", items) + } +} diff --git a/internal/app/rename.go b/internal/app/rename.go new file mode 100644 index 0000000..5e00c82 --- /dev/null +++ b/internal/app/rename.go @@ -0,0 +1,207 @@ +package app + +import ( + "context" + "os" + "path/filepath" + "strings" + + "github.com/egoist/mygo/ui" + + "mygoland/internal/lsp" +) + +// renameState 是重命名弹窗的状态。 +type renameState struct { + open bool + openDlg bool + from string // 原名,用于提示 + to string // 输入框里的新名 + uri string + pos lsp.Position + path string +} + +// FindReferences 把光标处符号的所有引用列进命令面板。 +func (a *App) FindReferences() { + d := a.doc() + c := a.lsp + if d == nil || c == nil || !lsp.IsGoFile(d.path) { + a.alert("查找引用", "先把光标放到 Go 文件的符号上") + return + } + pos := positionAt(d, d.st.Cursor()) + uri := d.uri + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + locs, err := c.References(ctx, uri, pos, true) + if err != nil { + a.win.Update(func() { a.alert("查找引用失败", err.Error()) }) + return + } + items := make([]paletteItem, 0, len(locs)) + for _, loc := range locs { + p := lsp.URIToPath(loc.URI) + if p == "" { + continue + } + line := loc.Range.Start.Line + 1 + label := p + if a.root != "" { + if rel, err := filepath.Rel(a.root, p); err == nil { + label = filepath.ToSlash(rel) + } + } + items = append(items, paletteItem{ + Kind: itemLine, + Path: p, + Line: line, + Label: label, + Text: linePreview(p, line), + }) + } + a.win.Update(func() { + a.pal = paletteState{open: true, refs: true, refsAll: items, items: items} + if len(items) == 0 { + a.pal.items = nil + } + a.win.Update(func() {}) + }) + }() +} + +// linePreview 取文件某一行的内容用做列表预览。 +func linePreview(path string, line int) string { + data, err := os.ReadFile(path) + if err != nil { + return "" + } + lines := strings.Split(string(data), "\n") + if line < 1 || line > len(lines) { + return "" + } + s := strings.TrimSpace(lines[line-1]) + if len(s) > 140 { + s = s[:140] + "…" + } + return s +} + +// RenameSymbol 打开重命名弹窗,光标处的词作为默认值。 +func (a *App) RenameSymbol() { + d := a.doc() + c := a.lsp + if d == nil || c == nil || !lsp.IsGoFile(d.path) { + a.alert("重命名", "先把光标放到 Go 文件的符号上") + return + } + off := d.st.Cursor() + start, end := wordBounds(d, off) + word := "" + if end > start { + word = d.buf.String()[start:end] + } + if word == "" { + a.alert("重命名", "光标处没有可重命名的符号") + return + } + a.ren = renameState{ + open: true, + from: word, + to: word, + uri: d.uri, + pos: positionAt(d, off), + path: d.path, + } + a.win.Update(func() {}) +} + +// renameDialog 画重命名弹窗。 +func (a *App) renameDialog(c *ui.Context) { + if !a.ren.open { + return + } + t := c.Theme() + + ui.Modal(c, &a.ren.open, func() { + ui.Column(c).Width(420).Gap(10).Children(func() { + ui.Text(c, "重命名符号").FontSize(13).Bold().TextColor(t.Text) + ui.Text(c, "当前:"+a.ren.from).FontSize(10).TextColor(t.TextMuted).SingleLine() + + inp := ui.TextInput(c, &a.ren.to).FillWidth().FontSize(13).AutoFocus() + if inp.Submitted() { + a.confirmRename() + } + + ui.Row(c).Gap(8).Justify(ui.End).Children(func() { + if ui.Button(c, "取消").Clicked() { + a.ren.open = false + } + if ui.Button(c, "确定").Clicked() { + a.confirmRename() + } + }) + }) + }) + + if !a.ren.open && a.ren.openDlg { + // 弹窗关掉后把焦点还给编辑器。 + a.ren.openDlg = false + a.focusEditorSoon() + } + if !a.ren.openDlg && a.ren.open { + a.ren.openDlg = true + a.win.Update(func() {}) + } +} + +// confirmRename 发请求并把结果应用到各个文件。 +func (a *App) confirmRename() { + name := strings.TrimSpace(a.ren.to) + if name == "" || name == a.ren.from { + a.ren.open = false + return + } + c := a.lsp + uri, pos := a.ren.uri, a.ren.pos + a.ren.open = false + a.win.Update(func() {}) + if c == nil { + return + } + go func() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + we, err := c.Rename(ctx, uri, pos, name) + if err != nil { + a.win.Update(func() { a.alert("重命名失败", err.Error()) }) + return + } + changes := we.ByFile() + a.win.Update(func() { a.applyWorkspaceEdits(changes) }) + }() +} + +// applyWorkspaceEdits 把跨文件修改落到各个缓冲区上(不自动保存,留给用户检查)。 +func (a *App) applyWorkspaceEdits(changes map[string][]lsp.TextEdit) { + n := 0 + for uri, edits := range changes { + if len(edits) == 0 { + continue + } + path := lsp.URIToPath(uri) + if path == "" { + continue + } + d, err := a.loadDoc(path) + if err != nil { + continue + } + a.applyEdits(d, edits) + n++ + } + a.syncTitle() + a.saveSession() + logf("rename: %d 个文件已更新", n) +} diff --git a/internal/app/renameentry.go b/internal/app/renameentry.go new file mode 100644 index 0000000..b9ca384 --- /dev/null +++ b/internal/app/renameentry.go @@ -0,0 +1,190 @@ +package app + +import ( + "os" + "path/filepath" + "strings" + + "github.com/egoist/mygo/ui" + + "mygoland/internal/lsp" +) + +// renameEntryState 是「重命名」弹窗的状态。 +type renameEntryState struct { + open bool + dlg bool + path string + isDir bool + name string +} + +// BeginRename 打开重命名弹窗,输入框预填当前名字。 +// +// 输入里可以带目录(如 sub/util.go),这样顺带能搬文件—— +// 不单独做「移动」,一个输入框覆盖两种操作。 +func (a *App) BeginRename(path string, isDir bool) { + if path == "" { + return + } + a.renEntry = renameEntryState{ + open: true, + dlg: true, + path: path, + isDir: isDir, + name: filepath.Base(path), + } + a.win.Update(func() {}) +} + +// renameEntryDialog 画重命名弹窗。 +func (a *App) renameEntryDialog(c *ui.Context) { + if !a.renEntry.open { + return + } + t := c.Theme() + + ui.Modal(c, &a.renEntry.dlg, func() { + ui.Column(c).Width(440).Gap(10).Children(func() { + title := "重命名文件" + if a.renEntry.isDir { + title = "重命名文件夹" + } + ui.Text(c, title).FontSize(13).Bold().TextColor(t.Text) + ui.Text(c, filepath.Dir(a.renEntry.path)).FontSize(10).TextColor(t.TextMuted).SingleLine() + + inp := ui.TextInput(c, &a.renEntry.name).FillWidth().FontSize(13).AutoFocus() + if inp.Submitted() { + a.confirmRenameEntry() + } + ui.Text(c, "可以带目录,如 sub/name.go,等于同时移动").FontSize(10).TextColor(t.TextMuted).SingleLine() + + ui.Row(c).Gap(8).Justify(ui.End).Children(func() { + if ui.Button(c, "取消").Clicked() { + a.renEntry.open = false + } + if ui.Button(c, "确定").Clicked() { + a.confirmRenameEntry() + } + }) + }) + }) + + // 遮罩/ Esc 只改副本,弹窗照常重建;只有按钮能真正关掉。 + if !a.renEntry.dlg && a.renEntry.open { + a.renEntry.dlg = true + a.win.Update(func() {}) + } + if !a.renEntry.open && a.renEntry.dlg { + a.renEntry.dlg = false + a.focusEditorSoon() + } +} + +// confirmRenameEntry 落盘改名,并同步已打开的文件。 +func (a *App) confirmRenameEntry() { + old := a.renEntry.path + name := strings.TrimSpace(a.renEntry.name) + if name == "" { + a.renEntry.open = false + return + } + target := filepath.FromSlash(name) + if !filepath.IsAbs(target) { + target = filepath.Join(filepath.Dir(old), target) + } + target = filepath.Clean(target) + + // 关掉弹窗再干活,避免错误提示被弹窗盖住。 + a.renEntry.open = false + if target == old { + a.win.Update(func() {}) + return + } + if strings.EqualFold(target, old) { + // 只改大小写:Windows 上需要先改名到临时名字再改回来。 + tmp := old + ".renaming" + if err := os.Rename(old, tmp); err == nil { + _ = os.Rename(tmp, target) + } + } else { + if _, err := os.Stat(target); err == nil { + a.alert("重命名失败", "目标已存在:"+filepath.Base(target)) + return + } + if err := os.Rename(old, target); err != nil { + a.alert("重命名失败", err.Error()) + return + } + } + + a.afterRename(old, target) + a.win.Update(func() {}) +} + +// afterRename 把内存里跟旧路径有关的东西都搬到新路径。 +func (a *App) afterRename(old, target string) { + remap := func(p string) (string, bool) { return remapPath(p, old, target) } + + for _, d := range a.docs { + np, ok := remap(d.path) + if !ok { + continue + } + // 先和语言服务器断开旧 URI,再按新路径挂回去。 + d.stopWatch() + if a.lsp != nil && d.opened { + _ = a.lsp.DidClose(d.uri) + d.opened = false + } + d.path = np + d.uri = lsp.PathToURI(np) + a.lspOpen(d) + a.startWatch(d) + if a.active == old || strings.HasPrefix(a.active, old+string(filepath.Separator)) { + a.active = np + } + } + + // 展开状态与目录缓存都按路径存的,改名后这些键就失效了。 + next := map[string]*bool{} + for k, v := range a.open { + if nk, ok := remap(k); ok { + next[nk] = v + } else { + next[k] = v + } + } + a.open = next + a.dirs = map[string][]os.DirEntry{} + if a.sel != nil { + sel := map[string]bool{} + for k := range a.sel { + nk, _ := remap(k) + sel[nk] = true + } + a.sel = sel + } + + a.syncTitle() + a.saveSession() + a.refreshGit() +} + +// remapPath 把落在 old 里的路径换到 target 下。 +// +// 只按「目录分隔符」判断前缀:a.go.bak 不属于 a.go, +// 只看字符串前缀会把这类同名前缀的邻居误伤。 +func remapPath(p, old, target string) (string, bool) { + if p == "" || old == "" { + return p, false + } + if p == old { + return target, true + } + prefix := old + string(filepath.Separator) + if strings.HasPrefix(p, prefix) { + return filepath.Join(target, strings.TrimPrefix(p, prefix)), true + } + return p, false +} diff --git a/internal/app/renameentry_test.go b/internal/app/renameentry_test.go new file mode 100644 index 0000000..ce04f43 --- /dev/null +++ b/internal/app/renameentry_test.go @@ -0,0 +1,44 @@ +package app + +import ( + "path/filepath" + "testing" +) + +func TestRemapPath(t *testing.T) { + old := filepath.Join("C:", "work", "a.go") + target := filepath.Join("C:", "work", "b.go") + + cases := []struct { + in string + want string + ok bool + }{ + {old, target, true}, + {old + ".bak", old + ".bak", false}, // 同名前缀的邻居不能动 + {filepath.Join("C:", "work", "other.go"), filepath.Join("C:", "work", "other.go"), false}, + } + for _, c := range cases { + got, ok := remapPath(c.in, old, target) + if got != c.want || ok != c.ok { + t.Fatalf("remapPath(%q)=(%q,%v),期望 (%q,%v)", c.in, got, ok, c.want, c.ok) + } + } +} + +func TestRemapPathDir(t *testing.T) { + old := filepath.Join("C:", "work", "pkg") + target := filepath.Join("C:", "work", "lib") + + inside := filepath.Join(old, "sub", "x.go") + got, ok := remapPath(inside, old, target) + if !ok || got != filepath.Join(target, "sub", "x.go") { + t.Fatalf("目录内文件应跟着搬: (%q,%v)", got, ok) + } + + sibling := filepath.Join("C:", "work", "pkg2", "y.go") + got, ok = remapPath(sibling, old, target) + if ok || got != sibling { + t.Fatalf("同前缀的兄弟目录不能动: (%q,%v)", got, ok) + } +} diff --git a/internal/app/replace.go b/internal/app/replace.go new file mode 100644 index 0000000..e7d6bb4 --- /dev/null +++ b/internal/app/replace.go @@ -0,0 +1,200 @@ +package app + +// 全局搜索替换:预览 + 确认两步走。 +// +// 文本来源分两类,规则不同: +// - 打开中的文件:以**缓冲区**为准(未保存的改动也算),替换落在缓冲区上, +// 保持未保存状态走一步撤销——绝不绕过缓冲区直接写盘,否则一保存就把 +// 替换结果盖掉了; +// - 没打开的文件:读盘 → 按原编码解码 → 替换 → 按原编码写回(GBK 配置 +// 改完还是 GBK)。 +// +// 匹配规则与全局搜索共用 buildReplaceRe(正则/大小写/整词同一套开关)。 + +import ( + "os" + "path/filepath" + "regexp" + "sort" + "strings" + + "github.com/egoist/mygo/ui/editor" +) + +// buildReplaceRe 与搜索的 buildMatcher 同一套装配规则,但返回正则本体—— +// 替换要用 FindAllStringIndex 和 ExpandString,一个布尔函数不够。 +func buildReplaceRe(query string, o searchOpts) (*regexp.Regexp, error) { + pat := query + if !o.useRegex { + pat = regexp.QuoteMeta(pat) + } + // 整词边界只加在 ASCII 词首尾上,理由见 buildMatcher。 + if o.wholeWord && asciiWordEnds(query) { + pat = `\b(?:` + pat + `)\b` + } + if !o.matchCase { + pat = "(?i)" + pat + } + return regexp.Compile(pat) +} + +// replaceInText 按行应用替换,返回新文本与替换次数。 +// +// 逐行走是因为搜索的语义就是按行(^ $ 锚在行上),替换必须同语义, +// 不然「搜得到换不掉」比搜不到更气人。行结构原样保留,CRLF 不受影响。 +// replacement 在正则模式下支持 $1 这类分组引用——所以必须用 +// SubmatchIndex 拿到分组位置,FindAllStringIndex 只有整匹配, +// ExpandString 会把 $1 展开成空串。 +func replaceInText(text string, re *regexp.Regexp, replacement string) (string, int) { + lines := strings.Split(text, "\n") + total := 0 + for i, line := range lines { + ms := re.FindAllStringSubmatchIndex(line, -1) + if len(ms) == 0 { + continue + } + total += len(ms) + var b strings.Builder + last := 0 + for _, m := range ms { + b.WriteString(line[last:m[0]]) + b.Write(re.ExpandString(nil, replacement, line, m)) + last = m[1] + } + b.WriteString(line[last:]) + lines[i] = b.String() + } + return strings.Join(lines, "\n"), total +} + +// fileReplace 是计划里的一个文件。 +type fileReplace struct { + Abs string + Rel string // 仓库相对路径,正斜杠,给人看 + // Count 是预览时算出的替换处数;确认时以实际执行为准 + //(预览和确认之间缓冲区可能又变了)。 + Count int +} + +// replacePlan 是一次替换的预览结果。 +type replacePlan struct { + Files []fileReplace + Total int + Truncated bool // 超出文件数上限,只列了一部分 +} + +// replacePlanCap 是预览最多列出的文件数,防止失控的工作区把面板撑爆。 +const replacePlanCap = 400 + +// buildReplacePlan 算一遍替换计划(只读,不写任何东西)。 +// openTexts 是打开文件「绝对路径 → 缓冲区文本」的快照,由调用方在主线程收好; +// 其余文件在这里读盘。编码不是 UTF-8 的文件也参与:decodeFile 能解 GBK/UTF-16。 +func (a *App) buildReplacePlan(openTexts map[string]string, query, replacement string, o searchOpts) (replacePlan, error) { + re, err := buildReplaceRe(query, o) + if err != nil { + return replacePlan{}, err + } + var plan replacePlan + seen := map[string]bool{} + for path, text := range openTexts { + if n := countReplace(re, text, replacement); n > 0 { + plan.Files = append(plan.Files, fileReplace{Abs: path, Rel: a.relOf(path), Count: n}) + plan.Total += n + } + seen[path] = true + } + for _, rel := range a.workspaceFiles() { + if len(plan.Files) >= replacePlanCap { + plan.Truncated = true + break + } + abs := filepath.Join(a.root, filepath.FromSlash(rel)) + if seen[abs] { + continue + } + info, err := os.Stat(abs) + if err != nil || info.Size() > 512*1024 { + continue + } + data, err := os.ReadFile(abs) + if err != nil { + continue + } + text, _, ok := decodeFile(data) + if !ok { + continue // 不是文本,不碰 + } + if n := countReplace(re, text, replacement); n > 0 { + plan.Files = append(plan.Files, fileReplace{Abs: abs, Rel: rel, Count: n}) + plan.Total += n + } + } + sort.Slice(plan.Files, func(i, j int) bool { return plan.Files[i].Rel < plan.Files[j].Rel }) + return plan, nil +} + +// countReplace 算替换处数。 +func countReplace(re *regexp.Regexp, text, replacement string) int { + _, n := replaceInText(text, re, replacement) + return n +} + +// relOf 把绝对路径转成给人看的相对显示(越出根就原样给)。 +func (a *App) relOf(abs string) string { + if rel, err := filepath.Rel(a.root, abs); err == nil { + return filepath.ToSlash(rel) + } + return filepath.ToSlash(abs) +} + +// applyReplacePlan 执行计划:打开的改缓冲区(一步撤销 + 同步 LSP), +// 其余按原编码写盘。必须在主线程调用(缓冲区编辑与 lspSync 的要求)。 +// 返回替换处数与失败清单。 +func (a *App) applyReplacePlan(query, replacement string, o searchOpts, files []fileReplace) (int, int, []string) { + re, err := buildReplaceRe(query, o) + if err != nil { + return 0, 0, []string{"匹配规则有误: " + err.Error()} + } + hits, nfiles := 0, 0 + var failed []string + for _, f := range files { + if d := a.find(f.Abs); d != nil { + newText, n := replaceInText(d.buf.String(), re, replacement) + if n == 0 { + continue // 预览之后缓冲区又变了,这次没有可替换的 + } + d.buf.Transact(func() { + d.buf.Edit(editor.Edit{Start: 0, End: d.buf.Len(), Text: newText}) + }) + a.lspSync(d) + hits += n + nfiles++ + continue + } + data, err := os.ReadFile(f.Abs) + if err != nil { + failed = append(failed, f.Rel+": "+err.Error()) + continue + } + text, enc, ok := decodeFile(data) + if !ok { + failed = append(failed, f.Rel+": 不是文本文件,已跳过") + continue + } + newText, n := replaceInText(text, re, replacement) + if n == 0 { + continue // 磁盘内容变了,没有可替换的 + } + out, err := encodeFile(newText, enc) + if err == nil { + err = os.WriteFile(f.Abs, out, 0o644) + } + if err != nil { + failed = append(failed, f.Rel+": "+err.Error()) + continue + } + hits += n + nfiles++ + } + return hits, nfiles, failed +} diff --git a/internal/app/replace_test.go b/internal/app/replace_test.go new file mode 100644 index 0000000..9e046b6 --- /dev/null +++ b/internal/app/replace_test.go @@ -0,0 +1,202 @@ +package app + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/egoist/mygo/ui/editor" +) + +func TestReplaceInTextLiteral(t *testing.T) { + re, err := buildReplaceRe("过磅", searchOpts{}) + if err != nil { + t.Fatal(err) + } + text := "过磅记录\n原料过磅\n过磅过磅\n" + got, n := replaceInText(text, re, "称重") + if n != 4 { + t.Fatalf("应替换 4 处,实际 %d", n) + } + if want := "称重记录\n原料称重\n称重称重\n"; got != want { + t.Fatalf("结果不对: %q", got) + } +} + +func TestReplaceInTextCaseInsensitive(t *testing.T) { + re, err := buildReplaceRe("Foo", searchOpts{}) + if err != nil { + t.Fatal(err) + } + got, n := replaceInText("foo FOO Foo", re, "Bar") + if n != 3 { + t.Fatalf("默认忽略大小写,应替换 3 处,实际 %d", n) + } + if got != "Bar Bar Bar" { + t.Fatalf("结果不对: %q", got) + } +} + +func TestReplaceInTextCaseSensitive(t *testing.T) { + re, err := buildReplaceRe("Foo", searchOpts{matchCase: true}) + if err != nil { + t.Fatal(err) + } + _, n := replaceInText("foo FOO Foo", re, "Bar") + if n != 1 { + t.Fatalf("区分大小写应只替换 1 处,实际 %d", n) + } +} + +func TestReplaceInTextRegexGroups(t *testing.T) { + re, err := buildReplaceRe(`(\w+)@example\.com`, searchOpts{useRegex: true}) + if err != nil { + t.Fatal(err) + } + got, n := replaceInText("cgh@example.com; x@example.com", re, "$1@x.org") + if n != 2 { + t.Fatalf("应替换 2 处,实际 %d", n) + } + if want := "cgh@x.org; x@x.org"; got != want { + t.Fatalf("分组引用不对: %q", got) + } +} + +func TestReplaceInTextWholeWord(t *testing.T) { + re, err := buildReplaceRe("id", searchOpts{wholeWord: true}) + if err != nil { + t.Fatal(err) + } + got, n := replaceInText("id idx identify id", re, "ID") + if n != 2 { + t.Fatalf("整词应只替换 2 处,实际 %d", n) + } + if got != "ID idx identify ID" { + t.Fatalf("结果不对: %q", got) + } +} + +func TestReplaceInTextEmptyReplacement(t *testing.T) { + re, err := buildReplaceRe("debug_", searchOpts{}) + if err != nil { + t.Fatal(err) + } + got, n := replaceInText("a debug_x debug_y", re, "") + if n != 2 || got != "a x y" { + t.Fatalf("空替换即删除: n=%d got=%q", n, got) + } +} + +func TestReplaceInTextCRLFPreserved(t *testing.T) { + re, err := buildReplaceRe("old", searchOpts{}) + if err != nil { + t.Fatal(err) + } + got, n := replaceInText("a old\r\nold\r\n", re, "new") + if n != 2 { + t.Fatalf("应替换 2 处,实际 %d", n) + } + if got != "a new\r\nnew\r\n" { + t.Fatalf("CRLF 应原样保留: %q", got) + } +} + +func TestReplaceInTextNoMatch(t *testing.T) { + re, err := buildReplaceRe("不存在", searchOpts{}) + if err != nil { + t.Fatal(err) + } + text := "原文不动\n" + got, n := replaceInText(text, re, "x") + if n != 0 || got != text { + t.Fatalf("无匹配应原样返回: n=%d got=%q", n, got) + } +} + +func TestBuildReplaceReInvalid(t *testing.T) { + if _, err := buildReplaceRe("a(", searchOpts{useRegex: true}); err == nil { + t.Fatal("非法正则应报错") + } +} + +func TestReplaceInTextMultipleLines(t *testing.T) { + re, err := buildReplaceRe("v1", searchOpts{}) + if err != nil { + t.Fatal(err) + } + text := strings.Repeat("x := v1\n", 3) + got, n := replaceInText(text, re, "v2") + if n != 3 || got != strings.Repeat("x := v2\n", 3) { + t.Fatalf("跨行累计不对: n=%d got=%q", n, got) + } +} + +// TestApplyReplacePlan 执行层三条规则:磁盘 UTF-8 直接写回、GBK 按原编码写回、 +// 打开中的文件只改缓冲区(变脏)且不动盘。 +func TestApplyReplacePlan(t *testing.T) { + root := t.TempDir() + write := func(name string, data []byte) string { + t.Helper() + p := filepath.Join(root, name) + if err := os.WriteFile(p, data, 0o644); err != nil { + t.Fatal(err) + } + return p + } + + // 1) 磁盘 UTF-8 文件。 + u := write("utf8.txt", []byte("host = old\nport = 1\n")) + + // 2) GBK 文件(「过磅」的 GBK 编码)。 + gbk, err := encodeFile("过磅 = old\n", encGBK) + if err != nil { + t.Fatal(err) + } + g := write("gbk.cfg", gbk) + + // 3) 打开中的文件:缓冲区有未保存内容,磁盘上没有匹配。 + bufPath := write("open.txt", []byte("nothing here\n")) + d := &Doc{path: bufPath, buf: editor.NewBuffer("open old line\n")} + a := &App{root: root, docs: []*Doc{d}} + + plan, err := a.buildReplacePlan(map[string]string{bufPath: d.buf.String()}, "old", "new", searchOpts{}) + if err != nil { + t.Fatal(err) + } + if plan.Total != 3 || len(plan.Files) != 3 { + t.Fatalf("预览应为 3 处 / 3 个文件,实际 %d 处 / %d 个: %+v", plan.Total, len(plan.Files), plan.Files) + } + + hits, nfiles, failed := a.applyReplacePlan("old", "new", searchOpts{}, plan.Files) + if len(failed) > 0 { + t.Fatalf("不应有失败: %v", failed) + } + if hits != 3 || nfiles != 3 { + t.Fatalf("应替换 3 处 / 3 个文件,实际 %d / %d", hits, nfiles) + } + + // UTF-8 文件已写盘。 + if b, err := os.ReadFile(u); err != nil || string(b) != "host = new\nport = 1\n" { + t.Fatalf("UTF-8 文件没写对: %q %v", b, err) + } + // GBK 文件写回后仍是 GBK,且内容正确。 + b, err := os.ReadFile(g) + if err != nil { + t.Fatal(err) + } + text, enc, ok := decodeFile(b) + if !ok || enc != encGBK || text != "过磅 = new\n" { + t.Fatalf("GBK 文件应保持 GBK 且内容正确: enc=%v ok=%v text=%q", enc, ok, text) + } + // 打开中的文件:缓冲区已替换并变脏,磁盘未动。 + if got := d.buf.String(); got != "open new line\n" { + t.Fatalf("缓冲区应已替换: %q", got) + } + if !d.buf.Modified() { + t.Fatal("缓冲区应保持未保存(脏)状态") + } + if disk, _ := os.ReadFile(bufPath); string(disk) != "nothing here\n" { + t.Fatalf("打开中的文件不应直接写盘: %q", disk) + } +} diff --git a/internal/app/runconfig.go b/internal/app/runconfig.go new file mode 100644 index 0000000..5eb1c00 --- /dev/null +++ b/internal/app/runconfig.go @@ -0,0 +1,249 @@ +package app + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + + "github.com/egoist/mygo/ui" +) + +// runConfig 是一条运行/调试配置。 +type runConfig struct { + Name string `json:"name"` + Program string `json:"program"` + Args string `json:"args"` + StopOnEntry bool `json:"stopOnEntry"` +} + +// configsFile 是一个工作区里的全部运行配置。 +type configsFile struct { + Configs []runConfig `json:"configs"` + Active int `json:"active"` +} + +// defaultConfig 是没有配置时的默认值。 +func defaultConfig() runConfig { + return runConfig{Name: "默认", Program: "."} +} + +// activeCfg 返回当前选中的配置(越界时兜底到默认)。 +func (a *App) activeCfg() runConfig { + if len(a.cfgs.Configs) == 0 { + return defaultConfig() + } + i := a.cfgs.Active + if i < 0 || i >= len(a.cfgs.Configs) { + i = 0 + } + return a.cfgs.Configs[i] +} + +// setActiveCfg 把改动写回当前配置。 +func (a *App) setActiveCfg(cfg runConfig) { + if len(a.cfgs.Configs) == 0 { + a.cfgs.Configs = []runConfig{cfg} + a.cfgs.Active = 0 + return + } + i := a.cfgs.Active + if i < 0 || i >= len(a.cfgs.Configs) { + i = 0 + } + a.cfgs.Configs[i] = cfg +} + +// cfgNames 返回所有配置名,供下拉框使用。 +func (a *App) cfgNames() []string { + out := make([]string, 0, len(a.cfgs.Configs)) + for _, c := range a.cfgs.Configs { + out = append(out, c.Name) + } + return out +} + +// loadConfig 读取工作区的运行配置;老格式(单个对象)自动迁移成一条。 +func (a *App) loadConfig() { + a.cfgs = configsFile{Configs: []runConfig{defaultConfig()}} + p := a.configPath() + if p == "" { + return + } + data, err := os.ReadFile(p) + if err != nil { + return + } + // 新格式 + var f configsFile + if err := json.Unmarshal(data, &f); err == nil && len(f.Configs) > 0 { + a.cfgs = f + if a.cfgs.Active < 0 || a.cfgs.Active >= len(a.cfgs.Configs) { + a.cfgs.Active = 0 + } + return + } + // 老格式:直接存了一个 runConfig + var one runConfig + if err := json.Unmarshal(data, &one); err == nil && (one.Program != "" || one.Args != "") { + if one.Name == "" { + one.Name = "默认" + } + a.cfgs = configsFile{Configs: []runConfig{one}, Active: 0} + } +} + +// saveConfig 写回运行配置。 +func (a *App) saveConfig() { + p := a.configPath() + if p == "" { + return + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return + } + data, err := json.MarshalIndent(a.cfgs, "", " ") + if err != nil { + return + } + _ = os.WriteFile(p, data, 0o644) +} + +// runConfigDialogState 是「运行配置」弹窗的状态。 +type runConfigDialogState struct { + open bool + dlg bool + // draft 是正在编辑的那条配置。 + draft runConfig +} + +// OpenRunConfigs 打开运行配置弹窗。 +func (a *App) OpenRunConfigs() { + a.cfgDlg = runConfigDialogState{open: true, dlg: true, draft: a.activeCfg()} + a.win.Update(func() {}) +} + +// runConfigDialog 画运行配置弹窗。 +func (a *App) runConfigDialog(c *ui.Context) { + if !a.cfgDlg.open { + return + } + t := c.Theme() + + ui.Modal(c, &a.cfgDlg.dlg, func() { + ui.Column(c).Width(520).Gap(10).Children(func() { + ui.Text(c, "运行配置").FontSize(14).Bold().TextColor(t.Text) + + // 配置列表:点一下切换成正在编辑的那条。 + ui.Row(c).Gap(4).Wrap().Children(func() { + for i, cfg := range a.cfgs.Configs { + idx := i + label := cfg.Name + if label == "" { + label = "(未命名)" + } + sel := idx == a.cfgs.Active + if ui.Button(c, label).Selected(sel).Clicked() { + a.cfgs.Active = idx + a.cfgDlg.draft = a.cfgs.Configs[idx] + } + } + }) + + ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { + ui.Text(c, "名称").FontSize(11).TextColor(t.TextMuted).Width(48) + ui.TextInput(c, &a.cfgDlg.draft.Name).FillWidth().FontSize(13) + }) + ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { + ui.Text(c, "包目录").FontSize(11).TextColor(t.TextMuted).Width(48) + ui.TextInput(c, &a.cfgDlg.draft.Program).FillWidth().FontSize(13) + }) + ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { + ui.Text(c, "参数").FontSize(11).TextColor(t.TextMuted).Width(48) + ui.TextInput(c, &a.cfgDlg.draft.Args).FillWidth().FontSize(13) + }) + ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { + ui.Switch(c, &a.cfgDlg.draft.StopOnEntry) + ui.Text(c, "启动即停(调试时停在第一行)").FontSize(11).TextColor(t.TextMuted) + }) + + ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { + if ui.Button(c, "新建").Clicked() { + a.cfgs.Configs = append(a.cfgs.Configs, runConfig{Name: "新配置", Program: "."}) + a.cfgs.Active = len(a.cfgs.Configs) - 1 + a.cfgDlg.draft = a.cfgs.Configs[a.cfgs.Active] + } + if ui.Button(c, "复制").Clicked() { + cp := a.cfgDlg.draft + cp.Name = strings.TrimSpace(cp.Name) + " 副本" + a.cfgs.Configs = append(a.cfgs.Configs, cp) + a.cfgs.Active = len(a.cfgs.Configs) - 1 + a.cfgDlg.draft = cp + } + if ui.Button(c, "删除").Clicked() { + a.deleteActiveCfg() + } + ui.Box(c).Grow(1) + if ui.Button(c, "取消").Clicked() { + a.cfgDlg.open = false + a.loadConfig() + } + if ui.Button(c, "保存").Clicked() { + a.commitCfg() + a.cfgDlg.open = false + } + }) + }) + }) + + // 编辑中的值实时同步到配置里,切换标签时不丢。 + a.setActiveCfg(a.cfgDlg.draft) + + if !a.cfgDlg.dlg && a.cfgDlg.open { + a.cfgDlg.dlg = true + a.win.Update(func() {}) + } + if !a.cfgDlg.open && a.cfgDlg.dlg { + a.cfgDlg.dlg = false + a.focusEditorSoon() + } +} + +// deleteActiveCfg 删掉当前配置,至少保留一条。 +func (a *App) deleteActiveCfg() { + if len(a.cfgs.Configs) <= 1 { + a.cfgs.Configs = []runConfig{defaultConfig()} + a.cfgs.Active = 0 + a.cfgDlg.draft = a.cfgs.Configs[0] + return + } + i := a.cfgs.Active + a.cfgs.Configs = append(a.cfgs.Configs[:i], a.cfgs.Configs[i+1:]...) + if i >= len(a.cfgs.Configs) { + i = len(a.cfgs.Configs) - 1 + } + a.cfgs.Active = i + a.cfgDlg.draft = a.cfgs.Configs[i] +} + +// commitCfg 收尾:名字为空时补一个,然后落盘。 +func (a *App) commitCfg() { + a.setActiveCfg(a.cfgDlg.draft) + for i := range a.cfgs.Configs { + if strings.TrimSpace(a.cfgs.Configs[i].Name) == "" { + a.cfgs.Configs[i].Name = "未命名" + } + if strings.TrimSpace(a.cfgs.Configs[i].Program) == "" { + a.cfgs.Configs[i].Program = "." + } + } + a.saveConfig() +} + +// orDash 空字符串显示成短横,避免出现「参数 」这种半截文案。 +func orDash(s string) string { + if strings.TrimSpace(s) == "" { + return "—" + } + return s +} diff --git a/internal/app/runconfig_test.go b/internal/app/runconfig_test.go new file mode 100644 index 0000000..e3e69e3 --- /dev/null +++ b/internal/app/runconfig_test.go @@ -0,0 +1,107 @@ +package app + +import ( + "os" + "path/filepath" + "testing" +) + +func cfgApp(t *testing.T) *App { + t.Helper() + isolateConfig(t) + return &App{root: t.TempDir()} +} + +func TestConfigDefaults(t *testing.T) { + a := cfgApp(t) + a.loadConfig() + if got := a.activeCfg(); got.Program != "." || got.Name == "" { + t.Fatalf("没有配置文件时应有默认配置: %+v", got) + } +} + +func TestConfigRoundTrip(t *testing.T) { + a := cfgApp(t) + a.cfgs = configsFile{ + Configs: []runConfig{ + {Name: "服务端", Program: "./cmd/server", Args: "-addr :8080"}, + {Name: "测试", Program: ".", StopOnEntry: true}, + }, + Active: 1, + } + a.saveConfig() + + b := &App{root: a.root} + b.loadConfig() + if len(b.cfgs.Configs) != 2 || b.cfgs.Active != 1 { + t.Fatalf("读回来不一致: %+v", b.cfgs) + } + if got := b.activeCfg(); got.Name != "测试" || !got.StopOnEntry { + t.Fatalf("选中的应该是第二条: %+v", got) + } +} + +// TestConfigMigratesOldFormat 老版本存的是单个对象,升级后要变成一条配置。 +func TestConfigMigratesOldFormat(t *testing.T) { + a := cfgApp(t) + p := a.configPath() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + old := `{"program":"./cmd/app","args":"-v","stopOnEntry":true}` + if err := os.WriteFile(p, []byte(old), 0o644); err != nil { + t.Fatal(err) + } + a.loadConfig() + if len(a.cfgs.Configs) != 1 { + t.Fatalf("应迁移成 1 条,实际 %d", len(a.cfgs.Configs)) + } + got := a.activeCfg() + if got.Program != "./cmd/app" || got.Args != "-v" || !got.StopOnEntry || got.Name == "" { + t.Fatalf("迁移后的配置不对: %+v", got) + } +} + +func TestConfigActiveOutOfRange(t *testing.T) { + a := cfgApp(t) + a.cfgs = configsFile{Configs: []runConfig{{Name: "只有一条", Program: "."}}, Active: 5} + if got := a.activeCfg(); got.Name != "只有一条" { + t.Fatalf("下标越界要兜底到第一条: %+v", got) + } + a.setActiveCfg(runConfig{Name: "改过", Program: "./x"}) + if a.cfgs.Configs[0].Name != "改过" { + t.Fatalf("改动应落到第一条: %+v", a.cfgs.Configs) + } +} + +func TestConfigCommitFillsNames(t *testing.T) { + a := cfgApp(t) + a.cfgs = configsFile{Configs: []runConfig{{Name: " ", Program: ""}}} + a.cfgDlg.draft = a.cfgs.Configs[0] + a.commitCfg() + got := a.cfgs.Configs[0] + if got.Name != "未命名" || got.Program != "." { + t.Fatalf("空名字/空包目录应补默认值: %+v", got) + } + if _, err := os.Stat(a.configPath()); err != nil { + t.Fatalf("提交后应落盘: %v", err) + } +} + +func TestDeleteActiveConfig(t *testing.T) { + a := cfgApp(t) + a.cfgs = configsFile{ + Configs: []runConfig{{Name: "A"}, {Name: "B"}}, + Active: 0, + } + a.cfgDlg.draft = a.cfgs.Configs[0] + a.deleteActiveCfg() + if len(a.cfgs.Configs) != 1 || a.cfgs.Configs[0].Name != "B" { + t.Fatalf("删掉当前项后应剩 B: %+v", a.cfgs) + } + // 只剩一条时删除,应该重置成默认而不是清空 + a.deleteActiveCfg() + if len(a.cfgs.Configs) != 1 || a.cfgs.Configs[0].Program != "." { + t.Fatalf("最后一条删掉后应回到默认: %+v", a.cfgs) + } +} diff --git a/internal/app/search_test.go b/internal/app/search_test.go new file mode 100644 index 0000000..2af5790 --- /dev/null +++ b/internal/app/search_test.go @@ -0,0 +1,63 @@ +package app + +import "testing" + +func mustMatch(t *testing.T, query string, o searchOpts, line string, want bool) { + t.Helper() + m, err := buildMatcher(query, o) + if err != nil { + t.Fatalf("编译失败 %q: %v", query, err) + } + if got := m(line); got != want { + t.Fatalf("%q 匹配 %q: 期望 %v 实际 %v", query, line, want, got) + } +} + +func TestMatchPlainIgnoreCase(t *testing.T) { + o := searchOpts{} + mustMatch(t, "func", o, "func main() {}", true) + mustMatch(t, "FUNC", o, "func main() {}", true) + mustMatch(t, "xyz", o, "func main() {}", false) +} + +func TestMatchCaseSensitive(t *testing.T) { + o := searchOpts{matchCase: true} + mustMatch(t, "func", o, "func main() {}", true) + mustMatch(t, "FUNC", o, "func main() {}", false) +} + +func TestMatchWholeWord(t *testing.T) { + o := searchOpts{wholeWord: true} + mustMatch(t, "main", o, "func main() {", true) + mustMatch(t, "main", o, "func mainLoop() {", false) +} + +func TestMatchRegex(t *testing.T) { + o := searchOpts{useRegex: true} + mustMatch(t, `func\s+\w+\(`, o, "func Add(a, b int) {", true) + mustMatch(t, `^import`, o, `import "fmt"`, true) + mustMatch(t, `^\d+$`, o, "42", true) + mustMatch(t, `^\d+$`, o, "42 ", false) +} + +// TestMatchRegexLiteralWhenOff 不开正则时,特殊字符要按字面意思匹配。 +func TestMatchRegexLiteralWhenOff(t *testing.T) { + o := searchOpts{} + mustMatch(t, "a+b", o, "x = a+b", true) + mustMatch(t, "a+b", o, "x = aaab", false) + mustMatch(t, "a.c", o, "a.c", true) + mustMatch(t, "a.c", o, "abc", false) +} + +// TestMatchBadRegex 正则写错时返回错误,搜索面板应显示没有结果而不是崩。 +func TestMatchBadRegex(t *testing.T) { + if _, err := buildMatcher("a(", searchOpts{useRegex: true}); err == nil { + t.Fatal("非法正则应返回错误") + } +} + +// TestMatchChineseWholeWord 中文没有词边界,整词会退化成包含,仍应命中。 +func TestMatchChineseWholeWord(t *testing.T) { + o := searchOpts{wholeWord: true} + mustMatch(t, "过磅", o, "// 过磅记录", true) +} diff --git a/internal/app/second.go b/internal/app/second.go new file mode 100644 index 0000000..3641609 --- /dev/null +++ b/internal/app/second.go @@ -0,0 +1,75 @@ +package app + +import ( + "os" + "path/filepath" + "strings" +) + +// openFromArgs 处理启动时的命令行参数。 +// +// 第一个参数可能是目录(当工作区)也可能是文件(当要打开的文件); +// 文件则用它所在的目录当工作区。 +func (a *App) openFromArgs(args []string) { + if len(args) == 0 { + if last := lastWorkspace(); last != "" { + a.setRoot(last) + } + return + } + first := args[0] + if st, err := os.Stat(first); err == nil && !st.IsDir() { + a.setRoot(filepath.Dir(first)) + a.OpenFile(first) + return + } + a.setRoot(first) + if len(args) > 1 { + a.OpenFile(args[1]) + } +} + +// secondInstance 处理「又一个 MyGoland 被启动」:把窗口叫到前台, +// 并按对方传来的参数打开文件或工作区。 +func (a *App) secondInstance(args []string, wd string) { + if a.win == nil { + return + } + a.win.Show() + a.win.Focus() + + for _, arg := range args { + // 相对路径按对方的当前目录解析。 + p := arg + if !filepath.IsAbs(p) { + p = filepath.Join(wd, p) + } + st, err := os.Stat(p) + if err != nil { + continue + } + if st.IsDir() { + dir := p + a.win.Update(func() { a.setRoot(dir) }) + continue + } + file := p + a.win.Update(func() { + // 文件不在当前工作区里,连工作区一起换过去。 + if a.root == "" || !within(a.root, file) { + a.setRoot(filepath.Dir(file)) + } + go a.OpenFile(file) + }) + } +} + +// within 判断 path 是否在 root 之下(忽略大小写,Windows 路径习惯)。 +func within(root, path string) bool { + r := strings.ToLower(filepath.Clean(root)) + p := strings.ToLower(filepath.Clean(path)) + if r == p { + return true + } + return strings.HasPrefix(p, r+string(filepath.Separator)) +} diff --git a/internal/app/second_test.go b/internal/app/second_test.go new file mode 100644 index 0000000..ccdd9d9 --- /dev/null +++ b/internal/app/second_test.go @@ -0,0 +1,35 @@ +package app + +import ( + "path/filepath" + "testing" +) + +func TestWithin(t *testing.T) { + root := filepath.Join("C:", "work") + cases := []struct { + path string + want bool + }{ + {filepath.Join(root, "a.go"), true}, + {filepath.Join(root, "sub", "b.go"), true}, + {filepath.Join("C:", "workshop", "c.go"), false}, // 同前缀的兄弟目录不算 + {filepath.Join("C:", "other", "d.go"), false}, + } + for _, c := range cases { + if got := within(root, c.path); got != c.want { + t.Fatalf("within(%q)=%v 期望 %v", c.path, got, c.want) + } + } + if !within(root, root) { + t.Fatal("根目录本身应算在内") + } +} + +// TestWithinCaseInsensitive Windows 路径大小写不敏感。 +func TestWithinCaseInsensitive(t *testing.T) { + root := `C:/Work` + if !within(root, `c:/work/sub/a.go`) { + t.Fatal("大小写不同也应算在目录内") + } +} diff --git a/internal/app/session.go b/internal/app/session.go new file mode 100644 index 0000000..5de7a8e --- /dev/null +++ b/internal/app/session.go @@ -0,0 +1,333 @@ +package app + +import ( + "crypto/sha1" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/egoist/mygo/ui/editor" +) + +// sessionState 是关掉再打开时要恢复的界面状态。 +// +// 存在用户配置目录而不是工作区里:这些是「这台机器上的使用习惯」, +// 不该跟着仓库一起提交。 +type sessionState struct { + Root string `json:"root"` + Tabs []string `json:"tabs"` + Active string `json:"active"` + Breakpoints map[string][]bpJSON `json:"breakpoints,omitempty"` + Panel bool `json:"panel"` + PanelTab int `json:"panelTab"` + PanelH float32 `json:"panelH"` + Sidebar bool `json:"sidebar"` + SidebarW float32 `json:"sidebarW"` + PanelKind int `json:"panelKind"` + Light bool `json:"light"` + ShellIdx int `json:"shellIdx"` + // Terms 存每个终端会话用的外壳编号,TermIdx 是当前显示的那个。 + Terms []int `json:"terms,omitempty"` + TermIdx int `json:"termIdx"` + // Cursors 记每个文件上次的光标与滚动位置,键是绝对路径。 + Cursors map[string]cursorJSON `json:"cursors,omitempty"` +} + +// cursorJSON 是一个文件的位置记忆。 +type cursorJSON struct { + Line int `json:"line"` // 0 起 + Column int `json:"column"` // 0 起 + ScrollY float64 `json:"scrollY"` +} + +// bpJSON 是断点在会话文件里的形态。 +// +// 老版本写的是纯行号数组,UnmarshalJSON 兼容一下,免得升级后断点全丢。 +type bpJSON struct { + Line int `json:"line"` + Cond string `json:"cond,omitempty"` + Enabled bool `json:"enabled"` +} + +func (b *bpJSON) UnmarshalJSON(data []byte) error { + var n int + if err := json.Unmarshal(data, &n); err == nil { + b.Line, b.Enabled = n, true + return nil + } + type plain bpJSON + var v plain + if err := json.Unmarshal(data, &v); err != nil { + return err + } + *b = bpJSON(v) + return nil +} + +// sessionDir 返回存会话文件的目录。 +func sessionDir() string { + base, err := os.UserConfigDir() + if err != nil { + return "" + } + return filepath.Join(base, "mygoland") +} + +// sessionPath 按工作区路径散列出一个文件名,不同项目互不干扰。 +func sessionPath(root string) string { + dir := sessionDir() + if dir == "" || root == "" { + return "" + } + sum := sha1.Sum([]byte(strings.ToLower(filepath.Clean(root)))) + return filepath.Join(dir, fmt.Sprintf("session-%x.json", sum[:6])) +} + +// lastPath 记录上次打开的工作区,启动时没带参数就用它。 +func lastPath() string { + dir := sessionDir() + if dir == "" { + return "" + } + return filepath.Join(dir, "last.json") +} + +// saveSession 把当前界面状态写盘。只在主线程调用。 +func (a *App) saveSession() { + if a.restoring || a.root == "" { + return + } + p := sessionPath(a.root) + if p == "" { + return + } + bps := map[string][]bpJSON{} + for path, m := range a.bps { + if len(m) == 0 { + continue + } + lines := make([]bpJSON, 0, len(m)) + for line, bp := range m { + lines = append(lines, bpJSON{Line: line, Cond: bp.Cond, Enabled: bp.Enabled}) + } + sort.Slice(lines, func(i, j int) bool { return lines[i].Line < lines[j].Line }) + bps[path] = lines + } + + st := sessionState{ + Root: a.root, + Active: a.active, + Breakpoints: bps, + Panel: a.panel, + PanelTab: a.panelTab, + PanelH: a.panelH, + Sidebar: a.sidebarOn, + SidebarW: a.sidebar, + PanelKind: a.panelKind, + Light: a.light, + ShellIdx: a.shellIdx, + Terms: a.termShells(), + TermIdx: a.termIdx, + } + st.Cursors = map[string]cursorJSON{} + for _, d := range a.docs { + st.Tabs = append(st.Tabs, d.path) + if d.st == nil { + continue + } + // 大文件是只读截断的,位置意义不大,跳过。 + if d.truncated { + continue + } + pos := d.st.CursorPos() + st.Cursors[d.path] = cursorJSON{ + Line: pos.Line, + Column: pos.Col, + ScrollY: d.st.ScrollY(), + } + } + b, err := json.MarshalIndent(st, "", " ") + if err != nil { + logf("保存会话失败: %v", err) + return + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + logf("保存会话失败: %v", err) + return + } + if err := os.WriteFile(p, b, 0o644); err != nil { + logf("保存会话失败: %v", err) + return + } + // 顺手记下最后的工作区,下次没带参数时直接打开它。 + last := fmt.Sprintf("{\"root\":%q}", a.root) + _ = os.WriteFile(lastPath(), []byte(last), 0o644) +} + +// loadSession 读回某个工作区的会话状态。 +func loadSession(root string) (sessionState, bool) { + var st sessionState + p := sessionPath(root) + if p == "" { + return st, false + } + b, err := os.ReadFile(p) + if err != nil { + return st, false + } + if err := json.Unmarshal(b, &st); err != nil { + logf("读取会话失败: %v", err) + return st, false + } + return st, true +} + +// lastWorkspace 返回上次打开的工作区路径,目录不存在时返回空。 +func lastWorkspace() string { + b, err := os.ReadFile(lastPath()) + if err != nil { + return "" + } + var v struct { + Root string `json:"root"` + } + if err := json.Unmarshal(b, &v); err != nil || v.Root == "" { + return "" + } + if st, err := os.Stat(v.Root); err != nil || !st.IsDir() { + return "" + } + return v.Root +} + +// restoreSession 恢复某个工作区的界面状态。 +func (a *App) restoreSession(root string) { + st, ok := loadSession(root) + if !ok { + return + } + a.applySession(st) +} + +// applySession 把会话状态套到当前界面上。 +// +// 期间把 restoring 置真:恢复标签页会触发 loadDoc,那里面会存会话, +// 不挡住就会用「恢复了一半」的状态覆盖掉原文件。 +func (a *App) applySession(st sessionState) { + a.restoring = true + defer func() { a.restoring = false }() + + if st.Light != a.light { + a.SetLight(st.Light) + } + if st.SidebarW >= sidebarMin { + a.sidebar = st.SidebarW + } + a.sidebarOn = st.Sidebar + a.panelKind = st.PanelKind + a.panel = st.Panel + a.panelTab = st.PanelTab + if st.PanelH >= 80 { + a.panelH = st.PanelH + } + if st.ShellIdx >= 0 && st.ShellIdx < 3 { + a.shellIdx = st.ShellIdx + } + // 终端会话只恢复「有几个、各是什么外壳」,进程等切到终端页再启动—— + // 开机就把几个 shell 全拉起来没有必要。 + for _, sh := range st.Terms { + if sh < 0 || sh > 2 { + sh = 0 + } + a.terms = append(a.terms, &termSession{shell: sh, state: "启动中…"}) + } + if len(a.terms) > 0 { + a.termIdx = st.TermIdx + if a.termIdx < 0 || a.termIdx >= len(a.terms) { + a.termIdx = 0 + } + } + for path, lines := range st.Breakpoints { + if len(lines) == 0 { + continue + } + m := map[int]breakpoint{} + for _, ln := range lines { + m[ln.Line] = breakpoint{Cond: ln.Cond, Enabled: ln.Enabled} + } + a.bps[path] = m + } + for _, p := range st.Tabs { + if _, err := os.Stat(p); err != nil { + continue // 文件可能已经被删了 + } + d, err := a.loadDoc(p) + if err != nil { + continue + } + if c, ok := st.Cursors[p]; ok { + // 位置要等编辑器排过版再套,否则滚动距离算不准。 + a.pendingCursor = append(a.pendingCursor, cursorRestore{doc: d, cur: c}) + } + } + if st.Active != "" { + if d := a.find(st.Active); d != nil { + a.active = d.path + } + } + a.syncTitle() +} + +// cursorRestore 是一条待应用的「回到原位」请求。 +type cursorRestore struct { + doc *Doc + cur cursorJSON +} + +// applyPendingCursor 把上次的光标与滚动位置套回编辑器。 +// +// 必须等编辑器排过版再做:滚动距离依赖内容高度,一打开就设会被算成 0。 +// 只处理一次,之后用户的滚动就归用户了。 +func (a *App) applyPendingCursor() { + if len(a.pendingCursor) == 0 { + return + } + batch := a.pendingCursor + a.pendingCursor = nil + for _, it := range batch { + if it.doc == nil || it.doc.st == nil || !a.hasDoc(it.doc) { + continue + } + line := it.cur.Line + if line < 0 { + line = 0 + } + if line >= it.doc.buf.LineCount() { + line = it.doc.buf.LineCount() - 1 + } + col := it.cur.Column + lineLen := len(it.doc.buf.Line(line)) + if col > lineLen { + col = lineLen + } + // GoTo 会把光标行滚到中间,所以先定位、再把滚动条拉回原位。 + it.doc.st.GoTo(editor.Pos{Line: line, Col: col}) + if it.cur.ScrollY > 0 { + it.doc.st.SetScrollY(it.cur.ScrollY) + } + } + a.refresh() +} + +// hasDoc 判断文档还在打开列表里。 +func (a *App) hasDoc(target *Doc) bool { + for _, d := range a.docs { + if d == target { + return true + } + } + return false +} diff --git a/internal/app/session_test.go b/internal/app/session_test.go new file mode 100644 index 0000000..8b62c4d --- /dev/null +++ b/internal/app/session_test.go @@ -0,0 +1,94 @@ +package app + +import ( + "os" + "path/filepath" + "testing" +) + +// isolateConfig 把配置目录指到临时目录,避免测试污染真实的会话文件。 +func isolateConfig(t *testing.T) { + t.Helper() + dir := t.TempDir() + t.Setenv("AppData", dir) + t.Setenv("XDG_CONFIG_HOME", dir) +} + +func TestSessionRoundTrip(t *testing.T) { + isolateConfig(t) + root := t.TempDir() + p1 := filepath.Join(root, "a.go") + p2 := filepath.Join(root, "b.go") + for _, p := range []string{p1, p2} { + if err := os.WriteFile(p, []byte("package x\n"), 0o644); err != nil { + t.Fatal(err) + } + } + + a := &App{ + root: root, bps: map[string]map[int]breakpoint{p1: {3: {Enabled: true}, 7: {Enabled: true}}}, + sidebar: 320, sidebarOn: false, + panel: true, panelTab: 2, panelH: 260, + panelKind: 1, light: true, shellIdx: 2, + } + a.docs = []*Doc{{path: p1}, {path: p2}} + a.active = p2 + a.saveSession() + + st, ok := loadSession(root) + if !ok { + t.Fatal("没有读到会话") + } + if !st.Panel || st.PanelTab != 2 || st.PanelH != 260 { + t.Fatalf("面板状态不对: %+v", st) + } + if st.Sidebar || st.SidebarW != 320 || st.PanelKind != 1 { + t.Fatalf("侧栏状态不对: %+v", st) + } + if len(st.Tabs) != 2 || st.Tabs[0] != p1 || st.Tabs[1] != p2 { + t.Fatalf("标签不对: %+v", st.Tabs) + } + if st.Active != p2 { + t.Fatalf("当前标签不对: %q", st.Active) + } + if len(st.Breakpoints[p1]) != 2 { + t.Fatalf("断点不对: %+v", st.Breakpoints) + } + if !st.Light || st.ShellIdx != 2 { + t.Fatalf("主题/外壳不对: %+v", st) + } +} + +func TestLastWorkspace(t *testing.T) { + isolateConfig(t) + root := t.TempDir() + a := &App{root: root, bps: map[string]map[int]breakpoint{}} + a.saveSession() + + got := lastWorkspace() + if filepath.Clean(got) != filepath.Clean(root) { + t.Fatalf("上次工作区应是 %q,实际 %q", root, got) + } +} + +// TestLastWorkspaceGone 确认目录被删后不会返回失效路径。 +func TestLastWorkspaceGone(t *testing.T) { + isolateConfig(t) + root := t.TempDir() + a := &App{root: root, bps: map[string]map[int]breakpoint{}} + a.saveSession() + + if err := os.RemoveAll(root); err != nil { + t.Fatal(err) + } + if got := lastWorkspace(); got != "" { + t.Fatalf("目录不存在时不该返回 %q", got) + } +} + +func TestSessionMissing(t *testing.T) { + isolateConfig(t) + if _, ok := loadSession(filepath.Join(t.TempDir(), "nope")); ok { + t.Fatal("不存在的会话不该读成功") + } +} diff --git a/internal/app/settings.go b/internal/app/settings.go new file mode 100644 index 0000000..da780ea --- /dev/null +++ b/internal/app/settings.go @@ -0,0 +1,270 @@ +package app + +import ( + "encoding/json" + "os" + "path/filepath" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" +) + +// settings 是跨工作区的编辑器偏好,存在用户配置目录里。 +type settings struct { + FontSize float32 `json:"fontSize"` + LineHeight float32 `json:"lineHeight"` + TabSize int `json:"tabSize"` + Spaces bool `json:"spaces"` + SoftWrap bool `json:"softWrap"` + FormatOnSave bool `json:"formatOnSave"` + // OrganizeImports 在保存 Go 文件时顺手整理 import:补缺失的、删没用的。 + OrganizeImports bool `json:"organizeImports"` + Light bool `json:"light"` + // History 开关本地历史(保存后留点、历史面板)。 + History bool `json:"history"` + // AutoSnapshot 在编辑停手后自动留点(只写历史,不动原文件)。 + AutoSnapshot bool `json:"autoSnapshot"` + // InlayHints 控制参数名/类型这类内联提示。 + // 老配置文件里没有这一项,读的时候要按「默认开」处理(见 loadSettings)。 + InlayHints bool `json:"inlayHints"` +} + +// defaultSettings 是没配置过时的取值,和改动前的硬编码保持一致。 +func defaultSettings() settings { + return settings{ + FontSize: 13, + LineHeight: 1.4, + TabSize: 4, + Spaces: false, // Go 用 tab + SoftWrap: false, + FormatOnSave: true, + // gopls 的整理是确定性改动(补缺/删无用),默认开。 + OrganizeImports: true, + History: true, + AutoSnapshot: true, + InlayHints: true, + } +} + +// inlaysOn 返回内联提示是否开启。 +func (a *App) inlaysOn() bool { + return a.set.InlayHints +} + +// settingsPath 返回设置文件路径。 +func settingsPath() string { + dir := sessionDir() + if dir == "" { + return "" + } + return filepath.Join(dir, "settings.json") +} + +// loadSettings 读设置,读不到就用默认值。 +func loadSettings() settings { + st := defaultSettings() + p := settingsPath() + if p == "" { + return st + } + b, err := os.ReadFile(p) + if err != nil { + return st + } + // 缺字段时保留默认值,避免旧文件把新字段清零。 + if err := json.Unmarshal(b, &st); err != nil { + logf("读取设置失败: %v", err) + return defaultSettings() + } + return st +} + +// saveSettings 写设置文件。 +func saveSettings(st settings) { + p := settingsPath() + if p == "" { + return + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + logf("保存设置失败: %v", err) + return + } + b, err := json.MarshalIndent(st, "", " ") + if err != nil { + logf("保存设置失败: %v", err) + return + } + if err := os.WriteFile(p, b, 0o644); err != nil { + logf("保存设置失败: %v", err) + } +} + +// OpenSettings 打开设置弹窗。 +func (a *App) OpenSettings() { + a.setDlg = a.set + a.setOpen = true + a.win.Update(func() {}) +} + +// settingsDialog 画设置弹窗。改动即时预览,点「确定」才落盘。 +func (a *App) settingsDialog(c *ui.Context) { + if !a.setOpen { + return + } + t := c.Theme() + + ui.Modal(c, &a.setOpen, func() { + ui.Column(c).Width(520).Gap(12).Children(func() { + ui.Text(c, "设置").FontSize(14).Bold().TextColor(t.Text) + ui.Text(c, "改动即时生效,点「确定」保存").FontSize(10).TextColor(t.TextMuted).SingleLine() + + row := func(label string, body func()) { + ui.Row(c).FillWidth().Gap(12).AlignItems(ui.Center).Children(func() { + ui.Text(c, label).FontSize(12).TextColor(t.Text).Width(96) + body() + }) + } + + fontIdx := indexOfFloat(fontSizes, a.setDlg.FontSize) + row("字号", func() { + if ui.Segmented(c, &fontIdx, "12", "13", "14", "15", "16").Changed() { + a.setDlg.FontSize = fontSizes[fontIdx] + } + }) + + lhIdx := indexOfFloat(lineHeights, a.setDlg.LineHeight) + row("行高", func() { + if ui.Segmented(c, &lhIdx, "1.3", "1.4", "1.5", "1.7").Changed() { + a.setDlg.LineHeight = lineHeights[lhIdx] + } + }) + + tabIdx := 0 + switch a.setDlg.TabSize { + case 2: + tabIdx = 0 + case 4: + tabIdx = 1 + case 8: + tabIdx = 2 + } + row("缩进宽度", func() { + if ui.Segmented(c, &tabIdx, "2", "4", "8").Changed() { + a.setDlg.TabSize = tabSizes[tabIdx] + } + }) + + row("缩进方式", func() { + ui.Checkbox(c, &a.setDlg.Spaces, "用空格缩进(Go 一般不勾)") + }) + + row("自动换行", func() { + ui.Checkbox(c, &a.setDlg.SoftWrap, "超宽自动折行") + }) + + row("保存时", func() { + ui.Checkbox(c, &a.setDlg.FormatOnSave, "保存时自动格式化 Go 文件") + ui.Checkbox(c, &a.setDlg.OrganizeImports, "保存时整理 import(补缺失 / 删无用)") + ui.Checkbox(c, &a.setDlg.InlayHints, "显示类型 / 参数名内联提示") + ui.Checkbox(c, &a.setDlg.History, "保留本地历史(保存后留快照)") + ui.Checkbox(c, &a.setDlg.AutoSnapshot, "停手后自动留快照(不自动改磁盘)") + }) + + themeIdx := 0 + if a.setDlg.Light { + themeIdx = 1 + } + row("主题", func() { + if ui.Segmented(c, &themeIdx, "深色", "浅色").Changed() { + a.setDlg.Light = themeIdx == 1 + a.SetLight(a.setDlg.Light) + } + }) + + ui.Row(c).Gap(8).Justify(ui.End).Children(func() { + if ui.Button(c, "恢复默认").Clicked() { + a.setDlg = defaultSettings() + a.applySettings(a.setDlg) + } + if ui.Button(c, "取消").Clicked() { + // 取消要把预览时的改动退回去。 + a.applySettings(a.set) + a.setOpen = false + } + if ui.Button(c, "确定").Clicked() { + a.applySettings(a.setDlg) + a.set = a.setDlg + saveSettings(a.set) + a.setOpen = false + } + }) + }) + }) + + // 即时预览:滑块一动就套到已打开的编辑器上。 + a.applySettings(a.setDlg) + + if !a.setOpen { + a.focusEditorSoon() + } +} + +var ( + fontSizes = []float32{12, 13, 14, 15, 16} + lineHeights = []float32{1.3, 1.4, 1.5, 1.7} + tabSizes = []int{2, 4, 8} +) + +func indexOfFloat(list []float32, v float32) int { + for i, x := range list { + if x == v { + return i + } + } + return 1 +} + +// applySettings 把设置套到所有已打开的编辑器上。 +// +// 弹窗里每帧都会调它做即时预览,所以先跟「已应用的值」比一次: +// 没变就直接返回,避免每帧都请求重绘。 +func (a *App) applySettings(st settings) { + if a.applied == st { + return + } + prev := a.applied + a.applied = st + indent := editor.IndentAuto + if st.Spaces { + indent = editor.IndentSpaces + } + for _, d := range a.docs { + if d.st == nil { + continue + } + d.st.Font = ui.Font{Size: st.FontSize} + d.st.LineHeight = st.LineHeight + d.st.TabSize = st.TabSize + d.st.Indent = indent + d.st.SoftWrap = st.SoftWrap + } + // 内联提示开关变了就重来一遍:关掉要清空,打开要重新问 gopls。 + if prev.InlayHints != st.InlayHints { + for _, d := range a.docs { + a.scheduleInlays(d) + } + } + if a.win != nil { + a.win.Update(func() {}) + } +} + +// editorSettings 返回新文档该用的排版参数。 +func (a *App) editorSettings() (ui.Font, float32, int, editor.IndentStyle, bool) { + st := a.applied + indent := editor.IndentAuto + if st.Spaces { + indent = editor.IndentSpaces + } + return ui.Font{Size: st.FontSize}, st.LineHeight, st.TabSize, indent, st.SoftWrap +} diff --git a/internal/app/settings_test.go b/internal/app/settings_test.go new file mode 100644 index 0000000..6e2095d --- /dev/null +++ b/internal/app/settings_test.go @@ -0,0 +1,97 @@ +package app + +import ( + "os" + "path/filepath" + "testing" +) + +func TestSettingsDefaults(t *testing.T) { + isolateConfig(t) + st := loadSettings() + want := defaultSettings() + if st != want { + t.Fatalf("没有配置文件时应取默认值: %+v != %+v", st, want) + } +} + +func TestSettingsRoundTrip(t *testing.T) { + isolateConfig(t) + custom := settings{ + FontSize: 15, LineHeight: 1.7, TabSize: 2, + Spaces: true, SoftWrap: true, FormatOnSave: false, Light: true, + } + saveSettings(custom) + got := loadSettings() + if got != custom { + t.Fatalf("读回来的设置不一致: %+v != %+v", got, custom) + } +} + +// TestSettingsPartialFile 确认旧配置缺字段时不会把新字段清零。 +func TestSettingsPartialFile(t *testing.T) { + isolateConfig(t) + p := settingsPath() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(`{"fontSize":16}`), 0o644); err != nil { + t.Fatal(err) + } + got := loadSettings() + if got.FontSize != 16 { + t.Fatalf("字号应为 16,实际 %v", got.FontSize) + } + if got.TabSize != defaultSettings().TabSize || got.LineHeight != defaultSettings().LineHeight { + t.Fatalf("缺的字段应保留默认值: %+v", got) + } +} + +func TestSettingsBrokenFile(t *testing.T) { + isolateConfig(t) + p := settingsPath() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(`{not json`), 0o644); err != nil { + t.Fatal(err) + } + if got := loadSettings(); got != defaultSettings() { + t.Fatalf("文件损坏时应退回默认值: %+v", got) + } +} + +// TestSettingsInlayDefaultOn 老配置文件里没有 inlayHints 这一项,要按「开」处理。 +func TestSettingsInlayDefaultOn(t *testing.T) { + isolateConfig(t) + p := settingsPath() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + // 只有字号,没有 inlayHints + if err := os.WriteFile(p, []byte(`{"fontSize":15}`), 0o644); err != nil { + t.Fatal(err) + } + st := loadSettings() + if !st.InlayHints { + t.Fatal("旧配置没写这一项时应默认开启") + } + if st.FontSize != 15 { + t.Fatalf("其它字段应正常读入: %v", st.FontSize) + } +} + +// TestSettingsInlayExplicitOff 显式关掉要记住。 +func TestSettingsInlayExplicitOff(t *testing.T) { + isolateConfig(t) + p := settingsPath() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(`{"inlayHints":false}`), 0o644); err != nil { + t.Fatal(err) + } + if loadSettings().InlayHints { + t.Fatal("显式 false 应被尊重") + } +} diff --git a/internal/app/single.go b/internal/app/single.go new file mode 100644 index 0000000..00cb5c7 --- /dev/null +++ b/internal/app/single.go @@ -0,0 +1,133 @@ +package app + +import ( + "encoding/json" + "fmt" + "hash/fnv" + "net" + "os" + "sync" + "time" +) + +// 单实例:第一个进程在本地端口上监听,后来的进程把参数发过去然后退出。 +// +// 为什么不用框架自带的 RequestSingleInstanceLock:它在 Windows 上走的是 +// Unix socket,实测第二个进程既没转发也没退出(端口/套接字建不起来, +// 两个进程都认为自己才是第一个)。这里用回环 TCP + 握手,行为可预期。 + +const singleMagic = "mygoland-single" + +// secondMsg 是转发给已运行实例的消息。 +type secondMsg struct { + App string `json:"app"` + Args []string `json:"args"` + WD string `json:"wd"` +} + +var ( + singleLn net.Listener + singleOnce sync.Once + secondEvents = make(chan secondMsg, 8) +) + +// ClaimSingleInstance 尝试成为唯一实例。 +// +// 返回 true 表示本进程是第一个,可以继续启动;返回 false 表示参数已经 +// 交给已运行的实例,本进程应当直接退出。 +func ClaimSingleInstance(name string, args []string) bool { + // 自动化调试实例不参与单实例:否则它会把参数转发给用户正开着的窗口, + // 自己直接退掉,测试就无从下手了。 + if os.Getenv("MYGO_AUTOMATION") != "" { + return true + } + ports := singlePorts(name) + for _, port := range ports { + addr := fmt.Sprintf("127.0.0.1:%d", port) + ln, err := net.Listen("tcp", addr) + if err == nil { + singleOnce.Do(func() { + singleLn = ln + go serveSingle(ln) + }) + return true + } + // 端口被占:可能是我们自己的实例,握个手确认。 + if forwardTo(port, args) { + return false + } + } + // 全都被别的程序占着:宁可多开一个窗口,也不要打不开。 + return true +} + +// singlePorts 按应用名散列出一小段候选端口。 +func singlePorts(name string) []int { + h := fnv.New32a() + _, _ = h.Write([]byte(name)) + base := 47800 + int(h.Sum32()%120) + out := make([]int, 0, 6) + for i := 0; i < 6; i++ { + out = append(out, base+i) + } + return out +} + +// serveSingle 接收后来者的参数。 +func serveSingle(ln net.Listener) { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + _ = c.SetDeadline(time.Now().Add(3 * time.Second)) + var m secondMsg + if err := json.NewDecoder(c).Decode(&m); err != nil { + return + } + if m.App != singleMagic { + return + } + _, _ = c.Write([]byte("ok")) + select { + case secondEvents <- m: + default: + // 队列满了说明主线程卡住,丢掉这条也比阻塞后来者好。 + } + }(c) + } +} + +// forwardTo 把参数发给指定端口上的实例,成功返回 true。 +func forwardTo(port int, args []string) bool { + wd, _ := os.Getwd() + msg := secondMsg{App: singleMagic, Args: args, WD: wd} + b, err := json.Marshal(msg) + if err != nil { + return false + } + c, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 800*time.Millisecond) + if err != nil { + return false + } + defer c.Close() + _ = c.SetDeadline(time.Now().Add(2 * time.Second)) + if _, err := c.Write(b); err != nil { + return false + } + // 只有认领了握手才说明对面是我们的实例,而不是别的程序占了端口。 + buf := make([]byte, 2) + n, err := c.Read(buf) + return err == nil && n == 2 && string(buf[:n]) == "ok" +} + +// watchSecondInstance 在主线程外监听转发来的启动请求。 +func (a *App) watchSecondInstance() { + go func() { + for m := range secondEvents { + a.secondInstance(m.Args, m.WD) + } + }() +} diff --git a/internal/app/symbols.go b/internal/app/symbols.go new file mode 100644 index 0000000..cb9f635 --- /dev/null +++ b/internal/app/symbols.go @@ -0,0 +1,122 @@ +package app + +import ( + "context" + "path/filepath" + "strings" + "time" + + "mygoland/internal/lsp" +) + +// symbolDelay 是输入停顿多久后才问 gopls:每敲一个字都查一次会很卡。 +const symbolDelay = 180 * time.Millisecond + +// OpenSymbols 打开「转到符号」(全工作区)。 +func (a *App) OpenSymbols() { + a.pal = paletteState{open: true, symbol: true, waiting: true} + a.pal.gen++ + gen := a.pal.gen + go a.searchSymbols("", gen) + a.win.Update(func() {}) +} + +// searchSymbols 向 gopls 要一组符号填进面板。 +func (a *App) searchSymbols(query string, gen int) { + if a.lsp == nil || a.root == "" { + a.win.Update(func() { + if a.pal.gen == gen { + a.pal.waiting = false + } + }) + return + } + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + syms, err := a.lsp.WorkspaceSymbols(ctx, query) + + items := make([]paletteItem, 0, len(syms)) + if err == nil { + for _, s := range syms { + uri := s.Location.URI + if uri == "" { + uri = s.TargetURI + } + path := lsp.URIToPath(uri) + if path == "" { + continue + } + // gopls 的 workspace/symbol 会把依赖包也算进来 + // (空查询时尤其明显),这里只留工作区内的符号。 + if !within(a.root, path) { + continue + } + rel := filepath.ToSlash(path) + if r, err := filepath.Rel(a.root, path); err == nil { + rel = filepath.ToSlash(r) + } + // 面板的 itemLine 行是「小字 Label 在上、大字 Text 在下」, + // 所以名字放 Text,种类和文件放 Label。 + items = append(items, paletteItem{ + Kind: itemLine, + Path: path, + Line: s.Location.Range.Start.Line + 1, + Label: kindName(s.Kind) + " · " + rel, + Hint: rel + " " + s.ContainerName, + Text: s.Name, + }) + } + } + + a.win.Update(func() { + // 期间用户又敲了字,这批结果作废。 + if a.pal.gen != gen || !a.pal.symbol { + return + } + a.pal.items = items + a.pal.waiting = false + a.pal.sel = 0 + }) +} + +// kindName 把 LSP 的符号类型编号转成中文,放在副标题里帮助区分。 +func kindName(kind int) string { + switch kind { + case 2, 3, 4, 23: + return "模块/包/命名空间" + case 5: + return "类" + case 6: + return "方法" + case 7, 8: + return "属性/字段" + case 9: + return "构造函数" + case 10: + return "枚举" + case 11: + return "接口" + case 12: + return "函数" + case 13: + return "变量" + case 14: + return "常量" + case 22: + return "结构体" + case 26: + return "类型参数" + } + return "符号" +} + +// scheduleSymbols 输入变化后延迟查询,避免每个按键都打一次 gopls。 +func (a *App) scheduleSymbols(query string) { + a.pal.gen++ + gen := a.pal.gen + a.pal.waiting = true + time.AfterFunc(symbolDelay, func() { a.searchSymbols(query, gen) }) +} + +// symbolHint 把查询串规整一下:gopls 对空串会返回一大把,直接原样用。 +func symbolHint(q string) string { return strings.TrimSpace(q) } diff --git a/internal/app/tabmenu.go b/internal/app/tabmenu.go new file mode 100644 index 0000000..fb21569 --- /dev/null +++ b/internal/app/tabmenu.go @@ -0,0 +1,160 @@ +package app + +import ( + "fmt" + + "github.com/egoist/mygo" +) + +// tabMenu 是文件标签页的右键菜单。 +// +// 菜单项后面带上数量(关闭左边(3)这种),是因为「关闭全部」这类操作 +// 一旦点错就不可撤销,先让人看清会影响几个文件。 +func (a *App) tabEntries(path string) []menuEntry { + idx := a.docIndex(path) + if idx < 0 { + return nil + } + n := len(a.docs) + var out []menuEntry + + out = append(out, menuEntry{label: "关闭", action: func() { go a.CloseDoc(path) }}) + if idx > 0 { + out = append(out, menuEntry{ + label: fmt.Sprintf("关闭左边(%d)", idx), + action: func() { a.closePaths(0, idx) }, + }) + } + if idx < n-1 { + out = append(out, menuEntry{ + label: fmt.Sprintf("关闭右边(%d)", n-1-idx), + action: func() { a.closePaths(idx+1, n) }, + }) + } + out = append(out, menuEntry{divider: true}) + if n > 1 { + out = append(out, menuEntry{ + label: fmt.Sprintf("关闭其他(%d)", n-1), + action: func() { a.closeOthers(path) }, + }) + } + out = append(out, menuEntry{ + label: fmt.Sprintf("关闭全部(%d)", n), + action: func() { a.closePaths(0, n) }, + }) + out = append(out, menuEntry{divider: true}) + + if saved := a.savedPaths(); len(saved) == 0 { + out = append(out, menuEntry{label: "关闭已保存的", disabled: true}) + } else { + out = append(out, menuEntry{ + label: fmt.Sprintf("关闭已保存的(%d)", len(saved)), + action: func() { a.closeSaved() }, + }) + } + return out +} + +// docIndex 返回文件在标签栏里的位置,找不到为 -1。 +func (a *App) docIndex(path string) int { + for i, d := range a.docs { + if d.path == path { + return i + } + } + return -1 +} + +// savedPaths 返回没有未保存改动的文件。 +func (a *App) savedPaths() []string { + var out []string + for _, d := range a.docs { + if !d.buf.Modified() { + out = append(out, d.path) + } + } + return out +} + +// closeOthers 关掉除 path 以外的所有标签。 +func (a *App) closeOthers(path string) { + var paths []string + for _, d := range a.docs { + if d.path != path { + paths = append(paths, d.path) + } + } + a.closePathsOf(paths) +} + +// closeSaved 只关已保存的标签,天然不会丢改动,直接关。 +func (a *App) closeSaved() { + a.closePathsOf(a.savedPaths()) +} + +// closePaths 关闭 [from, to) 区间的标签。 +func (a *App) closePaths(from, to int) { + if from < 0 { + from = 0 + } + if to > len(a.docs) { + to = len(a.docs) + } + if from >= to { + return + } + paths := make([]string, 0, to-from) + for _, d := range a.docs[from:to] { + paths = append(paths, d.path) + } + a.closePathsOf(paths) +} + +// closePathsOf 是批量关闭的执行端。 +// +// 未保存的文件只统一问一次,而不是逐个弹框——一次关五个标签弹五次确认 +// 没人受得了。选择「全部保存」时用 writeDoc 同步落盘,不走 saveDoc 的 +// 异步格式化,否则关窗口和写盘会撞在一起。 +func (a *App) closePathsOf(paths []string) { + if len(paths) == 0 || a.win == nil { + return + } + + var dirty []*Doc + for _, p := range paths { + if d := a.find(p); d != nil && d.buf.Modified() { + dirty = append(dirty, d) + } + } + + if len(dirty) > 0 { + res, err := mygo.Dialog.Message(mygo.MessageOptions{ + Parent: a.win, + Type: mygo.MessageWarning, + Title: "未保存的更改", + Message: fmt.Sprintf("要关闭的 %d 个文件里有 %d 个未保存。", len(paths), len(dirty)), + Buttons: []string{"全部保存", "不保存", "取消"}, + DefaultButton: 0, + CancelButton: 2, + }) + if err != nil { + return + } + switch res.Button { + case 0: + for _, d := range dirty { + a.writeDoc(d) + } + case 1: + // 丢弃改动。 + default: + return + } + } + + a.win.Update(func() { + for _, p := range paths { + a.removeDoc(p) + } + }) +} diff --git a/internal/app/terminal.go b/internal/app/terminal.go new file mode 100644 index 0000000..2eaee18 --- /dev/null +++ b/internal/app/terminal.go @@ -0,0 +1,367 @@ +package app + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/egoist/mygo/plugins/terminal" + "github.com/egoist/mygo/ui" +) + +// shellChoice 是一个可选的终端外壳。 +type shellChoice struct { + Name string + Cmd []string +} + +// termSession 是一次终端会话。 +// +// 多个会话各自持有独立的 shell 进程,互不影响:一个跑着 go test, +// 另一个照样能敲 git,这是单会话做不到的。 +type termSession struct { + t *terminal.Terminal + shell int + state string + msg string + started bool +} + +// 会话标签上显示的名字:短一点,别把标签栏撑开。 +func (s *termSession) label() string { + switch s.shell { + case 0: + return "PS" + case 1: + return "Bash" + case 2: + return "CMD" + } + return "终端" +} + +// detectShells 列出可选的终端外壳;找不到的条目仍保留,启动时给出提示。 +func detectShells() []shellChoice { + return []shellChoice{ + {Name: "PowerShell", Cmd: powerShellCmd()}, + {Name: "Git Bash", Cmd: gitBashCmd()}, + {Name: "CMD", Cmd: cmdCmd()}, + } +} + +// powerShellCmd 优先 PowerShell 7(pwsh),退回系统自带的 5.1。 +func powerShellCmd() []string { + if p, err := exec.LookPath("pwsh.exe"); err == nil { + return []string{p, "-NoLogo"} + } + if root := os.Getenv("SystemRoot"); root != "" { + p := filepath.Join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") + if _, err := os.Stat(p); err == nil { + return []string{p, "-NoLogo"} + } + } + return nil +} + +// gitBashCmd 在常见安装位置查找 Git Bash。 +func gitBashCmd() []string { + var candidates []string + for _, base := range []string{ + os.Getenv("ProgramFiles"), + os.Getenv("ProgramFiles(x86)"), + os.Getenv("LOCALAPPDATA"), + } { + if base == "" { + continue + } + candidates = append(candidates, + filepath.Join(base, "Git", "bin", "bash.exe"), + filepath.Join(base, "Programs", "Git", "bin", "bash.exe")) + } + for _, p := range candidates { + if _, err := os.Stat(p); err == nil { + return []string{p, "-i"} + } + } + if p, err := exec.LookPath("bash.exe"); err == nil { + return []string{p, "-i"} + } + return nil +} + +// cmdCmd 返回系统的命令解释器。 +func cmdCmd() []string { + if p := os.Getenv("ComSpec"); p != "" { + return []string{p} + } + return []string{"cmd.exe"} +} + +// ToggleTerminal 打开底部面板并切到终端页签。 +func (a *App) ToggleTerminal() { + a.panel = true + a.panelTab = 3 + if a.panelH < 240 { + a.panelH = 260 + } + a.refresh() +} + +// curTerm 返回当前显示的会话。 +func (a *App) curTerm() *termSession { + if a.termIdx < 0 || a.termIdx >= len(a.terms) { + return nil + } + return a.terms[a.termIdx] +} + +// hasTerm 判断会话是否还在列表里(异步启动回来时可能已经被关掉了)。 +func (a *App) hasTerm(s *termSession) bool { + for _, x := range a.terms { + if x == s { + return true + } + } + return false +} + +// ensureTerm 保证至少有一个会话,并把当前会话启动起来。 +func (a *App) ensureTerm() { + if a.shells == nil { + a.shells = detectShells() + } + if len(a.terms) == 0 { + a.terms = []*termSession{{shell: a.shellIdx, state: "启动中…"}} + a.termIdx = 0 + } + s := a.curTerm() + if s == nil || s.started { + return + } + s.started = true + go a.startTerm(s, s.shell, a.root) +} + +// newTerm 新建一个会话并切过去。 +func (a *App) newTerm() { + if a.shells == nil { + a.shells = detectShells() + } + s := &termSession{shell: a.shellIdx, state: "启动中…", started: true} + a.terms = append(a.terms, s) + a.termIdx = len(a.terms) - 1 + go a.startTerm(s, s.shell, a.root) + a.refresh() +} + +// closeTerm 关闭第 i 个会话;关掉最后一个时留一个空位,下次显示会重新启动。 +func (a *App) closeTerm(i int) { + if i < 0 || i >= len(a.terms) { + return + } + if t := a.terms[i].t; t != nil { + _ = t.Close() + } + a.terms = append(a.terms[:i], a.terms[i+1:]...) + switch { + case len(a.terms) == 0: + a.termIdx = 0 + case a.termIdx >= len(a.terms): + a.termIdx = len(a.terms) - 1 + case a.termIdx > i: + a.termIdx-- + } + a.refresh() +} + +// startTerm 在后台启动终端:New 可能要下载原生库,不能阻塞界面线程。 +func (a *App) startTerm(s *termSession, idx int, dir string) { + shells := a.shells + if idx < 0 || idx >= len(shells) { + idx = 0 + } + choice := shells[idx] + if len(choice.Cmd) == 0 { + a.win.Update(func() { + if a.hasTerm(s) { + s.state = "不可用" + s.msg = "没有找到 " + choice.Name + ",请确认已安装后再点重启。" + } + }) + return + } + if dir == "" { + dir, _ = os.UserHomeDir() + } + logf("terminal starting: %s in %s", choice.Name, dir) + term, err := terminal.New(terminal.Options{Command: choice.Cmd, Dir: dir}) + if err == nil { + logf("terminal started: %s", choice.Name) + } + a.win.Update(func() { + if !a.hasTerm(s) { + return + } + if err != nil { + s.state = "不可用" + s.msg = terminalErrorText(err) + return + } + s.t = term + s.state = "就绪" + }) +} + +// terminalErrorText 把启动失败翻译成可操作的提示。 +func terminalErrorText(err error) string { + msg := err.Error() + lower := strings.ToLower(msg) + if !strings.Contains(lower, "ghostty") && !strings.Contains(lower, "download") && !strings.Contains(lower, "下载") { + return "终端启动失败:" + msg + } + return "缺少终端原生库 libghostty-vt。\n" + + "把下载到的 DLL 放到 MyGoland.exe 同目录、命名为 ghostty-vt.dll,\n" + + "或设置环境变量 MYGO_GHOSTTY_VT 指向该文件,然后点「重启」。\n" + + "下载地址:https://github.com/egoist/mygo/releases/download/libghostty-vt-befcdfd2c3a1/libghostty-vt-windows-amd64.dll\n" + + "原始错误:" + msg +} + +// restartTerm 重新启动当前会话(其它会话不动)。 +func (a *App) restartTerm() { + s := a.curTerm() + if s == nil { + a.win.Update(func() { a.ensureTerm() }) + return + } + if s.t != nil { + _ = s.t.Close() + } + s.t = nil + s.started = false + s.state = "启动中…" + s.msg = "" + a.win.Update(func() { a.ensureTerm() }) +} + +// resetTerminal 在工作区切换时丢弃全部会话,下次显示时落在新目录。 +func (a *App) resetTerminal() { + for _, s := range a.terms { + if s.t != nil { + _ = s.t.Close() + } + } + a.terms = nil + a.termIdx = 0 +} + +// terminalView 是面板里的「终端」页签。 +func (a *App) terminalView(c *ui.Context) { + t := c.Theme() + a.ensureTerm() + s := a.curTerm() + + ui.Column(c).FillHeight().Children(func() { + ui.Row(c).Padding(2, 8).Gap(6).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + // 会话标签:点名字切换,点 × 关闭。 + // 这里一律用 ButtonBase——面板容器里的 ui.Button 收不到点击。 + for i, sess := range a.terms { + idx := i + active := idx == a.termIdx + bg := ui.Color{} + if active { + bg = t.SurfaceHover + } + tab := ui.ButtonBase(c).Padding(2, 6).Radius(4). + Cursor(ui.CursorPointer).Background(bg) + tab.Children(func() { + fg := t.TextMuted + if active { + fg = t.Text + } + ui.Textf(c, "%d %s", idx+1, sess.label()).FontSize(11).TextColor(fg) + }) + if tab.Clicked() { + a.termIdx = idx + a.refresh() + } + ui.Box(c).Width(2) + } + ui.Box(c).Grow(1) + // 外壳选择只作用于当前会话,切了就地重启它。 + names := make([]string, 0, len(a.shells)) + for _, sh := range a.shells { + names = append(names, sh.Name) + } + if len(names) > 0 { + ui.Segmented(c, &a.shellIdx, names...) + } + if s != nil && a.shellIdx != s.shell { + s.shell = a.shellIdx + a.restartTerm() + } + if s != nil && s.state == "已退出" { + if ui.Button(c, "重启").Clicked() { + a.restartTerm() + } + } + // 新建/关闭放在右上角图标区:这里(iconButton)点击稳定, + // 而行内小按钮的点击区容易互相盖住。 + if iconButton(c, "new", "新建", "新建一个终端(Ctrl+Shift+`)", t.TextMuted) { + a.newTerm() + } + if len(a.terms) > 1 && iconButton(c, "stop", "关闭", "关闭当前终端", t.TextMuted) { + a.closeTerm(a.termIdx) + } + if iconButton(c, "refresh", "重启", "重启当前终端", t.TextMuted) { + a.restartTerm() + } + }) + + if s == nil || s.t == nil { + ui.Column(c).Grow(1).Padding(10, 12).Gap(4).Children(func() { + state := "启动中…" + msg := "" + if s != nil { + state, msg = s.state, s.msg + } + ui.Text(c, state).FontSize(12).TextColor(t.TextMuted) + for _, line := range strings.Split(msg, "\n") { + if line == "" { + continue + } + ui.Text(c, line).FontSize(12).TextColor(t.Danger).SingleLine() + } + }) + return + } + + // 外壳自己退出(用户输入 exit)后更新状态。 + select { + case <-s.t.Done(): + s.state = "已退出" + default: + } + terminal.View(c, s.t).Fill().AutoFocus() + }) +} + +// termShells 返回各会话用的外壳编号,写进会话存档。 +func (a *App) termShells() []int { + if len(a.terms) == 0 { + return nil + } + out := make([]int, 0, len(a.terms)) + for _, s := range a.terms { + out = append(out, s.shell) + } + return out +} + +// refresh 请求重绘;没有窗口时(单元测试)什么也不做。 +func (a *App) refresh() { + if a.win != nil { + a.win.Update(func() {}) + } +} diff --git a/internal/app/terminal_test.go b/internal/app/terminal_test.go new file mode 100644 index 0000000..48945cf --- /dev/null +++ b/internal/app/terminal_test.go @@ -0,0 +1,82 @@ +package app + +import "testing" + +// newTestApp 造一个没有窗口的 App,终端会话操作不依赖 UI。 +func newTestApp(shells ...int) *App { + a := &App{} + for _, sh := range shells { + a.terms = append(a.terms, &termSession{shell: sh, state: "就绪"}) + } + a.termIdx = 0 + return a +} + +func TestTermLabel(t *testing.T) { + cases := map[int]string{0: "PS", 1: "Bash", 2: "CMD", 9: "终端"} + for sh, want := range cases { + if got := (&termSession{shell: sh}).label(); got != want { + t.Fatalf("shell %d 标签应为 %q,实际 %q", sh, want, got) + } + } +} + +func TestCloseTermMiddle(t *testing.T) { + a := newTestApp(0, 1, 2) + a.termIdx = 0 + a.closeTerm(1) // 关中间那个,当前不变 + if len(a.terms) != 2 || a.termIdx != 0 { + t.Fatalf("关中间后应剩 2 个且选中不变: %d %d", len(a.terms), a.termIdx) + } + if a.terms[1].shell != 2 { + t.Fatalf("剩下应是原第 1 和第 3 个: %+v", a.terms) + } +} + +func TestCloseTermBeforeActive(t *testing.T) { + a := newTestApp(0, 1, 2) + a.termIdx = 2 + a.closeTerm(0) // 关掉当前左边的,选中要左移一位 + if a.termIdx != 1 || len(a.terms) != 2 { + t.Fatalf("选中应左移: idx=%d n=%d", a.termIdx, len(a.terms)) + } + if a.terms[a.termIdx].shell != 2 { + t.Fatalf("选中的还应是原来的第 3 个: %+v", a.terms) + } +} + +func TestCloseTermActiveLast(t *testing.T) { + a := newTestApp(0, 1) + a.termIdx = 1 + a.closeTerm(1) // 关掉当前,且它是最后一个 + if len(a.terms) != 1 || a.termIdx != 0 { + t.Fatalf("应回落到第一个: n=%d idx=%d", len(a.terms), a.termIdx) + } +} + +func TestCloseLastRemaining(t *testing.T) { + a := newTestApp(0) + a.closeTerm(0) + if len(a.terms) != 0 || a.termIdx != 0 { + t.Fatalf("关空后应清空且索引归零: n=%d idx=%d", len(a.terms), a.termIdx) + } +} + +func TestCloseTermOutOfRange(t *testing.T) { + a := newTestApp(0) + a.closeTerm(5) // 越界不该 panic + if len(a.terms) != 1 { + t.Fatalf("越界关闭不应改动列表: %d", len(a.terms)) + } +} + +func TestTermShellsForSession(t *testing.T) { + a := newTestApp(0, 1, 2) + got := a.termShells() + if len(got) != 3 || got[0] != 0 || got[1] != 1 || got[2] != 2 { + t.Fatalf("会话存档应记录每个外壳: %v", got) + } + if newTestApp().termShells() != nil { + t.Fatal("没有会话时应返回 nil") + } +} diff --git a/internal/app/testlens.go b/internal/app/testlens.go new file mode 100644 index 0000000..65aee3c --- /dev/null +++ b/internal/app/testlens.go @@ -0,0 +1,171 @@ +package app + +// 测试闭环的「透镜」辅助:失败定位解析、-run 过滤串、测试函数扫描、 +// 输出文件名到磁盘路径的还原。这一层全是纯逻辑(App 方法只碰缓存), +// 单测不拉进程就能覆盖。 + +import ( + "os" + "path/filepath" + "regexp" + "strconv" + "strings" +) + +// failLocRe 匹配测试输出里的「文件.go:行号:」。 +// ` main_test.go:12: boom`、`/x/y/sub_test.go:7:` 和带盘符的 +// `D:\x\y\sub_test.go:7:` 都吃——盘符的冒号在可选的 `[A-Za-z]:` 里消化掉, +// 不然 `[^:\s]` 会在 D 后面被冒号截断。 +var failLocRe = regexp.MustCompile(`^\s*((?:[A-Za-z]:)?[^:\s]+\.go):(\d+):`) + +// testFuncRe 匹配顶格的测试函数声明。只认 Test/Benchmark/Fuzz 开头的大写名, +// `func writeTestFile(t *testing.T)` 这类 helper 不会误中。 +var testFuncRe = regexp.MustCompile(`(?m)^func (Test|Benchmark|Fuzz)(\w+)\(`) + +// failureLoc 从一段测试输出里找第一个失败位置。 +// go test 把 t.Errorf 的位置打在输出行首(缩进后的 file:line:), +// `--- FAIL:` 行本身不带位置,正则自然跳过。 +func failureLoc(lines []string) (string, int) { + for _, l := range lines { + m := failLocRe.FindStringSubmatch(l) + if m == nil { + continue + } + n, err := strconv.Atoi(m[2]) + if err != nil || n <= 0 { + continue + } + return m[1], n + } + return "", 0 +} + +// runFilterFor 把测试全名转成 -run 的锚定正则。 +// 子测试按 / 分段各锚一次:`TestFoo/case 1` → `^TestFoo$/^case 1$`。 +// QuoteMeta 很关键——子测试名常带空格、方括号这类正则元字符。 +func runFilterFor(name string) string { + parts := strings.Split(name, "/") + for i, p := range parts { + parts[i] = "^" + regexp.QuoteMeta(p) + "$" + } + return strings.Join(parts, "/") +} + +// testFuncInfo 是源码里扫到的一个可运行测试。 +type testFuncInfo struct { + Name string + Line int // 0 基 +} + +// scanTestFuncs 找出文本里的 Test/Benchmark/Fuzz 函数和它们的行号。 +// 不走 gopls:确定性正则、零延迟,而且对未保存的缓冲区同样生效—— +// 新写的测试函数没保存也能直接跑。 +func scanTestFuncs(text string) []testFuncInfo { + var out []testFuncInfo + for _, loc := range testFuncRe.FindAllStringSubmatchIndex(text, -1) { + out = append(out, testFuncInfo{ + Name: text[loc[2]:loc[3]] + text[loc[4]:loc[5]], + Line: strings.Count(text[:loc[0]], "\n"), + }) + } + return out +} + +// testFuncAt 返回光标行落在哪个测试函数里;不在任何函数体内时返回 false。 +// 判定方式:找光标上方最近的一个测试函数,若它与光标**之间**出现了顶格的 +// `}`,说明函数体已经结束——收尾 `}` 那一行本身仍算在函数里(跟主流 IDE +// 的「运行光标处测试」一致),函数之间的空行不算。 +func testFuncAt(text string, line int) (string, bool) { + var best *testFuncInfo + funcs := scanTestFuncs(text) + for i := range funcs { + if funcs[i].Line <= line { + best = &funcs[i] + } else { + break + } + } + if best == nil { + return "", false + } + for l := best.Line + 1; l < line; l++ { + if strings.HasPrefix(lineAt(text, l), "}") { + return "", false + } + } + return best.Name, true +} + +// lineAt 取第 n 行(0 基)的内容,越界返回空串。 +func lineAt(text string, n int) string { + if n < 0 { + return "" + } + for i := 0; i < n; i++ { + if j := strings.IndexByte(text, '\n'); j >= 0 { + text = text[j+1:] + } else { + return "" + } + } + if j := strings.IndexByte(text, '\n'); j >= 0 { + text = text[:j] + } + return strings.TrimRight(text, "\r") +} + +// modulePrefix 读工作区 go.mod 的 module 名(按 root 缓存),读不到返回空。 +func (a *App) modulePrefix() string { + if a.root == "" { + return "" + } + if a.modRoot == a.root && a.modName != "" { + return a.modName + } + data, err := os.ReadFile(filepath.Join(a.root, "go.mod")) + if err != nil { + return "" + } + for _, l := range strings.Split(string(data), "\n") { + l = strings.TrimSpace(l) + if strings.HasPrefix(l, "module ") { + a.modRoot = a.root + a.modName = strings.TrimSpace(strings.TrimPrefix(l, "module ")) + return a.modName + } + } + return "" +} + +// resolveTestFile 把失败输出里的文件名还原成磁盘路径。 +// go test 的输出通常只给包内相对名(main_test.go:12),要拼上包目录; +// 包目录按「module 前缀 + import 路径」从工作区根还原。拼出来的路径不存在时, +// 退一步在工作区文件索引里找同名文件(对付特殊布局),再不行就把猜的路径 +// 原样返回——openAt 打不开会自己报错,不在这里吞。 +func (a *App) resolveTestFile(pkg, file string) string { + if filepath.IsAbs(file) { + return file + } + rel := pkg + if mod := a.modulePrefix(); mod != "" { + switch { + case pkg == mod: + rel = "" + case strings.HasPrefix(pkg, mod+"/"): + rel = strings.TrimPrefix(pkg, mod+"/") + } + } + p := filepath.Join(a.root, filepath.FromSlash(rel), filepath.FromSlash(file)) + if _, err := os.Stat(p); err == nil { + return p + } + if paths, ok := a.indexSnapshot(); ok { + base := filepath.Base(file) + for _, cand := range paths { + if filepath.Base(cand) == base { + return cand + } + } + } + return p +} diff --git a/internal/app/testlens_test.go b/internal/app/testlens_test.go new file mode 100644 index 0000000..add49cf --- /dev/null +++ b/internal/app/testlens_test.go @@ -0,0 +1,123 @@ +package app + +import ( + "os" + "path/filepath" + "reflect" + "testing" +) + +func TestFailureLocPicksTestFile(t *testing.T) { + lines := []string{ + "=== RUN TestFoo", + " main_test.go:12: boom", + "--- FAIL: TestFoo (0.00s)", + "FAIL", + } + file, line := failureLoc(lines) + if file != "main_test.go" || line != 12 { + t.Fatalf("应解析出 main_test.go:12,实际 %s:%d", file, line) + } +} + +func TestFailureLocAbsolutePath(t *testing.T) { + file, line := failureLoc([]string{` D:\x\y\sub_test.go:7: nope`}) + if file != `D:\x\y\sub_test.go` || line != 7 { + t.Fatalf("绝对路径应原样保留,实际 %s:%d", file, line) + } +} + +func TestFailureLocNone(t *testing.T) { + if f, l := failureLoc([]string{"--- FAIL: TestX (0.1s)", "panic: boom"}); f != "" || l != 0 { + t.Fatalf("没有 file:line 时应为空,实际 %s:%d", f, l) + } +} + +func TestRunFilterFor(t *testing.T) { + cases := map[string]string{ + "TestFoo": "^TestFoo$", + "TestFoo/case 1": "^TestFoo$/^case 1$", + "TestFoo/a[b]/sub": "^TestFoo$/^a\\[b\\]$/^sub$", + } + for name, want := range cases { + if got := runFilterFor(name); got != want { + t.Errorf("runFilterFor(%q) = %q,期望 %q", name, got, want) + } + } +} + +func TestScanTestFuncs(t *testing.T) { + src := `package app + +func helper(t *testing.T) {} + +func TestFoo(t *testing.T) { +} + +func BenchmarkX(b *testing.B) { +} + +func TestBar(t *testing.T) { +} +` + got := scanTestFuncs(src) + want := []testFuncInfo{ + {Name: "TestFoo", Line: 4}, + {Name: "BenchmarkX", Line: 7}, + {Name: "TestBar", Line: 10}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("扫描结果不符,got %+v want %+v", got, want) + } +} + +func TestTestFuncAt(t *testing.T) { + src := "package app\n\nfunc TestFoo(t *testing.T) {\n\tx()\n}\n\nfunc TestBar(t *testing.T) {\n}\n" + cases := []struct { + line int + name string + found bool + }{ + {0, "", false}, // package 行 + {1, "", false}, // 第一个函数之前 + {2, "TestFoo", true}, // 声明行本身 + {3, "TestFoo", true}, // 函数体内 + {4, "TestFoo", true}, // 收尾 } 上仍算在函数里 + {5, "", false}, // 函数之间的空行 + {6, "TestBar", true}, + } + for _, c := range cases { + name, ok := testFuncAt(src, c.line) + if ok != c.found || name != c.name { + t.Errorf("testFuncAt(line=%d) = (%q,%v),期望 (%q,%v)", c.line, name, ok, c.name, c.found) + } + } +} + +func TestResolveTestFile(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil { + t.Fatal(err) + } + dir := filepath.Join(root, "internal", "app") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "foo_test.go"), []byte("package app\n"), 0o644); err != nil { + t.Fatal(err) + } + + a := &App{root: root} + got := a.resolveTestFile("demo/internal/app", "foo_test.go") + if want := filepath.Join(dir, "foo_test.go"); got != want { + t.Fatalf("应按 module 前缀还原,got %q want %q", got, want) + } + + // 绝对路径直接透传。 + if got := a.resolveTestFile("demo", root); got != root { + t.Fatalf("绝对路径应透传,got %q", got) + } + + // 包路径不在 module 里且文件不存在:不 panic,返回一个猜测路径。 + _ = a.resolveTestFile("other/pkg", "zzz_test.go") +} diff --git a/internal/app/testrun.go b/internal/app/testrun.go new file mode 100644 index 0000000..c3e4ee1 --- /dev/null +++ b/internal/app/testrun.go @@ -0,0 +1,394 @@ +package app + +import ( + "encoding/json" + "fmt" + "path/filepath" + "strconv" + "strings" + + "github.com/egoist/mygo/ui" + + "mygoland/internal/lsp" + "mygoland/internal/task" +) + +// 测试结果树:跑 `go test -json`,把事件流解析成「包 → 测试 → 子测试」的层级。 +// +// 为什么用 -json 而不是解析文本:文本输出没有结构,失败和通过的界限只能靠 +// 前缀猜;-json 每条事件都带 package/test/action,子测试还能靠名字里的斜杠还原层级。 + +// testStatus 是一条测试的状态。 +type testStatus int + +const ( + testNone testStatus = iota + testRunning + testPass + testFail + testSkip +) + +func (s testStatus) mark() string { + switch s { + case testRunning: + return "⟳" + case testPass: + return "✓" + case testFail: + return "✗" + case testSkip: + return "○" + } + return "·" +} + +// testNode 是树里的一个节点。 +type testNode struct { + Pkg string + Name string // 完整名,子测试形如 TestFoo/case1 + Depth int // 缩进层级,0 是包 + Status testStatus + Elapsed float64 + Output []string + // File/Line 是失败输出的第一个 file:line(已还原成磁盘路径),失败时才有。 + File string + Line int +} + +// testState 是测试面板的状态。 +type testState struct { + running bool + task *task.Task + nodes []*testNode + seen map[string]*testNode + sel int + pattern string +} + +// key 是节点在 map 里的标识。 +func testKey(pkg, name string) string { return pkg + "\x00" + name } + +// RunTestTree 跑测试并填结果树;pattern 为空表示整个工作区。 +func (a *App) RunTestTree(pattern string) { + if a.root == "" { + a.alert("运行测试", "先打开一个工作区。") + return + } + if pattern == "" { + pattern = "./..." + } + a.startTest("test", "-json", pattern) +} + +// runOneTest 用 -run 只跑一个用例(含子测试路径)。 +// pkg 可以是 import 路径,也可以是 ./相对目录,go test 都认。 +func (a *App) runOneTest(pkg, name string) { + if a.root == "" { + a.alert("运行测试", "先打开一个工作区。") + return + } + a.startTest("test", "-json", "-run", runFilterFor(name), pkg) +} + +// startTest 拉起一次 go test 并把结果树清空重填;args 是 go 的完整参数。 +func (a *App) startTest(args ...string) { + if a.test.running { + a.StopTask() + } + t, err := task.Start(a.root, "go", args...) + if err != nil { + a.alert("运行测试", err.Error()) + return + } + a.test = testState{ + running: true, + task: t, + seen: map[string]*testNode{}, + pattern: strings.Join(args, " "), + } + a.panel = true + a.panelTab = 5 + if a.panelH < 260 { + a.panelH = 300 + } + a.refresh() + + go func() { + for line := range t.Lines { + a.testEvent(line) + } + t.Wait() + a.win.Update(func() { + a.test.running = false + a.test.task = nil + }) + }() +} + +// runTestAtCursor 跑光标所在的那个测试函数。 +// 函数扫描走本地正则(scanTestFuncs),没保存的新函数也能跑。 +func (a *App) runTestAtCursor() { + d := a.doc() + if d == nil || a.root == "" { + a.RunTestTree("") + return + } + name, ok := testFuncAt(d.buf.String(), d.st.CursorPos().Line) + if !ok { + a.appendOut("光标不在测试函数里,改为运行全部测试。") + a.RunTestTree("") + return + } + a.runOneTest(packagePattern(a.root, d.path), name) +} + +// testEvent 处理一行 -json 事件。 +// +// 这里的调用来自读取协程,所以要自己进 UI 线程。 +func (a *App) testEvent(line string) { + line = strings.TrimSpace(line) + if line == "" || !strings.HasPrefix(line, "{") { + return + } + var ev struct { + Action string `json:"Action"` + Package string `json:"Package"` + Test string `json:"Test"` + Elapsed float64 `json:"Elapsed"` + Output string `json:"Output"` + } + if err := json.Unmarshal([]byte(line), &ev); err != nil { + return + } + a.win.Update(func() { a.applyTestEvent(ev.Action, ev.Package, ev.Test, ev.Elapsed, ev.Output) }) +} + +// applyTestEvent 把事件落到树上。 +func (a *App) applyTestEvent(action, pkg, test string, elapsed float64, output string) { + if a.test.seen == nil { + a.test.seen = map[string]*testNode{} + } + + // 包级事件:没有 Test 字段,用包名当一个根节点。 + name := test + if name == "" && pkg != "" && action != "output" { + name = "" + } + if pkg == "" { + return + } + + n, ok := a.test.seen[testKey(pkg, name)] + if !ok { + // 包节点在第一次出现时创建,位置固定在列表前面。 + if name != "" { + if _, hasPkg := a.test.seen[testKey(pkg, "")]; !hasPkg { + a.addTestNode(&testNode{Pkg: pkg, Name: "", Depth: 0, Status: testNone}) + } + } + depth := 0 + if name != "" { + depth = 1 + strings.Count(name, "/") + } + n = &testNode{Pkg: pkg, Name: name, Depth: depth} + a.addTestNode(n) + } + + switch action { + case "run": + n.Status = testRunning + case "pass": + n.Status = testPass + n.Elapsed = elapsed + case "fail": + n.Status = testFail + n.Elapsed = elapsed + // 从自己的输出里找失败位置并当场还原成磁盘路径: + // applyTestEvent 在主线程跑,resolveTestFile 里的 os.Stat / 索引 + // 扫描在这里做是安全的,且每个失败节点只做一次。 + if file, line := failureLoc(n.Output); file != "" { + n.File = a.resolveTestFile(pkg, file) + n.Line = line + } + case "skip": + n.Status = testSkip + n.Elapsed = elapsed + case "output": + if output != "" { + n.Output = append(n.Output, strings.TrimRight(output, "\n")) + } + } +} + +// addTestNode 追加一个节点并登记。 +func (a *App) addTestNode(n *testNode) { + a.test.nodes = append(a.test.nodes, n) + a.test.seen[testKey(n.Pkg, n.Name)] = n +} + +// testCounts 统计通过/失败数量,给页签做角标。 +func (a *App) testCounts() (pass, fail, skip int) { + for _, n := range a.test.nodes { + if n.Name == "" { + continue + } + switch n.Status { + case testPass: + pass++ + case testFail: + fail++ + case testSkip: + skip++ + } + } + return +} + +// runCurrentPackageTests 只跑当前文件所在的包。 +func (a *App) runCurrentPackageTests() { + d := a.doc() + if d == nil || a.root == "" { + a.RunTestTree("") + return + } + a.RunTestTree(packagePattern(a.root, d.path)) +} + +// packagePattern 把文件路径换算成 go test 的包模式(./相对路径)。 +func packagePattern(root, path string) string { + dir := path + if i := strings.LastIndexAny(dir, `/\`); i > 0 { + dir = dir[:i] + } + rel := dir + if strings.HasPrefix(strings.ToLower(dir), strings.ToLower(root)) { + rel = dir[len(root):] + } + rel = strings.ReplaceAll(rel, `\`, "/") + rel = strings.TrimPrefix(rel, "/") + if rel == "" { + return "." + } + return "./" + rel +} + +// testView 是面板里的「测试」页签。 +func (a *App) testView(c *ui.Context) { + t := c.Theme() + pass, fail, skip := a.testCounts() + + ui.Column(c).FillHeight().Children(func() { + ui.Row(c).Padding(3, 10).Gap(8).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + ui.Textf(c, "%s", a.test.pattern).FontSize(11).TextColor(t.TextMuted).SingleLine() + ui.Box(c).Grow(1) + if pass+fail+skip > 0 { + ui.Textf(c, "✓ %d ✗ %d ○ %d", pass, fail, skip).FontSize(11).TextColor(t.TextMuted) + } + if a.test.running { + ui.Text(c, "运行中…").FontSize(11).TextColor(t.Accent) + } + if ui.Button(c, "全部测试").Clicked() { + a.RunTestTree("") + } + if ui.Button(c, "当前包").Clicked() { + a.runCurrentPackageTests() + } + }) + + if len(a.test.nodes) == 0 { + ui.Column(c).Grow(1).FillHeight().Center().Children(func() { + ui.Text(c, "还没有运行测试").FontSize(12).TextColor(t.TextMuted) + }) + return + } + + // 树占满剩余高度;选中项的输出直接内联在它下面, + // 不另开输出区——两个区域争高度会把其中一个挤没。 + ui.Scroll(c).Grow(1).Children(func() { + ui.Column(c).Gap(1).Children(func() { + for i, n := range a.test.nodes { + idx := i + row := ui.ButtonBase(c).FillWidth().Height(22).Padding(0, 6).Radius(3). + Cursor(ui.CursorPointer) + if idx == a.test.sel { + row = row.Background(t.SurfaceHover) + } + row.Children(func() { + ui.Row(c).FillWidth().Gap(6).AlignItems(ui.Center).Children(func() { + ui.Box(c).Width(float32(n.Depth) * 12) + ui.Text(c, n.Status.mark()).FontSize(11). + TextColor(testColor(t, n.Status)).Width(14) + label := n.Name + if label == "" { + label = strings.TrimPrefix(n.Pkg, "mygoland/") + "(整个包)" + } + ui.Text(c, label).FontSize(11).TextColor(t.Text).SingleLine() + if n.Elapsed > 0 { + ui.Textf(c, "%.2fs", n.Elapsed).FontSize(10).TextColor(t.TextMuted) + } + }) + }) + if row.Clicked() { + a.test.sel = idx + a.refresh() + } + + // 选中项:先给操作行(重跑 / 失败跳源码),再把输出末尾内联出来。 + if idx == a.test.sel { + pad := 6 + float32(n.Depth)*12 + 22 + ui.Row(c).Padding(2, pad).Gap(6).Children(func() { + if n.Name != "" { + if ui.Button(c, "重跑这个用例").Clicked() { + a.runOneTest(n.Pkg, n.Name) + } + } + if n.Status == testFail && n.File != "" { + label := filepath.Base(n.File) + ":" + strconv.Itoa(n.Line) + if ui.Button(c, "跳到 "+label).Clicked() { + a.openAt(n.File, lsp.Position{Line: n.Line - 1}) + } + } + }) + lines := n.Output + if len(lines) > 6 { + lines = lines[len(lines)-6:] + } + for _, line := range lines { + if strings.TrimSpace(line) == "" { + continue + } + ui.Text(c, line).FontSize(10).TextColor(t.TextMuted). + Padding(0, pad).SingleLine() + } + } + } + }) + }) + }) +} + +// testColor 按状态给颜色。 +func testColor(t *ui.Theme, s testStatus) ui.Color { + switch s { + case testPass: + return t.Success + case testFail: + return t.Danger + case testSkip: + return t.Warning + case testRunning: + return t.Accent + } + return t.TextMuted +} + +// testTabLabel 是页签上的文字,带失败数。 +func (a *App) testTabLabel() string { + _, fail, _ := a.testCounts() + if fail > 0 { + return fmt.Sprintf("测试 %d✗", fail) + } + return "测试" +} diff --git a/internal/app/testrun_test.go b/internal/app/testrun_test.go new file mode 100644 index 0000000..0273573 --- /dev/null +++ b/internal/app/testrun_test.go @@ -0,0 +1,159 @@ +package app + +import ( + "os" + "path/filepath" + "testing" +) + +// ev 是 testEvent 的简写,只用于测试里造事件。 +func ev(a *App, action, pkg, test string, elapsed float64, output string) { + a.applyTestEvent(action, pkg, test, elapsed, output) +} + +// TestTestTreeBasic 一个包里的一个用例从 run 到 pass。 +func TestTestTreeBasic(t *testing.T) { + a := &App{} + ev(a, "run", "demo", "TestAdd", 0, "") + ev(a, "pass", "demo", "TestAdd", 0.02, "") + + if len(a.test.nodes) != 2 { + t.Fatalf("应有包节点 + 用例节点共 2 个,实际 %d", len(a.test.nodes)) + } + pkg := a.test.nodes[0] + if pkg.Name != "" || pkg.Depth != 0 { + t.Fatalf("第一个应是包节点: %+v", pkg) + } + n := a.test.nodes[1] + if n.Name != "TestAdd" || n.Status != testPass || n.Elapsed != 0.02 { + t.Fatalf("用例节点不对: %+v", n) + } +} + +// TestTestTreeSubtest 子测试靠名字里的斜杠还原层级。 +func TestTestTreeSubtest(t *testing.T) { + a := &App{} + ev(a, "run", "demo", "TestAdd/a", 0, "") + ev(a, "pass", "demo", "TestAdd/a", 0.01, "") + ev(a, "run", "demo", "TestAdd/b/c", 0, "") + ev(a, "fail", "demo", "TestAdd/b/c", 0.03, "") + + byName := map[string]*testNode{} + for _, n := range a.test.nodes { + byName[n.Name] = n + } + if byName["TestAdd/a"].Depth != 2 { + t.Fatalf("一级子测试缩进应为 2,实际 %d", byName["TestAdd/a"].Depth) + } + if byName["TestAdd/b/c"].Depth != 3 { + t.Fatalf("二级子测试缩进应为 3,实际 %d", byName["TestAdd/b/c"].Depth) + } + if byName["TestAdd/b/c"].Status != testFail { + t.Fatalf("失败状态没记上: %+v", byName["TestAdd/b/c"]) + } +} + +// TestTestTreeOutput 输出挂在对应节点上,包级输出挂在包节点上。 +func TestTestTreeOutput(t *testing.T) { + a := &App{} + ev(a, "run", "demo", "TestFoo", 0, "") + ev(a, "output", "demo", "TestFoo", 0, "=== RUN TestFoo\n") + ev(a, "output", "demo", "TestFoo", 0, " foo_test.go:12: 期望 1 得到 2\n") + ev(a, "fail", "demo", "TestFoo", 0.05, "") + ev(a, "output", "demo", "", 0, "FAIL\tdemo\t0.05s\n") + + byName := map[string]*testNode{} + for _, n := range a.test.nodes { + byName[n.Name] = n + } + if got := byName["TestFoo"].Output; len(got) != 2 { + t.Fatalf("用例输出应有 2 行,实际 %d: %v", len(got), got) + } + if got := byName[""].Output; len(got) != 1 { + t.Fatalf("包输出应有 1 行,实际 %d", len(got)) + } +} + +// TestTestCounts 统计只算真正的用例,不把包节点算进去。 +func TestTestCounts(t *testing.T) { + a := &App{} + ev(a, "pass", "demo", "TestA", 0, "") + ev(a, "fail", "demo", "TestB", 0, "") + ev(a, "skip", "demo", "TestC", 0, "") + + pass, fail, skip := a.testCounts() + if pass != 1 || fail != 1 || skip != 1 { + t.Fatalf("统计不对: %d/%d/%d", pass, fail, skip) + } + if label := a.testTabLabel(); label != "测试 1✗" { + t.Fatalf("有失败时页签要带角标,实际 %q", label) + } +} + +// TestTestTreeFailLocation 失败输出里的 file:line 要还原成磁盘路径挂到节点上—— +// 这是「点失败用例跳源码」的数据来源,整条链一起测。 +func TestTestTreeFailLocation(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil { + t.Fatal(err) + } + dir := filepath.Join(root, "internal", "app") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "app_test.go"), []byte("package app\n"), 0o644); err != nil { + t.Fatal(err) + } + + a := &App{root: root} + ev(a, "run", "demo/internal/app", "TestAdd", 0, "") + ev(a, "output", "demo/internal/app", "TestAdd", 0, "=== RUN TestAdd\n") + ev(a, "output", "demo/internal/app", "TestAdd", 0, " app_test.go:9: 期望 1 得到 2\n") + ev(a, "fail", "demo/internal/app", "TestAdd", 0.01, "") + + var n *testNode + for _, x := range a.test.nodes { + if x.Name == "TestAdd" { + n = x + } + } + if n == nil || n.File == "" { + t.Fatalf("失败节点应带定位: %+v", n) + } + if want := filepath.Join(dir, "app_test.go"); n.File != want || n.Line != 9 { + t.Fatalf("定位不对: %s:%d,期望 %s:9", n.File, n.Line, want) + } +} + +// TestRunFilterForAnchor 与 go test -run 的语义对齐:整段锚定、子测试分段。 +func TestRunFilterForAnchor(t *testing.T) { + if got := runFilterFor("TestAdd/b/c"); got != "^TestAdd$/^b$/^c$" { + t.Fatalf("子测试过滤串不对: %q", got) + } +} + +// TestPackagePattern 文件路径换算成 go test 的包模式。 +func TestPackagePattern(t *testing.T) { + cases := []struct{ root, path, want string }{ + {`D:\proj`, `D:\proj\internal\app\x.go`, "./internal/app"}, + {`D:\proj`, `D:\proj\main.go`, "."}, + {`D:\proj`, `D:\proj\a\b\c.go`, "./a/b"}, + } + for _, c := range cases { + if got := packagePattern(c.root, c.path); got != c.want { + t.Fatalf("%s → 期望 %s 实际 %s", c.path, c.want, got) + } + } +} + +// TestTestStatusMark 状态符号。 +func TestTestStatusMark(t *testing.T) { + cases := map[testStatus]string{ + testPass: "✓", testFail: "✗", testSkip: "○", testRunning: "⟳", testNone: "·", + } + for st, want := range cases { + if got := st.mark(); got != want { + t.Fatalf("%v 的符号应为 %q 实际 %q", st, want, got) + } + } +} diff --git a/internal/app/theme.go b/internal/app/theme.go new file mode 100644 index 0000000..ad67e32 --- /dev/null +++ b/internal/app/theme.go @@ -0,0 +1,124 @@ +package app + +import "github.com/egoist/mygo/ui" + +// 界面配色分深色与浅色两套,骨架都按 Islands 的做法: +// 窗口底色负责「沟」,面板是浮在上面的圆角岛屿。 +// +// 深色 = Islands Dark + One Dark Vivid:Vivid 把标准 One Dark 的五个核心色 +// 整体提亮(红 #E06C75→#EF596F、青 #56B6C2→#2BBAC5、绿 #98C379→#89CA78、 +// 紫 #C678DD→#D55FDE、前景 #ABB2BF→#BBBBBB)。 +// +// 浅色 = Islands Light + One Light:One Light 是 One Dark 的官方同源浅色, +// 语义一一对应(关键字紫、字符串绿、数字橙、函数蓝),不是另外凑的一套。 +// 唯一不照搬的是强调色:One Dark 的 #61AFEF 在白底上对比度只有 2.4:1, +// 拿来做按钮和焦点环看不清,浅色改用 GitHub 的链接蓝 #0969DA(约 5.2:1)。 + +// titleBarHeight 是自绘标题栏的高度,单位 DIP。 +// 必须与 windows 后端的 captionHeight(32) 一致:后端按它画窗口按钮, +// 页面按它排版,两者不一致就会出现按钮与内容错位。 +// captionButtonsW 是右上角三颗窗口按钮的宽度(3×46),标题栏右侧要留出来。 +const ( + titleBarHeight = 32 + captionButtonsW = 138 +) + +// palette 是一套界面配色的角色表。 +type palette struct { + bgDeep string // 窗口底、岛屿之间的沟、状态栏 + island string // 岛屿本体,同时也是编辑器背景 + hover string + pressed string + border string + text string + muted string + accent string + accentHover string + accentPress string + accentOn string // 强调色上的文字 + danger string + warning string + success string + scroll string +} + +var darkPalette = palette{ + bgDeep: "#1B1E24", + island: "#282C34", + hover: "#2F343D", + pressed: "#3A4049", + border: "#3A4049", + text: "#BBBBBB", + muted: "#7F848E", + accent: "#61AFEF", + accentHover: "#7ABCFF", + accentPress: "#4E9BD8", + accentOn: "#15181D", + danger: "#EF596F", + warning: "#E5C07B", + success: "#89CA78", + scroll: "#4B5263", +} + +var lightPalette = palette{ + bgDeep: "#E7EAEE", + island: "#FFFFFF", + hover: "#F3F5F8", + pressed: "#E9EDF1", + border: "#DCE1E7", + text: "#24292F", + muted: "#656D76", + accent: "#0969DA", + accentHover: "#0860CA", + accentPress: "#0550AE", + accentOn: "#FFFFFF", + danger: "#CF222E", + warning: "#9A6700", + success: "#1A7F37", + scroll: "#C9D1D9", +} + +// theme 返回给定明暗下的界面配色。 +func theme(light bool) *ui.Theme { + t := ui.DarkTheme() + p := darkPalette + if light { + t = ui.LightTheme() + p = lightPalette + } + + t.Background = ui.Hex(p.bgDeep) + t.Surface = ui.Hex(p.island) + t.SurfaceHover = ui.Hex(p.hover) + t.SurfacePressed = ui.Hex(p.pressed) + t.Border = ui.Hex(p.border) + t.Text = ui.Hex(p.text) + t.TextMuted = ui.Hex(p.muted) + t.Accent = ui.Hex(p.accent) + t.AccentHover = ui.Hex(p.accentHover) + t.AccentPressed = ui.Hex(p.accentPress) + t.AccentText = ui.Hex(p.accentOn) + t.Danger = ui.Hex(p.danger) + t.Warning = ui.Hex(p.warning) + t.Success = ui.Hex(p.success) + t.Focus = ui.Hex(p.accent) + t.Scrollbar = ui.Hex(p.scroll) + + if light { + t.Selection = ui.RGBA(9, 105, 218, 0.16) + t.Inverse = ui.Hex("#24292F") + t.InverseText = ui.Hex("#FFFFFF") + } else { + t.Selection = ui.RGBA(97, 175, 239, 0.26) + t.Inverse = ui.Hex("#E6E6E6") + t.InverseText = ui.Hex(p.bgDeep) + } + + t.ScrollbarWidth = 8 + // Islands 的圆角比传统主题大得多。8 是观感与密度的平衡点: + // 再大(12)会让 32px 高的标题栏和状态栏显得虚浮。 + t.Radius = 8 + t.Spacing = 4 + t.FontSize = 13 + return t +} diff --git a/internal/app/titlebar.go b/internal/app/titlebar.go new file mode 100644 index 0000000..fa5c7cf --- /dev/null +++ b/internal/app/titlebar.go @@ -0,0 +1,145 @@ +package app + +import ( + "path/filepath" + + "github.com/egoist/mygo" + "github.com/egoist/mygo/ui" +) + +// menuHit 是一个菜单项按钮在这一帧的位置。 +type menuHit struct { + item *mygo.MenuItem + btn ui.Element +} + +// titleBar 画窗口顶部那条与主题同色的标题栏。 +// +// 窗口用 mygo.TitleBarHidden 起,系统标题栏不再绘制,整个顶部交给页面。 +// DragWindow 是关键:它让这条空白区成为原生标题栏的等价物——按下时框架 +// 向系统发 WM_NCLBUTTONDOWN + HTCAPTION,于是拖动、拖到屏幕边缘分屏 +// (Aero Snap)、双击最大化全部由系统完成,不是框架模拟移动窗口。 +// 右上角 float(captionButtonsW) 的空白是给后端的窗口按钮让位, +// 那些按钮带着 HTMAXBUTTON 命中码,所以 Win11 的贴靠布局也还在。 +// +// 标题栏有两种形态:平时是「汉堡 + 标识 + 文件名」,点汉堡后整条变成菜单。 +// 收起只看「在菜单以外按下」——不能用鼠标移开来收:那样鼠标从「文件」滑向 +// 「编辑」的途中就会收起,后面的菜单根本点不到。 +func (a *App) titleBar(c *ui.Context) { + t := c.Theme() + + // burger 是「点在菜单外」的判定锚点:菜单项画在它右边, + // 所以点菜单项算「在汉堡之外」,才会走到下面的命中判断。 + var burger ui.Element + + bar := ui.Row(c).Height(float32(titleBarHeight)).MinHeight(float32(titleBarHeight)). + FillWidth().DragWindow(). + Background(t.Background). + Padding(0, 8).Gap(4).AlignItems(ui.Center) + bar.Children(func() { + // 标识放在最左,占位宽度与下方竖条一致并水平居中, + // 看上去就是竖条顶端的头;汉堡菜单紧随其后。 + if logo != nil { + ui.Row(c).Width(railWidth).Justify(ui.Center).AlignItems(ui.Center).Children(func() { + ui.Image(c, logo).Size(26, 26) + }) + } else { + ui.Box(c).Width(railWidth) + } + + burger = a.hamburger(c) + + if a.menuOpen { + a.menuBar(c) + ui.Box(c).Grow(1) + ui.Box(c).Width(float32(captionButtonsW)) + return + } + + ui.Box(c).Width(2) + // 汉堡右侧显示项目名(工作区目录名);没有工作区时退回应用名。 + name := "MyGoland" + if a.root != "" { + name = filepath.Base(a.root) + } + ui.Text(c, name).FontSize(12).TextColor(t.TextMuted).SingleLine() + + ui.Box(c).Grow(1) + ui.Box(c).Width(float32(captionButtonsW)) + }) + + if !a.menuOpen { + return + } + // 下拉开着时不判:那期间用户点的是子菜单。 + if a.menuPopup { + return + } + if !burger.PressedOutside() { + return + } + // 点击落在菜单以外了。先看是不是点中了某一项——命中就展开它的下拉, + // 否则收起回汉堡形态。 + if it, btn, ok := a.menuHitAt(); ok { + a.openPop(btn, entriesFromMenu(it.Submenu)) + return + } + a.menuOpen = false + a.win.Update(func() {}) +} + +// hamburger 是主菜单开关。展开时图标转成强调色,再点一下也能收起。 +func (a *App) hamburger(c *ui.Context) ui.Element { + t := c.Theme() + // 不加 Tooltip:气泡会浮在汉堡下方,正好压住侧栏的「项目」标题行。 + btn := ui.ButtonBase(c).Size(26, 26).Radius(6).Padding(0). + Cursor(ui.CursorPointer) + + fg := t.Text + if a.menuOpen { + fg = t.Accent + } + btn.Draw(func(p *ui.Painter, r ui.Rect) { + // 用三条横线画图标:字体里不一定有 ☰ 字形。 + cx := r.X + r.W/2 + for i := -1; i <= 1; i++ { + y := r.Y + r.H/2 + float32(i)*4.5 + p.Fill(ui.Rect{X: cx - 6, Y: y - 0.75, W: 12, H: 1.5}, fg, 1) + } + }) + if btn.Clicked() { + a.menuOpen = !a.menuOpen + a.win.Update(func() {}) + } + return btn +} + +// menuBar 画平铺的菜单条,并记下每一项的位置供点击判断。 +// +// 这里刻意不判断点击:标题栏整体是 DragWindow,按钮的 Clicked 收不到事件 +// (实测指针 over=true 而 clicks=0),点中哪一项改由 titleBar 末尾统一判断。 +func (a *App) menuBar(c *ui.Context) { + t := c.Theme() + a.menuHits = a.menuHits[:0] + for _, item := range a.menuItems() { + item := item + btn := ui.ButtonBase(c).Padding(1, 9).Radius(5). + Cursor(ui.CursorPointer) + btn.Children(func() { + ui.Text(c, item.Label).FontSize(12).TextColor(t.Text) + }) + a.menuHits = append(a.menuHits, menuHit{item: item, btn: btn}) + } +} + +// menuHitAt 返回指针当前落在哪个菜单项上,以及那个按钮(用作弹出面板的锚点)。 +func (a *App) menuHitAt() (*mygo.MenuItem, ui.Element, bool) { + for _, h := range a.menuHits { + if _, _, over := h.btn.PointerPosition(); over { + return h.item, h.btn, true + } + } + return nil, ui.Element{}, false +} + +// titleText 返回标题栏里显示的文字:当前文件与工作区。 diff --git a/internal/app/tree_test.go b/internal/app/tree_test.go new file mode 100644 index 0000000..228891b --- /dev/null +++ b/internal/app/tree_test.go @@ -0,0 +1,61 @@ +package app + +import ( + "io/fs" + "os" + "path/filepath" + "testing" +) + +func TestExpandAll(t *testing.T) { + root := t.TempDir() + deep := filepath.Join(root, "a", "b") + if err := os.MkdirAll(deep, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(deep, "x.go"), []byte("package x\n"), 0o644); err != nil { + t.Fatal(err) + } + a := &App{root: root, open: map[string]*bool{}, dirs: map[string][]fs.DirEntry{}} + + a.ExpandAll() + + for _, dir := range []string{ + filepath.Join(root, "a"), + filepath.Join(deep), + } { + if !*a.openFlag(dir) { + t.Fatalf("%s 没有被展开", dir) + } + } + + a.CollapseAll() + for _, dir := range []string{ + filepath.Join(root, "a"), + filepath.Join(deep), + } { + if *a.openFlag(dir) { + t.Fatalf("%s 没有被折叠", dir) + } + } +} + +func TestAddEntriesTargetDir(t *testing.T) { + root := t.TempDir() + f := filepath.Join(root, "main.go") + if err := os.WriteFile(f, []byte("package main\n"), 0o644); err != nil { + t.Fatal(err) + } + a := &App{root: root, open: map[string]*bool{}, dirs: map[string][]fs.DirEntry{}, sel: map[string]bool{}} + + // 没有选中项时落在工作区根。 + if got := len(a.addEntries()); got != 2 { + t.Fatalf("应当有两个菜单项,实际 %d", got) + } + + // 选中一个文件时,应当落到它所在的目录(这里是根)。 + a.sel[f] = true + if got := len(a.addEntries()); got != 2 { + t.Fatalf("应当有两个菜单项,实际 %d", got) + } +} diff --git a/internal/app/unsaved.go b/internal/app/unsaved.go new file mode 100644 index 0000000..6b44a44 --- /dev/null +++ b/internal/app/unsaved.go @@ -0,0 +1,147 @@ +package app + +import ( + "fmt" + + "github.com/egoist/mygo" +) + +// 未保存对话框的三个选项。 +const ( + choiceSave = iota + choiceDiscard + choiceCancel +) + +// dirtyDocs 返回有未保存改动的文件,须在主线程调用。 +func (a *App) dirtyDocs() []*Doc { + var out []*Doc + for _, d := range a.docs { + if d.buf.Modified() { + out = append(out, d) + } + } + return out +} + +// askUnsaved 询问如何处理未保存的文件,只在 goroutine 中调用。 +func (a *App) askUnsaved(n int, detail string) int { + res, err := mygo.Dialog.Message(mygo.MessageOptions{ + Parent: a.win, + Type: mygo.MessageWarning, + Title: "未保存的更改", + Message: fmt.Sprintf("有 %d 个文件尚未保存。", n), + Detail: detail, + Buttons: []string{"保存全部", "不保存", "取消"}, + DefaultButton: 0, + CancelButton: 2, + }) + if err != nil { + return choiceCancel + } + switch res.Button { + case 0: + return choiceSave + case 1: + return choiceDiscard + } + return choiceCancel +} + +// saveDocs 写回一组文件,全部成功才返回 true。 +func (a *App) saveDocs(docs []*Doc) bool { + for _, d := range docs { + if !d.buf.Modified() { + continue + } + if err := writeDocFile(d); err != nil { + a.alert("保存失败", fmt.Sprintf("%s\n%s", d.path, err)) + return false + } + } + if a.win != nil { + a.win.Update(a.syncTitle) + } + return true +} + +// exitAfterConfirm 退出前询问,确认后再执行 proceed。 +func (a *App) exitAfterConfirm(dirty []*Doc, proceed func()) { + ok := false + switch a.askUnsaved(len(dirty), "退出前需要处理这些文件。") { + case choiceSave: + ok = a.saveDocs(dirty) + case choiceDiscard: + ok = true + } + a.win.Update(func() { + a.exitPending = false + if ok { + proceed() + } + }) +} + +// guardClose 在窗口关闭前拦截未保存的改动。 +func (a *App) guardClose(e *mygo.CloseEvent) { + if a.allowExit { + return + } + // 已经有确认流程在跑,先拦住,避免弹两次。 + if a.exitPending { + e.PreventDefault() + return + } + dirty := a.dirtyDocs() + if len(dirty) == 0 { + return + } + e.PreventDefault() + a.exitPending = true + go a.exitAfterConfirm(dirty, func() { + a.allowExit = true + a.win.Close() + }) +} + +// guardQuit 在应用退出前拦截未保存的改动。 +func (a *App) guardQuit(e *mygo.QuitEvent) { + if a.allowExit { + return + } + if a.exitPending { + e.PreventDefault() + return + } + dirty := a.dirtyDocs() + if len(dirty) == 0 { + return + } + e.PreventDefault() + a.exitPending = true + go a.exitAfterConfirm(dirty, func() { + a.allowExit = true + mygo.App.Exit(0) + }) +} + +// switchRoot 带未保存检查地切换工作区。 +func (a *App) switchRoot(abs string) { + dirty := a.dirtyDocs() + if len(dirty) == 0 { + a.setRoot(abs) + return + } + go func() { + ok := false + switch a.askUnsaved(len(dirty), "切换工作区会关闭当前打开的文件。") { + case choiceSave: + ok = a.saveDocs(dirty) + case choiceDiscard: + ok = true + } + if ok { + a.win.Update(func() { a.setRoot(abs) }) + } + }() +} diff --git a/internal/app/unsaved_test.go b/internal/app/unsaved_test.go new file mode 100644 index 0000000..c7906a1 --- /dev/null +++ b/internal/app/unsaved_test.go @@ -0,0 +1,82 @@ +package app + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/egoist/mygo/ui/editor" +) + +// newTestDoc 造一个指向临时文件的文档。 +func newTestDoc(t *testing.T, content string) *Doc { + t.Helper() + dir := t.TempDir() + p := filepath.Join(dir, "main.go") + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return &Doc{path: p, buf: editor.NewBuffer(content)} +} + +func TestDirtyDocs(t *testing.T) { + a := &App{} + d1 := newTestDoc(t, "package main\n") + d2 := newTestDoc(t, "package main\n") + a.docs = []*Doc{d1, d2} + + if got := a.dirtyDocs(); len(got) != 0 { + t.Fatalf("刚打开不应有脏文件,实际 %d", len(got)) + } + + d2.buf.Edit(editor.Edit{Start: 0, End: 0, Text: "// 改动\n"}) + got := a.dirtyDocs() + if len(got) != 1 || got[0] != d2 { + t.Fatalf("脏文件识别错误: %+v", got) + } +} + +func TestWriteDocFile(t *testing.T) { + d := newTestDoc(t, "package main\n") + d.buf.Edit(editor.Edit{Start: 0, End: 0, Text: "// 头部\n"}) + if !d.buf.Modified() { + t.Fatal("编辑后应当是脏的") + } + if err := writeDocFile(d); err != nil { + t.Fatalf("写盘失败: %v", err) + } + if d.buf.Modified() { + t.Fatal("写盘后不应再是脏的") + } + got, err := os.ReadFile(d.path) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(string(got), "// 头部\n") { + t.Fatalf("磁盘内容不对: %q", string(got)) + } +} + +// TestSaveDocsNilWindow 确认没有窗口时批量保存也不会崩。 +func TestSaveDocsNilWindow(t *testing.T) { + a := &App{} + d := newTestDoc(t, "package main\n") + d.buf.Edit(editor.Edit{Start: 0, End: 0, Text: "// x\n"}) + a.docs = []*Doc{d} + if !a.saveDocs(a.dirtyDocs()) { + t.Fatal("保存应当成功") + } + if d.buf.Modified() { + t.Fatal("保存后仍是脏的") + } +} + +// TestWriteDocFileError 确认目标不可写时返回错误而不是 panic。 +func TestWriteDocFileError(t *testing.T) { + dir := t.TempDir() + d := &Doc{path: filepath.Join(dir, "no-such-dir", "x.go"), buf: editor.NewBuffer("package x\n")} + if err := writeDocFile(d); err == nil { + t.Fatal("应当返回错误") + } +} diff --git a/internal/app/view.go b/internal/app/view.go new file mode 100644 index 0000000..f6a5320 --- /dev/null +++ b/internal/app/view.go @@ -0,0 +1,686 @@ +package app + +import ( + "fmt" + "path/filepath" + "strings" + "time" + + "github.com/egoist/mygo/ui" + "github.com/egoist/mygo/ui/editor" +) + +// islandGap 是所有浮岛之间的统一间距;窗口四周另有边距。 +const islandGap float32 = 6 + +// railWidth 是左侧竖条的宽度,标题栏的标识按它对齐。 +const railWidth float32 = 40 + +// sidebarMin 是项目浮岛的最小宽度:再窄标题栏那排按钮就该挤在一起了。 +const sidebarMin float32 = 190 + +// view 是整个窗口的内容,每帧重建。 +// +// 布局按 Islands Dark 的思路分层:最外层是窗口底色,只负责在岛屿之间 +// 露出「沟」;内容整体内缩 8,侧栏与主区各是一张圆角卡片,浮在底色上。 +func (a *App) view(c *ui.Context) { + c.SetTheme(a.th) + t := c.Theme() + + // 最大化、还原这类整窗跳变,框架会在 WM_SIZE 处理里先用上一帧的布局 + // 撑满新尺寸画一帧(surface.go 的 drawNow,为的是拖动窗口时内容跟手), + // 视觉上就是内容先被放大一下再恢复。这一帧只铺底色,把明显的拉伸 + // 换成一次纯背景过渡;正常拖动时每帧变化远小于阈值,不会触发。 + w, h := c.Size() + jump := false + if a.lastSize[0] > 0 { + rw, rh := w/a.lastSize[0], h/a.lastSize[1] + jump = rw > 1.2 || rw < 0.83 || rh > 1.2 || rh < 0.83 + } + a.lastSize[0], a.lastSize[1] = w, h + if jump { + ui.Box(c).Fill().Background(t.Background) + return + } + + ui.Column(c).Fill().Background(t.Background).Children(func() { + // 自绘标题栏代替系统标题栏,紧随其下才是岛屿。 + a.titleBar(c) + + // 自绘弹出菜单:覆盖层,要挂在根级。 + a.popMenu(c) + + // 弹窗挂在这个 Column 里是实测能居中的位置(Modal 的 overlay + // 以当前父级为参照,挂到根级反而会掉到编辑器右下角)。 + if a.newOpen { + a.newEntryDialog(c) + } + + // 命令面板、重命名与提交弹窗都是覆盖层。 + a.paletteView(c) + a.renameDialog(c) + a.renameEntryDialog(c) + a.commitDialog(c) + + a.settingsDialog(c) + a.breakpointCondDialog(c) + a.runConfigDialog(c) + + if a.root == "" { + ui.Column(c).Grow(1).Children(func() { a.welcomeView(c) }) + return + } + + ui.Row(c).Grow(1).Gap(islandGap).Padding(8, 8, 8, 8).AlignItems(ui.Stretch).Children(func() { + a.toolRail(c) + ui.Column(c).Grow(1).FillHeight().Gap(islandGap).Children(func() { + // 项目岛、自绘分隔条、编辑岛横排。 + // 不用 ui.Split:它在分段边界裁剪,贴边卡片的圆角会被切平, + // 而且分隔条固定 1 DIP、宽度还会被内容撑开。 + ui.Row(c).Grow(1).FillHeight().AlignItems(ui.Stretch).Children(func() { + if a.sidebarOn { + ui.Column(c).Width(a.sidebar).Shrink(0).FillHeight().Children(func() { + a.sidebarView(c) + }) + a.splitter(c) + } + a.mainView(c) + }) + a.statusCard(c) + }) + }) + }) + +} + +// welcomeView 是未打开工作区时的引导页。 +func (a *App) welcomeView(c *ui.Context) { + t := c.Theme() + ui.Column(c).Fill().Center().Gap(10).Children(func() { + logoCard(c, 104) + ui.Box(c).Height(6) + ui.Text(c, "MyGoland").FontSize(34).Bold().TextColor(t.Text) + ui.Text(c, "轻量 Go IDE · mygo + Go · v"+Version).FontSize(13).TextColor(t.TextMuted) + ui.Box(c).Height(16) + if ui.PrimaryButton(c, "打开文件夹").Clicked() { + go a.OpenFolderDialog() + } + ui.Text(c, "或按 Ctrl+O").FontSize(11).TextColor(t.TextMuted) + a.recentView(c) + }) +} + +// sidebarView 是左侧工具窗在 Split 里的那一格。 +// +// 右侧让出 4 DIP 的沟,与主区左侧的 4 DIP 合起来才是 Islands 那种明显的 +// 间距——Split 自带的分隔线只有 1 DIP,单靠它做不出岛屿之间的空隙。 +func (a *App) sidebarView(c *ui.Context) { + ui.Column(c).FillHeight().Children(func() { + if a.panelKind == 1 { + a.outlineView(c) + return + } + a.sidebarPanel(c) + }) +} + +// toolRail 是窗口最左侧的竖条,用来切换工具窗,和 IDE 的惯例一致。 +func (a *App) toolRail(c *ui.Context) { + t := c.Theme() + // 竖条也是一块岛屿:独立卡片、圆角、和工具窗之间留缝。 + ui.Column(c).Width(railWidth).FillHeight().Radius(t.Radius).Background(t.Surface).Clip(). + Gap(2).Padding(6, 0, 6, 0).AlignItems(ui.Center).Justify(ui.Start).Children(func() { + a.railButton(c, "folder", "项目", 0) + a.railButton(c, "outline", "大纲", 1) + }) +} + +// railButton 画竖条上的一个入口;点当前项会收起工具窗。 +func (a *App) railButton(c *ui.Context, name, tip string, kind int) { + t := c.Theme() + active := a.sidebarOn && a.panelKind == kind + + // 不画任何底色块:选中与悬停只靠图标颜色区分。 + el := ui.ButtonBase(c).Width(30).Height(30).Radius(6) + + color := t.TextMuted + if active { + color = t.Accent + } + el.Children(func() { + ui.Row(c).Fill().Justify(ui.Center).AlignItems(ui.Center).Children(func() { + icon(c, name, 16, color) + }) + }) + if tip != "" { + el = el.Tooltip(tip) + } + if el.Clicked() { + if active { + a.sidebarOn = false + } else { + a.sidebarOn = true + a.panelKind = kind + } + a.win.Update(func() {}) + } +} + +// sidebarPanel 是左侧的「项目」工具窗本体,画成一张独立岛屿。 +func (a *App) sidebarPanel(c *ui.Context) { + t := c.Theme() + ui.Column(c).FillHeight().FillWidth().Radius(t.Radius).Background(t.Surface).Clip().Children(func() { + // 工具窗标题栏。 + ui.Row(c).Padding(6, 8).Gap(4).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + ui.Text(c, "项目").FontSize(11).Bold().TextColor(t.TextMuted) + ui.Box(c).Grow(1) + if iconButton(c, "locate", "", "定位当前文件", t.TextMuted) { + a.RevealActive() + } + plus := iconButtonEl(c, "plus", "", "新建文件或文件夹", t.TextMuted) + if plus.Clicked() { + a.openPop(plus, a.addEntries()) + } + if iconButton(c, "refresh", "", "刷新文件树", t.TextMuted) { + a.Refresh() + } + if iconButton(c, "collapse", "", "全部折叠", t.TextMuted) { + a.CollapseAll() + } + if iconButton(c, "expand", "", "展开全部", t.TextMuted) { + a.ExpandAll() + } + }) + // 根目录名。 + ui.Row(c).Padding(4, 10).AlignItems(ui.Center).Children(func() { + ui.Text(c, strings.ToUpper(filepath.Base(a.root))).FontSize(11). + TextColor(t.TextMuted).SingleLine() + }) + ui.Scroll(c).Grow(1).Children(func() { + a.treeNode(c, a.root, 0) + }) + // 底部状态:工作区路径。 + ui.Row(c).Padding(4, 10).BorderWidth(1, 0, 0, 0).BorderColor(t.Border).Children(func() { + ui.Text(c, a.root).FontSize(10).TextColor(t.TextMuted).SingleLine() + }) + }) +} + +// RevealActive 在左侧文件树里定位当前打开的文件:逐级展开父目录、 +// 高亮那一行,并滚动到可见处。 +func (a *App) RevealActive() { + d := a.doc() + if d == nil || a.root == "" { + return + } + // 树里的路径来自 filepath.Join(Windows 上是反斜杠),而 a.root 可能是 + // 命令行传进来的正斜杠路径,直接比前缀永远不匹配,所以两边先 Clean 统一。 + root := filepath.Clean(a.root) + path := filepath.Clean(d.path) + if !strings.HasPrefix(path, root) { + return + } + // 从文件所在目录一路展开到根。 + for dir := filepath.Dir(path); strings.HasPrefix(dir, root); dir = filepath.Dir(dir) { + *a.openFlag(dir) = true + if dir == root { + break + } + } + a.revealPath = path + a.revealPending = true + a.win.Update(func() {}) +} + +// activePath 返回当前打开文件的规范化路径,没有打开文件时为空。 +// +// 要先 Clean:树里的路径来自 filepath.Join(Windows 是反斜杠),而文件路径 +// 可能来自命令行参数(正斜杠),不统一就永远不相等。 +func (a *App) activePath() string { + d := a.doc() + if d == nil { + return "" + } + return filepath.Clean(d.path) +} + +// treeNode 递归画出一层目录,depth 决定缩进层级。 +// +// 不用 ui.Tree/ui.TreeItem:TreeItem 的标签只接受一段文字,挂不了类型图标。 +// 这里自己排版——缩进用空白 Box、折叠箭头用字符、图标交给 fileIcon。 +func (a *App) treeNode(c *ui.Context, dir string, depth int) { + for _, e := range a.entries(dir) { + p := filepath.Join(dir, e.Name()) + if e.IsDir() { + if skipDir(e.Name()) { + continue + } + open := a.openFlag(p) + if a.treeRow(c, p, e.Name(), depth, true, *open) { + *open = !*open + a.win.Update(func() {}) + } + if *open { + a.treeNode(c, p, depth+1) + } + continue + } + if skipFile(e.Name()) { + continue + } + if a.treeRow(c, p, e.Name(), depth, false, false) { + go a.OpenFile(p) + } + } +} + +// treeRow 画文件树的一行:缩进、折叠箭头、类型图标、文件名。 +// 返回这一帧是否被点击——目录用来切换展开,文件用来打开。 +func (a *App) treeRow(c *ui.Context, path, name string, depth int, isDir, open bool) bool { + t := c.Theme() + active := path != "" && path == a.activePath() + + // Justify(Start) 不能省:Row 默认把内容居中,那样缩进块不起作用, + // 长短不同的文件名起点还会左右飘。 + row := ui.ButtonBase(c).FillWidth().Padding(1, 4).Gap(3).Radius(3). + Justify(ui.Start).AlignItems(ui.Center).Cursor(ui.CursorPointer) + target := float32(0) + if open { + target = 90 + } + chevronAngle := row.AnimateTo("chevron", target, + ui.Animation{Duration: 140 * time.Millisecond, Ease: ui.EaseOut}) + row.Children(func() { + // 整行底色:一个**始终存在**的绝对定位块,只切颜色、不增删元素。 + // + // 之前试过事后给行设 Background/TextColor/Draw,结果样式串到了相邻的 + // 上一行(名字是对的,颜色错行)——那是 mygo 即时模式的元素复用问题。 + // 改成「按内容位置绘制的独立元素」就落得准了。 + bgc := ui.RGBA(0, 0, 0, 0) + fg := t.Text + switch { + case a.selected(path): + // 选中的行比「当前文件」更重,多选时一眼看清范围。 + bgc = t.Accent.Alpha(0.30) + fg = t.Text + case active: + bgc = t.Accent.Alpha(0.16) + fg = t.Accent + } + // git 状态优先于普通文字色,但让位给选中/当前行。 + if st, ok := a.gst.info.Files[path]; ok && !a.selected(path) && !active { + fg = a.gitColor(st) + } + ui.Box(c).Absolute().Left(0).Top(0).Right(0).Bottom(0). + Background(bgc).Radius(3) + + if depth > 0 { + ui.Box(c).Width(float32(depth) * 12) + } + if isDir { + // 展开时箭头转 90°,带过渡,避免瞬间跳变。 + icon(c, "chevron", 10, t.TextMuted).Rotate(chevronAngle).Width(11) + } else { + // 文件行留出与箭头同宽的空位,让图标竖着对齐。 + ui.Box(c).Width(11) + } + a.fileIcon(c, name, isDir) + ui.Text(c, name).FontSize(12).TextColor(fg).SingleLine() + if st, ok := a.gst.info.Files[path]; ok { + if b := gitBadge(st); b != "" { + ui.Text(c, b).FontSize(10).TextColor(a.gitColor(st)) + } + } + }) + + // 被「定位」选中的那一行铺一层强调色。 + // 滚动只做一次——每帧都调 ScrollIntoView 会把滚动条钉死,用户翻不动。 + // 右键:在这个目录下新建文件/文件夹。 + // 文件行取它所在的目录,目录行就用它自己。 + if row.RightClicked() { + a.openPop(row, a.treeEntries(path, isDir)) + } + + if path == a.revealPath && a.revealPending { + a.revealPending = false + row.ScrollIntoView() + } + if !row.Clicked() { + return false + } + mods := c.Modifiers() + switch { + case mods&ui.Ctrl != 0: + // Ctrl 点击只改选中,不打开也不展开。 + a.toggleSelect(path) + a.win.Update(func() {}) + return false + case mods&ui.Shift != 0: + a.selectRange(path) + a.win.Update(func() {}) + return false + } + a.selectOnly(path) + return true +} + +// mainView 是右侧那半边的容器:左侧让出 4 DIP 的沟。 +func (a *App) mainView(c *ui.Context) { + a.mainPanel(c) +} + +// splitter 是项目岛与编辑岛之间的分隔条:宽度与岛屿间距一致, +// 全程不画任何颜色(拖动时也不染色),只靠光标形状提示可拖动。 +// +// 拖拽用「起点宽度 + 累计位移」算绝对值,拖动期间绝不复位位移: +// 一旦每帧归零,框架会认为元素被拖回原位,产生假的负数增量, +// 侧栏会被一路顶到最小值(踩过一次)。 +func (a *App) splitter(c *ui.Context) { + if a.splitDrag == nil { + a.splitDrag = &ui.Point{} + } + el := ui.Box(c).Width(islandGap).FillHeight().Cursor(ui.CursorResizeEW). + Draggable(a.splitDrag, ui.DraggableOptions{Axis: ui.Horizontal}) + + _, _, held := el.Dragged() + if held { + if !a.splitHeld { + a.splitHeld = true + a.splitBase = a.sidebar + } + w := a.splitBase + a.splitDrag.X + if w < sidebarMin { + w = sidebarMin + } + if max, _ := c.Size(); max > 0 && w > max-420 { + w = max - 420 + } + a.sidebar = w + return + } + if a.splitHeld { + // 松手:结束这次拖动并复位位移,元素回到布局位置。 + a.splitHeld = false + a.splitDrag.X = 0 + a.splitDrag.Y = 0 + a.saveSession() + } +} + +// statusCard 是底部状态栏浮岛。 +func (a *App) statusCard(c *ui.Context) { + t := c.Theme() + ui.Row(c).FillWidth().Radius(t.Radius).Background(t.Surface).Clip().Children(func() { + if d := a.doc(); d != nil { + a.statusBar(c, d) + } else { + a.emptyStatusBar(c) + } + }) +} + +// mainPanel 是标签栏、编辑区与底部面板组成的岛屿。 +// 状态栏不在这里:它归窗口底色,由 view 画。 +func (a *App) mainPanel(c *ui.Context) { + t := c.Theme() + ui.Column(c).Grow(1).FillWidth().Radius(t.Radius).Background(t.Surface).Clip().Children(func() { + // 没有打开文件时不画标签栏:空标签栏里只剩一条撑开的空白和它的 + // 下边框,会在编辑区顶部留下一条莫名其妙的横线。 + if len(a.docs) > 0 { + a.tabBar(c) + } + if a.panel { + ui.SplitVertical(c, &a.panelH, + func() { a.editorArea(c, false) }, + func() { a.panelView(c) }).Grow(1) + } else { + a.editorArea(c, true) + } + }) +} + +// editorArea 画编辑区;grow 为真时占满剩余高度。 +func (a *App) editorArea(c *ui.Context, grow bool) { + t := c.Theme() + // 差异视图 / 历史视图开着时占满编辑区。 + if a.histViewActive() { + a.historyView(c) + return + } + if a.diffActive() { + a.renderDiff(c) + return + } + d := a.doc() + if d == nil { + e := ui.Column(c).Center().Gap(6).Children(func() { + ui.Text(c, "没有打开的文件").FontSize(14).TextColor(t.TextMuted) + ui.Text(c, "在左侧单击文件即可打开").FontSize(12).TextColor(t.TextMuted) + }) + if grow { + e.Grow(1) + } else { + e.Fill() + } + return + } + a.runPendingCmd(d) + a.decorate(d) + // 关掉「可以滚过末尾」:这是编辑器滚动条在自己内部唯一的判据 + // (scrollbars() 里 `ed.scrollMax() > 0`,而 scrollMax 在 scrollPastEnd + // 为真时是 `total - lineHeight`,短文本也大于 0,于是短文件照样画滚动条)。 + // 关掉后 scrollMax 变成 `total - viewH`,内容不满一页时被 max(0, …) 归零, + // 滚动条自然消失;长文件不受影响,仍然照常滚动。 + d.st.NoScrollPastEnd = true + + // 上面是面包屑,下面是编辑器 + 缩略图。 + ui.Column(c).Fill().Children(func() { + a.breadcrumb(c, d) + // 编辑器与缩略图并排:编辑器吃满剩余宽度,缩略图固定窄条。 + ui.Row(c).Grow(1).AlignItems(ui.Stretch).Children(func() { + e := editor.View(c, d.st).FillHeight().Grow(1) + // AutoFocus 只在元素**首次出现**的那一帧生效——编辑器一直都在, + // 所以弹窗/面板关掉后调它没有任何作用。要抢回焦点得用 Focus, + // 但它「每帧调用就每帧保持」,只能在我们真正需要时调一次。 + if a.wantFocus { + e.Focus() + a.wantFocus = false + } else if grow { + e.AutoFocus() + } + // Bounds 是上一帧布局的矩形,首帧为 0,缩略图会跳过视口框。 + a.minimap(c, d, e.Bounds().H) + }) + }) + a.lspSync(d) +} + +// tabBar 是打开文件的标签栏,每个标签自带关闭按钮。 +func (a *App) tabBar(c *ui.Context) { + t := c.Theme() + ui.Row(c).Padding(4, 6).Gap(2).AlignItems(ui.Center). + BorderWidth(0, 0, 1, 0).BorderColor(t.Border).Children(func() { + for _, d := range a.docs { + d := d + active := d.path == a.active + bg := t.Background + fg := t.TextMuted + if active { + bg = t.Surface + fg = t.Text + } + ui.Row(c).Radius(3).Background(bg).AlignItems(ui.Center). + Children(func() { + label := filepath.Base(d.path) + if d.buf.Modified() { + label = "● " + label + } + open := ui.ButtonBase(c).Padding(3, 7).Children(func() { + ui.Text(c, label).FontSize(12).TextColor(fg).SingleLine() + }) + if open.Clicked() { + a.active = d.path + } + close := ui.ButtonBase(c).Padding(3, 5).Radius(3).Children(func() { + icon(c, "close", 11, t.TextMuted) + }).Tooltip("关闭") + if close.Clicked() { + go a.CloseDoc(d.path) + } + }).Padding(0, 1) + } + ui.Box(c).Grow(1) + }) +} + +// statusBar 是底部状态栏,左侧光标与行数,右侧诊断、编码与语言。 +func (a *App) statusBar(c *ui.Context, d *Doc) { + t := c.Theme() + pos := d.st.CursorPos() + lang := "纯文本" + if l := d.buf.Language(); l != nil { + lang = l.Name + } + eol := "LF" + if strings.Contains(d.buf.LineEnding(), "\r") { + eol = "CRLF" + } + errs, warns := 0, 0 + for _, p := range d.problems { + switch p.Severity { + case editor.SeverityError: + errs++ + case editor.SeverityWarning: + warns++ + } + } + + ui.Row(c).Padding(0, 2).AlignItems(ui.Center).Height(24).Children(func() { + segment(c, fmt.Sprintf("行 %d,列 %d", pos.Line+1, pos.Col+1), t.TextMuted) + divider(c) + segment(c, fmt.Sprintf("%d 行", d.buf.LineCount()), t.TextMuted) + divider(c) + statusCount(c, "error", errs, severityColor(t, errs, t.Danger)) + statusCount(c, "warning", warns, severityColor(t, warns, t.Warning)) + ui.Box(c).Grow(1) + if a.gst.info.OK { + segment(c, "⎇ "+a.gst.info.Branch, t.TextMuted) + divider(c) + if n := a.gst.info.Dirty; n > 0 { + segment(c, fmt.Sprintf("%d 处改动", n), t.Warning) + divider(c) + } + } + if a.lspState != "" { + segment(c, a.lspState, t.TextMuted) + divider(c) + } + segment(c, eol, t.TextMuted) + divider(c) + if cv := a.coverStatText(d.path); cv != "" { + segment(c, cv, t.TextMuted) + divider(c) + } + if stat := a.diffStatText(d.path); stat != "" { + segment(c, stat, t.TextMuted) + divider(c) + } + segment(c, encName(d.enc), t.TextMuted) + divider(c) + if d.truncated { + // 截断过就说明看到的不是全文,必须说清楚。 + segment(c, "只读·已截断", t.Warning) + divider(c) + } + segment(c, lang, t.TextMuted) + divider(c) + a.statusPanelHint(c) + }) +} + +// emptyStatusBar 在没有打开文件时也占住状态栏高度。 +func (a *App) emptyStatusBar(c *ui.Context) { + t := c.Theme() + ui.Row(c).Padding(0, 8).AlignItems(ui.Center).Height(24).Children(func() { + ui.Box(c).Grow(1) + if a.gst.info.OK { + segment(c, "⎇ "+a.gst.info.Branch, t.TextMuted) + divider(c) + if n := a.gst.info.Dirty; n > 0 { + segment(c, fmt.Sprintf("%d 处改动", n), t.Warning) + divider(c) + } + } + if a.lspState != "" { + segment(c, a.lspState, t.TextMuted) + divider(c) + } + a.statusPanelHint(c) + }) +} + +// segment 是状态栏的一段文字。 +func segment(c *ui.Context, text string, color ui.Color) { + ui.Text(c, text).FontSize(11).TextColor(color).Padding(0, 7) +} + +// divider 是状态栏分段之间的竖线。 +func divider(c *ui.Context) { + ui.Box(c).Width(1).Height(12).Background(c.Theme().Border) +} + +// severityColor 在数量为 0 时用弱化色。 +func severityColor(t *ui.Theme, n int, on ui.Color) ui.Color { + if n == 0 { + return t.TextMuted + } + return on +} + +// statusCount 画一个带图标的计数。 +func statusCount(c *ui.Context, name string, n int, color ui.Color) { + ui.Row(c).Gap(3).Padding(0, 6).AlignItems(ui.Center).Children(func() { + icon(c, name, 11, color) + ui.Textf(c, "%d", n).FontSize(11).TextColor(color) + }) +} + +// activeIndex 返回当前文件在标签栏中的下标,没有则为 -1。 +func (a *App) activeIndex() int { + for i, d := range a.docs { + if d.path == a.active { + return i + } + } + if len(a.docs) > 0 { + return 0 + } + return -1 +} + +// CollapseAll 收起文件树的所有目录。 +func (a *App) CollapseAll() { + apply := func() { + for _, p := range a.open { + *p = false + } + } + if a.win == nil { + apply() + return + } + a.win.Update(apply) +} + +// ToggleSidebar 显示或隐藏左侧项目工具窗。 +func (a *App) ToggleSidebar() { + a.sidebarOn = !a.sidebarOn + a.win.Update(func() {}) +} + +// ToggleMinimap 显示或隐藏编辑器右侧的代码缩略图。 +func (a *App) ToggleMinimap() { + a.minimapOn = !a.minimapOn + a.win.Update(func() {}) +} diff --git a/internal/app/watch.go b/internal/app/watch.go new file mode 100644 index 0000000..d473622 --- /dev/null +++ b/internal/app/watch.go @@ -0,0 +1,163 @@ +package app + +import ( + "context" + "os" + "path/filepath" + "time" + + "github.com/egoist/mygo" +) + +// watchDebounce 是磁盘事件去抖时长:一次保存常常连发多个事件。 +const watchDebounce = 300 * time.Millisecond + +// docWatch 记录一个文件的监听器与最近一次已知的磁盘状态。 +type docWatch struct { + w *mygo.FileWatcher + ctx context.Context + cancel context.CancelFunc + at time.Time + size int64 +} + +// stamp 记录文件当前的时间戳与大小,用于识别「自己的保存」。 +func (dw *docWatch) stamp(path string) { + st, err := os.Stat(path) + if err != nil { + return + } + dw.at, dw.size = st.ModTime(), st.Size() +} + +// unchanged 判断磁盘状态是否与记录一致。 +func (dw *docWatch) unchanged(st os.FileInfo) bool { + if dw == nil { + return false + } + return dw.at.Equal(st.ModTime()) && dw.size == st.Size() +} + +// startWatch 开始监听文件在编辑器外的改动。 +func (a *App) startWatch(d *Doc) { + if d.watch != nil || a.win == nil || d.path == "" { + return + } + ctx, cancel := context.WithCancel(context.Background()) + w, err := mygo.WatchFiles(ctx, d.path, mygo.FileWatchOptions{Debounce: watchDebounce}) + if err != nil { + cancel() + logf("监听 %s 失败: %v", d.path, err) + return + } + dw := &docWatch{w: w, ctx: ctx, cancel: cancel} + dw.stamp(d.path) + d.watch = dw + + go func() { + for { + if _, err := w.Next(ctx); err != nil { + return + } + a.win.Update(func() { a.onDiskChange(d) }) + } + }() +} + +// stopWatch 结束监听。 +func (d *Doc) stopWatch() { + if d.watch == nil { + return + } + d.watch.cancel() + _ = d.watch.w.Close() + d.watch = nil +} + +// onDiskChange 处理磁盘上的改动,须在主线程调用。 +func (a *App) onDiskChange(d *Doc) { + if a.find(d.path) != d { + d.stopWatch() + return + } + st, err := os.Stat(d.path) + if err != nil { + if os.IsNotExist(err) { + a.appendOut("文件已从磁盘删除:" + filepath.Base(d.path)) + d.watch = nil + } + return + } + if d.watch != nil && d.watch.unchanged(st) { + return + } + data, err := os.ReadFile(d.path) + if err != nil { + return + } + text := string(data) + if text == d.buf.String() { + if d.watch != nil { + d.watch.at, d.watch.size = st.ModTime(), st.Size() + } + return + } + if d.buf.Modified() { + a.askConflict(d, text) + return + } + a.reloadDoc(d, text) + if d.watch != nil { + d.watch.at, d.watch.size = st.ModTime(), st.Size() + } + logf("reload %s after external change", d.path) + a.appendOut("文件已在编辑器外更改,已重新加载:" + filepath.Base(d.path)) +} + +// reloadDoc 用磁盘内容替换缓冲区,旧诊断一并清掉。 +func (a *App) reloadDoc(d *Doc, text string) { + d.buf.Reset(text) + if d.st != nil { + d.st.SetDiagnostics(d.buf.Version(), nil) + d.problems = nil + } +} + +// askConflict 在缓冲区有改动时询问如何处理磁盘上的新内容。 +func (a *App) askConflict(d *Doc, text string) { + path := d.path + go func() { + res, err := mygo.Dialog.Message(mygo.MessageOptions{ + Parent: a.win, + Type: mygo.MessageWarning, + Title: "文件已在编辑器外更改", + Message: filepath.Base(path) + " 在编辑器外被修改,而你有未保存的改动。", + Detail: "重新加载会丢弃你在编辑器里的修改。", + Buttons: []string{"重新加载", "保留我的改动"}, + DefaultButton: 1, + CancelButton: 1, + }) + if err != nil { + return + } + if res.Button != 0 { + return + } + a.win.Update(func() { + if a.find(path) != d { + return + } + a.reloadDoc(d, text) + if d.watch != nil { + d.watch.stamp(path) + } + }) + }() +} + +// notifySaved 在写盘后刷新已知的磁盘状态,避免把自己的保存当成外部改动。 +func (d *Doc) notifySaved() { + if d.watch != nil { + d.watch.stamp(d.path) + } +} diff --git a/internal/app/watch_test.go b/internal/app/watch_test.go new file mode 100644 index 0000000..2c36e45 --- /dev/null +++ b/internal/app/watch_test.go @@ -0,0 +1,81 @@ +package app + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/egoist/mygo" +) + +// TestFileWatchFires 确认 mygo 的单文件监听在本机可用。 +func TestFileWatchFires(t *testing.T) { + if testing.Short() { + t.Skip("需要真实文件系统事件") + } + dir := t.TempDir() + p := filepath.Join(dir, "a.txt") + if err := os.WriteFile(p, []byte("one"), 0o644); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + w, err := mygo.WatchFiles(ctx, p, mygo.FileWatchOptions{Debounce: 100 * time.Millisecond}) + if err != nil { + t.Skipf("本机不支持文件监听: %v", err) + } + defer w.Close() + + go func() { + time.Sleep(400 * time.Millisecond) + _ = os.WriteFile(p, []byte("one-two"), 0o644) + }() + + done := make(chan struct{}) + go func() { + if _, err := w.Next(ctx); err == nil { + close(done) + } + }() + select { + case <-done: + case <-time.After(15 * time.Second): + t.Fatal("15 秒内没有收到文件改动事件") + } +} + +// TestOnDiskChangeReload 确认干净缓冲区会被磁盘内容替换。 +func TestOnDiskChangeReload(t *testing.T) { + a := &App{} + d := newTestDoc(t, "package main\n") + a.docs = []*Doc{d} + + if err := os.WriteFile(d.path, []byte("package main\n\n// 外部改动\n"), 0o644); err != nil { + t.Fatal(err) + } + a.onDiskChange(d) + + if !strings.Contains(d.buf.String(), "外部改动") { + t.Fatalf("没有重新加载,当前内容: %q", d.buf.String()) + } + if d.buf.Modified() { + t.Fatal("重载后不应是脏的") + } +} + +// TestOnDiskChangeSameContent 确认内容没变时不动缓冲区。 +func TestOnDiskChangeSameContent(t *testing.T) { + a := &App{} + d := newTestDoc(t, "package main\n") + a.docs = []*Doc{d} + before := d.buf.Version() + + a.onDiskChange(d) + + if d.buf.Version() != before { + t.Fatal("内容未变,不应重置缓冲区") + } +} diff --git a/internal/app/wscheck.go b/internal/app/wscheck.go new file mode 100644 index 0000000..ff06de9 --- /dev/null +++ b/internal/app/wscheck.go @@ -0,0 +1,96 @@ +package app + +import ( + "os/exec" + "path/filepath" + "strconv" + "strings" + + "github.com/egoist/mygo/ui/editor" +) + +// wsCheckState 是全工作区检查的状态。 +type wsCheckState struct { + on bool + items []Problem + at int64 + err string +} + +// RunWorkspaceCheck 在工作区根目录跑 go vet,把结果并进「问题」面板。 +// +// 为什么用 go vet 而不是问语言服务器:LSP 没有「把整个项目的诊断给我」这种请求, +// 它只推已打开的文件。vet 恰好能一次覆盖整个模块,代价是编译期检查而非编辑器实时分析。 +func (a *App) RunWorkspaceCheck() { + if a.root == "" || a.wsState.on { + return + } + root := a.root + a.wsState.on = true + a.wsState.err = "" + a.panel = true + a.panelTab = 1 + a.win.Update(func() {}) + + go func() { + cmd := exec.Command("go", "vet", "./...") + cmd.Dir = root + out, err := cmd.CombinedOutput() + items := parseVetOutput(root, string(out)) + a.win.Update(func() { + a.wsState.on = false + a.wsState.items = items + if err != nil && len(items) == 0 { + // 没有解析出问题但命令失败:多半是环境问题(没装 go、模块坏了), + // 直接把输出甩到运行面板,别让它悄无声息地失败。 + a.wsState.err = strings.TrimSpace(string(out)) + a.panelTab = 0 + a.appendOut("go vet 失败:" + a.wsState.err) + } + a.win.Update(func() {}) + }) + }() +} + +// parseVetOutput 解析 `path:line:col: message` 形式的行。 +func parseVetOutput(root, out string) []Problem { + var ps []Problem + for _, line := range strings.Split(out, "\n") { + line = strings.TrimRight(line, "\r") + i := strings.Index(line, ".go:") + if i < 0 { + continue + } + path := line[:i+3] + rest := line[i+4:] + parts := strings.SplitN(rest, ":", 3) + if len(parts) < 2 { + continue + } + lineNo, err := strconv.Atoi(strings.TrimSpace(parts[0])) + if err != nil { + continue + } + col, msg := 0, "" + if c, err := strconv.Atoi(strings.TrimSpace(parts[1])); err == nil { + col = c + if len(parts) == 3 { + msg = parts[2] + } + } else { + msg = strings.Join(parts[1:], ":") + } + if !filepath.IsAbs(path) { + path = filepath.Join(root, filepath.FromSlash(strings.TrimPrefix(path, "./"))) + } + ps = append(ps, Problem{ + Path: filepath.Clean(path), + Line: lineNo, + Col: col + 1, + Text: strings.TrimSpace(msg), + Severity: editor.SeverityError, + Source: "vet", + }) + } + return ps +} diff --git a/internal/app/wscheck_test.go b/internal/app/wscheck_test.go new file mode 100644 index 0000000..7806bec --- /dev/null +++ b/internal/app/wscheck_test.go @@ -0,0 +1,118 @@ +package app + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestParseVetOutput(t *testing.T) { + root := filepath.Join("C:", "work", "proj") + out := strings.Join([]string{ + "# demo/greeter", + "./greeter/greeter.go:7:6: fmt.Sprintf format %s has arg name of wrong type int", + "a.go:3: printf: non-constant format string", + "vet: something odd", + "", + }, "\n") + + ps := parseVetOutput(root, out) + if len(ps) != 2 { + t.Fatalf("应解析出 2 条,实际 %d: %+v", len(ps), ps) + } + if ps[0].Line != 7 || ps[0].Col != 7 || !strings.Contains(ps[0].Text, "fmt.Sprintf") { + t.Fatalf("第一条不对: %+v", ps[0]) + } + if ps[0].Path != filepath.Join(root, "greeter", "greeter.go") { + t.Fatalf("相对路径没拼对: %q", ps[0].Path) + } + if ps[0].Source != "vet" { + t.Fatalf("来源应是 vet: %q", ps[0].Source) + } + if ps[1].Line != 3 { + t.Fatalf("第二条行号不对: %+v", ps[1]) + } +} + +func TestParseVetOutputAbsolute(t *testing.T) { + // 必须用真的绝对路径:filepath.Join("C:", "work") 在 Windows 上是 + // "C:work"(盘符相对),并不算绝对路径,会让这条断言失真。 + root := t.TempDir() + abs := filepath.Join(root, "x.go") + ps := parseVetOutput(root, abs+":10:2: boom") + if len(ps) != 1 || ps[0].Path != abs { + t.Fatalf("绝对路径应原样保留: %+v", ps) + } +} + +// TestWorkspaceCheckRealVet 用真 go vet 跑一遍,确认解析器吃得下真实输出。 +func TestWorkspaceCheckRealVet(t *testing.T) { + if testing.Short() { + t.Skip("需要 go 工具链") + } + if _, err := exec.LookPath("go"); err != nil { + t.Skip("没有 go") + } + dir := t.TempDir() + writeTestFile(t, filepath.Join(dir, "go.mod"), "module demo\n\ngo 1.21\n") + writeTestFile(t, filepath.Join(dir, "main.go"), `package main + +import "fmt" + +func main() { + fmt.Printf("%s", 1) +} +`) + cmd := exec.Command("go", "vet", "./...") + cmd.Dir = dir + out, _ := cmd.CombinedOutput() + + ps := parseVetOutput(dir, string(out)) + if len(ps) == 0 { + t.Fatalf("go vet 应当报出格式问题,输出:\n%s", out) + } + if !strings.HasSuffix(ps[0].Path, "main.go") { + t.Fatalf("路径不对: %q", ps[0].Path) + } + if ps[0].Line != 6 { + t.Fatalf("行号应是 6,实际 %d", ps[0].Line) + } + if !strings.Contains(ps[0].Text, "Printf") { + t.Fatalf("消息不对: %q", ps[0].Text) + } +} + +func writeTestFile(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +// TestAllProblemsDedup 同一问题既被语言服务器报、又被 vet 报时,只留一条。 +func TestAllProblemsDedup(t *testing.T) { + dup := Problem{Path: "x.go", Line: 3, Text: "boom"} + a := &App{ + docs: []*Doc{{problems: []Problem{dup}}}, + wsState: wsCheckState{items: []Problem{ + {Path: "x.go", Line: 3, Text: "boom", Source: "vet"}, // 与上面重复 + {Path: "x.go", Line: 9, Text: "只有 vet 报的", Source: "vet"}, + }}, + } + ps := a.allProblems() + if len(ps) != 2 { + t.Fatalf("去重后应剩 2 条,实际 %d: %+v", len(ps), ps) + } + // 保留的应当是语言服务器那条(没有 Source 标记) + if ps[0].Source != "" { + t.Fatalf("重复项应保留语言服务器版本: %+v", ps[0]) + } + if ps[1].Line != 9 { + t.Fatalf("第二条应是 vet 独有的: %+v", ps[1]) + } +} diff --git a/internal/dap/client.go b/internal/dap/client.go new file mode 100644 index 0000000..130a7d6 --- /dev/null +++ b/internal/dap/client.go @@ -0,0 +1,492 @@ +// Package dap 实现一个最小可用的 Debug Adapter Protocol 客户端,用于驱动 dlv dap。 +package dap + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os/exec" + "strconv" + "strings" + "sync" + "time" +) + +// request 是发往调试适配器的请求。 +type request struct { + Seq int `json:"seq"` + Type string `json:"type"` + Command string `json:"command"` + Arguments any `json:"arguments,omitempty"` +} + +// response 是适配器的应答。 +type response struct { + Seq int `json:"seq"` + Type string `json:"type"` + RequestSeq int `json:"request_seq"` + Success bool `json:"success"` + Command string `json:"command"` + Message string `json:"message"` + Body json.RawMessage `json:"body"` +} + +// message 用来区分应答与事件。 +type message struct { + Type string `json:"type"` + Event string `json:"event"` + Seq int `json:"seq"` +} + +// Client 是一个 DAP 连接。 +type Client struct { + cmd *exec.Cmd + conn net.Conn + bw *bufio.Writer + r *bufio.Reader + + mu sync.Mutex + seq int + pending map[int]chan response + + done chan struct{} + once sync.Once + onEvent func(event string, body json.RawMessage) + logf func(string, ...any) +} + +// Start 启动 dlv dap 并连接它监听的端口。 +// +// dlv dap 不接受 stdio 传输:它会监听一个随机端口并把地址打到标准输出, +// 所以先解析 "DAP server listening at: host:port" 再拨号。 +func Start(dir string, onEvent func(string, json.RawMessage), logf func(string, ...any)) (*Client, error) { + if logf == nil { + logf = func(string, ...any) {} + } + path, err := exec.LookPath("dlv") + if err != nil { + return nil, fmt.Errorf("找不到 dlv,请先执行:go install github.com/go-delve/delve/cmd/dlv@latest") + } + cmd := exec.Command(path, "dap", "--listen=127.0.0.1:0") + cmd.Dir = dir + cmd.SysProcAttr = procAttr() + + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + stderr, err := cmd.StderrPipe() + if err != nil { + return nil, err + } + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("启动 dlv 失败:%w", err) + } + + addrCh := make(chan string, 1) + go func() { + sc := bufio.NewScanner(stdout) + for sc.Scan() { + line := sc.Text() + logf("dlv: %s", line) + if i := strings.Index(line, "listening at:"); i >= 0 { + addr := strings.TrimSpace(line[i+len("listening at:"):]) + select { + case addrCh <- addr: + default: + } + } + } + }() + go func() { + sc := bufio.NewScanner(stderr) + sc.Buffer(make([]byte, 0, 64*1024), 1024*1024) + for sc.Scan() { + logf("dlv: %s", sc.Text()) + } + }() + + var addr string + select { + case addr = <-addrCh: + case <-time.After(20 * time.Second): + _ = cmd.Process.Kill() + return nil, fmt.Errorf("dlv dap 没有在 20 秒内就绪") + } + + var conn net.Conn + for i := 0; i < 20; i++ { + conn, err = net.DialTimeout("tcp", addr, 2*time.Second) + if err == nil { + break + } + time.Sleep(150 * time.Millisecond) + } + if err != nil { + _ = cmd.Process.Kill() + return nil, fmt.Errorf("连接 %s 失败:%w", addr, err) + } + + c := &Client{ + cmd: cmd, + conn: conn, + bw: bufio.NewWriter(conn), + r: bufio.NewReader(conn), + pending: map[int]chan response{}, + done: make(chan struct{}), + onEvent: onEvent, + logf: logf, + } + go c.readLoop() + return c, nil +} + +// readFrame 读出一条 DAP 报文。 +func readFrame(r *bufio.Reader) ([]byte, error) { + length := -1 + for { + line, err := r.ReadString('\n') + if err != nil { + return nil, err + } + line = strings.TrimRight(line, "\r\n") + if line == "" { + break + } + if k, v, ok := strings.Cut(line, ":"); ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") { + n, err := strconv.Atoi(strings.TrimSpace(v)) + if err != nil { + return nil, fmt.Errorf("dap: 非法的 Content-Length %q", v) + } + length = n + } + } + if length < 0 { + return nil, errors.New("dap: 缺少 Content-Length") + } + buf := make([]byte, length) + if _, err := io.ReadFull(r, buf); err != nil { + return nil, err + } + return buf, nil +} + +func (c *Client) readLoop() { + defer c.close() + for { + body, err := readFrame(c.r) + if err != nil { + return + } + var m message + if err := json.Unmarshal(body, &m); err != nil { + continue + } + switch m.Type { + case "response": + var resp response + if err := json.Unmarshal(body, &resp); err != nil { + continue + } + c.mu.Lock() + ch := c.pending[resp.RequestSeq] + c.mu.Unlock() + if ch != nil { + select { + case ch <- resp: + default: + } + } + case "event": + var ev struct { + Body json.RawMessage `json:"body"` + } + _ = json.Unmarshal(body, &ev) + if c.onEvent != nil { + go c.onEvent(m.Event, ev.Body) + } + } + } +} + +// Do 发送请求并等待应答。 +func (c *Client) Do(command string, args any, timeout time.Duration) (json.RawMessage, error) { + c.mu.Lock() + c.seq++ + seq := c.seq + ch := make(chan response, 1) + c.pending[seq] = ch + c.mu.Unlock() + + defer func() { + c.mu.Lock() + delete(c.pending, seq) + c.mu.Unlock() + }() + + body, err := json.Marshal(request{Seq: seq, Type: "request", Command: command, Arguments: args}) + if err != nil { + return nil, err + } + c.mu.Lock() + _, werr := fmt.Fprintf(c.bw, "Content-Length: %d\r\n\r\n", len(body)) + if werr == nil { + _, werr = c.bw.Write(body) + } + if werr == nil { + werr = c.bw.Flush() + } + c.mu.Unlock() + if werr != nil { + return nil, werr + } + + select { + case resp := <-ch: + if !resp.Success { + if resp.Message != "" { + return nil, errors.New("dap: " + resp.Message) + } + return nil, fmt.Errorf("dap: %s 失败", command) + } + return resp.Body, nil + case <-time.After(timeout): + return nil, fmt.Errorf("dap: %s 超时", command) + case <-c.done: + return nil, errors.New("dap: 连接已关闭") + } +} + +// Initialize 完成 DAP 握手。 +func (c *Client) Initialize() error { + _, err := c.Do("initialize", map[string]any{ + "clientID": "mygoland", + "clientName": "MyGoland", + "adapterID": "go", + "linesStartAt1": true, + "columnsStartAt1": true, + "pathFormat": "path", + "supportsVariableType": true, + "supportsVariablePaging": false, + "supportsRunInTerminalRequest": false, + }, 30*time.Second) + return err +} + +// Launch 启动被调试程序,args 是传给程序的参数。 +func (c *Client) Launch(program string, args []string, stopOnEntry bool, timeout time.Duration) error { + _, err := c.Do("launch", map[string]any{ + "mode": "debug", + "program": program, + "args": args, + "stopOnEntry": stopOnEntry, + }, timeout) + return err +} + +// Evaluate 在某个栈帧上求值。 +func (c *Client) Evaluate(expr string, frameID int) (string, error) { + body, err := c.Do("evaluate", map[string]any{ + "expression": expr, + "frameId": frameID, + "context": "watch", + }, 15*time.Second) + if err != nil { + return "", err + } + var out struct { + Result string `json:"result"` + Type string `json:"type"` + } + if err := json.Unmarshal(body, &out); err != nil { + return "", err + } + if out.Type != "" { + return out.Result + " (" + out.Type + ")", nil + } + return out.Result, nil +} + +// ConfigurationDone 告诉适配器配置阶段结束,程序可以跑起来。 +func (c *Client) ConfigurationDone() error { + _, err := c.Do("configurationDone", nil, 10*time.Second) + return err +} + +// BreakpointSpec 是设置断点时的入参:行号 + 可选条件。 +type BreakpointSpec struct { + Line int `json:"line"` + Condition string `json:"condition,omitempty"` +} + +// Breakpoint 是一个断点。 +type Breakpoint struct { + Line int `json:"line"` + Verified bool `json:"verified"` + Message string `json:"message"` +} + +// SetBreakpoints 为某个文件设置断点,行号从 1 开始。 +func (c *Client) SetBreakpoints(path string, specs []BreakpointSpec) ([]Breakpoint, error) { + bps := make([]map[string]any, 0, len(specs)) + lines := make([]int, 0, len(specs)) + for _, s := range specs { + entry := map[string]any{"line": s.Line} + if s.Condition != "" { + entry["condition"] = s.Condition + } + bps = append(bps, entry) + lines = append(lines, s.Line) + } + body, err := c.Do("setBreakpoints", map[string]any{ + "source": map[string]any{"path": path}, + "breakpoints": bps, + "lines": lines, + }, 15*time.Second) + if err != nil { + return nil, err + } + var out struct { + Breakpoints []Breakpoint `json:"breakpoints"` + } + _ = json.Unmarshal(body, &out) + return out.Breakpoints, nil +} + +// Frame 是一个调用栈帧。 +type Frame struct { + ID int `json:"id"` + Name string `json:"name"` + Line int `json:"line"` + Column int `json:"column"` + Source struct { + Path string `json:"path"` + Name string `json:"name"` + } `json:"source"` +} + +// Thread 是一个线程。dlv dap 把 goroutine 当线程列出来, +// name 通常是 goroutine 正停住的函数名。 +type Thread struct { + ID int `json:"id"` + Name string `json:"name"` +} + +// Threads 列出当前的线程(goroutine)。 +func (c *Client) Threads() ([]Thread, error) { + body, err := c.Do("threads", nil, 15*time.Second) + if err != nil { + return nil, err + } + var out struct { + Threads []Thread `json:"threads"` + } + _ = json.Unmarshal(body, &out) + return out.Threads, nil +} + +// StackTrace 取某个线程的调用栈。 +func (c *Client) StackTrace(threadID, levels int) ([]Frame, error) { + body, err := c.Do("stackTrace", map[string]any{ + "threadId": threadID, + "startFrame": 0, + "levels": levels, + }, 15*time.Second) + if err != nil { + return nil, err + } + var out struct { + StackFrames []Frame `json:"stackFrames"` + } + _ = json.Unmarshal(body, &out) + return out.StackFrames, nil +} + +// Scope 是一个作用域。 +type Scope struct { + Name string `json:"name"` + VariablesReference int `json:"variablesReference"` + Expensive bool `json:"expensive"` +} + +// Scopes 取栈帧的作用域。 +func (c *Client) Scopes(frameID int) ([]Scope, error) { + body, err := c.Do("scopes", map[string]any{"frameId": frameID}, 15*time.Second) + if err != nil { + return nil, err + } + var out struct { + Scopes []Scope `json:"scopes"` + } + _ = json.Unmarshal(body, &out) + return out.Scopes, nil +} + +// Variable 是一个变量。 +type Variable struct { + Name string `json:"name"` + Value string `json:"value"` + Type string `json:"type"` + VariablesReference int `json:"variablesReference"` +} + +// Variables 取某个引用下的变量。 +func (c *Client) Variables(ref int) ([]Variable, error) { + body, err := c.Do("variables", map[string]any{"variablesReference": ref}, 15*time.Second) + if err != nil { + return nil, err + } + var out struct { + Variables []Variable `json:"variables"` + } + _ = json.Unmarshal(body, &out) + return out.Variables, nil +} + +// Continue 继续执行。 +func (c *Client) Continue(threadID int) error { + _, err := c.Do("continue", map[string]any{"threadId": threadID}, 15*time.Second) + return err +} + +// Next 步过。 +func (c *Client) Next(threadID int) error { + _, err := c.Do("next", map[string]any{"threadId": threadID}, 15*time.Second) + return err +} + +// StepIn 单步进入。 +func (c *Client) StepIn(threadID int) error { + _, err := c.Do("stepIn", map[string]any{"threadId": threadID}, 15*time.Second) + return err +} + +// StepOut 跳出。 +func (c *Client) StepOut(threadID int) error { + _, err := c.Do("stepOut", map[string]any{"threadId": threadID}, 15*time.Second) + return err +} + +// Close 断开并结束调试会话。 +func (c *Client) Close() { + if c == nil { + return + } + _, _ = c.Do("disconnect", map[string]any{"terminateDebuggee": true}, 3*time.Second) + c.close() + if c.cmd != nil && c.cmd.Process != nil { + _ = c.cmd.Process.Kill() + } +} + +func (c *Client) close() { + c.once.Do(func() { + close(c.done) + if c.conn != nil { + _ = c.conn.Close() + } + }) +} diff --git a/internal/dap/client_test.go b/internal/dap/client_test.go new file mode 100644 index 0000000..7fbe208 --- /dev/null +++ b/internal/dap/client_test.go @@ -0,0 +1,389 @@ +package dap + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// eventLog 收集适配器事件。 +type eventLog struct { + mu sync.Mutex + events map[string]chan json.RawMessage +} + +func newEventLog() *eventLog { + return &eventLog{events: map[string]chan json.RawMessage{}} +} + +func (l *eventLog) push(name string, body json.RawMessage) { + l.mu.Lock() + ch, ok := l.events[name] + if !ok { + ch = make(chan json.RawMessage, 8) + l.events[name] = ch + } + l.mu.Unlock() + select { + case ch <- body: + default: + } +} + +func (l *eventLog) wait(name string, d time.Duration) (json.RawMessage, bool) { + l.mu.Lock() + ch, ok := l.events[name] + if !ok { + ch = make(chan json.RawMessage, 8) + l.events[name] = ch + } + l.mu.Unlock() + select { + case body := <-ch: + return body, true + case <-time.After(d): + return nil, false + } +} + +const prog = `package main + +import "fmt" + +func add(a, b int) int { + sum := a + b + return sum +} + +func main() { + x := 1 + y := 2 + fmt.Println(add(x, y)) +} +` + +// goroutineProg 三个 worker 并发跑,用来验证 threads 列 goroutine。 +const goroutineProg = `package main + +import "sync" + +func worker(wg *sync.WaitGroup, n int) { + defer wg.Done() + x := n * 2 + _ = x +} + +func main() { + var wg sync.WaitGroup + for i := 0; i < 3; i++ { + wg.Add(1) + go worker(&wg, i) + } + wg.Wait() +} +` + +// TestThreadsGoroutines 停在并发程序的断点上时,threads 应列出 +// goroutine,且当前停住的那个在列表里——这是调试面板 goroutine 列表的数据源。 +func TestThreadsGoroutines(t *testing.T) { + if testing.Short() { + t.Skip("集成测试需要 dlv") + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil { + t.Fatal(err) + } + main := filepath.Join(dir, "main.go") + if err := os.WriteFile(main, []byte(goroutineProg), 0o644); err != nil { + t.Fatal(err) + } + + log := newEventLog() + c, err := Start(dir, log.push, t.Logf) + if err != nil { + t.Skipf("dlv 不可用: %v", err) + } + defer c.Close() + + if err := c.Initialize(); err != nil { + t.Fatalf("initialize: %v", err) + } + launched := make(chan error, 1) + go func() { launched <- c.Launch("./", nil, false, 120*time.Second) }() + + if _, ok := log.wait("initialized", 90*time.Second); !ok { + t.Fatal("没有收到 initialized 事件") + } + // 第 7 行 `x := n * 2`:三个 worker 都会经过。 + if _, err := c.SetBreakpoints(main, []BreakpointSpec{{Line: 7}}); err != nil { + t.Fatalf("setBreakpoints: %v", err) + } + if err := c.ConfigurationDone(); err != nil { + t.Fatalf("configurationDone: %v", err) + } + body, ok := log.wait("stopped", 90*time.Second) + if !ok { + t.Fatal("没有停在断点上") + } + var stopped struct { + ThreadID int `json:"threadId"` + } + if err := json.Unmarshal(body, &stopped); err != nil { + t.Fatal(err) + } + + threads, err := c.Threads() + if err != nil { + t.Fatalf("threads: %v", err) + } + if len(threads) == 0 { + t.Fatal("应至少列出一个 goroutine") + } + ids := map[int]bool{} + current := false + for _, th := range threads { + if th.ID == 0 { + t.Fatalf("goroutine 编号不应为 0: %+v", th) + } + if ids[th.ID] { + t.Fatalf("goroutine 编号重复: %d", th.ID) + } + ids[th.ID] = true + if th.ID == stopped.ThreadID { + current = true + } + } + if !current { + t.Fatalf("当前停住的 goroutine %d 不在列表里: %+v", stopped.ThreadID, threads) + } + <-launched +} + +func TestDebugSession(t *testing.T) { + if testing.Short() { + t.Skip("集成测试需要 dlv") + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil { + t.Fatal(err) + } + main := filepath.Join(dir, "main.go") + if err := os.WriteFile(main, []byte(prog), 0o644); err != nil { + t.Fatal(err) + } + + log := newEventLog() + c, err := Start(dir, log.push, t.Logf) + if err != nil { + t.Skipf("dlv 不可用: %v", err) + } + defer c.Close() + + if err := c.Initialize(); err != nil { + t.Fatalf("initialize: %v", err) + } + + launched := make(chan error, 1) + go func() { launched <- c.Launch("./", nil, false, 120*time.Second) }() + + // 等适配器准备好接收断点。 + if _, ok := log.wait("initialized", 90*time.Second); !ok { + t.Fatal("没有收到 initialized 事件") + } + if _, err := c.SetBreakpoints(main, []BreakpointSpec{{Line: 6}}); err != nil { + t.Fatalf("setBreakpoints: %v", err) + } + if err := c.ConfigurationDone(); err != nil { + t.Fatalf("configurationDone: %v", err) + } + + body, ok := log.wait("stopped", 90*time.Second) + if !ok { + t.Fatal("没有停在断点上") + } + var stopped struct { + Reason string `json:"reason"` + ThreadID int `json:"threadId"` + } + if err := json.Unmarshal(body, &stopped); err != nil { + t.Fatal(err) + } + if stopped.ThreadID == 0 { + t.Fatalf("stopped 事件没有线程号: %s", body) + } + + frames, err := c.StackTrace(stopped.ThreadID, 10) + if err != nil { + t.Fatalf("stackTrace: %v", err) + } + if len(frames) == 0 { + t.Fatal("调用栈为空") + } + top := frames[0] + if top.Line != 6 { + t.Fatalf("断点行号: got %d want 6(栈顶 %s)", top.Line, top.Name) + } + if !strings.HasSuffix(strings.ToLower(top.Source.Path), "main.go") { + t.Fatalf("栈顶文件不对: %s", top.Source.Path) + } + + // 变量里应当有 a 和 b。 + scopes, err := c.Scopes(top.ID) + if err != nil { + t.Fatalf("scopes: %v", err) + } + names := map[string]string{} + for _, sc := range scopes { + if sc.Expensive || sc.VariablesReference == 0 { + continue + } + vs, err := c.Variables(sc.VariablesReference) + if err != nil { + continue + } + for _, v := range vs { + names[v.Name] = v.Value + } + } + if _, ok := names["a"]; !ok { + t.Fatalf("变量里没有 a:%v", names) + } + if names["a"] != "1" { + t.Fatalf("a 的值: got %q want \"1\"", names["a"]) + } + + // 表达式求值。 + res, err := c.Evaluate("a+b", top.ID) + if err != nil { + t.Fatalf("evaluate: %v", err) + } + if !strings.HasPrefix(res, "3") { + t.Fatalf("a+b 求值结果: %q", res) + } + + // 单步一次,应当移动到 return 行。 + if err := c.Next(stopped.ThreadID); err != nil { + t.Fatalf("next: %v", err) + } + body, ok = log.wait("stopped", 60*time.Second) + if !ok { + t.Fatal("单步后没有再次停下") + } + if err := json.Unmarshal(body, &stopped); err != nil { + t.Fatal(err) + } + frames, err = c.StackTrace(stopped.ThreadID, 10) + if err != nil { + t.Fatalf("stackTrace: %v", err) + } + if frames[0].Line != 7 { + t.Fatalf("单步后行号: got %d want 7", frames[0].Line) + } + + // 继续执行,程序应当跑完。 + if err := c.Continue(stopped.ThreadID); err != nil { + t.Fatalf("continue: %v", err) + } + if _, ok := log.wait("terminated", 60*time.Second); !ok { + t.Fatal("程序没有结束") + } + if err := <-launched; err != nil { + t.Fatalf("launch: %v", err) + } +} + +// TestConditionalBreakpoint 验证条件断点:循环里只有 i == 3 那次才停。 +func TestConditionalBreakpoint(t *testing.T) { + if testing.Short() { + t.Skip("集成测试需要 dlv") + } + prog := `package main + +import "fmt" + +func main() { + total := 0 + for i := 0; i < 5; i++ { + total += i + } + fmt.Println(total) +} +` + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil { + t.Fatal(err) + } + main := filepath.Join(dir, "main.go") + if err := os.WriteFile(main, []byte(prog), 0o644); err != nil { + t.Fatal(err) + } + + log := newEventLog() + c, err := Start(dir, log.push, t.Logf) + if err != nil { + t.Skipf("dlv 不可用: %v", err) + } + defer c.Close() + + if err := c.Initialize(); err != nil { + t.Fatalf("initialize: %v", err) + } + go func() { _ = c.Launch("./", nil, false, 120*time.Second) }() + + if _, ok := log.wait("initialized", 90*time.Second); !ok { + t.Fatal("没有收到 initialized 事件") + } + // 第 8 行是 total += i,条件 i == 3 + if _, err := c.SetBreakpoints(main, []BreakpointSpec{{Line: 8, Condition: "i == 3"}}); err != nil { + t.Fatalf("setBreakpoints: %v", err) + } + if err := c.ConfigurationDone(); err != nil { + t.Fatalf("configurationDone: %v", err) + } + + body, ok := log.wait("stopped", 90*time.Second) + if !ok { + t.Fatal("条件断点没有停下") + } + var stopped struct { + ThreadID int `json:"threadId"` + } + if err := json.Unmarshal(body, &stopped); err != nil { + t.Fatal(err) + } + frames, err := c.StackTrace(stopped.ThreadID, 10) + if err != nil || len(frames) == 0 { + t.Fatalf("stackTrace: %v", err) + } + if got := frames[0].Line; got != 8 { + t.Fatalf("应停在第 8 行,实际 %d", got) + } + + // 停在 i == 3 时,变量 i 的值必须是 3 + scopes, err := c.Scopes(frames[0].ID) + if err != nil { + t.Fatalf("scopes: %v", err) + } + found := "" + for _, sc := range scopes { + if sc.Expensive || sc.VariablesReference == 0 { + continue + } + vs, err := c.Variables(sc.VariablesReference) + if err != nil { + continue + } + for _, v := range vs { + if v.Name == "i" { + found = v.Value + } + } + } + if found != "3" { + t.Fatalf("条件断点应在 i == 3 时停下,实际 i = %q", found) + } +} diff --git a/internal/dap/procattr_other.go b/internal/dap/procattr_other.go new file mode 100644 index 0000000..fbfdff4 --- /dev/null +++ b/internal/dap/procattr_other.go @@ -0,0 +1,10 @@ +//go:build !windows + +package dap + +import "syscall" + +// procAttr 在非 Windows 平台不需要额外属性。 +func procAttr() *syscall.SysProcAttr { + return nil +} diff --git a/internal/dap/procattr_windows.go b/internal/dap/procattr_windows.go new file mode 100644 index 0000000..5a3bee3 --- /dev/null +++ b/internal/dap/procattr_windows.go @@ -0,0 +1,10 @@ +//go:build windows + +package dap + +import "syscall" + +// procAttr 隐藏 dlv 子进程的控制台窗口。 +func procAttr() *syscall.SysProcAttr { + return &syscall.SysProcAttr{HideWindow: true} +} diff --git a/internal/git/git.go b/internal/git/git.go new file mode 100644 index 0000000..9c219ed --- /dev/null +++ b/internal/git/git.go @@ -0,0 +1,267 @@ +// Package git 用命令行读仓库状态:不引第三方库,也不碰 .git 内部结构。 +package git + +import ( + "bytes" + "context" + "fmt" + "os/exec" + "path/filepath" + "strings" + "time" +) + +// Info 是一个工作区的 git 快照。 +type Info struct { + // OK 表示这是一个 git 仓库(且装了 git)。 + OK bool + // Branch 是当前分支名,游离头时是短哈希。 + Branch string + // Files 是「绝对路径 → 状态码」,状态码是 M/A/D/R/?? /U 之一。 + Files map[string]string + // Dirty 是改动文件数。 + Dirty int +} + +// Available 判断目录里能不能用 git(装了 git 且是仓库)。 +func Available(root string) bool { + if root == "" { + return false + } + if _, err := exec.LookPath("git"); err != nil { + return false + } + out, err := run(root, "rev-parse", "--is-inside-work-tree") + return err == nil && strings.TrimSpace(out) == "true" +} + +// Load 读一次仓库状态。 +func Load(root string) Info { + info := Info{Files: map[string]string{}} + if !Available(root) { + return info + } + info.OK = true + if out, err := run(root, "rev-parse", "--abbrev-ref", "HEAD"); err == nil { + info.Branch = strings.TrimSpace(out) + } + out, err := run(root, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames") + if err != nil { + return info + } + for _, e := range parsePorcelain(out) { + abs := filepath.Join(root, filepath.FromSlash(e.path)) + info.Files[abs] = e.code + } + info.Dirty = len(info.Files) + return info +} + +type entry struct { + code string + path string +} + +// parsePorcelain 解析 porcelain v1 -z 的输出。 +func parsePorcelain(out string) []entry { + var res []entry + for _, rec := range strings.Split(out, "\x00") { + // "XY path":前两个字符是状态,第三个是空格 + if len(rec) < 4 { + continue + } + code := codeFor(rec[0], rec[1]) + if code == "" { + continue + } + res = append(res, entry{code: code, path: rec[3:]}) + } + return res +} + +// codeFor 把 XY 两位状态压成一个给人看的码。 +func codeFor(x, y byte) string { + switch { + case x == '?' || y == '?': + return "??" + case x == 'U' || y == 'U': + return "U" + case x == 'D' || y == 'D': + return "D" + case x == 'R': + return "R" + case x == 'A': + return "A" + case x == 'M' || y == 'M': + return "M" + case x == 'T' || y == 'T': + return "M" + } + return "" +} + +// run 在 root 下执行 git 命令并返回标准输出。 +func run(root string, args ...string) (string, error) { + full := append([]string{"-C", root}, args...) + cmd := exec.Command("git", full...) + // 只读查询不要抢 .git/index.lock,免得和外部 git 命令打架。 + cmd.Env = append(cmd.Environ(), "GIT_OPTIONAL_LOCKS=0") + var buf bytes.Buffer + cmd.Stdout = &buf + if err := cmd.Run(); err != nil { + return "", err + } + return buf.String(), nil +} + +// gitTimeout 是一次 git 命令的上限。pull/push 走网络,留足慢网的时间; +// 本地命令远用不了这么多。 +const gitTimeout = 2 * time.Minute + +// runOut 跑 git 并返回**合并后**的输出:git 的进度与报错大多走 stderr, +// pull/push 的结果要原样给用户看,得分开接。 +func runOut(root string, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), gitTimeout) + defer cancel() + full := append([]string{"-C", root}, args...) + cmd := exec.CommandContext(ctx, "git", full...) + var buf bytes.Buffer + cmd.Stdout = &buf + cmd.Stderr = &buf + err := cmd.Run() + return strings.TrimSpace(buf.String()), err +} + +// Stage 把所有改动加入暂存区。 +func Stage(root string) error { + _, err := run(root, "add", "-A") + return err +} + +// StagePaths 只把指定文件加入暂存区(选择性暂存)。 +// paths 是仓库相对路径(正斜杠);删除的文件 add 同样会记录删除。 +// 一个都不选时直接成功——调用方应当在上游拦住「空提交」。 +func StagePaths(root string, paths []string) error { + if len(paths) == 0 { + return nil + } + args := append([]string{"add", "--"}, paths...) + _, err := run(root, args...) + return err +} + +// Commit 提交暂存区的内容。 +func Commit(root, message string) error { + _, err := run(root, "commit", "-m", message) + return err +} + +// Pull 拉取并合并当前分支。 +// +// 用 --ff-only:分叉时直接失败并把 git 的提示原样带回来, +// 绝不偷偷做 merge commit——IDE 里一键操作宁可保守。 +func Pull(root string) (string, error) { + return runOut(root, "pull", "--ff-only") +} + +// Push 推送当前分支到上游;还没有上游时自动补一次 -u origin <分支>, +// 这是新仓库第一次推送的固定动作,替用户省一步。 +func Push(root string) (string, error) { + out, err := runOut(root, "push") + if err == nil || !strings.Contains(out, "no upstream") { + return out, err + } + branch, berr := run(root, "rev-parse", "--abbrev-ref", "HEAD") + if berr != nil { + return out, err + } + return runOut(root, "push", "--set-upstream", "origin", strings.TrimSpace(branch)) +} + +// ShowFile 返回某文件在 HEAD 里的内容。 +// +// 新文件(还没提交过)会报错,调用方把 old 当成空文本处理即可。 +func ShowFile(root, path string) (string, error) { + rel, err := filepath.Rel(root, path) + if err != nil { + return "", err + } + return run(root, "show", "HEAD:"+filepath.ToSlash(rel)) +} + +// Numstat 一次拿到所有改动文件的行数增减,键是仓库相对路径(正斜杠)。 +// +// 每个文件各起一次 git 进程太慢,状态栏每帧都要看这个数, +// 所以统一在后台刷一次存起来查。 +func Numstat(root string) map[string][2]int { + out, err := run(root, "diff", "--numstat") + if err != nil { + return nil + } + m := map[string][2]int{} + for _, line := range strings.Split(out, "\n") { + f := strings.Fields(line) + if len(f) < 3 { + continue + } + var add, del int + // 二进制文件给的是 "-",算 0。 + fmt.Sscanf(f[0], "%d", &add) + fmt.Sscanf(f[1], "%d", &del) + m[f[2]] = [2]int{add, del} + } + return m +} + +// LogEntry 是一条提交记录(名字避开已有的 Commit 函数)。 +type LogEntry struct { + Hash string + Author string + When string // 相对时间,如 "3 hours ago" + Subject string +} + +// Log 取某个文件或目录的提交历史,limit 为 0 时用 50。 +// +// 用 \x1f 分隔字段:提交标题里什么字符都可能有,只有控制符不会出现在里头。 +func Log(root, path string, limit int) ([]LogEntry, error) { + if limit <= 0 { + limit = 50 + } + args := []string{ + "log", + fmt.Sprintf("--max-count=%d", limit), + "--pretty=format:%h\x1f%an\x1f%ar\x1f%s", + } + if path != "" { + rel, err := filepath.Rel(root, path) + if err == nil { + args = append(args, "--", filepath.ToSlash(rel)) + } + } + out, err := run(root, args...) + if err != nil { + return nil, err + } + var commits []LogEntry + for _, line := range strings.Split(strings.TrimSpace(out), "\n") { + if line == "" { + continue + } + f := strings.SplitN(line, "\x1f", 4) + if len(f) < 4 { + continue + } + commits = append(commits, LogEntry{Hash: f[0], Author: f[1], When: f[2], Subject: f[3]}) + } + return commits, nil +} + +// ShowAt 取某文件在指定版本里的内容(rev 可以是 或 ^)。 +func ShowAt(root, rev, path string) (string, error) { + rel, err := filepath.Rel(root, path) + if err != nil { + return "", err + } + return run(root, "show", rev+":"+filepath.ToSlash(rel)) +} diff --git a/internal/git/git_test.go b/internal/git/git_test.go new file mode 100644 index 0000000..22ee042 --- /dev/null +++ b/internal/git/git_test.go @@ -0,0 +1,305 @@ +package git + +import ( + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestCodeFor(t *testing.T) { + cases := []struct { + x, y byte + want string + }{ + {'?', '?', "??"}, + {' ', 'M', "M"}, + {'M', ' ', "M"}, + {'M', 'M', "M"}, + {'A', ' ', "A"}, + {' ', 'D', "D"}, + {'D', ' ', "D"}, + {'R', ' ', "R"}, + {'U', 'U', "U"}, + {' ', ' ', ""}, + } + for _, c := range cases { + if got := codeFor(c.x, c.y); got != c.want { + t.Fatalf("codeFor(%q,%q)=%q 期望 %q", c.x, c.y, got, c.want) + } + } +} + +func TestParsePorcelain(t *testing.T) { + // git status --porcelain=v1 -z 的真实形状:每条 "XY path" 以 NUL 结尾 + out := " M main.go\x00?? new.go\x00A added.go\x00 D gone.go\x00" + got := parsePorcelain(out) + want := map[string]string{ + "main.go": "M", + "new.go": "??", + "added.go": "A", + "gone.go": "D", + } + if len(got) != len(want) { + t.Fatalf("解析条数不对: %+v", got) + } + for _, e := range got { + if want[e.path] != e.code { + t.Fatalf("%s 状态应为 %q,实际 %q", e.path, want[e.path], e.code) + } + } +} + +// TestLoadRealRepo 用一个真仓库验证整条链路。 +func TestLoadRealRepo(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("没有 git") + } + dir := t.TempDir() + gitRun(t, dir, "init") + gitRun(t, dir, "config", "user.email", "test@example.com") + gitRun(t, dir, "config", "user.name", "test") + + if err := os.WriteFile(filepath.Join(dir, "a.go"), []byte("package a\n"), 0o644); err != nil { + t.Fatal(err) + } + gitRun(t, dir, "add", "-A") + gitRun(t, dir, "commit", "-m", "init") + + if info := Load(dir); !info.OK || info.Dirty != 0 { + t.Fatalf("刚提交完应该干净,实际 %+v", info) + } + + // 改一个、加一个 + if err := os.WriteFile(filepath.Join(dir, "a.go"), []byte("package a\n// x\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "b.go"), []byte("package a\n"), 0o644); err != nil { + t.Fatal(err) + } + + info := Load(dir) + if !info.OK || info.Branch == "" { + t.Fatalf("应当读到分支名: %+v", info) + } + if info.Files[filepath.Join(dir, "a.go")] != "M" { + t.Fatalf("a.go 应为 M,实际 %q", info.Files[filepath.Join(dir, "a.go")]) + } + if info.Files[filepath.Join(dir, "b.go")] != "??" { + t.Fatalf("b.go 应为 ??,实际 %q", info.Files[filepath.Join(dir, "b.go")]) + } + if info.Dirty != 2 { + t.Fatalf("脏文件数应为 2,实际 %d", info.Dirty) + } + + // 提交后应该重新变干净 + if err := Stage(dir); err != nil { + t.Fatal(err) + } + if err := Commit(dir, "second"); err != nil { + t.Fatal(err) + } + if info := Load(dir); info.Dirty != 0 { + t.Fatalf("提交后应该干净,实际 %d", info.Dirty) + } +} + +// TestStagePathsSelective 选择性暂存:只勾选的文件进提交,其余保持脏。 +func TestStagePathsSelective(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("没有 git") + } + dir := t.TempDir() + gitRun(t, dir, "init") + gitRun(t, dir, "config", "user.email", "test@example.com") + gitRun(t, dir, "config", "user.name", "test") + + write := func(name, content string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + write("keep.go", "package a\n") + write("skip.go", "package a\n") + gitRun(t, dir, "add", "-A") + gitRun(t, dir, "commit", "-m", "init") + + // 两个文件都改,只暂存 keep.go。 + write("keep.go", "package a\n// keep\n") + write("skip.go", "package a\n// skip\n") + + if err := StagePaths(dir, []string{"keep.go"}); err != nil { + t.Fatal(err) + } + // 空清单应当安全地什么都不做。 + if err := StagePaths(dir, nil); err != nil { + t.Fatalf("空清单不应报错: %v", err) + } + if err := Commit(dir, "only keep"); err != nil { + t.Fatal(err) + } + + info := Load(dir) + if got := info.Files[filepath.Join(dir, "keep.go")]; got != "" { + t.Fatalf("keep.go 应已提交,实际状态 %q", got) + } + if got := info.Files[filepath.Join(dir, "skip.go")]; got != "M" { + t.Fatalf("skip.go 应保持未提交(M),实际 %q", got) + } + if info.Dirty != 1 { + t.Fatalf("脏文件数应为 1,实际 %d", info.Dirty) + } + + // 删除的文件也能通过 StagePaths 记录删除。 + if err := os.Remove(filepath.Join(dir, "skip.go")); err != nil { + t.Fatal(err) + } + if err := StagePaths(dir, []string{"skip.go"}); err != nil { + t.Fatal(err) + } + if err := Commit(dir, "remove skip"); err != nil { + t.Fatal(err) + } + if info := Load(dir); info.Dirty != 0 { + t.Fatalf("删除提交后应该干净,实际 %d 处", info.Dirty) + } +} + +func gitRun(t *testing.T, dir string, args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", dir}, args...)...) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v 失败: %v\n%s", args, err, out) + } +} + +// TestShowFileAndNumstat 差异视图要的两样东西:HEAD 里的旧内容、行数增减。 +func TestShowFileAndNumstat(t *testing.T) { + if testing.Short() { + t.Skip("集成测试需要 git") + } + dir := t.TempDir() + gitRun(t, dir, "init", "-q", ".") + gitRun(t, dir, "config", "user.email", "t@t.com") + gitRun(t, dir, "config", "user.name", "t") + + path := filepath.Join(dir, "a.go") + if err := os.WriteFile(path, []byte("package main\n"), 0o644); err != nil { + t.Fatal(err) + } + gitRun(t, dir, "add", "-A") + gitRun(t, dir, "commit", "-qm", "初始") + + // 提交后再改两行:旧内容要能取到,numstat 要的数要对。 + if err := os.WriteFile(path, []byte("package main\n\n// 新加\nfunc main() {}\n"), 0o644); err != nil { + t.Fatal(err) + } + + old, err := ShowFile(dir, path) + if err != nil { + t.Fatalf("取 HEAD 版本失败: %v", err) + } + if old != "package main\n" { + t.Fatalf("旧内容不对: %q", old) + } + + stats := Numstat(dir) + // 原来 1 行,现在 4 行(多了空行、注释、函数声明)→ +3 −0 + if got := stats["a.go"]; got[0] != 3 || got[1] != 0 { + t.Fatalf("行数增减不对: %v", got) + } +} + +// TestShowFileUntracked 新文件取不到 HEAD 版本,要报错(调用方当空文本处理)。 +func TestShowFileUntracked(t *testing.T) { + if testing.Short() { + t.Skip("集成测试需要 git") + } + dir := t.TempDir() + gitRun(t, dir, "init", "-q", ".") + path := filepath.Join(dir, "new.go") + if err := os.WriteFile(path, []byte("package main\n"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := ShowFile(dir, path); err == nil { + t.Fatal("未跟踪文件不该取到 HEAD 版本") + } +} + +// TestLogEntries 提交历史的解析:hash/作者/时间/标题四段都要对上。 +func TestLogEntries(t *testing.T) { + if testing.Short() { + t.Skip("集成测试需要 git") + } + dir := t.TempDir() + gitRun(t, dir, "init", "-q", ".") + gitRun(t, dir, "config", "user.email", "t@t.com") + gitRun(t, dir, "config", "user.name", "曹港回") + + path := filepath.Join(dir, "a.go") + names := []string{"一", "二", "三"} + for i, body := range []string{"v1\n", "v2\n", "v3\n"} { + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + gitRun(t, dir, "add", "-A") + gitRun(t, dir, "commit", "-qm", "第"+names[i]+"版") + } + + commits, err := Log(dir, path, 0) + if err != nil { + t.Fatalf("取历史失败: %v", err) + } + if len(commits) != 3 { + t.Fatalf("应有 3 条提交,实际 %d", len(commits)) + } + // 最新的在最前 + if commits[0].Subject != "第三版" { + t.Fatalf("顺序不对: %+v", commits[0]) + } + if commits[0].Author != "曹港回" { + t.Fatalf("作者不对: %q", commits[0].Author) + } + if len(commits[0].Hash) < 5 || commits[0].When == "" { + t.Fatalf("hash 或时间缺失: %+v", commits[0]) + } + + // ShowAt 取父提交与本次提交的内容 + oldText, err := ShowAt(dir, commits[0].Hash+"^", path) + if err != nil { + t.Fatalf("取父版本失败: %v", err) + } + newText, err := ShowAt(dir, commits[0].Hash, path) + if err != nil { + t.Fatalf("取本次版本失败: %v", err) + } + if oldText != "v2\n" || newText != "v3\n" { + t.Fatalf("版本内容不对: old=%q new=%q", oldText, newText) + } +} + +// TestLogDir 目录也能取历史(不限文件)。 +func TestLogDir(t *testing.T) { + if testing.Short() { + t.Skip("集成测试需要 git") + } + dir := t.TempDir() + gitRun(t, dir, "init", "-q", ".") + gitRun(t, dir, "config", "user.email", "t@t.com") + gitRun(t, dir, "config", "user.name", "t") + sub := filepath.Join(dir, "pkg") + if err := os.MkdirAll(sub, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(sub, "a.go"), []byte("package a\n"), 0o644); err != nil { + t.Fatal(err) + } + gitRun(t, dir, "add", "-A") + gitRun(t, dir, "commit", "-qm", "初始") + + commits, err := Log(dir, sub, 0) + if err != nil || len(commits) == 0 { + t.Fatalf("目录历史应为非空: %v %v", commits, err) + } +} diff --git a/internal/lsp/client.go b/internal/lsp/client.go new file mode 100644 index 0000000..aa948e7 --- /dev/null +++ b/internal/lsp/client.go @@ -0,0 +1,479 @@ +package lsp + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "strings" + "time" +) + +// Options 配置一个 LSP 客户端。 +type Options struct { + // Root 是工作区目录,gopls 以此为根。 + Root string + // Logf 接收诊断日志,可为 nil。 + Logf func(string, ...any) + // OnDiagnostics 在收到诊断通知时调用,来自 gopls 的读协程。 + OnDiagnostics func(uri string, version int, ds []Diagnostic) + // OnExit 在 gopls 进程退出时调用(手动 Close 也会触发,调用方要自己 + // 区分是意外崩溃还是主动关闭)。来自 wait 协程,不要在里面做重活。 + OnExit func() + // Command 是语言服务器命令,默认 "gopls"。 + Command string +} + +// Client 是一个 gopls 连接。 +type Client struct { + conn *conn + cmd *exec.Cmd + root string + logf func(string, ...any) + waitDone chan struct{} +} + +// Start 拉起语言服务器并完成初始化握手。 +func Start(ctx context.Context, opts Options) (*Client, error) { + bin := opts.Command + if bin == "" { + bin = "gopls" + } + logf := opts.Logf + if logf == nil { + logf = func(string, ...any) {} + } + path, err := exec.LookPath(bin) + if err != nil { + return nil, fmt.Errorf("找不到 %s,请先执行:go install golang.org/x/tools/gopls@latest", bin) + } + + cmd := exec.Command(path) + cmd.Dir = opts.Root + cmd.SysProcAttr = procAttr() + + stdin, err := cmd.StdinPipe() + if err != nil { + return nil, err + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + stderr, err := cmd.StderrPipe() + if err != nil { + return nil, err + } + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("启动 %s 失败:%w", bin, err) + } + + c := &Client{cmd: cmd, root: opts.Root, logf: logf, waitDone: make(chan struct{})} + c.conn = newConn(stdin, stdout, logf) + c.conn.onNotify = func(method string, params json.RawMessage) { + switch method { + case "textDocument/publishDiagnostics": + var p PublishDiagnosticsParams + if err := json.Unmarshal(params, &p); err != nil { + return + } + if opts.OnDiagnostics != nil { + opts.OnDiagnostics(p.URI, p.Version, p.Diagnostics) + } + case "window/showMessage": + var m struct { + Type int `json:"type"` + Message string `json:"message"` + } + if json.Unmarshal(params, &m) == nil { + logf("gopls 提示:%s", m.Message) + } + } + } + + go func() { + sc := bufio.NewScanner(stderr) + sc.Buffer(make([]byte, 0, 64*1024), 1024*1024) + for sc.Scan() { + logf("gopls: %s", sc.Text()) + } + }() + go func() { + if err := cmd.Wait(); err != nil { + logf("gopls 退出:%v", err) + } + close(c.waitDone) + if opts.OnExit != nil { + opts.OnExit() + } + }() + + initCtx, cancel := context.WithTimeout(ctx, 90*time.Second) + defer cancel() + params := InitializeParams{ + ProcessID: os.Getpid(), + ClientInfo: &ClientInfo{Name: "MyGoland", Version: "0.1.0"}, + RootURI: PathToURI(opts.Root), + RootPath: opts.Root, + WorkspaceFolders: []WorkspaceFolder{{ + URI: PathToURI(opts.Root), + Name: baseName(opts.Root), + }}, + Capabilities: defaultCapabilities(), + } + var res InitializeResult + if err := c.conn.call(initCtx, "initialize", params, &res); err != nil { + c.Close() + return nil, fmt.Errorf("初始化失败:%w", err) + } + if res.ServerInfo != nil { + logf("语言服务器:%s %s", res.ServerInfo.Name, shorten(res.ServerInfo.Version, 60)) + } + if err := c.conn.notify("initialized", struct{}{}); err != nil { + c.Close() + return nil, err + } + return c, nil +} + +// baseName 返回路径的最后一段,跨平台处理分隔符。 +func baseName(p string) string { + p = strings.TrimRight(p, `/\`) + if i := strings.LastIndexAny(p, `/\`); i >= 0 { + return p[i+1:] + } + return p +} + +// shorten 截断过长的字符串,gopls 的版本字段可能是一整段构建信息。 +func shorten(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] + "…" +} + +// DidOpen 通知文档已打开。 +func (c *Client) DidOpen(uri, languageID string, version int, text string) error { + return c.conn.notify("textDocument/didOpen", map[string]any{ + "textDocument": TextDocumentItem{URI: uri, LanguageID: languageID, Version: version, Text: text}, + }) +} + +// DidChange 通知文档的增量修改。 +func (c *Client) DidChange(uri string, version int, changes []ContentChange) error { + return c.conn.notify("textDocument/didChange", map[string]any{ + "textDocument": VersionedTextDocumentIdentifier{URI: uri, Version: version}, + "contentChanges": changes, + }) +} + +// DidSave 通知文档已保存。 +func (c *Client) DidSave(uri, text string) error { + params := map[string]any{"textDocument": TextDocumentIdentifier{URI: uri}} + if text != "" { + params["text"] = text + } + return c.conn.notify("textDocument/didSave", params) +} + +// DidClose 通知文档已关闭。 +func (c *Client) DidClose(uri string) error { + return c.conn.notify("textDocument/didClose", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + }) +} + +// Completion 请求补全。 +func (c *Client) Completion(ctx context.Context, uri string, pos Position) ([]CompletionItem, error) { + var raw json.RawMessage + err := c.conn.call(ctx, "textDocument/completion", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "position": pos, + }, &raw) + if err != nil { + return nil, err + } + return decodeCompletions(raw), nil +} + +// decodeCompletions 兼容数组与 CompletionList 两种返回。 +func decodeCompletions(raw json.RawMessage) []CompletionItem { + s := strings.TrimSpace(string(raw)) + if s == "" || s == "null" { + return nil + } + if strings.HasPrefix(s, "[") { + var arr []CompletionItem + _ = json.Unmarshal(raw, &arr) + return arr + } + var list CompletionList + if err := json.Unmarshal(raw, &list); err == nil { + return list.Items + } + return nil +} + +// Hover 请求悬停信息。 +func (c *Client) Hover(ctx context.Context, uri string, pos Position) (*Hover, error) { + var raw json.RawMessage + err := c.conn.call(ctx, "textDocument/hover", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "position": pos, + }, &raw) + if err != nil { + return nil, err + } + if len(raw) == 0 || string(raw) == "null" { + return nil, nil + } + var h Hover + if err := json.Unmarshal(raw, &h); err != nil { + return nil, err + } + return &h, nil +} + +// Definition 请求定义位置。 +func (c *Client) Definition(ctx context.Context, uri string, pos Position) ([]Location, error) { + var raw json.RawMessage + err := c.conn.call(ctx, "textDocument/definition", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "position": pos, + }, &raw) + if err != nil { + return nil, err + } + return decodeLocations(raw), nil +} + +// decodeLocations 兼容 Location、Location[] 与 LocationLink[]。 +func decodeLocations(raw json.RawMessage) []Location { + s := strings.TrimSpace(string(raw)) + if s == "" || s == "null" { + return nil + } + if strings.HasPrefix(s, "[") { + var arr []json.RawMessage + if err := json.Unmarshal(raw, &arr); err != nil { + return nil + } + out := make([]Location, 0, len(arr)) + for _, x := range arr { + if loc, ok := decodeLocation(x); ok { + out = append(out, loc) + } + } + return out + } + if loc, ok := decodeLocation(raw); ok { + return []Location{loc} + } + return nil +} + +func decodeLocation(raw json.RawMessage) (Location, bool) { + var loc Location + if err := json.Unmarshal(raw, &loc); err == nil && loc.URI != "" { + return loc, true + } + var link struct { + TargetURI string `json:"targetUri"` + TargetRange Range `json:"targetRange"` + TargetSelectionRange Range `json:"targetSelectionRange"` + } + if err := json.Unmarshal(raw, &link); err == nil && link.TargetURI != "" { + r := link.TargetSelectionRange + if r == (Range{}) { + r = link.TargetRange + } + return Location{URI: link.TargetURI, Range: r}, true + } + return Location{}, false +} + +// DocumentSymbol 请求文件的符号树。 +// +// 服务端可能返回层级式的 DocumentSymbol,也可能返回平铺的 SymbolInformation, +// 后者会被转成同一形状,位置取 location.range。 +func (c *Client) DocumentSymbol(ctx context.Context, uri string) ([]DocumentSymbol, error) { + var raw json.RawMessage + err := c.conn.call(ctx, "textDocument/documentSymbol", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + }, &raw) + if err != nil { + return nil, err + } + return decodeSymbols(raw), nil +} + +// decodeSymbols 兼容 DocumentSymbol[] 与 SymbolInformation[]。 +func decodeSymbols(raw json.RawMessage) []DocumentSymbol { + s := strings.TrimSpace(string(raw)) + if s == "" || s == "null" { + return nil + } + var syms []DocumentSymbol + if err := json.Unmarshal(raw, &syms); err == nil && len(syms) > 0 && syms[0].Name != "" { + return syms + } + var infos []struct { + Name string `json:"name"` + Kind int `json:"kind"` + Location struct { + Range Range `json:"range"` + } `json:"location"` + } + if err := json.Unmarshal(raw, &infos); err != nil { + return nil + } + out := make([]DocumentSymbol, 0, len(infos)) + for _, in := range infos { + out = append(out, DocumentSymbol{ + Name: in.Name, + Kind: in.Kind, + Range: in.Location.Range, + SelectionRange: in.Location.Range, + }) + } + return out +} + +// References 请求符号的引用位置。 +func (c *Client) References(ctx context.Context, uri string, pos Position, includeDecl bool) ([]Location, error) { + var locs []Location + err := c.conn.call(ctx, "textDocument/references", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "position": pos, + "context": map[string]any{"includeDeclaration": includeDecl}, + }, &locs) + return locs, err +} + +// Rename 请求把符号改名为 newName,返回跨文件的修改。 +func (c *Client) Rename(ctx context.Context, uri string, pos Position, newName string) (WorkspaceEdit, error) { + var we WorkspaceEdit + err := c.conn.call(ctx, "textDocument/rename", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "position": pos, + "newName": newName, + }, &we) + return we, err +} + +// CodeActions 请求指定范围上的代码动作(快速修复、整理 import 等)。 +func (c *Client) CodeActions(ctx context.Context, uri string, r Range, diags []Diagnostic) ([]CodeAction, error) { + var out []CodeAction + err := c.conn.call(ctx, "textDocument/codeAction", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "range": r, + "context": map[string]any{"diagnostics": diags}, + }, &out) + return out, err +} + +// OrganizeImports 请求整理 import,返回能直接落到缓冲区的修改。 +// +// gopls 把这个能力挂在 source.organizeImports 代码动作上;请求时用 only +// 过滤、不带诊断——补缺/删无用 import 不依赖某一条诊断。range 对 source +// 动作无意义,给零值即可。 +// +// 只收集本文件的改动:保存场景不会碰别的文件,遇到跨文件的 edit 直接忽略。 +func (c *Client) OrganizeImports(ctx context.Context, uri string) ([]TextEdit, error) { + var acts []CodeAction + err := c.conn.call(ctx, "textDocument/codeAction", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "range": Range{}, + "context": map[string]any{ + "diagnostics": []Diagnostic{}, + "only": []string{"source.organizeImports"}, + }, + }, &acts) + if err != nil { + return nil, err + } + var edits []TextEdit + for _, act := range acts { + if !strings.HasPrefix(act.Kind, "source.organizeImports") { + continue + } + if act.Edit == nil { + continue + } + edits = append(edits, act.Edit.ByFile()[uri]...) + } + return edits, nil +} + +// ExecuteCommand 让服务端执行一条命令。 +func (c *Client) ExecuteCommand(ctx context.Context, cmd Command) error { + return c.conn.call(ctx, "workspace/executeCommand", map[string]any{ + "command": cmd.Command, + "arguments": cmd.Arguments, + }, nil) +} + +// Format 请求整篇格式化。 +func (c *Client) Format(ctx context.Context, uri string, opts FormattingOptions) ([]TextEdit, error) { + var edits []TextEdit + err := c.conn.call(ctx, "textDocument/formatting", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "options": opts, + }, &edits) + if err != nil { + return nil, err + } + return edits, nil +} + +// Close 关闭语言服务器。 +func (c *Client) Close() error { + if c == nil || c.conn == nil { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + _ = c.conn.call(ctx, "shutdown", nil, nil) + _ = c.conn.notify("exit", nil) + c.conn.close() + if c.cmd != nil && c.cmd.Process != nil { + select { + case <-c.waitDone: + case <-time.After(2 * time.Second): + _ = c.cmd.Process.Kill() + } + } + return nil +} + +// ErrClosed 表示连接已关闭。 +var ErrClosed = errors.New("lsp: 连接已关闭") + +// InlayHints 请求一段范围内的内联提示。 +func (c *Client) InlayHints(ctx context.Context, uri string, rng Range) ([]InlayHint, error) { + var out []InlayHint + err := c.conn.call(ctx, "textDocument/inlayHint", map[string]any{ + "textDocument": TextDocumentIdentifier{URI: uri}, + "range": rng, + }, &out) + if err != nil { + return nil, err + } + return out, nil +} + +// WorkspaceSymbols 在整个工作区里按名字找符号。 +func (c *Client) WorkspaceSymbols(ctx context.Context, query string) ([]SymbolInformation, error) { + var out []SymbolInformation + err := c.conn.call(ctx, "workspace/symbol", map[string]any{ + "query": query, + }, &out) + if err != nil { + return nil, err + } + return out, nil +} diff --git a/internal/lsp/client_test.go b/internal/lsp/client_test.go new file mode 100644 index 0000000..92fce3a --- /dev/null +++ b/internal/lsp/client_test.go @@ -0,0 +1,496 @@ +package lsp + +import ( + "context" + "os" + "path/filepath" + "sort" + "strings" + "testing" + "time" +) + +// writeFile 写入测试文件。 +func writeFile(t *testing.T, path, content string) { + t.Helper() + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +// startTestClient 在临时模块里拉起 gopls,没有 gopls 时跳过测试。 +func startTestClient(t *testing.T) (*Client, string, chan []Diagnostic) { + t.Helper() + if testing.Short() { + t.Skip("集成测试需要 gopls") + } + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "go.mod"), "module demo\n\ngo 1.21\n") + diags := make(chan []Diagnostic, 16) + c, err := Start(context.Background(), Options{ + Root: dir, + Logf: t.Logf, + OnDiagnostics: func(uri string, version int, ds []Diagnostic) { + select { + case diags <- ds: + default: + } + }, + }) + if err != nil { + t.Skipf("gopls 不可用: %v", err) + } + t.Cleanup(func() { _ = c.Close() }) + return c, dir, diags +} + +func TestGoplsDiagnostics(t *testing.T) { + c, dir, diags := startTestClient(t) + src := "package main\n\nfunc main() {\n\tvar n int\n\tn = \"not an int\"\n\t_ = n\n}\n" + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + + deadline := time.After(90 * time.Second) + for { + select { + case ds := <-diags: + if len(ds) == 0 { + continue + } + for _, d := range ds { + if d.Severity == 1 { + return // 拿到了类型错误诊断。 + } + } + case <-deadline: + t.Fatal("等待诊断超时") + } + } +} + +func TestGoplsCompletion(t *testing.T) { + c, dir, _ := startTestClient(t) + src := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Pr\n}\n" + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + // 光标停在 "fmt.Pr" 之后。 + off := len(src) - len("\n}\n") + pos := OffsetToPosition(src, off) + + var items []CompletionItem + var err error + for i := 0; i < 10; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + items, err = c.Completion(ctx, uri, pos) + cancel() + if err == nil && len(items) > 0 { + break + } + time.Sleep(500 * time.Millisecond) + } + if err != nil { + t.Fatalf("补全失败: %v", err) + } + if len(items) == 0 { + t.Fatal("没有补全结果") + } + for _, it := range items { + if it.Label == "Println" { + return + } + } + t.Fatalf("补全里没有 Println,前几项:%+v", items[:min(3, len(items))]) +} + +// TestGoplsDidChange 验证增量同步:改坏代码后应收到新的诊断。 +func TestGoplsDidChange(t *testing.T) { + c, dir, diags := startTestClient(t) + src := "package main\n\nfunc main() {\n}\n" + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + + // 塞入一处类型错误。 + edited := "package main\n\nfunc main() {\n\tvar n int = \"boom\"\n\t_ = n\n}\n" + r, text, ok := DiffChange(src, edited) + if !ok { + t.Fatal("预期有改动") + } + if err := c.DidChange(uri, 2, []ContentChange{{Range: &r, Text: text}}); err != nil { + t.Fatal(err) + } + + deadline := time.After(90 * time.Second) + for { + select { + case ds := <-diags: + for _, d := range ds { + if d.Severity == 1 { + return + } + } + case <-deadline: + t.Fatal("改动后没有等到错误诊断") + } + } +} + +func TestGoplsDefinition(t *testing.T) { + c, dir, _ := startTestClient(t) + src := "package main\n\nfunc helper() {}\n\nfunc main() {\n\thelper()\n}\n" + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + // 光标停在 "helper()" 里的标识符上。 + off := strings.LastIndex(src, "helper") + 2 + pos := OffsetToPosition(src, off) + + var locs []Location + for i := 0; i < 10; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + var err error + locs, err = c.Definition(ctx, uri, pos) + cancel() + if err == nil && len(locs) > 0 { + break + } + time.Sleep(500 * time.Millisecond) + } + if len(locs) == 0 { + t.Fatal("没有定义位置") + } + if got, want := locs[0].Range.Start.Line, 2; got != want { + t.Fatalf("定义行号: got %d want %d", got, want) + } +} + +func TestGoplsDocumentSymbol(t *testing.T) { + c, dir, _ := startTestClient(t) + src := "package main\n\nfunc helper() {}\n\ntype point struct {\n\tX int\n\tY int\n}\n\nfunc main() {\n\thelper()\n\t_ = point{}\n}\n" + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + + var syms []DocumentSymbol + for i := 0; i < 10; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + var err error + syms, err = c.DocumentSymbol(ctx, uri) + cancel() + if err == nil && len(syms) > 0 { + break + } + time.Sleep(500 * time.Millisecond) + } + if len(syms) == 0 { + t.Fatal("没有取到符号") + } + for _, s := range syms { + if s.Name == "point" { + if len(s.Children) == 0 { + t.Fatalf("结构体 point 应当有字段子符号: %+v", s) + } + return + } + } + names := make([]string, 0, len(syms)) + for _, s := range syms { + names = append(names, s.Name) + } + t.Fatalf("没有找到 point,实际符号: %v", names) +} + +func TestGoplsReferencesAndRename(t *testing.T) { + c, dir, _ := startTestClient(t) + src := "package main\n\nfunc helper() {}\n\nfunc main() {\n\thelper()\n\thelper()\n}\n" + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + // helper 声明在第 2 行(0 起),名字从第 6 列开始 + pos := Position{Line: 2, Character: 6} + + var locs []Location + for i := 0; i < 10; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + var err error + locs, err = c.References(ctx, uri, pos, true) + cancel() + if err == nil && len(locs) >= 3 { + break + } + time.Sleep(500 * time.Millisecond) + } + if len(locs) < 3 { + t.Fatalf("helper 应当有 3 处引用(声明 + 2 次调用),实际 %d", len(locs)) + } + + var we WorkspaceEdit + var err error + for i := 0; i < 10; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + we, err = c.Rename(ctx, uri, pos, "assist") + cancel() + if err == nil && len(we.ByFile()) > 0 { + break + } + time.Sleep(500 * time.Millisecond) + } + changes := we.ByFile() + edits := changes[uri] + if len(edits) < 3 { + t.Fatalf("重命名应当产生至少 3 处修改,实际 %d (%v)", len(edits), err) + } + for _, e := range edits { + if e.NewText != "assist" { + t.Fatalf("修改内容应为 assist,实际 %q", e.NewText) + } + } +} + +func TestGoplsCodeActions(t *testing.T) { + c, dir, diags := startTestClient(t) + // 用了 fmt 但没 import:gopls 会报 undefined: fmt, + // 并把那条诊断原样带回来才会给出「Import "fmt"」的快速修复—— + // 这正好验证「诊断 → 动作」这条链路。 + src := "package main\n\nfunc main() {\n\tfmt.Println(1)\n}\n" + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + + // 等真实的诊断推送 + var got []Diagnostic + deadline := time.After(60 * time.Second) + for got == nil { + select { + case ds := <-diags: + if len(ds) > 0 { + got = ds + } + case <-deadline: + t.Fatal("没有收到诊断") + } + } + + rng := got[0].Range + var acts []CodeAction + for i := 0; i < 10; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + var err error + acts, err = c.CodeActions(ctx, uri, rng, got) + cancel() + if err == nil && len(acts) > 0 { + break + } + time.Sleep(300 * time.Millisecond) + } + if len(acts) == 0 { + t.Fatalf("诊断 %q 应当带来至少一条代码动作", got[0].Message) + } + // 至少有一条自带改动(gopls 的「Import \"fmt\"」就是 edit 形态) + withEdit := 0 + for _, a := range acts { + if a.Title == "" { + t.Fatalf("动作没有标题: %+v", a) + } + if a.Edit != nil && len(a.Edit.ByFile()) > 0 { + withEdit++ + } + } + if withEdit == 0 { + t.Fatalf("%d 条动作里没有一条带改动: %+v", len(acts), acts) + } +} + +// TestGoplsOrganizeImports 确认按 only=source.organizeImports 请求, +// gopls 给的是能直接落缓冲区的修改:删掉没用的 import、补上缺的。 +func TestGoplsOrganizeImports(t *testing.T) { + c, dir, diags := startTestClient(t) + + // fmt 引了没用(要删),strings 用了没引(要补)——一次覆盖两个方向。 + src := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tprintln(strings.ToUpper(\"a\"))\n}\n" + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + // 等诊断,说明 gopls 已把包分析完,动作才拿得到。 + select { + case <-diags: + case <-time.After(60 * time.Second): + t.Skip("没等到诊断") + } + + var edits []TextEdit + for i := 0; i < 10; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + var err error + edits, err = c.OrganizeImports(ctx, uri) + cancel() + if err == nil && len(edits) > 0 { + break + } + time.Sleep(300 * time.Millisecond) + } + if len(edits) == 0 { + t.Fatal("整理 import 应当给出修改(删 fmt / 补 strings),实际为空") + } + // gopls 给的是增量 delta 编辑(碎片),必须真正应用后看最终文本—— + // 直接拼 NewText 会得到 "srings" 这种假象。 + got := applyTextEdits(src, edits) + if !strings.Contains(got, `"strings"`) || strings.Contains(got, `"fmt"`) { + t.Fatalf("整理结果不对,期望 fmt→strings:\n%s", got) + } +} + +// applyTextEdits 按位置从后往前应用一组 LSP 修改,返回最终文本。 +func applyTextEdits(text string, edits []TextEdit) string { + sorted := append([]TextEdit(nil), edits...) + sort.Slice(sorted, func(i, j int) bool { + a, b := sorted[i].Range.Start, sorted[j].Range.Start + if a.Line != b.Line { + return a.Line > b.Line + } + return a.Character > b.Character + }) + for _, e := range sorted { + start := PositionToOffset(text, e.Range.Start) + end := PositionToOffset(text, e.Range.End) + text = text[:start] + e.NewText + text[end:] + } + return text +} + +// TestGoplsInlayHints 确认 gopls 会按我们的能力声明返回内联提示。 +func TestGoplsInlayHints(t *testing.T) { + c, dir, diags := startTestClient(t) + defer c.Close() + + src := `package main + +import "fmt" + +func add(a, b int) int { return a + b } + +func main() { + total := add(1, 2) + fmt.Println(total) +} +` + path := filepath.Join(dir, "main.go") + writeFile(t, path, src) + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + // 等诊断,说明 gopls 已经分析完这个包。 + select { + case <-diags: + case <-time.After(60 * time.Second): + t.Skip("没等到诊断") + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + lines := strings.Split(src, "\n") + hints, err := c.InlayHints(ctx, uri, Range{ + Start: Position{Line: 0, Character: 0}, + End: Position{Line: len(lines) - 1, Character: len(lines[len(lines)-1])}, + }) + if err != nil { + t.Fatalf("inlayHint: %v", err) + } + if len(hints) == 0 { + t.Fatal("gopls 没有返回内联提示(检查 initialize 里的 inlayHint 能力声明)") + } + var labels []string + for _, h := range hints { + labels = append(labels, h.Label.Text()) + } + t.Logf("提示: %v", labels) +} + +// TestGoplsWorkspaceSymbols 全工作区符号搜索。 +func TestGoplsWorkspaceSymbols(t *testing.T) { + c, dir, diags := startTestClient(t) + defer c.Close() + + writeFile(t, filepath.Join(dir, "main.go"), `package main + +import "fmt" + +func add(a, b int) int { return a + b } + +func main() { + fmt.Println(add(1, 2)) +} +`) + src := `package main + +// Twice 把数字翻倍。 +func Twice(n int) int { return n * 2 } +` + path := filepath.Join(dir, "greeter.go") + writeFile(t, path, src) + uri := PathToURI(path) + if err := c.DidOpen(uri, "go", 1, src); err != nil { + t.Fatal(err) + } + select { + case <-diags: + case <-time.After(60 * time.Second): + t.Skip("没等到诊断") + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + syms, err := c.WorkspaceSymbols(ctx, "Twice") + if err != nil { + t.Fatalf("workspace/symbol: %v", err) + } + if len(syms) == 0 { + t.Fatal("没有找到 Twice") + } + found := false + for _, s := range syms { + if s.Name == "Twice" { + found = true + if s.Location.URI == "" { + t.Fatal("符号缺少位置") + } + } + } + if !found { + t.Fatalf("结果里没有 Twice: %+v", syms) + } +} diff --git a/internal/lsp/jsonrpc.go b/internal/lsp/jsonrpc.go new file mode 100644 index 0000000..7595163 --- /dev/null +++ b/internal/lsp/jsonrpc.go @@ -0,0 +1,276 @@ +package lsp + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "strconv" + "strings" + "sync" +) + +// rpcError 是 JSON-RPC 的 error 对象。 +type rpcError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func (e *rpcError) Error() string { return fmt.Sprintf("lsp: %d %s", e.Code, e.Message) } + +// message 是 JSON-RPC 报文,请求、响应、通知共用。 +type message struct { + JSONRPC string `json:"jsonrpc"` + ID *int64 `json:"id,omitempty"` + Method string `json:"method,omitempty"` + Params json.RawMessage `json:"params,omitempty"` + Result json.RawMessage `json:"result,omitempty"` + Error *rpcError `json:"error,omitempty"` +} + +// conn 负责 Content-Length 分帧与请求/响应配对。 +type conn struct { + w io.WriteCloser + bw *bufio.Writer + r *bufio.Reader + + mu sync.Mutex + nextID int64 + pending map[int64]chan message + + writeCh chan []byte + done chan struct{} + once sync.Once + + onNotify func(method string, params json.RawMessage) + logf func(string, ...any) +} + +func newConn(w io.WriteCloser, r io.Reader, logf func(string, ...any)) *conn { + if logf == nil { + logf = func(string, ...any) {} + } + c := &conn{ + w: w, + bw: bufio.NewWriter(w), + r: bufio.NewReader(r), + pending: map[int64]chan message{}, + writeCh: make(chan []byte, 512), + done: make(chan struct{}), + logf: logf, + } + go c.writeLoop() + go c.readLoop() + return c +} + +// readFrame 读出一条报文,跳过头部。 +func readFrame(r *bufio.Reader) ([]byte, error) { + length := -1 + for { + line, err := r.ReadString('\n') + if err != nil { + return nil, err + } + line = strings.TrimRight(line, "\r\n") + if line == "" { + break + } + if k, v, ok := strings.Cut(line, ":"); ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") { + n, err := strconv.Atoi(strings.TrimSpace(v)) + if err != nil { + return nil, fmt.Errorf("lsp: 非法的 Content-Length %q", v) + } + length = n + } + } + if length < 0 { + return nil, errors.New("lsp: 缺少 Content-Length") + } + buf := make([]byte, length) + if _, err := io.ReadFull(r, buf); err != nil { + return nil, err + } + return buf, nil +} + +func (c *conn) writeLoop() { + for { + select { + case body := <-c.writeCh: + if _, err := fmt.Fprintf(c.bw, "Content-Length: %d\r\n\r\n", len(body)); err != nil { + c.close() + return + } + if _, err := c.bw.Write(body); err != nil { + c.close() + return + } + if err := c.bw.Flush(); err != nil { + c.close() + return + } + case <-c.done: + return + } + } +} + +func (c *conn) readLoop() { + defer c.close() + for { + body, err := readFrame(c.r) + if err != nil { + return + } + var m message + if err := json.Unmarshal(body, &m); err != nil { + c.logf("lsp: 无法解析报文: %v", err) + continue + } + switch { + case m.Method == "" && m.ID != nil: + c.mu.Lock() + ch := c.pending[*m.ID] + c.mu.Unlock() + if ch != nil { + select { + case ch <- m: + default: + } + } + case m.Method != "" && m.ID != nil: + go c.answer(m) + case m.Method != "": + if c.onNotify != nil { + c.onNotify(m.Method, m.Params) + } + } + } +} + +// answer 回应服务端发来的请求,主要是 gopls 的配置询问。 +func (c *conn) answer(m message) { + var result any + switch m.Method { + case "workspace/configuration": + var p struct { + Items []json.RawMessage `json:"items"` + } + _ = json.Unmarshal(m.Params, &p) + // gopls 会问客户端要 "gopls" 这一节的设置;回 null 等于「什么都不配」, + // 而它默认不给内联提示,所以这里显式打开。 + items := make([]any, len(p.Items)) + for i := range items { + items[i] = goplsSettings() + } + result = items + case "workspace/workspaceFolders": + result = []WorkspaceFolder{} + default: + result = nil + } + b, err := json.Marshal(result) + if err != nil { + b = []byte("null") + } + msg := message{JSONRPC: "2.0", ID: m.ID, Result: b} + body, err := json.Marshal(msg) + if err != nil { + return + } + select { + case c.writeCh <- body: + case <-c.done: + } +} + +// send 把报文排进写队列,不阻塞调用方。 +func (c *conn) send(m message) error { + m.JSONRPC = "2.0" + body, err := json.Marshal(m) + if err != nil { + return err + } + select { + case c.writeCh <- body: + return nil + case <-c.done: + return errors.New("lsp: 连接已关闭") + } +} + +// notify 发送通知。 +func (c *conn) notify(method string, params any) error { + raw, err := json.Marshal(params) + if err != nil { + return err + } + return c.send(message{Method: method, Params: raw}) +} + +// call 发送请求并等待响应。 +func (c *conn) call(ctx context.Context, method string, params any, result any) error { + raw, err := json.Marshal(params) + if err != nil { + return err + } + c.mu.Lock() + c.nextID++ + id := c.nextID + ch := make(chan message, 1) + c.pending[id] = ch + c.mu.Unlock() + + defer func() { + c.mu.Lock() + delete(c.pending, id) + c.mu.Unlock() + }() + + if err := c.send(message{ID: &id, Method: method, Params: raw}); err != nil { + return err + } + select { + case m := <-ch: + if m.Error != nil { + return m.Error + } + if result != nil && len(m.Result) > 0 { + return json.Unmarshal(m.Result, result) + } + return nil + case <-ctx.Done(): + return ctx.Err() + case <-c.done: + return errors.New("lsp: 连接已关闭") + } +} + +// close 关闭连接,可重复调用。 +func (c *conn) close() { + c.once.Do(func() { + close(c.done) + _ = c.w.Close() + }) +} + +// goplsSettings 是给 gopls 的默认设置。 +// +// 只开「读代码有帮助」的提示,常量值/未用变量这类噪音保持关闭。 +// 注意只写 hints:加 ui 这类不认识的节点会被 gopls 报「unexpected setting」。 +func goplsSettings() map[string]any { + hints := map[string]any{ + "assignVariableTypes": true, + "compositeLiteralFields": true, + "compositeLiteralTypes": true, + "constantValues": false, + "functionTypeParameters": true, + "parameterNames": true, + "rangeVariableTypes": true, + "unusedVariableNames": false, + } + return map[string]any{"hints": hints} +} diff --git a/internal/lsp/procattr_other.go b/internal/lsp/procattr_other.go new file mode 100644 index 0000000..359a570 --- /dev/null +++ b/internal/lsp/procattr_other.go @@ -0,0 +1,10 @@ +//go:build !windows + +package lsp + +import "syscall" + +// procAttr 在非 Windows 平台不需要额外属性。 +func procAttr() *syscall.SysProcAttr { + return nil +} diff --git a/internal/lsp/procattr_windows.go b/internal/lsp/procattr_windows.go new file mode 100644 index 0000000..7dbc32c --- /dev/null +++ b/internal/lsp/procattr_windows.go @@ -0,0 +1,10 @@ +//go:build windows + +package lsp + +import "syscall" + +// procAttr 隐藏 gopls 子进程的控制台窗口。 +func procAttr() *syscall.SysProcAttr { + return &syscall.SysProcAttr{HideWindow: true} +} diff --git a/internal/lsp/protocol.go b/internal/lsp/protocol.go new file mode 100644 index 0000000..26ecfef --- /dev/null +++ b/internal/lsp/protocol.go @@ -0,0 +1,376 @@ +// Package lsp 实现一个最小可用的 LSP 客户端,通过 stdio 与 gopls 通信。 +// +// 只实现 MyGoland 需要的部分:初始化、文档同步、诊断、补全、悬停、跳转定义、 +// 引用、重命名、代码动作、格式化、内联提示。 +package lsp + +import ( + "encoding/json" + "strings" +) + +// Position 是 LSP 的位置:行号与行内偏移都是 0 起,Character 以 UTF-16 码元计。 +type Position struct { + Line int `json:"line"` + Character int `json:"character"` +} + +// Range 是文本区间。 +type Range struct { + Start Position `json:"start"` + End Position `json:"end"` +} + +// Location 是文件中的一个区间。 +type Location struct { + URI string `json:"uri"` + Range Range `json:"range"` +} + +// TextEdit 是一次文本替换。 +type TextEdit struct { + Range Range `json:"range"` + NewText string `json:"newText"` +} + +// TextDocumentItem 是 didOpen 传入的文档。 +type TextDocumentItem struct { + URI string `json:"uri"` + LanguageID string `json:"languageId"` + Version int `json:"version"` + Text string `json:"text"` +} + +// VersionedTextDocumentIdentifier 标识某个版本的文档。 +type VersionedTextDocumentIdentifier struct { + URI string `json:"uri"` + Version int `json:"version"` +} + +// TextDocumentIdentifier 只标识文档。 +type TextDocumentIdentifier struct { + URI string `json:"uri"` +} + +// ContentChange 是 didChange 的一项增量修改。 +type ContentChange struct { + Range *Range `json:"range,omitempty"` + Text string `json:"text"` +} + +// MarkupContent 是 LSP 的富文本,也接受纯字符串的写法。 +type MarkupContent struct { + Kind string `json:"kind"` + Value string `json:"value"` +} + +// UnmarshalJSON 让 MarkupContent 兼容 "text" 与 {kind,value} 两种形式。 +func (m *MarkupContent) UnmarshalJSON(b []byte) error { + if len(b) > 0 && b[0] == '"' { + var s string + if err := json.Unmarshal(b, &s); err != nil { + return err + } + m.Kind, m.Value = "plaintext", s + return nil + } + type alias MarkupContent + var a alias + if err := json.Unmarshal(b, &a); err != nil { + return err + } + *m = MarkupContent(a) + return nil +} + +// CompletionItem 是一条补全建议。 +type CompletionItem struct { + Label string `json:"label"` + Kind int `json:"kind"` + Detail string `json:"detail"` + Documentation json.RawMessage `json:"documentation"` + InsertText string `json:"insertText"` + TextEdit *TextEdit `json:"textEdit"` + FilterText string `json:"filterText"` + SortText string `json:"sortText"` +} + +// CompletionList 是补全结果的一种包装。 +type CompletionList struct { + Items []CompletionItem `json:"items"` + IsIncomplete bool `json:"isIncomplete"` +} + +// DocumentationText 把 documentation 字段统一成纯文本。 +func (c CompletionItem) DocumentationText() string { + if len(c.Documentation) == 0 { + return "" + } + var m MarkupContent + if err := json.Unmarshal(c.Documentation, &m); err == nil { + return m.Value + } + return "" +} + +// Hover 是悬停信息。 +type Hover struct { + Contents json.RawMessage `json:"contents"` + Range *Range `json:"range,omitempty"` +} + +// Text 把悬停内容统一成纯文本。 +func (h Hover) Text() string { + if len(h.Contents) == 0 { + return "" + } + var m MarkupContent + if err := json.Unmarshal(h.Contents, &m); err == nil { + return m.Value + } + var list []MarkupContent + if err := json.Unmarshal(h.Contents, &list); err == nil { + out := "" + for _, x := range list { + out += x.Value + "\n\n" + } + return out + } + var arr []string + if err := json.Unmarshal(h.Contents, &arr); err == nil { + out := "" + for _, x := range arr { + out += x + "\n\n" + } + return out + } + return "" +} + +// Diagnostic 是一条诊断。 +type Diagnostic struct { + Range Range `json:"range"` + Severity int `json:"severity"` + Source string `json:"source"` + Message string `json:"message"` + // Data 是服务端附带的载荷,请求代码动作时必须原样带回去, + // 否则 gopls 认不出是哪条诊断,也就不会给出对应的快速修复。 + Data json.RawMessage `json:"data,omitempty"` +} + +// PublishDiagnosticsParams 是诊断通知的参数。 +type PublishDiagnosticsParams struct { + URI string `json:"uri"` + Version int `json:"version"` + Diagnostics []Diagnostic `json:"diagnostics"` +} + +// WorkspaceEdit 是一组跨文件的修改,两种形态择一出现。 +type WorkspaceEdit struct { + Changes map[string][]TextEdit `json:"changes"` + // DocumentChanges 是带版本的形态,gopls 有时用它。 + DocumentChanges []struct { + TextDocument struct { + URI string `json:"uri"` + } `json:"textDocument"` + Edits []TextEdit `json:"edits"` + } `json:"documentChanges"` +} + +// Command 是服务端提供的一条可执行命令。 +type Command struct { + Title string `json:"title"` + Command string `json:"command"` + Arguments []any `json:"arguments,omitempty"` +} + +// CodeAction 是一条代码动作,改动可能直接给 edit,也可能给一条命令。 +type CodeAction struct { + Title string `json:"title"` + Kind string `json:"kind"` + Edit *WorkspaceEdit `json:"edit,omitempty"` + Command *Command `json:"command,omitempty"` + Diagnostics []Diagnostic `json:"diagnostics,omitempty"` + IsPreferred bool `json:"isPreferred,omitempty"` +} + +// ByFile 把两种形态合并成 uri → 修改列表。 +func (w WorkspaceEdit) ByFile() map[string][]TextEdit { + out := map[string][]TextEdit{} + for uri, edits := range w.Changes { + out[uri] = append(out[uri], edits...) + } + for _, dc := range w.DocumentChanges { + if dc.TextDocument.URI == "" { + continue + } + out[dc.TextDocument.URI] = append(out[dc.TextDocument.URI], dc.Edits...) + } + return out +} + +// DocumentSymbol 是一个符号,可能带子符号。 +type DocumentSymbol struct { + Name string `json:"name"` + Detail string `json:"detail"` + Kind int `json:"kind"` + Range Range `json:"range"` + SelectionRange Range `json:"selectionRange"` + Children []DocumentSymbol `json:"children"` +} + +// FormattingOptions 是格式化请求的参数。 +type FormattingOptions struct { + TabSize int `json:"tabSize"` + InsertSpaces bool `json:"insertSpaces"` +} + +// WorkspaceFolder 是工作区目录。 +type WorkspaceFolder struct { + URI string `json:"uri"` + Name string `json:"name"` +} + +// InitializeParams 是初始化请求的参数,只填 mygo 用得到的字段。 +type InitializeParams struct { + ProcessID int `json:"processId"` + ClientInfo *ClientInfo `json:"clientInfo,omitempty"` + RootURI string `json:"rootUri"` + RootPath string `json:"rootPath,omitempty"` + WorkspaceFolders []WorkspaceFolder `json:"workspaceFolders,omitempty"` + Capabilities ClientCapabilities `json:"capabilities"` + InitializationOptions map[string]any `json:"initializationOptions,omitempty"` +} + +// ClientInfo 描述客户端。 +type ClientInfo struct { + Name string `json:"name"` + Version string `json:"version"` +} + +// ClientCapabilities 是客户端能力声明。 +type ClientCapabilities struct { + Workspace WorkspaceCapabilities `json:"workspace"` + TextDocument TextDocumentCapabilities `json:"textDocument"` + Window map[string]any `json:"window,omitempty"` +} + +// WorkspaceCapabilities 声明工作区能力。 +type WorkspaceCapabilities struct { + WorkspaceFolders bool `json:"workspaceFolders"` + Configuration bool `json:"configuration"` +} + +// TextDocumentCapabilities 声明文档能力。 +type TextDocumentCapabilities struct { + Synchronization SynchronizationCapabilities `json:"synchronization"` + Completion map[string]any `json:"completion,omitempty"` + Hover map[string]any `json:"hover,omitempty"` + Definition map[string]any `json:"definition,omitempty"` + PublishDiagnostics map[string]any `json:"publishDiagnostics,omitempty"` + Formatting map[string]any `json:"formatting,omitempty"` + DocumentSymbol map[string]any `json:"documentSymbol,omitempty"` + // InlayHint 不能省:gopls 只有在客户端声明了这个能力时才回内联提示, + // 没声明时 textDocument/inlayHint 只会返回空数组。 + InlayHint map[string]any `json:"inlayHint,omitempty"` +} + +// SynchronizationCapabilities 声明同步能力。 +type SynchronizationCapabilities struct { + DynamicRegistration bool `json:"dynamicRegistration"` + DidSave bool `json:"didSave"` + WillSave bool `json:"willSave"` +} + +// InitializeResult 是初始化结果。 +type InitializeResult struct { + Capabilities json.RawMessage `json:"capabilities"` + ServerInfo *ServerInfo `json:"serverInfo,omitempty"` +} + +// ServerInfo 描述服务端。 +type ServerInfo struct { + Name string `json:"name"` + Version string `json:"version"` +} + +// defaultCapabilities 返回 MyGoland 声明的能力集合。 +func defaultCapabilities() ClientCapabilities { + return ClientCapabilities{ + Workspace: WorkspaceCapabilities{WorkspaceFolders: true, Configuration: true}, + TextDocument: TextDocumentCapabilities{ + Synchronization: SynchronizationCapabilities{DidSave: true}, + Completion: map[string]any{ + "completionItem": map[string]any{ + "snippetSupport": false, + "documentationFormat": []string{"markdown", "plaintext"}, + }, + "contextSupport": true, + }, + Hover: map[string]any{"contentFormat": []string{"markdown", "plaintext"}}, + Definition: map[string]any{"linkSupport": false}, + PublishDiagnostics: map[string]any{"relatedInformation": false}, + Formatting: map[string]any{}, + DocumentSymbol: map[string]any{"hierarchicalDocumentSymbolSupport": true}, + InlayHint: map[string]any{ + "dynamicRegistration": false, + "resolveSupport": map[string]any{ + "properties": []string{ + "tooltip", "textEdits", "label.tooltip", "label.location", "label.command", + }, + }, + }, + }, + } +} + +// InlayHint 是一条内联提示(参数名、类型等)。 +type InlayHint struct { + Position Position `json:"position"` + Label InlayLabel `json:"label"` + Kind int `json:"kind,omitempty"` + PaddingLeft bool `json:"paddingLeft,omitempty"` + PaddingRight bool `json:"paddingRight,omitempty"` +} + +// InlayLabel 是提示文字:协议允许一个字符串,或者若干带位置的部分。 +type InlayLabel struct { + Parts []string +} + +func (l *InlayLabel) UnmarshalJSON(data []byte) error { + var s string + if err := json.Unmarshal(data, &s); err == nil { + l.Parts = []string{s} + return nil + } + var parts []struct { + Value string `json:"value"` + } + if err := json.Unmarshal(data, &parts); err != nil { + return err + } + l.Parts = l.Parts[:0] + for _, p := range parts { + l.Parts = append(l.Parts, p.Value) + } + return nil +} + +// Text 把各段拼成一行文字。 +func (l InlayLabel) Text() string { + return strings.Join(l.Parts, "") +} + +// SymbolInformation 是 workspace/symbol 返回的一条符号。 +type SymbolInformation struct { + Name string `json:"name"` + Kind int `json:"kind"` + ContainerName string `json:"containerName,omitempty"` + Location struct { + URI string `json:"uri"` + Range Range `json:"range"` + } `json:"location"` + // 新版协议允许 WorkspaceSymbol 用 location.uri,也可能给 targetUri。 + TargetURI string `json:"targetUri,omitempty"` +} diff --git a/internal/lsp/uri.go b/internal/lsp/uri.go new file mode 100644 index 0000000..0802d0b --- /dev/null +++ b/internal/lsp/uri.go @@ -0,0 +1,139 @@ +package lsp + +import ( + "net/url" + "runtime" + "strings" + "unicode/utf16" + "unicode/utf8" +) + +// PathToURI 把本地路径转成 file URI。 +// +// Windows 上 D:\a\b 变成 file:///D:/a/b;非 ASCII 字符按 UTF-8 百分号编码。 +func PathToURI(path string) string { + p := strings.ReplaceAll(path, "\\", "/") + if runtime.GOOS == "windows" && !strings.HasPrefix(p, "/") { + p = "/" + p + } + u := url.URL{Scheme: "file", Path: p} + return u.String() +} + +// URIToPath 把 file URI 还原成本地路径。 +func URIToPath(uri string) string { + u, err := url.Parse(uri) + if err != nil { + return "" + } + p, err := url.PathUnescape(u.Path) + if err != nil { + p = u.Path + } + if runtime.GOOS == "windows" { + p = strings.TrimPrefix(p, "/") + p = strings.ReplaceAll(p, "/", "\\") + } + return p +} + +// UTF16Len 返回 s 的 UTF-16 码元数,LSP 的 Character 以此计数。 +func UTF16Len(s string) int { + n := 0 + for _, r := range s { + n += len(utf16.Encode([]rune{r})) + } + return n +} + +// UTF16ToByte 把 s 中前 n 个 UTF-16 码元对应的字节数返回。 +func UTF16ToByte(s string, n int) int { + if n <= 0 { + return 0 + } + count := 0 + for i, r := range s { + if count >= n { + return i + } + if r > 0xFFFF { + count += 2 + if count > n { + // 落在代理对中间,退到字符起始位置。 + return i + } + } else { + count++ + } + } + return len(s) +} + +// OffsetToPosition 把字节偏移转成 LSP 位置。 +func OffsetToPosition(text string, off int) Position { + if off < 0 { + off = 0 + } + if off > len(text) { + off = len(text) + } + head := text[:off] + line := strings.Count(head, "\n") + start := strings.LastIndexByte(head, '\n') + 1 + return Position{Line: line, Character: UTF16Len(head[start:])} +} + +// PositionToOffset 把 LSP 位置转成字节偏移,越界时收敛到最近的合法位置。 +func PositionToOffset(text string, p Position) int { + off := 0 + for i := 0; i < p.Line; i++ { + idx := strings.IndexByte(text[off:], '\n') + if idx < 0 { + return len(text) + } + off += idx + 1 + } + end := strings.IndexByte(text[off:], '\n') + line := text[off:] + if end >= 0 { + line = text[off : off+end] + } + return off + UTF16ToByte(line, p.Character) +} + +// IsGoFile 判断路径是否是 Go 源文件。 +func IsGoFile(path string) bool { + return strings.HasSuffix(strings.ToLower(path), ".go") +} + +// DiffChange 计算把 old 变成 new 的最小单区间修改。 +// +// 前后缀按 rune 对齐比较,避免把 UTF-8 多字节字符切断; +// 多光标同时编辑时区间会覆盖得比实际更宽,但结果依然正确。 +func DiffChange(old, new string) (Range, string, bool) { + if old == new { + return Range{}, "", false + } + // 公共前缀,按 rune 前进。 + i := 0 + for i < len(old) && i < len(new) { + r, size := utf8.DecodeRuneInString(old[i:]) + s, size2 := utf8.DecodeRuneInString(new[i:]) + if r != s || size != size2 { + break + } + i += size + } + // 公共后缀,按 rune 后退。 + j, k := len(old), len(new) + for j > i && k > i { + r, size := utf8.DecodeLastRuneInString(old[:j]) + s, size2 := utf8.DecodeLastRuneInString(new[:k]) + if r != s || size != size2 { + break + } + j -= size + k -= size2 + } + return Range{Start: OffsetToPosition(old, i), End: OffsetToPosition(old, j)}, new[i:k], true +} diff --git a/internal/lsp/uri_test.go b/internal/lsp/uri_test.go new file mode 100644 index 0000000..d4586da --- /dev/null +++ b/internal/lsp/uri_test.go @@ -0,0 +1,86 @@ +package lsp + +import ( + "runtime" + "testing" +) + +func TestPathURIRoundTrip(t *testing.T) { + var path string + if runtime.GOOS == "windows" { + path = `D:\WorkSpaces\测试\main.go` + } else { + path = "/home/user/测试/main.go" + } + uri := PathToURI(path) + got := URIToPath(uri) + if got != path { + t.Fatalf("round trip: got %q want %q (uri %q)", got, path, uri) + } +} + +func TestOffsetPositionCJK(t *testing.T) { + text := "package main\n\nfunc 你好() {\n\tprintln(1)\n}\n" + // 第二行开头(换行后)应是 Line 1, Character 0。 + off := len("package main\n") + if got := OffsetToPosition(text, off); got != (Position{Line: 1, Character: 0}) { + t.Fatalf("line start: %+v", got) + } + // "func " 之后是 4 个 ASCII 字符,中文每个占 1 个 UTF-16 码元。 + off2 := len("package main\n\nfunc ") + if got := OffsetToPosition(text, off2); got != (Position{Line: 2, Character: 5}) { + t.Fatalf("after func: %+v", got) + } + // 中文后位置:5 + 2 = 7。 + off3 := off2 + len("你好") + if got := OffsetToPosition(text, off3); got != (Position{Line: 2, Character: 7}) { + t.Fatalf("after cjk: %+v", got) + } + if back := PositionToOffset(text, Position{Line: 2, Character: 7}); back != off3 { + t.Fatalf("back: got %d want %d", back, off3) + } +} + +func TestLenSurrogatePair(t *testing.T) { + // 表情符号占 2 个 UTF-16 码元。 + if got := UTF16Len("a😀b"); got != 4 { + t.Fatalf("UTF16Len: got %d want 4", got) + } + if got := UTF16ToByte("a😀b", 3); got != len("a😀") { + t.Fatalf("UTF16ToByte: got %d want %d", got, len("a😀")) + } +} + +func TestDiffChange(t *testing.T) { + tests := []struct { + name string + old, new string + text string + ok bool + }{ + {"insert", "package main\n", "package main\n\n", "\n", true}, + {"replace cjk", "var 甲 = 1", "var 乙 = 1", "乙", true}, + {"delete", "abc\ndef", "abc", "", true}, + {"same", "abc", "abc", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r, text, ok := DiffChange(tt.old, tt.new) + if ok != tt.ok { + t.Fatalf("ok: got %v want %v", ok, tt.ok) + } + if !ok { + return + } + if text != tt.text { + t.Fatalf("text: got %q want %q", text, tt.text) + } + // 用 range 把改动应用回 old,结果必须等于 new。 + start := PositionToOffset(tt.old, r.Start) + end := PositionToOffset(tt.old, r.End) + if applied := tt.old[:start] + text + tt.old[end:]; applied != tt.new { + t.Fatalf("apply: got %q want %q", applied, tt.new) + } + }) + } +} diff --git a/internal/task/kill_other.go b/internal/task/kill_other.go new file mode 100644 index 0000000..8b0b45f --- /dev/null +++ b/internal/task/kill_other.go @@ -0,0 +1,21 @@ +//go:build !windows + +package task + +import ( + "errors" + "os" + "syscall" +) + +// procAttr 让子进程自成一个进程组,便于整组结束。 +func procAttr() *syscall.SysProcAttr { + return &syscall.SysProcAttr{Setpgid: true} +} + +// killTree 结束整个进程组。 +func killTree(pid int) { + if err := syscall.Kill(-pid, syscall.SIGKILL); err != nil && !errors.Is(err, os.ErrProcessDone) { + _ = syscall.Kill(pid, syscall.SIGKILL) + } +} diff --git a/internal/task/kill_windows.go b/internal/task/kill_windows.go new file mode 100644 index 0000000..92b9249 --- /dev/null +++ b/internal/task/kill_windows.go @@ -0,0 +1,19 @@ +//go:build windows + +package task + +import ( + "os/exec" + "strconv" + "syscall" +) + +// procAttr 隐藏子进程的控制台窗口。 +func procAttr() *syscall.SysProcAttr { + return &syscall.SysProcAttr{HideWindow: true} +} + +// killTree 结束整个进程树,避免 go run 派生的程序残留。 +func killTree(pid int) { + _ = exec.Command("taskkill", "/PID", strconv.Itoa(pid), "/T", "/F").Run() +} diff --git a/internal/task/task.go b/internal/task/task.go new file mode 100644 index 0000000..37a392f --- /dev/null +++ b/internal/task/task.go @@ -0,0 +1,93 @@ +// Package task 负责启动外部命令并流式输出,供运行面板使用。 +package task + +import ( + "bufio" + "io" + "os/exec" + "sync" +) + +// Task 是一次命令执行。 +type Task struct { + // Name 是命令名,用于界面显示。 + Name string + // Lines 按输出顺序流出标准输出与标准错误的每一行,结束时关闭。 + Lines chan string + + cmd *exec.Cmd + done chan struct{} + mu sync.Mutex + stopped bool +} + +// Start 在 dir 下启动命令,标准输出与标准错误合并成有序的行。 +func Start(dir, name string, args ...string) (*Task, error) { + cmd := exec.Command(name, args...) + cmd.Dir = dir + cmd.SysProcAttr = procAttr() + + pr, pw := io.Pipe() + cmd.Stdout = pw + cmd.Stderr = pw + + if err := cmd.Start(); err != nil { + _ = pw.Close() + _ = pr.Close() + return nil, err + } + + t := &Task{ + Name: name, + Lines: make(chan string, 2048), + cmd: cmd, + done: make(chan struct{}), + } + + go func() { + defer close(t.Lines) + sc := bufio.NewScanner(pr) + sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024) + for sc.Scan() { + t.Lines <- sc.Text() + } + _ = pr.Close() + }() + + go func() { + _ = cmd.Wait() + _ = pw.Close() + close(t.done) + }() + + return t, nil +} + +// Wait 阻塞到命令结束。 +func (t *Task) Wait() { <-t.done } + +// ExitCode 返回退出码,进程还没结束时为 -1。 +func (t *Task) ExitCode() int { + if t == nil || t.cmd == nil || t.cmd.ProcessState == nil { + return -1 + } + return t.cmd.ProcessState.ExitCode() +} + +// Stopped 报告是否被主动停止。 +func (t *Task) Stopped() bool { + t.mu.Lock() + defer t.mu.Unlock() + return t.stopped +} + +// Stop 结束整个进程树,go run 派生的子进程也一并结束。 +func (t *Task) Stop() { + if t == nil || t.cmd == nil || t.cmd.Process == nil { + return + } + t.mu.Lock() + t.stopped = true + t.mu.Unlock() + killTree(t.cmd.Process.Pid) +} diff --git a/internal/task/task_test.go b/internal/task/task_test.go new file mode 100644 index 0000000..52f0ca7 --- /dev/null +++ b/internal/task/task_test.go @@ -0,0 +1,60 @@ +package task + +import ( + "strings" + "testing" + "time" +) + +func TestRunCollectsOutput(t *testing.T) { + tk, err := Start(".", "go", "version") + if err != nil { + t.Fatalf("启动失败: %v", err) + } + var lines []string + for l := range tk.Lines { + lines = append(lines, l) + } + tk.Wait() + if code := tk.ExitCode(); code != 0 { + t.Fatalf("退出码 %d", code) + } + if len(lines) == 0 { + t.Fatal("没有输出") + } + if !strings.Contains(strings.Join(lines, "\n"), "go version") { + t.Fatalf("输出异常: %v", lines) + } +} + +func TestExitCodeOfFailure(t *testing.T) { + tk, err := Start(".", "go", "tool", "no-such-tool") + if err != nil { + t.Fatalf("启动失败: %v", err) + } + var lines []string + for l := range tk.Lines { + lines = append(lines, l) + } + tk.Wait() + if code := tk.ExitCode(); code == 0 { + t.Fatalf("预期非零退出码,实际 0,输出: %v", lines) + } + if len(lines) == 0 { + t.Fatal("失败命令也应有输出") + } +} + +func TestStop(t *testing.T) { + // 用 go 自身跑一个必然耗时的命令,然后中途结束。 + tk, err := Start(".", "go", "build", "-a", "std") + if err != nil { + t.Fatalf("启动失败: %v", err) + } + time.Sleep(300 * time.Millisecond) + tk.Stop() + tk.Wait() + if !tk.Stopped() { + t.Fatal("Stopped 应为 true") + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..6cf7aee --- /dev/null +++ b/main.go @@ -0,0 +1,25 @@ +// MyGoland 是一个用 mygo + Go 实现的轻量级 Go IDE。 +package main + +import ( + "log" + "os" + + "github.com/egoist/mygo" + + "mygoland/internal/app" +) + +func main() { + app.SetupLog() + // 单实例:第二个进程把命令行转交给已运行的实例后直接退出, + // 这样双击文件不会开出第二个窗口。 + if !app.ClaimSingleInstance("mygoland", os.Args[1:]) { + return + } + a := app.New() + mygo.App.WhenReady(a.Start) + if err := mygo.App.Run(); err != nil { + log.Fatal(err) + } +} diff --git a/mygo.json b/mygo.json new file mode 100644 index 0000000..ceffeac --- /dev/null +++ b/mygo.json @@ -0,0 +1,9 @@ +{ + "name": "MyGoland", + "slug": "mygoland", + "identifier": "dev.cgh.mygoland", + "version": "0.1.0", + "copyright": "Copyright © 2026 曹港回", + "main": ".", + "icon": "resources/icon.png" +} diff --git a/resources/ghostty-vt.dll b/resources/ghostty-vt.dll new file mode 100644 index 0000000..2e009a0 Binary files /dev/null and b/resources/ghostty-vt.dll differ diff --git a/resources/icon.png b/resources/icon.png new file mode 100644 index 0000000..dc486e8 Binary files /dev/null and b/resources/icon.png differ diff --git a/rsrc_windows_amd64.syso b/rsrc_windows_amd64.syso new file mode 100644 index 0000000..c7cc89e Binary files /dev/null and b/rsrc_windows_amd64.syso differ diff --git a/tools/click/main.go b/tools/click/main.go new file mode 100644 index 0000000..abbad91 --- /dev/null +++ b/tools/click/main.go @@ -0,0 +1,49 @@ +// click :在窗口坐标里点一下 +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "os" + "strconv" +) + +func main() { + sock, win := os.Args[1], os.Args[2] + x, _ := strconv.ParseFloat(os.Args[3], 64) + y, _ := strconv.ParseFloat(os.Args[4], 64) + // 可选的第五个参数:left(默认)/ right / middle + button := "left" + if len(os.Args) > 5 { + button = os.Args[5] + } + id, _ := strconv.Atoi(win) + c, err := net.Dial("unix", sock) + if err != nil { + fmt.Println("连接失败:", err) + os.Exit(1) + } + defer c.Close() + enc := json.NewEncoder(c) + dec := json.NewDecoder(bufio.NewReader(c)) + evs := []map[string]any{ + {"type": "pointerMove", "x": x, "y": y}, + {"type": "pointerDown", "x": x, "y": y, "button": button}, + {"type": "pointerUp", "x": x, "y": y, "button": button}, + } + if err := enc.Encode(map[string]any{"id": 1, "method": "input", "params": map[string]any{"window": id, "events": evs}}); err != nil { + fmt.Println("发送失败:", err) + os.Exit(1) + } + var resp struct { + Error any `json:"error"` + } + _ = dec.Decode(&resp) + if resp.Error != nil { + fmt.Printf("失败: %+v\n", resp.Error) + return + } + fmt.Println("点击完成", x, y) +} diff --git a/tools/keys/main.go b/tools/keys/main.go new file mode 100644 index 0000000..b51c233 --- /dev/null +++ b/tools/keys/main.go @@ -0,0 +1,44 @@ +// keys :发送按键(语法同菜单快捷键,如 CmdOrCtrl+P) +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "os" + "strconv" +) + +func main() { + sock, win := os.Args[1], os.Args[2] + id, _ := strconv.Atoi(win) + c, err := net.Dial("unix", sock) + if err != nil { + fmt.Println("连接失败:", err) + os.Exit(1) + } + defer c.Close() + enc := json.NewEncoder(c) + dec := json.NewDecoder(bufio.NewReader(c)) + for _, k := range os.Args[3:] { + var evs []map[string]any + if len(k) > 5 && k[:5] == "text=" { + evs = []map[string]any{{"type": "text", "text": k[5:]}} + } else { + evs = []map[string]any{{"type": "keyDown", "key": k}, {"type": "keyUp", "key": k}} + } + if err := enc.Encode(map[string]any{"id": 1, "method": "input", "params": map[string]any{"window": id, "events": evs}}); err != nil { + fmt.Println("发送失败:", err) + os.Exit(1) + } + var resp struct { + Error any `json:"error"` + } + _ = dec.Decode(&resp) + if resp.Error != nil { + fmt.Printf("失败 %s: %+v\n", k, resp.Error) + } + } + fmt.Println("按键完成") +} diff --git a/tools/menu/main.go b/tools/menu/main.go new file mode 100644 index 0000000..5d4b92d --- /dev/null +++ b/tools/menu/main.go @@ -0,0 +1,34 @@ +// menu :点菜单项,路径如 编辑 快速打开文件 +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "os" + "strconv" +) + +func main() { + sock, win := os.Args[1], os.Args[2] + id, _ := strconv.Atoi(win) + c, err := net.Dial("unix", sock) + if err != nil { + fmt.Println("连接失败:", err) + os.Exit(1) + } + defer c.Close() + enc := json.NewEncoder(c) + dec := json.NewDecoder(bufio.NewReader(c)) + _ = enc.Encode(map[string]any{"id": 1, "method": "menu", "params": map[string]any{"window": id, "path": os.Args[3:]}}) + var resp struct { + Error any `json:"error"` + } + _ = dec.Decode(&resp) + if resp.Error != nil { + fmt.Printf("失败: %+v\n", resp.Error) + return + } + fmt.Println("菜单已触发") +} diff --git a/tools/shot/main.go b/tools/shot/main.go new file mode 100644 index 0000000..220b5e1 --- /dev/null +++ b/tools/shot/main.go @@ -0,0 +1,76 @@ +// 截取正在运行的 MyGoland 窗口,用于本地像素级验证。 +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "os" +) + +type windowInfo struct { + ID int `json:"id"` + Title string `json:"title"` +} + +func main() { + if len(os.Args) < 3 { + fmt.Println("用法: shot ") + os.Exit(2) + } + c, err := net.Dial("unix", os.Args[1]) + if err != nil { + fmt.Println("连接失败:", err) + os.Exit(1) + } + defer c.Close() + enc := json.NewEncoder(c) + dec := json.NewDecoder(bufio.NewReader(c)) + + if err := enc.Encode(map[string]any{"id": 1, "method": "windows"}); err != nil { + fmt.Println("发送失败:", err) + os.Exit(1) + } + var wr struct { + Result struct { + Windows []windowInfo `json:"windows"` + } `json:"result"` + Error any `json:"error"` + } + if err := dec.Decode(&wr); err != nil { + fmt.Println("解析失败:", err) + os.Exit(1) + } + if len(wr.Result.Windows) == 0 { + fmt.Println("没有窗口") + os.Exit(1) + } + id := wr.Result.Windows[0].ID + + if err := enc.Encode(map[string]any{"id": 2, "method": "capture", "params": map[string]any{"window": id}}); err != nil { + fmt.Println("发送失败:", err) + os.Exit(1) + } + var cr struct { + Result struct { + PNG []byte `json:"png"` + Width int `json:"width"` + Height int `json:"height"` + } `json:"result"` + Error any `json:"error"` + } + if err := dec.Decode(&cr); err != nil { + fmt.Println("解析失败:", err) + os.Exit(1) + } + if len(cr.Result.PNG) == 0 { + fmt.Printf("截图失败: %+v\n", cr.Error) + os.Exit(1) + } + if err := os.WriteFile(os.Args[2], cr.Result.PNG, 0o644); err != nil { + fmt.Println("写文件失败:", err) + os.Exit(1) + } + fmt.Printf("ok %dx%d -> %s\n", cr.Result.Width, cr.Result.Height, os.Args[2]) +} diff --git a/tools/tree/main.go b/tools/tree/main.go new file mode 100644 index 0000000..2eb0bce --- /dev/null +++ b/tools/tree/main.go @@ -0,0 +1,82 @@ +// 列出正在运行的 MyGoland 窗口的无障碍元素树,用于精确定位控件坐标。 +// +// 有了它就不用再靠肉眼估坐标:按 Label 一查就知道按钮在哪。 +// 用法: tree [筛选关键词] +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "os" + "strings" +) + +type node struct { + ID any `json:"id"` + Role string `json:"role"` + Label string `json:"label"` + Value string `json:"value"` + Bounds rect `json:"bounds"` + Actions []string `json:"actions"` +} + +type rect struct { + X float32 `json:"x"` + Y float32 `json:"y"` + W float32 `json:"w"` + H float32 `json:"h"` +} + +func (r rect) center() (float32, float32) { + return r.X + r.W/2, r.Y + r.H/2 +} + +func main() { + if len(os.Args) < 2 { + fmt.Println("用法: tree [关键词]") + os.Exit(2) + } + filter := "" + if len(os.Args) >= 3 { + filter = strings.ToLower(os.Args[2]) + } + + c, err := net.Dial("unix", os.Args[1]) + if err != nil { + fmt.Println("连接失败:", err) + os.Exit(1) + } + defer c.Close() + enc := json.NewEncoder(c) + dec := json.NewDecoder(bufio.NewReader(c)) + + if err := enc.Encode(map[string]any{"id": 1, "method": "tree"}); err != nil { + fmt.Println("发送失败:", err) + os.Exit(1) + } + var res struct { + Result struct { + Nodes []node `json:"nodes"` + } `json:"result"` + Error any `json:"error"` + } + if err := dec.Decode(&res); err != nil { + fmt.Println("读取失败:", err) + os.Exit(1) + } + for _, n := range res.Result.Nodes { + text := n.Label + if text == "" { + text = n.Value + } + if filter != "" && !strings.Contains(strings.ToLower(text), filter) { + continue + } + cx, cy := n.Bounds.center() + fmt.Printf("%-10s %-14s %6.0f,%-6.0f %4.0fx%-4.0f %s\n", + n.Role, strings.Join(n.Actions, ","), cx, cy, + n.Bounds.W, n.Bounds.H, text) + } +}