Restore last file, cursor, scroll, selection and find state on relaunch (spec §7)

Persist a tiny JSON snapshot (SessionState) written by the cmd layer
($HOME/.pad/session.json off-Android, /storage/emulated/0/Pad/ on
Android) and call the logic-owned snapshot rate-limited (<=1/s, on
change) from emitFrame plus unconditionally at Shutdown. On launch the
cmd layer hands the snapshot to Logic.BeginRestore before Run; the
file re-opens through the normal openFile path and lands straight on
the editor page.

- Cursor/selection land with the content, clamped to a shrunk file
  (path-guarded so a late result for a replaced file cannot apply the
  snapshot to the wrong buffer); a missing file falls back to the
  browser.
- Scroll is applied only after the first ScaleEvent has been laid out:
  the size ConfigEvent precedes it and the one-way MaxScroll clamp in a
  wrong-unit layout would corrupt the offset (found by e2e).
- Find: query + open/closed + current match are persisted; results are
  regenerated by re-scanning and the saved current match is re-selected
  by byte offset (Find.Restoring/RestoreMatch) without re-scrolling the
  restored viewport. A closed-bar query re-scans on the next bar open
  instead (an eager scan would be dropped and leave Scanning stuck).
- The main-owned find_bar widget is seeded with the restored query so
  its first frame matches the logic-side query.

