diff --git a/view.go b/view.go index d0e357e5..9c7eb3eb 100644 --- a/view.go +++ b/view.go @@ -8,6 +8,7 @@ import ( "bytes" "io" "strings" + "sync" "unicode/utf8" "github.com/go-errors/errors" @@ -34,19 +35,27 @@ var ( // position. type View struct { name string - x0, y0, x1, y1 int // left top right bottom - ox, oy int // view offsets - cx, cy int // cursor position - rx, ry int // Read() offsets - wx, wy int // Write() offsets - lines [][]cell + x0, y0, x1, y1 int // left top right bottom + ox, oy int // view offsets + cx, cy int // cursor position + rx, ry int // Read() offsets + wx, wy int // Write() offsets + lines [][]cell // All the data - readBuffer []byte // used for storing unreaded bytes + // readBuffer is used for storing unread bytes + readBuffer []byte - tainted bool // true if the viewLines must be updated - viewLines []viewLine // internal representation of the view's buffer + // tained is true if the viewLines must be updated + tainted bool - ei *escapeInterpreter // used to decode ESC sequences on Write + // internal representation of the view's buffer + viewLines []viewLine + + // writeMutex protects locks the write process + writeMutex sync.Mutex + + // ei is used to decode ESC sequences on Write + ei *escapeInterpreter // Visible specifies whether the view is visible. Visible bool @@ -326,10 +335,10 @@ func (v *View) writeCells(x, y int, cells []cell) { // be called to clear the view's buffer. func (v *View) Write(p []byte) (n int, err error) { v.tainted = true - - // Fill with empty cells, if writing outside current view buffer + v.writeMutex.Lock() v.makeWriteable(v.wx, v.wy) v.writeRunes(bytes.Runes(p)) + v.writeMutex.Unlock() return len(p), nil } @@ -575,11 +584,14 @@ func (v *View) realPosition(vx, vy int) (x, y int, err error) { // Clear empties the view's internal buffer. // And resets reading and writing offsets. func (v *View) Clear() { + v.writeMutex.Lock() v.Rewind() v.tainted = true + v.ei.reset() v.lines = nil v.viewLines = nil v.clearRunes() + v.writeMutex.Unlock() } // clearRunes erases all the cells in the view.