Files
MyGolandRelease/internal/app/output.go
T
zerorigin c35564b65e 编辑器右键菜单补应用层动作,并做完评估报告"本周做"剩余项
第 9 项。原报告 4.5 判断「编辑器无右键菜单」是错的:框架 ui/editor
自带完整菜单(跳转定义、剪切/复制/粘贴、全选、切换注释、选区/转换/
折叠三个子菜单),State.ContextMenu 只是留给应用层的追加点。所以本次
不重造菜单,只往那个追加点里填应用层独有的 16 项:

- gopls:代码动作、查找引用、重命名符号(要求 Go 文件 + LSP 在线,
  改文本的还要求非只读)
- 编辑:格式化文档、在文件中查找
- 测试:运行光标处的测试 / 当前包(只在 _test.go 出现,普通文件里挂
  一个永远点不动的项是噪音,而它一旦可点又会退化成跑全部测试)
- 定位:在项目树中定位、在资源管理器中显示、本地历史
- 剪贴板:复制相对路径 / 绝对路径

菜单项造在纯函数 editorMenuItems(editorMenuCap) 里,可用性由
goFile/lspReady/inRoot/onDisk/readOnly 五个事实决定;条件插入容易留下
连着两条分隔线或末尾挂一条,统一由 compactEditorMenu 收口。

验证不止单测:TestEditorMenuShowsInEditor 用 ui.NewTester 真把编辑器
渲染出来、真右击、读 tt.Menu() 的菜单文案,再 ChooseMenuItem 走完
「菜单 → 动作 → 剪贴板」整条链路,并断言灰掉的项点不动。框架文档明确
说右键菜单不能用 automation 插座驱动,所以走 Tester 这条路。

顺带一次 gofmt -w 把全仓 gofmt -l 清空(13 个文件,多是 CRLF 与文档
注释空格),并更正报告 4.5、补齐执行状态。

其余"本周做"项(回收站删除、参数引号切分 + Env/WorkDir、日志轮转、
标签同名区分)一并入库。
2026-11-05 16:06:17 +08:00

597 lines
15 KiB
Go

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)
}
cfg := a.activeCfg()
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
}
}
}
}
// 程序参数必须排在包名之后:`go run ./pkg a b` 里 a b 才是传给程序的,
// 写在 pkg 前面会被 go 当成自己的参数。
progArgs := parseArgs(cfg.Args)
args := append([]string{"run", pkg}, progArgs...)
if len(progArgs) > 0 {
label += " " + strings.Join(progArgs, " ")
}
a.startTaskAt(label, a.cfgWorkDir(cfg), envFromLines(cfg.Env), "go", args...)
}
// cfgWorkDir 解析运行配置里的工作目录:空表示工作区根,
// 相对路径按工作区根算(与 Program 的语义一致)。
func (a *App) cfgWorkDir(cfg runConfig) string {
w := strings.TrimSpace(cfg.WorkDir)
if w == "" {
return a.root
}
if filepath.IsAbs(w) {
return w
}
return filepath.Join(a.root, w)
}
// 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) {
a.startTaskAt(label, a.root, nil, name, args...)
}
// startTaskAt 在指定目录与环境变量下启动命令。
//
// dir 为空时回落到工作区根;env 为增量(不整体替换),
// 否则 PATH 之类被清掉,go 命令直接找不到。
func (a *App) startTaskAt(label, dir string, env map[string]string, name string, args ...string) {
if a.root == "" {
return
}
if dir == "" {
dir = a.root
}
if a.running {
a.StopTask()
}
a.panel = true
a.panelTab = 0
if a.panelH < 80 {
a.panelH = 220
}
a.appendOut("$ " + label)
envList := make([]string, 0, len(env))
for k, v := range env {
envList = append(envList, k+"="+v)
}
t, err := task.StartWith(task.Options{Dir: dir, Env: envList}, 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()
}
}