merge decorator
Vladimir Bauer
7 years ago
| 0 | package decor | |
| 1 | ||
| 2 | import ( | |
| 3 | "fmt" | |
| 4 | "strings" | |
| 5 | "unicode/utf8" | |
| 6 | ) | |
| 7 | ||
| 8 | func Merge(decorator Decorator, wcc ...WC) Decorator { | |
| 9 | if _, ok := decorator.Sync(); !ok { | |
| 10 | return decorator | |
| 11 | } | |
| 12 | var placeHolders []*placeHolderDecorator | |
| 13 | for _, wc := range wcc { | |
| 14 | wc.Init() | |
| 15 | placeHolders = append(placeHolders, &placeHolderDecorator{ | |
| 16 | WC: wc, | |
| 17 | wsync: make(chan int), | |
| 18 | }) | |
| 19 | } | |
| 20 | md := &MergeDecorator{ | |
| 21 | decorator: decorator, | |
| 22 | placeHolders: placeHolders, | |
| 23 | } | |
| 24 | md.WC = decorator.SetConfig(md.WC) | |
| 25 | return md | |
| 26 | } | |
| 27 | ||
| 28 | type MergeDecorator struct { | |
| 29 | WC | |
| 30 | decorator Decorator | |
| 31 | placeHolders []*placeHolderDecorator | |
| 32 | } | |
| 33 | ||
| 34 | func (d *MergeDecorator) PlaceHolders() []Decorator { | |
| 35 | decorators := make([]Decorator, len(d.placeHolders)) | |
| 36 | for i, ph := range d.placeHolders { | |
| 37 | decorators[i] = ph | |
| 38 | } | |
| 39 | return decorators | |
| 40 | } | |
| 41 | ||
| 42 | func (d *MergeDecorator) Decor(st *Statistics) string { | |
| 43 | msg := d.decorator.Decor(st) | |
| 44 | msgLen := utf8.RuneCountInString(msg) | |
| 45 | pWidth := msgLen / (len(d.placeHolders) + 1) | |
| 46 | mod := msgLen % (len(d.placeHolders) + 1) | |
| 47 | d.wsync <- pWidth + mod | |
| 48 | for _, ph := range d.placeHolders { | |
| 49 | ph.wsync <- pWidth | |
| 50 | } | |
| 51 | // fmt.Fprintln(os.Stderr, "all sent") | |
| 52 | max := <-d.wsync | |
| 53 | for _, ph := range d.placeHolders { | |
| 54 | max += <-ph.wsync | |
| 55 | } | |
| 56 | if (d.C & DextraSpace) != 0 { | |
| 57 | max++ | |
| 58 | } | |
| 59 | return fmt.Sprintf(fmt.Sprintf(d.format, max), msg) | |
| 60 | } | |
| 61 | ||
| 62 | type placeHolderDecorator struct { | |
| 63 | WC | |
| 64 | wsync chan int | |
| 65 | } | |
| 66 | ||
| 67 | func (d *placeHolderDecorator) Decor(st *Statistics) string { | |
| 68 | go func() { | |
| 69 | width := <-d.wsync | |
| 70 | msg := strings.Repeat(" ", width) | |
| 71 | d.wsync <- utf8.RuneCountInString(d.FormatMsg(msg)) | |
| 72 | }() | |
| 73 | return "" | |
| 74 | } |