Files
MyGolandRelease/internal/app/palette.go
T
zerorigin 4ace9c9fb6 fix: 按评估优先级修四项(标签右键/UTF-8 截断/覆盖率输出/.gitignore)
1. 标签页右键菜单接回(回归修复)
   tabmenu.go 的 160 行实现全库零调用点,tabBar 只处理 Clicked。
   补 RightClicked → openPop(tabEntries(path)),右键时先设 active
   (菜单无标题,靠标签高亮传达「关闭左边」相对谁算)。
   新增 tabmenu_test.go 8 个单测。

2. 中文按字节截断导致乱码
   palette.go trimmed[:160]、rename.go s[:140] 会把多字节字符切断。
   trimTo 从 gitlog.go 提到 strutil.go(三个调用方共用),两处改用它;
   n<=0 返回空串。strutil_test.go 6 个单测(含真实 linePreview 路径)。

3. 覆盖率运行不再吞测试输出
   原来 lines 收集后 _ = lines 丢弃,测试失败只看到覆盖率数字。
   改用 ExitCode() 判失败,只回放 FAIL/--- FAIL/panic/# 包/file.go:12 行
   (上限 200),覆盖率页顶部给红底摘要 + 「查看测试输出」按钮。
   coverageFailLines/Summary 纯函数 + 5 个单测。

4. 索引与搜索感知 .gitignore
   新增 ignore.go:dir/、*.ext、/rootonly、带路径、**、! 取反、注释。
   内置跳过扩到 vendor/dist/build/out/target/.next(文件树仍用保守 skipDir)。
   indexState 加 truncated,快速打开底部提示「索引已截断至 N 个文件」。
   ignore_test.go 10 个单测 + 真实遍历集成测试。

验证:go vet ./... 干净;go test ./internal/... 7 包全绿;
e2e 实例 tools/tree 确认菜单 5 项齐全 + tools/shot 截图核对。
2026-11-05 15:43:33 +08:00

636 lines
17 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
}
rules := loadIgnoreRules(root)
var files []string
_ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil {
return nil
}
rel, relErr := filepath.Rel(root, p)
relSlash := ""
if relErr == nil {
relSlash = filepath.ToSlash(rel)
}
if d.IsDir() {
if p != root && (isBuiltinSkipDir(d.Name()) || rules.match(relSlash, true)) {
return filepath.SkipDir
}
return nil
}
if skipFile(d.Name()) || rules.match(relSlash, false) {
return nil
}
if relErr == nil {
files = append(files, relSlash)
}
if len(files) > indexFileCap {
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
}
// 按字符截断,别切坏中文(见 strutil.go 的注释)。
trimmed := trimTo(strings.TrimSpace(line), 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 !a.pal.search && a.indexTruncated() {
ui.Textf(c, "索引已截断至 %d 个文件", indexFileCap).
FontSize(10).TextColor(t.Warning)
}
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])
}