From e9e3e4084e49c78817f025a230ef09d582147b94 Mon Sep 17 00:00:00 2001 From: Matteo Kloiber Date: Thu, 16 Apr 2015 20:19:44 +0200 Subject: [PATCH] Implemented `RendererFactory` in `Par`. --- example/par.go | 3 ++- example/theme.go | 2 +- p.go | 56 +++++++++++++++++++++++------------------------- 3 files changed, 30 insertions(+), 31 deletions(-) diff --git a/example/par.go b/example/par.go index ffbc60a..6c13340 100644 --- a/example/par.go +++ b/example/par.go @@ -29,7 +29,8 @@ func main() { par1.X = 20 par1.Border.Label = "标签" - par2 := termui.NewPar("Simple text\nwith label. It can be multilined with \\n or break automatically") + par2 := termui.NewPar("Simple colored text\nwith label. It [can be](RED) multilined with \\n or [break automatically](GREEN, BOLD)") + par2.RendererFactory = termui.MarkdownTextRendererFactory{} par2.Height = 5 par2.Width = 37 par2.Y = 4 diff --git a/example/theme.go b/example/theme.go index f3695c2..30c51a3 100644 --- a/example/theme.go +++ b/example/theme.go @@ -123,7 +123,7 @@ func main() { ui.Render(p, list, g, sp, lc, bc, lc1, p1) } - evt := EventCh() + evt := ui.EventCh() i := 0 for { select { diff --git a/p.go b/p.go index e327d74..b6237fb 100644 --- a/p.go +++ b/p.go @@ -13,38 +13,43 @@ package termui */ type Par struct { Block - Text string - TextFgColor Attribute - TextBgColor Attribute + Text string + TextFgColor Attribute + TextBgColor Attribute + RendererFactory TextRendererFactory } // NewPar returns a new *Par with given text as its content. func NewPar(s string) *Par { return &Par{ - Block: *NewBlock(), - Text: s, - TextFgColor: theme.ParTextFg, - TextBgColor: theme.ParTextBg} + Block: *NewBlock(), + Text: s, + TextFgColor: theme.ParTextFg, + TextBgColor: theme.ParTextBg, + RendererFactory: PlainRendererFactory{}, + } } // Buffer implements Bufferer interface. func (p *Par) Buffer() []Point { ps := p.Block.Buffer() - rs := str2runes(p.Text) - i, j, k := 0, 0, 0 - for i < p.innerHeight && k < len(rs) { - // the width of char is about to print - w := charWidth(rs[k]) + fg, bg := p.TextFgColor, p.TextBgColor + sequence := p.RendererFactory.TextRenderer(p.Text).Render(fg, bg) + runes := []rune(sequence.NormalizedText) - if rs[k] == '\n' || j+w > p.innerWidth { - i++ - j = 0 // set x = 0 - if rs[k] == '\n' { - k++ + y, x, n := 0, 0, 0 + for y < p.innerHeight && n < len(runes) { + point, width := sequence.PointAt(n, x+p.innerX, y+p.innerY) + + if runes[n] == '\n' || x+width > p.innerWidth { + y++ + x = 0 // set x = 0 + if runes[n] == '\n' { + n++ } - if i >= p.innerHeight { + if y >= p.innerHeight { ps = append(ps, newPointWithAttrs('…', p.innerX+p.innerWidth-1, p.innerY+p.innerHeight-1, @@ -54,18 +59,11 @@ func (p *Par) Buffer() []Point { continue } - pi := Point{} - pi.X = p.innerX + j - pi.Y = p.innerY + i - pi.Ch = rs[k] - pi.Bg = p.TextBgColor - pi.Fg = p.TextFgColor - - ps = append(ps, pi) - - k++ - j += w + ps = append(ps, point) + n++ + x += width } + return p.Block.chopOverflow(ps) }