package editor import ( "log" "os" "path/filepath" "strconv" "strings" "sync" "time" "pad/internal/browser" "pad/internal/io/pool" "pad/internal/io/pool/mock" "pad/internal/io/pool/types" "pad/internal/ui" ) // ConfigEvent represents a window configuration change (resize, orientation). // PixelWidth and PixelHeight are the raw pixel dimensions from Gio. type ConfigEvent struct { PixelWidth int PixelHeight int } // ScaleEvent represents a metric change (HiDPI scale factor). type ScaleEvent struct { Scale float32 } // ConfigUpdate is a common interface for all configuration updates. // Both ConfigEvent and ScaleEvent implement this interface. type ConfigUpdate interface { apply(*State) } func (e ConfigEvent) apply(s *State) { s.PixelWidth = e.PixelWidth s.PixelHeight = e.PixelHeight } func (e ScaleEvent) apply(s *State) { s.SetScale(e.Scale) } // ResultEvent represents a completed async task result. type ResultEvent struct { // Future: add result fields here } // Logic runs the logic goroutine and provides channels for communication. // // Single-owner invariant (architecture.md §1): the logic goroutine is the // sole reader/writer of l.state. Every other goroutine talks to it through // the channels below. The only exception is Inspect, a test-only request // channel whose fn still executes on the owner. type Logic struct { state *State browserManager *browser.BrowserManager configChan chan ConfigUpdate frameChan chan Frame // frames carry the view-state snapshot inputChan chan []ui.InputEvent layoutChan chan ui.GlyphLayout resultChan chan ResultEvent searchQueryChan chan string openFileChan chan string retryChan chan string // auto-save retries autosaveChan chan struct{} // auto-save debounce ticks (timer -> owner) inspectChan chan *inspectReq workerPool *pool.WorkerPool mockFS pool.FileSystem done chan struct{} exitWg sync.WaitGroup 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 } // NewLogic creates a new Logic instance, accepting an optional mockFS. func NewLogic(mfs pool.FileSystem, path string, openfunc func(string)) *Logic { state := NewState() TheState = state // The openfunc (e.g. the Android Termux bridge) is kept on TheState.open // as an optional external hook, but it is NOT the tap path: tapping a file // must open it in the in-app editor (doc/spec.md). The previous wiring set // ui.OpenFile = openfunc, which routed every tap through the external // bridge and bypassed the editor entirely. TheState.open = openfunc ui.OpenFile = func(path string) { OpenFile(path) } // Initialize mock filesystem if nil mockFS := mfs if mockFS == nil { mockFS = mock.NewFileSystem() populateMockFileSystem(mockFS) } // Initialize worker pool wp := pool.NewWorkerPool(8) // Increased worker pool size to 8 wp.Start() state.Browser.CurrentPath = path bm, _ := browser.NewBrowserManager(&state.Browser, wp, mockFS) TheLogic = &Logic{ state: state, browserManager: bm, configChan: make(chan ConfigUpdate), frameChan: make(chan Frame, 1), inputChan: make(chan []ui.InputEvent), layoutChan: make(chan ui.GlyphLayout), resultChan: make(chan ResultEvent), searchQueryChan: make(chan string), openFileChan: make(chan string), retryChan: make(chan string, 1), // Buffered channel autosaveChan: make(chan struct{}), inspectChan: make(chan *inspectReq), workerPool: wp, mockFS: mockFS, done: make(chan struct{}), } return TheLogic } // ConfigChan returns the unified config channel for the logic goroutine. // Accepts ConfigEvent (size) and ScaleEvent (scale factor). func (l *Logic) ConfigChan() chan<- ConfigUpdate { return l.configChan } // FrameChan returns the frame channel for the logic goroutine. func (l *Logic) FrameChan() <-chan Frame { return l.frameChan } // InputChan returns the input channel for the logic goroutine. func (l *Logic) InputChan() chan<- []ui.InputEvent { return l.inputChan } // LayoutChan returns the glyph layout feedback channel. func (l *Logic) LayoutChan() chan<- ui.GlyphLayout { return l.layoutChan } // ResultChan returns the result channel for the logic goroutine. func (l *Logic) ResultChan() chan<- ResultEvent { return l.resultChan } // SearchQueryChan returns the search query channel for the logic goroutine. // The main goroutine sends updated search text here when it detects a change. func (l *Logic) SearchQueryChan() chan<- string { return l.searchQueryChan } // ClipboardSetChan returns the channel the logic goroutine uses to request a // system clipboard write; the main goroutine executes the Gio clipboard op. func (l *Logic) ClipboardSetChan() <-chan string { return l.state.clipboardSetChan } // PasteReqChan returns the channel the logic goroutine uses to request the // system clipboard content for paste. func (l *Logic) PasteReqChan() <-chan struct{} { return l.state.pasteReqChan } // PasteChan delivers system clipboard content to the logic goroutine for // paste (tests use it to inject clipboard text without a main loop). func (l *Logic) PasteChan() chan<- string { return l.state.pasteChan } var TheState *State var TheLogic *Logic // Run runs the logic goroutine loop. func (l *Logic) Run() { l.exitWg.Add(1) defer l.exitWg.Done() // Dispatch initial directory index build on startup l.workerPool.Dispatch(pool.NewBuildIndexTask(l.state.Browser.CurrentPath, l.mockFS)) for { select { case <-l.done: return case update := <-l.configChan: update.apply(l.state) l.emitFrame() case layout := <-l.layoutChan: // Store the full GlyphLayout on editor state. // Derive LastLineY from it for scroll clamping. l.state.Editor.GlyphLayout = layout var derivedLastLineY ui.Dp if len(layout.Y) > 0 { derivedLastLineY = layout.Y[len(layout.Y)-1] } if derivedLastLineY != l.state.LastLineY { l.state.LastLineY = derivedLastLineY l.emitFrame() } case events := <-l.inputChan: for _, evt := range events { evt.Handler(evt.Data) } l.emitFrame() case query := <-l.searchQueryChan: if query != l.state.Browser.Query { l.state.Browser.Query = query if l.state.page == BrowserPage { browser.HandleSearch(&l.state.Browser, query) } } l.emitFrame() case path := <-l.openFileChan: // 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)) case filename := <-l.retryChan: log.Printf("Logic: Retrying save for %s", filename) if filename == l.state.Editor.Filename { // Reconstruct full content from chunked buffer for saving content, ok := l.fullContentBytes() if !ok { break } l.workerPool.DispatchNonBlocking( pool.NewWriteFileTask(filename, content, l.mockFS), ) } case <-l.autosaveChan: // Auto-save debounce tick. The timer goroutine only sent a token; // the owner reconstructs content and dispatches the write. l.saveTimer = nil if l.state.Editor.Filename == "" { break } content, ok := l.fullContentBytes() if !ok { break } l.workerPool.DispatchNonBlocking( pool.NewWriteFileTask(l.state.Editor.Filename, content, l.mockFS), ) case p := <-l.state.pasteChan: // Clipboard content arrived from the main goroutine: insert it // (replacing any live selection, per the selection-aware edit rule). HandlePaste(p) l.emitFrame() case req := <-l.inspectChan: // Test-only: fn runs on the owner, preserving single ownership. req.resp <- req.fn(l.state) case res := <-l.workerPool.ResultChan(): l.handleWorkerResult(res) case <-l.resultChan: l.emitFrame() case cmd := <-l.debugCmdC: l.applyDebugCmd(cmd) } } } // 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() { elems := l.state.layout(l.browserManager) now := time.Now() if PerfRecord != nil { var delta time.Duration if !l.lastEmit.IsZero() { delta = now.Sub(l.lastEmit) } l.lastEmit = now s := l.state rec := ProbeRecord{T: now, DeltaMs: float64(delta.Nanoseconds()) / 1e6, Page: pageName(s.page)} if s.page == EditorPage { rec.ScrollDP = float32(s.ScrollOffset) rec.MaxScrollDP = float32(s.MaxScroll) rec.VisStart = s.VisibleStart rec.VisEnd = s.VisibleEnd if cb := s.Editor.ChunkedBuffer; cb != nil { if li := cb.LineIndex; li != nil { rec.TotalLines = li.LineCount() } } } else { rec.ScrollDP = float32(s.Browser.ScrollOffset) } PerfRecord(rec) } l.frameChan <- l.frameOf(elems) } // EnableDebugCmdPoll starts a background poller (debug-only) that watches //