| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416 | /*Package door: a go implementation of a BBS door for linux and Windowsthat uses door32.sys, understand CP437 and unicode (if available),detects screen size, and supports TheDraw Fonts.	    import (				"door"			)		int main() {			d = door.Door{}			d.Init() // Process commandline switches, initialize door, detect screen size.			d.Write("Welcome to my awesome door, written in "+door.ColorText("BLINK BOLD WHITE")+"go"+door.Reset+"."+door.CRNL)			d.Write("Press a key...")			d.Key()			d.Write(door.CRNL)		}*/package doorimport (	"flag"	"fmt"	"log"	"os"	"path/filepath"	"runtime/debug"	"sync"	"time"	"golang.org/x/term")// debugging output - enable hereconst DEBUG_DOOR bool = false// For debugging input reader routines.const DEBUG_INPUT bool = falseconst DEBUG_OUTPUT bool = false// See door_test.go for DEBUG test constconst SavePos = "\x1b[s"              // Save Cursor Positionconst RestorePos = "\x1b[u"           // Restore Cursor Positionconst CRNL = "\r\n"                   // BBS Line Endingconst Clrscr = "\x1b[0m\x1b[2J\x1b[H" // Clear screen, home cursorconst HideCursor = "\x1b[?25l"        // Hide Cursorconst ShowCursor = "\x1b[?25h"        // Show Cursorconst Reset string = "\x1b[0m"        // ANSI Color Resetconst CURSOR_POS = "\x1b[6n"const SAVE_POS = "\x1b[s"const RESTORE_POS = "\x1b[u"// Move these into the door structure, instead of having globals.var Unicode bool                                                // Unicode support detectedvar CP437 bool                                                  // CP437 support detectedvar Full_CP437 bool                                             // Full CP437 support detected (handles control codes properly)var Height int                                                  // Screen height detectedvar Width int                                                   // Screen width detectedvar Inactivity time.Duration = time.Duration(120) * time.Second // Inactivity timeouttype ColorRender func(string) stringtype Updater func() stringtype CursorPos struct {	X, Y int}type Mouse struct {	Button int8	X      int8	Y      int8}type MouseMode intconst (	Off      MouseMode = 0	X10      MouseMode = 9	Normal   MouseMode = 1000	Button   MouseMode = 1002	AnyEvent MouseMode = 1003)type ReaderData struct {	R   rune	Ex  Extended	Err error}/*type noCopy struct{}func (*noCopy) Lock()   {}func (*noCopy) Unlock() {}	noCopy         noCopy*/type Door struct {	Config         DropfileConfig	READFD         int	WRITEFD        int	Disconnected   bool             // int32         // atomic bool      // Has User disconnected/Hung up?	TimeOut        time.Time        // Fixed point in time, when time expires	StartTime      time.Time        // Time when User started door	Pushback       FIFOBuffer[rune] // Key buffer	LastColor      []int            // Track the last color sent for restore color	ReaderClosed   bool             // Reader close	readerChannel  chan ReaderData  // Reading from the User	readerMutex    sync.Mutex       // Reader close mutex	ReaderCanClose bool             // We can close the reader (in tests)	WriterClosed   bool             // Writer closed	writerChannel  chan string      // Writing to the User	writerMutex    sync.RWMutex	LastMouse      []Mouse     // Store Mouse information	LastCursor     []CursorPos // Store Cursor pos information	mcMutex        sync.Mutex  // Lock for LastMouse, LastCursor	wg             sync.WaitGroup	tio_default    *term.State // Terminal State to restore	Mouse          MouseMode   // Mouse mode enabled}func (d *Door) SafeWriterClose() {	d.writerMutex.Lock()	defer d.writerMutex.Unlock()	if !d.WriterClosed {		d.WriterClosed = true		close(d.writerChannel)	}}func (d *Door) WriterIsClosed() bool {	d.writerMutex.RLock()	defer d.writerMutex.RUnlock()	return d.WriterClosed}/*Enable mouse support9 : X10 Support1000: Normal1002: Button Event1003: Any-Event*/func (d *Door) EnableMouse(mode MouseMode) {	if d.Mouse != Off {		// Disable current mode first		d.DisableMouse()	}	d.Mouse = mode	if d.Mouse != Off {		d.Write(fmt.Sprintf("\x1b[?%dh", int(d.Mouse)))	}}// Disable mouse supportfunc (d *Door) DisableMouse() {	if d.Mouse != Off {		d.Write(fmt.Sprintf("\x1b[?%dl", int(d.Mouse)))	}	d.Mouse = Off}func (d *Door) AddMouse(mouse Mouse) {	d.mcMutex.Lock()	defer d.mcMutex.Unlock()	d.LastMouse = append(d.LastMouse, mouse)}var WantGetMouse boolfunc (d *Door) GetMouse() (Mouse, bool) {	if WantGetMouse {		WantGetMouse = false	} else {		log.Println("GetMouse called, but WantGetMouse not true.")	}	d.mcMutex.Lock()	defer d.mcMutex.Unlock()	return ArrayDelete(&d.LastMouse, 0)}func (d *Door) GetCursorPos() (CursorPos, bool) {	d.mcMutex.Lock()	if DEBUG_DOOR {		log.Printf("LastCursor %p/%p %d, %d\n", d, &d.LastCursor, len(d.LastCursor), cap(d.LastCursor))	}	defer d.mcMutex.Unlock()	if DEBUG_DOOR {		log.Printf("LastCursor: %#v\n", d.LastCursor)	}	return ArrayDelete(&d.LastCursor, 0)}func (d *Door) AddCursorPos(cursor CursorPos) {	d.mcMutex.Lock()	if DEBUG_DOOR {		log.Printf("LastCursor %p/%p %d, %d\n", d, &d.LastCursor, len(d.LastCursor), cap(d.LastCursor))	}	defer d.mcMutex.Unlock()	d.LastCursor = append(d.LastCursor, cursor)	if DEBUG_DOOR {		log.Printf("LastCursor now %d, %d\n", len(d.LastCursor), cap(d.LastCursor))		log.Printf("AddCursor: %#v\n", d.LastCursor)	}}func (d *Door) ClearMouseCursor() {	d.mcMutex.Lock()	defer d.mcMutex.Unlock()	if DEBUG_DOOR {		log.Println("ClearMouseCursor")	}	d.LastMouse = make([]Mouse, 0, 2)	d.LastCursor = make([]CursorPos, 0, 3)}// Return the amount of time left as time.Durationfunc (d *Door) TimeLeft() time.Duration {	return time.Until(d.TimeOut)}func (d *Door) TimeUsed() time.Duration {	return time.Since(d.StartTime)}func (d *Door) Disconnect() bool {	return d.Disconnected // atomic.LoadInt32(&d.Disconnected) != 0}func (d *Door) Detect() bool {	// detect is destructive ... make it non-destructive	// destructive: clears/trashes the screen.	var detect string = "\r\x03\x04" + CURSOR_POS + "\b \b\b \b" +		"\r\u2615" + CURSOR_POS + "\b \b\b \b\b \b" +		SAVE_POS + "\x1b[999C\x1b[999B" + CURSOR_POS + RESTORE_POS	// hot beverage is 3 bytes long -- need 3 "\b \b" to erase.	d.Write(detect)	var info []CursorPos = make([]CursorPos, 0, 3)	var done bool	for !done {		_, ex, err := d.WaitKey(time.Second)		log.Println("WaitKey:", ex, err)		if ex == CURSOR {			cursor, ok := d.GetCursorPos()			if ok {				info = append(info, cursor)				if len(info) == 3 {					done = true				}			}		}		if err != nil {			done = true		}	}	if len(info) != 3 {		// Detection FAILED.		log.Println("Detect FAILED:", info)		return false	}	// Ok!  Let's see what we've got...	var valid bool	// Where did I get these numbers from?	// linux term (telnet/ssh) [0].X = 1, [1].X = 3	// VS Code terminal: 1, 3	// https://docs.python.org/3/library/unicodedata.html	// \u2615 is a fullwidth (2 char) unicode symbol!	// SO, [1].X == 3 // and not 2.	// syncterm [0].X = 3, [1].X = 4	// Magiterm [0].X = 3, [1].X = 4	// cp437 + telnet [0].X = 1, [1].X = 4  FullCP437 = False	// ^ Fails FullCP437 test - characters codes ignored.	// cp437plus + telnet 3, 4.  (Has FullCP437 support.)	// if (info[0].X == 1 || info[0].X == 3) &&	//	(info[1].X == 2 || info[1].X == 3) {	// Breakdown by detected type:	// Unicode \x03 \x04 (control codes ignored)	// Unicode \u2615 = fullwidth takes up 2 characters	// CP437 \x03 \x04 Hearts Diamonds Symbols 2 characters	// ^ Only works for FullCP437	// CP437 \u2615 = b'\xe2\x98\x95' 3 bytes	// So info[1].X = 4	if info[0].X == 1 && info[1].X == 3 {		Unicode = true		valid = true	} else {		// info[1].X = 4		Unicode = false		CP437 = true		valid = true	}	if info[0].X == 3 {		Full_CP437 = true	}	if !valid {		log.Println("Detect FAILED (not valid):", info)		return false	}	Width, Height = info[2].X, info[2].Y	// Putty doesn't seem to restoring the cursor position (when detecting).	d.Write(Goto(1, info[0].Y))	log.Printf("Unicode: %t, CP437: %t, Full %t, Screen %v\n", Unicode, CP437, Full_CP437, info[2])	return true}// Initialize door framework.  Parse commandline, read dropfile,// detect terminal capabilities.func (d *Door) Init(doorname string) {	var dropfile string	d.Pushback = NewFIFOBuffer[rune](5)	// Get path to binary, and chdir to it.	var binaryPath string	binaryPath, _ = os.Executable()	binaryPath = filepath.Dir(binaryPath)	_ = os.Chdir(binaryPath)	flag.StringVar(&dropfile, "d", "", "Path to dropfile")	flag.Parse()	if len(dropfile) == 0 {		flag.PrintDefaults()		os.Exit(2)	}	d.ReadDropfile(dropfile)	if d.Config.Comm_type == 0 {		// RAW MODE		d.tio_default, _ = term.MakeRaw(d.READFD)	}	// Logfile will be doorname - node #	var logfilename string = fmt.Sprintf("%s-%d.log", doorname, d.Config.Node)	var logf *os.File	var err error	logf, err = os.OpenFile(logfilename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)	if err != nil {		log.Panicf("Error creating log file %s: %v", logfilename, err)	}	// Set logging output to logfilename.	log.SetOutput(logf)	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)	log.Printf("Loading dropfile %s\n", dropfile)	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)	d.readerChannel = make(chan ReaderData, 16) // was 8 ?	d.writerChannel = make(chan string)         // unbuffered	d.ClearMouseCursor()	d.setupChannels()	d.Detect()	if Unicode {		BOXES = BOXES_UNICODE		BARS = BARS_UNICODE	} else {		BOXES = BOXES_CP437		BARS = BARS_CP437	}}func (d *Door) Close() {	defer func() {		if err := recover(); err != nil {			log.Println("door.Close FAILURE:", err)			// This displays stack trace stderr			debug.PrintStack()		}	}()	d.DisableMouse()	log.Println("Closing...")	close(d.writerChannel)	log.Println("wg.Wait()")	d.wg.Wait()	log.Println("Closed.")	if d.Config.Comm_type == 0 {		// Linux - restore console settings to default/original.		term.Restore(d.READFD, d.tio_default)	}}// Goto X, Y - Position the cursor using ANSI Escape Codes//// Example:////	d.Write(door.Goto(1, 5) + "Now at X=1, Y=5.")func Goto(x int, y int) string {	return fmt.Sprintf("\x1b[%d;%dH", y, x)}
 |