door.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*
  2. Package door: a go implementation of a BBS door for linux and Windows
  3. that uses door32.sys, understand CP437 and unicode (if available),
  4. detects screen size, and supports TheDraw Fonts.
  5. import (
  6. "door"
  7. )
  8. int main() {
  9. d = door.Door{}
  10. d.Init() // Process commandline switches, initialize door, detect screen size.
  11. d.Write("Welcome to my awesome door, written in "+door.ColorText("BLINK BOLD WHITE")+"go"+door.Reset+"."+door.CRNL)
  12. d.Write("Press a key...")
  13. d.Key()
  14. d.Write(door.CRNL)
  15. }
  16. */
  17. package door
  18. import (
  19. "bytes"
  20. "flag"
  21. "fmt"
  22. "io"
  23. "log"
  24. "os"
  25. "path/filepath"
  26. "runtime/debug"
  27. "sync"
  28. "time"
  29. "golang.org/x/term"
  30. )
  31. // debugging output - enable here
  32. const DEBUG_DOOR bool = false
  33. // For debugging input reader routines.
  34. const DEBUG_INPUT bool = false
  35. const DEBUG_OUTPUT bool = false
  36. // See door_test.go for DEBUG test const
  37. // Right now these are strings. Should they be []byte ?
  38. const SavePos = "\x1b[s" // Save Cursor Position
  39. const RestorePos = "\x1b[u" // Restore Cursor Position
  40. // const CRNL = "\r\n" // BBS Line Ending
  41. const CRNL = "\n"
  42. const Clrscr = "\x1b[0m\x1b[2J\x1b[H" // Clear screen, home cursor
  43. const HideCursor = "\x1b[?25l" // Hide Cursor
  44. const ShowCursor = "\x1b[?25h" // Show Cursor
  45. const Reset string = "\x1b[0m" // ANSI Color Reset
  46. const CURSOR_POS = "\x1b[6n"
  47. const SAVE_POS = "\x1b[s"
  48. const RESTORE_POS = "\x1b[u"
  49. // Move these into the door structure, instead of having globals.
  50. var Unicode bool // Unicode support detected
  51. var CP437 bool // CP437 support detected
  52. var Full_CP437 bool // Full CP437 support detected (handles control codes properly)
  53. var Height int // Screen height detected
  54. var Width int // Screen width detected
  55. var Inactivity time.Duration = time.Duration(120) * time.Second // Inactivity timeout
  56. type ColorRender func(*bytes.Buffer, []byte)
  57. type Updater func(*bytes.Buffer)
  58. type UpdaterI interface {
  59. Update() bool
  60. }
  61. type OutputI interface {
  62. Output() []byte
  63. }
  64. type CursorPos struct {
  65. X, Y int
  66. }
  67. type Mouse struct {
  68. Button uint8
  69. X uint8
  70. Y uint8
  71. }
  72. type MouseMode int16
  73. const (
  74. Off MouseMode = 0
  75. X10 MouseMode = 9
  76. Normal MouseMode = 1000
  77. Button MouseMode = 1002
  78. AnyEvent MouseMode = 1003
  79. )
  80. type ReaderData struct {
  81. R rune
  82. Ex Extended
  83. Err error
  84. }
  85. /*
  86. type noCopy struct{}
  87. func (*noCopy) Lock() {}
  88. func (*noCopy) Unlock() {}
  89. noCopy noCopy
  90. */
  91. type BaseWriter struct {
  92. Closed bool
  93. TranslateToUnicode bool
  94. uniBuffer *bytes.Buffer
  95. ansiCSI bool
  96. ansiCode []byte
  97. LastSavedColor []int
  98. }
  99. type Door struct {
  100. Config DropfileConfig
  101. READFD int
  102. WRITEFD int
  103. Writer OSWriter // OS specific writer
  104. writeMutex sync.Mutex // Writer lock
  105. nlBuffer *bytes.Buffer // NewLines Translate buffer
  106. TranslateNL bool // Translate NewLines?
  107. ansiCSI bool // ANSI CSI
  108. ansiCode []byte // ANSI CSI Codes
  109. Disconnected bool // Has User disconnected/Hung up?
  110. TimeOut time.Time // Fixed point in time, when time expires
  111. StartTime time.Time // Time when User started door
  112. Pushback FIFOBuffer[rune] // Key buffer
  113. LastColor []int // Track the last color sent for restore color
  114. ReaderClosed bool // Reader close
  115. readerChannel chan ReaderData // Reading from the User
  116. readerMutex sync.Mutex // Reader close mutex
  117. ReaderEnd bool // Reader should end
  118. LastMouse []Mouse // Store Mouse information
  119. LastCursor []CursorPos // Store Cursor pos information
  120. mcMutex sync.Mutex // Lock for LastMouse, LastCursor
  121. wg sync.WaitGroup // Reader finished
  122. tio_default *term.State // Terminal State to restore
  123. Mouse MouseMode // Mouse mode enabled
  124. }
  125. /*
  126. Enable mouse support
  127. 9 : X10 Support
  128. 1000: Normal
  129. 1002: Button Event
  130. 1003: Any-Event
  131. */
  132. func (d *Door) EnableMouse(mode MouseMode) {
  133. if d.Mouse != Off {
  134. // Disable current mode first
  135. d.DisableMouse()
  136. }
  137. d.Mouse = mode
  138. if d.Mouse != Off {
  139. var output []byte
  140. output = fmt.Appendf(output, "\x1b[?%dh", int(d.Mouse))
  141. d.Write(output)
  142. // d.Write(fmt.Sprintf("\x1b[?%dh", int(d.Mouse)))
  143. }
  144. }
  145. // Disable mouse support
  146. func (d *Door) DisableMouse() {
  147. if d.Mouse != Off {
  148. var output []byte
  149. output = fmt.Appendf(output, "\x1b[?%dl", int(d.Mouse))
  150. d.Write(output)
  151. // d.Write(fmt.Sprintf("\x1b[?%dl", int(d.Mouse)))
  152. }
  153. d.Mouse = Off
  154. }
  155. func (d *Door) AddMouse(mouse Mouse) {
  156. d.mcMutex.Lock()
  157. defer d.mcMutex.Unlock()
  158. d.LastMouse = append(d.LastMouse, mouse)
  159. }
  160. var WantGetMouse bool
  161. func (d *Door) GetMouse() (Mouse, bool) {
  162. if WantGetMouse {
  163. WantGetMouse = false
  164. } else {
  165. log.Println("GetMouse called, but WantGetMouse not true.")
  166. }
  167. d.mcMutex.Lock()
  168. defer d.mcMutex.Unlock()
  169. return ArrayDelete(&d.LastMouse, 0)
  170. }
  171. func (d *Door) GetCursorPos() (CursorPos, bool) {
  172. d.mcMutex.Lock()
  173. if DEBUG_DOOR {
  174. log.Printf("LastCursor %p/%p %d, %d\n", d, &d.LastCursor, len(d.LastCursor), cap(d.LastCursor))
  175. }
  176. defer d.mcMutex.Unlock()
  177. if DEBUG_DOOR {
  178. log.Printf("LastCursor: %#v\n", d.LastCursor)
  179. }
  180. return ArrayDelete(&d.LastCursor, 0)
  181. }
  182. func (d *Door) AddCursorPos(cursor CursorPos) {
  183. d.mcMutex.Lock()
  184. if DEBUG_DOOR {
  185. log.Printf("LastCursor %p/%p %d, %d\n", d, &d.LastCursor, len(d.LastCursor), cap(d.LastCursor))
  186. }
  187. defer d.mcMutex.Unlock()
  188. d.LastCursor = append(d.LastCursor, cursor)
  189. if DEBUG_DOOR {
  190. log.Printf("LastCursor now %d, %d\n", len(d.LastCursor), cap(d.LastCursor))
  191. log.Printf("AddCursor: %#v\n", d.LastCursor)
  192. }
  193. }
  194. func (d *Door) ClearMouseCursor() {
  195. d.mcMutex.Lock()
  196. defer d.mcMutex.Unlock()
  197. if DEBUG_DOOR {
  198. log.Println("ClearMouseCursor")
  199. }
  200. d.LastMouse = make([]Mouse, 0, 2)
  201. d.LastCursor = make([]CursorPos, 0, 3)
  202. }
  203. // Return the amount of time left as time.Duration
  204. func (d *Door) TimeLeft() time.Duration {
  205. return time.Until(d.TimeOut)
  206. }
  207. func (d *Door) TimeUsed() time.Duration {
  208. return time.Since(d.StartTime)
  209. }
  210. func (d *Door) Disconnect() bool {
  211. return d.Disconnected // atomic.LoadInt32(&d.Disconnected) != 0
  212. }
  213. func (d *Door) Detect() bool {
  214. // detect is destructive ... make it non-destructive
  215. // destructive: clears/trashes the screen.
  216. var detect bytes.Buffer
  217. detect.WriteString("\r\x03\x04" + CURSOR_POS + "\b \b\b \b" +
  218. "\r\u2615" + CURSOR_POS + "\b \b\b \b\b \b" +
  219. SAVE_POS + "\x1b[999C\x1b[999B" + CURSOR_POS + RESTORE_POS)
  220. // hot beverage is 3 bytes long -- need 3 "\b \b" to erase.
  221. d.Write(detect.Bytes())
  222. var info []CursorPos = make([]CursorPos, 0, 3)
  223. var done bool
  224. for !done {
  225. _, ex, err := d.WaitKey(time.Second)
  226. log.Println("WaitKey:", ex, err)
  227. if ex == CURSOR {
  228. cursor, ok := d.GetCursorPos()
  229. if ok {
  230. info = append(info, cursor)
  231. if len(info) == 3 {
  232. done = true
  233. }
  234. }
  235. }
  236. if err != nil {
  237. done = true
  238. }
  239. }
  240. if len(info) != 3 {
  241. // Detection FAILED.
  242. log.Println("Detect FAILED:", info)
  243. return false
  244. }
  245. // Ok! Let's see what we've got...
  246. var valid bool
  247. // Where did I get these numbers from?
  248. // linux term (telnet/ssh) [0].X = 1, [1].X = 3
  249. // VS Code terminal: 1, 3
  250. // https://docs.python.org/3/library/unicodedata.html
  251. // \u2615 is a fullwidth (2 char) unicode symbol!
  252. // SO, [1].X == 3 // and not 2.
  253. // syncterm [0].X = 3, [1].X = 4
  254. // Magiterm [0].X = 3, [1].X = 4
  255. // cp437 + telnet [0].X = 1, [1].X = 4 FullCP437 = False
  256. // ^ Fails FullCP437 test - characters codes ignored.
  257. // cp437plus + telnet 3, 4. (Has FullCP437 support.)
  258. // if (info[0].X == 1 || info[0].X == 3) &&
  259. // (info[1].X == 2 || info[1].X == 3) {
  260. // Breakdown by detected type:
  261. // Unicode \x03 \x04 (control codes ignored)
  262. // Unicode \u2615 = fullwidth takes up 2 characters
  263. // CP437 \x03 \x04 Hearts Diamonds Symbols 2 characters
  264. // ^ Only works for FullCP437
  265. // CP437 \u2615 = b'\xe2\x98\x95' 3 bytes
  266. // So info[1].X = 4
  267. if info[0].X == 1 && info[1].X == 3 {
  268. Unicode = true
  269. valid = true
  270. } else {
  271. // info[1].X = 4
  272. Unicode = false
  273. CP437 = true
  274. valid = true
  275. }
  276. if info[0].X == 3 {
  277. Full_CP437 = true
  278. }
  279. if !valid {
  280. log.Println("Detect FAILED (not valid):", info)
  281. return false
  282. }
  283. Width, Height = info[2].X, info[2].Y
  284. // Putty doesn't seem to restoring the cursor position (when detecting).
  285. d.Write(Goto(1, info[0].Y))
  286. log.Printf("Unicode: %t, CP437: %t, Full %t, Screen %v\n", Unicode, CP437, Full_CP437, info[2])
  287. return true
  288. }
  289. // Initialize door framework. Parse commandline, read dropfile,
  290. // detect terminal capabilities.
  291. func (d *Door) Init(doorname string) {
  292. var dropfile string
  293. d.Pushback = NewFIFOBuffer[rune](5)
  294. // Get path to binary, and chdir to it.
  295. var binaryPath string
  296. binaryPath, _ = os.Executable()
  297. binaryPath = filepath.Dir(binaryPath)
  298. _ = os.Chdir(binaryPath)
  299. flag.StringVar(&dropfile, "d", "", "Path to dropfile")
  300. flag.Parse()
  301. if len(dropfile) == 0 {
  302. flag.PrintDefaults()
  303. os.Exit(2)
  304. }
  305. d.ReadDropfile(dropfile)
  306. if d.Config.Comm_type == 0 {
  307. // RAW MODE
  308. d.tio_default, _ = term.MakeRaw(d.READFD)
  309. }
  310. // Logfile will be doorname - node #
  311. var logfilename string = fmt.Sprintf("%s-%d.log", doorname, d.Config.Node)
  312. var logf *os.File
  313. var err error
  314. logf, err = os.OpenFile(logfilename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
  315. if err != nil {
  316. log.Panicf("Error creating log file %s: %v", logfilename, err)
  317. }
  318. // Set logging output to logfilename.
  319. log.SetOutput(logf)
  320. log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
  321. log.Printf("Loading dropfile %s\n", dropfile)
  322. log.Printf("BBS %s, User %s / Handle %s / File %d\n", d.Config.BBSID, d.Config.Real_name, d.Config.Handle, d.Config.Comm_handle)
  323. d.readerChannel = make(chan ReaderData, 16) // was 8 ?
  324. d.ClearMouseCursor()
  325. d.setupChannels()
  326. d.Writer.Init(d)
  327. d.Detect()
  328. if Unicode {
  329. BOXES = &BOXES_UNICODE
  330. BARS = &BARS_UNICODE
  331. } else {
  332. BOXES = &BOXES_CP437
  333. BARS = &BARS_CP437
  334. }
  335. }
  336. func (d *Door) Close() {
  337. defer func() {
  338. if err := recover(); err != nil {
  339. log.Println("door.Close FAILURE:", err)
  340. // This displays stack trace stderr
  341. debug.PrintStack()
  342. }
  343. }()
  344. d.DisableMouse()
  345. // This disables anymore Writes.
  346. d.Writer.Stop()
  347. /*
  348. d.writerMutex.Lock()
  349. d.WriterClosed = true
  350. d.writerMutex.Unlock()
  351. */
  352. // I need a way to shutdown the reader.
  353. // This isn't shutting it down, we hang on d.wg.Wait()
  354. d.readerMutex.Lock()
  355. // d.ReaderClosed = true
  356. d.ReaderEnd = true
  357. d.readerMutex.Unlock()
  358. // log.Println("Closing...")
  359. // close(d.writerChannel)
  360. log.Println("wg.Wait()")
  361. d.wg.Wait()
  362. log.Println("Closed.")
  363. if d.Config.Comm_type == 0 {
  364. // Linux - restore console settings to default/original.
  365. term.Restore(d.READFD, d.tio_default)
  366. }
  367. }
  368. // Goto X, Y - Position the cursor using ANSI Escape Codes
  369. //
  370. // Example:
  371. //
  372. // d.Write(door.Goto(1, 5) + "Now at X=1, Y=5.")
  373. func Goto(x int, y int) []byte {
  374. var output []byte
  375. output = fmt.Appendf(output, "\x1b[%d;%dH", y, x)
  376. return output
  377. }
  378. // No change in benchmarks using this ...
  379. func GotoW(x, y int, w io.Writer) {
  380. fmt.Fprintf(w, "\x1b[%d;%dH", y, x)
  381. }
  382. // Why doesn't func Goto2 work? I get wrong answers / tests fail.
  383. // If this is called from a go routine .. while another goto is being
  384. // done... hell might brake loose.
  385. var gotobuff *bytes.Buffer
  386. func Goto2(x int, y int) []byte {
  387. if gotobuff == nil {
  388. gotobuff = &bytes.Buffer{}
  389. }
  390. gotobuff.Reset()
  391. fmt.Fprintf(gotobuff, "\x1b[%d;%dH", y, x)
  392. return gotobuff.Bytes()
  393. }
  394. func GotoS(x int, y int) string {
  395. return fmt.Sprintf("\x1b[%d;%dH", y, x)
  396. }
  397. func (d *Door) setupChannels() {
  398. d.wg.Add(1)
  399. go Reader(d)
  400. }