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

627 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
}
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])
}