table.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. // Copyright 2016 The G3N 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. package gui
  5. import (
  6. "fmt"
  7. "math"
  8. "github.com/g3n/engine/math32"
  9. "github.com/g3n/engine/window"
  10. )
  11. //
  12. // Table implements a panel which can contains child panels
  13. // organized in rows and columns.
  14. //
  15. type Table struct {
  16. Panel // Embedded panel
  17. styles *TableStyles // pointer to current styles
  18. cols []TableColumn // array of columns descriptors
  19. colmap map[string]*TableColumn // maps column id to column descriptor
  20. firstRow int // index of the first visible row
  21. lastRow int // index of the last visible row
  22. rows []*tableRow // array of table rows
  23. headerHeight float32 // header height
  24. vscroll *ScrollBar // vertical scroll bar
  25. showHeader bool
  26. }
  27. // TableColumn describes a table column
  28. type TableColumn struct {
  29. Id string // Column id used to reference the column. Must be unique
  30. Name string // Column name shown in the header
  31. Width float32 // Column preferable width in pixels
  32. Hidden bool // Hidden flag
  33. Format string // Format string for numbers and strings
  34. Alignment Align // Cell content alignment: AlignNone|AlignLeft|AlignCenter|AlignRight
  35. Expand int // Width expansion factor
  36. order int // show order
  37. header *Panel // header panel
  38. label *Label // header label
  39. }
  40. // TableHeaderStyle describes the style of the table header
  41. type TableHeaderStyle struct {
  42. Border BorderSizes
  43. Paddings BorderSizes
  44. BorderColor math32.Color4
  45. BgColor math32.Color
  46. FgColor math32.Color
  47. }
  48. // TableRowStyle describes the style of the table row
  49. type TableRowStyle struct {
  50. Border BorderSizes
  51. Paddings BorderSizes
  52. BorderColor math32.Color4
  53. BgColor math32.Color
  54. FgColor math32.Color
  55. }
  56. // TableRowStyles describes all styles for the table row
  57. type TableRowStyles struct {
  58. Normal TableRowStyle
  59. Selected TableRowStyle
  60. }
  61. // TableStyles describes all styles of the table header and rows
  62. type TableStyles struct {
  63. Header *TableHeaderStyle
  64. Row *TableRowStyles
  65. }
  66. // TableClickEvent describes a mouse click event over a table
  67. type TableClickEvent struct {
  68. X float32 // Table content area X coordinate
  69. Y float32 // Table content area Y coordinate
  70. Header bool // True if header was clicked
  71. Row int // Index of table row (may be -1)
  72. Col string // Id of table column (may be empty)
  73. }
  74. // tableRow is panel which contains an entire table row of cells
  75. type tableRow struct {
  76. Panel // embedded panel
  77. selected bool // row selected flag
  78. cells []*tableCell // array of row cells
  79. }
  80. // tableCell is a panel which contains one cell (a label)
  81. type tableCell struct {
  82. Panel // embedded panel
  83. label Label // cell label
  84. value interface{} // cell current value
  85. }
  86. // NewTable creates and returns a pointer to a new Table with the
  87. // specified width, height and columns
  88. func NewTable(width, height float32, cols []TableColumn) (*Table, error) {
  89. t := new(Table)
  90. t.Panel.Initialize(width, height)
  91. t.styles = &StyleDefault.Table
  92. t.showHeader = true
  93. // Checks columns descriptors
  94. t.colmap = make(map[string]*TableColumn)
  95. t.cols = make([]TableColumn, len(cols))
  96. copy(t.cols, cols)
  97. for i := 0; i < len(t.cols); i++ {
  98. c := &t.cols[i]
  99. if c.Format == "" {
  100. c.Format = "%v"
  101. }
  102. c.order = i
  103. if c.Id == "" {
  104. return nil, fmt.Errorf("Column with empty id")
  105. }
  106. if t.colmap[c.Id] != nil {
  107. return nil, fmt.Errorf("Column with duplicate id")
  108. }
  109. t.colmap[c.Id] = c
  110. }
  111. // Create header panels
  112. for i := 0; i < len(t.cols); i++ {
  113. c := &t.cols[i]
  114. c.header = NewPanel(0, 0)
  115. t.applyHeaderStyle(c.header)
  116. c.label = NewLabel(c.Name)
  117. c.header.Add(c.label)
  118. width := c.Width
  119. if width < c.label.Width()+c.header.MinWidth() {
  120. width = c.label.Width() + c.header.MinWidth()
  121. }
  122. c.header.SetContentSize(width, c.label.Height())
  123. t.headerHeight = c.header.Height()
  124. t.Panel.Add(c.header)
  125. }
  126. t.recalcHeader()
  127. // Subscribe to events
  128. t.Panel.Subscribe(OnMouseUp, t.onMouse)
  129. t.Panel.Subscribe(OnMouseDown, t.onMouse)
  130. t.Panel.Subscribe(OnResize, func(evname string, ev interface{}) {
  131. t.recalc()
  132. })
  133. return t, nil
  134. }
  135. // ShowHeaders shows or hides the table header
  136. func (t *Table) ShowHeader(show bool) {
  137. if t.showHeader == show {
  138. return
  139. }
  140. t.showHeader = show
  141. for i := 0; i < len(t.cols); i++ {
  142. c := &t.cols[i]
  143. c.header.SetVisible(t.showHeader)
  144. }
  145. t.recalc()
  146. }
  147. // ShowColumn sets the visibility of the column with the specified id
  148. // If the column id does not exit the function panics.
  149. func (t *Table) ShowColumn(col string, show bool) {
  150. c := t.colmap[col]
  151. if c == nil {
  152. panic("Invalid column id")
  153. }
  154. if c.Hidden == !show {
  155. return
  156. }
  157. c.Hidden = show
  158. t.recalcHeader()
  159. t.recalc()
  160. }
  161. // Len returns the total number of rows of the table
  162. func (t *Table) Len() int {
  163. return len(t.rows)
  164. }
  165. // SetRows clears all current rows of the table and
  166. // sets new rows from the specifying parameter.
  167. // Each row is a map keyed by the colum id.
  168. // The map value currently can be a string or any number type
  169. // If a row column is not found it is ignored
  170. func (t *Table) SetRows(values []map[string]interface{}) {
  171. // Add missing rows
  172. if len(values) > len(t.rows) {
  173. count := len(values) - len(t.rows)
  174. for row := 0; row < count; row++ {
  175. t.insertRow(len(t.rows), nil)
  176. }
  177. // Remove remaining rows
  178. } else if len(values) < len(t.rows) {
  179. for row := len(values); row < len(t.rows); row++ {
  180. t.removeRow(row)
  181. }
  182. }
  183. // Set rows values
  184. for row := 0; row < len(values); row++ {
  185. t.SetRow(row, values[row])
  186. }
  187. t.firstRow = 0
  188. t.recalc()
  189. }
  190. // SetRow sets the value of all the cells of the specified row from
  191. // the specified map indexed by column id.
  192. func (t *Table) SetRow(row int, values map[string]interface{}) {
  193. if row < 0 || row >= len(t.rows) {
  194. panic("Invalid row index")
  195. }
  196. for ci := 0; ci < len(t.cols); ci++ {
  197. c := t.cols[ci]
  198. cv := values[c.Id]
  199. if cv == nil {
  200. continue
  201. }
  202. t.SetCell(row, c.Id, values[c.Id])
  203. }
  204. t.recalcRow(t.rows[row])
  205. }
  206. // SetCell sets the value of the cell specified by its row and column id
  207. func (t *Table) SetCell(row int, colid string, value interface{}) {
  208. if row < 0 || row >= len(t.rows) {
  209. panic("Invalid row index")
  210. }
  211. c := t.colmap[colid]
  212. if c == nil {
  213. return
  214. }
  215. cell := t.rows[row].cells[c.order]
  216. cell.label.SetText(fmt.Sprintf(c.Format, value))
  217. }
  218. // SetColFormat sets the formatting string (Printf) for the specified column
  219. // Update must be called to update the table.
  220. func (t *Table) SetColFormat(id, format string) error {
  221. c := t.colmap[id]
  222. if c == nil {
  223. return fmt.Errorf("No column with id:%s", id)
  224. }
  225. c.Format = format
  226. return nil
  227. }
  228. // InsertRow inserts the specified values in a new row at the specified index
  229. func (t *Table) InsertRow(row int, values map[string]interface{}) {
  230. t.insertRow(row, values)
  231. t.recalc()
  232. }
  233. // RemoveRow removes from the specified row from the table
  234. func (t *Table) RemoveRow(row int) {
  235. // Checks row index
  236. if row < 0 || row >= len(t.rows) {
  237. panic("Invalid row index")
  238. }
  239. t.removeRow(row)
  240. t.recalc()
  241. }
  242. // insertRow is the internal version of InsertRow which does not call recalc()
  243. func (t *Table) insertRow(row int, values map[string]interface{}) {
  244. // Checks row index
  245. if row < 0 || row > len(t.rows) {
  246. panic("Invalid row index")
  247. }
  248. // Creates tableRow panel
  249. trow := new(tableRow)
  250. trow.Initialize(0, 0)
  251. trow.cells = make([]*tableCell, 0)
  252. for ci := 0; ci < len(t.cols); ci++ {
  253. // Creates tableRow cell panel
  254. cell := new(tableCell)
  255. cell.Initialize(0, 0)
  256. cell.label.initialize("", StyleDefault.Font)
  257. cell.Add(&cell.label)
  258. trow.cells = append(trow.cells, cell)
  259. trow.Panel.Add(cell)
  260. }
  261. t.Panel.Add(trow)
  262. // Inserts tableRow in the table rows at the specified index
  263. t.rows = append(t.rows, nil)
  264. copy(t.rows[row+1:], t.rows[row:])
  265. t.rows[row] = trow
  266. t.updateRowStyle(row)
  267. // Sets the new row values from the specified map
  268. if values != nil {
  269. t.SetRow(row, values)
  270. }
  271. t.recalcRow(trow)
  272. }
  273. // removeRow removes from the table the row specified its index
  274. func (t *Table) removeRow(row int) {
  275. // Get row to be removed
  276. trow := t.rows[row]
  277. // Remove row from table
  278. copy(t.rows[row:], t.rows[row+1:])
  279. t.rows[len(t.rows)-1] = nil
  280. t.rows = t.rows[:len(t.rows)-1]
  281. // Dispose the row cell panels and its children
  282. for i := 0; i < len(trow.cells); i++ {
  283. cell := trow.cells[i]
  284. cell.DisposeChildren(true)
  285. cell.Dispose()
  286. }
  287. // Adjusts table first visible row if necessary
  288. //if t.firstRow == row {
  289. // t.firstRow--
  290. // if t.firstRow < 0 {
  291. // t.firstRow = 0
  292. // }
  293. //}
  294. }
  295. // AddRow adds a new row at the end of the table with the specified values
  296. func (t *Table) AddRow(values map[string]interface{}) {
  297. t.InsertRow(len(t.rows), values)
  298. }
  299. // onMouseEvent process subscribed mouse events
  300. func (t *Table) onMouse(evname string, ev interface{}) {
  301. e := ev.(*window.MouseEvent)
  302. switch evname {
  303. case OnMouseDown:
  304. tce := t.findClick(e)
  305. log.Error("Click:%+v", tce)
  306. case OnMouseUp:
  307. default:
  308. return
  309. }
  310. t.root.StopPropagation(StopAll)
  311. }
  312. // findClick finds where in the table the specified mouse click event
  313. // occurred updating the specified TableClickEvent with the click coordinates.
  314. func (t *Table) findClick(e *window.MouseEvent) TableClickEvent {
  315. x, y := t.ContentCoords(e.Xpos, e.Ypos)
  316. tce := TableClickEvent{X: x, Y: y, Row: -1}
  317. // Find column id
  318. colx := float32(0)
  319. for ci := 0; ci < len(t.cols); ci++ {
  320. c := t.cols[ci]
  321. if c.Hidden {
  322. continue
  323. }
  324. colx += c.header.Width()
  325. if x < colx {
  326. tce.Col = c.Id
  327. break
  328. }
  329. }
  330. // If column not found the user clicked at the right of rows
  331. if tce.Col == "" {
  332. return tce
  333. }
  334. // Checks if is in header
  335. if t.showHeader && y < t.headerHeight {
  336. tce.Header = true
  337. return tce
  338. }
  339. // Find row clicked
  340. rowy := float32(0)
  341. if t.showHeader {
  342. rowy = t.headerHeight
  343. }
  344. theight := t.ContentHeight()
  345. for ri := t.firstRow; ri < len(t.rows); ri++ {
  346. trow := t.rows[ri]
  347. rowy += trow.height
  348. if rowy > theight {
  349. break
  350. }
  351. if y < rowy {
  352. tce.Row = ri
  353. break
  354. }
  355. }
  356. return tce
  357. }
  358. // recalcHeader recalculates and sets the position and size of the header panels
  359. func (t *Table) recalcHeader() {
  360. posx := float32(0)
  361. for i := 0; i < len(t.cols); i++ {
  362. c := t.cols[i]
  363. if c.Hidden {
  364. continue
  365. }
  366. c.header.SetPosition(posx, 0)
  367. posx += c.header.Width()
  368. }
  369. }
  370. // recalc calculates the visibility, positions and sizes of all row cells.
  371. // should be called in the following situations:
  372. // - the table is resized
  373. // - row is added, inserted or removed
  374. // - column alignment and expansion changed
  375. // - column visibility is changed
  376. // - horizontal or vertical scroll position changed
  377. func (t *Table) recalc() {
  378. // Get initial Y coordinate and total height of the table for rows
  379. starty := t.headerHeight
  380. if !t.showHeader {
  381. starty = 0
  382. }
  383. theight := t.ContentHeight()
  384. // Determines if it is necessary to show the scrollbar or not.
  385. scroll := false
  386. py := starty
  387. for ri := 0; ri < len(t.rows); ri++ {
  388. trow := t.rows[ri]
  389. py += trow.height
  390. if py > theight {
  391. scroll = true
  392. t.lastRow = ri
  393. break
  394. }
  395. }
  396. t.setVScrollBar(scroll)
  397. // Sets the position and sizes of all cells of the visible rows
  398. py = starty
  399. for ri := 0; ri < len(t.rows); ri++ {
  400. trow := t.rows[ri]
  401. // If row is before first row or its y coordinate is greater the table height,
  402. // sets it invisible
  403. if ri < t.firstRow || py > theight {
  404. trow.SetVisible(false)
  405. continue
  406. }
  407. // Set row y position and visible
  408. trow.SetPosition(0, py)
  409. trow.SetVisible(true)
  410. //log.Error("ri:%v py:%v theight:%v", ri, py, theight)
  411. py += trow.height
  412. }
  413. }
  414. // recalcRow recalculates the positions and sizes of all cells of the specified row
  415. // Should be called when the row is created and column visibility or order is changed.
  416. func (t *Table) recalcRow(trow *tableRow) {
  417. // Calculates and sets row height
  418. maxheight := float32(0)
  419. for ci := 0; ci < len(t.cols); ci++ {
  420. // If column is hidden, ignore
  421. c := t.cols[ci]
  422. if c.Hidden {
  423. continue
  424. }
  425. cell := trow.cells[c.order]
  426. cellHeight := cell.MinHeight() + cell.label.Height()
  427. if cellHeight > maxheight {
  428. maxheight = cellHeight
  429. }
  430. }
  431. trow.SetContentHeight(maxheight)
  432. // Sets row cells sizes and positions and sets row width
  433. px := float32(0)
  434. for ci := 0; ci < len(t.cols); ci++ {
  435. // If column is hidden, ignore
  436. c := t.cols[ci]
  437. if c.Hidden {
  438. continue
  439. }
  440. // Sets cell position and size
  441. cell := trow.cells[c.order]
  442. cell.SetPosition(px, 0)
  443. cell.SetSize(c.header.Width(), trow.ContentHeight())
  444. px += c.header.Width()
  445. }
  446. trow.SetContentWidth(px)
  447. }
  448. func (t *Table) sortCols() {
  449. }
  450. // setVScrollBar sets the visibility state of the vertical scrollbar
  451. func (t *Table) setVScrollBar(state bool) {
  452. // Visible
  453. if state {
  454. var scrollWidth float32 = 20
  455. // Creates scroll bar if necessary
  456. if t.vscroll == nil {
  457. t.vscroll = NewVScrollBar(0, 0)
  458. t.vscroll.SetBorders(0, 0, 0, 1)
  459. t.vscroll.Subscribe(OnChange, t.onVScrollBarEvent)
  460. t.Panel.Add(t.vscroll)
  461. }
  462. // Initial y coordinate and height
  463. py := float32(0)
  464. height := t.ContentHeight()
  465. if t.showHeader {
  466. py = t.headerHeight
  467. height -= py
  468. }
  469. t.vscroll.SetSize(scrollWidth, height)
  470. t.vscroll.SetPositionX(t.ContentWidth() - scrollWidth)
  471. t.vscroll.SetPositionY(py)
  472. t.vscroll.recalc()
  473. t.vscroll.SetVisible(true)
  474. // Not visible
  475. } else {
  476. if t.vscroll != nil {
  477. t.vscroll.SetVisible(false)
  478. }
  479. }
  480. }
  481. // onVScrollBarEvent is called when a vertical scroll bar event is received
  482. func (t *Table) onVScrollBarEvent(evname string, ev interface{}) {
  483. pos := t.vscroll.Value()
  484. maxFirst := t.calcMaxFirst()
  485. first := int(math.Floor((float64(maxFirst) * pos) + 0.5))
  486. //log.Error("maxFirst:%v first:%v", maxFirst, first)
  487. if first == t.firstRow {
  488. return
  489. }
  490. //s.scrollBarEvent = true
  491. t.firstRow = first
  492. t.recalc()
  493. }
  494. // calcMaxFirst calculates the maximum index of the first visible row
  495. // such as the remaing rows fits completely inside the table
  496. // It is used when scrolling the table vertically
  497. func (t *Table) calcMaxFirst() int {
  498. // Get table height for rows considering if header is shown or not
  499. total := t.ContentHeight()
  500. if t.showHeader {
  501. total -= t.headerHeight
  502. }
  503. ri := len(t.rows) - 1
  504. if ri < 0 {
  505. return 0
  506. }
  507. height := float32(0)
  508. for {
  509. trow := t.rows[ri]
  510. height += trow.height
  511. if height > total {
  512. break
  513. }
  514. ri--
  515. if ri < 0 {
  516. break
  517. }
  518. }
  519. return ri + 1
  520. }
  521. // updateRowStyle applies the correct style for the specified row
  522. func (t *Table) updateRowStyle(ri int) {
  523. row := t.rows[ri]
  524. if row.selected {
  525. t.applyRowStyle(row, &t.styles.Row.Selected)
  526. return
  527. }
  528. t.applyRowStyle(row, &t.styles.Row.Normal)
  529. }
  530. // applyRowStyle applies the specified style to all cells for the specified table row
  531. func (t *Table) applyRowStyle(row *tableRow, trs *TableRowStyle) {
  532. for i := 0; i < len(row.cells); i++ {
  533. cell := row.cells[i]
  534. cell.SetBordersFrom(&trs.Border)
  535. cell.SetBordersColor4(&trs.BorderColor)
  536. cell.SetPaddingsFrom(&trs.Paddings)
  537. cell.SetColor(&trs.BgColor)
  538. }
  539. }
  540. // applyStyle applies the specified menu body style
  541. func (t *Table) applyHeaderStyle(hp *Panel) {
  542. s := t.styles.Header
  543. hp.SetBordersFrom(&s.Border)
  544. hp.SetBordersColor4(&s.BorderColor)
  545. hp.SetPaddingsFrom(&s.Paddings)
  546. hp.SetColor(&s.BgColor)
  547. }