forked from tdewolff/canvas
-
Notifications
You must be signed in to change notification settings - Fork 1
/
text.go
855 lines (785 loc) · 22.4 KB
/
text.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
package canvas
import (
"image/color"
"math"
"reflect"
"sort"
"strconv"
"strings"
"unicode/utf8"
canvasText "github.com/eihigh/canvas/text"
)
// TextAlign specifies how the text should align or whether it should be justified.
type TextAlign int
// see TextAlign
const (
Left TextAlign = iota
Right
Center
Top
Bottom
Justify
)
func (ta TextAlign) String() string {
switch ta {
case Left:
return "Left"
case Right:
return "Right"
case Center:
return "Center"
case Top:
return "Top"
case Bottom:
return "Bottom"
case Justify:
return "Justify"
}
return "Invalid(" + strconv.Itoa(int(ta)) + ")"
}
// WritingMode specifies how the text lines should be laid out.
type WritingMode int
// see WritingMode
const (
HorizontalTB WritingMode = iota
VerticalRL
VerticalLR
)
// TextOrientation specifies how horizontal text should be oriented within vertical text, or how vertical-only text should be layed out in horizontal text.
type TextOrientation int
// see TextOrientation
const (
Natural TextOrientation = iota // turn horizontal text 90deg clockwise for VerticalRL, and counter clockwise for VerticalLR
Upright // split characters and lay them out upright
)
func (wm WritingMode) String() string {
switch wm {
case HorizontalTB:
return "HorizontalTB"
case VerticalRL:
return "VerticalRL"
case VerticalLR:
return "VerticalLR"
}
return "Invalid(" + strconv.Itoa(int(wm)) + ")"
}
// Text holds the representation of a text object.
type Text struct {
lines []line
fonts map[*Font]bool
Mode WritingMode
}
type line struct {
y float64
spans []TextSpan
}
// Heights returns the maximum top, ascent, descent, and bottom heights of the line, where top and bottom are equal to ascent and descent respectively with added line spacing.
func (l line) Heights(mode WritingMode, orient TextOrientation) (float64, float64, float64, float64) {
top, ascent, descent, bottom := 0.0, 0.0, 0.0, 0.0
if mode == HorizontalTB {
for _, span := range l.spans {
spanAscent, spanDescent, lineSpacing := span.Face.Metrics().Ascent, span.Face.Metrics().Descent, span.Face.Metrics().LineGap
top = math.Max(top, spanAscent+lineSpacing)
ascent = math.Max(ascent, spanAscent)
descent = math.Max(descent, spanDescent)
bottom = math.Max(bottom, spanDescent+lineSpacing)
}
} else if orient == Upright {
width := 0.0
for _, span := range l.spans {
for _, glyph := range span.Glyphs {
width = math.Max(width, span.Face.textWidth([]canvasText.Glyph{glyph}))
}
}
top = width / 2.0
ascent = width / 2.0
descent = width / 2.0
bottom = width / 2.0
} else {
panic("not implemented")
}
return top, ascent, descent, bottom
}
// TextSpan is a span of text.
type TextSpan struct {
x float64
Width float64
Face *FontFace
Text string
Glyphs []canvasText.Glyph
Direction canvasText.Direction
}
////////////////////////////////////////////////////////////////
func itemizeString(log string, script canvasText.Script) ([]string, []string) {
offset := 0
vis, mapV2L := canvasText.Bidi(log)
items := canvasText.ScriptItemizer(vis, script)
itemsV := make([]string, 0, len(items))
itemsL := make([]string, 0, len(items))
for _, item := range items {
itemV := []rune(item.Text)
itemL := make([]rune, len(itemV))
for i := 0; i < len(itemV); i++ {
itemL[mapV2L[offset+i]-offset] = itemV[i]
}
itemsV = append(itemsV, item.Text)
itemsL = append(itemsL, string(itemL))
offset += len(itemV)
}
return itemsL, itemsV
}
// NewTextLine is a simple text line using a single font face, a string (supporting new lines) and horizontal alignment (Left, Center, Right). The text's baseline will be drawn on the current coordinate.
func NewTextLine(face *FontFace, s string, halign TextAlign) *Text {
t := &Text{
fonts: map[*Font]bool{face.Font: true},
}
ascent, descent, spacing := face.Metrics().Ascent, face.Metrics().Descent, face.Metrics().LineGap
i := 0
y := 0.0
skipNext := false
for j, r := range s + "\n" {
if canvasText.IsParagraphSeparator(r) {
if skipNext {
skipNext = false
i++
continue
}
if i < j {
ppem := face.PPEM(DefaultResolution)
lineWidth := 0.0
line := line{y: y, spans: []TextSpan{}}
itemsL, itemsV := itemizeString(s[i:j], face.Script)
for k := 0; k < len(itemsL); k++ {
glyphs := face.Font.shaper.Shape(itemsV[k], ppem, face.Direction, face.Script, face.Language, face.Font.features, face.Font.variations)
width := face.textWidth(glyphs)
text := itemsL[k]
if face.Direction == canvasText.BottomToTop {
length := len([]rune(text))
reverseText := make([]rune, length)
for pos, r := range []rune(text) {
reverseText[length-pos-1] = r
}
text = string(reverseText)
}
line.spans = append(line.spans, TextSpan{
x: lineWidth,
Width: width,
Face: face,
Text: text,
Glyphs: glyphs,
Direction: face.Direction,
})
lineWidth += width
}
if halign == Center {
for k := range line.spans {
line.spans[k].x = -lineWidth / 2.0
}
} else if halign == Right {
for k := range line.spans {
line.spans[k].x = -lineWidth
}
}
t.lines = append(t.lines, line)
}
y += ascent + descent + spacing
i = j + utf8.RuneLen(r)
skipNext = r == '\r' && j+1 < len(s) && s[j+1] == '\n'
}
}
return t
}
// NewTextBox is an advanced text formatter that will format text placement based on the settings. It takes a single font face, a string, the width or height of the box (can be zero to disable), horizontal and vertical alignment (Left, Center, Right, Top, Bottom or Justify), text indentation for the first line and line stretch (percentage to stretch the line based on the line height).
func NewTextBox(face *FontFace, s string, width, height float64, halign, valign TextAlign, indent, lineStretch float64) *Text {
rt := NewRichText(face)
rt.WriteString(s)
return rt.ToText(width, height, halign, valign, indent, lineStretch)
}
type indexer []int
func (indexer indexer) index(loc int) int {
for index, start := range indexer {
if loc < start {
return index - 1
}
}
return len(indexer) - 1
}
// RichText allows to build up a rich text with text spans of different font faces and fitting that into a box using Donald Knuth's line breaking algorithm.
// TODO: RichText add support for decoration spans to properly underline the spaces betwee words too
type RichText struct {
*strings.Builder
locs indexer // faces locations ino string by number of runes
faces []*FontFace
mode WritingMode
orient TextOrientation
}
// NewRichText returns a new rich text with the given default font face.
func NewRichText(face *FontFace) *RichText {
return &RichText{
Builder: &strings.Builder{},
locs: indexer{0},
faces: []*FontFace{face},
mode: HorizontalTB,
orient: Natural,
}
}
// Reset resets the rich text to its initial state.
func (rt *RichText) Reset() {
rt.Builder.Reset()
rt.locs = rt.locs[:0]
rt.faces = rt.faces[:0]
}
// SetFace sets the font face.
func (rt *RichText) SetFace(face *FontFace) {
if face == rt.faces[len(rt.faces)-1] {
return
}
prevLoc := rt.locs[len(rt.locs)-1]
if rt.Len()-prevLoc == 0 {
rt.locs = rt.locs[:len(rt.locs)-1]
rt.faces = rt.faces[:len(rt.faces)-1]
}
rt.locs = append(rt.locs, len([]rune(rt.String())))
rt.faces = append(rt.faces, face)
}
// SetFaceSpan sets the font face between start and end measured in bytes.
func (rt *RichText) SetFaceSpan(face *FontFace, start, end int) {
// TODO: optimize when face already is on (part of) the span
if end <= start || rt.Len() <= start {
return
} else if rt.Len() < end {
end = rt.Len()
}
k := 0
i, j := 0, len(rt.locs)-1
for k < len(rt.locs) {
if rt.locs[k] < start {
i = k
}
if end <= rt.locs[k] {
j = k - 1
break
}
k++
}
rt.locs[j] = len([]rune(rt.String()[:end]))
rt.locs = append(rt.locs[:i], append(indexer{len([]rune(rt.String()[:start]))}, rt.locs[j:]...)...)
rt.faces = append(rt.faces[:i], append([]*FontFace{face}, rt.faces[j:]...)...)
}
// Add adds a string with a given font face.
func (rt *RichText) Add(face *FontFace, text string) *RichText {
rt.SetFace(face)
rt.WriteString(text)
return rt
}
// SetWritingMode sets the writing mode.
func (rt *RichText) SetWritingMode(mode WritingMode) {
rt.mode = mode
}
// SetTextOrientation sets the text orientation of non-CJK between CJK.
func (rt *RichText) SetTextOrientation(orient TextOrientation) {
rt.orient = orient
}
func writingModeDirection(mode WritingMode, direction canvasText.Direction) canvasText.Direction {
if direction == canvasText.TopToBottom || direction == canvasText.BottomToTop {
if mode == HorizontalTB {
return canvasText.LeftToRight
}
return canvasText.TopToBottom
} else if mode != HorizontalTB {
// unknown, left to right, right to left
return canvasText.TopToBottom
}
return direction
}
// ToText takes the added text spans and fits them within a given box of certain width and height using Donald Knuth's line breaking algorithm.
func (rt *RichText) ToText(width, height float64, halign, valign TextAlign, indent, lineStretch float64) *Text {
log := rt.String()
vis, mapV2L := canvasText.Bidi(log)
logRunes := []rune(log)
// itemize string by font face and script
texts := []string{}
scripts := []canvasText.Script{}
faces := []*FontFace{}
i, j := 0, 0 // index into vis
curFace := 0 // index into rt.faces
for k, r := range []rune(vis) {
nextFace := rt.locs.index(mapV2L[k])
if nextFace != curFace {
items := canvasText.ScriptItemizer(vis[i:j], rt.faces[curFace].Script)
for _, item := range items {
texts = append(texts, item.Text)
scripts = append(scripts, item.Script)
faces = append(faces, rt.faces[curFace])
i += len(item.Text)
}
curFace = nextFace
i = j
}
j += utf8.RuneLen(r)
}
if i < j {
items := canvasText.ScriptItemizer(vis[i:j], rt.faces[curFace].Script)
for _, item := range items {
texts = append(texts, item.Text)
scripts = append(scripts, item.Script)
faces = append(faces, rt.faces[curFace])
i += len(item.Text)
}
}
// shape text into glyphs and keep index into texts and faces
clusterOffset := uint32(0)
glyphIndices := indexer{} // indexes glyphs into texts and faces
glyphs := []canvasText.Glyph{}
for k, text := range texts {
face := faces[k]
ppem := face.PPEM(DefaultResolution)
direction := writingModeDirection(rt.mode, face.Direction)
script := scripts[k]
glyphsString := face.Font.shaper.Shape(text, ppem, direction, face.Script, face.Language, face.Font.features, face.Font.variations)
for i := range glyphsString {
glyphsString[i].SFNT = face.Font.SFNT
glyphsString[i].Size = face.Size
glyphsString[i].Script = script
glyphsString[i].Cluster += clusterOffset
}
glyphIndices = append(glyphIndices, len(glyphs))
glyphs = append(glyphs, glyphsString...)
clusterOffset += uint32(len(text))
}
upright := rt.orient == Upright
vertical := rt.mode != HorizontalTB
if vertical {
width, height = height, width
halign, valign = valign, halign
if halign == Top {
halign = Left
} else if halign == Bottom {
halign = Right
}
if valign == Left {
valign = Top
} else if valign == Right {
valign = Bottom
}
}
align := canvasText.Left
if halign == Justify {
align = canvasText.Justified
}
// break glyphs into lines following Donald Knuth's line breaking algorithm
looseness := 0
items := canvasText.GlyphsToItems(glyphs, indent, align, vertical, upright)
var breaks []*canvasText.Breakpoint
if width != 0.0 {
breaks = canvasText.Linebreak(items, width, looseness)
} else {
lineWidth := 0.0
for _, item := range items {
if item.Type != canvasText.PenaltyType {
lineWidth += item.Width
}
}
breaks = append(breaks, &canvasText.Breakpoint{Position: len(items) - 1, Width: lineWidth})
}
// build up lines
t := &Text{
lines: []line{{}},
fonts: map[*Font]bool{},
Mode: rt.mode,
}
glyphs = append(glyphs, canvasText.Glyph{Cluster: uint32(len(vis))}) // makes indexing easier
i, j = 0, 0 // index into: glyphs, breaks/lines
atStart := true
x, y := 0.0, 0.0 // both positive toward the bottom right
lineSpacing := 1.0 + lineStretch
if halign == Right {
x += width - breaks[j].Width
} else if halign == Center {
x += (width - breaks[j].Width) / 2.0
}
for position, item := range items {
if position == breaks[j].Position {
// add spaces to previous span
for _, glyph := range glyphs[i : i+item.Size] {
if glyph.Text != "\u200B" {
t.lines[j].spans[len(t.lines[j].spans)-1].Text += glyph.Text
}
}
if item.Type == canvasText.PenaltyType && item.Flagged && item.Width != 0.0 {
if 0 < len(t.lines[j].spans) {
span := &t.lines[j].spans[len(t.lines[j].spans)-1]
id := span.Face.Font.GlyphIndex('-')
glyph := canvasText.Glyph{
SFNT: span.Face.Font.SFNT,
Size: span.Face.Size,
ID: id,
XAdvance: int32(span.Face.Font.GlyphAdvance(id)),
Text: "-",
}
span.Glyphs = append(span.Glyphs, glyph)
span.Width += span.Face.textWidth([]canvasText.Glyph{glyph})
span.Text += "-"
}
}
_, ascent, _, bottom := t.lines[j].Heights(rt.mode, rt.orient)
if 0 < j {
ascent *= lineSpacing
}
bottom *= lineSpacing
t.lines[j].y = y + ascent
y += ascent + bottom
if height != 0.0 && (height < y || position == len(items)-1) {
// doesn't fit or at the end of items
break
}
t.lines = append(t.lines, line{})
if j+1 < len(breaks) {
j++
}
x = 0.0
if halign == Right {
x += width - breaks[j].Width
} else if halign == Center {
x += (width - breaks[j].Width) / 2.0
}
atStart = true
} else if item.Type == canvasText.BoxType {
// find index k into faces/texts
a := i
dx := 0.0
k := glyphIndices.index(i)
for b := i + 1; b <= i+item.Size; b++ {
nextK := glyphIndices.index(b)
if nextK != k || b == i+item.Size {
ac, bc := glyphs[a].Cluster, glyphs[b].Cluster
if glyphs[a+1].Cluster < ac {
// right-to-left
ac = glyphs[b-1].Cluster
bc = uint32(len(vis))
if 0 < a {
bc = glyphs[a-1].Cluster
}
}
ar := utf8.RuneCountInString(vis[:ac])
br := utf8.RuneCountInString(vis[:bc])
s := string(logRunes[ar:br])
w := faces[k].textWidth(glyphs[a:b])
t.lines[j].spans = append(t.lines[j].spans, TextSpan{
x: x + dx,
Width: w,
Face: faces[k],
Text: s,
Glyphs: glyphs[a:b],
Direction: writingModeDirection(rt.mode, faces[k].Direction),
})
t.fonts[faces[k].Font] = true
k = nextK
a = b
dx += w
}
}
if 0 < item.Size {
atStart = false
}
x += item.Width
} else if item.Type == canvasText.GlueType && !atStart {
width := item.Width
if 0.0 <= breaks[j].Ratio {
if !math.IsInf(item.Stretch, 0.0) {
width += breaks[j].Ratio * item.Stretch
}
} else if !math.IsInf(item.Shrink, 0.0) {
width += breaks[j].Ratio * item.Shrink
}
x += width
// add spaces to previous span
for _, glyph := range glyphs[i : i+item.Size] {
t.lines[j].spans[len(t.lines[j].spans)-1].Text += glyph.Text
}
}
i += item.Size
}
_, ascent, descent, bottom := t.lines[j].Heights(rt.mode, rt.orient)
y -= bottom * lineSpacing
if height != 0.0 && height < y+descent {
// doesn't fit
t.lines = t.lines[:len(t.lines)-1]
if 0 < j {
_, _, descent2, bottom2 := t.lines[j-1].Heights(rt.mode, rt.orient)
y += descent2 - (bottom2+ascent)*lineSpacing
} else {
// no lines at all
y = 0.0
}
} else {
y += descent
}
// vertical align
if rt.mode == VerticalRL {
if valign == Top {
valign = Bottom
} else if valign == Bottom {
valign = Top
}
}
if valign == Center || valign == Bottom {
dy := height - y
if valign == Center {
dy /= 2.0
}
for j := range t.lines {
t.lines[j].y += dy
}
} else if valign == Justify {
ddy := (height - y) / float64(len(t.lines)-1)
dy := 0.0
for j := range t.lines {
t.lines[j].y += dy
dy += ddy
}
}
if rt.mode == VerticalRL {
for j := range t.lines {
t.lines[j].y = height - t.lines[j].y
}
}
return t
}
// Empty returns true if there are no text lines or text spans.
func (t *Text) Empty() bool {
for _, line := range t.lines {
if len(line.spans) != 0 {
return false
}
}
return true
}
// Heights returns the top and bottom position of the first and last line respectively.
func (t *Text) Heights() (float64, float64) {
if len(t.lines) == 0 {
return 0.0, 0.0
}
firstLine := t.lines[0]
lastLine := t.lines[len(t.lines)-1]
_, ascent, _, _ := firstLine.Heights(HorizontalTB, Natural)
_, _, descent, _ := lastLine.Heights(HorizontalTB, Natural)
return -firstLine.y + ascent, lastLine.y + descent
}
// Bounds returns the bounding rectangle that defines the text box.
func (t *Text) Bounds() Rect {
if len(t.lines) == 0 || len(t.lines[0].spans) == 0 {
return Rect{}
}
rect := Rect{}
for _, line := range t.lines {
for _, span := range line.spans {
// TODO: vertical text
rect = rect.Add(Rect{span.x, -line.y - span.Face.Metrics().Descent, span.Width, span.Face.Metrics().Ascent + span.Face.Metrics().Descent})
}
}
return rect
}
// OutlineBounds returns the rectangle that contains the entire text box, i.e. the glyph outlines (slow).
func (t *Text) OutlineBounds() Rect {
if len(t.lines) == 0 || len(t.lines[0].spans) == 0 {
return Rect{}
}
r := Rect{}
for _, line := range t.lines {
for _, span := range line.spans {
// TODO: vertical text
p, _, err := span.Face.GlyphsToPath(span.Glyphs, span.Face.PPEM(DefaultResolution))
if err != nil {
panic(err)
}
spanBounds := p.Bounds()
spanBounds = spanBounds.Move(Point{span.x, -line.y})
r = r.Add(spanBounds)
}
}
t.WalkDecorations(func(col color.RGBA, p *Path) {
r = r.Add(p.Bounds())
})
return r
}
// Fonts returns the list of fonts used.
func (t *Text) Fonts() []*Font {
fonts := []*Font{}
fontNames := []string{}
fontMap := map[string]*Font{}
for font := range t.fonts {
name := font.Name()
fontNames = append(fontNames, name)
fontMap[name] = font
}
sort.Strings(fontNames)
for _, name := range fontNames {
fonts = append(fonts, fontMap[name])
}
return fonts
}
// MostCommonFontFace returns the most common FontFace of the text.
func (t *Text) MostCommonFontFace() *FontFace {
fonts := map[*Font]int{}
sizes := map[float64]int{}
styles := map[FontStyle]int{}
variants := map[FontVariant]int{}
colors := map[color.RGBA]int{}
for _, line := range t.lines {
for _, span := range line.spans {
fonts[span.Face.Font]++
sizes[span.Face.Size]++
styles[span.Face.Style]++
variants[span.Face.Variant]++
colors[span.Face.Color]++
}
}
if len(fonts) == 0 {
return nil
}
font, size, style, variant, col := (*Font)(nil), 0.0, FontRegular, FontNormal, Black
for key, val := range fonts {
if fonts[font] < val {
font = key
}
}
for key, val := range sizes {
if sizes[size] < val {
size = key
}
}
for key, val := range styles {
if styles[style] < val {
style = key
}
}
for key, val := range variants {
if variants[variant] < val {
variant = key
}
}
for key, val := range colors {
if colors[col] < val {
col = key
}
}
face := font.Face(size, col)
face.Style = style
face.Variant = variant
return face
}
type decorationSpan struct {
deco FontDecorator
col color.RGBA
x float64
width float64
face *FontFace // biggest face
}
// WalkDecorations calls the callback for each color of decoration used per line.
func (t *Text) WalkDecorations(callback func(col color.RGBA, deco *Path)) {
// TODO: vertical text
// accumulate paths with colors for all lines
cs := []color.RGBA{}
ps := []*Path{}
for _, line := range t.lines {
// track active decorations, when finished draw and append to accumulated paths
active := []decorationSpan{}
for k, span := range line.spans {
foundActive := make([]bool, len(active))
for _, spanDeco := range span.Face.Deco {
found := false
for i, deco := range active {
if span.Face.Color == deco.col && reflect.DeepEqual(deco.deco, spanDeco) {
// extend decoration
active[i].width = span.x + span.Width - active[i].x
if active[i].face.Size < span.Face.Size {
active[i].face = span.Face
}
foundActive[i] = true
found = true
break
}
}
if !found {
// add new decoration
active = append(active, decorationSpan{
deco: spanDeco,
col: span.Face.Color,
x: span.x,
width: span.Width,
face: span.Face,
})
}
}
if k == len(line.spans)-1 {
foundActive = make([]bool, len(active))
}
di := 0
for i, found := range foundActive {
if !found {
// remove active decoration and draw it
decoSpan := active[i-di]
xOffset := span.Face.mmPerEm * float64(span.Face.XOffset)
yOffset := span.Face.mmPerEm * float64(span.Face.YOffset)
p := decoSpan.deco.Decorate(decoSpan.face, decoSpan.width)
p = p.Translate(decoSpan.x+xOffset, -line.y+yOffset)
foundColor := false
for j, col := range cs {
if col == decoSpan.col {
ps[j] = ps[j].Append(p)
foundColor = true
}
}
if !foundColor {
cs = append(cs, decoSpan.col)
ps = append(ps, p)
}
active = append(active[:i-di], active[i-di+1:]...)
di++
}
}
}
}
for i := 0; i < len(ps); i++ {
callback(cs[i], ps[i])
}
}
// WalkSpans calls the callback for each text span per line.
func (t *Text) WalkSpans(callback func(x, y float64, span TextSpan)) {
for _, line := range t.lines {
for _, span := range line.spans {
xOffset := span.Face.mmPerEm * float64(span.Face.XOffset)
yOffset := span.Face.mmPerEm * float64(span.Face.YOffset)
if t.Mode == HorizontalTB {
callback(span.x+xOffset, -line.y+yOffset, span)
} else {
callback(line.y+xOffset, -span.x+yOffset, span)
}
}
}
}
// RenderAsPath renders the text and its decorations converted to paths, calling r.RenderPath.
func (t *Text) RenderAsPath(r Renderer, m Matrix, resolution Resolution) {
t.WalkDecorations(func(col color.RGBA, p *Path) {
style := DefaultStyle
style.FillColor = col
r.RenderPath(p, style, m)
})
for _, line := range t.lines {
for _, span := range line.spans {
x, y := span.x, -line.y
if t.Mode != HorizontalTB {
x, y = line.y, -span.x
}
style := DefaultStyle
style.FillColor = span.Face.Color
p, _, err := span.Face.GlyphsToPath(span.Glyphs, span.Face.PPEM(resolution))
if err != nil {
panic(err)
}
p = p.Translate(x, y)
r.RenderPath(p, style, m)
}
}
}