aerc/ui/context.go

102 lines
1.9 KiB
Go
Raw Normal View History

2018-02-16 06:05:07 +01:00
package ui
import (
"fmt"
2018-02-18 01:42:29 +01:00
"github.com/mattn/go-runewidth"
tb "github.com/nsf/termbox-go"
2018-02-16 06:05:07 +01:00
)
// A context allows you to draw in a sub-region of the terminal
type Context struct {
x int
y int
width int
height int
}
func (ctx *Context) Width() int {
return ctx.width
}
func (ctx *Context) Height() int {
return ctx.height
}
func NewContext(width, height int) *Context {
2018-02-16 06:05:07 +01:00
return &Context{0, 0, width, height}
}
func (ctx *Context) Subcontext(x, y, width, height int) *Context {
if x+width > ctx.width || y+height > ctx.height {
panic(fmt.Errorf("Attempted to create context larger than parent"))
}
return &Context{
x: ctx.x + x,
y: ctx.y + y,
width: width,
height: height,
}
}
2018-02-18 01:42:29 +01:00
func (ctx *Context) SetCell(x, y int, ch rune, fg, bg tb.Attribute) {
2018-02-16 06:05:07 +01:00
if x >= ctx.width || y >= ctx.height {
panic(fmt.Errorf("Attempted to draw outside of context"))
}
2018-02-18 01:42:29 +01:00
tb.SetCell(ctx.x+x, ctx.y+y, ch, fg, bg)
2018-02-16 06:05:07 +01:00
}
2018-02-18 01:42:29 +01:00
func (ctx *Context) Printf(x, y int, ref tb.Cell,
format string, a ...interface{}) int {
2018-02-16 06:05:07 +01:00
if x >= ctx.width || y >= ctx.height {
panic(fmt.Errorf("Attempted to draw outside of context"))
}
str := fmt.Sprintf(format, a...)
x += ctx.x
y += ctx.y
old_x := x
newline := func() bool {
x = old_x
y++
return y < ctx.height
}
for _, ch := range str {
2018-02-18 01:42:29 +01:00
if str == " こんにちは " {
fmt.Printf("%c\n", ch)
}
2018-02-16 06:05:07 +01:00
switch ch {
case '\n':
if !newline() {
2018-02-18 01:42:29 +01:00
return runewidth.StringWidth(str)
2018-02-16 06:05:07 +01:00
}
case '\r':
x = old_x
default:
2018-02-18 01:42:29 +01:00
tb.SetCell(x, y, ch, ref.Fg, ref.Bg)
x += runewidth.RuneWidth(ch)
2018-02-16 06:05:07 +01:00
if x == old_x+ctx.width {
if !newline() {
2018-02-18 01:42:29 +01:00
return runewidth.StringWidth(str)
2018-02-16 06:05:07 +01:00
}
}
}
}
2018-02-18 01:42:29 +01:00
return runewidth.StringWidth(str)
2018-02-16 06:05:07 +01:00
}
2018-02-18 01:42:29 +01:00
func (ctx *Context) Fill(x, y, width, height int, ref tb.Cell) {
2018-02-16 06:05:07 +01:00
_x := x
2018-02-18 01:42:29 +01:00
_y := y
for ; y < _y+height && y < ctx.height; y++ {
for ; x < _x+width && x < ctx.width; x++ {
2018-02-16 06:05:07 +01:00
ctx.SetCell(x, y, ref.Ch, ref.Fg, ref.Bg)
}
x = _x
}
}