gridwrap.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. package widget
  2. import (
  3. "fmt"
  4. "math"
  5. "sync"
  6. "fyne.io/fyne/v2"
  7. "fyne.io/fyne/v2/canvas"
  8. "fyne.io/fyne/v2/data/binding"
  9. "fyne.io/fyne/v2/driver/desktop"
  10. "fyne.io/fyne/v2/internal/widget"
  11. "fyne.io/fyne/v2/theme"
  12. )
  13. // Declare conformity with interfaces.
  14. var _ fyne.Widget = (*GridWrap)(nil)
  15. var _ fyne.Focusable = (*GridWrap)(nil)
  16. // GridWrapItemID is the ID of an individual item in the GridWrap widget.
  17. //
  18. // Since: 2.4
  19. type GridWrapItemID = int
  20. // GridWrap is a widget with an API very similar to widget.List,
  21. // that lays out items in a scrollable wrapping grid similar to container.NewGridWrap.
  22. // It caches and reuses widgets for performance.
  23. //
  24. // Since: 2.4
  25. type GridWrap struct {
  26. BaseWidget
  27. Length func() int `json:"-"`
  28. CreateItem func() fyne.CanvasObject `json:"-"`
  29. UpdateItem func(id GridWrapItemID, item fyne.CanvasObject) `json:"-"`
  30. OnSelected func(id GridWrapItemID) `json:"-"`
  31. OnUnselected func(id GridWrapItemID) `json:"-"`
  32. currentFocus ListItemID
  33. focused bool
  34. scroller *widget.Scroll
  35. selected []GridWrapItemID
  36. itemMin fyne.Size
  37. offsetY float32
  38. offsetUpdated func(fyne.Position)
  39. }
  40. // NewGridWrap creates and returns a GridWrap widget for displaying items in
  41. // a wrapping grid layout with scrolling and caching for performance.
  42. //
  43. // Since: 2.4
  44. func NewGridWrap(length func() int, createItem func() fyne.CanvasObject, updateItem func(GridWrapItemID, fyne.CanvasObject)) *GridWrap {
  45. gwList := &GridWrap{Length: length, CreateItem: createItem, UpdateItem: updateItem}
  46. gwList.ExtendBaseWidget(gwList)
  47. return gwList
  48. }
  49. // NewGridWrapWithData creates a new GridWrap widget that will display the contents of the provided data.
  50. //
  51. // Since: 2.4
  52. func NewGridWrapWithData(data binding.DataList, createItem func() fyne.CanvasObject, updateItem func(binding.DataItem, fyne.CanvasObject)) *GridWrap {
  53. gwList := NewGridWrap(
  54. data.Length,
  55. createItem,
  56. func(i GridWrapItemID, o fyne.CanvasObject) {
  57. item, err := data.GetItem(int(i))
  58. if err != nil {
  59. fyne.LogError(fmt.Sprintf("Error getting data item %d", i), err)
  60. return
  61. }
  62. updateItem(item, o)
  63. })
  64. data.AddListener(binding.NewDataListener(gwList.Refresh))
  65. return gwList
  66. }
  67. // CreateRenderer is a private method to Fyne which links this widget to its renderer.
  68. func (l *GridWrap) CreateRenderer() fyne.WidgetRenderer {
  69. l.ExtendBaseWidget(l)
  70. if f := l.CreateItem; f != nil && l.itemMin.IsZero() {
  71. l.itemMin = f().MinSize()
  72. }
  73. layout := &fyne.Container{Layout: newGridWrapLayout(l)}
  74. l.scroller = widget.NewVScroll(layout)
  75. layout.Resize(layout.MinSize())
  76. return newGridWrapRenderer([]fyne.CanvasObject{l.scroller}, l, l.scroller, layout)
  77. }
  78. // FocusGained is called after this GridWrap has gained focus.
  79. //
  80. // Implements: fyne.Focusable
  81. func (l *GridWrap) FocusGained() {
  82. l.focused = true
  83. l.scrollTo(l.currentFocus)
  84. l.RefreshItem(l.currentFocus)
  85. }
  86. // FocusLost is called after this GridWrap has lost focus.
  87. //
  88. // Implements: fyne.Focusable
  89. func (l *GridWrap) FocusLost() {
  90. l.focused = false
  91. l.RefreshItem(l.currentFocus)
  92. }
  93. // MinSize returns the size that this widget should not shrink below.
  94. func (l *GridWrap) MinSize() fyne.Size {
  95. l.ExtendBaseWidget(l)
  96. return l.BaseWidget.MinSize()
  97. }
  98. func (l *GridWrap) scrollTo(id GridWrapItemID) {
  99. if l.scroller == nil {
  100. return
  101. }
  102. row := math.Floor(float64(id) / float64(l.getColCount()))
  103. y := float32(row)*l.itemMin.Height + float32(row)*theme.Padding()
  104. if y < l.scroller.Offset.Y {
  105. l.scroller.Offset.Y = y
  106. } else if y+l.itemMin.Height > l.scroller.Offset.Y+l.scroller.Size().Height {
  107. l.scroller.Offset.Y = y + l.itemMin.Height - l.scroller.Size().Height
  108. }
  109. l.offsetUpdated(l.scroller.Offset)
  110. }
  111. // RefreshItem refreshes a single item, specified by the item ID passed in.
  112. //
  113. // Since: 2.4
  114. func (l *GridWrap) RefreshItem(id GridWrapItemID) {
  115. if l.scroller == nil {
  116. return
  117. }
  118. l.BaseWidget.Refresh()
  119. lo := l.scroller.Content.(*fyne.Container).Layout.(*gridWrapLayout)
  120. visible := lo.visible
  121. if item, ok := visible[id]; ok {
  122. lo.setupGridItem(item, id, l.focused && l.currentFocus == id)
  123. }
  124. }
  125. // Resize is called when this GridWrap should change size. We refresh to ensure invisible items are drawn.
  126. func (l *GridWrap) Resize(s fyne.Size) {
  127. l.BaseWidget.Resize(s)
  128. l.offsetUpdated(l.scroller.Offset)
  129. l.scroller.Content.(*fyne.Container).Layout.(*gridWrapLayout).updateGrid(true)
  130. }
  131. // Select adds the item identified by the given ID to the selection.
  132. func (l *GridWrap) Select(id GridWrapItemID) {
  133. if len(l.selected) > 0 && id == l.selected[0] {
  134. return
  135. }
  136. length := 0
  137. if f := l.Length; f != nil {
  138. length = f()
  139. }
  140. if id < 0 || id >= length {
  141. return
  142. }
  143. old := l.selected
  144. l.selected = []GridWrapItemID{id}
  145. defer func() {
  146. if f := l.OnUnselected; f != nil && len(old) > 0 {
  147. f(old[0])
  148. }
  149. if f := l.OnSelected; f != nil {
  150. f(id)
  151. }
  152. }()
  153. l.scrollTo(id)
  154. l.Refresh()
  155. }
  156. // ScrollTo scrolls to the item represented by id
  157. func (l *GridWrap) ScrollTo(id GridWrapItemID) {
  158. length := 0
  159. if f := l.Length; f != nil {
  160. length = f()
  161. }
  162. if id < 0 || int(id) >= length {
  163. return
  164. }
  165. l.scrollTo(id)
  166. l.Refresh()
  167. }
  168. // ScrollToBottom scrolls to the end of the list
  169. func (l *GridWrap) ScrollToBottom() {
  170. length := 0
  171. if f := l.Length; f != nil {
  172. length = f()
  173. }
  174. if length > 0 {
  175. length--
  176. }
  177. l.scrollTo(GridWrapItemID(length))
  178. l.Refresh()
  179. }
  180. // ScrollToTop scrolls to the start of the list
  181. func (l *GridWrap) ScrollToTop() {
  182. l.scrollTo(0)
  183. l.Refresh()
  184. }
  185. // ScrollToOffset scrolls the list to the given offset position
  186. func (l *GridWrap) ScrollToOffset(offset float32) {
  187. l.scroller.Offset.Y = offset
  188. l.offsetUpdated(l.scroller.Offset)
  189. }
  190. // TypedKey is called if a key event happens while this GridWrap is focused.
  191. //
  192. // Implements: fyne.Focusable
  193. func (l *GridWrap) TypedKey(event *fyne.KeyEvent) {
  194. switch event.Name {
  195. case fyne.KeySpace:
  196. l.Select(l.currentFocus)
  197. case fyne.KeyDown:
  198. count := 0
  199. if f := l.Length; f != nil {
  200. count = f()
  201. }
  202. l.RefreshItem(l.currentFocus)
  203. l.currentFocus += l.getColCount()
  204. if l.currentFocus >= count-1 {
  205. l.currentFocus = count - 1
  206. }
  207. l.scrollTo(l.currentFocus)
  208. l.RefreshItem(l.currentFocus)
  209. case fyne.KeyLeft:
  210. if l.currentFocus <= 0 {
  211. return
  212. }
  213. if l.currentFocus%l.getColCount() == 0 {
  214. return
  215. }
  216. l.RefreshItem(l.currentFocus)
  217. l.currentFocus--
  218. l.scrollTo(l.currentFocus)
  219. l.RefreshItem(l.currentFocus)
  220. case fyne.KeyRight:
  221. if f := l.Length; f != nil && l.currentFocus >= f()-1 {
  222. return
  223. }
  224. if (l.currentFocus+1)%l.getColCount() == 0 {
  225. return
  226. }
  227. l.RefreshItem(l.currentFocus)
  228. l.currentFocus++
  229. l.scrollTo(l.currentFocus)
  230. l.RefreshItem(l.currentFocus)
  231. case fyne.KeyUp:
  232. if l.currentFocus <= 0 {
  233. return
  234. }
  235. l.RefreshItem(l.currentFocus)
  236. l.currentFocus -= l.getColCount()
  237. if l.currentFocus < 0 {
  238. l.currentFocus = 0
  239. }
  240. l.scrollTo(l.currentFocus)
  241. l.RefreshItem(l.currentFocus)
  242. }
  243. }
  244. // TypedRune is called if a text event happens while this GridWrap is focused.
  245. //
  246. // Implements: fyne.Focusable
  247. func (l *GridWrap) TypedRune(_ rune) {
  248. // intentionally left blank
  249. }
  250. // GetScrollOffset returns the current scroll offset position
  251. func (l *GridWrap) GetScrollOffset() float32 {
  252. return l.offsetY
  253. }
  254. // Unselect removes the item identified by the given ID from the selection.
  255. func (l *GridWrap) Unselect(id GridWrapItemID) {
  256. if len(l.selected) == 0 || l.selected[0] != id {
  257. return
  258. }
  259. l.selected = nil
  260. l.Refresh()
  261. if f := l.OnUnselected; f != nil {
  262. f(id)
  263. }
  264. }
  265. // UnselectAll removes all items from the selection.
  266. func (l *GridWrap) UnselectAll() {
  267. if len(l.selected) == 0 {
  268. return
  269. }
  270. selected := l.selected
  271. l.selected = nil
  272. l.Refresh()
  273. if f := l.OnUnselected; f != nil {
  274. for _, id := range selected {
  275. f(id)
  276. }
  277. }
  278. }
  279. // Declare conformity with WidgetRenderer interface.
  280. var _ fyne.WidgetRenderer = (*gridWrapRenderer)(nil)
  281. type gridWrapRenderer struct {
  282. objects []fyne.CanvasObject
  283. list *GridWrap
  284. scroller *widget.Scroll
  285. layout *fyne.Container
  286. }
  287. func newGridWrapRenderer(objects []fyne.CanvasObject, l *GridWrap, scroller *widget.Scroll, layout *fyne.Container) *gridWrapRenderer {
  288. lr := &gridWrapRenderer{objects: objects, list: l, scroller: scroller, layout: layout}
  289. lr.scroller.OnScrolled = l.offsetUpdated
  290. return lr
  291. }
  292. func (l *gridWrapRenderer) Layout(size fyne.Size) {
  293. l.scroller.Resize(size)
  294. }
  295. func (l *gridWrapRenderer) MinSize() fyne.Size {
  296. return l.scroller.MinSize().Max(l.list.itemMin)
  297. }
  298. func (l *gridWrapRenderer) Refresh() {
  299. if f := l.list.CreateItem; f != nil {
  300. l.list.itemMin = f().MinSize()
  301. }
  302. l.Layout(l.list.Size())
  303. l.scroller.Refresh()
  304. l.layout.Layout.(*gridWrapLayout).updateGrid(true)
  305. canvas.Refresh(l.list)
  306. }
  307. func (l *gridWrapRenderer) Destroy() {
  308. }
  309. func (l *gridWrapRenderer) Objects() []fyne.CanvasObject {
  310. return l.objects
  311. }
  312. // Declare conformity with interfaces.
  313. var _ fyne.Widget = (*gridWrapItem)(nil)
  314. var _ fyne.Tappable = (*gridWrapItem)(nil)
  315. var _ desktop.Hoverable = (*gridWrapItem)(nil)
  316. type gridWrapItem struct {
  317. BaseWidget
  318. onTapped func()
  319. background *canvas.Rectangle
  320. child fyne.CanvasObject
  321. hovered, selected bool
  322. }
  323. func newGridWrapItem(child fyne.CanvasObject, tapped func()) *gridWrapItem {
  324. gw := &gridWrapItem{
  325. child: child,
  326. onTapped: tapped,
  327. }
  328. gw.ExtendBaseWidget(gw)
  329. return gw
  330. }
  331. // CreateRenderer is a private method to Fyne which links this widget to its renderer.
  332. func (gw *gridWrapItem) CreateRenderer() fyne.WidgetRenderer {
  333. gw.ExtendBaseWidget(gw)
  334. gw.background = canvas.NewRectangle(theme.HoverColor())
  335. gw.background.CornerRadius = theme.SelectionRadiusSize()
  336. gw.background.Hide()
  337. objects := []fyne.CanvasObject{gw.background, gw.child}
  338. return &gridWrapItemRenderer{widget.NewBaseRenderer(objects), gw}
  339. }
  340. // MinSize returns the size that this widget should not shrink below.
  341. func (gw *gridWrapItem) MinSize() fyne.Size {
  342. gw.ExtendBaseWidget(gw)
  343. return gw.BaseWidget.MinSize()
  344. }
  345. // MouseIn is called when a desktop pointer enters the widget.
  346. func (gw *gridWrapItem) MouseIn(*desktop.MouseEvent) {
  347. gw.hovered = true
  348. gw.Refresh()
  349. }
  350. // MouseMoved is called when a desktop pointer hovers over the widget.
  351. func (gw *gridWrapItem) MouseMoved(*desktop.MouseEvent) {
  352. }
  353. // MouseOut is called when a desktop pointer exits the widget.
  354. func (gw *gridWrapItem) MouseOut() {
  355. gw.hovered = false
  356. gw.Refresh()
  357. }
  358. // Tapped is called when a pointer tapped event is captured and triggers any tap handler.
  359. func (gw *gridWrapItem) Tapped(*fyne.PointEvent) {
  360. if gw.onTapped != nil {
  361. gw.selected = true
  362. gw.Refresh()
  363. gw.onTapped()
  364. }
  365. }
  366. // Declare conformity with the WidgetRenderer interface.
  367. var _ fyne.WidgetRenderer = (*gridWrapItemRenderer)(nil)
  368. type gridWrapItemRenderer struct {
  369. widget.BaseRenderer
  370. item *gridWrapItem
  371. }
  372. // MinSize calculates the minimum size of a listItem.
  373. // This is based on the size of the status indicator and the size of the child object.
  374. func (gw *gridWrapItemRenderer) MinSize() fyne.Size {
  375. return gw.item.child.MinSize()
  376. }
  377. // Layout the components of the listItem widget.
  378. func (gw *gridWrapItemRenderer) Layout(size fyne.Size) {
  379. gw.item.background.Resize(size)
  380. gw.item.child.Resize(size)
  381. }
  382. func (gw *gridWrapItemRenderer) Refresh() {
  383. gw.item.background.CornerRadius = theme.SelectionRadiusSize()
  384. if gw.item.selected {
  385. gw.item.background.FillColor = theme.SelectionColor()
  386. gw.item.background.Show()
  387. } else if gw.item.hovered {
  388. gw.item.background.FillColor = theme.HoverColor()
  389. gw.item.background.Show()
  390. } else {
  391. gw.item.background.Hide()
  392. }
  393. gw.item.background.Refresh()
  394. canvas.Refresh(gw.item.super())
  395. }
  396. // Declare conformity with Layout interface.
  397. var _ fyne.Layout = (*gridWrapLayout)(nil)
  398. type gridWrapLayout struct {
  399. list *GridWrap
  400. children []fyne.CanvasObject
  401. itemPool *syncPool
  402. visible map[GridWrapItemID]*gridWrapItem
  403. renderLock sync.Mutex
  404. }
  405. func newGridWrapLayout(list *GridWrap) fyne.Layout {
  406. l := &gridWrapLayout{list: list, itemPool: &syncPool{}, visible: make(map[GridWrapItemID]*gridWrapItem)}
  407. list.offsetUpdated = l.offsetUpdated
  408. return l
  409. }
  410. func (l *gridWrapLayout) Layout(_ []fyne.CanvasObject, _ fyne.Size) {
  411. l.updateGrid(true)
  412. }
  413. func (l *gridWrapLayout) MinSize(_ []fyne.CanvasObject) fyne.Size {
  414. if lenF := l.list.Length; lenF != nil {
  415. cols := l.list.getColCount()
  416. rows := float32(math.Ceil(float64(lenF()) / float64(cols)))
  417. return fyne.NewSize(l.list.itemMin.Width,
  418. (l.list.itemMin.Height+theme.Padding())*rows-theme.Padding())
  419. }
  420. return fyne.NewSize(0, 0)
  421. }
  422. func (l *gridWrapLayout) getItem() *gridWrapItem {
  423. item := l.itemPool.Obtain()
  424. if item == nil {
  425. if f := l.list.CreateItem; f != nil {
  426. item = newGridWrapItem(f(), nil)
  427. }
  428. }
  429. return item.(*gridWrapItem)
  430. }
  431. func (l *gridWrapLayout) offsetUpdated(pos fyne.Position) {
  432. if l.list.offsetY == pos.Y {
  433. return
  434. }
  435. l.list.offsetY = pos.Y
  436. l.updateGrid(false)
  437. }
  438. func (l *gridWrapLayout) setupGridItem(li *gridWrapItem, id GridWrapItemID, focus bool) {
  439. previousIndicator := li.selected
  440. li.selected = false
  441. for _, s := range l.list.selected {
  442. if id == s {
  443. li.selected = true
  444. break
  445. }
  446. }
  447. if focus {
  448. li.hovered = true
  449. li.Refresh()
  450. } else if previousIndicator != li.selected || li.hovered {
  451. li.hovered = false
  452. li.Refresh()
  453. }
  454. if f := l.list.UpdateItem; f != nil {
  455. f(id, li.child)
  456. }
  457. li.onTapped = func() {
  458. l.list.RefreshItem(l.list.currentFocus)
  459. canvas := fyne.CurrentApp().Driver().CanvasForObject(l.list)
  460. if canvas != nil {
  461. canvas.Focus(l.list)
  462. }
  463. l.list.currentFocus = id
  464. l.list.Select(id)
  465. }
  466. }
  467. func (l *GridWrap) getColCount() int {
  468. colCount := 1
  469. width := l.Size().Width
  470. if width > l.itemMin.Width {
  471. colCount = int(math.Floor(float64(width+theme.Padding()) / float64(l.itemMin.Width+theme.Padding())))
  472. }
  473. return colCount
  474. }
  475. func (l *gridWrapLayout) updateGrid(refresh bool) {
  476. // code here is a mashup of listLayout.updateList and gridWrapLayout.Layout
  477. l.renderLock.Lock()
  478. length := 0
  479. if f := l.list.Length; f != nil {
  480. length = f()
  481. }
  482. colCount := l.list.getColCount()
  483. visibleRowsCount := int(math.Ceil(float64(l.list.scroller.Size().Height)/float64(l.list.itemMin.Height+theme.Padding()))) + 1
  484. offY := l.list.offsetY - float32(math.Mod(float64(l.list.offsetY), float64(l.list.itemMin.Height+theme.Padding())))
  485. minRow := int(offY / (l.list.itemMin.Height + theme.Padding()))
  486. minItem := GridWrapItemID(minRow * colCount)
  487. maxRow := int(math.Min(float64(minRow+visibleRowsCount), math.Ceil(float64(length)/float64(colCount))))
  488. maxItem := GridWrapItemID(math.Min(float64(maxRow*colCount), float64(length-1)))
  489. if l.list.UpdateItem == nil {
  490. fyne.LogError("Missing UpdateCell callback required for GridWrap", nil)
  491. }
  492. wasVisible := l.visible
  493. l.visible = make(map[GridWrapItemID]*gridWrapItem)
  494. var cells []fyne.CanvasObject
  495. y := offY
  496. curItem := minItem
  497. for row := minRow; row <= maxRow && curItem <= maxItem; row++ {
  498. x := float32(0)
  499. for col := 0; col < colCount && curItem <= maxItem; col++ {
  500. c, ok := wasVisible[curItem]
  501. if !ok {
  502. c = l.getItem()
  503. if c == nil {
  504. continue
  505. }
  506. c.Resize(l.list.itemMin)
  507. }
  508. c.Move(fyne.NewPos(x, y))
  509. if refresh {
  510. c.Resize(l.list.itemMin)
  511. }
  512. x += l.list.itemMin.Width + theme.Padding()
  513. l.visible[curItem] = c
  514. cells = append(cells, c)
  515. curItem++
  516. }
  517. y += l.list.itemMin.Height + theme.Padding()
  518. }
  519. for id, old := range wasVisible {
  520. if _, ok := l.visible[id]; !ok {
  521. l.itemPool.Release(old)
  522. }
  523. }
  524. l.children = cells
  525. objects := l.children
  526. l.list.scroller.Content.(*fyne.Container).Objects = objects
  527. l.renderLock.Unlock() // user code should not be locked
  528. for row, obj := range l.visible {
  529. l.setupGridItem(obj, row, l.list.focused && l.list.currentFocus == row)
  530. }
  531. }