Put Editor behind a constructor function

This commit is contained in:
Timothy Warren 2021-03-24 14:17:29 -04:00
parent 0902d494c5
commit 63cad6d012
3 changed files with 34 additions and 15 deletions

View File

@ -10,11 +10,13 @@ func main() {
oldState := terminal.RawOn()
defer terminal.RawOff(oldState)
e := editor.New()
// The input loop
for {
editor.RefreshScreen()
e.RefreshScreen()
if editor.ProcessKeypress() == false {
if e.ProcessKeypress() == false {
break
}
}

View File

@ -5,29 +5,31 @@ import (
"timshome.page/gilo/internal/terminal"
)
type Editor struct {
type editor struct {
rows int
cols int
}
func drawRows() {
_, rows := terminal.Size()
func New() *editor {
cols, rows := terminal.Size()
for y :=0; y < rows; y += 1 {
terminal.OutLn("~")
}
e := new(editor)
e.cols = cols
e.rows = rows
return e
}
func RefreshScreen() {
func (e *editor) RefreshScreen() {
terminal.ANSICode(terminal.ClearScreen)
terminal.ANSICode(terminal.ResetCursor)
drawRows()
e.drawRows()
terminal.ANSICode(terminal.ResetCursor)
}
func ProcessKeypress() bool {
func (e *editor) ProcessKeypress() bool {
ch, _ := terminal.ReadKey()
// Clean up on exit
@ -41,10 +43,20 @@ func ProcessKeypress() bool {
// Ugliest syntax structure ever?
switch {
case char.IsCtrl(ch):
terminal.OutLn("%d", ch)
terminal.WriteLn("%d", ch)
default:
terminal.OutLn("%d ('%c')", ch, ch)
terminal.WriteLn("%d ('%c')", ch, ch)
}
return true
}
func (e *editor) drawRows() {
for y :=0; y < e.rows; y += 1 {
terminal.Write("~")
if y < (e.rows - 1) {
terminal.Write("\r\n")
}
}
}

View File

@ -97,14 +97,19 @@ func Size () (width int, height int) {
// Figure out the size the hard way
height, width = sizeTrick()
OutLn("%d Rows, %d Cols", height, width)
WriteLn("%d Rows, %d Cols", height, width)
return width, height
}
// Print a formatted string to stdout, with CRLF line endings for proper terminal formatting
func OutLn(format string, a ...interface{}) {
func WriteLn(format string, a ...interface{}) {
formatted := fmt.Sprintf(format, a...)
fmt.Printf("%s\r\n", formatted)
}
func Write(format string, a ...interface{}) {
fmt.Printf(format, a...)
}