github.com/xyproto/orbiton/v2@v2.65.12-0.20240516144430-e10a419274ec/monitor.go (about) 1 package main 2 3 import ( 4 "github.com/fsnotify/fsnotify" 5 "github.com/xyproto/vt100" 6 ) 7 8 // StartMonitoring will start monitoring the current file for changes 9 // and reload the file whenever it changes. 10 func (e *Editor) StartMonitoring(c *vt100.Canvas, tty *vt100.TTY, status *StatusBar) { 11 watcher, err := fsnotify.NewWatcher() 12 if err != nil { 13 status.Clear(c) 14 status.SetError(err) 15 status.Show(c, e) 16 } 17 defer watcher.Close() 18 19 absFilename, err := e.AbsFilename() 20 if err != nil { 21 status.ClearAll(c) 22 status.SetError(err) 23 status.Show(c, e) 24 } 25 26 go func() { 27 28 for { 29 select { 30 case event, ok := <-watcher.Events: 31 if !ok { 32 return 33 } 34 35 // Handle the received event, for the currently monitored file(s) 36 if event.Has(fsnotify.Write) { // is it a write event? 37 status.Clear(c) 38 status.SetMessage("Reloading " + e.filename) 39 status.Show(c, e) 40 41 if err := e.Reload(c, tty, status, nil); err != nil { 42 status.ClearAll(c) 43 status.SetError(err) 44 status.Show(c, e) 45 } 46 47 const drawLines = true 48 e.FullResetRedraw(c, status, drawLines) 49 e.redraw = true 50 e.redrawCursor = true 51 } 52 53 case err, ok := <-watcher.Errors: 54 if !ok { 55 return 56 } 57 status.ClearAll(c) 58 status.SetError(err) 59 status.Show(c, e) 60 } 61 } 62 63 }() 64 65 _ = watcher.Add(absFilename) 66 }