Debian Codegraph @

shiny/text/text.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package text lays out paragraphs of text.
6 //
7 // A body of text is laid out into a Frame: Frames contain Paragraphs (stacked
8 // vertically), Paragraphs contain Lines (stacked vertically), and Lines
9 // contain Boxes (stacked horizontally). Each Box holds a []byte slice of the
10 // text. For example, to simply print a Frame's text from start to finish:
11 //
12 // var f *text.Frame = etc
13 // for p := f.FirstParagraph(); p != nil; p = p.Next(f) {
14 // for l := p.FirstLine(f); l != nil; l = l.Next(f) {
15 // for b := l.FirstBox(f); b != nil; b = b.Next(f) {
16 // fmt.Print(b.Text(f))
17 // }
18 // }
19 // }
20 //
21 // A Frame's structure (the tree of Paragraphs, Lines and Boxes), and its
22 // []byte text, are not modified directly. Instead, a Frame's maximum width can
23 // be re-sized, and text can be added and removed via Carets (which implement
24 // standard io interfaces). For example, to add some words to the end of a
25 // frame:
26 //
27 // var f *text.Frame = etc
28 // c := f.NewCaret()
29 // c.Seek(0, text.SeekEnd)
30 // c.WriteString("Not with a bang but a whimper.\n")
31 // c.Close()
32 //
33 // Either way, such modifications can cause re-layout, which can add or remove
34 // Paragraphs, Lines and Boxes. The underlying memory for such structs can be
35 // reused, so pointer values, such as of type *Box, should not be held over
36 // such modifications.
37 package text // import "golang.org/x/exp/shiny/text"
38
39 import (
40 "io"
41 "unicode/utf8"
42
43 "golang.org/x/image/font"
44 "golang.org/x/image/math/fixed"
45 )
46
47 // Direction is either forwards or backwards.
48 type Direction bool
49
50 const (
51 Forwards Direction = false
52 Backwards Direction = true
53 )
54
55 // These constants are equal to os.SEEK_SET, os.SEEK_CUR and os.SEEK_END,
56 // understood by the io.Seeker interface, and are provided so that users of
57 // this package don't have to explicitly import "os".
58 const (
59 SeekSet int = 0
60 SeekCur int = 1
61 SeekEnd int = 2
62 )
63
64 // maxLen is maximum (inclusive) value of len(Frame.text) and therefore of
65 // Box.i, Box.j and Caret.k.
66 const maxLen = 0x7fffffff
67
68 // Frame holds Paragraphs of text.
69 //
70 // The zero value is a valid Frame of empty text, which contains one Paragraph,
71 // which contains one Line, which contains one Box.
72 type Frame struct {
73 // These slices hold the Frame's Paragraphs, Lines and Boxes, indexed by
74 // fields such as Paragraph.firstL and Box.next.
75 //
76 // Their contents are not necessarily in layout order. Each slice is
77 // obviously backed by an array, but a Frame's list of children
78 // (Paragraphs) forms a doubly-linked list, not an array list, so that
79 // insertion has lower algorithmic complexity. Similarly for a Paragraph's
80 // list of children (Lines) and a Line's list of children (Boxes).
81 //
82 // The 0'th index into each slice is a special case. Otherwise, each
83 // element is either in use (forming a double linked list with its
84 // siblings) or in a free list (forming a single linked list; the prev
85 // field is -1).
86 //
87 // A zero firstFoo field means that the parent holds a single, implicit
88 // (lazily allocated), empty-but-not-nil *Foo child. Every Frame contains
89 // at least one Paragraph. Similarly, every Paragraph contains at least one
90 // Line, and every Line contains at least one Box.
91 //
92 // A zero next or prev field means that there is no such sibling (for an
93 // in-use Paragraph, Line or Box) or no such next free element (if in the
94 // free list).
95 paragraphs []Paragraph
96 lines []Line
97 boxes []Box
98
99 // These values cache the total height-in-pixels of or the number of
100 // elements in the paragraphs or lines linked lists. The plus one is so
101 // that the zero value means the cache is invalid.
102 cachedHeightPlus1 int32
103 cachedLineCountPlus1 int32
104 cachedParagraphCountPlus1 int32
105
106 // freeX is the index of the first X (Paragraph, Line or Box) in the
107 // respective free list. Zero means that there is no such free element.
108 freeP, freeL, freeB int32
109
110 firstP int32
111
112 maxWidth fixed.Int26_6
113
114 faceHeight int32
115 face font.Face
116
117 // len is the total length of the Frame's current textual content, in
118 // bytes. It can be smaller then len(text), since that []byte can contain
119 // 'holes' of deleted content.
120 //
121 // Like the paragraphs, lines and boxes slice-typed fields above, the text
122 // []byte does not necessarily hold the textual content in layout order.
123 // Instead, it holds the content in edit (insertion) order, with occasional
124 // compactions. Again, the algorithmic complexity of insertions matters.
125 len int
126 text []byte
127
128 // seqNum is a sequence number that is incremented every time the Frame's
129 // text or layout is modified. It lets us detect whether a Caret's cached
130 // p, l, b and k fields are stale.
131 seqNum uint64
132
133 carets []*Caret
134
135 // lineReaderData supports the Frame's lineReader, used when reading a
136 // Line's text one rune at a time.
137 lineReaderData bAndK
138 }
139
140 // TODO: allow multiple font faces, i.e. rich text?
141
142 // SetFace sets the font face for measuring text.
143 func (f *Frame) SetFace(face font.Face) {
144 if !f.initialized() {
145 f.initialize()
146 }
147 f.face = face
148 if face == nil {
149 f.faceHeight = 0
150 } else {
151 // We round up the ascent and descent separately, instead of asking for
152 // the metrics' height, since we quantize the baseline to the integer
153 // pixel grid. For example, if ascent and descent were both 3.2 pixels,
154 // then the naive height would be 6.4, which rounds up to 7, but we
155 // should really provide 8 pixels (= ceil(3.2) + ceil(3.2)) between
156 // each line to avoid overlap.
157 //
158 // TODO: is a font.Metrics.Height actually useful in practice??
159 //
160 // TODO: is it the font face's responsibility to track line spacing, as
161 // in "double line spacing", or does that belong somewhere else, since
162 // it doesn't affect the face's glyph masks?
163 m := face.Metrics()
164 f.faceHeight = int32(m.Ascent.Ceil() + m.Descent.Ceil())
165 }
166 if f.len != 0 {
167 f.relayout()
168 }
169 }
170
171 // TODO: should SetMaxWidth take an int number of pixels instead of a
172 // fixed.Int26_6 number of sub-pixels? Height returns an int, since it assumes
173 // that the text baselines are quantized to the integer pixel grid.
174
175 // SetMaxWidth sets the target maximum width of a Line of text, as a
176 // fixed-point fractional number of pixels. Text will be broken so that a
177 // Line's width is less than or equal to this maximum width. This line breaking
178 // is not strict. A Line containing asingleverylongword combined with a narrow
179 // maximum width will not be broken and will remain longer than the target
180 // maximum width; soft hyphens are not inserted.
181 //
182 // A non-positive argument is treated as an infinite maximum width.
183 func (f *Frame) SetMaxWidth(m fixed.Int26_6) {
184 if !f.initialized() {
185 f.initialize()
186 }
187 if f.maxWidth == m {
188 return
189 }
190 f.maxWidth = m
191 if f.len != 0 {
192 f.relayout()
193 }
194 }
195
196 func (f *Frame) relayout() {
197 for p := f.firstP; p != 0; p = f.paragraphs[p].next {
198 l := f.mergeIntoOneLine(p)
199 layout(f, l)
200 }
201 f.invalidateCaches()
202 f.seqNum++
203 }
204
205 // mergeIntoOneLine merges all of a Paragraph's Lines into a single Line, and
206 // compacts its empty and otherwise joinable Boxes. It returns the index of
207 // that Line.
208 func (f *Frame) mergeIntoOneLine(p int32) (l int32) {
209 firstL := f.paragraphs[p].firstL
210 ll := &f.lines[firstL]
211 b0 := ll.firstB
212 bb0 := &f.boxes[b0]
213 for {
214 if b1 := bb0.next; b1 != 0 {
215 bb1 := &f.boxes[b1]
216 if !f.joinBoxes(b0, b1, bb0, bb1) {
217 b0, bb0 = b1, bb1
218 }
219 continue
220 }
221
222 if ll.next == 0 {
223 f.paragraphs[p].invalidateCaches()
224 f.lines[firstL].invalidateCaches()
225 return firstL
226 }
227
228 // Unbreak the Line.
229 nextLL := &f.lines[ll.next]
230 b1 := nextLL.firstB
231 bb1 := &f.boxes[b1]
232 bb0.next = b1
233 bb1.prev = b0
234
235 toFree := ll.next
236 ll.next = nextLL.next
237 // There's no need to fix up f.lines[ll.next].prev since it will just
238 // be freed later in the loop.
239 f.freeLine(toFree)
240 }
241 }
242
243 // joinBoxes joins two adjacent Boxes if the Box.j field of the first one
244 // equals the Box.i field of the second, or at least one of them is empty. It
245 // returns whether they were joined. If they were joined, the second of the two
246 // Boxes is freed.
247 func (f *Frame) joinBoxes(b0, b1 int32, bb0, bb1 *Box) bool {
248 switch {
249 case bb0.i == bb0.j:
250 // The first Box is empty. Replace its i/j with the second one's.
251 bb0.i, bb0.j = bb1.i, bb1.j
252 case bb1.i == bb1.j:
253 // The second box is empty. Drop it.
254 case bb0.j == bb1.i:
255 // The two non-empty Boxes are joinable.
256 bb0.j = bb1.j
257 default:
258 return false
259 }
260 bb0.next = bb1.next
261 if bb0.next != 0 {
262 f.boxes[bb0.next].prev = b0
263 }
264 f.freeBox(b1)
265 return true
266 }
267
268 func (f *Frame) initialized() bool {
269 return len(f.paragraphs) > 0
270 }
271
272 func (f *Frame) initialize() {
273 // The first valid Paragraph, Line and Box all have index 1. The 0'th index
274 // of each slice is a special case.
275 f.paragraphs = make([]Paragraph, 2, 16)
276 f.lines = make([]Line, 2, 16)
277 f.boxes = make([]Box, 2, 16)
278
279 f.firstP = 1
280 f.paragraphs[1].firstL = 1
281 f.lines[1].firstB = 1
282 }
283
284 // newParagraph returns the index of an empty Paragraph, and whether or not the
285 // underlying memory has been re-allocated. Re-allocation means that any
286 // existing *Paragraph pointers become invalid.
287 func (f *Frame) newParagraph() (p int32, realloc bool) {
288 if f.freeP != 0 {
289 p := f.freeP
290 pp := &f.paragraphs[p]
291 f.freeP = pp.next
292 *pp = Paragraph{}
293 return p, false
294 }
295 realloc = len(f.paragraphs) == cap(f.paragraphs)
296 f.paragraphs = append(f.paragraphs, Paragraph{})
297 return int32(len(f.paragraphs) - 1), realloc
298 }
299
300 // newLine returns the index of an empty Line, and whether or not the
301 // underlying memory has been re-allocated. Re-allocation means that any
302 // existing *Line pointers become invalid.
303 func (f *Frame) newLine() (l int32, realloc bool) {
304 if f.freeL != 0 {
305 l := f.freeL
306 ll := &f.lines[l]
307 f.freeL = ll.next
308 *ll = Line{}
309 return l, false
310 }
311 realloc = len(f.lines) == cap(f.lines)
312 f.lines = append(f.lines, Line{})
313 return int32(len(f.lines) - 1), realloc
314 }
315
316 // newBox returns the index of an empty Box, and whether or not the underlying
317 // memory has been re-allocated. Re-allocation means that any existing *Box
318 // pointers become invalid.
319 func (f *Frame) newBox() (b int32, realloc bool) {
320 if f.freeB != 0 {
321 b := f.freeB
322 bb := &f.boxes[b]
323 f.freeB = bb.next
324 *bb = Box{}
325 return b, false
326 }
327 realloc = len(f.boxes) == cap(f.boxes)
328 f.boxes = append(f.boxes, Box{})
329 return int32(len(f.boxes) - 1), realloc
330 }
331
332 func (f *Frame) freeParagraph(p int32) {
333 f.paragraphs[p] = Paragraph{next: f.freeP, prev: -1}
334 f.freeP = p
335 // TODO: run a compaction if the free-list is too large?
336 }
337
338 func (f *Frame) freeLine(l int32) {
339 f.lines[l] = Line{next: f.freeL, prev: -1}
340 f.freeL = l
341 // TODO: run a compaction if the free-list is too large?
342 }
343
344 func (f *Frame) freeBox(b int32) {
345 f.boxes[b] = Box{next: f.freeB, prev: -1}
346 f.freeB = b
347 // TODO: run a compaction if the free-list is too large?
348 }
349
350 func (f *Frame) lastParagraph() int32 {
351 for p := f.firstP; ; {
352 if next := f.paragraphs[p].next; next != 0 {
353 p = next
354 continue
355 }
356 return p
357 }
358 }
359
360 // FirstParagraph returns the first paragraph of this frame.
361 func (f *Frame) FirstParagraph() *Paragraph {
362 if !f.initialized() {
363 f.initialize()
364 }
365 return &f.paragraphs[f.firstP]
366 }
367
368 func (f *Frame) invalidateCaches() {
369 f.cachedHeightPlus1 = 0
370 f.cachedLineCountPlus1 = 0
371 f.cachedParagraphCountPlus1 = 0
372 }
373
374 // Height returns the height in pixels of this Frame.
375 func (f *Frame) Height() int {
376 if !f.initialized() {
377 f.initialize()
378 }
379 if f.cachedHeightPlus1 <= 0 {
380 h := 1
381 for p := f.firstP; p != 0; p = f.paragraphs[p].next {
382 h += f.paragraphs[p].Height(f)
383 }
384 f.cachedHeightPlus1 = int32(h)
385 }
386 return int(f.cachedHeightPlus1 - 1)
387 }
388
389 // LineCount returns the number of Lines in this Frame.
390 //
391 // This count includes any soft returns inserted to wrap text to the maxWidth.
392 func (f *Frame) LineCount() int {
393 if !f.initialized() {
394 f.initialize()
395 }
396 if f.cachedLineCountPlus1 <= 0 {
397 n := 1
398 for p := f.firstP; p != 0; p = f.paragraphs[p].next {
399 n += f.paragraphs[p].LineCount(f)
400 }
401 f.cachedLineCountPlus1 = int32(n)
402 }
403 return int(f.cachedLineCountPlus1 - 1)
404 }
405
406 // ParagraphCount returns the number of Paragraphs in this Frame.
407 //
408 // This count excludes any soft returns inserted to wrap text to the maxWidth.
409 func (f *Frame) ParagraphCount() int {
410 if !f.initialized() {
411 f.initialize()
412 }
413 if f.cachedParagraphCountPlus1 <= 0 {
414 n := 1
415 for p := f.firstP; p != 0; p = f.paragraphs[p].next {
416 n++
417 }
418 f.cachedParagraphCountPlus1 = int32(n)
419 }
420 return int(f.cachedParagraphCountPlus1 - 1)
421 }
422
423 // Len returns the number of bytes in the Frame's text.
424 func (f *Frame) Len() int {
425 // We would normally check f.initialized() at the start of each exported
426 // method of a Frame, but that is not necessary here. The Frame's text's
427 // length does not depend on its Paragraphs, Lines and Boxes.
428 return f.len
429 }
430
431 // deletedLen returns the number of deleted bytes in the Frame's text.
432 func (f *Frame) deletedLen() int {
433 return len(f.text) - f.len
434 }
435
436 func (f *Frame) compactText() {
437 // f.text contains f.len live bytes and len(f.text) - f.len deleted bytes.
438 // After the compaction, the new f.text slice's capacity should be at least
439 // f.len, to hold all of the live bytes, but also be below len(f.text) to
440 // allow total memory use to decrease. The actual value used (halfway
441 // between them) is arbitrary. A lower value means less up-front memory
442 // consumption but a lower threshold for re-allocating the f.text slice
443 // upon further writes, such as a paste immediately after a cut. A higher
444 // value means the opposite.
445 newText := make([]byte, 0, f.len+f.deletedLen()/2)
446 for p := f.firstP; p != 0; {
447 pp := &f.paragraphs[p]
448 for l := pp.firstL; l != 0; {
449 ll := &f.lines[l]
450
451 i := int32(len(newText))
452 for b := ll.firstB; b != 0; {
453 bb := &f.boxes[b]
454 newText = append(newText, f.text[bb.i:bb.j]...)
455 nextB := bb.next
456 f.freeBox(b)
457 b = nextB
458 }
459 j := int32(len(newText))
460 ll.firstB, _ = f.newBox()
461 bb := &f.boxes[ll.firstB]
462 bb.i, bb.j = i, j
463
464 l = ll.next
465 }
466 p = pp.next
467 }
468 f.text = newText
469 if len(newText) != f.len {
470 panic("text: invalid state")
471 }
472 }
473
474 // NewCaret returns a new Caret at the start of this Frame.
475 func (f *Frame) NewCaret() *Caret {
476 if !f.initialized() {
477 f.initialize()
478 }
479 // Make the first Paragraph, Line and Box explicit, since Carets require an
480 // explicit p, l and b.
481 p := f.FirstParagraph()
482 l := p.FirstLine(f)
483 b := l.FirstBox(f)
484 c := &Caret{
485 f: f,
486 p: f.firstP,
487 l: p.firstL,
488 b: l.firstB,
489 k: b.i,
490 caretsIndex: len(f.carets),
491 }
492 f.carets = append(f.carets, c)
493 return c
494 }
495
496 // readRune returns the next rune and its size in bytes, starting from the Box
497 // indexed by b and the text in that Box indexed by k. It also returns the new
498 // b and k indexes after reading size bytes. The b argument must not be zero,
499 // and the newB return value will not be zero.
500 //
501 // It can cross Box boundaries, but not Line boundaries, in finding the next
502 // rune.
503 func (f *Frame) readRune(b, k int32) (r rune, size int, newB, newK int32) {
504 bb := &f.boxes[b]
505
506 // In the fastest, common case, see if we can read a rune without crossing
507 // a Box boundary.
508 r, size = utf8.DecodeRune(f.text[k:bb.j])
509 if r < utf8.RuneSelf || size > 1 {
510 return r, size, b, k + int32(size)
511 }
512
513 // Otherwise, we decoded invalid UTF-8, possibly because a valid UTF-8 rune
514 // straddled this Box and the next one. Try again, copying up to
515 // utf8.UTFMax bytes from multiple Boxes into a single contiguous buffer.
516 buf := [utf8.UTFMax]byte{}
517 newBAndKs := [utf8.UTFMax + 1]bAndK{
518 0: bAndK{b, k},
519 }
520 n := int32(0)
521 for {
522 if k < bb.j {
523 nCopied := int32(copy(buf[n:], f.text[k:bb.j]))
524 for i := int32(1); i <= nCopied; i++ {
525 newBAndKs[n+i] = bAndK{b, k + i}
526 }
527 n += nCopied
528 if n == utf8.UTFMax {
529 break
530 }
531 }
532 b = bb.next
533 if b == 0 {
534 break
535 }
536 bb = &f.boxes[b]
537 k = bb.i
538 }
539 r, size = utf8.DecodeRune(buf[:n])
540 bk := newBAndKs[size]
541 if bk.b == 0 {
542 panic("text: invalid state")
543 }
544 return r, size, bk.b, bk.k
545 }
546
547 // readLastRune is like readRune but it reads the last rune before b-and-k
548 // instead of the first rune after.
549 func (f *Frame) readLastRune(b, k int32) (r rune, size int, newB, newK int32) {
550 bb := &f.boxes[b]
551
552 // In the fastest, common case, see if we can read a rune without crossing
553 // a Box boundary.
554 r, size = utf8.DecodeLastRune(f.text[bb.i:k])
555 if r < utf8.RuneSelf || size > 1 {
556 return r, size, b, k - int32(size)
557 }
558
559 // Otherwise, we decoded invalid UTF-8, possibly because a valid UTF-8 rune
560 // straddled this Box and the previous one. Try again, copying up to
561 // utf8.UTFMax bytes from multiple Boxes into a single contiguous buffer.
562 buf := [utf8.UTFMax]byte{}
563 newBAndKs := [utf8.UTFMax + 1]bAndK{
564 utf8.UTFMax: bAndK{b, k},
565 }
566 n := int32(utf8.UTFMax)
567 for {
568 if k < bb.j {
569 nCopied := k - bb.i
570 if nCopied > n {
571 nCopied = n
572 }
573 copy(buf[n-nCopied:n], f.text[k-nCopied:k])
574 for i := int32(1); i <= nCopied; i++ {
575 newBAndKs[n-i] = bAndK{b, k - i}
576 }
577 n -= nCopied
578 if n == 0 {
579 break
580 }
581 }
582 b = bb.prev
583 if b == 0 {
584 break
585 }
586 bb = &f.boxes[b]
587 k = bb.j
588 }
589 r, size = utf8.DecodeLastRune(buf[n:])
590 bk := newBAndKs[utf8.UTFMax-size]
591 if bk.b == 0 {
592 panic("text: invalid state")
593 }
594 return r, size, bk.b, bk.k
595 }
596
597 func (f *Frame) lineReader(b, k int32) lineReader {
598 f.lineReaderData.b = b
599 f.lineReaderData.k = k
600 return lineReader{f}
601 }
602
603 // bAndK is a text position k within a Box b. The k is analogous to the Caret.k
604 // field. For a bAndK x, letting bb := Frame.boxes[x.b], an invariant is that
605 // bb.i <= x.k && x.k <= bb.j.
606 type bAndK struct {
607 b int32
608 k int32
609 }
610
611 // lineReader is an io.RuneReader for a Line of text, from its current position
612 // (a bAndK) up until the end of the Line containing that Box.
613 //
614 // A Frame can have only one active lineReader at any one time. To avoid
615 // excessive memory allocation and garbage collection, the lineReader's data is
616 // a field of the Frame struct and reused.
617 type lineReader struct{ f *Frame }
618
619 func (z lineReader) bAndK() bAndK {
620 return z.f.lineReaderData
621 }
622
623 func (z lineReader) ReadRune() (r rune, size int, err error) {
624 d := &z.f.lineReaderData
625 for d.b != 0 {
626 bb := &z.f.boxes[d.b]
627 if d.k < bb.j {
628 r, size, d.b, d.k = z.f.readRune(d.b, d.k)
629 return r, size, nil
630 }
631 d.b = bb.next
632 d.k = z.f.boxes[d.b].i
633 }
634 return 0, 0, io.EOF
635 }
636
637 // Paragraph holds Lines of text.
638 type Paragraph struct {
639 firstL, next, prev int32
640 cachedHeightPlus1 int32
641 cachedLineCountPlus1 int32
642 }
643
644 func (p *Paragraph) lastLine(f *Frame) int32 {
645 for l := p.firstL; ; {
646 if next := f.lines[l].next; next != 0 {
647 l = next
648 continue
649 }
650 return l
651 }
652 }
653
654 // FirstLine returns the first Line of this Paragraph.
655 //
656 // f is the Frame that contains the Paragraph.
657 func (p *Paragraph) FirstLine(f *Frame) *Line {
658 return &f.lines[p.firstL]
659 }
660
661 // Next returns the next Paragraph after this one in the Frame.
662 //
663 // f is the Frame that contains the Paragraph.
664 func (p *Paragraph) Next(f *Frame) *Paragraph {
665 if p.next == 0 {
666 return nil
667 }
668 return &f.paragraphs[p.next]
669 }
670
671 func (p *Paragraph) invalidateCaches() {
672 p.cachedHeightPlus1 = 0
673 p.cachedLineCountPlus1 = 0
674 }
675
676 // Height returns the height in pixels of this Paragraph.
677 func (p *Paragraph) Height(f *Frame) int {
678 if p.cachedHeightPlus1 <= 0 {
679 h := 1
680 for l := p.firstL; l != 0; l = f.lines[l].next {
681 h += f.lines[l].Height(f)
682 }
683 p.cachedHeightPlus1 = int32(h)
684 }
685 return int(p.cachedHeightPlus1 - 1)
686 }
687
688 // LineCount returns the number of Lines in this Paragraph.
689 //
690 // This count includes any soft returns inserted to wrap text to the maxWidth.
691 func (p *Paragraph) LineCount(f *Frame) int {
692 if p.cachedLineCountPlus1 <= 0 {
693 n := 1
694 for l := p.firstL; l != 0; l = f.lines[l].next {
695 n++
696 }
697 p.cachedLineCountPlus1 = int32(n)
698 }
699 return int(p.cachedLineCountPlus1 - 1)
700 }
701
702 // Line holds Boxes of text.
703 type Line struct {
704 firstB, next, prev int32
705 cachedHeightPlus1 int32
706 }
707
708 func (l *Line) lastBox(f *Frame) int32 {
709 for b := l.firstB; ; {
710 if next := f.boxes[b].next; next != 0 {
711 b = next
712 continue
713 }
714 return b
715 }
716 }
717
718 // FirstBox returns the first Box of this Line.
719 //
720 // f is the Frame that contains the Line.
721 func (l *Line) FirstBox(f *Frame) *Box {
722 return &f.boxes[l.firstB]
723 }
724
725 // Next returns the next Line after this one in the Paragraph.
726 //
727 // f is the Frame that contains the Line.
728 func (l *Line) Next(f *Frame) *Line {
729 if l.next == 0 {
730 return nil
731 }
732 return &f.lines[l.next]
733 }
734
735 func (l *Line) invalidateCaches() {
736 l.cachedHeightPlus1 = 0
737 }
738
739 // Height returns the height in pixels of this Line.
740 func (l *Line) Height(f *Frame) int {
741 // TODO: measure the height of each box, if we allow rich text (i.e. more
742 // than one Frame-wide font face).
743 if f.face == nil {
744 return 0
745 }
746 if l.cachedHeightPlus1 <= 0 {
747 l.cachedHeightPlus1 = f.faceHeight + 1
748 }
749 return int(l.cachedHeightPlus1 - 1)
750 }
751
752 // Box holds a contiguous run of text.
753 type Box struct {
754 next, prev int32
755 // Frame.text[i:j] holds this Box's text.
756 i, j int32
757 }
758
759 // Next returns the next Box after this one in the Line.
760 //
761 // f is the Frame that contains the Box.
762 func (b *Box) Next(f *Frame) *Box {
763 if b.next == 0 {
764 return nil
765 }
766 return &f.boxes[b.next]
767 }
768
769 // Text returns the Box's text.
770 //
771 // f is the Frame that contains the Box.
772 func (b *Box) Text(f *Frame) []byte {
773 return f.text[b.i:b.j]
774 }
775
776 // TrimmedText returns the Box's text, trimmed right of any white space if it
777 // is the last Box in its Line.
778 //
779 // f is the Frame that contains the Box.
780 func (b *Box) TrimmedText(f *Frame) []byte {
781 s := f.text[b.i:b.j]
782 if b.next == 0 {
783 for len(s) > 0 && s[len(s)-1] <= ' ' {
784 s = s[:len(s)-1]
785 }
786 }
787 return s
788 }