richtext.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. package widget
  2. import (
  3. "image/color"
  4. "math"
  5. "strings"
  6. "sync"
  7. "unicode"
  8. "fyne.io/fyne/v2"
  9. "fyne.io/fyne/v2/canvas"
  10. "fyne.io/fyne/v2/internal/cache"
  11. "fyne.io/fyne/v2/internal/widget"
  12. "fyne.io/fyne/v2/layout"
  13. "fyne.io/fyne/v2/theme"
  14. )
  15. const (
  16. passwordChar = "•"
  17. )
  18. // RichText represents the base element for a rich text-based widget.
  19. //
  20. // Since: 2.1
  21. type RichText struct {
  22. BaseWidget
  23. Segments []RichTextSegment
  24. Wrapping fyne.TextWrap
  25. Scroll widget.ScrollDirection
  26. inset fyne.Size // this varies due to how the widget works (entry with scroller vs others with padding)
  27. rowBounds []rowBoundary // cache for boundaries
  28. scr *widget.Scroll
  29. prop *canvas.Rectangle // used to apply text minsize to the scroller `scr`, if present - TODO improve #2464
  30. visualCache map[RichTextSegment][]fyne.CanvasObject
  31. cacheLock sync.Mutex
  32. minCache fyne.Size
  33. }
  34. // NewRichText returns a new RichText widget that renders the given text and segments.
  35. // If no segments are specified it will be converted to a single segment using the default text settings.
  36. //
  37. // Since: 2.1
  38. func NewRichText(segments ...RichTextSegment) *RichText {
  39. t := &RichText{Segments: segments}
  40. t.Scroll = widget.ScrollNone
  41. t.updateRowBounds()
  42. return t
  43. }
  44. // NewRichTextWithText returns a new RichText widget that renders the given text.
  45. // The string will be converted to a single text segment using the default text settings.
  46. //
  47. // Since: 2.1
  48. func NewRichTextWithText(text string) *RichText {
  49. return NewRichText(&TextSegment{
  50. Style: RichTextStyleInline,
  51. Text: text,
  52. })
  53. }
  54. // CreateRenderer is a private method to Fyne which links this widget to its renderer
  55. func (t *RichText) CreateRenderer() fyne.WidgetRenderer {
  56. if t.scr == nil && t.Scroll != widget.ScrollNone {
  57. t.prop = canvas.NewRectangle(color.Transparent)
  58. t.scr = widget.NewScroll(&fyne.Container{Layout: layout.NewMaxLayout(), Objects: []fyne.CanvasObject{
  59. t.prop, &fyne.Container{}}})
  60. }
  61. t.ExtendBaseWidget(t)
  62. r := &textRenderer{obj: t}
  63. t.updateRowBounds() // set up the initial text layout etc
  64. r.Refresh()
  65. return r
  66. }
  67. // MinSize calculates the minimum size of a rich text widget.
  68. // This is based on the contained text with a standard amount of padding added.
  69. func (t *RichText) MinSize() fyne.Size {
  70. // we don't return the minCache here, as any internal segments could have caused it to change...
  71. t.ExtendBaseWidget(t)
  72. min := t.BaseWidget.MinSize()
  73. t.minCache = min
  74. return min
  75. }
  76. // Refresh triggers a redraw of the rich text.
  77. //
  78. // Implements: fyne.Widget
  79. func (t *RichText) Refresh() {
  80. t.minCache = fyne.Size{}
  81. t.updateRowBounds()
  82. t.BaseWidget.Refresh()
  83. }
  84. // Resize sets a new size for the rich text.
  85. // This should only be called if it is not in a container with a layout manager.
  86. //
  87. // Implements: fyne.Widget
  88. func (t *RichText) Resize(size fyne.Size) {
  89. t.propertyLock.RLock()
  90. baseSize := t.size
  91. segments := t.Segments
  92. skipResize := !t.minCache.IsZero() && size.Width >= t.minCache.Width && size.Height >= t.minCache.Height && t.Wrapping == fyne.TextWrapOff
  93. t.propertyLock.RUnlock()
  94. if baseSize == size {
  95. return
  96. }
  97. t.propertyLock.Lock()
  98. t.size = size
  99. t.propertyLock.Unlock()
  100. if skipResize {
  101. if len(segments) < 2 { // we can simplify :)
  102. cache.Renderer(t).Layout(size)
  103. return
  104. }
  105. }
  106. t.updateRowBounds()
  107. t.Refresh()
  108. }
  109. // String returns the text widget buffer as string
  110. func (t *RichText) String() string {
  111. ret := strings.Builder{}
  112. for _, seg := range t.Segments {
  113. ret.WriteString(seg.Textual())
  114. }
  115. return ret.String()
  116. }
  117. // CharMinSize returns the average char size to use for internal computation
  118. func (t *RichText) charMinSize(concealed bool, style fyne.TextStyle) fyne.Size {
  119. defaultChar := "M"
  120. if concealed {
  121. defaultChar = passwordChar
  122. }
  123. return fyne.MeasureText(defaultChar, theme.TextSize(), style)
  124. }
  125. // deleteFromTo removes the text between the specified positions
  126. func (t *RichText) deleteFromTo(lowBound int, highBound int) string {
  127. start := 0
  128. var ret []rune
  129. deleting := false
  130. var segs []RichTextSegment
  131. for i, seg := range t.Segments {
  132. if _, ok := seg.(*TextSegment); !ok {
  133. if !deleting {
  134. segs = append(segs, seg)
  135. }
  136. continue
  137. }
  138. end := start + len([]rune(seg.(*TextSegment).Text))
  139. if end < lowBound {
  140. segs = append(segs, seg)
  141. start = end
  142. continue
  143. }
  144. startOff := int(math.Max(float64(lowBound-start), 0))
  145. endOff := int(math.Min(float64(end), float64(highBound))) - start
  146. deleted := make([]rune, endOff-startOff)
  147. r := ([]rune)(seg.(*TextSegment).Text)
  148. copy(deleted, r[startOff:endOff])
  149. ret = append(ret, deleted...)
  150. r2 := append(r[:startOff], r[endOff:]...)
  151. seg.(*TextSegment).Text = string(r2)
  152. segs = append(segs, seg)
  153. // prepare next iteration
  154. start = end
  155. if start >= highBound {
  156. segs = append(segs, t.Segments[i+1:]...)
  157. break
  158. } else if start >= lowBound {
  159. deleting = true
  160. }
  161. }
  162. t.Segments = segs
  163. t.Refresh()
  164. return string(ret)
  165. }
  166. // cachedSegmentVisual returns a cached segment visual representation.
  167. // The offset value is > 0 if the segment had been split and so we need multiple objects.
  168. func (t *RichText) cachedSegmentVisual(seg RichTextSegment, offset int) fyne.CanvasObject {
  169. t.cacheLock.Lock()
  170. defer t.cacheLock.Unlock()
  171. if t.visualCache == nil {
  172. t.visualCache = make(map[RichTextSegment][]fyne.CanvasObject)
  173. }
  174. if vis, ok := t.visualCache[seg]; ok && offset < len(vis) {
  175. return vis[offset]
  176. }
  177. vis := seg.Visual()
  178. if offset < len(t.visualCache[seg]) {
  179. t.visualCache[seg][offset] = vis
  180. } else {
  181. t.visualCache[seg] = append(t.visualCache[seg], vis)
  182. }
  183. return vis
  184. }
  185. // insertAt inserts the text at the specified position
  186. func (t *RichText) insertAt(pos int, runes string) {
  187. index := 0
  188. start := 0
  189. var into *TextSegment
  190. for i, seg := range t.Segments {
  191. if _, ok := seg.(*TextSegment); !ok {
  192. continue
  193. }
  194. end := start + len([]rune(seg.(*TextSegment).Text))
  195. into = seg.(*TextSegment)
  196. index = i
  197. if end > pos {
  198. break
  199. }
  200. start = end
  201. }
  202. if into == nil {
  203. return
  204. }
  205. r := ([]rune)(into.Text)
  206. r2 := append(r[:pos], append([]rune(runes), r[pos:]...)...)
  207. into.Text = string(r2)
  208. t.Segments[index] = into
  209. t.Refresh()
  210. }
  211. // Len returns the text widget buffer length
  212. func (t *RichText) len() int {
  213. ret := 0
  214. for _, seg := range t.Segments {
  215. ret += len([]rune(seg.Textual()))
  216. }
  217. return ret
  218. }
  219. // lineSizeToColumn returns the rendered size for the line specified by row up to the col position
  220. func (t *RichText) lineSizeToColumn(col, row int) fyne.Size {
  221. if row < 0 {
  222. row = 0
  223. }
  224. if col < 0 {
  225. col = 0
  226. }
  227. bound := t.rowBoundary(row)
  228. total := fyne.NewSize(0, 0)
  229. counted := 0
  230. last := false
  231. for i, seg := range bound.segments {
  232. var size fyne.Size
  233. if text, ok := seg.(*TextSegment); ok {
  234. start := 0
  235. if i == 0 {
  236. start = bound.begin
  237. }
  238. measureText := []rune(text.Text)[start:]
  239. if col < counted+len(measureText) {
  240. measureText = measureText[0 : col-counted]
  241. last = true
  242. }
  243. if concealed(seg) {
  244. measureText = []rune(strings.Repeat(passwordChar, len(measureText)))
  245. }
  246. counted += len(measureText)
  247. label := canvas.NewText(string(measureText), color.Black)
  248. label.TextStyle = text.Style.TextStyle
  249. label.TextSize = text.size()
  250. size = label.MinSize()
  251. } else {
  252. size = t.cachedSegmentVisual(seg, 0).MinSize()
  253. }
  254. total.Width += size.Width
  255. total.Height = fyne.Max(total.Height, size.Height)
  256. if last {
  257. break
  258. }
  259. }
  260. return total.Add(fyne.NewSize(theme.InnerPadding()-t.inset.Width, 0))
  261. }
  262. // Row returns the characters in the row specified.
  263. // The row parameter should be between 0 and t.Rows()-1.
  264. func (t *RichText) row(row int) []rune {
  265. if row < 0 || row >= t.rows() {
  266. return nil
  267. }
  268. bound := t.rowBounds[row]
  269. var ret []rune
  270. for i, seg := range bound.segments {
  271. if text, ok := seg.(*TextSegment); ok {
  272. if i == 0 {
  273. if len(bound.segments) == 1 {
  274. ret = append(ret, []rune(text.Text)[bound.begin:bound.end]...)
  275. } else {
  276. ret = append(ret, []rune(text.Text)[bound.begin:]...)
  277. }
  278. } else if i == len(bound.segments)-1 && len(bound.segments) > 1 && bound.end != 0 {
  279. ret = append(ret, []rune(text.Text)[:bound.end]...)
  280. }
  281. }
  282. }
  283. return ret
  284. }
  285. // RowBoundary returns the boundary of the row specified.
  286. // The row parameter should be between 0 and t.Rows()-1.
  287. func (t *RichText) rowBoundary(row int) *rowBoundary {
  288. t.propertyLock.RLock()
  289. defer t.propertyLock.RUnlock()
  290. if row < 0 || row >= t.rows() {
  291. return nil
  292. }
  293. return &t.rowBounds[row]
  294. }
  295. // RowLength returns the number of visible characters in the row specified.
  296. // The row parameter should be between 0 and t.Rows()-1.
  297. func (t *RichText) rowLength(row int) int {
  298. return len(t.row(row))
  299. }
  300. // rows returns the number of text rows in this text entry.
  301. // The entry may be longer than required to show this amount of content.
  302. func (t *RichText) rows() int {
  303. return len(t.rowBounds)
  304. }
  305. // updateRowBounds updates the row bounds used to render properly the text widget.
  306. // updateRowBounds should be invoked every time a segment Text, widget Wrapping or size changes.
  307. func (t *RichText) updateRowBounds() {
  308. t.propertyLock.RLock()
  309. var bounds []rowBoundary
  310. innerPadding := theme.InnerPadding()
  311. maxWidth := t.size.Width - 2*innerPadding + 2*t.inset.Width
  312. wrapWidth := maxWidth
  313. var iterateSegments func(segList []RichTextSegment)
  314. iterateSegments = func(segList []RichTextSegment) {
  315. var currentBound *rowBoundary
  316. for _, seg := range segList {
  317. if parent, ok := seg.(RichTextBlock); ok {
  318. iterateSegments(parent.Segments())
  319. if !seg.Inline() {
  320. wrapWidth = maxWidth
  321. }
  322. continue
  323. }
  324. if _, ok := seg.(*TextSegment); !ok {
  325. if currentBound == nil {
  326. bound := rowBoundary{segments: []RichTextSegment{seg}}
  327. bounds = append(bounds, bound)
  328. currentBound = &bound
  329. } else {
  330. bounds[len(bounds)-1].segments = append(bounds[len(bounds)-1].segments, seg)
  331. }
  332. if seg.Inline() {
  333. wrapWidth -= t.cachedSegmentVisual(seg, 0).MinSize().Width
  334. } else {
  335. wrapWidth = maxWidth
  336. currentBound = nil
  337. }
  338. continue
  339. }
  340. textSeg := seg.(*TextSegment)
  341. textStyle := textSeg.Style.TextStyle
  342. textSize := textSeg.size()
  343. leftPad := float32(0)
  344. if textSeg.Style == RichTextStyleBlockquote {
  345. leftPad = innerPadding * 2
  346. }
  347. retBounds := lineBounds(textSeg, t.Wrapping, wrapWidth-leftPad, maxWidth, func(text []rune) float32 {
  348. return fyne.MeasureText(string(text), textSize, textStyle).Width
  349. })
  350. if currentBound != nil {
  351. if len(retBounds) > 0 {
  352. bounds[len(bounds)-1].end = retBounds[0].end // invalidate row ending as we have more content
  353. bounds[len(bounds)-1].segments = append(bounds[len(bounds)-1].segments, seg)
  354. bounds = append(bounds, retBounds[1:]...)
  355. }
  356. } else {
  357. bounds = append(bounds, retBounds...)
  358. }
  359. currentBound = &bounds[len(bounds)-1]
  360. if seg.Inline() {
  361. last := bounds[len(bounds)-1]
  362. begin := 0
  363. if len(last.segments) == 1 {
  364. begin = last.begin
  365. }
  366. runes := []rune(textSeg.Text)
  367. // check ranges - as we resize it can be wrong?
  368. if begin > len(runes) {
  369. begin = len(runes)
  370. }
  371. end := last.end
  372. if end > len(runes) {
  373. end = len(runes)
  374. }
  375. text := string(runes[begin:end])
  376. lastWidth := fyne.MeasureText(text, textSeg.size(), textSeg.Style.TextStyle).Width
  377. if len(retBounds) == 1 {
  378. wrapWidth -= lastWidth
  379. } else {
  380. wrapWidth = maxWidth - lastWidth
  381. }
  382. } else {
  383. currentBound = nil
  384. wrapWidth = maxWidth
  385. }
  386. }
  387. }
  388. iterateSegments(t.Segments)
  389. t.propertyLock.RUnlock()
  390. t.propertyLock.Lock()
  391. t.rowBounds = bounds
  392. t.propertyLock.Unlock()
  393. }
  394. // RichTextBlock is an extension of a text segment that contains other segments
  395. //
  396. // Since: 2.1
  397. type RichTextBlock interface {
  398. Segments() []RichTextSegment
  399. }
  400. // Renderer
  401. type textRenderer struct {
  402. widget.BaseRenderer
  403. obj *RichText
  404. }
  405. func (r *textRenderer) Layout(size fyne.Size) {
  406. r.obj.propertyLock.RLock()
  407. bounds := r.obj.rowBounds
  408. objs := r.Objects()
  409. if r.obj.scr != nil {
  410. r.obj.scr.Resize(size)
  411. objs = r.obj.scr.Content.(*fyne.Container).Objects[1].(*fyne.Container).Objects
  412. }
  413. r.obj.propertyLock.RUnlock()
  414. // Accessing theme here is slow, so we cache the value
  415. innerPadding := theme.InnerPadding()
  416. lineSpacing := theme.LineSpacing()
  417. left := innerPadding - r.obj.inset.Width
  418. yPos := innerPadding - r.obj.inset.Height
  419. lineWidth := size.Width - left*2
  420. var rowItems []fyne.CanvasObject
  421. rowAlign := fyne.TextAlignLeading
  422. i := 0
  423. for row, bound := range bounds {
  424. for segI := range bound.segments {
  425. if i == len(objs) {
  426. break // Refresh may not have created all objects for all rows yet...
  427. }
  428. inline := segI < len(bound.segments)-1
  429. obj := objs[i]
  430. i++
  431. _, isText := obj.(*canvas.Text)
  432. if !isText && !inline {
  433. if len(rowItems) != 0 {
  434. width, _ := r.layoutRow(rowItems, rowAlign, left, yPos, lineWidth)
  435. left += width
  436. }
  437. height := obj.MinSize().Height
  438. obj.Move(fyne.NewPos(left, yPos))
  439. obj.Resize(fyne.NewSize(lineWidth, height))
  440. yPos += height + lineSpacing
  441. continue
  442. }
  443. rowItems = append(rowItems, obj)
  444. if inline {
  445. continue
  446. }
  447. leftPad := float32(0)
  448. if text, ok := bound.segments[0].(*TextSegment); ok {
  449. rowAlign = text.Style.Alignment
  450. if text.Style == RichTextStyleBlockquote {
  451. leftPad = lineSpacing * 4
  452. }
  453. } else if link, ok := bound.segments[0].(*HyperlinkSegment); ok {
  454. rowAlign = link.Alignment
  455. }
  456. _, y := r.layoutRow(rowItems, rowAlign, left+leftPad, yPos, lineWidth-leftPad)
  457. yPos += y
  458. rowItems = nil
  459. }
  460. lastSeg := bound.segments[len(bound.segments)-1]
  461. if !lastSeg.Inline() && row < len(bounds)-1 && bounds[row+1].segments[0] != lastSeg { // ignore wrapped lines etc
  462. yPos += lineSpacing
  463. }
  464. }
  465. }
  466. // MinSize calculates the minimum size of a rich text widget.
  467. // This is based on the contained text with a standard amount of padding added.
  468. func (r *textRenderer) MinSize() fyne.Size {
  469. r.obj.propertyLock.RLock()
  470. bounds := r.obj.rowBounds
  471. wrap := r.obj.Wrapping
  472. scroll := r.obj.Scroll
  473. objs := r.Objects()
  474. if r.obj.scr != nil {
  475. objs = r.obj.scr.Content.(*fyne.Container).Objects[1].(*fyne.Container).Objects
  476. }
  477. r.obj.propertyLock.RUnlock()
  478. height := float32(0)
  479. width := float32(0)
  480. rowHeight := float32(0)
  481. rowWidth := float32(0)
  482. // Accessing the theme here is slow, so we cache the value
  483. lineSpacing := theme.LineSpacing()
  484. i := 0
  485. for row, bound := range bounds {
  486. for range bound.segments {
  487. if i == len(objs) {
  488. break // Refresh may not have created all objects for all rows yet...
  489. }
  490. obj := objs[i]
  491. i++
  492. min := obj.MinSize()
  493. if img, ok := obj.(*richImage); ok {
  494. if !img.MinSize().Subtract(img.oldMin).IsZero() {
  495. img.oldMin = img.MinSize()
  496. r.Refresh() // TODO resolve this in a similar way to #2991
  497. }
  498. }
  499. rowHeight = fyne.Max(rowHeight, min.Height)
  500. rowWidth += min.Width
  501. }
  502. if wrap == fyne.TextWrapOff {
  503. width = fyne.Max(width, rowWidth)
  504. }
  505. height += rowHeight
  506. rowHeight = 0
  507. rowWidth = 0
  508. lastSeg := bound.segments[len(bound.segments)-1]
  509. if !lastSeg.Inline() && row < len(bounds)-1 && bounds[row+1].segments[0] != lastSeg { // ignore wrapped lines etc
  510. height += lineSpacing
  511. }
  512. }
  513. if height == 0 {
  514. charMinSize := r.obj.charMinSize(false, fyne.TextStyle{})
  515. height = charMinSize.Height
  516. }
  517. min := fyne.NewSize(width, height).
  518. Add(fyne.NewSize(theme.InnerPadding()*2, theme.InnerPadding()*2).Subtract(r.obj.inset).Subtract(r.obj.inset))
  519. if r.obj.scr != nil {
  520. r.obj.prop.SetMinSize(min)
  521. }
  522. switch scroll {
  523. case widget.ScrollBoth:
  524. return fyne.NewSize(32, 32)
  525. case widget.ScrollHorizontalOnly:
  526. return fyne.NewSize(32, min.Height)
  527. case widget.ScrollVerticalOnly:
  528. return fyne.NewSize(min.Width, 32)
  529. default:
  530. return min
  531. }
  532. }
  533. func (r *textRenderer) Refresh() {
  534. r.obj.propertyLock.RLock()
  535. bounds := r.obj.rowBounds
  536. scroll := r.obj.Scroll
  537. r.obj.propertyLock.RUnlock()
  538. var objs []fyne.CanvasObject
  539. for _, bound := range bounds {
  540. for i, seg := range bound.segments {
  541. if _, ok := seg.(*TextSegment); !ok {
  542. obj := r.obj.cachedSegmentVisual(seg, 0)
  543. seg.Update(obj)
  544. objs = append(objs, obj)
  545. continue
  546. }
  547. reuse := 0
  548. if i == 0 {
  549. reuse = bound.firstSegmentReuse
  550. }
  551. obj := r.obj.cachedSegmentVisual(seg, reuse)
  552. seg.Update(obj)
  553. txt := obj.(*canvas.Text)
  554. textSeg := seg.(*TextSegment)
  555. runes := []rune(textSeg.Text)
  556. if i == 0 {
  557. if len(bound.segments) == 1 {
  558. txt.Text = string(runes[bound.begin:bound.end])
  559. } else {
  560. txt.Text = string(runes[bound.begin:])
  561. }
  562. } else if i == len(bound.segments)-1 && len(bound.segments) > 1 {
  563. txt.Text = string(runes[:bound.end])
  564. }
  565. if concealed(seg) {
  566. txt.Text = strings.Repeat(passwordChar, len(runes))
  567. }
  568. objs = append(objs, txt)
  569. }
  570. }
  571. r.obj.propertyLock.Lock()
  572. if r.obj.scr != nil {
  573. r.obj.scr.Content = &fyne.Container{Layout: layout.NewMaxLayout(), Objects: []fyne.CanvasObject{
  574. r.obj.prop, &fyne.Container{Objects: objs}}}
  575. r.obj.scr.Direction = scroll
  576. r.SetObjects([]fyne.CanvasObject{r.obj.scr})
  577. r.obj.scr.Refresh()
  578. } else {
  579. r.SetObjects(objs)
  580. }
  581. r.obj.propertyLock.Unlock()
  582. r.Layout(r.obj.Size())
  583. canvas.Refresh(r.obj)
  584. }
  585. func (r *textRenderer) layoutRow(texts []fyne.CanvasObject, align fyne.TextAlign, xPos, yPos, lineWidth float32) (float32, float32) {
  586. initialX := xPos
  587. if len(texts) == 1 {
  588. min := texts[0].MinSize()
  589. if text, ok := texts[0].(*canvas.Text); ok {
  590. texts[0].Resize(min)
  591. xPad := float32(0)
  592. switch text.Alignment {
  593. case fyne.TextAlignLeading:
  594. case fyne.TextAlignTrailing:
  595. xPad = lineWidth - min.Width
  596. case fyne.TextAlignCenter:
  597. xPad = (lineWidth - min.Width) / 2
  598. }
  599. texts[0].Move(fyne.NewPos(xPos+xPad, yPos))
  600. } else {
  601. texts[0].Resize(fyne.NewSize(lineWidth, min.Height))
  602. texts[0].Move(fyne.NewPos(xPos, yPos))
  603. }
  604. return min.Width, min.Height
  605. }
  606. height := float32(0)
  607. tallestBaseline := float32(0)
  608. realign := false
  609. baselines := make([]float32, len(texts))
  610. // Access to theme is slow, so we cache the text size
  611. textSize := theme.TextSize()
  612. for i, text := range texts {
  613. var size fyne.Size
  614. if txt, ok := text.(*canvas.Text); ok {
  615. s, base := fyne.CurrentApp().Driver().RenderedTextSize(txt.Text, txt.TextSize, txt.TextStyle)
  616. if base > tallestBaseline {
  617. if tallestBaseline > 0 {
  618. realign = true
  619. }
  620. tallestBaseline = base
  621. }
  622. size = s
  623. baselines[i] = base
  624. } else if c, ok := text.(*fyne.Container); ok {
  625. wid := c.Objects[0]
  626. if link, ok := wid.(*Hyperlink); ok {
  627. s, base := fyne.CurrentApp().Driver().RenderedTextSize(link.Text, textSize, link.TextStyle)
  628. if base > tallestBaseline {
  629. if tallestBaseline > 0 {
  630. realign = true
  631. }
  632. tallestBaseline = base
  633. }
  634. size = s
  635. baselines[i] = base
  636. }
  637. }
  638. if size.IsZero() {
  639. size = text.MinSize()
  640. }
  641. text.Resize(size)
  642. text.Move(fyne.NewPos(xPos, yPos))
  643. xPos += size.Width
  644. if height == 0 {
  645. height = size.Height
  646. } else if height != size.Height {
  647. height = fyne.Max(height, size.Height)
  648. realign = true
  649. }
  650. }
  651. if realign {
  652. for i, text := range texts {
  653. delta := tallestBaseline - baselines[i]
  654. text.Move(fyne.NewPos(text.Position().X, yPos+delta))
  655. }
  656. }
  657. spare := lineWidth - xPos
  658. switch align {
  659. case fyne.TextAlignTrailing:
  660. first := texts[0]
  661. first.Resize(fyne.NewSize(first.Size().Width+spare, height))
  662. setAlign(first, fyne.TextAlignTrailing)
  663. for _, text := range texts[1:] {
  664. text.Move(text.Position().Add(fyne.NewPos(spare, 0)))
  665. }
  666. case fyne.TextAlignCenter:
  667. pad := spare / 2
  668. first := texts[0]
  669. first.Resize(fyne.NewSize(first.Size().Width+pad, height))
  670. setAlign(first, fyne.TextAlignTrailing)
  671. last := texts[len(texts)-1]
  672. last.Resize(fyne.NewSize(last.Size().Width+pad, height))
  673. setAlign(last, fyne.TextAlignLeading)
  674. for _, text := range texts[1:] {
  675. text.Move(text.Position().Add(fyne.NewPos(pad, 0)))
  676. }
  677. default:
  678. last := texts[len(texts)-1]
  679. last.Resize(fyne.NewSize(last.Size().Width+spare, height))
  680. setAlign(last, fyne.TextAlignLeading)
  681. }
  682. return xPos - initialX, height
  683. }
  684. // binarySearch accepts a function that checks if the text width less the maximum width and the start and end rune index
  685. // binarySearch returns the index of rune located as close to the maximum line width as possible
  686. func binarySearch(lessMaxWidth func(int, int) bool, low int, maxHigh int) int {
  687. if low >= maxHigh {
  688. return low
  689. }
  690. if lessMaxWidth(low, maxHigh) {
  691. return maxHigh
  692. }
  693. high := low
  694. delta := maxHigh - low
  695. for delta > 0 {
  696. delta /= 2
  697. if lessMaxWidth(low, high+delta) {
  698. high += delta
  699. }
  700. }
  701. for (high < maxHigh) && lessMaxWidth(low, high+1) {
  702. high++
  703. }
  704. return high
  705. }
  706. // concealed returns true if the segment represents a password, meaning the text should be obscured.
  707. func concealed(seg RichTextSegment) bool {
  708. if text, ok := seg.(*TextSegment); ok {
  709. return text.Style.concealed
  710. }
  711. return false
  712. }
  713. // findSpaceIndex accepts a slice of runes and a fallback index
  714. // findSpaceIndex returns the index of the last space in the text, or fallback if there are no spaces
  715. func findSpaceIndex(text []rune, fallback int) int {
  716. curIndex := fallback
  717. for ; curIndex >= 0; curIndex-- {
  718. if unicode.IsSpace(text[curIndex]) {
  719. break
  720. }
  721. }
  722. if curIndex < 0 {
  723. return fallback
  724. }
  725. return curIndex
  726. }
  727. // lineBounds accepts a slice of Segments, a wrapping mode, a maximum line width and a function to measure line width.
  728. // lineBounds returns a slice containing the boundary metadata of each line with the given wrapping applied.
  729. func lineBounds(seg *TextSegment, wrap fyne.TextWrap, firstWidth, maxWidth float32, measurer func([]rune) float32) []rowBoundary {
  730. lines := splitLines(seg)
  731. if maxWidth < 0 || wrap == fyne.TextWrapOff {
  732. return lines
  733. }
  734. measureWidth := firstWidth
  735. text := []rune(seg.Text)
  736. checker := func(low int, high int) bool {
  737. return measurer(text[low:high]) <= measureWidth
  738. }
  739. reuse := 0
  740. var bounds []rowBoundary
  741. for _, l := range lines {
  742. low := l.begin
  743. high := l.end
  744. if low == high {
  745. l.firstSegmentReuse = reuse
  746. reuse++
  747. bounds = append(bounds, l)
  748. continue
  749. }
  750. switch wrap {
  751. case fyne.TextTruncate:
  752. high = binarySearch(checker, low, high)
  753. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, high})
  754. reuse++
  755. case fyne.TextWrapBreak:
  756. for low < high {
  757. if measurer(text[low:high]) <= measureWidth {
  758. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, high})
  759. reuse++
  760. low = high
  761. high = l.end
  762. measureWidth = maxWidth
  763. } else {
  764. newHigh := binarySearch(checker, low, high)
  765. if newHigh <= low {
  766. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, low + 1})
  767. reuse++
  768. low++
  769. } else {
  770. high = newHigh
  771. }
  772. }
  773. }
  774. case fyne.TextWrapWord:
  775. for low < high {
  776. sub := text[low:high]
  777. subWidth := measurer(sub)
  778. if subWidth <= measureWidth {
  779. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, high})
  780. reuse++
  781. low = high
  782. high = l.end
  783. if low < high && unicode.IsSpace(text[low]) {
  784. low++
  785. }
  786. measureWidth = maxWidth
  787. } else {
  788. oldHigh := high
  789. last := low + len(sub) - 1
  790. fallback := binarySearch(checker, low, last) - low
  791. if fallback < 1 { // even a character won't fit
  792. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, low + 1})
  793. low++
  794. high = low + 1
  795. reuse++
  796. if high > l.end {
  797. return bounds
  798. }
  799. } else {
  800. spaceIndex := findSpaceIndex(sub, fallback)
  801. if spaceIndex == 0 {
  802. spaceIndex = 1
  803. }
  804. high = low + spaceIndex
  805. }
  806. if high == fallback && subWidth <= maxWidth { // add a newline as there is more space on next
  807. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, low})
  808. reuse++
  809. high = oldHigh
  810. measureWidth = maxWidth
  811. continue
  812. }
  813. }
  814. }
  815. }
  816. }
  817. return bounds
  818. }
  819. func setAlign(obj fyne.CanvasObject, align fyne.TextAlign) {
  820. if text, ok := obj.(*canvas.Text); ok {
  821. text.Alignment = align
  822. return
  823. }
  824. if c, ok := obj.(*fyne.Container); ok {
  825. wid := c.Objects[0]
  826. if link, ok := wid.(*Hyperlink); ok {
  827. link.Alignment = align
  828. link.Refresh()
  829. }
  830. }
  831. }
  832. // splitLines accepts a text segment and returns a slice of boundary metadata denoting the
  833. // start and end indices of each line delimited by the newline character.
  834. func splitLines(seg *TextSegment) []rowBoundary {
  835. var low, high int
  836. var lines []rowBoundary
  837. text := []rune(seg.Text)
  838. length := len(text)
  839. for i := 0; i < length; i++ {
  840. if text[i] == '\n' {
  841. high = i
  842. lines = append(lines, rowBoundary{[]RichTextSegment{seg}, len(lines), low, high})
  843. low = i + 1
  844. }
  845. }
  846. return append(lines, rowBoundary{[]RichTextSegment{seg}, len(lines), low, length})
  847. }
  848. type rowBoundary struct {
  849. segments []RichTextSegment
  850. firstSegmentReuse int
  851. begin, end int
  852. }