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 := parseArgs(cfg.Args) stopOnEntry := cfg.StopOnEntry // dlv 自己的 cwd 与 launch 的 cwd 都跟着配置走: // 前者决定相对 program 怎么解析,后者决定被调试进程的工作目录。 dir := a.cfgWorkDir(cfg) env := envFromLines(cfg.Env) go func() { c, err := dap.Start(dir, 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 = "构建中…" }) // env / cwd 是 dlv 的扩展字段,作用于被调试进程而不是 dlv 自己。 if err := c.LaunchWith(dap.LaunchOptions{ Program: prog, Args: args, StopOnEntry: stopOnEntry, Env: env, WorkDir: dir, }, 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])) }