MyGoland 首次提交:Go 轻量 IDE
- 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲) - 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表) - 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记 - Git:状态着色、选择性暂存提交、pull/push、历史并排对比 - 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复 - 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈 - 设计文档与验证记录见 docs/plans/
This commit is contained in:
commit
a80c0f886a
220 files changed
+20784
No files matched your search
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -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() {}) })
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -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() {})
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 5.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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() {})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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("截断文件不该记录光标位置")
|
||||
}
|
||||
}
|
||||
@@ -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]))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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) })
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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(`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path fill="currentColor" d="M1.6 3.4c0-.5.4-.9.9-.9h3.2l1.4 1.6h6.4c.5 0 .9.4.9.9v7.2c0 .5-.4.9-.9.9H2.5c-.5 0-.9-.4-.9-.9z"/></svg>`)
|
||||
iconFile = mustSVG(`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path fill="currentColor" d="M3.6 1.6h5.2l3.6 3.6v9.2H3.6zm5.4.9v3h3z"/></svg>`)
|
||||
iconCode = mustSVG(`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path fill="currentColor" d="M6.1 3.9 1.9 8.1l4.2 4.2 1.1-1.1L4.1 8.1l3.1-3.1zm3.8 0-1.1 1.1 3.1 3.1-3.1 3.1 1.1 1.1 4.2-4.2z"/></svg>`)
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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() {})
|
||||
})
|
||||
}
|
||||
@@ -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]) + "…"
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
@@ -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": `<path d="M3 8a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>`,
|
||||
"refresh": `<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M20 3.5V8h-4.5"/>`,
|
||||
"collapse": `<path d="M8 5l4 4 4-4"/><path d="M8 19l4-4 4 4"/>`,
|
||||
"expand": `<path d="M8 10l4-4 4 4"/><path d="M8 14l4 4 4-4"/>`,
|
||||
"plus": `<path d="M12 5v14"/><path d="M5 12h14"/>`,
|
||||
"outline": `<path d="M4 6h3"/><path d="M10 6h10"/><path d="M4 12h3"/><path d="M10 12h10"/><path d="M4 18h3"/><path d="M10 18h10"/>`,
|
||||
"chevron": `<path d="M9.5 6.5l6 5.5-6 5.5"/>`,
|
||||
// 靶心加十字准星:定位当前文件在树里的位置。
|
||||
"locate": `<circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="1.8" fill="black"/><path d="M12 2.5v3"/><path d="M12 18.5v3"/><path d="M2.5 12h3"/><path d="M18.5 12h3"/>`,
|
||||
"build": `<path d="M13.5 3.5l7 7-2.5 2.5-7-7z"/><path d="M11.5 9.5L4 17l2.5 2.5 7.5-7.5"/>`,
|
||||
"run": `<path d="M8.5 5.5l10 6.5-10 6.5z" fill="black"/>`,
|
||||
"test": `<path d="M9 3.5h6"/><path d="M10 3.5v6.2L4.8 18.2A1.8 1.8 0 0 0 6.3 21h11.4a1.8 1.8 0 0 0 1.5-2.8L14 9.7V3.5"/>`,
|
||||
"stop": `<path d="M7.5 7.5h9v9h-9z" fill="black"/>`,
|
||||
"clear": `<path d="M4 7h16"/><path d="M9.5 7V5h5v2"/><path d="M6.5 7l1 13h9l1-13"/>`,
|
||||
"hide": `<path d="M6 9l6 6 6-6"/>`,
|
||||
"panel": `<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M3.5 15h17"/>`,
|
||||
"continue": `<path d="M8 5v14"/><path d="M13 6l7 6-7 6z" fill="black"/>`,
|
||||
"over": `<path d="M4 11.5h10.5"/><path d="M11.5 8l3.5 3.5-3.5 3.5"/><circle cx="18" cy="17.5" r="1.6" fill="black"/>`,
|
||||
"into": `<path d="M12 4v9"/><path d="M8 9.5l4 4 4-4"/><path d="M6 19h12"/>`,
|
||||
"out": `<path d="M12 20V11"/><path d="M8 14.5l4-4 4 4"/><path d="M6 5h12"/>`,
|
||||
"close": `<path d="M7 7l10 10"/><path d="M17 7L7 17"/>`,
|
||||
"error": `<circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5"/><path d="M12 16.5h.01"/>`,
|
||||
"warning": `<path d="M12 3.8l9.2 16.4H2.8z"/><path d="M12 9.5v4.5"/><path d="M12 17.2h.01"/>`,
|
||||
"debug": `<path d="M12 4.5a3 3 0 0 1 3 3v2a3 3 0 0 1-6 0v-2a3 3 0 0 1 3-3z"/><path d="M6 12h12"/><path d="M8 19l2.5-3"/><path d="M16 19l-2.5-3"/>`,
|
||||
}
|
||||
|
||||
// icons 是解析好的图标,进程启动时建一次。
|
||||
var icons = map[string]*ui.SVG{}
|
||||
|
||||
func init() {
|
||||
for name, body := range iconMarkup {
|
||||
src := `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">` + body + `</svg>`
|
||||
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()
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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])}
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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() {})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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("函数与类型应当用不同颜色")
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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() {})
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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() {})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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("大小写不同也应算在目录内")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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("不存在的会话不该读成功")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 应被尊重")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -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) }
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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() {})
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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 "测试"
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 返回标题栏里显示的文字:当前文件与工作区。
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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) })
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -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("应当返回错误")
|
||||
}
|
||||
}
|
||||
@@ -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() {})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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("内容未变,不应重置缓冲区")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user