Files
openchamber-android-native/third_party/mygo/document_watch.go
T
OpenChamber 6c0ee61750 feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
2026-11-18 13:22:59 +08:00

243 lines
5.9 KiB
Go

package mygo
import (
"context"
"os"
"path/filepath"
"slices"
"sync"
"time"
)
// Documents notice what other apps do to their files: one WatchFiles per
// open document's file, and a look when a document's window is focused,
// since watches miss changes (VS Code and Notepad++ look then too). An
// unedited document reads its file again, an edited one is in conflict
// and asks at its next save, a file renamed in its directory is followed,
// and a deleted one is written again by the next save. A watch of the
// file rather than of its directory costs the same whatever else the
// directory holds: a directory is one FSEvents stream on macOS, whatever
// is in it.
var docWatches struct {
sync.Mutex
files map[string]*docFileWatch
}
type docFileWatch struct {
refs int
cancel context.CancelFunc
}
// watch watches b's file, after it opened or moved.
func (b *docBase) watch() {
b.mu.Lock()
path := ""
if !b.closed {
path = b.path
}
old := b.watched
b.watched = path
b.mu.Unlock()
if path == old {
return
}
docWatches.Lock()
defer docWatches.Unlock()
if old != "" {
if w := docWatches.files[old]; w != nil {
if w.refs--; w.refs == 0 {
w.cancel()
delete(docWatches.files, old)
}
}
}
if path == "" {
return
}
if w := docWatches.files[path]; w != nil {
w.refs++
return
}
ctx, cancel := context.WithCancel(context.Background())
if docWatches.files == nil {
docWatches.files = map[string]*docFileWatch{}
}
docWatches.files[path] = &docFileWatch{refs: 1, cancel: cancel}
go watchDocumentFile(ctx, path)
}
// watchDocumentFile follows the changes of the file at path until ctx is
// done, or its directory goes away.
func watchDocumentFile(ctx context.Context, path string) {
w, err := WatchFiles(ctx, path, FileWatchOptions{Debounce: 100 * time.Millisecond})
if err != nil {
// The file may have gone before the watch started, renamed after
// the document read it: nothing would look for it until a focus.
for _, b := range documentsAt(path) {
go b.checkDisk()
}
return
}
defer w.Close()
// What changed before the watch started, as after a rename.
for _, b := range documentsAt(path) {
go b.checkDisk()
}
for {
r := w.next(ctx)
if r.err != nil {
return
}
// The file that went away, by what it was when the watch last saw
// it, as a look now may come after the next rename, or else as the
// document last read or wrote it: the watch looks once changes
// settle, so a file that replaced the one it saw, which the
// document read (when the watch started, or its window was
// focused), can be renamed before the watch ever saw it.
docs := documentsAt(path)
moved := ""
if r.events[len(r.events)-1].Op == FileRemove {
ids := []fileWatchGone{r.gone}
for _, b := range docs {
// A document in conflict read a file another replaced,
// whose identity a new file may have taken since.
b.mu.Lock()
if !b.conflict && !b.deleted {
ids = append(ids, b.stamp.file)
}
b.mu.Unlock()
}
moved = findRenamed(filepath.Dir(w.Root()), ids)
}
for _, b := range docs {
if moved != "" {
b.moved(moved)
} else {
go b.checkDisk()
}
}
if moved != "" {
return // moved watches the new path
}
}
}
// findRenamed returns the path of the file in dir that one of ids
// identifies, the first of ids that one does, or "".
func findRenamed(dir string, ids []fileWatchGone) string {
if !slices.ContainsFunc(ids, func(id fileWatchGone) bool { return id.ok }) {
return ""
}
entries, err := os.ReadDir(dir)
if err != nil {
return ""
}
found, at := "", len(ids)
for _, entry := range entries {
info, err := entry.Info()
if err != nil {
continue
}
id := fileWatchEntryOf(info).id
for i, want := range ids[:at] {
if want.ok && want.id == id {
found, at = filepath.Join(dir, entry.Name()), i
break
}
}
}
return found
}
// documentsAt returns the open documents of the file at path.
func documentsAt(path string) []*docBase {
var at []*docBase
for _, b := range allDocuments() {
if b.Path() == path {
at = append(at, b)
}
}
return at
}
// checkDisk compares b's file with what b last read or wrote. A file gone
// from its path is looked for in its directory by what b read, as the
// watch does: this look can come between a rename and the watch's batch
// (the look when the watch started, or a window focused), and the watch
// doesn't look for what a document it finds deleted read.
func (b *docBase) checkDisk() {
b.io.Lock()
b.mu.Lock()
path, known, edited, closed := b.path, b.stamp, b.edited, b.closed
wasDeleted, conflict := b.deleted, b.conflict
b.mu.Unlock()
if path == "" || closed {
b.io.Unlock()
return
}
now, exists, err := statStamp(path)
if err == nil && !exists && !wasDeleted {
// Network shares report files gone that are not (VS Code).
time.Sleep(100 * time.Millisecond)
now, exists, err = statStamp(path)
}
if err != nil {
b.io.Unlock()
return
}
switch {
case !exists:
moved := ""
if !wasDeleted && !conflict {
moved = findRenamed(filepath.Dir(path), []fileWatchGone{known.file})
}
b.mu.Lock()
// The watch followed the file while this looked.
current := b.path == path
changed := current && moved == "" && !b.deleted
if changed {
b.deleted = true
}
b.mu.Unlock()
b.io.Unlock()
if current && moved != "" {
b.moved(moved)
} else if changed {
b.notify()
}
case now.same(known) && !wasDeleted:
readOnly := !fileWritable(path)
b.mu.Lock()
changed := b.readOnly != readOnly
b.readOnly = readOnly
b.mu.Unlock()
b.io.Unlock()
if changed {
b.notify()
}
case !edited:
b.io.Unlock()
_ = b.reload(path)
default:
b.mu.Lock()
changed := !b.conflict || b.deleted
b.conflict, b.deleted = true, false
b.mu.Unlock()
b.io.Unlock()
if changed {
b.notify()
}
}
}
// moved follows b's file, which another app renamed to path.
func (b *docBase) moved(path string) {
b.mu.Lock()
b.path = path
b.mu.Unlock()
addRecent(path)
b.watch()
b.notify()
}