diff --git a/.agents/notes/implemented/architecture/2026-11-13-viva-editor-essentials-ownership.md b/.agents/notes/implemented/architecture/2026-11-13-viva-editor-essentials-ownership.md new file mode 100644 index 0000000000..2d8564951e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-13-viva-editor-essentials-ownership.md @@ -0,0 +1,68 @@ +# Agent 笔记:编辑器查找与恢复副本的职责 + +状态:已实现 + +## 先说结论 + +文件内查找、显示设置默认值、最近访问顺序、快捷键方案转换和恢复冲突判断由 Rust Core 决定。 +桌面端只负责原生文本缓冲、绘制和文件读写。恢复副本独立于自动保存,关闭 Scratch 标签会保留内容, +遇到磁盘文件改变时必须由用户明确选择保留编辑器或载入磁盘。 + +## 问题 + +Viva(桌面界面框架)的编辑器已经拥有不可变文本树,重新在 Core 维护全文会增加常驻内存。 +把全文塞进 JSON 请求也会在每次查找时产生多次转义和复制。另一方面,正常退出时保存标签位置不能 +恢复崩溃前尚未写入文件的内容;自动保存关闭时也必须有独立的恢复路径。 + +## 决策 + +- 桌面端在窗口线程取得不可变文本快照,后台工作线程经借用式 C ABI(同步调用期间共享字节的跨语言接口) + 提供 UTF-8 数据。Core 只返回有界的原始字节范围和替换计划,不缓存源文件。 + 原生文本树、行宽计算和单步撤销的准备在后台完成,回到窗口线程再次检查快照、查询代数和文档归属。 + 关闭查找栏、文档或项目会取消查询和定时器,过期结果不得修改编辑器。 +- 显示偏好经过 Core 解析后才交给绘制。最近文件的排序、过滤和逻辑顺序不依赖墙上时钟。 + 原生工作队列保持同一窗口事件顺序,多个窗口的历史文件读写在原生边界串行完成。 + 快捷键方案保存独立绑定,切换方案同时切换实际工作台分发所用的绑定。 +- 恢复适配器使用平台用户配置目录下的 `Lithe Desktop/EditorRecovery/`。 + 每个 `.draft` 文件包含小型元数据头和原始 UTF-8 内容;后台流式写入私有临时文件、同步后原子替换。 + 临时文件与最终文件在同一个目录,既不会混用两个代数,也不需要复制整篇内容到 JSON。 + 所有窗口共用原生写入锁,检查 Core 给出的单文档、总字节数和条数限制后再写入。 +- 编辑器输入只安排短暂的合并定时器。实际写入由一个有界队列合并同一文档的快照;保存或丢弃操作在旧写入之后执行。 + 项目、窗口关闭时先提交最后的快照、停止定时器,再等待所属后台任务结束。 + 普通文件保存成功后移除恢复副本;Scratch 关闭时保留,另存为成功或明确丢弃才移除。 +- 恢复时比较保存前基线摘要和实际磁盘内容。文件改变或消失时保留冲突;文件监听只比较重启后观察到的 + 磁盘基线,不能据此自动确认崩溃前的冲突。用户选择保留编辑器或载入磁盘前,手动保存和自动保存都不得覆盖磁盘。 + 更晚的外部修改仍由既有原生受保护写入检查拒绝。 + +正确做法:查找请求 A 返回前文本发生变化,丢弃 A;后台队列收到新快照后又收到保存成功通知,最终删除副本。 +不要这样做:绘制时展开全文并查找、让旧替换结果修改新版本、把文件监听观察到的“未变化”当成恢复冲突已获用户确认。 + +## 考虑过的备选方案 + +- 在 Core 保留第二份文本:会重复原生编辑器的文档所有权,拒绝。 +- 全文 JSON 请求:会转义和复制整个源文件,拒绝。 +- 只依赖自动保存:用户关闭自动保存或发生外部修改时不能保障恢复,拒绝。 +- 把草稿放到项目或发行包:会污染工作区,或者改变签名与增量更新基线,拒绝。 +- 自建正则引擎:Core 已有成熟 `regex` 依赖,直接使用 Unicode 匹配和捕获组替换。 + +## 后果 + +查找需要后台临时连续字节快照,原生文本树仍是唯一长期全文所有者。恢复写入是编辑后短暂合并的检查点, +崩溃发生在检查点完成前时,最后一次检查点之后的按键无法保证恢复。配额满时明确报错并保留编辑器内容, +不静默淘汰未保存的用户数据。恢复文件和最近文件属于可变用户状态,禁止通过工作树资源复用流程共享。 +它们始终位于安装目录之外,不影响代码签名和 Sparkle 增量更新。 + +## 验证 + +- `desktop/internal/workbench/editor_essentials_test.go`:替换、单步撤销、过期隔离、磁盘冲突保护、草稿持久化与最近访问。 +- `desktop/internal/settingswindow/editor_essentials_test.go`:实际设置回显、方案独立、切换、重复名称和默认方案保护。 +- `desktop/internal/draftstore/store_test.go`:原子覆盖、重建适配器读取和配额拒绝时原内容保持。 +- `editor_essentials_visual_test.go`:以真实 Page 无头渲染深色中文与浅色英文界面。 +- Core 的可执行向量为 `rust/fixtures/editor/ide-essentials-v1.json`,借用式 C ABI 测试同时检查空指针和非法 UTF-8。 +- 编辑器改动前后各运行六次原有性能基线;原生窗口与 Windows 平台验收独立记录,不能用无头截图代替。 + +## 适用范围 + +`desktop/internal/editorview/`、`desktop/internal/draftstore/`、工作台的 `editor_find.go`、`editor_recovery.go`、 +`recent_files.go`、`scratch_files.go`,以及设置窗口相应组件。共享规则和正式接口文档属于外部 Core 仓库, +本笔记不作为第二份协议参考。 diff --git a/desktop/internal/core/bridge.go b/desktop/internal/core/bridge.go index 5d2ac7bd6d..59ae3a502b 100644 --- a/desktop/internal/core/bridge.go +++ b/desktop/internal/core/bridge.go @@ -45,6 +45,21 @@ func executeJSON(request []byte) []byte { return C.GoBytes(unsafe.Pointer(response), C.int(C.strlen(response))) } +// executeDocumentJSON borrows immutable source bytes for the synchronous Core call. +// Only the small request and bounded result are copied across the C ABI. Core never +// retains the Go pointer, and the slice contains no Go pointers. +func executeDocumentJSON(request, source []byte) []byte { + cRequest := C.CString(string(request)) + defer C.free(unsafe.Pointer(cRequest)) + response := C.lithe_core_execute_document_json(cRequest, (*C.uint8_t)(unsafe.Pointer(unsafe.SliceData(source))), C.size_t(len(source))) + runtime.KeepAlive(source) + if response == nil { + return nil + } + defer C.lithe_core_free_string(response) + return C.GoBytes(unsafe.Pointer(response), C.int(C.strlen(response))) +} + // cancelOperation asks the kernel to cancel the in-flight request whose operationId is // operationID. It reports whether the kernel found an active operation with that id: the C // function returns 1 when it did and 0 when it did not (the operation already finished, has not diff --git a/desktop/internal/core/desktop_go_test.go b/desktop/internal/core/desktop_go_test.go index 8e62b3240b..6a258a90d2 100644 --- a/desktop/internal/core/desktop_go_test.go +++ b/desktop/internal/core/desktop_go_test.go @@ -154,17 +154,39 @@ func TestBuildDesktopCoreChecksOutFreshPinnedRevision(t *testing.T) { script := filepath.Join(fixture, "scripts/desktop/build-desktop-core.sh") write(script, strings.Replace(string(build), pinPrefix+pin+`"`, pinPrefix+revision+`"`, 1), 0o700) write(filepath.Join(fixture, "bin/rustc"), "#!/usr/bin/env bash\nif [[ \"$1\" == -vV ]]; then echo 'host: x86_64-unknown-linux-gnu'; else echo 'rustc fixture'; fi\n", 0o700) - write(filepath.Join(fixture, "bin/cargo"), "#!/usr/bin/env bash\nif [[ \"$1\" == clean ]]; then exit 0; fi\nmkdir -p \"$CARGO_TARGET_DIR/debug\"\nprintf fixture > \"$CARGO_TARGET_DIR/debug/liblithe_core.a\"\nprintf helper > \"$CARGO_TARGET_DIR/debug/lithe-mcp\"\nfor arg in \"$@\"; do case \"$arg\" in native-static-libs=*) printf '%s\\n' '-lm' > \"${arg#native-static-libs=}\";; esac; done\n", 0o700) + write(filepath.Join(fixture, "bin/cargo"), `#!/usr/bin/env bash +set -euo pipefail +if [[ "$1" == clean ]]; then exit 0; fi +out="$CARGO_TARGET_DIR/debug" +helper=lithe-mcp +libs=-lm +for ((i=1; i<=$#; i++)); do + if [[ "${!i}" == --target ]]; then + j=$((i+1)) + out="$CARGO_TARGET_DIR/${!j}/debug" + if [[ "${!j}" == *-windows-gnu ]]; then + [[ "${WINAPI_NO_BUNDLED_LIBRARIES:-}" == 1 ]] || { echo 'winapi still requires Cargo-private import libraries' >&2; exit 1; } + helper=lithe-mcp.exe + libs=-lkernel32 + fi + fi +done +mkdir -p "$out" +printf fixture > "$out/liblithe_core.a" +printf helper > "$out/$helper" +for arg in "$@"; do case "$arg" in native-static-libs=*) printf '%s\n' "$libs" > "${arg#native-static-libs=}";; esac; done +`, 0o700) + target := "x86_64-unknown-linux-gnu" runBuild := func() ([]byte, error) { t.Helper() cmd := exec.CommandContext(testContext(t), bash, script) for _, entry := range os.Environ() { upper := strings.ToUpper(entry) - if !strings.HasPrefix(upper, "PATH=") && !strings.HasPrefix(upper, "LITHE_CORE_RUST_DIR=") && !strings.HasPrefix(upper, "LITHE_CORE_TARGET=") { + if !strings.HasPrefix(upper, "PATH=") && !strings.HasPrefix(upper, "LITHE_CORE_RUST_DIR=") && !strings.HasPrefix(upper, "LITHE_CORE_TARGET=") && !strings.HasPrefix(upper, "WINAPI_NO_BUNDLED_LIBRARIES=") { cmd.Env = append(cmd.Env, entry) } } - cmd.Env = append(cmd.Env, "PATH="+filepath.Join(fixture, "bin")+string(os.PathListSeparator)+os.Getenv("PATH")) + cmd.Env = append(cmd.Env, "PATH="+filepath.Join(fixture, "bin")+string(os.PathListSeparator)+os.Getenv("PATH"), "LITHE_CORE_TARGET="+target) return cmd.CombinedOutput() } // A no-index directory may still contain untracked user files. Recovery @@ -188,6 +210,21 @@ func TestBuildDesktopCoreChecksOutFreshPinnedRevision(t *testing.T) { if _, err := os.Stat(filepath.Join(checkout, "rust/Cargo.toml")); err != nil { t.Fatalf("pinned worktree was not checked out: %v", err) } + // The GNU cgo lane must ask winapi to use MinGW's system import libraries, + // not private libwinapi_* archives from a transient Cargo registry path. + target = "x86_64-pc-windows-gnu" + output, err = runBuild() + if err != nil { + t.Fatalf("building Windows Core with system import libraries: %v\n%s", err, output) + } + stage := filepath.Join(fixture, ".artifacts/desktop/lithe-core", target, "debug") + if libs, err := os.ReadFile(filepath.Join(stage, "native-static-libs.txt")); err != nil || string(libs) != "-lkernel32\n" { + t.Fatalf("unexpected Windows linker inputs: %q, %v", libs, err) + } + if identity, err := os.ReadFile(filepath.Join(stage, "identity.txt")); err != nil || !strings.Contains(string(identity), "winapi-import-libraries=mingw-system\n") { + t.Fatalf("Windows import library identity missing: %q, %v", identity, err) + } + target = "x86_64-unknown-linux-gnu" // Once a worktree has an index, a deliberate deletion must not be repaired // by checkout behind the user's back, even if the build cannot proceed. if err := os.Remove(manifest); err != nil { diff --git a/desktop/internal/core/editor_essentials.go b/desktop/internal/core/editor_essentials.go new file mode 100644 index 0000000000..c9daa8bda9 --- /dev/null +++ b/desktop/internal/core/editor_essentials.go @@ -0,0 +1,171 @@ +package core + +import ( + "context" + "encoding/json" + "fmt" +) + +// EditorStoredPreferences preserves missing values from earlier settings versions. +// Core alone supplies defaults and validates ranges and style identifiers. +type EditorStoredPreferences struct { + LineNumbers *bool `json:"lineNumbers,omitempty"` + Whitespace *bool `json:"whitespace,omitempty"` + CursorStyle string `json:"cursorStyle,omitempty"` + CursorBlink *bool `json:"cursorBlink,omitempty"` + AutoSaveDelayMilliseconds *uint64 `json:"autoSaveDelayMilliseconds,omitempty"` +} + +// EditorPreferences is the actual presentation configuration resolved by Core. +type EditorPreferences struct { + LineNumbers bool `json:"lineNumbers"` + Whitespace bool `json:"whitespace"` + CursorStyle string `json:"cursorStyle"` + CursorBlink bool `json:"cursorBlink"` + AutoSaveDelayMilliseconds uint64 `json:"autoSaveDelayMilliseconds"` + MinimumAutoSaveDelayMilliseconds uint64 `json:"minimumAutoSaveDelayMilliseconds"` + MaximumAutoSaveDelayMilliseconds uint64 `json:"maximumAutoSaveDelayMilliseconds"` +} + +func (c *Client) ResolveEditorPreferences(ctx context.Context, stored EditorStoredPreferences) (EditorPreferences, error) { + var result EditorPreferences + err := c.Execute(ctx, "editor.preferences.resolve", stored, &result) + return result, err +} + +// EditorByteRange is a half-open byte span of the exact immutable snapshot searched. +type EditorByteRange struct { + Start int `json:"start"` + End int `json:"end"` +} + +type EditorFindRequest struct { + Query string `json:"query"` + CaseSensitive bool `json:"caseSensitive"` + WholeWord bool `json:"wholeWord"` + Regex bool `json:"regex"` + Range *EditorByteRange `json:"range,omitempty"` + Replacement *string `json:"replacement,omitempty"` + ReplaceStart *int `json:"replaceStart,omitempty"` + Caret int `json:"caret"` + Backwards bool `json:"backwards"` +} + +type EditorReplacement struct { + EditorByteRange + Text string `json:"text"` +} + +type EditorFindResult struct { + Range *EditorByteRange `json:"range,omitempty"` + Matches []EditorByteRange `json:"matches"` + Edits []EditorReplacement `json:"edits"` + Selected *int `json:"selected"` + Truncated bool `json:"truncated"` +} + +// FindEditorText runs on a worker: source is an immutable snapshot, borrowed by Rust +// rather than copied into a JSON string. Operation cancellation uses the ordinary registry. +func (c *Client) FindEditorText(ctx context.Context, source []byte, input EditorFindRequest) (EditorFindResult, error) { + var result EditorFindResult + if err := ctx.Err(); err != nil { + return result, err + } + id := fmt.Sprintf("desktop-%d", nextCoreOperation.Add(1)) + request, err := json.Marshal(requestEnvelope{OperationID: id, Command: "editor.find", Payload: input}) + if err != nil { + return result, err + } + stop := watchCancellation(ctx, id) + defer stop() + err = decodeResponse(ctx, "editor.find", executeDocumentJSON(request, source), &result) + return result, err +} + +type EditorRecentEntry struct { + Path string `json:"path"` + Name string `json:"name"` + Line int `json:"line"` + Column int `json:"column"` + Opened uint64 `json:"opened"` + Edited uint64 `json:"edited"` +} + +type EditorRecentEvent struct { + Kind string `json:"kind"` + Path string `json:"path"` + Name string `json:"name"` + Line int `json:"line"` + Column int `json:"column"` +} + +type EditorRecentRequest struct { + Entries []EditorRecentEntry `json:"entries,omitempty"` + Event *EditorRecentEvent `json:"event,omitempty"` + Query string `json:"query"` + OnlyEdited bool `json:"onlyEdited"` +} + +type EditorRecentResult struct { + Entries []EditorRecentEntry `json:"entries"` + Results []EditorRecentEntry `json:"results"` +} + +func (c *Client) ReduceEditorRecent(ctx context.Context, input EditorRecentRequest) (EditorRecentResult, error) { + var result EditorRecentResult + err := c.Execute(ctx, "editor.recent.reduce", input, &result) + return result, err +} + +type EditorRecoveryRequest struct { + BaseHash string `json:"baseHash"` + DiskHash *string `json:"diskHash"` + Scratch bool `json:"scratch"` + Bytes uint64 `json:"bytes"` + Saved bool `json:"saved"` + Discarded bool `json:"discarded"` +} + +type EditorRecoveryDecision struct { + Action string `json:"action"` + MaxDocumentBytes int64 `json:"maxDocumentBytes"` + MaxStorageBytes int64 `json:"maxStorageBytes"` + MaxDocuments int `json:"maxDocuments"` +} + +func (c *Client) DecideEditorRecovery(ctx context.Context, input EditorRecoveryRequest) (EditorRecoveryDecision, error) { + var result EditorRecoveryDecision + err := c.Execute(ctx, "editor.recovery.decide", input, &result) + return result, err +} + +type KeymapScheme struct { + ID string `json:"id"` + Name string `json:"name"` + Bindings map[string][]string `json:"bindings"` +} + +type KeymapSchemes struct { + Active string `json:"active"` + Schemes []KeymapScheme `json:"schemes,omitempty"` +} + +type KeymapSchemeRequest struct { + State KeymapSchemes `json:"state"` + Current map[string][]string `json:"current,omitempty"` + Operation string `json:"operation"` + ID string `json:"id"` + Name string `json:"name"` + Bindings map[string][]string `json:"bindings,omitempty"` +} + +type KeymapSchemeResult struct { + State KeymapSchemes `json:"state"` + Bindings map[string][]string `json:"bindings"` +} + +func (c *Client) ReduceKeymapSchemes(ctx context.Context, input KeymapSchemeRequest) (KeymapSchemeResult, error) { + var result KeymapSchemeResult + err := c.Execute(ctx, "keymap.schemes.reduce", input, &result) + return result, err +} diff --git a/desktop/internal/core/editor_essentials_test.go b/desktop/internal/core/editor_essentials_test.go new file mode 100644 index 0000000000..ad9591e000 --- /dev/null +++ b/desktop/internal/core/editor_essentials_test.go @@ -0,0 +1,60 @@ +package core + +import ( + "context" + "errors" + "testing" +) + +func TestEditorFindBorrowsUnicodeSourceAndPlansReplacements(t *testing.T) { + c := NewClient() + replacement := "${1}!" + got, err := c.FindEditorText(context.Background(), []byte("😀 αβ\nαβ"), EditorFindRequest{Query: "(αβ)", Regex: true, Replacement: &replacement}) + if err != nil { + t.Fatal(err) + } + if len(got.Matches) != 2 || got.Matches[0].Start != 5 || got.Matches[1].Start != 10 || len(got.Edits) != 2 || got.Edits[0].Text != "αβ!" { + t.Fatalf("unexpected Unicode plan: %+v", got) + } + _, err = c.FindEditorText(context.Background(), []byte("secret"), EditorFindRequest{Query: "[", Regex: true}) + var failure *Error + if !errors.As(err, &failure) || failure.Details != "invalid_pattern" { + t.Fatalf("invalid regex: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err = c.FindEditorText(ctx, []byte("x"), EditorFindRequest{Query: "x"}); !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled search: %v", err) + } +} + +func TestEditorEssentialsResolveDefaultsAndKeepIndependentSchemes(t *testing.T) { + c := NewClient() + ctx := context.Background() + prefs, err := c.ResolveEditorPreferences(ctx, EditorStoredPreferences{}) + if err != nil { + t.Fatal(err) + } + if !prefs.LineNumbers || !prefs.CursorBlink || prefs.CursorStyle != "line" || prefs.AutoSaveDelayMilliseconds != 1500 { + t.Fatalf("preferences: %+v", prefs) + } + state, err := c.ReduceKeymapSchemes(ctx, KeymapSchemeRequest{Current: map[string][]string{"search.files": {"meta+f"}}}) + if err != nil { + t.Fatal(err) + } + cloned, err := c.ReduceKeymapSchemes(ctx, KeymapSchemeRequest{State: state.State, Operation: "saveAs", ID: "mine", Name: "Mine"}) + if err != nil { + t.Fatal(err) + } + if cloned.State.Active != "mine" || len(cloned.State.Schemes) != 2 || cloned.Bindings["search.files"][0] != "meta+f" { + t.Fatalf("scheme: %+v", cloned) + } + recent, err := c.ReduceEditorRecent(ctx, EditorRecentRequest{Event: &EditorRecentEvent{Kind: "edited", Path: "src/a.go", Name: "a.go", Line: 2}}) + if err != nil || len(recent.Results) != 1 || recent.Results[0].Line != 2 { + t.Fatalf("recent: %+v %v", recent, err) + } + decision, err := c.DecideEditorRecovery(ctx, EditorRecoveryRequest{BaseHash: "old"}) + if err != nil || decision.Action != "restoreConflict" { + t.Fatalf("recovery: %+v %v", decision, err) + } +} diff --git a/desktop/internal/draftstore/store.go b/desktop/internal/draftstore/store.go new file mode 100644 index 0000000000..eae9143b54 --- /dev/null +++ b/desktop/internal/draftstore/store.go @@ -0,0 +1,215 @@ +// Package draftstore owns atomic recovery files in application data, never the installation +// or project. Core supplies recovery policy and limits; this adapter performs native I/O. +package draftstore + +import ( + "bufio" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "strings" + "sync" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +type Entry struct { + Root string `json:"root"` + Path string `json:"path"` + Name string `json:"name"` + Scratch bool `json:"scratch"` + BaseHash string `json:"baseHash"` + Text string `json:"-"` + Line int `json:"line"` + Column int `json:"column"` +} + +// All windows in this process serialize native recovery I/O, including quota checks. +// This lock is never acquired by the UI thread. +var recoveryIO sync.Mutex + +const maxHeaderBytes = 64 * 1024 + +type Store struct { + dir string + limits core.EditorRecoveryDecision +} + +func New(dir string, limits core.EditorRecoveryDecision) *Store { + return &Store{dir: filepath.Join(dir, "EditorRecovery"), limits: limits} +} +func Key(path string) string { sum := sha256.Sum256([]byte(path)); return hex.EncodeToString(sum[:]) } +func Hash(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) } +func (s *Store) filename(root, path string) string { + return filepath.Join(s.dir, Key(root+"\x00"+path)+".draft") +} +func (s *Store) Load(root, path string) (Entry, bool, error) { + recoveryIO.Lock() + defer recoveryIO.Unlock() + entry, found, err := s.read(s.filename(root, path), true) + if err == nil && found && (entry.Root != root || entry.Path != path) { + return Entry{}, false, errors.New("recovery identity does not match") + } + return entry, found, err +} +func (s *Store) read(path string, contents bool) (entry Entry, found bool, err error) { + file, err := os.Open(path) + if errors.Is(err, os.ErrNotExist) { + return entry, false, nil + } + if err != nil { + return entry, false, err + } + defer func() { err = errors.Join(err, file.Close()) }() + reader := bufio.NewReaderSize(file, maxHeaderBytes+1) + header, err := reader.ReadSlice('\n') + if err != nil { + return entry, false, err + } + if len(header) > maxHeaderBytes { + return entry, false, errors.New("recovery metadata exceeds limit") + } + if err = json.Unmarshal(header, &entry); err != nil { + return entry, false, err + } + if !contents { + return entry, true, nil + } + data, err := io.ReadAll(io.LimitReader(reader, s.limits.MaxDocumentBytes+1)) + if err != nil { + return entry, false, err + } + if int64(len(data)) > s.limits.MaxDocumentBytes || !utf8.Valid(data) { + return entry, false, errors.New("recovery source is invalid or exceeds limit") + } + entry.Text = string(data) + return entry, true, nil +} +func (s *Store) files() (entries []os.DirEntry, err error) { + directory, err := os.Open(s.dir) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + defer func() { err = errors.Join(err, directory.Close()) }() + // A fixed directory bound also limits corrupted/foreign checkpoint inventories. + files, err := directory.ReadDir(s.limits.MaxDocuments*2 + 1) + if err != nil && err != io.EOF { + return nil, err + } + if len(files) > s.limits.MaxDocuments*2 { + return nil, errors.New("recovery directory exceeds limit") + } + return files, nil +} +func (s *Store) List(root string, scratch bool) ([]Entry, error) { + recoveryIO.Lock() + defer recoveryIO.Unlock() + files, err := s.files() + if err != nil { + return nil, err + } + entries := []Entry{} + for _, file := range files { + if file.IsDir() || filepath.Ext(file.Name()) != ".draft" { + continue + } + entry, ok, err := s.read(filepath.Join(s.dir, file.Name()), false) + if err != nil { + return nil, err + } + if ok && entry.Root == root && entry.Scratch == scratch { + entries = append(entries, entry) + } + } + return entries, nil +} +func (s *Store) Save(entry Entry) error { + return s.SaveSource(entry, int64(len(entry.Text)), func(w io.Writer) error { _, err := io.Copy(w, strings.NewReader(entry.Text)); return err }) +} + +// SaveSource streams an immutable native buffer; checkpointing needs no full JSON/text copy. +// The metadata and source commit in one atomic file, so a crash cannot mix generations. +func (s *Store) SaveSource(entry Entry, size int64, write func(io.Writer) error) (err error) { + recoveryIO.Lock() + defer recoveryIO.Unlock() + if size < 0 || size > s.limits.MaxDocumentBytes { + return errors.New("recovery source exceeds limit") + } + header, err := json.Marshal(entry) + if err != nil { + return err + } + header = append(header, '\n') + if len(header) > maxHeaderBytes { + return errors.New("recovery metadata exceeds limit") + } + if err := os.MkdirAll(s.dir, 0700); err != nil { + return err + } + files, err := s.files() + if err != nil { + return err + } + filename := s.filename(entry.Root, entry.Path) + var total int64 + count := 0 + for _, file := range files { + if file.IsDir() || filepath.Ext(file.Name()) != ".draft" { + continue + } + count++ + if filepath.Join(s.dir, file.Name()) == filename { + count-- + continue + } + info, err := file.Info() + if err != nil { + return err + } + total += info.Size() + } + if count >= s.limits.MaxDocuments || total+int64(len(header))+size > s.limits.MaxStorageBytes { + return errors.New("recovery storage is full") + } + temp, err := os.CreateTemp(s.dir, ".checkpoint-*") + if err != nil { + return err + } + temporary := temp.Name() + defer func() { + if cleanup := os.Remove(temporary); cleanup != nil && !errors.Is(cleanup, os.ErrNotExist) { + err = errors.Join(err, cleanup) + } + }() + if _, err = temp.Write(header); err == nil { + err = write(temp) + } + if err == nil { + err = temp.Sync() + } + closeErr := temp.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + return os.Rename(temporary, filename) +} +func (s *Store) Remove(root, path string) error { + recoveryIO.Lock() + defer recoveryIO.Unlock() + err := os.Remove(s.filename(root, path)) + if errors.Is(err, os.ErrNotExist) { + return nil + } + return err +} diff --git a/desktop/internal/draftstore/store_test.go b/desktop/internal/draftstore/store_test.go new file mode 100644 index 0000000000..12c80dc9f9 --- /dev/null +++ b/desktop/internal/draftstore/store_test.go @@ -0,0 +1,42 @@ +package draftstore + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "testing" +) + +func TestRecoveryStoreAtomicOverwriteAndQuotaPreservePriorContents(t *testing.T) { + dir := t.TempDir() + limits := core.EditorRecoveryDecision{MaxDocumentBytes: 32, MaxStorageBytes: 4096, MaxDocuments: 1} + s := New(dir, limits) + entry := Entry{Root: "workspace", Path: "a.txt", Text: "first"} + if err := s.Save(entry); err != nil { + t.Fatal(err) + } + entry.Text = "updated 😀" + if err := s.Save(entry); err != nil { + t.Fatal(err) + } + if err := s.Save(Entry{Root: "workspace", Path: "b.txt", Text: "full"}); err == nil { + t.Fatal("document cap ignored") + } + fresh := New(dir, limits) + got, found, err := fresh.Load("workspace", "a.txt") + if err != nil || !found || got.Text != "updated 😀" { + t.Fatalf("reopened checkpoint: %+v %v %v", got, found, err) + } + entry.Text = "012345678901234567890123456789012" + if err := s.Save(entry); err == nil { + t.Fatal("source cap ignored") + } + got, _, err = fresh.Load("workspace", "a.txt") + if err != nil || got.Text != "updated 😀" { + t.Fatal("rejected save destroyed prior checkpoint") + } + if err = s.Remove("workspace", "a.txt"); err != nil { + t.Fatal(err) + } + if err = s.Remove("workspace", "a.txt"); err != nil { + t.Fatal(err) + } +} diff --git a/desktop/internal/editorview/multicaret.go b/desktop/internal/editorview/multicaret.go index ee72c51c5a..7689ae915a 100644 --- a/desktop/internal/editorview/multicaret.go +++ b/desktop/internal/editorview/multicaret.go @@ -371,7 +371,7 @@ func (v *View) paintExtraCarets(canvas *gfx.Canvas, look Look) { for _, s := range v.extra { v.caret = s.caret x, y := v.caretPoint() - canvas.Fill(gfx.Rect{X: float32(int(x + 0.5)), Y: y, Width: 2, Height: v.lineH}, look.Caret) + v.paintConfiguredCaret(canvas, x, y, look.Caret) } v.caret = primary } diff --git a/desktop/internal/editorview/paint.go b/desktop/internal/editorview/paint.go index ea66be687f..e6b7450397 100644 --- a/desktop/internal/editorview/paint.go +++ b/desktop/internal/editorview/paint.go @@ -31,6 +31,7 @@ const ( // view's hits, so the view takes the pointer and the keyboard where it was painted. func (v *View) Paint(canvas *gfx.Canvas, area gfx.Rect, look Look) { v.clock = canvas.Now() + v.whitespaceColor = look.Subtle font := v.font cellW, cellH := canvas.MonoCellSize(font.Size, font.Face) if cellW <= 0 || cellH <= 0 || area.Width <= 0 || area.Height <= 0 { @@ -57,6 +58,9 @@ func (v *View) Paint(canvas *gfx.Canvas, area gfx.Rect, look Look) { digits := v.gutterDigits(lines) // The gutter is the numbers with their padding, then the icon column, then the fold arrows. numbersEnd := float32(digits)*cellW + 2*gutterPad + if v.presentation.HideLineNumbers && !v.decor.labelled { + numbersEnd = 2 * gutterPad + } gutter := numbersEnd + v.lineIconColumn() + v.foldColumn() v.iconX = area.X + numbersEnd + lineIconInset v.numbersRight = area.X + numbersEnd @@ -173,6 +177,7 @@ func (v *View) Paint(canvas *gfx.Canvas, area gfx.Rect, look Look) { end = wraps[k+1].at } p := v.part(l, row, end, from, to) + v.paintSearchMatches(canvas, l, p, from, to, shift, y, look.Selection) if line == caretLine && k == composeRow && composeCells > 0 { // The input method draws the text being composed at the caret, over the // editor. The rest of the row moves right to make room for it, so no glyph @@ -190,7 +195,7 @@ func (v *View) Paint(canvas *gfx.Canvas, area gfx.Rect, look Look) { } top += float32(len(wraps)) * v.lineH } - if v.focused && !v.preedit.Composing && (v.vimBlock() || v.blinkOn(canvas)) { + if v.focused && !v.preedit.Composing && (v.vimBlock() || v.presentation.DisableCursorBlink || v.blinkOn(canvas)) { if len(v.extra) > 0 { v.paintExtraCarets(canvas, look) } @@ -202,7 +207,7 @@ func (v *View) Paint(canvas *gfx.Canvas, area gfx.Rect, look Look) { block.Alpha *= 0.6 canvas.Fill(gfx.Rect{X: float32(math.Round(float64(x))), Y: y, Width: v.cellW, Height: v.lineH}, block) } else { - canvas.Fill(gfx.Rect{X: float32(math.Round(float64(x))), Y: y, Width: 2, Height: v.lineH}, look.Caret) + v.paintConfiguredCaret(canvas, x, y, look.Caret) } } canvas.Unclip() @@ -233,6 +238,9 @@ func (v *View) Paint(canvas *gfx.Canvas, area gfx.Rect, look Look) { v.paintBreakpoint(canvas, look, points[point], area.X+gutterBarX+gutterBarWidth, area.X+numbersEnd, number.y) continue } + if v.presentation.HideLineNumbers && !v.decor.labelled { + continue + } label := v.lineLabel(number.line) n := len(label) if n == 0 { @@ -440,6 +448,7 @@ func (v *View) paintRow(canvas *gfx.Canvas, text string, base int, row wrapRow, if cells >= to { break } + v.paintWhitespace(canvas, r, cells, width, shift, y) if r == '\t' || r < 0x20 { v.paintLabel(canvas, text[labelAt-base:labelTo-base], label, labelEnd, shift, y, textStyle) label = -1 diff --git a/desktop/internal/editorview/prepared_edit.go b/desktop/internal/editorview/prepared_edit.go new file mode 100644 index 0000000000..38504ff7b0 --- /dev/null +++ b/desktop/internal/editorview/prepared_edit.go @@ -0,0 +1,102 @@ +package editorview + +import ( + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" +) + +// PreparedEdit is an immutable native text replacement laid out on a worker. +// Core has already planned the edit; this only prepares the native rope and reporting span. +type PreparedEdit struct { + before, after, saved rope.Rope + dirty bool + change Edit + caret, widest int +} + +// PrepareEdits must run off the UI thread. A bulk replacement builds its rope and +// measures width here, so applying the result does not rebuild a document in Paint. +func PrepareEdits(before, saved rope.Rope, edits []TextEdit) (PreparedEdit, error) { + after := before + last := 0 + for _, e := range edits { + if e.Start < last { + return PreparedEdit{}, ErrOverlap + } + if e.Start < 0 || e.End < e.Start || e.End > before.Len() || inside(before, e.Start) || inside(before, e.End) { + return PreparedEdit{}, ErrPosition + } + last = e.End + } + for i := len(edits) - 1; i >= 0; i-- { + e := edits[i] + after = after.Replace(e.Start, e.End, []byte(e.Text)) + } + prepared := PreparedEdit{before: before, after: after, saved: saved, dirty: !after.Equal(saved)} + if len(edits) == 0 { + return prepared, nil + } + start, end, newEnd := rope.Diff(before, after) + if start == end && start == newEnd { + prepared.after = before + return prepared, nil + } + prepared.widest = widestLine(after, 0, after.LineCount()-1) + text, _ := after.Substring(start, newEnd) + prepared.change.Text = strings.Clone(text) + prepared.change.StartLine, prepared.change.StartColumn = SnapshotUTF16(before, start) + prepared.change.EndLine, prepared.change.EndColumn = SnapshotUTF16(before, end) + tail := edits[len(edits)-1] + prepared.caret = tail.Start + len(tail.Text) + for _, e := range edits[:len(edits)-1] { + prepared.caret += len(e.Text) - (e.End - e.Start) + } + return prepared, nil +} + +// ApplyPreparedEdit keeps saved contents and undo history while replacing the native +// buffer. A stale result, composing input or a read-only view changes nothing. +func (v *View) ApplyPreparedEdit(prepared PreparedEdit) bool { + if v.readOnly || v.preedit.Composing || !v.text.Same(prepared.before) || !v.saved.Same(prepared.saved) { + return false + } + if v.text.Same(prepared.after) { + return true + } + v.undo = append(v.undo, v.snapshot()) + if len(v.undo) > undoLimit { + v.undo = v.undo[len(v.undo)-undoLimit:] + } + v.redo = v.redo[:0] + v.extra = nil + v.text = prepared.after + v.widest = prepared.widest + v.revision++ + v.clearCursorHistory() + v.hl.SetText(v.text) + v.forgetRows() + v.anchor, v.caret = prepared.caret, prepared.caret + v.lastKind, v.goal = editOther, -1 + v.dirty = prepared.dirty + v.moved() + v.reportEdit(prepared.change) + return true +} + +// SnapshotUTF16 computes the native line and UTF-16 column of a byte offset. Call on a +// worker for unbounded source lines; capturing the offset and immutable rope is O(1). +func SnapshotUTF16(snapshot rope.Rope, at int) (line, column int) { + at = min(max(at, 0), snapshot.Len()) + line = snapshot.LineOf(at) + snapshot.Chunks(snapshot.LineStart(line), at, func(chunk string) bool { + for _, r := range chunk { + column++ + if r > 0xffff { + column++ + } + } + return true + }) + return +} diff --git a/desktop/internal/editorview/prepared_edit_test.go b/desktop/internal/editorview/prepared_edit_test.go new file mode 100644 index 0000000000..5861077b83 --- /dev/null +++ b/desktop/internal/editorview/prepared_edit_test.go @@ -0,0 +1,45 @@ +package editorview + +import "testing" + +func TestPreparedBulkEditIsAtomicUndoableAndRejectsStaleText(t *testing.T) { + v := newTestView(t, "a 😀 a") + prepared, err := PrepareEdits(v.TextSnapshot(), v.SavedSnapshot(), []TextEdit{{Range{0, 1}, "ALPHA"}, {Range{7, 8}, "β"}}) + if err != nil { + t.Fatal(err) + } + if !v.ApplyPreparedEdit(prepared) || v.contents() != "ALPHA 😀 β" { + t.Fatalf("prepared content: %q", v.contents()) + } + v.Undo() + if v.contents() != "a 😀 a" { + t.Fatalf("undo: %q", v.contents()) + } + v.typeText("x") + if v.ApplyPreparedEdit(prepared) { + t.Fatal("stale edit changed the document") + } +} + +func TestPreparedBulkEditRejectsChangedSavedBaselineAndKeepsNoOpOutOfUndo(t *testing.T) { + v := newTestView(t, "one") + v.SetSelection(3, 3) + v.typeText("!") + before := v.TextSnapshot() + prepared, err := PrepareEdits(before, v.SavedSnapshot(), []TextEdit{{Range{0, 3}, "two"}}) + if err != nil { + t.Fatal(err) + } + v.MarkSaved(before) + if v.ApplyPreparedEdit(prepared) || v.contents() != "one!" { + t.Fatal("saved baseline race was not rejected") + } + noOp, err := PrepareEdits(before, v.SavedSnapshot(), []TextEdit{{Range{0, 3}, "one"}}) + if err != nil { + t.Fatal(err) + } + count := len(v.undo) + if !v.ApplyPreparedEdit(noOp) || len(v.undo) != count || v.Dirty() { + t.Fatal("identical replacement added undo or changed dirty state") + } +} diff --git a/desktop/internal/editorview/presentation.go b/desktop/internal/editorview/presentation.go new file mode 100644 index 0000000000..ac0bfb09f1 --- /dev/null +++ b/desktop/internal/editorview/presentation.go @@ -0,0 +1,77 @@ +package editorview + +import ( + "sort" + + "github.com/vivaui/viva/gfx" +) + +// Presentation contains native drawing choices already resolved by the owner. +// Its zero value preserves the existing appearance for embedded editor consumers. +type Presentation struct { + HideLineNumbers bool + ShowWhitespace bool + CursorStyle string + DisableCursorBlink bool +} + +func (v *View) SetPresentation(value Presentation) { v.presentation = value } + +// SetSearchMatches installs Core's ordered byte ranges for this exact revision. +// A text edit invalidates their paint immediately, before a new worker can answer. +func (v *View) SetSearchMatches(matches []Range) { + v.searchRanges = append(v.searchRanges[:0], matches...) + v.searchRevision = v.revision +} + +func (v *View) ClearSearchMatches() { v.searchRanges = nil } + +func (v *View) paintSearchMatches(canvas *gfx.Canvas, l lineRef, p part, from, to, shift int, y float32, color gfx.Color) { + if v.searchRevision != v.revision || len(v.searchRanges) == 0 { + return + } + start, end := l.start+p.base, l.start+p.base+len(p.text) + first := sort.Search(len(v.searchRanges), func(i int) bool { return v.searchRanges[i].End >= start }) + color.Alpha *= 0.45 + for i := first; i < len(v.searchRanges) && v.searchRanges[i].Start <= end; i++ { + match := v.searchRanges[i] + lo, hi := v.selectionCells(l, match.Start, match.End) + if match.Start == match.End { + lo = v.cellsAt(l, match.Start-l.start) + hi = lo + 1 + } + lo, hi = max(lo, from), min(hi, to) + if hi <= lo { + continue + } + x := v.textLeft + float32(lo-shift)*v.cellW - v.scrollX + canvas.Fill(gfx.Rect{X: x, Y: y, Width: float32(hi-lo) * v.cellW, Height: v.lineH}, color) + } +} + +func (v *View) paintConfiguredCaret(canvas *gfx.Canvas, x, y float32, color gfx.Color) { + rect := gfx.Rect{X: float32(int(x + 0.5)), Y: y, Width: 2, Height: v.lineH} + switch v.presentation.CursorStyle { + case "block": + rect.Width = v.cellW + color.Alpha *= 0.6 + case "underline": + rect.Width = v.cellW + rect.Y += v.lineH - 2 + rect.Height = 2 + } + canvas.Fill(rect, color) +} + +func (v *View) paintWhitespace(canvas *gfx.Canvas, r rune, cells, width, shift int, y float32) { + if !v.presentation.ShowWhitespace || (r != ' ' && r != '\t') { + return + } + x := v.textLeft + float32(cells-shift)*v.cellW - v.scrollX + if r == ' ' { + canvas.Fill(gfx.Rect{X: x + v.cellW/2 - 0.75, Y: y + v.lineH/2 - 0.75, Width: 1.5, Height: 1.5}, v.whitespaceColor) + } else { + canvas.Fill(gfx.Rect{X: x + 2, Y: y + v.lineH/2, Width: max(float32(width)*v.cellW-4, 1), Height: 1}, v.whitespaceColor) + canvas.Fill(gfx.Rect{X: x + float32(width)*v.cellW - 4, Y: y + v.lineH/2 - 2, Width: 1, Height: 5}, v.whitespaceColor) + } +} diff --git a/desktop/internal/editorview/presentation_test.go b/desktop/internal/editorview/presentation_test.go new file mode 100644 index 0000000000..54c504a8cd --- /dev/null +++ b/desktop/internal/editorview/presentation_test.go @@ -0,0 +1,61 @@ +package editorview + +import ( + "github.com/vivaui/viva/gfx" + "testing" +) + +func TestPresentationHidesNumbersWithoutLosingBreakpointMargin(t *testing.T) { + v := newTestView(t, "one\ntwo\nthree") + canvas := new(gfx.Canvas) + area := gfx.Rect{Width: 600, Height: 300} + v.Paint(canvas, area, Look{}) + before := v.textLeft + if len(numberLabels(canvas, v)) != 3 { + t.Fatal("initial line numbers missing") + } + v.SetPresentation(Presentation{HideLineNumbers: true}) + paintAgain(v, canvas, area) + if len(numberLabels(canvas, v)) != 0 || v.textLeft >= before || v.textLeft <= textPad { + t.Fatalf("hidden numbers: left=%v before=%v", v.textLeft, before) + } +} + +func TestSearchHighlightInvalidatesWhenDocumentChanges(t *testing.T) { + v := newTestView(t, "alpha beta") + v.SetSearchMatches([]Range{{0, 5}}) + if v.searchRevision != v.revision || len(v.searchRanges) != 1 { + t.Fatal("search ranges were not installed") + } + v.typeText("x") + if v.searchRevision == v.revision { + t.Fatal("edit left the searched revision current") + } + v.ClearSearchMatches() + if len(v.searchRanges) != 0 { + t.Fatal("closed find retained ranges") + } +} + +func TestConfiguredCaretStyleAppliesToTheNativePaint(t *testing.T) { + v := newTestView(t, "x") + v.cellW, v.lineH = 8, 18 + for _, style := range []string{"line", "block", "underline"} { + v.SetPresentation(Presentation{CursorStyle: style}) + canvas := new(gfx.Canvas) + v.paintConfiguredCaret(canvas, 20, 30, gfx.RGB24(0xffffff)) + if len(canvas.Rectangles()) != 1 { + t.Fatalf("%s caret count: %d", style, len(canvas.Rectangles())) + } + width, height := float32(2), float32(18) + if style == "block" { + width = 8 + } + if style == "underline" { + width, height = 8, 2 + } + if rect := canvas.Rectangles()[0].Bounds; rect.Width != width || rect.Height != height { + t.Fatalf("%s caret: %+v", style, rect) + } + } +} diff --git a/desktop/internal/editorview/view.go b/desktop/internal/editorview/view.go index 40db6307dd..ca89315d37 100644 --- a/desktop/internal/editorview/view.go +++ b/desktop/internal/editorview/view.go @@ -213,8 +213,12 @@ type View struct { mm minimapState // hlGen counts the highlighter's reports of lines colored anew, from its goroutine, so // the minimap knows its colors are stale. - hlGen atomic.Uint64 - words Messages + hlGen atomic.Uint64 + words Messages + presentation Presentation + whitespaceColor gfx.Color + searchRanges []Range + searchRevision int // font is the font the view draws with, normalized; see SetFont. The cell size and line height // below are measured from it at each paint. diff --git a/desktop/internal/i18n/command_messages.go b/desktop/internal/i18n/command_messages.go index 2a8232bdef..dec1f7eb38 100644 --- a/desktop/internal/i18n/command_messages.go +++ b/desktop/internal/i18n/command_messages.go @@ -2,6 +2,7 @@ package i18n // CommandMessages name the actions of the command catalog (Find Action). type CommandMessages struct { + Find, Replace, RecentFiles, RecentEdits, NewScratch, ScratchFiles, SaveAs string AddNextOccurrence, UnselectOccurrence, SelectAllOccurrences, CloneCaretAbove, CloneCaretBelow string GroupEditor, GroupApp, GroupView, GroupProject, GroupToolWindows, GroupSearch, GroupGit, GroupRun, GroupTerminal, Settings, Plugins, Logs, ImportLegacy, ThemeSystem, ThemeLight, ThemeDark, LanguageEnglish, LanguageChinese, OpenProject, NewProject, Clone, CloseProject, SaveAll, SearchEverywhere, FindInFiles, ReplaceInFiles, Commit, CommitAndPush, Branches, GitConsole, Run, Debug, ToggleBreakpoint, NewTerminal, NoActions, FindAction, GitNextChange, GitPreviousChange, Fold, Unfold, FoldAll, UnfoldAll, ToggleVim string // ShowTool is the action that shows a tool window by its name. @@ -10,6 +11,7 @@ type CommandMessages struct { func commandMessages(language Language) CommandMessages { return CommandMessages{ + Find: Shared(language, "desktop.editorFind.find"), Replace: Shared(language, "desktop.editorFind.replace"), RecentFiles: Shared(language, "desktop.recentFiles.title"), RecentEdits: Shared(language, "desktop.recentFiles.edited"), NewScratch: Shared(language, "desktop.drafts.new"), ScratchFiles: Shared(language, "desktop.drafts.list"), SaveAs: Shared(language, "desktop.drafts.saveAs"), GroupApp: Shared(language, "desktop.command.groupApp"), GroupView: Shared(language, "desktop.command.groupView"), GroupEditor: Shared(language, "desktop.command.groupEditor"), diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index ee87c8bbe7..01f7966848 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -342,6 +342,16 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.document.externalReadFailed": "Could not check the file for external changes.", "desktop.document.hardLinkCancel": "Cancel", "desktop.document.watchUnavailable": "Could not monitor open files for external changes. Saving still checks the disk.", + "desktop.drafts.conflict": "Draft recovered. The disk file changed; compare the versions before choosing which to keep.", + "desktop.drafts.discard": "Discard draft", + "desktop.drafts.empty": "No scratch files.", + "desktop.drafts.failed": "Could not save the recovery copy. Unsaved contents remain in the editor.", + "desktop.drafts.list": "Scratch files", + "desktop.drafts.new": "New scratch file", + "desktop.drafts.recovered": "Unsaved contents were recovered.", + "desktop.drafts.saveAs": "Save As…", + "desktop.drafts.saved": "The draft was saved to a file.", + "desktop.drafts.untitled": "Untitled {number}", "desktop.editor.dropFiles": "Drop files here to open them", "desktop.editor.goToFile": "Go to File", "desktop.editor.hiddenTabs": "Show Hidden Tabs", @@ -371,6 +381,26 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editor.vimModeHelp": "Edit with Vim key bindings: Normal, Insert and Visual modes.", "desktop.editorActions.failed": "The plugin could not run this action.", "desktop.editorActions.stale": "The document changed. Wait for the actions to update.", + "desktop.editorFind.case": "Match case", + "desktop.editorFind.close": "Close find", + "desktop.editorFind.count": "{current}/{total}", + "desktop.editorFind.failed": "Could not complete the search or replacement.", + "desktop.editorFind.find": "Find", + "desktop.editorFind.invalidPattern": "The regular expression is invalid.", + "desktop.editorFind.loading": "Searching…", + "desktop.editorFind.next": "Next match", + "desktop.editorFind.previous": "Previous match", + "desktop.editorFind.regex": "Regular expression", + "desktop.editorFind.replace": "Replace", + "desktop.editorFind.replaceAll": "Replace all", + "desktop.editorFind.replaceOne": "Replace current", + "desktop.editorFind.replaced": "Replaced {count} occurrences.", + "desktop.editorFind.replacementTooLarge": "The replacement is too large. Narrow the scope.", + "desktop.editorFind.selection": "In selection", + "desktop.editorFind.stale": "The document changed. Retry the replacement.", + "desktop.editorFind.tooLarge": "This file exceeds the 64 MiB search limit.", + "desktop.editorFind.tooMany": "More than 10,000 matches. Narrow the scope before replacing all.", + "desktop.editorFind.word": "Whole words", "desktop.editorMenu.back": "Back", "desktop.editorMenu.deleteLine": "Delete Line", "desktop.editorMenu.duplicateLine": "Duplicate Line", @@ -386,6 +416,17 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorMenu.reformat": "Reformat Code", "desktop.editorMenu.rename": "Rename Symbol", "desktop.editorMenu.toggleComment": "Toggle Line Comment", + "desktop.editorPrefs.block": "Block", + "desktop.editorPrefs.cursorBlink": "Blink caret", + "desktop.editorPrefs.cursorStyle": "Caret style", + "desktop.editorPrefs.failed": "Could not update editor settings.", + "desktop.editorPrefs.line": "Line", + "desktop.editorPrefs.lineNumbers": "Show line numbers", + "desktop.editorPrefs.saveDelay": "Auto-save delay (ms)", + "desktop.editorPrefs.saveDelayHelp": "Wait this long after typing before auto-saving (250–60,000 ms). Disabled when auto-save is off. Draft recovery is independent.", + "desktop.editorPrefs.title": "Editor display", + "desktop.editorPrefs.underline": "Underline", + "desktop.editorPrefs.whitespace": "Show whitespace", "desktop.encoding.reopen": "Reopen with Encoding", "desktop.encoding.reopenDirty": "Save or discard your changes before reopening with another encoding.", "desktop.encoding.reopenFailed": "Could not reopen the file with that encoding.", @@ -719,6 +760,18 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.keymap.searchPlaceholder": "Filter by name or key", "desktop.keymap.toggleFullscreen": "Toggle Full Screen", "desktop.keymap.unbindable": "A letter or symbol needs Command, Control or Option so typing never runs an action.", + "desktop.keymapSchemes.default": "Default", + "desktop.keymapSchemes.delete": "Delete scheme", + "desktop.keymapSchemes.duplicateName": "A scheme with this name already exists.", + "desktop.keymapSchemes.failed": "Could not update keymap schemes. The original scheme is preserved.", + "desktop.keymapSchemes.invalidName": "Enter a scheme name of 1–64 characters.", + "desktop.keymapSchemes.limit": "Up to 16 keymap schemes can be saved.", + "desktop.keymapSchemes.name": "Scheme name", + "desktop.keymapSchemes.newTitle": "Save keymap scheme", + "desktop.keymapSchemes.rename": "Rename scheme…", + "desktop.keymapSchemes.renameTitle": "Rename keymap scheme", + "desktop.keymapSchemes.saveAs": "Save as new scheme…", + "desktop.keymapSchemes.scheme": "Keymap scheme", "desktop.languageStatus.degraded": "Degraded", "desktop.languageStatus.failed": "Failed", "desktop.languageStatus.none": "Not running", @@ -1010,6 +1063,11 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.rebase.start": "Start Rebase", "desktop.rebase.status": "Rebase: {status}", "desktop.rebase.title": "Rebase from Here", + "desktop.recentFiles.edited": "Recent edits", + "desktop.recentFiles.empty": "No matching recent files.", + "desktop.recentFiles.failed": "Could not read recent files.", + "desktop.recentFiles.query": "Search recent files", + "desktop.recentFiles.title": "Recent files", "desktop.references.empty": "Run Find Usages (Shift+F12) to list references here.", "desktop.refs.checkedOutAndRebased": "Checked out {branch} and rebased it onto the previous branch", "desktop.refs.mergeConfirm": "Merge {branch} into the current branch. If Git stops at conflicts, the Commit tool window shows the merge until you continue or abort it.", @@ -2696,6 +2754,16 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.document.externalReadFailed": "无法检查文件的外部变化。", "desktop.document.hardLinkCancel": "取消", "desktop.document.watchUnavailable": "无法监听打开文件的外部变化。保存时仍会检查磁盘内容。", + "desktop.drafts.conflict": "已恢复草稿;磁盘文件已更改,请比较后决定保留哪一份。", + "desktop.drafts.discard": "丢弃草稿", + "desktop.drafts.empty": "没有临时草稿。", + "desktop.drafts.failed": "无法保存恢复副本,未保存内容仍保留在编辑器中。", + "desktop.drafts.list": "临时草稿", + "desktop.drafts.new": "新建临时草稿", + "desktop.drafts.recovered": "已恢复未保存内容。", + "desktop.drafts.saveAs": "另存为…", + "desktop.drafts.saved": "草稿已另存为文件。", + "desktop.drafts.untitled": "临时草稿 {number}", "desktop.editor.dropFiles": "将文件拖到此处打开", "desktop.editor.goToFile": "转到文件", "desktop.editor.hiddenTabs": "显示隐藏的标签页", @@ -2725,6 +2793,26 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editor.vimModeHelp": "使用 Vim 按键编辑:普通、插入和可视模式。", "desktop.editorActions.failed": "插件无法执行此动作。", "desktop.editorActions.stale": "文档已变化,请等待动作更新。", + "desktop.editorFind.case": "区分大小写", + "desktop.editorFind.close": "关闭查找", + "desktop.editorFind.count": "{current}/{total}", + "desktop.editorFind.failed": "无法完成查找或替换。", + "desktop.editorFind.find": "查找", + "desktop.editorFind.invalidPattern": "正则表达式无效。", + "desktop.editorFind.loading": "正在查找…", + "desktop.editorFind.next": "下一个匹配", + "desktop.editorFind.previous": "上一个匹配", + "desktop.editorFind.regex": "正则表达式", + "desktop.editorFind.replace": "替换", + "desktop.editorFind.replaceAll": "全部替换", + "desktop.editorFind.replaceOne": "替换当前", + "desktop.editorFind.replaced": "已替换 {count} 处。", + "desktop.editorFind.replacementTooLarge": "替换结果过大,请缩小范围。", + "desktop.editorFind.selection": "仅在选区中", + "desktop.editorFind.stale": "文档已更改,请重试替换。", + "desktop.editorFind.tooLarge": "此文件超过查找的 64 MiB 上限。", + "desktop.editorFind.tooMany": "匹配超过 10000 处;请缩小范围后再全部替换。", + "desktop.editorFind.word": "整词匹配", "desktop.editorMenu.back": "后退", "desktop.editorMenu.deleteLine": "删除行", "desktop.editorMenu.duplicateLine": "复制行", @@ -2740,6 +2828,17 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorMenu.reformat": "格式化代码", "desktop.editorMenu.rename": "重命名符号", "desktop.editorMenu.toggleComment": "切换行注释", + "desktop.editorPrefs.block": "方块", + "desktop.editorPrefs.cursorBlink": "光标闪烁", + "desktop.editorPrefs.cursorStyle": "光标样式", + "desktop.editorPrefs.failed": "无法更新编辑器设置。", + "desktop.editorPrefs.line": "竖线", + "desktop.editorPrefs.lineNumbers": "显示行号", + "desktop.editorPrefs.saveDelay": "自动保存延迟(毫秒)", + "desktop.editorPrefs.saveDelayHelp": "停止输入后等待此时间再自动保存。范围为 250–60000 毫秒;关闭自动保存时不执行。草稿恢复独立保留。", + "desktop.editorPrefs.title": "编辑器显示", + "desktop.editorPrefs.underline": "下划线", + "desktop.editorPrefs.whitespace": "显示空白字符", "desktop.encoding.reopen": "按编码重新打开", "desktop.encoding.reopenDirty": "请先保存或放弃修改,再按其他编码重新打开。", "desktop.encoding.reopenFailed": "无法按该编码重新打开文件。", @@ -3073,6 +3172,18 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.keymap.searchPlaceholder": "按名称或按键筛选", "desktop.keymap.toggleFullscreen": "切换全屏", "desktop.keymap.unbindable": "字母或符号需要配合 Command、Control 或 Option,避免普通输入触发操作。", + "desktop.keymapSchemes.default": "默认方案", + "desktop.keymapSchemes.delete": "删除方案", + "desktop.keymapSchemes.duplicateName": "此方案名称已存在。", + "desktop.keymapSchemes.failed": "无法更新快捷键方案,原方案仍然保留。", + "desktop.keymapSchemes.invalidName": "请输入 1–64 个字符的方案名称。", + "desktop.keymapSchemes.limit": "最多可保存 16 套快捷键方案。", + "desktop.keymapSchemes.name": "方案名称", + "desktop.keymapSchemes.newTitle": "保存快捷键方案", + "desktop.keymapSchemes.rename": "重命名方案…", + "desktop.keymapSchemes.renameTitle": "重命名快捷键方案", + "desktop.keymapSchemes.saveAs": "保存为新方案…", + "desktop.keymapSchemes.scheme": "快捷键方案", "desktop.languageStatus.degraded": "功能受限", "desktop.languageStatus.failed": "失败", "desktop.languageStatus.none": "未运行", @@ -3364,6 +3475,11 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.rebase.start": "开始变基", "desktop.rebase.status": "变基状态:{status}", "desktop.rebase.title": "从此处变基", + "desktop.recentFiles.edited": "最近编辑", + "desktop.recentFiles.empty": "没有匹配的最近文件。", + "desktop.recentFiles.failed": "无法读取最近文件记录。", + "desktop.recentFiles.query": "搜索最近文件", + "desktop.recentFiles.title": "最近文件", "desktop.references.empty": "使用“查找引用”(Shift+F12)后,结果显示在这里。", "desktop.refs.checkedOutAndRebased": "已检出 {branch} 并把它变基到之前的分支", "desktop.refs.mergeConfirm": "把 {branch} 合并到当前分支。如果 Git 因冲突停下,提交工具窗口会显示这次合并,直到你继续或中止。", diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index e0ed05a0a1..9bdecb0430 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -45,6 +45,9 @@ type PluginRuntimeState struct { // Values are the settings the window edits. A field is the value that is stored, so the // empty string is the one that follows the system. type Values struct { + EditorPreferences core.EditorPreferences + EditorStoredPreferences core.EditorStoredPreferences + KeymapSchemes core.KeymapSchemes // MarketplaceQuery is the text the marketplace search starts with when the window opens on // the plugin page; empty leaves it as it is. MarketplaceQuery string @@ -306,7 +309,9 @@ type Options struct { // behind; false hides the setting for them. SweepsLeftovers bool // SetKeymap hands a change of Values.Keymap to the settings owner, like SetTabRows. - SetKeymap func(shortcuts.Overrides) + SetKeymap func(shortcuts.Overrides) + SetEditorPreferences func(core.EditorStoredPreferences, core.EditorPreferences) + SetKeymapSchemes func(core.KeymapSchemeResult) // SetNetwork hands the Network page's applied settings to the settings owner, with the // password to store: nil keeps the stored one and an empty string removes it. Nil // leaves the page unavailable. diff --git a/desktop/internal/settingswindow/editor_essentials_test.go b/desktop/internal/settingswindow/editor_essentials_test.go new file mode 100644 index 0000000000..0edca4115a --- /dev/null +++ b/desktop/internal/settingswindow/editor_essentials_test.go @@ -0,0 +1,72 @@ +package settingswindow + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/shortcuts" + "testing" +) + +func TestEditorEssentialsDisplaySettingsApplyActualValues(t *testing.T) { + var stored core.EditorStoredPreferences + var resolved core.EditorPreferences + w := newWindow(NewController(Options{SetEditorPreferences: func(s core.EditorStoredPreferences, r core.EditorPreferences) { stored, resolved = s, r }}), Values{Language: "en"}) + w.sess.page = pageEditor + d := openWindow(t, w) + d.pump() + d.click(i18n.Shared(i18n.English, "desktop.editorPrefs.lineNumbers")) + d.pump() + if stored.LineNumbers == nil || *stored.LineNumbers || resolved.LineNumbers { + t.Fatal("line number setting did not reach owner") + } + prefs := w.sess.values.EditorPreferences + prefs.Whitespace = true + prefs.CursorStyle = "block" + prefs.CursorBlink = false + prefs.AutoSaveDelayMilliseconds = 1 + w.setEditorPresentation(prefs) + if resolved.CursorStyle != "block" || !resolved.Whitespace || resolved.CursorBlink || resolved.AutoSaveDelayMilliseconds != 250 || w.editorDelay.Text() != "250" { + t.Fatalf("resolved display settings: %+v", resolved) + } + // The persisted source reopens as the same actual preference values. + next := newWindow(NewController(Options{}), Values{Language: "en", EditorStoredPreferences: stored}) + next.sess.page = pageEditor + nd := openWindow(t, next) + nd.pump() + if next.sess.values.EditorPreferences != resolved { + t.Fatalf("reload %+v, want %+v", next.sess.values.EditorPreferences, resolved) + } +} +func TestEditorEssentialsKeymapSchemesStayIndependent(t *testing.T) { + var published core.KeymapSchemeResult + w := newWindow(NewController(Options{SetKeymapSchemes: func(value core.KeymapSchemeResult) { published = value }}), Values{Language: "en"}) + w.sess.page = pageKeymap + d := openWindow(t, w) + d.pump() + if !w.reduceScheme(core.KeymapSchemeRequest{Operation: "saveAs", ID: "mine", Name: "My keys"}) { + t.Fatal(w.scheme.failure) + } + w.setKeymap(shortcuts.Overrides{"editor.find": []string{"meta+shift+f"}}) + if published.State.Active != "mine" || len(published.Bindings["editor.find"]) != 1 { + t.Fatalf("active scheme %+v", published) + } + if !w.reduceScheme(core.KeymapSchemeRequest{Operation: "select", ID: "default"}) || len(w.sess.values.Keymap) != 0 { + t.Fatal("custom keys leaked into default") + } + if !w.reduceScheme(core.KeymapSchemeRequest{Operation: "rename", ID: "mine", Name: "Renamed"}) { + t.Fatal(w.scheme.failure) + } + if !w.reduceScheme(core.KeymapSchemeRequest{Operation: "select", ID: "mine"}) || len(w.sess.values.Keymap["editor.find"]) != 1 { + t.Fatal("custom keys were lost") + } + before := w.sess.values.KeymapSchemes + if w.reduceScheme(core.KeymapSchemeRequest{Operation: "saveAs", ID: "duplicate", Name: "renamed"}) || len(w.sess.values.KeymapSchemes.Schemes) != len(before.Schemes) { + t.Fatal("duplicate changed state") + } + if !w.reduceScheme(core.KeymapSchemeRequest{Operation: "delete", ID: "mine"}) || w.sess.values.KeymapSchemes.Active != "default" { + t.Fatal("delete did not return to default") + } + if w.reduceScheme(core.KeymapSchemeRequest{Operation: "delete", ID: "default"}) { + t.Fatal("default deleted") + } +} diff --git a/desktop/internal/settingswindow/editor_essentials_visual_test.go b/desktop/internal/settingswindow/editor_essentials_visual_test.go new file mode 100644 index 0000000000..a2ce7f92ec --- /dev/null +++ b/desktop/internal/settingswindow/editor_essentials_visual_test.go @@ -0,0 +1,51 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/headless" + "os" + "path/filepath" + "testing" +) + +func TestVisualEditorEssentialsSettings(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct { + theme string + language i18n.Language + }{{"dark", i18n.Chinese}, {"light", i18n.English}} { + for _, scene := range []string{"editor-settings", "keymap-schemes"} { + t.Run(scene+"-"+look.theme, func(t *testing.T) { + w := newWindow(NewController(Options{Text: func() *i18n.Messages { return i18n.For(look.language) }, Language: func() i18n.Language { return look.language }, SystemLanguage: look.language, SystemDark: func() bool { return look.theme == "dark" }}), Values{Language: look.language.Code(), Theme: look.theme}) + if scene == "editor-settings" { + w.sess.page = pageEditor + } else { + w.sess.page = pageKeymap + if !w.reduceScheme(core.KeymapSchemeRequest{Operation: "saveAs", ID: "my-keys", Name: "My workspace"}) { + t.Fatal(w.scheme.failure) + } + } + session, err := headless.Open(w.config(), nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + if err = session.Driver().Pump(); err != nil { + t.Fatal(err) + } + if err = session.Screenshot(filepath.Join(out, scene+"-"+look.theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/settingswindow/editor_preferences_view.go b/desktop/internal/settingswindow/editor_preferences_view.go new file mode 100644 index 0000000000..a4b80afa3b --- /dev/null +++ b/desktop/internal/settingswindow/editor_preferences_view.go @@ -0,0 +1,103 @@ +package settingswindow + +import ( + "context" + "errors" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/ui" + "strconv" + "time" +) + +func (w *window) editorPresentationCard(c ui.C) { + lang := w.marketLanguage() + + values := &w.sess.values + if !w.editorDelayReady { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + resolved, err := core.NewClient().ResolveEditorPreferences(ctx, values.EditorStoredPreferences) + cancel() + if err != nil { + w.editorPrefsError = i18n.Shared(lang, "desktop.editorPrefs.failed") + w.reportEssentialsFailure("editor_preferences", err) + } else { + values.EditorPreferences = resolved + } + w.editorDelay.SetText(strconv.FormatUint(values.EditorPreferences.AutoSaveDelayMilliseconds, 10)) + w.editorDelayReady = true + } + current := values.EditorPreferences + w.card(c, i18n.Shared(lang, "desktop.editorPrefs.title"), "", func() { + if ui.Switch(c.Part("line-numbers"), ¤t.LineNumbers, i18n.Shared(lang, "desktop.editorPrefs.lineNumbers")).Changed() { + w.setEditorPresentation(current) + } + if ui.Switch(c.Part("whitespace"), ¤t.Whitespace, i18n.Shared(lang, "desktop.editorPrefs.whitespace")).Changed() { + w.setEditorPresentation(current) + } + w.settingsRow(c, i18n.Shared(lang, "desktop.editorPrefs.cursorStyle"), "", func() { + if ui.Select(c.Part("caret-style"), ¤t.CursorStyle, []string{"line", "block", "underline"}, func(style string) string { + switch style { + case "block": + return i18n.Shared(lang, "desktop.editorPrefs.block") + case "underline": + return i18n.Shared(lang, "desktop.editorPrefs.underline") + default: + return i18n.Shared(lang, "desktop.editorPrefs.line") + } + }).Width(selectWidth).Label(i18n.Shared(lang, "desktop.editorPrefs.cursorStyle")).Changed() { + w.setEditorPresentation(current) + } + }) + if ui.Switch(c.Part("cursor-blink"), ¤t.CursorBlink, i18n.Shared(lang, "desktop.editorPrefs.cursorBlink")).Changed() { + w.setEditorPresentation(current) + } + w.settingsRow(c, i18n.Shared(lang, "desktop.editorPrefs.saveDelay"), i18n.Shared(lang, "desktop.editorPrefs.saveDelayHelp"), func() { + ui.TextField(c.Part("autosave-delay"), &w.editorDelay, i18n.Shared(lang, "desktop.editorPrefs.saveDelay"), "").Width(105) + if ui.Button(c, w.text.Settings.OK).Outline().Small().Clicked() { + n, err := strconv.ParseUint(w.editorDelay.Text(), 10, 64) + if err != nil { + w.editorPrefsError = i18n.Shared(lang, "desktop.editorPrefs.saveDelayHelp") + w.reportEssentialsFailure("editor_preferences", errors.New("invalid_autosave_delay")) + } else { + current.AutoSaveDelayMilliseconds = n + w.setEditorPresentation(current) + } + } + }) + if w.editorPrefsError != "" { + ui.Wrap(c, w.editorPrefsError).Color(w.pal.danger).FontSize(12) + } + }) +} + +func (w *window) setEditorPresentation(value core.EditorPreferences) { + stored := core.EditorStoredPreferences{LineNumbers: &value.LineNumbers, Whitespace: &value.Whitespace, CursorStyle: value.CursorStyle, CursorBlink: &value.CursorBlink, AutoSaveDelayMilliseconds: &value.AutoSaveDelayMilliseconds} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + resolved, err := core.NewClient().ResolveEditorPreferences(ctx, stored) + if err != nil { + w.editorPrefsError = i18n.Shared(w.marketLanguage(), "desktop.editorPrefs.failed") + w.reportEssentialsFailure("editor_preferences", err) + return + } + stored.AutoSaveDelayMilliseconds = &resolved.AutoSaveDelayMilliseconds + w.sess.values.EditorStoredPreferences, w.sess.values.EditorPreferences = stored, resolved + w.editorDelay.SetText(strconv.FormatUint(resolved.AutoSaveDelayMilliseconds, 10)) + w.editorPrefsError = "" + if set := w.ctrl.opts.SetEditorPreferences; set != nil { + set(stored, resolved) + } +} + +func (w *window) resetEditorPresentation() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + value, err := core.NewClient().ResolveEditorPreferences(ctx, core.EditorStoredPreferences{}) + if err != nil { + w.reportEssentialsFailure("editor_preferences", err) + w.editorPrefsError = i18n.Shared(w.marketLanguage(), "desktop.editorPrefs.failed") + return + } + w.setEditorPresentation(value) +} diff --git a/desktop/internal/settingswindow/keymap_schemes_view.go b/desktop/internal/settingswindow/keymap_schemes_view.go new file mode 100644 index 0000000000..facbbd9f2f --- /dev/null +++ b/desktop/internal/settingswindow/keymap_schemes_view.go @@ -0,0 +1,156 @@ +package settingswindow + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/shortcuts" + "github.com/vivaui/viva/ui" + "time" +) + +type schemeDraft struct { + ready, open bool + operation, id string + name ui.Field + failure string +} + +func (w *window) reportEssentialsFailure(_ string, err error) { reportSettingsError(w.ctrl.opts, err) } + +func (w *window) reduceScheme(request core.KeymapSchemeRequest) bool { + request.State = w.sess.values.KeymapSchemes + request.Current = w.sess.values.Keymap + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + result, err := core.NewClient().ReduceKeymapSchemes(ctx, request) + if err != nil { + message := i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.failed") + var failure *core.Error + if errors.As(err, &failure) { + switch failure.Details { + case "invalid_name": + message = i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.invalidName") + case "duplicate_name": + message = i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.duplicateName") + case "too_many_schemes": + message = i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.limit") + } + } + w.scheme.failure = message + w.reportEssentialsFailure("keymap_schemes", err) + return false + } + w.sess.values.KeymapSchemes = result.State + w.sess.values.Keymap = shortcuts.Overrides(result.Bindings) + w.scheme.failure = "" + w.keymap.recording, w.keymap.message = "", "" + if set := w.ctrl.opts.SetKeymapSchemes; set != nil && request.Operation != "" { + set(result) + } + return true +} + +func (w *window) updateKeymapScheme(bindings shortcuts.Overrides) bool { + // An explicit empty object clears a scheme instead of retaining an old map. + if bindings == nil { + bindings = shortcuts.Overrides{} + } + return w.reduceScheme(core.KeymapSchemeRequest{Operation: "update", Bindings: bindings}) +} + +func (w *window) keymapSchemeCard(c ui.C) { + + s := &w.scheme + if !s.ready { + s.ready = true + w.reduceScheme(core.KeymapSchemeRequest{}) + } + state := w.sess.values.KeymapSchemes + w.card(c, i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.scheme"), "", func() { + ids := make([]string, 0, len(state.Schemes)) + for _, scheme := range state.Schemes { + ids = append(ids, scheme.ID) + } + selected := state.Active + ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { + if ui.Select(c.Part("scheme"), &selected, ids, func(id string) string { + for _, scheme := range state.Schemes { + if scheme.ID == id { + if id == "default" { + return i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.default") + } + return scheme.Name + } + } + return id + }).Width(selectWidth).Label(i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.scheme")).Changed() { + w.reduceScheme(core.KeymapSchemeRequest{Operation: "select", ID: selected}) + } + }) + ui.Row(c.Part("scheme-actions")).FillWidth().Gap(8).Items(ui.Center).Children(func() { + begin := func(operation string) { + s.operation, s.id, s.open = operation, state.Active, true + s.name.SetText("") + s.failure = "" + for _, scheme := range state.Schemes { + if scheme.ID == s.id && operation == "rename" { + s.name.SetText(scheme.Name) + } + } + } + if ui.Button(c, i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.saveAs")).Outline().Small().Clicked() { + begin("saveAs") + } + if ui.Button(c, i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.rename")).Outline().Small().Disabled(state.Active == "default").Clicked() { + begin("rename") + } + if ui.Button(c, i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.delete")).Outline().Small().Disabled(state.Active == "default").Clicked() { + begin("delete") + } + }) + if s.failure != "" && !s.open { + ui.Wrap(c, s.failure).Color(w.pal.danger).FontSize(12) + } + }) + if !s.open { + return + } + title := i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.newTitle") + if s.operation == "rename" { + title = i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.renameTitle") + } + if s.operation == "delete" { + title = i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.delete") + } + ui.ModalWith(c.Part("scheme-name"), &s.open, title, ui.ModalSpec{Width: 410}, func() { + if s.operation != "delete" { + ui.TextField(c, &s.name, i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.name"), "").FillWidth() + } + if s.failure != "" { + ui.Wrap(c, s.failure).FontSize(12).Color(w.pal.danger) + } + }, func() { + if ui.Button(c, w.text.Settings.Cancel).Outline().Clicked() { + s.open = false + } + if ui.Button(c, w.text.Settings.OK).Clicked() { + id := s.id + if s.operation == "saveAs" { + var random [16]byte + if _, err := rand.Read(random[:]); err != nil { + w.reportEssentialsFailure("keymap_schemes", err) + s.failure = i18n.Shared(w.marketLanguage(), "desktop.keymapSchemes.failed") + return + } + id = hex.EncodeToString(random[:]) + } + if w.reduceScheme(core.KeymapSchemeRequest{Operation: s.operation, ID: id, Name: s.name.Text()}) { + s.open = false + } + } + }) +} diff --git a/desktop/internal/settingswindow/keymap_view.go b/desktop/internal/settingswindow/keymap_view.go index 540e48f511..2b5997ea2c 100644 --- a/desktop/internal/settingswindow/keymap_view.go +++ b/desktop/internal/settingswindow/keymap_view.go @@ -38,6 +38,7 @@ func (w *window) keymapPage(c ui.C) { k := &w.keymap keys := w.sess.values.Keymap w.pageScroll(c, pageKeymap, func() { + w.keymapSchemeCard(c) ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { ui.TextField(c.Part("keymap-search"), &k.query, t.Search, t.SearchPlaceholder).Icon(icons.Search).Grow(1).MinWidth(0) if ui.Button(c.Part("keymap-reset-all"), t.ResetAll).Outline().Small().Disabled(len(keys) == 0).Clicked() { @@ -230,6 +231,9 @@ func (w *window) setKeymap(value shortcuts.Overrides) { if len(value) == 0 { value = nil } + if !w.updateKeymapScheme(value) { + return + } w.sess.values.Keymap = value if w.ctrl.opts.SetKeymap != nil { w.ctrl.opts.SetKeymap(value) diff --git a/desktop/internal/settingswindow/local_history_view_test.go b/desktop/internal/settingswindow/local_history_view_test.go index 8ae9075331..70f01b799c 100644 --- a/desktop/internal/settingswindow/local_history_view_test.go +++ b/desktop/internal/settingswindow/local_history_view_test.go @@ -7,6 +7,7 @@ import ( "strings" "sync" "testing" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -17,19 +18,27 @@ import ( // keeps a generated folder out, a line "(" is not a regular expression, and a path starting // with ".." is outside the project. type fakeLocalHistory struct { - mu sync.Mutex - previews []core.HistoryIgnoreRules - paths []string - limits []int - usage core.HistoryUsage - open bool - clears int - clearErr error + mu sync.Mutex + previews []core.HistoryIgnoreRules + paths []string + limits []int + usage core.HistoryUsage + open bool + clears int + clearErr error + previewGate <-chan struct{} } var fakeBuiltIns = []string{"**/node_modules/", "**/target/"} -func (f *fakeLocalHistory) Preview(_ context.Context, rules core.HistoryIgnoreRules, path string) (core.HistoryIgnorePreview, error) { +func (f *fakeLocalHistory) Preview(ctx context.Context, rules core.HistoryIgnoreRules, path string) (core.HistoryIgnorePreview, error) { + if f.previewGate != nil { + select { + case <-f.previewGate: + case <-ctx.Done(): + return core.HistoryIgnorePreview{}, ctx.Err() + } + } f.mu.Lock() defer f.mu.Unlock() f.previews, f.paths = append(f.previews, rules), append(f.paths, path) @@ -137,12 +146,38 @@ func TestLocalHistoryCardChecksTheRulesAsTheyAreTyped(t *testing.T) { // number of megabytes, stores each rule trimmed without blank lines, measures again under the // new limit, and Revert brings the stored rules back. func TestLocalHistoryCardAppliesTrimmedRulesAndTheLimit(t *testing.T) { - source := &fakeLocalHistory{usage: core.HistoryUsage{UsedBytes: 1 << 20, LimitBytes: 100 << 20}, open: true} + previewGate := make(chan struct{}) + var release sync.Once + defer release.Do(func() { close(previewGate) }) + source := &fakeLocalHistory{usage: core.HistoryUsage{UsedBytes: 1 << 20, LimitBytes: 100 << 20}, open: true, previewGate: previewGate} var applied []LocalHistorySettings w, d := openLocalHistoryCard(t, source, LocalHistorySettings{}, func(next LocalHistorySettings) { applied = append(applied, next) }) text := func(id string) string { return i18n.Shared(i18n.English, id) } d.until("the project's history size", func() bool { return d.text("1 MB / 100 MB") }) + // Deliver the initial preview after the usage frame, but before the click. + // Its built-in rules add a row and move Apply. This ordering must not leave + // the click using coordinates from the frame that had only usage data. + release.Do(func() { close(previewGate) }) + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + for { + w.localHistory.async.mu.Lock() + ready := w.localHistory.async.preview != nil + w.localHistory.async.mu.Unlock() + if ready { + break + } + select { + case <-d.driver.Wakes(): + case <-deadline.C: + t.Fatal("initial local history preview did not complete") + } + } + + builtIns := i18n.SharedFormat(i18n.English, "desktop.settings.localHistory.builtIns", map[string]string{"patterns": strings.Join(fakeBuiltIns, " ")}) + d.until("the initial preview row to be rendered before locating Apply", func() bool { return d.showsHelp(builtIns) }) + w.localHistory.patterns.SetText(" *.log \n\n**/gen/\n") w.localHistory.regexes.SetText("\n^build/ ") w.localHistory.limit.SetText("2.5") diff --git a/desktop/internal/settingswindow/window.go b/desktop/internal/settingswindow/window.go index 77750a786e..5f268c4b4e 100644 --- a/desktop/internal/settingswindow/window.go +++ b/desktop/internal/settingswindow/window.go @@ -66,8 +66,12 @@ const ( // window is one open settings window and the model of its Page. Everything in it runs on // its window thread, but for the fields that say so. type window struct { - ctrl *Controller - sess *session + editorDelay ui.Field + editorDelayReady bool + editorPrefsError string + scheme schemeDraft + ctrl *Controller + sess *session // win, stopWatch and gone are guarded by ctrl.mu: Controller.Open fills them in from the // thread that opened the window, and the window's own thread reads and clears them. diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index 7a44425bdb..beaa4e9a7a 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -467,6 +467,7 @@ func (w *window) editorPage(c ui.C) { } }) }) + w.editorPresentationCard(c) w.tabLimitCard(c) semantic := !values.DisableSemanticHighlight w.card(c, settings.EditorSemantic, settings.EditorSemanticHelp, func() { @@ -498,6 +499,7 @@ func (w *window) footer(c ui.C) { w.setTabOverflow("", true) w.setDisableSemanticHighlight(false, true) w.setVimMode(false, true) + w.resetEditorPresentation() w.setProcessTermination(ProcessTermination{}, true) w.resetSteppingFilters() w.setTerminalShell("", true) diff --git a/desktop/internal/shortcuts/shortcuts.go b/desktop/internal/shortcuts/shortcuts.go index d8c719354e..cc80294b92 100644 --- a/desktop/internal/shortcuts/shortcuts.go +++ b/desktop/internal/shortcuts/shortcuts.go @@ -156,6 +156,14 @@ var Catalog = []Action{ {ID: FindAction, Group: GroupSearch, Title: func(m *i18n.Messages) string { return m.Commands.FindAction }, Defaults: chords(chord(keymap.Primary|gfx.ModifierShift, "a"))}, {ID: "search.files", Group: GroupSearch, Title: func(m *i18n.Messages) string { return m.Commands.FindInFiles }, Defaults: chords(chord(keymap.Primary|gfx.ModifierShift, "f"))}, {ID: "search.replace", Group: GroupSearch, Title: func(m *i18n.Messages) string { return m.Commands.ReplaceInFiles }}, + {ID: "editor.newScratch", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.NewScratch }, Defaults: chords(chord(keymap.Primary, "n"))}, + {ID: "editor.scratchFiles", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.ScratchFiles }}, + {ID: "editor.recentFiles", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.RecentFiles }, Defaults: chords(chord(keymap.Primary, "e"))}, + {ID: "editor.recentEdits", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.RecentEdits }, Defaults: chords(chord(keymap.Primary|gfx.ModifierShift, "e"))}, + {ID: "editor.saveAs", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.SaveAs }, Defaults: chords(chord(keymap.Primary|gfx.ModifierShift, "s"))}, + {ID: "editor.find", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.Find }, Defaults: chords(chord(keymap.Primary, "f"))}, + {ID: "editor.replace", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.Replace }, Defaults: chords(chord(keymap.Primary, "r"))}, + {ID: "editor.fold", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.Fold }, Defaults: chords(chord(keymap.Primary, "-"))}, {ID: "editor.unfold", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.Unfold }, Defaults: chords(chord(keymap.Primary, "="))}, {ID: "editor.foldAll", Group: GroupEditor, Title: func(m *i18n.Messages) string { return m.Commands.FoldAll }, Defaults: chords(chord(keymap.Primary|gfx.ModifierShift, "-"))}, diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index f93098df64..dce7d29b2e 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -240,6 +240,8 @@ const logsShortcut = "⇧⌘L" // settings are the user's choices, kept in settingsFile. type settings struct { + EditorPreferences core.EditorStoredPreferences `json:"editorPreferences,omitzero"` + KeymapSchemes core.KeymapSchemes `json:"keymapSchemes,omitzero"` // Language is a stored i18n code; empty follows the system. Language string `json:"language,omitempty"` Theme themeChoice `json:"theme,omitempty"` @@ -408,6 +410,11 @@ type project struct { // App is the state of the window. type App struct { + chooseScratchPath func(string, string) (string, error) + recovery *recoveryWriter + recentFiles recentFileState + drafts draftListState + editorPreferences core.EditorPreferences // debugAttach are the host and port fields of the Debug panel's attach form. debugAttach debugAttachFields // root is the window's page; dnd are its drag and drop gestures and focus the control @@ -664,6 +671,8 @@ func New(options Options) *App { a.settings = settings{} } a.settings.Keymap = shortcuts.Normalize(a.settings.Keymap) + a.loadEditorEssentials() + a.initRecovery() a.applyNetwork() bundledInterfaceFamily() a.applyFonts() @@ -1077,6 +1086,7 @@ func (a *App) openProjectHere(path string) { a.loadLog(p) a.activatePluginWorkspace(root) a.restoreEditorSession(p) + a.restoreCheckpoints(p) a.restoreNativePanels(p) a.openPendingFiles(p) }) @@ -1123,6 +1133,15 @@ func (a *App) finishCloseProject(p *project, after func()) { a.saveNativePanels(p) a.releaseIndexing(p) a.closeEverywhere(p) + a.recentFiles.open = false + a.recentFiles.generation++ + a.recentFiles.lastEdited = 0 + a.recentFiles.list = nil + a.recentFiles.listState = ui.ListState{} + a.drafts.open, a.drafts.loading = false, false + a.drafts.generation++ + a.drafts.entries = nil + a.drafts.list = ui.ListState{} if a.navigation.open && a.navigation.project == p { a.closeNavigation() } diff --git a/desktop/internal/workbench/commands.go b/desktop/internal/workbench/commands.go index 73da47977d..b87e6df5d0 100644 --- a/desktop/internal/workbench/commands.go +++ b/desktop/internal/workbench/commands.go @@ -62,12 +62,20 @@ func (a *App) commands() []command { if p == nil { return sortCommands(list) } + add("editor.newScratch", t.GroupEditor, a.text.Commands.NewScratch, "", true, func() { a.newScratch(p) }) + add("editor.scratchFiles", t.GroupEditor, a.text.Commands.ScratchFiles, "", true, a.openScratchList) + add("editor.recentFiles", t.GroupEditor, a.text.Commands.RecentFiles, "", true, func() { a.openRecentFiles(false) }) + add("editor.recentEdits", t.GroupEditor, a.text.Commands.RecentEdits, "", true, func() { a.openRecentFiles(true) }) add("project.close", t.GroupProject, t.CloseProject, "", true, a.closeProject) add("documents.saveAll", t.GroupProject, t.SaveAll, "", true, func() { a.saveProjectDocuments(p, func(bool) {}) }) // The File menu closes the selected tab above its separator and Settings above it, as the // old Windows menu bar ordered them. if d := p.selectedDocument(p.docs.group); d != nil { id := d.id + if d.scratch { + add("editor.saveAs", t.GroupEditor, a.text.Commands.SaveAs, "", !d.saving, func() { a.saveScratchAs(p, d) }) + add("editor.discardScratch", t.GroupEditor, i18n.Shared(a.language(), "desktop.drafts.discard"), "", !d.saving, func() { a.discardScratch(p, d) }) + } add("tab.close", t.GroupProject, a.text.Editor.CloseTab, "", true, func() { a.closeDocument(p, id) }) } // The Terminal menu runs the editor's selection as one command through the long-command @@ -89,6 +97,8 @@ func (a *App) commands() []command { } // Code folding of the selected document. if d := p.selectedDocument(p.docs.group); d != nil { + add("editor.find", t.GroupEditor, i18n.Shared(a.language(), "desktop.editorFind.find"), "", true, func() { a.openEditorFind(false) }) + add("editor.replace", t.GroupEditor, i18n.Shared(a.language(), "desktop.editorFind.replace"), "", !d.virtual, func() { a.openEditorFind(true) }) add("editor.fold", t.GroupEditor, t.Fold, "", true, func() { a.foldCommand(d, func(v *editorview.View) { v.FoldAtCaret() }) }) add("editor.unfold", t.GroupEditor, t.Unfold, "", true, func() { a.foldCommand(d, func(v *editorview.View) { v.UnfoldAtCaret() }) }) add("editor.foldAll", t.GroupEditor, t.FoldAll, "", true, func() { a.foldCommand(d, (*editorview.View).FoldAll) }) diff --git a/desktop/internal/workbench/document_autosave.go b/desktop/internal/workbench/document_autosave.go index 34c4612a26..d2e7a123ce 100644 --- a/desktop/internal/workbench/document_autosave.go +++ b/desktop/internal/workbench/document_autosave.go @@ -15,21 +15,19 @@ import ( // every changed file at once (onFocusLost). Saving before a run and before closing goes on // as before. -// autoSaveDelay is how long after the last edit a changed file is saved. -const autoSaveDelay = 1500 * time.Millisecond - -// scheduleAutoSave saves d once no edit came for autoSaveDelay. +// scheduleAutoSave keeps one owned timer for the actual delay resolved by Core. func (a *App) scheduleAutoSave(p *project, d *document) { - if a.settings.DisableAutoSave || d.virtual { + if a.settings.DisableAutoSave || d.virtual || d.scratch { return } - d.autoSave++ + d.cancelAutoSave() generation := d.autoSave - time.AfterFunc(autoSaveDelay, func() { + d.autoSaveTimer = time.AfterFunc(time.Duration(a.editorPreferences.AutoSaveDelayMilliseconds)*time.Millisecond, func() { a.post(func(a *App) { if a.project != p || d.autoSave != generation || p.docs.find(d.id) != d || a.settings.DisableAutoSave { return } + d.autoSaveTimer = nil if d.view.IsComposing() { // An input method is still composing: try again once it may be done. a.scheduleAutoSave(p, d) @@ -49,10 +47,10 @@ func (a *App) onFocusLost() gfx.EventResult { return gfx.EventResult{} } for _, d := range p.docs.list { - if d.virtual || !d.dirty() || d.view.IsComposing() { + if d.scratch || d.virtual || !d.dirty() || d.view.IsComposing() { continue } - d.autoSave++ + d.cancelAutoSave() a.saveDocumentMode(p, d.id, true) } return gfx.EventResult{Repaint: true} @@ -78,8 +76,8 @@ func (a *App) noteEditorFocus(focused gfx.ID) { if left == 0 || left == current || a.settings.DisableAutoSave { return } - if d := p.docs.find(left); d != nil && !d.virtual && d.dirty() && !d.view.IsComposing() { - d.autoSave++ + if d := p.docs.find(left); d != nil && !d.virtual && !d.scratch && d.dirty() && !d.view.IsComposing() { + d.cancelAutoSave() a.post(func(a *App) { if a.project == p && p.docs.find(d.id) == d { a.saveDocumentMode(p, d.id, true) @@ -129,3 +127,11 @@ func (a *App) hardLinkSaveRequired(p *project, d *document, identity string, aut }, }) } + +func (d *document) cancelAutoSave() { + d.autoSave++ + if d.autoSaveTimer != nil { + d.autoSaveTimer.Stop() + d.autoSaveTimer = nil + } +} diff --git a/desktop/internal/workbench/document_observation.go b/desktop/internal/workbench/document_observation.go index a57f4d08c4..8fbbcb9481 100644 --- a/desktop/internal/workbench/document_observation.go +++ b/desktop/internal/workbench/document_observation.go @@ -241,6 +241,7 @@ func (a *App) scheduleDocumentChecks(p *project) { func (a *App) clearDocumentConflict(d *document) { d.conflicted = false + d.recoveredConflict = false d.conflictMissing = false d.conflictContent = editorview.Content{} d.conflictBytes = nil @@ -262,7 +263,11 @@ func (a *App) applyDocumentCheck(p *project, d *document, baseline rope.Rope, co return } if err == nil && !changed { - a.clearDocumentConflict(d) + // A recovered conflict was decided against the pre-crash hash. This watcher + // compares with the newly observed disk baseline and cannot acknowledge it. + if !d.recoveredConflict { + a.clearDocumentConflict(d) + } return } revision := uint64(d.view.Revision()) diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 069dddec10..f2ebbc7e38 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -49,6 +49,11 @@ var ( // document is a file open in a tab of the editor area. type document struct { + find editorFind + scratch bool + recoveredConflict bool + recoveryTimer *time.Timer + autoSaveTimer *time.Timer // folds is the document's code folding requests (folding.go). folds documentFolds // serverLinks are the links the language server reported for the text, and pluginLinks the @@ -260,6 +265,10 @@ func (a *App) openFile(p *project, path string) { kernel, _ := a.kernel.(editorKernel) a.background(p, 0, func(ctx context.Context) func(*App) { read, err := readDocumentEncoded(ctx, kernel, path) + restored := a.prepareRecoveredDocument(ctx, p, path, read.text, err) + if restored.found && restored.missing { + err = nil + } data := read.text var content editorview.Content var grammar *syntax.Syntax @@ -267,7 +276,11 @@ func (a *App) openFile(p *project, path string) { if err == nil { // The rope and the measure of the lines take time in proportion to the file, so // they are made here and the window thread only shows them. - content = editorview.Prepare(data) + if restored.found { + content = restored.disk + } else { + content = editorview.Prepare(data) + } grammar = registry.SyntaxForPath(path) if language, ok := registry.ForPath(path); ok { languageID = language.ID @@ -294,6 +307,7 @@ func (a *App) openFile(p *project, path string) { a.placeDocument(p, path, name, content, grammar, languageID) if d := p.docs.byPath(path); d != nil { d.encoding, d.hasBOM, d.diskBytes = read.encoding, read.hasBOM, read.disk + a.applyRecoveredDocument(p, d, restored) } // A plugin that serves this language starts its server the first time a // file of it is opened, not when the project opens: a workspace of Go @@ -509,6 +523,9 @@ func (a *App) placeDocumentAs(p *project, path, name string, content editorview. a.scheduleEditorActions(p, d) } a.enforceTabLimit(p, d) + if !virtual { + a.noteRecentFile(p, d, "opened") + } } // documentGroup is the editor group a file opens in: the one a document was last shown in, @@ -548,6 +565,9 @@ func (a *App) selectDocument(p *project, id int) { p.docs.group = g.ID a.focusDocument(id) p.touchDocument(id) + if d := p.docs.find(id); d != nil { + a.noteRecentFile(p, d, "opened") + } } // focusDocument asks for the keyboard to go to document id as soon as it is painted. @@ -564,6 +584,18 @@ func (a *App) saveDocumentMode(p *project, id int, auto bool) { if d == nil || d.virtual { return } + if d.recoveredConflict { + if !auto { + a.saveFailed(d.id, d.view.Revision(), d.name, documentio.ErrConflict) + } + return + } + if d.scratch { + if !auto { + a.saveScratchAs(p, d) + } + return + } if auto && (d.conflicted || d.recreateMissing || d.linkedAutoSaveOff) { return } @@ -635,6 +667,7 @@ func (a *App) saveDocumentMode(p *project, id int, auto bool) { return } d.view.MarkSaved(text) + a.flushCheckpoint(p, d, false) a.reloadDiffsOfPath(p, path) a.recordLocalHistory(p, path, "save", historyTexts{before: before, after: data}) d.encodingChanged, d.previousEncoding = false, nil @@ -679,11 +712,24 @@ func (a *App) saveDocumentMode(p *project, id int, auto bool) { // saveBeforeClose waits asynchronously for any in-flight save and the latest edits. func (a *App) saveBeforeClose(p *project, d *document, done func(bool)) { + if d.recoveredConflict { + done(false) + return + } if d.view.IsComposing() { a.saveFailed(d.id, d.view.Revision(), d.name, errComposing) done(false) return } + if d.scratch { + if d.saving { + d.closeWaiters = append(d.closeWaiters, done) + return + } + a.flushCheckpoint(p, d, false) + done(true) + return + } if !d.saving && !d.dirty() { a.checkBeforeClose(p, d, done) return @@ -765,6 +811,9 @@ func (a *App) closeDocument(p *project, id int) { // removeDocument takes a tab away without asking about its text. The caller has saved it or // decided that it is going away: deleting its file, for one. func (a *App) removeDocument(p *project, d *document) { + d.find.dispose() + d.cancelAutoSave() + a.flushCheckpoint(p, d, false) member := documentMember(d.id) g := p.terms.bench.GroupOf(member) if g == nil { @@ -809,7 +858,7 @@ func (a *App) saveProjectPass(p *project, verified map[int]int, done func(bool)) } documents := make([]core.SaveBatchDocument, 0, len(p.docs.list)) for _, d := range p.docs.list { - documents = append(documents, core.SaveBatchDocument{ID: documentMember(d.id), Dirty: d.dirty() || d.conflicted, ContentSynchronized: !d.view.IsComposing()}) + documents = append(documents, core.SaveBatchDocument{ID: documentMember(d.id), Dirty: !d.scratch && (d.dirty() || d.conflicted), ContentSynchronized: !d.view.IsComposing()}) } ctx, cancel := context.WithTimeout(p.ctx, kernelCallTimeout) plan, err := a.kernel.PlanDocumentSaveBatch(ctx, documents) @@ -865,6 +914,9 @@ func (a *App) closeDocuments(p *project) { watch.close() } for _, d := range p.docs.list { + a.flushCheckpoint(p, d, false) + d.find.dispose() + d.cancelAutoSave() d.view.Close() } p.docs = documentSet{} diff --git a/desktop/internal/workbench/documents_test.go b/desktop/internal/workbench/documents_test.go index cb2010d656..1c189ddbb4 100644 --- a/desktop/internal/workbench/documents_test.go +++ b/desktop/internal/workbench/documents_test.go @@ -333,6 +333,9 @@ func TestCloseDocumentSerializesInFlightSave(t *testing.T) { func TestWindowCloseWaitsForSuccessfulSave(t *testing.T) { h := newHarness(t, &testKernel{Client: core.NewClient()}) + // This test drives close-triggered saves explicitly. A real-time auto-save + // must not start an independent write while the test replaces the writer. + h.app.settings.DisableAutoSave = true root := t.TempDir() path := filepath.Join(root, "note.txt") if err := os.WriteFile(path, []byte("initial"), 0o600); err != nil { @@ -346,16 +349,20 @@ func TestWindowCloseWaitsForSuccessfulSave(t *testing.T) { if _, err := input.OnEvent(app.TextEvent{Kind: app.TextInsert, Text: "change"}); err != nil { t.Fatal(err) } + want := d.view.TextSnapshot().String() var allowed bool h.app.documentWriter = func(string, []byte, []byte) error { return os.ErrPermission } h.app.Config().OnCloseRequest(func() { allowed = true }) - h.settle() + h.await("the first close to finish its failed save", func() bool { return !h.app.closingProject && !d.saving }) if allowed || h.app.project == nil || !d.view.Dirty() { t.Fatal("window close lost unsaved changes after a failed write") } h.app.documentWriter = documentio.WriteGuarded h.app.Config().OnCloseRequest(func() { allowed = true }) - awaitDocumentState(t, h, func() bool { return allowed && h.app.project == nil }) + h.await("the successful save to finish closing the window", func() bool { return allowed && h.app.project == nil }) + if data, err := os.ReadFile(path); err != nil || string(data) != want { + t.Fatalf("closed window with disk = %q, want %q, error = %v", data, want, err) + } } // An external edit after opening must not be overwritten by a later editor save. diff --git a/desktop/internal/workbench/editor_essentials_test.go b/desktop/internal/workbench/editor_essentials_test.go new file mode 100644 index 0000000000..ee7f68e3ba --- /dev/null +++ b/desktop/internal/workbench/editor_essentials_test.go @@ -0,0 +1,310 @@ +package workbench + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/draftstore" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/vivaui/viva/keymap" +) + +func essentialsDocument(t *testing.T, text string) (*harness, *project, *document) { + t.Helper() + h := newHarnessWithLanguages(t, &testKernel{Client: core.NewClient()}, []string{"en-US"}) + h.app.settings.DisableAutoSave = true + root := t.TempDir() + path := filepath.Join(root, "notes.txt") + if err := os.WriteFile(path, []byte(text), 0600); err != nil { + t.Fatal(err) + } + h.open(root) + p := h.app.project + h.app.openFile(p, path) + h.settleChain() + d := p.docs.byPath(path) + if d == nil { + t.Fatal("document did not open") + } + return h, p, d +} +func TestEditorEssentialsFindReplaceNativeFlow(t *testing.T) { + h, p, d := essentialsDocument(t, "alpha 😀 alpha\nALPHA beta") + d.view.SetSelection(0, 0) + d.find.debounce = -1 + if _, err := h.driver.ShortcutChord(keymap.Primary, 'f'); err != nil { + t.Fatal(err) + } + if !d.find.open { + t.Fatal("find shortcut did not open the bar") + } + d.find.query.SetText("alpha") + h.app.refreshEditorFind(p, d) + h.await("Unicode matches", func() bool { return !d.find.pending && len(d.find.matches) == 3 }) + h.app.stepEditorFind(d, 1) + start, end := d.view.Selection() + if start != 11 || end != 16 { + t.Fatalf("next match %d..%d", start, end) + } + h.app.openEditorFind(true) + d.find.replacement.SetText("omega") + h.settleChain() + h.clickNamed(h.shared("desktop.editorFind.replaceAll")) + h.await("atomic replacement", func() bool { return d.view.TextSnapshot().String() == "omega 😀 omega\nomega beta" }) + d.view.Undo() + if got := d.view.TextSnapshot().String(); got != "alpha 😀 alpha\nALPHA beta" { + t.Fatalf("bulk undo: %q", got) + } + d.find.regex = true + d.find.query.SetText("[") + h.app.refreshEditorFind(p, d) + h.await("invalid pattern", func() bool { return !d.find.pending && d.find.failure == "invalid_pattern" }) + if got := d.view.TextSnapshot().String(); got != "alpha 😀 alpha\nALPHA beta" { + t.Fatal("invalid regex changed text") + } + h.app.closeEditorFind(d) + if d.find.open || d.find.timer != nil || d.find.cancel != nil { + t.Fatal("find retained resources") + } +} +func TestEditorEssentialsFindRejectsLateReplacement(t *testing.T) { + h, p, d := essentialsDocument(t, "one one") + d.find.open = true + before := d.view.TextSnapshot() + baseline := d.view.SavedSnapshot() + prepared, err := editorview.PrepareEdits(before, baseline, []editorview.TextEdit{{Range: editorview.Range{Start: 0, End: 3}, Text: "two"}}) + if err != nil { + t.Fatal(err) + } + d.find.generation = 5 + h.app.insertForTest(d, "!") + h.app.applyEditorFind(p, d, before, 5, true, core.EditorFindResult{Edits: []core.EditorReplacement{{EditorByteRange: core.EditorByteRange{Start: 0, End: 3}, Text: "two"}}}, prepared, nil) + if got := d.view.TextSnapshot().String(); got != "one one!" { + t.Fatalf("stale replacement overwrote edits: %q", got) + } +} +func TestEditorEssentialsRecoveryRestartsAndProtectsChangedDisk(t *testing.T) { + h, p, d := essentialsDocument(t, "disk baseline") + h.app.insertForTest(d, " + unsaved 😀") + h.app.flushCheckpoint(p, d, false) + h.settleChain() + storage := draftstore.New(h.store.Dir(), core.EditorRecoveryDecision{MaxDocumentBytes: 64 << 20, MaxStorageBytes: 256 << 20, MaxDocuments: 64}) + entry, found, err := storage.Load(p.root, d.path) + if err != nil || !found || entry.Text != "disk baseline + unsaved 😀" { + t.Fatalf("durable checkpoint: %+v %v %v", entry, found, err) + } + // A fresh view and a fresh storage owner simulate loss of the process, not normal close. + if err = os.WriteFile(d.path, []byte("external change"), 0600); err != nil { + t.Fatal(err) + } + restored := h.app.prepareRecoveredDocument(context.Background(), p, d.path, []byte("external change"), nil) + h.app.removeDocument(p, d) + h.settleChain() // remove may enqueue; the durable restored snapshot is already captured. + h.app.placeDocument(p, d.path, d.name, restored.disk, nil, "") + reopened := p.docs.byPath(d.path) + h.app.applyRecoveredDocument(p, reopened, restored) + if !reopened.conflicted || reopened.view.TextSnapshot().String() != entry.Text { + t.Fatal("changed disk was not presented as a recovered conflict") + } + h.app.saveDocumentMode(p, reopened.id, true) + h.settleChain() + disk, err := os.ReadFile(d.path) + if err != nil || string(disk) != "external change" { + t.Fatalf("recovery overwrote external data: %q %v", disk, err) + } + // Resolve explicitly so the harness can finish a normal close. + h.app.keepDocumentEditor(p, reopened) + h.app.saveDocument(p, reopened.id) + h.settleChain() + _, found, err = storage.Load(p.root, d.path) + if err != nil || found { + t.Fatalf("saved checkpoint remains: %v %v", found, err) + } +} +func TestEditorEssentialsScratchKeepsAndDiscardsAcrossOwners(t *testing.T) { + h, p, _ := essentialsDocument(t, "base") + h.app.newScratch(p) + d := p.selectedDocument(p.docs.group) + if d == nil || !d.scratch { + t.Fatal("scratch missing") + } + h.app.insertForTest(d, "draft before a destination 😀") + path := d.path + h.app.closeDocument(p, d.id) + h.settleChain() + if p.docs.byPath(path) != nil { + t.Fatal("close did not keep draft independently of tab") + } + h.app.openScratchList() + h.settleChain() + if len(h.app.drafts.entries) != 1 { + t.Fatalf("scratch list %+v", h.app.drafts.entries) + } + h.app.drafts.open = false + h.app.openScratch(p, path) + h.settleChain() + d = p.docs.byPath(path) + if d == nil || d.view.TextSnapshot().String() != "draft before a destination 😀" { + t.Fatal("reopened scratch lost content") + } + destination := filepath.Join(t.TempDir(), "saved.txt") + h.app.chooseScratchPath = func(string, string) (string, error) { return destination, nil } + h.app.saveScratchAs(p, d) + h.settleChain() + if p.docs.byPath(path) != nil || p.docs.byPath(destination) == nil { + t.Fatal("Save As did not replace scratch with destination") + } + h.app.newScratch(p) + d = p.selectedDocument(p.docs.group) + h.app.insertForTest(d, "discard me") + disk, err := os.ReadFile(destination) + if err != nil || string(disk) != "draft before a destination 😀" { + t.Fatalf("Save As: %q %v", disk, err) + } + h.app.discardScratch(p, d) + h.settleChain() + entries, err := h.app.recovery.store.List("", true) + if err != nil || len(entries) != 0 { + t.Fatalf("discard retained draft: %+v %v", entries, err) + } +} +func TestEditorEssentialsRecentFilesKeepEditOrderAndCaret(t *testing.T) { + h, p, d := essentialsDocument(t, "first\nsecond") + h.app.insertForTest(d, "!") + path := filepath.Join(p.root, "other.txt") + if err := os.WriteFile(path, []byte("other"), 0600); err != nil { + t.Fatal(err) + } + h.app.openFile(p, path) + h.settleChain() + h.app.openRecentFiles(false) + h.settleChain() + if len(h.app.recentFiles.list) != 2 || h.app.recentFiles.list[0].Name != "other.txt" { + t.Fatalf("open MRU %+v", h.app.recentFiles.list) + } + h.app.openRecentFiles(true) + h.settleChain() + if len(h.app.recentFiles.list) != 1 || h.app.recentFiles.list[0].Name != "notes.txt" { + t.Fatalf("edit MRU %+v", h.app.recentFiles.list) + } + h.app.recentFiles.query.SetText("missing") + h.app.queryRecentFiles(p) + h.settleChain() + if len(h.app.recentFiles.list) != 0 { + t.Fatal("filter retained unmatched files") + } + h.app.recentFiles.open = false +} + +func TestEditorEssentialsAutomaticRecoveryRequiresExplicitDecision(t *testing.T) { + h := newHarnessWithLanguages(t, &testKernel{Client: core.NewClient()}, []string{"en-US"}) + h.app.settings.DisableAutoSave = true + root := t.TempDir() + path := filepath.Join(root, "recovered.txt") + if err := os.WriteFile(path, []byte("external"), 0600); err != nil { + t.Fatal(err) + } + if err := h.app.recovery.store.Save(draftstore.Entry{Root: root, Path: path, Name: "recovered.txt", BaseHash: draftstore.Hash([]byte("before crash")), Text: "unsaved 😀"}); err != nil { + t.Fatal(err) + } + h.open(root) + h.settleChain() + p := h.app.project + d := p.docs.byPath(path) + if d == nil || !d.dirty() || !d.conflicted || !d.recoveredConflict { + t.Fatal("startup did not restore a pending conflict") + } + h.await("initial native disk observation", func() bool { return !d.checkPending && !d.checking }) + if !d.conflicted { + t.Fatal("watcher acknowledged recovery without user choice") + } + h.app.saveDocument(p, d.id) + h.settleChain() + disk, err := os.ReadFile(path) + if err != nil || string(disk) != "external" { + t.Fatalf("manual save bypassed conflict: %q %v", disk, err) + } + h.app.keepDocumentEditor(p, d) + h.app.saveDocument(p, d.id) + h.settleChain() + disk, err = os.ReadFile(path) + if err != nil || string(disk) != "unsaved 😀" || d.conflicted { + t.Fatalf("explicit keep/save: %q %v", disk, err) + } +} + +func TestEditorEssentialsSelectionScopeFollowsBulkReplacement(t *testing.T) { + h, p, d := essentialsDocument(t, "one one one") + d.view.SetSelection(0, 7) + d.find.debounce = -1 + h.app.openEditorFind(true) + d.find.selection = true + d.find.query.SetText("one") + d.find.replacement.SetText("a") + h.app.refreshEditorFind(p, d) + h.await("scoped matches", func() bool { return !d.find.pending && len(d.find.matches) == 2 }) + h.app.invalidator.Invalidate() + h.settleChain() + h.clickNamed(h.shared("desktop.editorFind.replaceAll")) + h.await("scoped replacement", func() bool { return d.view.TextSnapshot().String() == "a a one" && !d.find.pending }) + if d.find.scope == nil || d.find.scope.Start != 0 || d.find.scope.End != 3 || d.find.failure != "" { + t.Fatalf("scope after replacement: %+v failure=%s", d.find.scope, d.find.failure) + } +} + +func TestEditorEssentialsClosingProjectDropsDialogsAndStartsNewEditVisit(t *testing.T) { + h, p, d := essentialsDocument(t, "first") + h.app.insertForTest(d, "!") + h.app.openRecentFiles(false) + h.app.openScratchList() + h.settleChain() + h.app.closeProject() + h.await("project closed", func() bool { return h.app.project == nil }) + if h.app.recentFiles.open || h.app.drafts.open || h.app.recentFiles.lastEdited != 0 { + t.Fatal("closed project retained its dialogs or editing visit") + } + root := t.TempDir() + path := filepath.Join(root, "second.txt") + if err := os.WriteFile(path, []byte("second"), 0600); err != nil { + t.Fatal(err) + } + h.open(root) + p = h.app.project + h.app.openFile(p, path) + h.settleChain() + d = p.docs.byPath(path) + h.app.insertForTest(d, "!") + h.app.saveDocument(p, d.id) + h.settleChain() + h.app.openRecentFiles(true) + h.settleChain() + if len(h.app.recentFiles.list) != 1 || h.app.recentFiles.list[0].Name != "second.txt" { + t.Fatalf("new project edit visit: %+v", h.app.recentFiles.list) + } + h.app.recentFiles.open = false +} + +func TestEditorEssentialsDiscardFromListWaitsForStorageAndClosesOpenScratch(t *testing.T) { + h, p, _ := essentialsDocument(t, "base") + h.app.newScratch(p) + d := p.selectedDocument(p.docs.group) + path := d.path + h.app.insertForTest(d, "private draft") + h.app.flushCheckpoint(p, d, false) + h.settleChain() + h.app.openScratchList() + h.settleChain() + h.clickNamed(h.shared("desktop.drafts.discard")) + h.await("discard committed and list refreshed", func() bool { return !h.app.drafts.loading && len(h.app.drafts.entries) == 0 }) + if p.docs.byPath(path) != nil { + t.Fatal("discard left the editable scratch open") + } + entries, err := h.app.recovery.store.List("", true) + if err != nil || len(entries) != 0 { + t.Fatalf("discard checkpoint remains: %+v %v", entries, err) + } + h.app.drafts.open = false +} diff --git a/desktop/internal/workbench/editor_essentials_visual_test.go b/desktop/internal/workbench/editor_essentials_visual_test.go new file mode 100644 index 0000000000..646fa6b5e2 --- /dev/null +++ b/desktop/internal/workbench/editor_essentials_visual_test.go @@ -0,0 +1,121 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/draftstore" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" + "os" + "path/filepath" + "testing" +) + +func TestVisualEditorEssentials(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct{ theme, language string }{{"dark", "zh-Hans"}, {"light", "en"}} { + for _, scene := range []string{"find-replace", "recovery-conflict", "recent-edits", "scratch-editor", "scratch-list"} { + t.Run(scene+"-"+look.theme, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + root := filepath.Join(t.TempDir(), "EssentialsDemo") + if err := os.MkdirAll(root, 0700); err != nil { + t.Fatal(err) + } + source := "// Editor essentials demo\n\nfunc greet(name string) string {\n message := \"Hello, \" + name\n return message\n}\n\nfunc preview() {\n greet(\"Lithe\")\n greet(\"世界 😀\")\n}\n" + path := filepath.Join(root, "greeting.txt") + if err := os.WriteFile(path, []byte(source), 0600); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1440, 900 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + if scene == "recovery-conflict" { + if err := h.app.recovery.store.Save(draftstore.Entry{Root: root, Path: path, Name: "greeting.txt", BaseHash: draftstore.Hash([]byte("older baseline")), Text: source + "\n// Recovered unsaved note: finish this change.\n"}); err != nil { + t.Fatal(err) + } + } + h.open(root) + p := h.app.project + h.app.openFile(p, path) + h.settleChain() + d := p.docs.byPath(path) + if d == nil { + t.Fatal("editor missing") + } + switch scene { + case "find-replace": + d.find.debounce = -1 + d.view.SetSelection(0, 0) + h.app.openEditorFind(true) + d.find.query.SetText("greet") + d.find.replacement.SetText("welcome") + h.app.refreshEditorFind(p, d) + h.await("search matches", func() bool { return !d.find.pending && len(d.find.matches) == 3 }) + case "recovery-conflict": + if !d.conflicted || !d.dirty() { + t.Fatal("recovery must preserve a dirty conflict") + } + case "recent-edits": + h.app.insertForTest(d, "\n// Work in progress\n") + other := filepath.Join(root, "tasks.txt") + if err := os.WriteFile(other, []byte("Review editor settings\nKeep recovery copy\n"), 0600); err != nil { + t.Fatal(err) + } + h.app.openFile(p, other) + h.settleChain() + h.app.insertForTest(p.docs.byPath(other), "Ready for review\n") + h.app.openRecentFiles(true) + h.settleChain() + if len(h.app.recentFiles.list) != 2 { + t.Fatal("edit history missing") + } + case "scratch-editor", "scratch-list": + h.app.newScratch(p) + scratch := p.selectedDocument(p.docs.group) + h.app.insertForTest(scratch, "# Working notes\n\nWrite before choosing a destination.\n\n- Search and replace\n- Durable recovery\n- Independent keymap schemes\n\n中文与 emoji 😀 are preserved.\n") + h.app.flushCheckpoint(p, scratch, false) + h.settleChain() + if scene == "scratch-list" { + h.app.closeDocument(p, scratch.id) + h.settleChain() + h.app.openScratchList() + h.settleChain() + if len(h.app.drafts.entries) != 1 { + t.Fatal("persisted scratch missing") + } + } + } + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, scene+"-"+look.theme+".png")); err != nil { + t.Fatal(err) + } + // A capture may intentionally show a recovery conflict; release it before normal cleanup. + if d.conflicted { + h.app.keepDocumentEditor(p, d) + h.app.saveDocument(p, d.id) + h.settleChain() + } + h.app.recentFiles.open, h.app.drafts.open = false, false + }) + } + } +} diff --git a/desktop/internal/workbench/editor_find.go b/desktop/internal/workbench/editor_find.go new file mode 100644 index 0000000000..aa889611aa --- /dev/null +++ b/desktop/internal/workbench/editor_find.go @@ -0,0 +1,354 @@ +package workbench + +import ( + "context" + "errors" + "strconv" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +type editorFindKey struct { + query string + version int + matchCase, word, regex, selection bool +} + +// editorFind holds only one document's bar and the result for an exact text revision. +// Matching and replacement planning belong to Core; text preparation runs on a worker. +type editorFind struct { + open, replace, focus, pending bool + query, replacement ui.Field + matchCase, word, regex, selection bool + scope *core.EditorByteRange + key editorFindKey + computed bool + matches []core.EditorByteRange + current int + truncated bool + failure string + generation uint64 + cancel context.CancelFunc + timer *time.Timer + // A negative debounce lets tests drive completion without elapsed-time synchronization. + debounce time.Duration +} + +type editorFindKernel interface { + FindEditorText(context.Context, []byte, core.EditorFindRequest) (core.EditorFindResult, error) +} + +func (a *App) openEditorFind(replace bool) { + p := a.project + if p == nil { + return + } + d := p.selectedDocument(p.docs.group) + if d == nil || d.view.IsComposing() { + return + } + f := &d.find + if !f.open { + start, end := d.view.Selection() + if end > start { + f.scope = &core.EditorByteRange{Start: start, End: end} + if end-start <= 4096 { + f.query.SetText(d.view.SelectedText()) + } + } + } + f.open, f.replace, f.focus = true, replace, true + f.computed = false + a.performed("editor.find.open", surfaceShortcut) + a.invalidator.Invalidate() +} + +func (a *App) closeEditorFind(d *document) { + f := &d.find + f.generation++ + if f.cancel != nil { + f.cancel() + f.cancel = nil + } + if f.timer != nil { + f.timer.Stop() + f.timer = nil + } + f.open, f.pending, f.computed = false, false, false + f.matches = nil + d.view.ClearSearchMatches() + a.focusDocument(d.id) +} + +func (a *App) refreshEditorFind(p *project, d *document) { + f := &d.find + key := editorFindKey{f.query.Text(), d.view.Revision(), f.matchCase, f.word, f.regex, f.selection} + if f.computed && key == f.key { + return + } + f.key, f.computed = key, true + f.generation++ + if f.cancel != nil { + f.cancel() + f.cancel = nil + } + if f.timer != nil { + f.timer.Stop() + f.timer = nil + } + f.matches = nil + d.view.ClearSearchMatches() + if key.query == "" { + f.pending, f.failure = false, "" + return + } + f.pending = true + gen := f.generation + start := func() { a.runEditorFind(p, d, nil, nil) } + if f.debounce < 0 { + start() + return + } + delay := f.debounce + if delay == 0 { + delay = 80 * time.Millisecond + } + f.timer = time.AfterFunc(delay, func() { + a.post(func(a *App) { + if a.project == p && p.docs.find(d.id) == d && f.open && f.generation == gen { + f.timer = nil + start() + } + }) + }) +} + +// runEditorFind snapshots the native rope in O(1). No source flattening, matching, +// replacement expansion or whole-document layout happens on the window thread. +func (a *App) runEditorFind(p *project, d *document, replacement *string, replaceStart *int) { + kernel, ok := a.kernel.(editorFindKernel) + if !ok { + return + } + f := &d.find + if f.cancel != nil { + f.cancel() + } + ctx, cancel := context.WithTimeout(p.ctx, kernelCallTimeout) + f.cancel = cancel + f.generation++ + gen := f.generation + f.pending = true + before := d.view.TextSnapshot() + baseline := d.view.SavedSnapshot() + _, caret := d.view.SelectionOffsets() + input := core.EditorFindRequest{Query: f.query.Text(), CaseSensitive: f.matchCase, WholeWord: f.word, Regex: f.regex, Caret: caret, Replacement: replacement, ReplaceStart: replaceStart} + if f.selection { + input.Range = f.scope + } + a.background(p, kernelCallTimeout, func(context.Context) func(*App) { + defer cancel() + result, err := kernel.FindEditorText(ctx, before.Bytes(), input) + var prepared editorview.PreparedEdit + if err == nil && replacement != nil && len(result.Edits) > 0 { + edits := make([]editorview.TextEdit, len(result.Edits)) + for i, e := range result.Edits { + edits[i] = editorview.TextEdit{Range: editorview.Range{Start: e.Start, End: e.End}, Text: e.Text} + } + prepared, err = editorview.PrepareEdits(before, baseline, edits) + } + return func(a *App) { a.applyEditorFind(p, d, before, gen, replacement != nil, result, prepared, err) } + }) +} + +func (a *App) applyEditorFind(p *project, d *document, before rope.Rope, gen uint64, replacing bool, result core.EditorFindResult, prepared editorview.PreparedEdit, err error) { + f := &d.find + if a.project != p || p.docs.find(d.id) != d || !f.open || f.generation != gen { + return + } + f.pending = false + if !d.view.TextSnapshot().Same(before) { + f.computed = false + if replacing { + a.notifyInfo(i18n.Shared(a.language(), "desktop.editorFind.stale")) + } + return + } + if err != nil { + if errors.Is(err, context.Canceled) { + return + } // log-exempt: 用户取消:关闭或更新查询取消旧匹配。 + code := "failed" + var failure *core.Error + if errors.As(err, &failure) { + code = failure.Details + } + if code != f.failure { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_find", err)) + } + f.failure = code + return + } + f.failure = "" + if replacing { + if len(result.Edits) > 0 { + if !d.view.ApplyPreparedEdit(prepared) { + f.computed = false + a.notifyInfo(i18n.Shared(a.language(), "desktop.editorFind.stale")) + return + } + } + if result.Range != nil { + f.scope = result.Range + } + f.computed = false + a.notifyInfo(i18n.SharedFormat(a.language(), "desktop.editorFind.replaced", map[string]string{"count": strconv.Itoa(len(result.Edits))})) + return + } + f.matches, f.truncated = result.Matches, result.Truncated + f.current = 0 + if result.Selected != nil { + f.current = *result.Selected + } + ranges := make([]editorview.Range, len(result.Matches)) + for i, r := range result.Matches { + ranges[i] = editorview.Range{Start: r.Start, End: r.End} + } + d.view.SetSearchMatches(ranges) + a.stepEditorFind(d, 0) +} + +func (a *App) stepEditorFind(d *document, by int) { + f := &d.find + if len(f.matches) == 0 || f.pending { + return + } + f.current = (f.current + by + len(f.matches)) % len(f.matches) + match := f.matches[f.current] + d.view.SetSelection(match.Start, match.End) +} + +func editorFindFailure(language i18n.Language, failure string) string { + switch failure { + case "invalid_pattern": + return i18n.Shared(language, "desktop.editorFind.invalidPattern") + case "source_too_large", "source_too_large_or_invalid": + return i18n.Shared(language, "desktop.editorFind.tooLarge") + case "too_many_matches": + return i18n.Shared(language, "desktop.editorFind.tooMany") + case "replacement_too_large": + return i18n.Shared(language, "desktop.editorFind.replacementTooLarge") + default: + return i18n.Shared(language, "desktop.editorFind.failed") + } +} + +func (a *App) editorFindBar(c ui.C, p *project, d *document) { + f := &d.find + if !f.open { + return + } + a.refreshEditorFind(p, d) + + ui.Column(c.KeyInt(d.id).Part("find")).FillWidth().Shrink(0).PadX(8).PadY(5).Gap(4).Background(a.colors.Panel).Children(func() { + ui.Row(c).FillWidth().Items(ui.Center).Gap(5).Children(func() { + queryID := ui.ID(c.KeyInt(d.id).Part("find-query")) + if f.focus { + c.Canvas().RequestFocus(queryID) + f.focus = false + } + ui.TextFieldID(c, queryID, &f.query, i18n.Shared(a.language(), "desktop.editorFind.find"), i18n.Shared(a.language(), "desktop.editorFind.find")).Icon(icons.Search).Grow(1).MinWidth(70).OnKey(func(event gfx.KeyEvent) gfx.EventResult { + if event.Release { + return gfx.EventResult{} + } + if event.Key == gfx.KeyEscape { + a.closeEditorFind(d) + return gfx.EventResult{Handled: true, Repaint: true} + } + if event.Key == gfx.KeyEnter { + by := 1 + if event.Modifiers&gfx.ModifierShift != 0 { + by = -1 + } + a.stepEditorFind(d, by) + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} + }) + current := 0 + if len(f.matches) > 0 { + current = f.current + 1 + } + ui.Text(c, i18n.SharedFormat(a.language(), "desktop.editorFind.count", map[string]string{"current": strconv.Itoa(current), "total": strconv.Itoa(len(f.matches))})).FontSize(12).Color(a.colors.Subtle) + if a.gitIconButton(c, i18n.Shared(a.language(), "desktop.editorFind.previous"), icons.ArrowUp, false, f.pending || len(f.matches) == 0) { + c.After(func() { a.stepEditorFind(d, -1) }) + } + if a.gitIconButton(c, i18n.Shared(a.language(), "desktop.editorFind.next"), icons.ArrowDown, false, f.pending || len(f.matches) == 0) { + c.After(func() { a.stepEditorFind(d, 1) }) + } + if a.gitIconButton(c, i18n.Shared(a.language(), "desktop.editorFind.close"), icons.X, false, false) { + c.After(func() { a.closeEditorFind(d) }) + } + }) + ui.Row(c.Part("find-options")).FillWidth().Items(ui.Center).Gap(18).Children(func() { + for _, option := range []struct { + key string + label string + value *bool + disabled bool + }{{"case", i18n.Shared(a.language(), "desktop.editorFind.case"), &f.matchCase, false}, {"word", i18n.Shared(a.language(), "desktop.editorFind.word"), &f.word, false}, {"regex", i18n.Shared(a.language(), "desktop.editorFind.regex"), &f.regex, false}, {"selection", i18n.Shared(a.language(), "desktop.editorFind.selection"), &f.selection, f.scope == nil}} { + ui.Checkbox(c.Part(option.key), option.value, option.label).Disabled(option.disabled) + } + }) + if f.replace { + ui.Row(c).FillWidth().Items(ui.Center).Gap(6).Children(func() { + ui.TextField(c.Part("replacement"), &f.replacement, i18n.Shared(a.language(), "desktop.editorFind.replace"), i18n.Shared(a.language(), "desktop.editorFind.replace")).Grow(1).MinWidth(70) + disabled := d.view.ReadOnly() || d.view.IsComposing() || f.pending || len(f.matches) == 0 || f.failure != "" + if ui.Button(c, i18n.Shared(a.language(), "desktop.editorFind.replaceOne")).Outline().Small().Disabled(disabled).Clicked() { + c.After(func() { + r := f.replacement.Text() + at := f.matches[f.current].Start + a.performed("editor.find.replace", surfaceButton) + a.runEditorFind(p, d, &r, &at) + }) + } + if ui.Button(c, i18n.Shared(a.language(), "desktop.editorFind.replaceAll")).Outline().Small().Disabled(disabled || f.truncated).Clicked() { + c.After(func() { + r := f.replacement.Text() + a.performed("editor.find.replaceAll", surfaceButton) + a.runEditorFind(p, d, &r, nil) + }) + } + }) + } + if f.failure != "" { + ui.Wrap(c, editorFindFailure(a.language(), f.failure)).FontSize(12).Color(a.colors.Deleted) + } else if f.pending { + ui.Text(c, i18n.Shared(a.language(), "desktop.editorFind.loading")).FontSize(12).Color(a.colors.Subtle) + } else if f.truncated { + ui.Wrap(c, i18n.Shared(a.language(), "desktop.editorFind.tooMany")).FontSize(12).Color(a.colors.Subtle) + } + }) + ui.Divider(c) +} + +func (f *editorFind) dispose() { + f.generation++ + if f.cancel != nil { + f.cancel() + f.cancel = nil + } + if f.timer != nil { + f.timer.Stop() + f.timer = nil + } + f.open = false + f.matches = nil +} diff --git a/desktop/internal/workbench/editor_menu.go b/desktop/internal/workbench/editor_menu.go index 67eba76357..39c3d15a59 100644 --- a/desktop/internal/workbench/editor_menu.go +++ b/desktop/internal/workbench/editor_menu.go @@ -18,6 +18,13 @@ func (a *App) editorMenuItems(c ui.C, p *project, d *document) func(*ui.MenuItem menu.WidthRange(240, 280) a.editorActionMenuItems(c, p, d, menu) readOnly := d.view.ReadOnly() + if menu.Item(a.text.Commands.Find).Clicked() { + c.After(func() { a.selectDocument(p, d.id); a.openEditorFind(false) }) + } + if menu.Item(a.text.Commands.Replace).Disabled(readOnly).Clicked() { + c.After(func() { a.selectDocument(p, d.id); a.openEditorFind(true) }) + } + menu.Separator() if menu.Item(i18n.Shared(language, "desktop.editorMenu.goToDefinition")).Keys(primary, "b").Clicked() { c.After(func() { line, column := d.view.CaretUTF16() diff --git a/desktop/internal/workbench/editor_preferences.go b/desktop/internal/workbench/editor_preferences.go new file mode 100644 index 0000000000..a84cba91d2 --- /dev/null +++ b/desktop/internal/workbench/editor_preferences.go @@ -0,0 +1,27 @@ +package workbench + +import ( + "context" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/shortcuts" +) + +// Only the resolved preferences reach drawing; defaults and scheme migration live in Core. +func (a *App) loadEditorEssentials() { + ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + defer cancel() + client := core.NewClient() + prefs, err := client.ResolveEditorPreferences(ctx, a.settings.EditorPreferences) + if err != nil { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_preferences", err)) + } else { + a.editorPreferences = prefs + } + schemes, err := client.ReduceKeymapSchemes(ctx, core.KeymapSchemeRequest{State: a.settings.KeymapSchemes, Current: a.settings.Keymap}) + if err != nil { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("keymap_schemes", err)) + } else { + a.settings.KeymapSchemes = schemes.State + a.settings.Keymap = shortcuts.Overrides(schemes.Bindings) + } +} diff --git a/desktop/internal/workbench/editor_recovery.go b/desktop/internal/workbench/editor_recovery.go new file mode 100644 index 0000000000..78a6523013 --- /dev/null +++ b/desktop/internal/workbench/editor_recovery.go @@ -0,0 +1,232 @@ +package workbench + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/draftstore" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "io" + "os" + "sync" + "time" +) + +type checkpoint struct { + entry draftstore.Entry + text, base rope.Rope + remove bool + caret int + after func(*App) +} + +// A single native worker drains coalesced immutable snapshots. Its queue and storage share +// Core's document limit. The UI lock never spans filesystem work or source flattening. +type recoveryWriter struct { + mu sync.Mutex + pending map[string]checkpoint + running bool + store *draftstore.Store + limit int +} + +func (a *App) initRecovery() { + ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + defer cancel() + limits, err := core.NewClient().DecideEditorRecovery(ctx, core.EditorRecoveryRequest{}) + if err != nil { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_recovery", err)) + return + } + a.recovery = &recoveryWriter{pending: map[string]checkpoint{}, store: draftstore.New(a.store.Dir(), limits), limit: limits.MaxDocuments} +} +func (a *App) checkpointDocument(p *project, d *document) { + if d.virtual || a.recovery == nil { + return + } + if d.recoveryTimer != nil { + d.recoveryTimer.Stop() + } + // The timer retains only the document identity. Snapshot capture stays on the UI thread. + d.recoveryTimer = time.AfterFunc(200*time.Millisecond, func() { + a.post(func(a *App) { + if a.project == p && p.docs.find(d.id) == d { + d.recoveryTimer = nil + a.flushCheckpoint(p, d, false) + } + }) + }) +} +func (a *App) flushCheckpoint(p *project, d *document, remove bool) { + if d.virtual || a.recovery == nil { + return + } + if d.recoveryTimer != nil { + d.recoveryTimer.Stop() + d.recoveryTimer = nil + } + _, caret := d.view.SelectionOffsets() + root := p.root + if d.scratch { + root = "" + } + job := checkpoint{caret: caret, entry: draftstore.Entry{Root: root, Path: d.path, Name: d.name, Scratch: d.scratch}, text: d.view.TextSnapshot(), base: d.view.SavedSnapshot(), remove: remove || (!d.scratch && !d.dirty())} + a.enqueueCheckpoint(job) +} +func (a *App) enqueueCheckpoint(job checkpoint) { + writer := a.recovery + if writer == nil { + return + } + key := job.entry.Root + "\x00" + job.entry.Path + writer.mu.Lock() + if _, exists := writer.pending[key]; !exists && len(writer.pending) >= writer.limit { + writer.mu.Unlock() + a.recoveryFailed(context.DeadlineExceeded) + if job.after != nil { + job.after(a) + } + return + } + writer.pending[key] = job + if writer.running { + writer.mu.Unlock() + return + } + writer.running = true + writer.mu.Unlock() + a.background(nil, 0, func(context.Context) func(*App) { + for { + writer.mu.Lock() + var next checkpoint + var key string + for k, v := range writer.pending { + key, next = k, v + break + } + if key == "" { + writer.running = false + writer.mu.Unlock() + return nil + } + delete(writer.pending, key) + writer.mu.Unlock() + var err error + if next.remove { + err = writer.store.Remove(next.entry.Root, next.entry.Path) + } else { + next.entry.Line, next.entry.Column = editorview.SnapshotUTF16(next.text, next.caret) + digest := sha256.New() + next.base.Chunks(0, next.base.Len(), func(chunk string) bool { _, err = io.WriteString(digest, chunk); return err == nil }) + next.entry.BaseHash = hex.EncodeToString(digest.Sum(nil)) + if err == nil { + err = writer.store.SaveSource(next.entry, int64(next.text.Len()), func(w io.Writer) error { + var failure error + next.text.Chunks(0, next.text.Len(), func(chunk string) bool { _, failure = io.WriteString(w, chunk); return failure == nil }) + return failure + }) + } + } + if err != nil { + a.post(func(a *App) { a.recoveryFailed(err) }) + } + if next.after != nil { + a.post(next.after) + } + } + }) +} +func (a *App) recoveryFailed(err error) { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_recovery", documentLogError(err))) + a.notifyError(i18n.Shared(a.language(), "desktop.drafts.failed")) +} + +type recoveredDocument struct { + found, missing, conflict bool + prepared editorview.PreparedEdit + disk editorview.Content + line, column int + err error +} + +func (a *App) prepareRecoveredDocument(ctx context.Context, p *project, path string, data []byte, readErr error) recoveredDocument { + var result recoveredDocument + if a.recovery == nil { + return result + } + entry, found, err := a.recovery.store.Load(p.root, path) + if err != nil { + result.err = err + return result + } + if !found { + return result + } + if readErr != nil && !errors.Is(readErr, os.ErrNotExist) { + return result + } + hash := draftstore.Hash(data) + var diskHash *string + if readErr == nil { + diskHash = &hash + } + decision, err := core.NewClient().DecideEditorRecovery(ctx, core.EditorRecoveryRequest{BaseHash: entry.BaseHash, DiskHash: diskHash, Bytes: uint64(len(entry.Text))}) + if err != nil { + result.err = err + return result + } + result.disk = editorview.Prepare(data) + result.prepared, err = editorview.PrepareEdits(result.disk.Snapshot(), result.disk.Snapshot(), []editorview.TextEdit{{Range: editorview.Range{Start: 0, End: len(data)}, Text: entry.Text}}) + result.err = err + result.found = err == nil + result.missing = readErr != nil + result.conflict = decision.Action == "restoreConflict" + result.line, result.column = entry.Line, entry.Column + return result +} +func (a *App) applyRecoveredDocument(p *project, d *document, restored recoveredDocument) { + if restored.err != nil { + a.recoveryFailed(restored.err) + return + } + if !restored.found { + return + } + // Reuse the exact native baseline captured by the prepared edit, not an equivalent rope. + if restored.conflict { + d.conflicted, d.conflictMissing = true, restored.missing + d.recoveredConflict = true + d.conflictBytes = d.diskBytes + d.conflictContent = restored.disk + } + d.view.ApplyPreparedEdit(restored.prepared) + d.view.GoToNavigation(restored.line, restored.column, false) + message := i18n.Shared(a.language(), "desktop.drafts.recovered") + if restored.conflict { + message = i18n.Shared(a.language(), "desktop.drafts.conflict") + } + a.performed("editor.recovery.restored", surfaceMenu) + a.notifyInfo(message) +} +func (a *App) restoreCheckpoints(p *project) { + if a.recovery == nil { + return + } + storage := a.recovery.store + a.background(p, kernelCallTimeout, func(context.Context) func(*App) { + entries, err := storage.List(p.root, false) + return func(a *App) { + if err != nil { + a.recoveryFailed(err) + return + } + for _, entry := range entries { + a.openFile(p, entry.Path) + } + } + }) +} diff --git a/desktop/internal/workbench/editor_view.go b/desktop/internal/workbench/editor_view.go index e3e2001f3c..8fa9613d04 100644 --- a/desktop/internal/workbench/editor_view.go +++ b/desktop/internal/workbench/editor_view.go @@ -89,6 +89,9 @@ func (a *App) editorGroup(c ui.C, id string) ui.Box { if doc != nil && doc.conflicted { a.documentConflict(c, doc) } + if doc != nil { + a.editorFindBar(c, p, doc) + } ui.Column(c).Fill().Draw(place.bodyHook).Children(func() { a.groupBody(c, id, doc) }) @@ -182,6 +185,8 @@ func (a *App) documentInput(p *project, d *document) { } d.draw = func(dc *ui.DrawContext) { v := d.view + prefs := a.editorPreferences + v.SetPresentation(editorview.Presentation{HideLineNumbers: !prefs.LineNumbers, ShowWhitespace: prefs.Whitespace, CursorStyle: prefs.CursorStyle, DisableCursorBlink: !prefs.CursorBlink}) v.Bind(d.hit, d.input.Parts()) // The minimap's button was declared by the last paint; its click turns the minimap of // every view off or on, so the views painted after it in this paint follow too. diff --git a/desktop/internal/workbench/pluginsync.go b/desktop/internal/workbench/pluginsync.go index 35d628d79c..1396598f3b 100644 --- a/desktop/internal/workbench/pluginsync.go +++ b/desktop/internal/workbench/pluginsync.go @@ -78,6 +78,11 @@ func (a *App) documentSyncServer(d *document) (*pluginServer, string) { func (a *App) documentEdited(p *project, d *document, edit editorview.Edit) { a.relocateDocumentBreakpoints(p, d, edit) a.scheduleEditorActions(p, d) + a.checkpointDocument(p, d) + a.markRecentlyEdited(p, d) + if d.scratch { + return + } a.scheduleAutoSave(p, d) if a.plugins == nil || a.project != p || p.docs.byPath(d.path) != d { return diff --git a/desktop/internal/workbench/recent_files.go b/desktop/internal/workbench/recent_files.go new file mode 100644 index 0000000000..3d7d02b833 --- /dev/null +++ b/desktop/internal/workbench/recent_files.go @@ -0,0 +1,195 @@ +package workbench + +import ( + "context" + "errors" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/draftstore" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/ui" + "path/filepath" + "sync" +) + +var recentFilesIO sync.Mutex + +type recentRequest struct { + project *project + event *core.EditorRecentEvent + text rope.Rope + caret int + query string + edited bool + generation uint64 + search bool +} +type recentFileState struct { + mu sync.Mutex + pending []recentRequest + running bool + open, edited bool + query ui.Field + list []core.EditorRecentEntry + listState ui.ListState + computed string + generation uint64 + lastEdited int +} + +func recentFilesName(root string) string { return "editor-recent-" + draftstore.Key(root) + ".json" } +func (a *App) noteRecentFile(p *project, d *document, kind string) { + if d.virtual || d.scratch { + return + } + relative, err := filepath.Rel(p.root, d.path) + if err != nil { + a.recentFailed(err) + return + } + _, caret := d.view.SelectionOffsets() + event := core.EditorRecentEvent{Kind: kind, Path: filepath.ToSlash(relative), Name: d.name} + a.enqueueRecent(recentRequest{project: p, event: &event, text: d.view.TextSnapshot(), caret: caret}) +} +func (a *App) markRecentlyEdited(p *project, d *document) { + if a.recentFiles.lastEdited != d.id { + a.recentFiles.lastEdited = d.id + a.noteRecentFile(p, d, "edited") + } +} +func (a *App) recentFailed(err error) { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_recent", documentLogError(err))) + a.notifyError(i18n.Shared(a.language(), "desktop.recentFiles.failed")) +} +func (a *App) openRecentFiles(edited bool) { + p := a.project + if p == nil { + return + } + v := &a.recentFiles + v.open, v.edited = true, edited + v.query.SetText("") + v.computed = "\x00" + v.lastEdited = 0 + if d := p.selectedDocument(p.docs.group); d != nil && d.dirty() { + a.noteRecentFile(p, d, "edited") + } + a.queryRecentFiles(p) +} +func (a *App) queryRecentFiles(p *project) { + v := &a.recentFiles + v.computed = v.query.Text() + v.generation++ + a.enqueueRecent(recentRequest{project: p, query: v.query.Text(), edited: v.edited, generation: v.generation, search: true}) +} +func (a *App) enqueueRecent(request recentRequest) { + v := &a.recentFiles + v.mu.Lock() + // Core bounds persisted history; this separate native work queue bounds pending I/O. + if len(v.pending) >= 128 { + v.mu.Unlock() + a.recentFailed(context.DeadlineExceeded) + return + } + v.pending = append(v.pending, request) + if v.running { + v.mu.Unlock() + return + } + v.running = true + v.mu.Unlock() + a.background(nil, 0, func(context.Context) func(*App) { + for { + v.mu.Lock() + if len(v.pending) == 0 { + v.running = false + v.mu.Unlock() + return nil + } + job := v.pending[0] + v.pending = v.pending[1:] + v.mu.Unlock() + p := job.project + if job.event != nil { + job.event.Line, job.event.Column = editorview.SnapshotUTF16(job.text, job.caret) + } + recentFilesIO.Lock() + var entries []core.EditorRecentEntry + _, err := a.store.Load(recentFilesName(p.root), &entries) + ctx, cancel := context.WithTimeout(p.ctx, kernelCallTimeout) + var result core.EditorRecentResult + if err == nil { + result, err = core.NewClient().ReduceEditorRecent(ctx, core.EditorRecentRequest{Entries: entries, Event: job.event, Query: job.query, OnlyEdited: job.edited}) + } + cancel() + if err == nil { + entries = result.Entries + if job.event != nil { + err = a.store.Save(recentFilesName(p.root), entries) + } + } + recentFilesIO.Unlock() + a.post(func(a *App) { + if err != nil { + // log-exempt: 生命周期清理:关闭项目取消所属的历史读取,结果不再投递。 + if !errors.Is(err, context.Canceled) { + a.recentFailed(err) + } + return + } + if job.search && a.project == p && v.open && v.generation == job.generation { + v.list = result.Results + } + }) + } + }) +} +func (a *App) recentFilesPopup(c ui.C) { + v, p := &a.recentFiles, a.project + if !v.open || p == nil { + return + } + if v.computed != v.query.Text() { + a.queryRecentFiles(p) + } + title := i18n.Shared(a.language(), "desktop.recentFiles.title") + if v.edited { + title = i18n.Shared(a.language(), "desktop.recentFiles.edited") + } + ui.ModalWith(c.Part("recent-files"), &v.open, title, ui.ModalSpec{Width: 660}, func() { + submitted := ui.TextField(c.Part("query"), &v.query, i18n.Shared(a.language(), "desktop.recentFiles.query"), "").Icon(icons.Search).FillWidth().Submitted() + open := func(entry core.EditorRecentEntry) { + v.open = false + a.openFileAtPosition(p, filepath.Join(p.root, filepath.FromSlash(entry.Path)), entry.Line, entry.Column) + } + if submitted && len(v.list) > 0 && v.computed == v.query.Text() { + entry := v.list[0] + c.After(func() { open(entry) }) + } + if len(v.list) == 0 { + ui.Text(c, i18n.Shared(a.language(), "desktop.recentFiles.empty")).Color(a.colors.Subtle) + } + ui.List(c.Part("entries"), &v.listState, len(v.list), func(item ui.ListRow) { + row, index := item.C, item.Index + entry := v.list[index] + box := item.Element.FillWidth().Height(42).PadX(8).Radius(4).Hover(ui.Look{}.Background(a.colors.Hover)) + if item.Selected() { + box = box.Background(a.colors.Selection) + } + if box.Children(func() { + ui.Column(row).FillWidth().Children(func() { + ui.Text(row, entry.Name).FontSize(13).Color(a.colors.Text) + ui.Text(row, entry.Path).FontSize(11).Color(a.colors.Subtle).Ellipsis() + }) + }).Clicked() { + c.After(func() { open(entry) }) + } + }).Height(336) + if index, ok := v.listState.Submitted(); ok && index >= 0 && index < len(v.list) { + entry := v.list[index] + c.After(func() { open(entry) }) + } + }, nil) +} diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index f4c18dd9fd..54e9c851fa 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -275,6 +275,8 @@ func (a *App) runShortcut(id string, view *editorview.View) { // earlier client's plugin secrets, the Git dialogs and the New Project dialog. Each dialog's // state stays with its own file; the toasts are declared last, over all of them. func (a *App) overlays(c ui.C) { + a.scratchPopup(c) + a.recentFilesPopup(c) a.cloneView(c) if a.project != nil { a.everywherePopup(c) diff --git a/desktop/internal/workbench/scratch_files.go b/desktop/internal/workbench/scratch_files.go new file mode 100644 index 0000000000..b5e47e5ee7 --- /dev/null +++ b/desktop/internal/workbench/scratch_files.go @@ -0,0 +1,197 @@ +package workbench + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "os" + "strconv" + + "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" + "github.com/1lck/Lithe-IDEA/desktop/internal/draftstore" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +type draftListState struct { + list ui.ListState + open, loading bool + entries []draftstore.Entry + generation uint64 +} + +func (a *App) newScratch(p *project) { + if p == nil { + return + } + var random [16]byte + if _, err := rand.Read(random[:]); err != nil { + a.recoveryFailed(err) + return + } + path := "scratch:" + hex.EncodeToString(random[:]) + name := i18n.SharedFormat(a.language(), "desktop.drafts.untitled", map[string]string{"number": strconv.Itoa(p.docs.next + 1)}) + a.placeScratch(p, draftstore.Entry{Path: path, Name: name, Scratch: true}, editorview.Prepare(nil)) +} +func (a *App) placeScratch(p *project, entry draftstore.Entry, content editorview.Content) { + if d := p.docs.byPath(entry.Path); d != nil { + a.selectDocument(p, d.id) + return + } + a.placeDocumentAs(p, entry.Path, entry.Name, content, nil, "", true) + if d := p.docs.byPath(entry.Path); d != nil { + d.scratch, d.virtual = true, false + d.view.SetReadOnly(false) + d.view.GoToNavigation(entry.Line, entry.Column, false) + a.flushCheckpoint(p, d, false) + } +} +func (a *App) openScratchList() { + if a.project == nil || a.recovery == nil { + return + } + v := &a.drafts + v.open, v.loading = true, true + v.generation++ + gen := v.generation + storage := a.recovery.store + a.background(a.project, kernelCallTimeout, func(context.Context) func(*App) { + entries, err := storage.List("", true) + return func(a *App) { + if !v.open || v.generation != gen { + return + } + v.loading = false + if err != nil { + a.recoveryFailed(err) + return + } + v.entries = entries + } + }) +} +func (a *App) openScratch(p *project, path string) { + storage := a.recovery.store + a.background(p, kernelCallTimeout, func(context.Context) func(*App) { + entry, found, err := storage.Load("", path) + var content editorview.Content + if found && err == nil { + content = editorview.Prepare([]byte(entry.Text)) + } + return func(a *App) { + if err != nil { + a.recoveryFailed(err) + return + } + if found { + a.placeScratch(p, entry, content) + } + } + }) +} +func (a *App) discardScratch(p *project, d *document) { + if !d.scratch { + return + } + a.flushCheckpoint(p, d, true) + // Removing the tab normally keeps a scratch. The empty checkpoint is queued last. + a.removeDocument(p, d) + a.flushCheckpoint(p, d, true) +} +func (a *App) saveScratchAs(p *project, d *document) { + if d.saving || d.view.IsComposing() { + return + } + d.saving = true + before := d.view.TextSnapshot() + name := d.name + title := i18n.Shared(a.language(), "desktop.drafts.saveAs") + a.background(p, 0, func(ctx context.Context) func(*App) { + choose := a.chooseScratchPath + if choose == nil { + choose = func(title, name string) (string, error) { + return app.SaveFile(app.SaveFileOptions{Title: title, SuggestedName: name}) + } + } + path, err := choose(title, name) + if err == nil { + err = ctx.Err() + } + if err == nil && path != "" { + err = writeScratchFile(path, before.Bytes()) + } + return func(a *App) { + d.saving = false + waiters := d.closeWaiters + d.closeWaiters = nil + defer func() { + for _, done := range waiters { + done(err == nil && path != "") + } + }() + if err != nil { + a.saveFailed(d.id, d.view.Revision(), d.name, err) + return + } + if path == "" { + return + } + if d.view.TextSnapshot().Same(before) { + a.removeDocument(p, d) + a.flushCheckpoint(p, d, true) + } + a.openFile(p, path) + a.notifyInfo(i18n.Shared(a.language(), "desktop.drafts.saved")) + } + }) +} +func writeScratchFile(path string, data []byte) error { + expected, err := documentio.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return documentio.WriteMissing(path, data) + } + if err != nil { + return err + } + return documentio.WriteGuarded(path, data, expected) +} +func (a *App) scratchPopup(c ui.C) { + v, p := &a.drafts, a.project + if !v.open || p == nil { + return + } + ui.ModalWith(c.Part("scratch-files"), &v.open, i18n.Shared(a.language(), "desktop.drafts.list"), ui.ModalSpec{Width: 620}, func() { + if !v.loading && len(v.entries) == 0 { + ui.Text(c, i18n.Shared(a.language(), "desktop.drafts.empty")).Color(a.colors.Subtle) + } + ui.List(c.Part("entries"), &v.list, len(v.entries), func(item ui.ListRow) { + row, index := item.C, item.Index + entry := v.entries[index] + ui.Row(row).FillWidth().Items(ui.Center).Gap(8).Children(func() { + if ui.Button(row, entry.Name).Ghost().Grow(1).Disabled(v.loading).Clicked() { + c.After(func() { v.open = false; a.openScratch(p, entry.Path) }) + } + if ui.Button(row, i18n.Shared(a.language(), "desktop.drafts.discard")).Outline().Small().Disabled(v.loading).Clicked() { + c.After(func() { + v.loading = true + if d := p.docs.byPath(entry.Path); d != nil && d.scratch { + a.removeDocument(p, d) + } + a.enqueueCheckpoint(checkpoint{entry: entry, remove: true, after: func(a *App) { + if a.project == p && v.open { + a.openScratchList() + } + }}) + }) + } + }) + }).Height(300) + }, func() { + if ui.Button(c, i18n.Shared(a.language(), "desktop.drafts.new")).Clicked() { + c.After(func() { v.open = false; a.newScratch(p) }) + } + }) +} diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index c3c50173b0..0f976a08ef 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -270,6 +270,22 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { }) }, LocalHistory: a.localHistorySettingsSource(), + SetEditorPreferences: func(stored core.EditorStoredPreferences, resolved core.EditorPreferences) { + a.post(func(a *App) { + a.settings.EditorPreferences = stored + a.editorPreferences = resolved + a.saveSettings() + a.invalidator.Invalidate() + }) + }, + SetKeymapSchemes: func(value core.KeymapSchemeResult) { + a.post(func(a *App) { + a.settings.KeymapSchemes = value.State + a.settings.Keymap = shortcuts.Overrides(value.Bindings) + a.saveSettings() + a.invalidator.Invalidate() + }) + }, SetKeymap: func(value shortcuts.Overrides) { value = shortcuts.Normalize(value) a.post(func(a *App) { @@ -391,9 +407,10 @@ func (a *App) openSettingsPageWith(surface string, page settingsPage, query stri SteppingFilters: maps.Clone(a.settings.DebugSteppingFilters), Fonts: fontprefs.Normalize(a.settings.Fonts), Keymap: maps.Clone(a.settings.Keymap), - Network: a.settings.Network, - LocalHistory: a.settings.LocalHistory, - AutoCheckUpdates: a.autoCheckUpdates(), + EditorPreferences: a.editorPreferences, EditorStoredPreferences: a.settings.EditorPreferences, KeymapSchemes: a.settings.KeymapSchemes, + Network: a.settings.Network, + LocalHistory: a.settings.LocalHistory, + AutoCheckUpdates: a.autoCheckUpdates(), } var err error switch page { diff --git a/docs/assets/ide-essentials/README.md b/docs/assets/ide-essentials/README.md new file mode 100644 index 0000000000..f9d4aea934 --- /dev/null +++ b/docs/assets/ide-essentials/README.md @@ -0,0 +1,19 @@ +# 编辑器基础能力测试截图 + +来自生产 Viva Page 的无头渲染,使用隔离的临时项目、配置和公开演示内容。 +深色使用中文、浅色使用英文。截图不代表 macOS/Windows 原生窗口验收。 + +| 能力 | 深色中文 | 浅色英文 | +| --- | --- | --- | +| 文件内查找替换 | [截图](find-replace-dark.png) | [截图](find-replace-light.png) | +| 恢复后的磁盘冲突 | [截图](recovery-conflict-dark.png) | [截图](recovery-conflict-light.png) | +| 最近编辑 | [截图](recent-edits-dark.png) | [截图](recent-edits-light.png) | +| Scratch 编辑 | [截图](scratch-editor-dark.png) | [截图](scratch-editor-light.png) | +| 持久草稿列表 | [截图](scratch-list-dark.png) | [截图](scratch-list-light.png) | +| 编辑器设置 | [截图](editor-settings-dark.png) | [截图](editor-settings-light.png) | +| 命名快捷键方案 | [截图](keymap-schemes-dark.png) | [截图](keymap-schemes-light.png) | + +复验:设置 `LITHE_VISUAL_OUTPUT_DIR`,通过 `scripts/desktop/desktop-go.sh test +-tags vivahead,lithevisual ./internal/workbench ./internal/settingswindow +-run '^TestVisualEditorEssentials' -count=1 -timeout 120s` 生成。 +生产路径使用固定 Core 修订;开发中可用 `LITHE_CORE_RUST_DIR` 指向包含本功能的 Core 检出。 diff --git a/docs/assets/ide-essentials/editor-settings-dark.png b/docs/assets/ide-essentials/editor-settings-dark.png new file mode 100644 index 0000000000..e984a81ff7 Binary files /dev/null and b/docs/assets/ide-essentials/editor-settings-dark.png differ diff --git a/docs/assets/ide-essentials/editor-settings-light.png b/docs/assets/ide-essentials/editor-settings-light.png new file mode 100644 index 0000000000..35660440b4 Binary files /dev/null and b/docs/assets/ide-essentials/editor-settings-light.png differ diff --git a/docs/assets/ide-essentials/find-replace-dark.png b/docs/assets/ide-essentials/find-replace-dark.png new file mode 100644 index 0000000000..34fd75bb56 Binary files /dev/null and b/docs/assets/ide-essentials/find-replace-dark.png differ diff --git a/docs/assets/ide-essentials/find-replace-light.png b/docs/assets/ide-essentials/find-replace-light.png new file mode 100644 index 0000000000..448a37d36a Binary files /dev/null and b/docs/assets/ide-essentials/find-replace-light.png differ diff --git a/docs/assets/ide-essentials/keymap-schemes-dark.png b/docs/assets/ide-essentials/keymap-schemes-dark.png new file mode 100644 index 0000000000..685b0a782b Binary files /dev/null and b/docs/assets/ide-essentials/keymap-schemes-dark.png differ diff --git a/docs/assets/ide-essentials/keymap-schemes-light.png b/docs/assets/ide-essentials/keymap-schemes-light.png new file mode 100644 index 0000000000..c4e81e1a05 Binary files /dev/null and b/docs/assets/ide-essentials/keymap-schemes-light.png differ diff --git a/docs/assets/ide-essentials/recent-edits-dark.png b/docs/assets/ide-essentials/recent-edits-dark.png new file mode 100644 index 0000000000..9cd35f0ab7 Binary files /dev/null and b/docs/assets/ide-essentials/recent-edits-dark.png differ diff --git a/docs/assets/ide-essentials/recent-edits-light.png b/docs/assets/ide-essentials/recent-edits-light.png new file mode 100644 index 0000000000..077e6dbcad Binary files /dev/null and b/docs/assets/ide-essentials/recent-edits-light.png differ diff --git a/docs/assets/ide-essentials/recovery-conflict-dark.png b/docs/assets/ide-essentials/recovery-conflict-dark.png new file mode 100644 index 0000000000..95de66ba87 Binary files /dev/null and b/docs/assets/ide-essentials/recovery-conflict-dark.png differ diff --git a/docs/assets/ide-essentials/recovery-conflict-light.png b/docs/assets/ide-essentials/recovery-conflict-light.png new file mode 100644 index 0000000000..c752e2c0b0 Binary files /dev/null and b/docs/assets/ide-essentials/recovery-conflict-light.png differ diff --git a/docs/assets/ide-essentials/scratch-editor-dark.png b/docs/assets/ide-essentials/scratch-editor-dark.png new file mode 100644 index 0000000000..b28d7df1d9 Binary files /dev/null and b/docs/assets/ide-essentials/scratch-editor-dark.png differ diff --git a/docs/assets/ide-essentials/scratch-editor-light.png b/docs/assets/ide-essentials/scratch-editor-light.png new file mode 100644 index 0000000000..cc9d7ad8cf Binary files /dev/null and b/docs/assets/ide-essentials/scratch-editor-light.png differ diff --git a/docs/assets/ide-essentials/scratch-list-dark.png b/docs/assets/ide-essentials/scratch-list-dark.png new file mode 100644 index 0000000000..9f6c69fe94 Binary files /dev/null and b/docs/assets/ide-essentials/scratch-list-dark.png differ diff --git a/docs/assets/ide-essentials/scratch-list-light.png b/docs/assets/ide-essentials/scratch-list-light.png new file mode 100644 index 0000000000..d7b2b59fab Binary files /dev/null and b/docs/assets/ide-essentials/scratch-list-light.png differ diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 3d9e6b7541..cacc92ee81 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -391,7 +391,10 @@ Viva 编辑器性能基线 `scripts/desktop/perf/editor-bench.sh` 把每次运 Viva 的 Core 源码检出、Cargo 目标目录和暂存静态库位于当前工作树的 `.artifacts/desktop/lithe-core-rust/` 与 `.artifacts/desktop/lithe-core/`。暂存身份记录包含 -修订、目标、profile 与编译器,但尚不是可跨工作树复用的完整密封清单,故资源清单中的 +修订、目标、profile 与编译器;Windows GNU 构建还固定设置上游 winapi 的 +`WINAPI_NO_BUNDLED_LIBRARIES=1`,直接链接已安装 MinGW 的系统导入库,并记录 +`winapi-import-libraries=mingw-system`。这避免 cgo 依赖 Cargo 私有路径中的 +`libwinapi_*` 归档;不增加下载、缓存目录或运行期资源。该身份尚不是可跨工作树复用的完整密封清单,故资源清单中的 `viva-core-build-state` 明确拒绝复制;每个工作树独立构建和校验。Core 仓库恢复的 `scripts/rust-core/verify-rust-core-comments.sh` 先用固定词法器检查真实注释,再检查 Rustdoc;调用方应沿用本工作树的 `CARGO_TARGET_DIR`。独立 Core 检出未提供该变量时,输出只进入该检出的 `.artifacts/rust-core-checks/`(桌面默认检出内为 `.artifacts/desktop/lithe-core-rust/source/.artifacts/rust-core-checks/`)。词法器二进制、Cargo 状态与 Rustdoc 受 Core 修订、helper Cargo.lock、目标、编译器及环境约束,和已有 Core build state 一起排除,不注册复用 validator;只在构建/验证阶段生成,不进入安装包,不影响签名或增量更新。下方有关 Swift、Tauri、 JDTLS 和旧工作流的描述记录迁移前流程,不能当作 Viva 的当前构建或复用能力。 当前资源复用脚本的自包含回归覆盖路径、身份校验与禁止复制的状态;测试通过不证明本分支已删除的 PlantUML、远程服务、Swift/Tauri 客户端或旧 Windows 工作流仍可构建。preview 的 JDK 缓存历史问题见 [#1797](https://github.com/1lck/Lithe-IDEA/issues/1797);这些旧产品流程必须单独迁移和验证,不能用资源脚本自测替代。 @@ -1071,3 +1074,16 @@ Viva stdio Debug 的临时状态位于可写插件根的 只读,不影响签名或 Sparkle delta。此状态沿用 `official-plugin-packages` 不可复用路由, 没有 identity stamp,发现、校验和复制阶段均禁止跨工作树共享;复用脚本无 validator, 其注册与拒绝由 `scripts/resources/test-reuse-worktree-resources.mjs` 验证。 + + +### Viva 编辑器的用户数据 + +`store.Open` 选择平台用户配置目录,`Lithe Desktop/EditorRecovery/.draft` +保存编辑器恢复副本及 Scratch。小型 JSON 头与原始 UTF-8 内容在同一临时文件 +`.checkpoint-*` 中流式写入、同步后原子替换,避免把整篇内容序列化成 JSON。 +普通文件保存成功后移除副本;Scratch 关闭标签后仍保留,直到另存为或明确丢弃。 +Core 定义单文档、总磁盘和条数限制,原生适配器负责执行配额、私有权限和序列化写入。 +`editor-recent-.json` 保存最近文件和位置;`settings.json` 保存编辑器显示偏好 +与快捷键方案。它们没有可用于版本、平台、架构或工具链验证的构建身份,资源清单 +`viva-editor-user-state` 在所有复制阶段拒绝共享或复用。测试使用各自临时配置目录。 +这些数据不进入安装包或签名输入,运行时也不修改安装资源,不影响 Sparkle delta。 diff --git a/docs/viva-migration.md b/docs/viva-migration.md index e92bd54542..a069027777 100644 --- a/docs/viva-migration.md +++ b/docs/viva-migration.md @@ -572,3 +572,18 @@ MCP 管理随 Agent 对话失去消费者后,本轮整块删除,后续重新 | Windows 安装与更新 | — | Tauri 打包 `nsis`、`msi`(`tauri.conf.json` `bundle.targets`);Tauri updater 插件,`tauri.conf.json` 中 `pubkey` 为空串、`endpoints` 为空;稳定版发布工作流 `release-windows.yml` 用 secret `TAURI_SIGNING_PRIVATE_KEY` 与变量 `TAURI_UPDATER_PUBLIC_KEY` 签名,产出 `Lithe-<版本>-windows-x64-updater.exe` | `viva.toml [windows]`:`scope = "user"`、`publisher = "Lithe contributors"`;`package-desktop.sh` Windows 默认格式 `nsis,zip`;更新机制未找到 | 部分。同为 NSIS;没有 MSI、更新器与签名公钥配置 | | 发布工作流 | `release-macos.yml`、`release-preview-macos.yml` | `release-windows.yml`、`release-preview-windows.yml` | `.github/workflows/desktop-release.yml`,标签 `desktop-v*.*.*`,作为 prerelease 发布,避免旧客户端的更新器读到;`.github/workflows/desktop-autobuild.yml` 每天从 `preview` 构建并滚动发布到 prerelease `desktop-AutoBuild`(macOS arm64、Windows x64、Linux x64/arm64 的 deb 与 tar.gz,不跑测试),标签与旧客户端的 `AutoBuild` 分开 | 独立 | | 运行时只读边界 | 发行 bundle 运行期不可写(AGENTS.md) | 安装目录只读 | `package-desktop.sh` 注释声明运行时写入不落在 app 或安装目录;`runtime-package-integrity` 仅 macOS 夹具验证 | 一致于规则;Windows/最终包验证未完成 | + + +### 编辑器基础能力补齐(2026-11-13) + +Viva 编辑器新增文件内查找替换(Unicode、正则捕获组、选区、匹配高亮、批量替换单步撤销), +独立恢复检查点与外部磁盘冲突保护,显示行号/空白字符/光标样式与闪烁、实际自动保存延迟, +最近文件/最近编辑列表,独立命名快捷键方案,以及项目内 Scratch、持久草稿列表、另存为和丢弃。 +默认入口为主修饰键(macOS Command,其他平台 Control)加 F/R、E/Shift-E、N、Shift-S; +命令菜单同样提供入口并使用实际方案绑定。共享规则由固定版本的 Rust Core 提供, +原生编辑器与存储适配器执行结果。第三方快捷键导入仍由插件提供。 + +`editor-in-file-find-replace`、`editor-unsaved-recovery`、`editor-recent-files`、`editor-scratch-files` +记录独立能力;已有显示偏好与快捷键矩阵补充新范围。实际 Page 的无头截图见 +[测试截图](assets/ide-essentials/README.md),覆盖深色中文与浅色英文。 +原生 macOS 窗口和 Windows 的运行时验收仍为 pending。 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 0297c1e37c..ef6b693c60 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,7 +28,8 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" -# Lithe-core-rust #21 (debug.setBreakpointsMuted, debug.planMemoryWindow and +# Lithe-core-rust #22 (IDE find/replace, recovery, preferences, navigation, keymaps and +# Scratch lifecycle), squash-merged into main, on top of #21 (debug.setBreakpointsMuted, debug.planMemoryWindow and # debug.locateMemoryWindow, runConfig.decideTitleAction), squash-merged into main, on top of #20 # (lsp.declarationOrUsages and the references operation's includeDeclaration, for Go to # Declaration or Usages), #19 (MCP configuration and library commands removed) and #17: the plugin contract is one @@ -36,7 +37,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13 (execution.planLaunchCommand), #8, #7, #6 and #4. -PINNED_CORE_REVISION="c001967afac3fd8b706c16119c180807cac7d85a" +PINNED_CORE_REVISION="65cf82343c5e315aae2e335b2e8f0217b703e89a" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in @@ -53,6 +54,13 @@ if [[ "$RUST_TARGET" == *-windows-msvc ]]; then exit 2 fi +# cgo's external MinGW linker already supplies the Windows system import libraries. +# winapi's supported switch avoids depending on libwinapi_* archives under a +# Cargo registry/build-script directory that is not part of the staged Core. +if [[ "$RUST_TARGET" == *-windows-gnu ]]; then + export WINAPI_NO_BUNDLED_LIBRARIES=1 +fi + ARTIFACTS_DIR="$ROOT_DIR/.artifacts/desktop" STAGE_DIR="$ARTIFACTS_DIR/lithe-core/$RUST_TARGET/$PROFILE" CARGO_TARGET_DIR_BASH="$ARTIFACTS_DIR/lithe-core-rust/target" @@ -155,6 +163,9 @@ install -m 0755 "$HELPER" "$STAGE_DIR/bin/lithe-mcp$HELPER_EXE" printf 'rustc=%s\n' "$(rustc -V)" printf 'target=%s\n' "$RUST_TARGET" printf 'profile=%s\n' "$PROFILE" + if [[ "$RUST_TARGET" == *-windows-gnu ]]; then + printf 'winapi-import-libraries=mingw-system\n' + fi if [[ "$RUST_TARGET" == *-apple-darwin ]]; then printf 'macos-deployment-target=%s\n' "$MACOSX_DEPLOYMENT_TARGET" fi diff --git a/scripts/resources/reuse-worktree-resources.mjs b/scripts/resources/reuse-worktree-resources.mjs index 5c282fe44f..0e9c832f30 100644 --- a/scripts/resources/reuse-worktree-resources.mjs +++ b/scripts/resources/reuse-worktree-resources.mjs @@ -87,7 +87,9 @@ async function readRegistry() { // Native cgo cache fixtures own and remove temporary archives; the link digest // invalidates Go actions only and does not make Core output reusable. // Viva's Core checkout, Cargo target and staged static libraries have no sealed - // cross-worktree identity; marketplace transfer directories are runtime-owned. + // cross-worktree identity, including Windows GNU winapi-import-libraries=mingw-system. + // WINAPI_NO_BUNDLED_LIBRARIES selects installed MinGW inputs, not reusable downloads. + // Marketplace transfer directories are runtime-owned. // Both remain excluded before any source access or copy operation. // Build Provider snapshots remain under the excluded per-workspace PluginState // owner, including after removing the old macOS Maven tree output allocator. @@ -114,6 +116,8 @@ async function readRegistry() { // Offline Markdown libraries, including PlantUML, are pinned Git inputs. // Rebuild the target checkout's template/vendor resources before signing. // Generated bundles and live render state are never reusable resources. + // viva-editor-user-state: recovery source, recent files and keymap schemes are + // private mutable user data. Reject them before every source/copy/validator stage. const excludedResources = registry.excludedResources ?? []; if (!Array.isArray(excludedResources)) throw new Error("Invalid excluded worktree resources"); for (const resource of excludedResources) { diff --git a/scripts/resources/test-reuse-worktree-resources.mjs b/scripts/resources/test-reuse-worktree-resources.mjs index 1ce04f6d54..e0ee15c04d 100644 --- a/scripts/resources/test-reuse-worktree-resources.mjs +++ b/scripts/resources/test-reuse-worktree-resources.mjs @@ -100,6 +100,8 @@ try { const transfer = registry.excludedResources.find(item => item.id === "plugin-marketplace-state"); const icons = registry.excludedResources.find(item => item.id === "viva-file-icons"); assert.equal(core.reusable, false); + assert.match(core.identity, /WINAPI_NO_BUNDLED_LIBRARIES=1/); + assert.match(core.identity, /winapi-import-libraries=mingw-system/); assert.ok(core.locations.includes(".artifacts/desktop/lithe-core-rust/target/")); assert.ok(core.locations.includes(".artifacts/desktop/lithe-core/")); assert.equal(transfer.reusable, false); @@ -604,7 +606,7 @@ try { assert.notEqual(result.status, 0); assert.match(result.stderr, /language-tools is isolated/); - for (const id of ["windows-worker-plugins", "installed-worker-plugins"]) { + for (const id of ["windows-worker-plugins", "installed-worker-plugins", "viva-editor-user-state"]) { const result = run(process.execPath, [reuseScript, "--source", sourceRoot, "--resource", id]); assert.notEqual(result.status, 0); assert.match(diagnostics(result), /isolated/); diff --git a/scripts/resources/worktree-resources.json b/scripts/resources/worktree-resources.json index dd8ef14798..145b444caf 100644 --- a/scripts/resources/worktree-resources.json +++ b/scripts/resources/worktree-resources.json @@ -74,7 +74,7 @@ ".artifacts/desktop/lithe-core-rust/source/.artifacts/rust-core-checks/", "/lithe core-cache-*/" ], - "identity": "The Core source checkout is pinned by build-desktop-core.sh, while Cargo target output and staged libraries depend on source revision, target, profile, compiler, environment and native linker inputs. The current staged identity is not a sealed reusable-resource manifest.", + "identity": "The Core source checkout is pinned by build-desktop-core.sh, while Cargo target output and staged libraries depend on source revision, target, profile, compiler, environment and native linker inputs. Windows GNU builds set WINAPI_NO_BUNDLED_LIBRARIES=1 and record winapi-import-libraries=mingw-system, using the installed MinGW system import libraries. The current staged identity is not a sealed reusable-resource manifest.", "reason": "Never copy or share these mutable build outputs or the checkout through worktree reuse. Each worktree builds or validates its own Core artifacts. They are build-time resources outside an installed application and do not modify a signed bundle or Sparkle baseline. Restored Core comment verification and its pinned lexer helper use the caller Cargo target, or a checkout-local .artifacts/rust-core-checks fallback; Rustdoc, helper binaries and build state remain excluded at every reuse stage. The native cgo cache regression owns one temporary fixture checkout and static archive, removes it after bounded compiler processes terminate, and never reuses it across worktrees. The Go cache identity includes staged Core/header/native-linker bytes and selected Windows import archives; this action hash is not a reusable-resource seal." }, { @@ -624,6 +624,18 @@ ], "identity": "Mutable user-owned plugin preference layers and one native publication, bound to captured root identity and exact source bytes. No build, platform, architecture or toolchain identity makes these reusable.", "reason": "Core supplies relative source names and a 1 MiB byte budget; native storage reads without creating files and publishes only after explicit save. Same-directory exclusive temporary files preserve native metadata and are removed after publication, failure or cancellation. Never copy, share, package or validate these as download resources at any worktree reuse stage. Preferences remain outside installed resources and do not alter code signatures or Sparkle delta baselines." + }, + { + "id": "viva-editor-user-state", + "reusable": false, + "locations": [ + "/EditorRecovery/.draft", + "/EditorRecovery/.checkpoint-*", + "/editor-recent-.json", + "/settings.json (editor preferences and keymap schemes)" + ], + "identity": "Mutable user-authored source snapshots, caret/history and personal keymap settings. Owned by the preference installation and document, with no reusable version/platform/architecture/toolchain stamp.", + "reason": "Native adapters read only when an editor or list needs them, and atomically replace private files after edits or explicit settings changes. Core owns limits and recovery conflict decisions; saved/discarded normal documents remove recovery copies, scratch files persist until Save As or discard. Never share, copy, package or run a build resource validator at any worktree reuse stage. These paths are outside installed resources and cannot affect code signatures or Sparkle delta baselines." } ] } diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 73d6a1cc0e..e75859d4fe 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11000,7 +11000,65 @@ "desktop.title.notDebuggable": "{name} cannot be debugged: its plugin declares no debug adapter for this run.", "desktop.title.runBusy": "The Run window is still running another operation. Wait for it to finish or stop it first.", "desktop.diff.keepWhitespace": "Do not ignore whitespace", - "desktop.tools.moveTo": "Move to" + "desktop.tools.moveTo": "Move to", + "desktop.editorFind.find": "Find", + "desktop.editorFind.replace": "Replace", + "desktop.editorFind.replaceOne": "Replace current", + "desktop.editorFind.replaceAll": "Replace all", + "desktop.editorFind.case": "Match case", + "desktop.editorFind.word": "Whole words", + "desktop.editorFind.regex": "Regular expression", + "desktop.editorFind.selection": "In selection", + "desktop.editorFind.previous": "Previous match", + "desktop.editorFind.next": "Next match", + "desktop.editorFind.close": "Close find", + "desktop.editorFind.loading": "Searching…", + "desktop.editorFind.invalidPattern": "The regular expression is invalid.", + "desktop.editorFind.tooLarge": "This file exceeds the 64 MiB search limit.", + "desktop.editorFind.tooMany": "More than 10,000 matches. Narrow the scope before replacing all.", + "desktop.editorFind.replacementTooLarge": "The replacement is too large. Narrow the scope.", + "desktop.editorFind.stale": "The document changed. Retry the replacement.", + "desktop.editorFind.failed": "Could not complete the search or replacement.", + "desktop.editorPrefs.title": "Editor display", + "desktop.editorPrefs.lineNumbers": "Show line numbers", + "desktop.editorPrefs.whitespace": "Show whitespace", + "desktop.editorPrefs.cursorStyle": "Caret style", + "desktop.editorPrefs.cursorBlink": "Blink caret", + "desktop.editorPrefs.line": "Line", + "desktop.editorPrefs.block": "Block", + "desktop.editorPrefs.underline": "Underline", + "desktop.editorPrefs.saveDelay": "Auto-save delay (ms)", + "desktop.editorPrefs.saveDelayHelp": "Wait this long after typing before auto-saving (250–60,000 ms). Disabled when auto-save is off. Draft recovery is independent.", + "desktop.editorPrefs.failed": "Could not update editor settings.", + "desktop.recentFiles.title": "Recent files", + "desktop.recentFiles.edited": "Recent edits", + "desktop.recentFiles.query": "Search recent files", + "desktop.recentFiles.empty": "No matching recent files.", + "desktop.recentFiles.failed": "Could not read recent files.", + "desktop.drafts.new": "New scratch file", + "desktop.drafts.saveAs": "Save As…", + "desktop.drafts.recovered": "Unsaved contents were recovered.", + "desktop.drafts.conflict": "Draft recovered. The disk file changed; compare the versions before choosing which to keep.", + "desktop.drafts.failed": "Could not save the recovery copy. Unsaved contents remain in the editor.", + "desktop.drafts.discard": "Discard draft", + "desktop.drafts.list": "Scratch files", + "desktop.drafts.empty": "No scratch files.", + "desktop.drafts.saved": "The draft was saved to a file.", + "desktop.keymapSchemes.scheme": "Keymap scheme", + "desktop.keymapSchemes.default": "Default", + "desktop.keymapSchemes.saveAs": "Save as new scheme…", + "desktop.keymapSchemes.rename": "Rename scheme…", + "desktop.keymapSchemes.delete": "Delete scheme", + "desktop.keymapSchemes.name": "Scheme name", + "desktop.keymapSchemes.newTitle": "Save keymap scheme", + "desktop.keymapSchemes.renameTitle": "Rename keymap scheme", + "desktop.keymapSchemes.invalidName": "Enter a scheme name of 1–64 characters.", + "desktop.keymapSchemes.duplicateName": "A scheme with this name already exists.", + "desktop.keymapSchemes.limit": "Up to 16 keymap schemes can be saved.", + "desktop.keymapSchemes.failed": "Could not update keymap schemes. The original scheme is preserved.", + "desktop.editorFind.count": "{current}/{total}", + "desktop.editorFind.replaced": "Replaced {count} occurrences.", + "desktop.drafts.untitled": "Untitled {number}" }, "overrides": { "windows": { diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index d62dfeb28d..06614d0838 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11000,7 +11000,65 @@ "desktop.title.notDebuggable": "无法调试 {name}:它所属的插件没有为这个运行声明调试适配器。", "desktop.title.runBusy": "运行窗口还在执行其他操作。请等它结束,或者先停止它。", "desktop.diff.keepWhitespace": "不忽略空白", - "desktop.tools.moveTo": "移动到" + "desktop.tools.moveTo": "移动到", + "desktop.editorFind.find": "查找", + "desktop.editorFind.replace": "替换", + "desktop.editorFind.replaceOne": "替换当前", + "desktop.editorFind.replaceAll": "全部替换", + "desktop.editorFind.case": "区分大小写", + "desktop.editorFind.word": "整词匹配", + "desktop.editorFind.regex": "正则表达式", + "desktop.editorFind.selection": "仅在选区中", + "desktop.editorFind.previous": "上一个匹配", + "desktop.editorFind.next": "下一个匹配", + "desktop.editorFind.close": "关闭查找", + "desktop.editorFind.loading": "正在查找…", + "desktop.editorFind.invalidPattern": "正则表达式无效。", + "desktop.editorFind.tooLarge": "此文件超过查找的 64 MiB 上限。", + "desktop.editorFind.tooMany": "匹配超过 10000 处;请缩小范围后再全部替换。", + "desktop.editorFind.replacementTooLarge": "替换结果过大,请缩小范围。", + "desktop.editorFind.stale": "文档已更改,请重试替换。", + "desktop.editorFind.failed": "无法完成查找或替换。", + "desktop.editorPrefs.title": "编辑器显示", + "desktop.editorPrefs.lineNumbers": "显示行号", + "desktop.editorPrefs.whitespace": "显示空白字符", + "desktop.editorPrefs.cursorStyle": "光标样式", + "desktop.editorPrefs.cursorBlink": "光标闪烁", + "desktop.editorPrefs.line": "竖线", + "desktop.editorPrefs.block": "方块", + "desktop.editorPrefs.underline": "下划线", + "desktop.editorPrefs.saveDelay": "自动保存延迟(毫秒)", + "desktop.editorPrefs.saveDelayHelp": "停止输入后等待此时间再自动保存。范围为 250–60000 毫秒;关闭自动保存时不执行。草稿恢复独立保留。", + "desktop.editorPrefs.failed": "无法更新编辑器设置。", + "desktop.recentFiles.title": "最近文件", + "desktop.recentFiles.edited": "最近编辑", + "desktop.recentFiles.query": "搜索最近文件", + "desktop.recentFiles.empty": "没有匹配的最近文件。", + "desktop.recentFiles.failed": "无法读取最近文件记录。", + "desktop.drafts.new": "新建临时草稿", + "desktop.drafts.saveAs": "另存为…", + "desktop.drafts.recovered": "已恢复未保存内容。", + "desktop.drafts.conflict": "已恢复草稿;磁盘文件已更改,请比较后决定保留哪一份。", + "desktop.drafts.failed": "无法保存恢复副本,未保存内容仍保留在编辑器中。", + "desktop.drafts.discard": "丢弃草稿", + "desktop.drafts.list": "临时草稿", + "desktop.drafts.empty": "没有临时草稿。", + "desktop.drafts.saved": "草稿已另存为文件。", + "desktop.keymapSchemes.scheme": "快捷键方案", + "desktop.keymapSchemes.default": "默认方案", + "desktop.keymapSchemes.saveAs": "保存为新方案…", + "desktop.keymapSchemes.rename": "重命名方案…", + "desktop.keymapSchemes.delete": "删除方案", + "desktop.keymapSchemes.name": "方案名称", + "desktop.keymapSchemes.newTitle": "保存快捷键方案", + "desktop.keymapSchemes.renameTitle": "重命名快捷键方案", + "desktop.keymapSchemes.invalidName": "请输入 1–64 个字符的方案名称。", + "desktop.keymapSchemes.duplicateName": "此方案名称已存在。", + "desktop.keymapSchemes.limit": "最多可保存 16 套快捷键方案。", + "desktop.keymapSchemes.failed": "无法更新快捷键方案,原方案仍然保留。", + "desktop.editorFind.count": "{current}/{total}", + "desktop.editorFind.replaced": "已替换 {count} 处。", + "desktop.drafts.untitled": "临时草稿 {number}" }, "overrides": { "macos": { diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 02d208467b..c186cf637e 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -104857,6 +104857,422 @@ "platforms": [ "desktop" ] + }, + { + "id": "desktop.editorFind.find", + "description": "IDE editor essentials: editorFind.find", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.replace", + "description": "IDE editor essentials: editorFind.replace", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.replaceOne", + "description": "IDE editor essentials: editorFind.replaceOne", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.replaceAll", + "description": "IDE editor essentials: editorFind.replaceAll", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.case", + "description": "IDE editor essentials: editorFind.case", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.word", + "description": "IDE editor essentials: editorFind.word", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.regex", + "description": "IDE editor essentials: editorFind.regex", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.selection", + "description": "IDE editor essentials: editorFind.selection", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.previous", + "description": "IDE editor essentials: editorFind.previous", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.next", + "description": "IDE editor essentials: editorFind.next", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.close", + "description": "IDE editor essentials: editorFind.close", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.loading", + "description": "IDE editor essentials: editorFind.loading", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.invalidPattern", + "description": "IDE editor essentials: editorFind.invalidPattern", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.tooLarge", + "description": "IDE editor essentials: editorFind.tooLarge", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.tooMany", + "description": "IDE editor essentials: editorFind.tooMany", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.replacementTooLarge", + "description": "IDE editor essentials: editorFind.replacementTooLarge", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.stale", + "description": "IDE editor essentials: editorFind.stale", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.failed", + "description": "IDE editor essentials: editorFind.failed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.title", + "description": "IDE editor essentials: editorPrefs.title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.lineNumbers", + "description": "IDE editor essentials: editorPrefs.lineNumbers", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.whitespace", + "description": "IDE editor essentials: editorPrefs.whitespace", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.cursorStyle", + "description": "IDE editor essentials: editorPrefs.cursorStyle", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.cursorBlink", + "description": "IDE editor essentials: editorPrefs.cursorBlink", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.line", + "description": "IDE editor essentials: editorPrefs.line", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.block", + "description": "IDE editor essentials: editorPrefs.block", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.underline", + "description": "IDE editor essentials: editorPrefs.underline", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.saveDelay", + "description": "IDE editor essentials: editorPrefs.saveDelay", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.saveDelayHelp", + "description": "IDE editor essentials: editorPrefs.saveDelayHelp", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.failed", + "description": "IDE editor essentials: editorPrefs.failed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.recentFiles.title", + "description": "IDE editor essentials: recentFiles.title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.recentFiles.edited", + "description": "IDE editor essentials: recentFiles.edited", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.recentFiles.query", + "description": "IDE editor essentials: recentFiles.query", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.recentFiles.empty", + "description": "IDE editor essentials: recentFiles.empty", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.recentFiles.failed", + "description": "IDE editor essentials: recentFiles.failed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.new", + "description": "IDE editor essentials: drafts.new", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.saveAs", + "description": "IDE editor essentials: drafts.saveAs", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.recovered", + "description": "IDE editor essentials: drafts.recovered", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.conflict", + "description": "IDE editor essentials: drafts.conflict", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.failed", + "description": "IDE editor essentials: drafts.failed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.discard", + "description": "IDE editor essentials: drafts.discard", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.list", + "description": "IDE editor essentials: drafts.list", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.empty", + "description": "IDE editor essentials: drafts.empty", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.drafts.saved", + "description": "IDE editor essentials: drafts.saved", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.scheme", + "description": "IDE editor essentials: keymapSchemes.scheme", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.default", + "description": "IDE editor essentials: keymapSchemes.default", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.saveAs", + "description": "IDE editor essentials: keymapSchemes.saveAs", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.rename", + "description": "IDE editor essentials: keymapSchemes.rename", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.delete", + "description": "IDE editor essentials: keymapSchemes.delete", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.name", + "description": "IDE editor essentials: keymapSchemes.name", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.newTitle", + "description": "IDE editor essentials: keymapSchemes.newTitle", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.renameTitle", + "description": "IDE editor essentials: keymapSchemes.renameTitle", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.invalidName", + "description": "IDE editor essentials: keymapSchemes.invalidName", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.duplicateName", + "description": "IDE editor essentials: keymapSchemes.duplicateName", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.limit", + "description": "IDE editor essentials: keymapSchemes.limit", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.keymapSchemes.failed", + "description": "IDE editor essentials: keymapSchemes.failed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorFind.count", + "description": "IDE editor essentials: editorFind.count", + "platforms": [ + "desktop" + ], + "parameters": { + "current": "integer", + "total": "integer" + } + }, + { + "id": "desktop.editorFind.replaced", + "description": "IDE editor essentials: editorFind.replaced", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "integer" + } + }, + { + "id": "desktop.drafts.untitled", + "description": "IDE editor essentials: drafts.untitled", + "platforms": [ + "desktop" + ], + "parameters": { + "number": "integer" + } } ] } diff --git a/shared/platform-feature-matrix/features/editor-global-appearance.json b/shared/platform-feature-matrix/features/editor-global-appearance.json index e28fd4df61..d7afa07530 100644 --- a/shared/platform-feature-matrix/features/editor-global-appearance.json +++ b/shared/platform-feature-matrix/features/editor-global-appearance.json @@ -9,7 +9,10 @@ "evidence": [ "desktop/internal/settingswindow/fonts_view.go", "desktop/internal/settingswindow/window_view.go", - "desktop/internal/fontprefs/fontprefs.go" + "desktop/internal/fontprefs/fontprefs.go", + "desktop/internal/settingswindow/editor_preferences_view.go", + "desktop/internal/editorview/presentation.go", + "desktop/internal/settingswindow/editor_essentials_test.go" ] }, "windows": { @@ -18,12 +21,15 @@ "evidence": [ "desktop/internal/settingswindow/fonts_view.go", "desktop/internal/settingswindow/window_view.go", - "desktop/internal/fontprefs/fontprefs.go" + "desktop/internal/fontprefs/fontprefs.go", + "desktop/internal/settingswindow/editor_preferences_view.go", + "desktop/internal/editorview/presentation.go", + "desktop/internal/settingswindow/editor_essentials_test.go" ] }, "owner": "Editor / Settings", - "notes": "Viva:字体与行间距设置页已实现(fonts_view.go 的 line spacing 显示,fontprefs 解析 LineSpacing),编辑器页(window_view.go 的 editorPage)只有标签行数与语义高亮开关。未找到高亮配色方案选择和其他显示偏好的设置入口。", - "verification": "自动化:运行 AppSettingsTests、MonacoWorkbenchThemeTests、SettingsSearchVocabularyTests,以及 scripts/macos/probe/probe-macos-monaco.sh --workbench-tests,检查持久化、逐字段坏值回退、恢复默认、双外观词法/语义配色、已有与新建分栏选项、模型/光标/撤销历史保留,以及隐藏行号后的断点图标、已有断点/空白行点击与相对行号恢复。产品验收:在中文和英文设置中检索行间距、配色、空白符和光标;在深浅外观及多个项目中逐项切换,检查主编辑器、分栏、独立窗口和完整源码预览实时更新。检查 6/72 字号与 1/3 倍行间距边界、键盘选择、窄设置窗口滚动、关闭设置与重启后的恢复,以及恢复默认。完整产品 UI 验收和 Windows WebView2 验收仍待完成;组件和 WebKit 探针通过不替代这些验收。 WebKit 用例检查 YAML 块/流映射和序列、普通/引号值、浮点数、块文本、锚点以及其他四方案的深浅色回归。 SQL WebKit 回归覆盖中文/emoji/转义字符串、NOT NULL/EXISTS/COLLATE、数字和符号、深浅方案及其他方案颜色保持。 WebKit 遍历全部 47 个基础语言的真实模型深浅色字符串,校验具体语言角色和其他四套配色的细分 token 继承;Java 文档注释/转义/注解由真实 TextMate worker 验证。", + "notes": "Viva:字体与行间距设置页已实现(fonts_view.go 的 line spacing 显示,fontprefs 解析 LineSpacing),编辑器页(window_view.go 的 editorPage)只有标签行数与语义高亮开关。未找到高亮配色方案选择和其他显示偏好的设置入口。 新增行号、空白字符、光标形状/闪烁和实际自动保存延迟。Core 解析默认值与限额,原生绘制不重新扫描全文。高亮方案等既有缺口仍不在本次范围。", + "verification": "新增范围:运行 desktop/internal/settingswindow/editor_essentials_test.go 和 editor_essentials_visual_test.go,检查持久设置与深色中文、浅色英文。macOS/Windows 原生窗口验收 pending。自动化:运行 AppSettingsTests、MonacoWorkbenchThemeTests、SettingsSearchVocabularyTests,以及 scripts/macos/probe/probe-macos-monaco.sh --workbench-tests,检查持久化、逐字段坏值回退、恢复默认、双外观词法/语义配色、已有与新建分栏选项、模型/光标/撤销历史保留,以及隐藏行号后的断点图标、已有断点/空白行点击与相对行号恢复。产品验收:在中文和英文设置中检索行间距、配色、空白符和光标;在深浅外观及多个项目中逐项切换,检查主编辑器、分栏、独立窗口和完整源码预览实时更新。检查 6/72 字号与 1/3 倍行间距边界、键盘选择、窄设置窗口滚动、关闭设置与重启后的恢复,以及恢复默认。完整产品 UI 验收和 Windows WebView2 验收仍待完成;组件和 WebKit 探针通过不替代这些验收。 WebKit 用例检查 YAML 块/流映射和序列、普通/引号值、浮点数、块文本、锚点以及其他四方案的深浅色回归。 SQL WebKit 回归覆盖中文/emoji/转义字符串、NOT NULL/EXISTS/COLLATE、数字和符号、深浅方案及其他方案颜色保持。 WebKit 遍历全部 47 个基础语言的真实模型深浅色字符串,校验具体语言角色和其他四套配色的细分 token 继承;Java 文档注释/转义/注解由真实 TextMate worker 验证。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/editor-in-file-find-replace.json b/shared/platform-feature-matrix/features/editor-in-file-find-replace.json new file mode 100644 index 0000000000..9ba0179c3c --- /dev/null +++ b/shared/platform-feature-matrix/features/editor-in-file-find-replace.json @@ -0,0 +1,29 @@ +{ + "id": "editor-in-file-find-replace", + "area": "编辑器", + "group": "文档编辑", + "capability": "文件内查找替换,支持正则、匹配选项、选区、定位、高亮和单步撤销批量替换", + "owner": "Editor / Core", + "notes": "Viva 共享实现;匹配、顺序和恢复决策在外部 Rust Core。macOS 无头流程与截图已覆盖;macOS 原生窗口和 Windows 原生验收未执行。", + "verification": "查找 Unicode/emoji、正则捕获组、零宽匹配、选区与批量替换;编辑后旧结果不能修改新版本,关闭后释放定时器。 自动化:editor_essentials_test.go 与 editor_essentials_visual_test.go。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/editor_find.go", + "desktop/internal/editorview/prepared_edit.go", + "desktop/internal/workbench/editor_essentials_test.go", + "desktop/internal/workbench/editor_essentials_visual_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/editor_find.go", + "desktop/internal/editorview/prepared_edit.go", + "desktop/internal/workbench/editor_essentials_test.go", + "desktop/internal/workbench/editor_essentials_visual_test.go" + ] + } +} diff --git a/shared/platform-feature-matrix/features/editor-recent-files.json b/shared/platform-feature-matrix/features/editor-recent-files.json new file mode 100644 index 0000000000..0bfab8b8ea --- /dev/null +++ b/shared/platform-feature-matrix/features/editor-recent-files.json @@ -0,0 +1,27 @@ +{ + "id": "editor-recent-files", + "area": "编辑器", + "group": "文档编辑", + "capability": "最近文件与最近编辑列表,保留光标位置,提供过滤和打开入口", + "owner": "Editor / Core", + "notes": "Viva 共享实现;匹配、顺序和恢复决策在外部 Rust Core。macOS 无头流程与截图已覆盖;macOS 原生窗口和 Windows 原生验收未执行。", + "verification": "依次打开和编辑两个文件,核对访问/编辑独立顺序;过滤、键盘与点击打开,重启后保留位置。 自动化:editor_essentials_test.go 与 editor_essentials_visual_test.go。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/recent_files.go", + "desktop/internal/workbench/editor_essentials_test.go", + "desktop/internal/workbench/editor_essentials_visual_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/recent_files.go", + "desktop/internal/workbench/editor_essentials_test.go", + "desktop/internal/workbench/editor_essentials_visual_test.go" + ] + } +} diff --git a/shared/platform-feature-matrix/features/editor-scratch-files.json b/shared/platform-feature-matrix/features/editor-scratch-files.json new file mode 100644 index 0000000000..48a486ba3b --- /dev/null +++ b/shared/platform-feature-matrix/features/editor-scratch-files.json @@ -0,0 +1,29 @@ +{ + "id": "editor-scratch-files", + "area": "编辑器", + "group": "文档编辑", + "capability": "无需先选择路径的 Scratch 文档、持久草稿列表、另存为和丢弃", + "owner": "Editor / Core", + "notes": "Viva 共享实现;匹配、顺序和恢复决策在外部 Rust Core。macOS 无头流程与截图已覆盖;macOS 原生窗口和 Windows 原生验收未执行。", + "verification": "项目内创建 Scratch,写入中文 emoji 后关闭标签;从列表恢复,另存为后打开真实文件并删除草稿;丢弃后不得重新出现。 自动化:editor_essentials_test.go 与 editor_essentials_visual_test.go。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/scratch_files.go", + "desktop/internal/draftstore/store.go", + "desktop/internal/workbench/editor_essentials_test.go", + "desktop/internal/workbench/editor_essentials_visual_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/scratch_files.go", + "desktop/internal/draftstore/store.go", + "desktop/internal/workbench/editor_essentials_test.go", + "desktop/internal/workbench/editor_essentials_visual_test.go" + ] + } +} diff --git a/shared/platform-feature-matrix/features/editor-unsaved-recovery.json b/shared/platform-feature-matrix/features/editor-unsaved-recovery.json new file mode 100644 index 0000000000..0110761059 --- /dev/null +++ b/shared/platform-feature-matrix/features/editor-unsaved-recovery.json @@ -0,0 +1,29 @@ +{ + "id": "editor-unsaved-recovery", + "area": "编辑器", + "group": "文档编辑", + "capability": "独立于自动保存的未保存内容恢复;磁盘改变或缺失时保留冲突并等待明确选择", + "owner": "Editor / Core", + "notes": "Viva 共享实现;匹配、顺序和恢复决策在外部 Rust Core。macOS 无头流程与截图已覆盖;macOS 原生窗口和 Windows 原生验收未执行。", + "verification": "编辑后持久化检查点,重新打开项目自动恢复;初次文件监听和手动/自动保存均不能绕过恢复冲突;明确保留编辑器后保存并清理副本。 自动化:editor_essentials_test.go 与 editor_essentials_visual_test.go。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/editor_recovery.go", + "desktop/internal/draftstore/store.go", + "desktop/internal/workbench/editor_essentials_test.go", + "desktop/internal/workbench/editor_essentials_visual_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/editor_recovery.go", + "desktop/internal/draftstore/store.go", + "desktop/internal/workbench/editor_essentials_test.go", + "desktop/internal/workbench/editor_essentials_visual_test.go" + ] + } +} diff --git a/shared/platform-feature-matrix/features/keymap-customization.json b/shared/platform-feature-matrix/features/keymap-customization.json index 80bfc4babd..42628173f1 100644 --- a/shared/platform-feature-matrix/features/keymap-customization.json +++ b/shared/platform-feature-matrix/features/keymap-customization.json @@ -12,7 +12,9 @@ "desktop/internal/settingswindow/keymap_view_test.go", "desktop/internal/shortcuts/shortcuts.go", "desktop/internal/core/keymap_gesture.go", - "desktop/internal/core/keymap_gesture_test.go" + "desktop/internal/core/keymap_gesture_test.go", + "desktop/internal/settingswindow/keymap_schemes_view.go", + "desktop/internal/settingswindow/editor_essentials_test.go" ] }, "windows": { @@ -24,12 +26,14 @@ "desktop/internal/settingswindow/keymap_view_test.go", "desktop/internal/shortcuts/shortcuts.go", "desktop/internal/core/keymap_gesture.go", - "desktop/internal/core/keymap_gesture_test.go" + "desktop/internal/core/keymap_gesture_test.go", + "desktop/internal/settingswindow/keymap_schemes_view.go", + "desktop/internal/settingswindow/editor_essentials_test.go" ] }, "owner": "Settings", - "verification": "macOS 使用默认 Command-Shift-A 从编辑器、侧栏及第二个项目窗口打开 Find Action,确认输入聚焦、/ 命令过滤、Return 仅执行一次、Escape 关闭且重新打开无旧查询;弹窗已打开时再次调用应切换到 / 并聚焦。改绑、禁用、恢复及录制时确认菜单与分发使用有效绑定;无工作区或搜索模块不可用时应禁用,激活失败应关闭。IDEA Classic 和 Eclipse 的 Find Action 暂无默认绑定,普通 Search Everywhere 保留双击 Shift 和 Shift-Command-O。macOS 从设置 → 快捷键依次选择 macOS、IntelliJ IDEA Classic、Eclipse,核对运行、调试、查找等操作在界面和实际监听器中的绑定;IDEA Classic 的 Stop Run 应为 Control-F2,Eclipse 的 Resume 应为 F8,继承父 keymap 的命令应使用上游绑定,Find、Replace、GotoImplementation 等显式清空的命令应无绑定;检查分类树初始折叠、全部展开和折叠、分类展开、搜索时自动显示匹配操作、选中行高亮、右侧紧凑键帽及工具栏编辑菜单;通过键帽、工具栏或右键菜单新增、删除与恢复默认,并检查键盘辅助功能;分别修改两套预设的同一命令,切换与重启后确认自定义绑定互不覆盖,并验证旧版单套覆盖迁移到 macOS;按命令名称、ID 和按键搜索,制造冲突并恢复当前预设或应用全部默认;导出再导入 keybindings.json,确认预设与自定义绑定恢复且命令实际执行。Windows 保持现有快捷键编辑、导出和导入验证。", - "notes": "Viva:设置 › 快捷键页列出全部动作,可按名称或按键筛选;录制新增组合键、删除单个组合键、单项恢复默认与全部重置,覆盖项存入设置并由 shortcuts 应用到工作台与 Find Action;按键解析由 Core keymap 手势命令完成。keymap_view_test.go 覆盖页面交互;冲突提示与原生窗口验收 pending。", + "verification": "新增范围:运行 desktop/internal/settingswindow/editor_essentials_test.go 和 editor_essentials_visual_test.go,检查持久设置与深色中文、浅色英文。macOS/Windows 原生窗口验收 pending。macOS 使用默认 Command-Shift-A 从编辑器、侧栏及第二个项目窗口打开 Find Action,确认输入聚焦、/ 命令过滤、Return 仅执行一次、Escape 关闭且重新打开无旧查询;弹窗已打开时再次调用应切换到 / 并聚焦。改绑、禁用、恢复及录制时确认菜单与分发使用有效绑定;无工作区或搜索模块不可用时应禁用,激活失败应关闭。IDEA Classic 和 Eclipse 的 Find Action 暂无默认绑定,普通 Search Everywhere 保留双击 Shift 和 Shift-Command-O。macOS 从设置 → 快捷键依次选择 macOS、IntelliJ IDEA Classic、Eclipse,核对运行、调试、查找等操作在界面和实际监听器中的绑定;IDEA Classic 的 Stop Run 应为 Control-F2,Eclipse 的 Resume 应为 F8,继承父 keymap 的命令应使用上游绑定,Find、Replace、GotoImplementation 等显式清空的命令应无绑定;检查分类树初始折叠、全部展开和折叠、分类展开、搜索时自动显示匹配操作、选中行高亮、右侧紧凑键帽及工具栏编辑菜单;通过键帽、工具栏或右键菜单新增、删除与恢复默认,并检查键盘辅助功能;分别修改两套预设的同一命令,切换与重启后确认自定义绑定互不覆盖,并验证旧版单套覆盖迁移到 macOS;按命令名称、ID 和按键搜索,制造冲突并恢复当前预设或应用全部默认;导出再导入 keybindings.json,确认预设与自定义绑定恢复且命令实际执行。Windows 保持现有快捷键编辑、导出和导入验证。", + "notes": "Viva:设置 › 快捷键页列出全部动作,可按名称或按键筛选;录制新增组合键、删除单个组合键、单项恢复默认与全部重置,覆盖项存入设置并由 shortcuts 应用到工作台与 Find Action;按键解析由 Core keymap 手势命令完成。keymap_view_test.go 覆盖页面交互;冲突提示与原生窗口验收 pending。 新增命名方案的保存、选择、重命名和删除;Core 保证独立绑定和默认方案保护。页面打开只读取,不自动写入设置。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {