Add structs for cursor position and size

This commit is contained in:
Timothy Warren 2021-03-25 12:27:48 -04:00
parent d04b4bec84
commit ca81c5a8cf
2 changed files with 26 additions and 15 deletions

View File

@ -12,15 +12,21 @@ const KiloVersion = "0.0.1"
// !Editor // !Editor
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
type cursor struct {
x int
y int
}
type editor struct { type editor struct {
rows int screen *terminal.Screen
cols int cursor *cursor
} }
func New() *editor { func New() *editor {
rows, cols := terminal.Size() screen := terminal.Size()
cursor := &cursor { 0, 0 }
return &editor{rows, cols} return &editor{screen, cursor }
} }
func (e *editor) RefreshScreen() { func (e *editor) RefreshScreen() {
@ -51,14 +57,14 @@ func (e *editor) ProcessKeypress() bool {
} }
func (e *editor) drawRows(ab *buffer) { func (e *editor) drawRows(ab *buffer) {
for y :=0; y < e.rows; y += 1 { for y :=0; y < e.screen.Rows; y += 1 {
if y == e.rows / 3 { if y == e.screen.Rows / 3 {
welcome := fmt.Sprintf("Gilo editor -- version %s", KiloVersion) welcome := fmt.Sprintf("Gilo editor -- version %s", KiloVersion)
if len(welcome) > e.cols { if len(welcome) > e.screen.Cols {
welcome = fn.TruncateString(welcome, e.cols) welcome = fn.TruncateString(welcome, e.screen.Cols)
} }
padding := (e.cols - len(welcome)) / 2 padding := (e.screen.Cols - len(welcome)) / 2
if padding > 0 { if padding > 0 {
ab.appendRune('~') ab.appendRune('~')
padding-- padding--
@ -76,7 +82,7 @@ func (e *editor) drawRows(ab *buffer) {
ab.append(terminal.ClearLine) ab.append(terminal.ClearLine)
if y < (e.rows - 1) { if y < (e.screen.Rows - 1) {
ab.append("\r\n") ab.append("\r\n")
} }
} }

View File

@ -6,23 +6,28 @@ import (
"os" "os"
) )
type Screen struct {
Rows int
Cols int
}
// Get the size of the terminal in rows and columns // Get the size of the terminal in rows and columns
func Size () (rows int, cols int) { func Size () *Screen {
check() check()
cols = 80 cols := 80
rows = 24 rows := 24
// Try the syscall first // Try the syscall first
cols, rows, err := term.GetSize(int(os.Stdin.Fd())) cols, rows, err := term.GetSize(int(os.Stdin.Fd()))
if err == nil { if err == nil {
return rows, cols return &Screen {rows, cols }
} }
// Figure out the size the hard way // Figure out the size the hard way
rows, cols = sizeTrick() rows, cols = sizeTrick()
return rows, cols return &Screen{ rows, cols }
} }
func sizeTrick () (rows int, cols int) { func sizeTrick () (rows int, cols int) {