func TestColorOffset(t *testing.T) { // ------------ 20 ---- -- ---- // ++++++++ ++++++++++ // --++++++++-- --++++++++++--- offsets := []Offset{Offset{5, 15}, Offset{25, 35}} item := Result{ item: &Item{ colors: &[]ansiOffset{ ansiOffset{[2]int32{0, 20}, ansiState{1, 5, 0}}, ansiOffset{[2]int32{22, 27}, ansiState{2, 6, tui.Bold}}, ansiOffset{[2]int32{30, 32}, ansiState{3, 7, 0}}, ansiOffset{[2]int32{33, 40}, ansiState{4, 8, tui.Bold}}}}} // [{[0 5] 9 false} {[5 15] 99 false} {[15 20] 9 false} {[22 25] 10 true} {[25 35] 99 false} {[35 40] 11 true}] pair := tui.NewColorPair(99, 199) colors := item.colorOffsets(offsets, tui.Dark256, pair, tui.AttrRegular, true) assert := func(idx int, b int32, e int32, c tui.ColorPair, bold bool) { var attr tui.Attr if bold { attr = tui.Bold } o := colors[idx] if o.offset[0] != b || o.offset[1] != e || o.color != c || o.attr != attr { t.Error(o) } } assert(0, 0, 5, tui.NewColorPair(1, 5), false) assert(1, 5, 15, pair, false) assert(2, 15, 20, tui.NewColorPair(1, 5), false) assert(3, 22, 25, tui.NewColorPair(2, 6), true) assert(4, 25, 35, pair, false) assert(5, 35, 40, tui.NewColorPair(4, 8), true) }
func (result *Result) colorOffsets(matchOffsets []Offset, theme *tui.ColorTheme, color tui.ColorPair, attr tui.Attr, current bool) []colorOffset { itemColors := result.item.Colors() // No ANSI code, or --color=no if len(itemColors) == 0 { var offsets []colorOffset for _, off := range matchOffsets { offsets = append(offsets, colorOffset{offset: [2]int32{off[0], off[1]}, color: color, attr: attr}) } return offsets } // Find max column var maxCol int32 for _, off := range matchOffsets { if off[1] > maxCol { maxCol = off[1] } } for _, ansi := range itemColors { if ansi.offset[1] > maxCol { maxCol = ansi.offset[1] } } cols := make([]int, maxCol) for colorIndex, ansi := range itemColors { for i := ansi.offset[0]; i < ansi.offset[1]; i++ { cols[i] = colorIndex + 1 // XXX } } for _, off := range matchOffsets { for i := off[0]; i < off[1]; i++ { cols[i] = -1 } } // sort.Sort(ByOrder(offsets)) // Merge offsets // ------------ ---- -- ---- // ++++++++ ++++++++++ // --++++++++-- --++++++++++--- curr := 0 start := 0 var colors []colorOffset add := func(idx int) { if curr != 0 && idx > start { if curr == -1 { colors = append(colors, colorOffset{ offset: [2]int32{int32(start), int32(idx)}, color: color, attr: attr}) } else { ansi := itemColors[curr-1] fg := ansi.color.fg bg := ansi.color.bg if theme != nil { if fg == -1 { if current { fg = theme.Current } else { fg = theme.Fg } } if bg == -1 { if current { bg = theme.DarkBg } else { bg = theme.Bg } } } colors = append(colors, colorOffset{ offset: [2]int32{int32(start), int32(idx)}, color: tui.NewColorPair(fg, bg), attr: ansi.color.attr.Merge(attr)}) } } } for idx, col := range cols { if col != curr { add(idx) start = idx curr = col } } add(int(maxCol)) return colors }