Files
MyGolandRelease/internal/app/output.go
T
zerorigin a80c0f886a MyGoland 首次提交:Go 轻量 IDE
- 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲)
- 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表)
- 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记
- Git:状态着色、选择性暂存提交、pull/push、历史并排对比
- 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复
- 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈
- 设计文档与验证记录见 docs/plans/
2026-11-04 16:37:05 +08:00

561 lines
14 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)
}
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()
}
}