door.go 10 KB

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