Docs: spec.md gains §2.4 and drops the §7 row; invariant 5 updated;
architecture.md gains §6.7. Tests: 7 e2e tests covering cursor/scroll/
selection restore, clamping, missing-file fallback, find-bar restore
(open/closed), and the saver/shutdown persist paths.
This commit is contained in:
gmp
2026-08-20 16:01:02 -04:00
parent f31f849665
commit e3690d6b98
10 changed files with 961 additions and 23 deletions
+110 -11
View File
@@ -91,6 +91,26 @@ type Logic struct {
saveTimer *time.Timer // auto-save debounce timer; non-nil while pending
lastEmit time.Time // time of the last frame emission (profiler cadence)
debugCmdC chan string // one-shot debug commands from the cmd-file poller; nil = disabled
// Relaunch state restoration (spec §7, see session.go): session is the
// snapshot handed in by the cmd layer via BeginRestore (zero = none),
// restoreFile names the open whose stat/read results are the restore's
// ("" = none; any other open cancels it). sessionSaver is the cmd layer's
// file writer; lastSession/lastSessionSave drive the rate-limited
// change-detected save from emitFrame. All touched only on the owner.
session SessionState
restoreFile string
// restoreScroll/restoreScrollArmed hold the snapshot's scroll offset
// until it is safe to apply it: only once the scale is known (the first
// ScaleEvent — the size ConfigEvent arrives before it, and a layout in
// between computes the viewport in the wrong unit, which would clamp
// the offset, and the clamp is one-way). scaleSeen tracks that event.
restoreScroll ui.Dp
restoreScrollArmed bool
scaleSeen bool
sessionSaver func(SessionState)
lastSession SessionState
lastSessionSave time.Time
}
// NewLogic creates a new Logic instance, accepting an optional mockFS.
@@ -211,6 +231,14 @@ func (l *Logic) Run() {
// Dispatch initial directory index build on startup
l.workerPool.Dispatch(pool.NewBuildIndexTask(l.state.Browser.CurrentPath, l.mockFS))
// Relaunch restoration (spec §7): re-open the last file if a session
// was handed in before Run (BeginRestore). The browser index is still
// built: the back button must land on a populated browser.
if l.session.File != "" {
l.restoreFile = l.session.File
l.openFile(l.session.File)
}
for {
select {
case <-l.done:
@@ -222,7 +250,18 @@ func (l *Logic) Run() {
return
case update := <-l.configChan:
update.apply(l.state)
if _, ok := update.(ScaleEvent); ok {
l.scaleSeen = true
}
l.emitFrame()
// The restored scroll lands only AFTER a layout at the current
// scale: its clamp uses MaxScroll, which must reflect the same
// viewport units (the size ConfigEvent precedes the first
// ScaleEvent, so a layout between them is in the wrong unit).
if l.scaleSeen && l.restoreScrollArmed {
l.maybeApplyRestoreScroll()
l.emitFrame()
}
case fb := <-l.layoutChan:
// Store the full GlyphLayout on editor state.
// Derive LastLineY from it for scroll clamping.
@@ -266,17 +305,7 @@ func (l *Logic) Run() {
l.state.Editor.findSetQuery(q)
l.emitFrame()
case path := <-l.openFileChan:
// Discard find results for the previous file; the query is kept
// (see EditorState.findReset) and re-scanned against the new file.
TheState.Editor.findReset()
// Create chunked buffer for virtual scrolling
chunkSize := DefaultChunkSize
cb := NewChunkedBuffer(path, chunkSize, l.mockFS, "")
cb.SetWorkerPool(l.workerPool)
TheState.Editor.ChunkedBuffer = cb
// Dispatch stat task to get file size
l.workerPool.Dispatch(pool.NewStatFileTask(path, l.mockFS))
l.openFile(path)
case filename := <-l.retryChan:
log.Printf("Logic: Retrying save for %s", filename)
delete(l.retryScheduled, filename)
@@ -304,11 +333,36 @@ func (l *Logic) Run() {
}
}
// openFile starts loading path in the editor (a browser row tap or the
// relaunch restore). Any open of a file that is not the in-flight restore
// cancels the restore: its late stat/read results must not re-apply the
// snapshot's positions to a different file. Must be called on the logic
// goroutine.
func (l *Logic) openFile(path string) {
if l.restoreFile != "" && l.restoreFile != path {
l.abortRestore() // a different open cancels the in-flight one
}
// Discard find results for the previous file; the query is kept
// (see EditorState.findReset) and re-scanned against the new file.
TheState.Editor.findReset()
// Create chunked buffer for virtual scrolling
chunkSize := DefaultChunkSize
cb := NewChunkedBuffer(path, chunkSize, l.mockFS, "")
cb.SetWorkerPool(l.workerPool)
TheState.Editor.ChunkedBuffer = cb
// Dispatch stat task to get file size
l.workerPool.Dispatch(pool.NewStatFileTask(path, l.mockFS))
}
// emitFrame computes the current frame, records a profiler probe (if enabled),
// and hands it to the main goroutine. Centralizing emission here ensures the
// in-app profiler (PerfRecord) sees every frame exactly once, on the owner
// goroutine. Must be called on the logic goroutine.
func (l *Logic) emitFrame() {
// Relaunch snapshot (spec §7): persist when the state has changed and
// the rate limit elapsed (tiny JSON file, see session.go).
l.saveSessionIfChanged()
elems := l.state.layout(l.browserManager)
now := time.Now()
if PerfRecord != nil {
@@ -518,7 +572,28 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
// Fallback: populate the deprecated Buffer field
l.state.Editor.Buffer = string(content)
}
// Relaunch restoration (spec §7): the content is in memory, so
// land the snapshot's cursor/selection (clamped to the file)
// and re-scan the restored find query. Path-guarded: a read
// result for a file the user has since replaced must not apply
// the snapshot to the replacement's buffer.
if res.FilePath == l.state.Editor.Filename && l.restoreFile == res.FilePath {
l.applyRestorePositions(len(content))
l.maybeApplyRestoreScroll()
l.abortRestore()
// Re-scan the restored query only when the bar was open:
// with the bar closed, the result would be dropped (the apply
// gate requires Visible) and Scanning would stay stuck true;
// findShow re-scans on the next open instead.
if f := &l.state.Editor.Find; f.Visible && f.Query != "" && !f.Scanning {
l.state.Editor.findDispatchScan()
}
}
}
} else if res.FilePath == l.restoreFile {
// The restored file's content could not be read: drop the
// restore (the editor keeps the empty file view it has).
l.abortRestore()
}
} else if res.TaskType == pool.TypeReadChunk {
// In-range files load fully via SetContent, so this is only a fallback.
@@ -539,9 +614,22 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
} else if res.TaskType == pool.TypeStatFile {
if res.Success {
if stat, ok := res.Data.(*pool.FileStat); ok {
// Relaunch restoration (spec §7): the file exists, so land
// the snapshot's find state now (the cursor/selection land
// with the content, the query re-scans against the new file).
if res.FilePath == l.restoreFile && l.restoreFile != "" {
f := &l.state.Editor.Find
f.Query = l.session.FindQuery
f.Visible = l.session.FindVisible
f.RestoreMatch = l.session.FindCurByte
f.Restoring = l.session.FindVisible
}
// Size guard: refuse to edit files above the limit. The browser can
// still list them; the editor shows a "too large to edit" notice.
if stat.Size > MaxEditableFileSize {
if l.restoreFile != "" {
l.abortRestore() // no content load follows; nothing lands
}
l.state.Editor.TooLarge = true
l.state.Editor.TooLargeSize = stat.Size
log.Printf("Logic: %s is %d bytes, exceeds the %d-byte edit limit", stat.Path, stat.Size, MaxEditableFileSize)
@@ -555,6 +643,11 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
l.workerPool.Dispatch(pool.NewBuildLineIndexTask(stat.Path, l.mockFS))
}
}
} else if res.FilePath == l.restoreFile && l.restoreFile != "" {
// The restored file is gone (deleted/moved since the last
// session): fall back to the browser instead of showing an
// empty editor.
l.abandonRestore()
}
} else if res.TaskType == pool.TypeBuildLineIndex {
if res.Success {
@@ -768,5 +861,11 @@ func (l *Logic) Shutdown() {
l.Done()
l.WaitForExit()
l.FlushAll()
// Final relaunch snapshot (spec §7): after exit the caller owns the
// state single-threaded, like FlushAll above, so one unconditional
// save makes the file exact for the next launch.
if l.sessionSaver != nil {
l.sessionSaver(l.SnapshotSession())
}
l.workerPool.Stop()
}
+38 -5
View File
@@ -55,6 +55,16 @@ type FindState struct {
// and the logic storing it (a round-trip away), wiping the input while
// typing.
ClearSeq int
// --- Relaunch restoration (spec §7, see session.go) ---
// Restoring is set while a restored session's find scan is in flight:
// its first result selects the restored current match (RestoreMatch) but
// does NOT scroll — the viewport stays where the restored scroll offset
// put it. applySearchResult consumes both; findReset drops them.
Restoring bool
// RestoreMatch is the byte offset of the pre-launch current find match
// (the snapshot's FindCurByte); -1 = none.
RestoreMatch int
}
// ToggleFind opens the find bar (or closes it when open). It is the tap
@@ -205,18 +215,41 @@ func (e *EditorState) applySearchResult(res pool.Result) {
f.Cur = i
}
}
// Relaunch restore: select the pre-launch current match by byte
// offset (spec §7) — the one containing the byte, else the first
// match after it, else the last (its text may have been edited
// away, so a fallback is always defined).
if f.Cur < 0 && f.RestoreMatch >= 0 {
i := sort.Search(len(f.Matches), func(i int) bool {
return f.Matches[i][0] > f.RestoreMatch
})
switch {
case i > 0 && f.Matches[i-1][1] > f.RestoreMatch:
f.Cur = i - 1
case i < len(f.Matches):
f.Cur = i
default:
f.Cur = len(f.Matches) - 1
}
}
if f.Cur < 0 {
f.Cur = 0
}
// The first discovery of matches (matches went 0 -> N) selects and
// scrolls the view to the current match; while the user keeps
// typing, results update in place and the view moves only on
// explicit next/prev.
// The first discovery of matches (matches went 0 -> N) selects the
// current match and scrolls the view to it — except during a
// relaunch restore (Restoring), where the viewport must stay where
// the restored scroll offset put it. While the user keeps typing,
// results update in place and the view moves only on explicit
// next/prev.
if wasEmpty {
SetSelection(f.Matches[f.Cur][0], f.Matches[f.Cur][1])
scrollToFindMatch(f.Matches[f.Cur][0])
if !f.Restoring {
scrollToFindMatch(f.Matches[f.Cur][0])
}
}
}
f.Restoring = false
f.RestoreMatch = -1
}
// findStep selects the next (dir>0) or previous (dir<0) match, wrapping
+219
View File
@@ -0,0 +1,219 @@
// State restoration on relaunch (spec §7).
//
// The restorable state is a small snapshot (SessionState) the logic
// goroutine takes on demand: the last opened file, the cursor byte offset,
// the editor scroll offset, the live selection, and the find bar (query,
// open/closed, current match). The search RESULTS themselves are not part
// of the snapshot: on relaunch they are regenerated by re-scanning the
// restored query, and the current match is re-selected by byte offset
// (FindState.Restoring/RestoreMatch), without re-scrolling the restored
// viewport.
//
// Ownership (architecture.md §1): the logic goroutine owns the snapshot
// content. The cmd layer (cmd/pad/main.go) owns the tiny JSON file that
// stores it and registers the writer (Logic.SetSessionSaver); the logic
// calls it rate-limited from emitFrame and unconditionally at Shutdown, so
// the file is current even if the process is killed shortly after a change.
// On startup the cmd layer reads the file and hands it to Logic.BeginRestore
// (before Run, single-threaded), which re-opens the file and shows the
// editor immediately; the cursor/selection/find state land as the file's
// stat and content arrive (handleWorkerResult). A restore whose file is
// gone falls back to the browser page.
package editor
import (
"log"
"time"
"pad/internal/ui"
)
// sessionSaveInterval rate-limits the periodic session save. The file is
// tiny (a few hundred bytes), so one write a second at most is negligible.
const sessionSaveInterval = time.Second
// SessionState is the relaunch snapshot (see the file doc above). All
// positions are absolute file byte offsets; Scroll is in Dp. It is a plain
// comparable value (used with == for change detection).
type SessionState struct {
File string // last opened file ("" = nothing to restore)
Cursor int // cursor byte offset
Scroll float64 // editor scroll offset, Dp
SelStart int // selection start byte (-1 = no selection)
SelEnd int // selection end byte, exclusive
FindQuery string // find bar query ("" = none)
FindVisible bool // find bar was open
FindCurByte int // start byte of the current find match (-1 = none)
}
// SetSessionSaver registers the callback that persists snapshots (the cmd
// layer's JSON file writer). It is invoked from the logic goroutine:
// rate-limited from emitFrame, and unconditionally at Shutdown. The
// callback must be fast (a tiny file write).
func (l *Logic) SetSessionSaver(f func(SessionState)) {
l.sessionSaver = f
}
// SnapshotSession captures the current relaunch snapshot. The cursor is
// clamped to the file length; the selection and current find match are -1/
// -1 when inactive. Must be called on the logic goroutine (or after it has
// fully exited, as Shutdown does).
func (l *Logic) SnapshotSession() SessionState {
s := l.state
e := &s.Editor
cur := e.CursorPosition
if cb := e.ChunkedBuffer; cb != nil {
if fl := int(cb.FileLen()); cur > fl {
cur = fl
}
}
f := &e.Find
curByte := -1
if f.Cur >= 0 && f.Cur < len(f.Matches) {
curByte = f.Matches[f.Cur][0]
}
return SessionState{
File: e.Filename,
Cursor: cur,
Scroll: float64(s.ScrollOffset),
SelStart: e.SelectionStart,
SelEnd: e.SelectionEnd,
FindQuery: f.Query,
FindVisible: f.Visible,
FindCurByte: curByte,
}
}
// saveSessionIfChanged persists the snapshot when it differs from the last
// saved one and the rate limit has elapsed. Must be called on the logic
// goroutine (it is called from emitFrame).
//
// While a restore is still pending (l.session set, not yet landed or
// abandoned) saves are suppressed: the pre-land snapshot has zeroed
// cursor/selection, and persisting it would clobber the positions being
// restored if the process is killed during startup.
func (l *Logic) saveSessionIfChanged() {
if l.sessionSaver == nil {
return
}
if l.session.File != "" {
return
}
now := time.Now()
if now.Sub(l.lastSessionSave) < sessionSaveInterval {
return
}
s := l.SnapshotSession()
if s == l.lastSession {
return
}
l.sessionSaver(s)
l.lastSession = s
l.lastSessionSave = now
}
// BeginRestore prepares the state for relaunch restoration: the last file
// is re-opened and the editor page shown immediately. The cursor,
// selection, find state and scroll land as the file's stat/content arrive
// (handleWorkerResult); the scroll offset is applied now and clamped by
// EditorLayout once the line index sets the real MaxScroll. Must be called
// after NewLogic and before Run (the cmd layer does both before starting
// the logic goroutine), so it touches state single-threaded.
func (l *Logic) BeginRestore(s SessionState) {
if s.File == "" {
return
}
l.session = s
e := &l.state.Editor
e.Filename = s.File
e.CursorPosition = 0 // the restored cursor lands with the content
e.TooLarge = false
e.TooLargeSize = 0
e.SelectionAnchor = -1
e.SelectionStart = -1
e.SelectionEnd = -1
// Fresh per-file find state; the snapshot's query and visibility land
// with the stat (the file must exist first).
e.findReset()
// The scroll offset is armed, not applied: it must not be clamped by a
// layout that runs before the scale is known (see the Logic struct).
l.restoreScroll = ui.Dp(s.Scroll)
l.restoreScrollArmed = s.Scroll > 0
l.state.page = EditorPage
l.state.FocusedElementID = "editor_text"
l.state.justOpenedAt = time.Now()
l.emitFrame() // show the editor page now; the content loads async
}
// abortRestore ends a restore without landing it (the user opened another
// file, the read failed, or the file is too large): clears the pending
// snapshot so session saving resumes (see saveSessionIfChanged). The editor
// state itself is left alone. Must be called on the logic goroutine.
func (l *Logic) abortRestore() {
l.restoreFile = ""
l.restoreScrollArmed = false
l.session = SessionState{}
}
// maybeApplyRestoreScroll lands the armed restore scroll offset once the
// viewport unit is trustworthy (the first ScaleEvent has arrived), clamped
// to the current MaxScroll (the layout clamps again if the line index
// shrinks it later). Must be called on the logic goroutine.
func (l *Logic) maybeApplyRestoreScroll() {
if !l.restoreScrollArmed {
return
}
if !l.scaleSeen {
return
}
if l.restoreScroll > l.state.MaxScroll {
l.restoreScroll = l.state.MaxScroll
}
l.state.ScrollOffset = l.restoreScroll
l.restoreScrollArmed = false
}
// applyRestorePositions clamps the restored snapshot's cursor and selection
// to a file of n bytes and applies them. Must be called on the logic
// goroutine.
func (l *Logic) applyRestorePositions(n int) {
s := l.session
e := &l.state.Editor
if c := s.Cursor; c >= 0 {
if c > n {
c = n
}
e.CursorPosition = c
}
if ss, se := s.SelStart, s.SelEnd; ss >= 0 && se > ss {
if se > n {
se = n
}
if ss < se {
e.SelectionAnchor = ss
e.SelectionStart = ss
e.SelectionEnd = se
}
}
}
// abandonRestore gives up on the relaunch restore (the file's stat failed:
// it was deleted or moved since the last session): reset the editor and
// land on the browser page, as if nothing had been restored. Must be called
// on the logic goroutine.
func (l *Logic) abandonRestore() {
l.abortRestore()
e := &l.state.Editor
log.Printf("Logic: cannot restore %q; starting in the browser", e.Filename)
e.Filename = ""
e.ChunkedBuffer = nil
e.CursorPosition = 0
e.SelectionAnchor = -1
e.SelectionStart = -1
e.SelectionEnd = -1
e.Find = FindState{SettleByte: -1}
l.state.page = BrowserPage
l.state.ScrollOffset = 0
l.state.FocusedElementID = ""
}
+5
View File
@@ -260,6 +260,11 @@ func (s *State) SetFontScale(fs float32) {
s.fontScale = fs
}
// Page returns the current page (BrowserPage or EditorPage).
func (s *State) Page() Page {
return s.page
}
func (s *State) Scale() float32 {
return s.scale
}