Hilbish/golibs/terminal/terminal.go

83 lines
2.0 KiB
Go
Raw Normal View History

package terminal
import (
"os"
"hilbish/util"
2022-03-29 12:52:26 +00:00
rt "github.com/arnodel/golua/runtime"
"github.com/arnodel/golua/lib/packagelib"
"golang.org/x/term"
)
var termState *term.State
2022-03-29 12:52:26 +00:00
var Loader = packagelib.Loader{
Load: loaderFunc,
Name: "terminal",
}
2022-03-29 12:52:26 +00:00
func loaderFunc(rtm *rt.Runtime) (rt.Value, func()) {
exports := map[string]util.LuaExport{
"setRaw": util.LuaExport{termsetRaw, 0, false},
"restoreState": util.LuaExport{termrestoreState, 0, false},
"size": util.LuaExport{termsize, 0, false},
"saveState": util.LuaExport{termsaveState, 0, false},
}
2022-03-29 12:52:26 +00:00
mod := rt.NewTable()
util.SetExports(rtm, mod, exports)
//util.Document(L, mod, "The terminal library is a simple and lower level library for certain terminal interactions.")
2022-03-29 12:52:26 +00:00
return rt.TableValue(mod), nil
}
// size()
// Gets the dimensions of the terminal. Returns a table with `width` and `height`
// Note: this is not the size in relation to the dimensions of the display
2022-03-29 12:52:26 +00:00
func termsize(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
w, h, err := term.GetSize(int(os.Stdin.Fd()))
if err != nil {
2022-03-29 12:52:26 +00:00
return nil, err
}
2022-03-29 12:52:26 +00:00
dimensions := rt.NewTable()
dimensions.Set(rt.StringValue("width"), rt.IntValue(int64(w)))
dimensions.Set(rt.StringValue("height"), rt.IntValue(int64(h)))
return c.PushingNext1(t.Runtime, rt.TableValue(dimensions)), nil
}
// saveState()
// Saves the current state of the terminal
2022-03-29 12:52:26 +00:00
func termsaveState(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
state, err := term.GetState(int(os.Stdin.Fd()))
if err != nil {
2022-03-29 12:52:26 +00:00
return nil, err
}
termState = state
2022-03-29 12:52:26 +00:00
return c.Next(), nil
}
// restoreState()
// Restores the last saved state of the terminal
2022-03-29 12:52:26 +00:00
func termrestoreState(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
err := term.Restore(int(os.Stdin.Fd()), termState)
if err != nil {
2022-03-29 12:52:26 +00:00
return nil, err
}
2022-03-29 12:52:26 +00:00
return c.Next(), nil
}
// setRaw()
// Puts the terminal in raw mode
2022-03-29 12:52:26 +00:00
func termsetRaw(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
_, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
2022-03-29 12:52:26 +00:00
return nil, err
}
2022-03-29 12:52:26 +00:00
return c.Next(), nil
}