richtext.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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 currentBound *rowBoundary
  314. var iterateSegments func(segList []RichTextSegment)
  315. iterateSegments = func(segList []RichTextSegment) {
  316. for _, seg := range segList {
  317. if parent, ok := seg.(RichTextBlock); ok {
  318. segs := parent.Segments()
  319. iterateSegments(segs)
  320. if len(segs) > 0 && !segs[len(segs)-1].Inline() {
  321. wrapWidth = maxWidth
  322. currentBound = nil
  323. }
  324. continue
  325. }
  326. if _, ok := seg.(*TextSegment); !ok {
  327. if currentBound == nil {
  328. bound := rowBoundary{segments: []RichTextSegment{seg}}
  329. bounds = append(bounds, bound)
  330. currentBound = &bound
  331. } else {
  332. bounds[len(bounds)-1].segments = append(bounds[len(bounds)-1].segments, seg)
  333. }
  334. if seg.Inline() {
  335. wrapWidth -= t.cachedSegmentVisual(seg, 0).MinSize().Width
  336. } else {
  337. wrapWidth = maxWidth
  338. currentBound = nil
  339. }
  340. continue
  341. }
  342. textSeg := seg.(*TextSegment)
  343. textStyle := textSeg.Style.TextStyle
  344. textSize := textSeg.size()
  345. leftPad := float32(0)
  346. if textSeg.Style == RichTextStyleBlockquote {
  347. leftPad = innerPadding * 2
  348. }
  349. retBounds := lineBounds(textSeg, t.Wrapping, wrapWidth-leftPad, maxWidth, func(text []rune) float32 {
  350. return fyne.MeasureText(string(text), textSize, textStyle).Width
  351. })
  352. if currentBound != nil {
  353. if len(retBounds) > 0 {
  354. bounds[len(bounds)-1].end = retBounds[0].end // invalidate row ending as we have more content
  355. bounds[len(bounds)-1].segments = append(bounds[len(bounds)-1].segments, seg)
  356. bounds = append(bounds, retBounds[1:]...)
  357. }
  358. } else {
  359. bounds = append(bounds, retBounds...)
  360. }
  361. currentBound = &bounds[len(bounds)-1]
  362. if seg.Inline() {
  363. last := bounds[len(bounds)-1]
  364. begin := 0
  365. if len(last.segments) == 1 {
  366. begin = last.begin
  367. }
  368. runes := []rune(textSeg.Text)
  369. // check ranges - as we resize it can be wrong?
  370. if begin > len(runes) {
  371. begin = len(runes)
  372. }
  373. end := last.end
  374. if end > len(runes) {
  375. end = len(runes)
  376. }
  377. text := string(runes[begin:end])
  378. lastWidth := fyne.MeasureText(text, textSeg.size(), textSeg.Style.TextStyle).Width
  379. if len(retBounds) == 1 {
  380. wrapWidth -= lastWidth
  381. } else {
  382. wrapWidth = maxWidth - lastWidth
  383. }
  384. } else {
  385. currentBound = nil
  386. wrapWidth = maxWidth
  387. }
  388. }
  389. }
  390. iterateSegments(t.Segments)
  391. t.propertyLock.RUnlock()
  392. t.propertyLock.Lock()
  393. t.rowBounds = bounds
  394. t.propertyLock.Unlock()
  395. }
  396. // RichTextBlock is an extension of a text segment that contains other segments
  397. //
  398. // Since: 2.1
  399. type RichTextBlock interface {
  400. Segments() []RichTextSegment
  401. }
  402. // Renderer
  403. type textRenderer struct {
  404. widget.BaseRenderer
  405. obj *RichText
  406. }
  407. func (r *textRenderer) Layout(size fyne.Size) {
  408. r.obj.propertyLock.RLock()
  409. bounds := r.obj.rowBounds
  410. objs := r.Objects()
  411. if r.obj.scr != nil {
  412. r.obj.scr.Resize(size)
  413. objs = r.obj.scr.Content.(*fyne.Container).Objects[1].(*fyne.Container).Objects
  414. }
  415. r.obj.propertyLock.RUnlock()
  416. // Accessing theme here is slow, so we cache the value
  417. innerPadding := theme.InnerPadding()
  418. lineSpacing := theme.LineSpacing()
  419. xInset := innerPadding - r.obj.inset.Width
  420. left := xInset
  421. yPos := innerPadding - r.obj.inset.Height
  422. lineWidth := size.Width - left*2
  423. var rowItems []fyne.CanvasObject
  424. rowAlign := fyne.TextAlignLeading
  425. i := 0
  426. for row, bound := range bounds {
  427. for segI := range bound.segments {
  428. if i == len(objs) {
  429. break // Refresh may not have created all objects for all rows yet...
  430. }
  431. inline := segI < len(bound.segments)-1
  432. obj := objs[i]
  433. i++
  434. _, isText := obj.(*canvas.Text)
  435. if !isText && !inline {
  436. if len(rowItems) != 0 {
  437. width, _ := r.layoutRow(rowItems, rowAlign, left, yPos, lineWidth)
  438. left += width
  439. rowItems = nil
  440. }
  441. height := obj.MinSize().Height
  442. obj.Move(fyne.NewPos(left, yPos))
  443. obj.Resize(fyne.NewSize(lineWidth, height))
  444. yPos += height
  445. left = xInset
  446. continue
  447. }
  448. rowItems = append(rowItems, obj)
  449. if inline {
  450. continue
  451. }
  452. leftPad := float32(0)
  453. if text, ok := bound.segments[0].(*TextSegment); ok {
  454. rowAlign = text.Style.Alignment
  455. if text.Style == RichTextStyleBlockquote {
  456. leftPad = lineSpacing * 4
  457. }
  458. } else if link, ok := bound.segments[0].(*HyperlinkSegment); ok {
  459. rowAlign = link.Alignment
  460. }
  461. _, y := r.layoutRow(rowItems, rowAlign, left+leftPad, yPos, lineWidth-leftPad)
  462. yPos += y
  463. rowItems = nil
  464. }
  465. lastSeg := bound.segments[len(bound.segments)-1]
  466. if !lastSeg.Inline() && row < len(bounds)-1 && bounds[row+1].segments[0] != lastSeg { // ignore wrapped lines etc
  467. yPos += lineSpacing
  468. }
  469. }
  470. }
  471. // MinSize calculates the minimum size of a rich text widget.
  472. // This is based on the contained text with a standard amount of padding added.
  473. func (r *textRenderer) MinSize() fyne.Size {
  474. r.obj.propertyLock.RLock()
  475. bounds := r.obj.rowBounds
  476. wrap := r.obj.Wrapping
  477. scroll := r.obj.Scroll
  478. objs := r.Objects()
  479. if r.obj.scr != nil {
  480. objs = r.obj.scr.Content.(*fyne.Container).Objects[1].(*fyne.Container).Objects
  481. }
  482. r.obj.propertyLock.RUnlock()
  483. height := float32(0)
  484. width := float32(0)
  485. rowHeight := float32(0)
  486. rowWidth := float32(0)
  487. // Accessing the theme here is slow, so we cache the value
  488. lineSpacing := theme.LineSpacing()
  489. i := 0
  490. for row, bound := range bounds {
  491. for range bound.segments {
  492. if i == len(objs) {
  493. break // Refresh may not have created all objects for all rows yet...
  494. }
  495. obj := objs[i]
  496. i++
  497. min := obj.MinSize()
  498. if img, ok := obj.(*richImage); ok {
  499. if !img.MinSize().Subtract(img.oldMin).IsZero() {
  500. img.oldMin = img.MinSize()
  501. r.Refresh() // TODO resolve this in a similar way to #2991
  502. }
  503. }
  504. rowHeight = fyne.Max(rowHeight, min.Height)
  505. rowWidth += min.Width
  506. }
  507. if wrap == fyne.TextWrapOff {
  508. width = fyne.Max(width, rowWidth)
  509. }
  510. height += rowHeight
  511. rowHeight = 0
  512. rowWidth = 0
  513. lastSeg := bound.segments[len(bound.segments)-1]
  514. if !lastSeg.Inline() && row < len(bounds)-1 && bounds[row+1].segments[0] != lastSeg { // ignore wrapped lines etc
  515. height += lineSpacing
  516. }
  517. }
  518. if height == 0 {
  519. charMinSize := r.obj.charMinSize(false, fyne.TextStyle{})
  520. height = charMinSize.Height
  521. }
  522. min := fyne.NewSize(width, height).
  523. Add(fyne.NewSize(theme.InnerPadding()*2, theme.InnerPadding()*2).Subtract(r.obj.inset).Subtract(r.obj.inset))
  524. if r.obj.scr != nil {
  525. r.obj.prop.SetMinSize(min)
  526. }
  527. switch scroll {
  528. case widget.ScrollBoth:
  529. return fyne.NewSize(32, 32)
  530. case widget.ScrollHorizontalOnly:
  531. return fyne.NewSize(32, min.Height)
  532. case widget.ScrollVerticalOnly:
  533. return fyne.NewSize(min.Width, 32)
  534. default:
  535. return min
  536. }
  537. }
  538. func (r *textRenderer) Refresh() {
  539. r.obj.propertyLock.RLock()
  540. bounds := r.obj.rowBounds
  541. scroll := r.obj.Scroll
  542. r.obj.propertyLock.RUnlock()
  543. var objs []fyne.CanvasObject
  544. for _, bound := range bounds {
  545. for i, seg := range bound.segments {
  546. if _, ok := seg.(*TextSegment); !ok {
  547. obj := r.obj.cachedSegmentVisual(seg, 0)
  548. seg.Update(obj)
  549. objs = append(objs, obj)
  550. continue
  551. }
  552. reuse := 0
  553. if i == 0 {
  554. reuse = bound.firstSegmentReuse
  555. }
  556. obj := r.obj.cachedSegmentVisual(seg, reuse)
  557. seg.Update(obj)
  558. txt := obj.(*canvas.Text)
  559. textSeg := seg.(*TextSegment)
  560. runes := []rune(textSeg.Text)
  561. if i == 0 {
  562. if len(bound.segments) == 1 {
  563. txt.Text = string(runes[bound.begin:bound.end])
  564. } else {
  565. txt.Text = string(runes[bound.begin:])
  566. }
  567. } else if i == len(bound.segments)-1 && len(bound.segments) > 1 {
  568. txt.Text = string(runes[:bound.end])
  569. }
  570. if concealed(seg) {
  571. txt.Text = strings.Repeat(passwordChar, len(runes))
  572. }
  573. objs = append(objs, txt)
  574. }
  575. }
  576. r.obj.propertyLock.Lock()
  577. if r.obj.scr != nil {
  578. r.obj.scr.Content = &fyne.Container{Layout: layout.NewMaxLayout(), Objects: []fyne.CanvasObject{
  579. r.obj.prop, &fyne.Container{Objects: objs}}}
  580. r.obj.scr.Direction = scroll
  581. r.SetObjects([]fyne.CanvasObject{r.obj.scr})
  582. r.obj.scr.Refresh()
  583. } else {
  584. r.SetObjects(objs)
  585. }
  586. r.obj.propertyLock.Unlock()
  587. r.Layout(r.obj.Size())
  588. canvas.Refresh(r.obj)
  589. }
  590. func (r *textRenderer) layoutRow(texts []fyne.CanvasObject, align fyne.TextAlign, xPos, yPos, lineWidth float32) (float32, float32) {
  591. initialX := xPos
  592. if len(texts) == 1 {
  593. min := texts[0].MinSize()
  594. if text, ok := texts[0].(*canvas.Text); ok {
  595. texts[0].Resize(min)
  596. xPad := float32(0)
  597. switch text.Alignment {
  598. case fyne.TextAlignLeading:
  599. case fyne.TextAlignTrailing:
  600. xPad = lineWidth - min.Width
  601. case fyne.TextAlignCenter:
  602. xPad = (lineWidth - min.Width) / 2
  603. }
  604. texts[0].Move(fyne.NewPos(xPos+xPad, yPos))
  605. } else {
  606. texts[0].Resize(fyne.NewSize(lineWidth, min.Height))
  607. texts[0].Move(fyne.NewPos(xPos, yPos))
  608. }
  609. return min.Width, min.Height
  610. }
  611. height := float32(0)
  612. tallestBaseline := float32(0)
  613. realign := false
  614. baselines := make([]float32, len(texts))
  615. // Access to theme is slow, so we cache the text size
  616. textSize := theme.TextSize()
  617. for i, text := range texts {
  618. var size fyne.Size
  619. if txt, ok := text.(*canvas.Text); ok {
  620. s, base := fyne.CurrentApp().Driver().RenderedTextSize(txt.Text, txt.TextSize, txt.TextStyle)
  621. if base > tallestBaseline {
  622. if tallestBaseline > 0 {
  623. realign = true
  624. }
  625. tallestBaseline = base
  626. }
  627. size = s
  628. baselines[i] = base
  629. } else if c, ok := text.(*fyne.Container); ok {
  630. wid := c.Objects[0]
  631. if link, ok := wid.(*Hyperlink); ok {
  632. s, base := fyne.CurrentApp().Driver().RenderedTextSize(link.Text, textSize, link.TextStyle)
  633. if base > tallestBaseline {
  634. if tallestBaseline > 0 {
  635. realign = true
  636. }
  637. tallestBaseline = base
  638. }
  639. size = s
  640. baselines[i] = base
  641. }
  642. }
  643. if size.IsZero() {
  644. size = text.MinSize()
  645. }
  646. text.Resize(size)
  647. text.Move(fyne.NewPos(xPos, yPos))
  648. xPos += size.Width
  649. if height == 0 {
  650. height = size.Height
  651. } else if height != size.Height {
  652. height = fyne.Max(height, size.Height)
  653. realign = true
  654. }
  655. }
  656. if realign {
  657. for i, text := range texts {
  658. delta := tallestBaseline - baselines[i]
  659. text.Move(fyne.NewPos(text.Position().X, yPos+delta))
  660. }
  661. }
  662. spare := lineWidth - xPos
  663. switch align {
  664. case fyne.TextAlignTrailing:
  665. first := texts[0]
  666. first.Resize(fyne.NewSize(first.Size().Width+spare, height))
  667. setAlign(first, fyne.TextAlignTrailing)
  668. for _, text := range texts[1:] {
  669. text.Move(text.Position().Add(fyne.NewPos(spare, 0)))
  670. }
  671. case fyne.TextAlignCenter:
  672. pad := spare / 2
  673. first := texts[0]
  674. first.Resize(fyne.NewSize(first.Size().Width+pad, height))
  675. setAlign(first, fyne.TextAlignTrailing)
  676. last := texts[len(texts)-1]
  677. last.Resize(fyne.NewSize(last.Size().Width+pad, height))
  678. setAlign(last, fyne.TextAlignLeading)
  679. for _, text := range texts[1:] {
  680. text.Move(text.Position().Add(fyne.NewPos(pad, 0)))
  681. }
  682. default:
  683. last := texts[len(texts)-1]
  684. last.Resize(fyne.NewSize(last.Size().Width+spare, height))
  685. setAlign(last, fyne.TextAlignLeading)
  686. }
  687. return xPos - initialX, height
  688. }
  689. // binarySearch accepts a function that checks if the text width less the maximum width and the start and end rune index
  690. // binarySearch returns the index of rune located as close to the maximum line width as possible
  691. func binarySearch(lessMaxWidth func(int, int) bool, low int, maxHigh int) int {
  692. if low >= maxHigh {
  693. return low
  694. }
  695. if lessMaxWidth(low, maxHigh) {
  696. return maxHigh
  697. }
  698. high := low
  699. delta := maxHigh - low
  700. for delta > 0 {
  701. delta /= 2
  702. if lessMaxWidth(low, high+delta) {
  703. high += delta
  704. }
  705. }
  706. for (high < maxHigh) && lessMaxWidth(low, high+1) {
  707. high++
  708. }
  709. return high
  710. }
  711. // concealed returns true if the segment represents a password, meaning the text should be obscured.
  712. func concealed(seg RichTextSegment) bool {
  713. if text, ok := seg.(*TextSegment); ok {
  714. return text.Style.concealed
  715. }
  716. return false
  717. }
  718. // findSpaceIndex accepts a slice of runes and a fallback index
  719. // findSpaceIndex returns the index of the last space in the text, or fallback if there are no spaces
  720. func findSpaceIndex(text []rune, fallback int) int {
  721. curIndex := fallback
  722. for ; curIndex >= 0; curIndex-- {
  723. if unicode.IsSpace(text[curIndex]) {
  724. break
  725. }
  726. }
  727. if curIndex < 0 {
  728. return fallback
  729. }
  730. return curIndex
  731. }
  732. // lineBounds accepts a slice of Segments, a wrapping mode, a maximum line width and a function to measure line width.
  733. // lineBounds returns a slice containing the boundary metadata of each line with the given wrapping applied.
  734. func lineBounds(seg *TextSegment, wrap fyne.TextWrap, firstWidth, maxWidth float32, measurer func([]rune) float32) []rowBoundary {
  735. lines := splitLines(seg)
  736. if maxWidth < 0 || wrap == fyne.TextWrapOff {
  737. return lines
  738. }
  739. measureWidth := firstWidth
  740. text := []rune(seg.Text)
  741. checker := func(low int, high int) bool {
  742. return measurer(text[low:high]) <= measureWidth
  743. }
  744. reuse := 0
  745. var bounds []rowBoundary
  746. for _, l := range lines {
  747. low := l.begin
  748. high := l.end
  749. if low == high {
  750. l.firstSegmentReuse = reuse
  751. reuse++
  752. bounds = append(bounds, l)
  753. continue
  754. }
  755. switch wrap {
  756. case fyne.TextTruncate:
  757. high = binarySearch(checker, low, high)
  758. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, high})
  759. reuse++
  760. case fyne.TextWrapBreak:
  761. for low < high {
  762. if measurer(text[low:high]) <= measureWidth {
  763. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, high})
  764. reuse++
  765. low = high
  766. high = l.end
  767. measureWidth = maxWidth
  768. } else {
  769. newHigh := binarySearch(checker, low, high)
  770. if newHigh <= low {
  771. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, low + 1})
  772. reuse++
  773. low++
  774. } else {
  775. high = newHigh
  776. }
  777. }
  778. }
  779. case fyne.TextWrapWord:
  780. for low < high {
  781. sub := text[low:high]
  782. subWidth := measurer(sub)
  783. if subWidth <= measureWidth {
  784. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, high})
  785. reuse++
  786. low = high
  787. high = l.end
  788. if low < high && unicode.IsSpace(text[low]) {
  789. low++
  790. }
  791. measureWidth = maxWidth
  792. } else {
  793. oldHigh := high
  794. last := low + len(sub) - 1
  795. fallback := binarySearch(checker, low, last) - low
  796. if fallback < 1 { // even a character won't fit
  797. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, low + 1})
  798. low++
  799. high = low + 1
  800. reuse++
  801. if high > l.end {
  802. return bounds
  803. }
  804. } else {
  805. spaceIndex := findSpaceIndex(sub, fallback)
  806. if spaceIndex == 0 {
  807. spaceIndex = 1
  808. }
  809. high = low + spaceIndex
  810. }
  811. if high == fallback && subWidth <= maxWidth { // add a newline as there is more space on next
  812. bounds = append(bounds, rowBoundary{[]RichTextSegment{seg}, reuse, low, low})
  813. reuse++
  814. high = oldHigh
  815. measureWidth = maxWidth
  816. continue
  817. }
  818. }
  819. }
  820. }
  821. }
  822. return bounds
  823. }
  824. func setAlign(obj fyne.CanvasObject, align fyne.TextAlign) {
  825. if text, ok := obj.(*canvas.Text); ok {
  826. text.Alignment = align
  827. return
  828. }
  829. if c, ok := obj.(*fyne.Container); ok {
  830. wid := c.Objects[0]
  831. if link, ok := wid.(*Hyperlink); ok {
  832. link.Alignment = align
  833. link.Refresh()
  834. }
  835. }
  836. }
  837. // splitLines accepts a text segment and returns a slice of boundary metadata denoting the
  838. // start and end indices of each line delimited by the newline character.
  839. func splitLines(seg *TextSegment) []rowBoundary {
  840. var low, high int
  841. var lines []rowBoundary
  842. text := []rune(seg.Text)
  843. length := len(text)
  844. for i := 0; i < length; i++ {
  845. if text[i] == '\n' {
  846. high = i
  847. lines = append(lines, rowBoundary{[]RichTextSegment{seg}, len(lines), low, high})
  848. low = i + 1
  849. }
  850. }
  851. return append(lines, rowBoundary{[]RichTextSegment{seg}, len(lines), low, length})
  852. }
  853. type rowBoundary struct {
  854. segments []RichTextSegment
  855. firstSegmentReuse int
  856. begin, end int
  857. }