2017-01-14 06:07:43 +00:00
|
|
|
// Copyright 2017 Zack Guo <zack.y.guo@gmail.com>. All rights reserved.
|
2015-04-21 13:56:10 +00:00
|
|
|
// Use of this source code is governed by a MIT license that can
|
|
|
|
// be found in the LICENSE file.
|
|
|
|
|
|
|
|
package termui
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
import (
|
|
|
|
"image"
|
2019-02-22 05:08:41 +00:00
|
|
|
|
|
|
|
rw "github.com/mattn/go-runewidth"
|
2019-01-24 04:12:10 +00:00
|
|
|
)
|
2015-04-21 13:56:10 +00:00
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
// Cell represents a viewable terminal cell
|
2015-04-21 13:56:10 +00:00
|
|
|
type Cell struct {
|
2019-01-24 04:12:10 +00:00
|
|
|
Rune rune
|
|
|
|
Style Style
|
2015-04-21 13:56:10 +00:00
|
|
|
}
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
var CellClear = Cell{
|
|
|
|
Rune: ' ',
|
|
|
|
Style: StyleClear,
|
2015-04-21 13:56:10 +00:00
|
|
|
}
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
// NewCell takes 1 to 2 arguments
|
|
|
|
// 1st argument = rune
|
|
|
|
// 2nd argument = optional style
|
|
|
|
func NewCell(rune rune, args ...interface{}) Cell {
|
|
|
|
style := StyleClear
|
|
|
|
if len(args) == 1 {
|
|
|
|
style = args[0].(Style)
|
|
|
|
}
|
|
|
|
return Cell{
|
|
|
|
Rune: rune,
|
|
|
|
Style: style,
|
2015-04-21 13:56:10 +00:00
|
|
|
}
|
2015-04-26 04:13:49 +00:00
|
|
|
}
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
// Buffer represents a section of a terminal and is a renderable rectangle of cells.
|
|
|
|
type Buffer struct {
|
|
|
|
image.Rectangle
|
|
|
|
CellMap map[image.Point]Cell
|
2015-04-21 13:56:10 +00:00
|
|
|
}
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
func NewBuffer(r image.Rectangle) *Buffer {
|
|
|
|
buf := &Buffer{
|
|
|
|
Rectangle: r,
|
|
|
|
CellMap: make(map[image.Point]Cell),
|
|
|
|
}
|
|
|
|
buf.Fill(CellClear, r) // clears out area
|
|
|
|
return buf
|
2015-04-21 13:56:10 +00:00
|
|
|
}
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
func (self *Buffer) GetCell(p image.Point) Cell {
|
|
|
|
return self.CellMap[p]
|
2015-04-21 13:56:10 +00:00
|
|
|
}
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
func (self *Buffer) SetCell(c Cell, p image.Point) {
|
|
|
|
self.CellMap[p] = c
|
2015-04-26 04:13:49 +00:00
|
|
|
}
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
func (self *Buffer) Fill(c Cell, rect image.Rectangle) {
|
|
|
|
for x := rect.Min.X; x < rect.Max.X; x++ {
|
|
|
|
for y := rect.Min.Y; y < rect.Max.Y; y++ {
|
|
|
|
self.SetCell(c, image.Pt(x, y))
|
2015-04-26 04:13:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-24 04:12:10 +00:00
|
|
|
func (self *Buffer) SetString(s string, style Style, p image.Point) {
|
2019-02-22 05:08:41 +00:00
|
|
|
runes := []rune(s)
|
|
|
|
x := 0
|
|
|
|
for _, char := range runes {
|
|
|
|
self.SetCell(Cell{char, style}, image.Pt(p.X+x, p.Y))
|
|
|
|
x += rw.RuneWidth(char)
|
2015-04-26 04:13:49 +00:00
|
|
|
}
|
2015-04-21 13:56:10 +00:00
|
|
|
}
|