write_linux.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package door
  2. import (
  3. "log"
  4. "strings"
  5. "syscall"
  6. )
  7. // https://go101.org/article/channel-closing.html
  8. func Writer(d *Door) {
  9. var handle int = d.Config.Comm_handle
  10. log.Println("Writer")
  11. defer d.wg.Done()
  12. var Closed bool = false
  13. for output := range d.writerChannel {
  14. // log.Println("output")
  15. /* Handle cases where we're updating a portion of the screen.
  16. When we SavePos, also save/restore the last color set.
  17. */
  18. if output == "" {
  19. Closed = true
  20. continue
  21. }
  22. if Closed {
  23. log.Println("ignoring write output.")
  24. continue
  25. }
  26. if strings.HasSuffix(output, RestorePos) {
  27. output += Color(d.LastColor...)
  28. } else {
  29. d.UpdateLastColor(output, &d.LastColor)
  30. }
  31. // log.Println("write output")
  32. buffer := []byte(output)
  33. n, err := syscall.Write(handle, buffer)
  34. if (err != nil) || (n != len(buffer)) {
  35. log.Println("closeChannel")
  36. Closed = true
  37. d.writerMutex.Lock()
  38. if !d.WriterClosed {
  39. d.WriterClosed = true
  40. // close(d.writerChannel)
  41. }
  42. d.writerMutex.Unlock()
  43. }
  44. }
  45. log.Println("closeChannel")
  46. d.writerMutex.Lock()
  47. if !d.WriterClosed {
  48. // Safe from data races, writerChannel unbuffered
  49. d.WriterClosed = true
  50. }
  51. d.writerMutex.Unlock()
  52. log.Println("~Writer")
  53. }