From fa34121f005ce4b90ee0b8508e2e8e2723bf387e Mon Sep 17 00:00:00 2001 From: Larry Clapp Date: Mon, 20 Mar 2023 21:10:04 -0400 Subject: [PATCH] text: fix sorting in faceOrderer.sorted faceOrderer.sorted tried to put the "primary" font first by tweaking the "less" function in sort.Slice, but it didn't work correctly. If item i equaled the "primary" font, less() always returned true. This did not take into account if item j was the "primary" font, in which case it could easily be sorted differently. Rather than adding another special case for that, which I couldn't convince myself was actually correct in every case, I just searched for the "primary" font and moved it to the front of the slice, and then omitted the first item of the slice from the rest of the sorting. Signed-off-by: Larry Clapp --- text/gotext.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/text/gotext.go b/text/gotext.go index e000d1c7..1774365e 100644 --- a/text/gotext.go +++ b/text/gotext.go @@ -221,12 +221,21 @@ func (c *faceOrderer) fontForStyle(font Font) (Font, bool) { // faces returns a slice of faces with primary as the first element and // the remaining faces ordered by insertion order. func (f *faceOrderer) sorted(primary Font) []font.Face { - sort.Slice(f.fonts, func(i, j int) bool { + // If we find primary, put it first, and omit it from the below sort. + lowest := 0 + for i := range f.fonts { if f.fonts[i] == primary { - return true + if i != 0 { + f.fonts[0], f.fonts[i] = f.fonts[i], f.fonts[0] + } + lowest = 1 + break } - a := f.fonts[i] - b := f.fonts[j] + } + sorting := f.fonts[lowest:] + sort.Slice(sorting, func(i, j int) bool { + a := sorting[i] + b := sorting[j] return f.fontDefaultOrder[a] < f.fontDefaultOrder[b] }) for i, font := range f.fonts {