Files
MyGolandRelease/internal/app/app.go
T
zerorigin c35564b65e 编辑器右键菜单补应用层动作,并做完评估报告"本周做"剩余项
第 9 项。原报告 4.5 判断「编辑器无右键菜单」是错的:框架 ui/editor
自带完整菜单(跳转定义、剪切/复制/粘贴、全选、切换注释、选区/转换/
折叠三个子菜单),State.ContextMenu 只是留给应用层的追加点。所以本次
不重造菜单,只往那个追加点里填应用层独有的 16 项:

- gopls:代码动作、查找引用、重命名符号(要求 Go 文件 + LSP 在线,
  改文本的还要求非只读)
- 编辑:格式化文档、在文件中查找
- 测试:运行光标处的测试 / 当前包(只在 _test.go 出现,普通文件里挂
  一个永远点不动的项是噪音,而它一旦可点又会退化成跑全部测试)
- 定位:在项目树中定位、在资源管理器中显示、本地历史
- 剪贴板:复制相对路径 / 绝对路径

菜单项造在纯函数 editorMenuItems(editorMenuCap) 里,可用性由
goFile/lspReady/inRoot/onDisk/readOnly 五个事实决定;条件插入容易留下
连着两条分隔线或末尾挂一条,统一由 compactEditorMenu 收口。

验证不止单测:TestEditorMenuShowsInEditor 用 ui.NewTester 真把编辑器
渲染出来、真右击、读 tt.Menu() 的菜单文案,再 ChooseMenuItem 走完
「菜单 → 动作 → 剪贴板」整条链路,并断言灰掉的项点不动。框架文档明确
说右键菜单不能用 automation 插座驱动,所以走 Tester 这条路。

顺带一次 gofmt -w 把全仓 gofmt -l 清空(13 个文件,多是 CRLF 与文档
注释空格),并更正报告 4.5、补齐执行状态。

其余"本周做"项(回收站删除、参数引号切分 + Env/WorkDir、日志轮转、
标签同名区分)一并入库。
2026-11-05 16:06:17 +08:00

942 lines
28 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 (
"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
// trans 是补全文档的译文缓存(原文→译文,空串哨兵表示同会话内翻译
// 失败过、不再重试),transInflight 去重进行中的请求。见 translate.go。
trans map[string]string
transInflight map[string]bool
// preheat 是标准库文档批量预热的进度(见 preheat.go),
// preheatInflight 去重预热中已排队的条目。
preheat preheatState
preheatInflight map[string]bool
// preheatAuto 保证每个会话只自动预热一次(打开项目后延时触发)。
preheatAuto 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
// 译文缓存也是跨工作区的:标准库文档固定,重启后秒出译文。
a.loadTranslations()
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)
// 标准库文档预热:打开项目 8 秒后自动跑(等界面先稳),每个会话只自动
// 一次;菜单里可随时手动重跑,已缓存的自动跳过。AfterFunc 的回调在
// 后台 goroutine,必须经 win.Update 投递回主线程(PreheatDocs 已处理)。
if !a.preheatAuto {
a.preheatAuto = true
time.AfterFunc(8*time.Second, a.PreheatDocs)
}
// 上次异常退出留下的未保存内容:先记下来,等界面就绪再问。
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) }
// 右键菜单补上框架没有的应用层动作(代码动作、跑测试、复制路径…)。
// 框架自带的那些仍在前半段,见 editor_menu.go 的说明。
a.attachEditorMenu(d)
// 补全面板自定义渲染:底部文档接 LLM 中文翻译(见 completion.go)。
d.st.RenderCompletions = a.renderCompletions
// 悬停卡片同理:文档正文翻译,签名与链接行保留。
d.st.RenderHover = a.renderHover
// 编辑器级的快捷键在这里拦。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() {})
}