Files
MyGolandRelease/internal/app/terminal.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

368 lines
9.0 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 (
"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() {})
}
}