table.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  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. "sort"
  9. "strconv"
  10. "github.com/g3n/engine/gui/assets"
  11. "github.com/g3n/engine/math32"
  12. "github.com/g3n/engine/window"
  13. )
  14. const (
  15. // Name of the event generated when the table is right or left clicked
  16. // Parameter is TableClickEvent
  17. OnTableClick = "onTableClick"
  18. // Name of the event generated when the table row count changes (no parameters)
  19. OnTableRowCount = "onTableRowCount"
  20. )
  21. // TableSortType is the type used to specify the sort method for a table column
  22. type TableSortType int
  23. const (
  24. TableSortNone TableSortType = iota
  25. TableSortString
  26. TableSortNumber
  27. )
  28. // TableSelType is the type used to specify the table row selection
  29. type TableSelType int
  30. const (
  31. // Single row selection mode (default)
  32. TableSelSingleRow = iota
  33. // Multiple row selection mode
  34. TableSelMultiRow
  35. )
  36. const (
  37. tableSortedNoneIcon = assets.SwapVert
  38. tableSortedAscIcon = assets.ArrowDownward
  39. tableSortedDescIcon = assets.ArrowUpward
  40. tableSortedNone = 0
  41. tableSortedAsc = 1
  42. tableSortedDesc = 2
  43. tableResizerPix = 4
  44. tableColMinWidth = 16
  45. tableErrInvRow = "Invalid row index"
  46. tableErrInvCol = "Invalid column id"
  47. )
  48. //
  49. // Table implements a panel which can contains child panels
  50. // organized in rows and columns.
  51. //
  52. type Table struct {
  53. Panel // Embedded panel
  54. styles *TableStyles // pointer to current styles
  55. header tableHeader // table headers
  56. rows []*tableRow // array of table rows
  57. rowCursor int // index of row cursor
  58. firstRow int // index of the first visible row
  59. lastRow int // index of the last visible row
  60. vscroll *ScrollBar // vertical scroll bar
  61. statusPanel Panel // optional bottom status panel
  62. statusLabel *Label // status label
  63. scrollBarEvent bool // do not update the scrollbar value in recalc() if true
  64. resizerPanel Panel // resizer panel
  65. resizeCol int // column being resized
  66. resizerX float32 // initial resizer x coordinate
  67. resizing bool // dragging the column resizer
  68. selType TableSelType // table selection type
  69. }
  70. // TableColumn describes a table column
  71. type TableColumn struct {
  72. Id string // Column id used to reference the column. Must be unique
  73. Header string // Column name shown in the table header
  74. Width float32 // Initial column width in pixels
  75. Minwidth float32 // Minimum width in pixels for this column
  76. Hidden bool // Hidden flag
  77. Align Align // Cell content alignment: AlignLeft|AlignCenter|AlignRight
  78. Format string // Format string for formatting the columns' cells
  79. FormatFunc TableFormatFunc // Format function (overrides Format string)
  80. Expand float32 // Column width expansion factor (0 for no expansion)
  81. Sort TableSortType // Column sort type
  82. Resize bool // Allow column to be resized by user
  83. }
  84. // TableCell describes a table cell.
  85. // It is used as a parameter for formatting function
  86. type TableCell struct {
  87. Tab *Table // Pointer to table
  88. Row int // Row index
  89. Col string // Column id
  90. Value interface{} // Cell value
  91. }
  92. // TableFormatFunc is the type for formatting functions
  93. type TableFormatFunc func(cell TableCell) string
  94. // TableHeaderStyle describes the style of the table header
  95. type TableHeaderStyle struct {
  96. Border BorderSizes
  97. Paddings BorderSizes
  98. BorderColor math32.Color4
  99. BgColor math32.Color
  100. FgColor math32.Color
  101. }
  102. // TableRowStyle describes the style of the table row
  103. type TableRowStyle struct {
  104. Border BorderSizes
  105. Paddings BorderSizes
  106. BorderColor math32.Color4
  107. BgColor math32.Color
  108. FgColor math32.Color
  109. }
  110. // TableRowStyles describes all styles for the table row
  111. type TableRowStyles struct {
  112. Normal TableRowStyle
  113. Selected TableRowStyle
  114. }
  115. // TableStatusStyle describes the style of the table status line panel
  116. type TableStatusStyle struct {
  117. Border BorderSizes
  118. Paddings BorderSizes
  119. BorderColor math32.Color4
  120. BgColor math32.Color
  121. FgColor math32.Color
  122. }
  123. // TableResizerStyle describes the style of the table resizer panel
  124. type TableResizerStyle struct {
  125. Width float32
  126. Border BorderSizes
  127. BorderColor math32.Color4
  128. BgColor math32.Color4
  129. }
  130. // TableStyles describes all styles of the table header and rows
  131. type TableStyles struct {
  132. Header *TableHeaderStyle
  133. RowEven *TableRowStyle
  134. RowOdd *TableRowStyle
  135. RowCursor *TableRowStyle
  136. RowSel *TableRowStyle
  137. Status *TableStatusStyle
  138. Resizer *TableResizerStyle
  139. }
  140. // TableClickEvent describes a mouse click event over a table
  141. // It contains the original mouse event plus additional information
  142. type TableClickEvent struct {
  143. window.MouseEvent // Embedded window mouse event
  144. X float32 // Table content area X coordinate
  145. Y float32 // Table content area Y coordinate
  146. Header bool // True if header was clicked
  147. Row int // Index of table row (may be -1)
  148. Col string // Id of table column (may be empty)
  149. ColOrder int // Current column exhibition order
  150. }
  151. // tableHeader is panel which contains the individual header panels for each column
  152. type tableHeader struct {
  153. Panel // embedded panel
  154. cmap map[string]*tableColHeader // maps column id with its panel/descriptor
  155. cols []*tableColHeader // array of individual column headers/descriptors
  156. lastPan Panel // last header panel not associated with a user column
  157. }
  158. // tableColHeader is panel for a column header
  159. type tableColHeader struct {
  160. Panel // header panel
  161. label *Label // header label
  162. ricon *Label // header right icon (sort direction)
  163. id string // column id
  164. width float32 // initial column width
  165. minWidth float32 // minimum width
  166. format string // column format string
  167. formatFunc TableFormatFunc // column format function
  168. align Align // column alignment
  169. expand float32 // column expand factor
  170. sort TableSortType // column sort type
  171. resize bool // column can be resized by user
  172. order int // row columns order
  173. sorted int // current sorted status
  174. xl float32 // left border coordinate in pixels
  175. xr float32 // right border coordinate in pixels
  176. }
  177. // tableRow is panel which contains an entire table row of cells
  178. type tableRow struct {
  179. Panel // embedded panel
  180. selected bool // row selected flag
  181. cells []*tableCell // array of row cells
  182. }
  183. // tableCell is a panel which contains one cell (a label)
  184. type tableCell struct {
  185. Panel // embedded panel
  186. label Label // cell label
  187. value interface{} // cell current value
  188. }
  189. // NewTable creates and returns a pointer to a new Table with the
  190. // specified width, height and columns
  191. func NewTable(width, height float32, cols []TableColumn) (*Table, error) {
  192. t := new(Table)
  193. t.Panel.Initialize(width, height)
  194. t.styles = &StyleDefault.Table
  195. t.rowCursor = -1
  196. // Initialize table header
  197. t.header.Initialize(0, 0)
  198. t.header.cmap = make(map[string]*tableColHeader)
  199. t.header.cols = make([]*tableColHeader, 0)
  200. // Create column header panels
  201. for ci := 0; ci < len(cols); ci++ {
  202. cdesc := cols[ci]
  203. // Column id must not be empty
  204. if cdesc.Id == "" {
  205. return nil, fmt.Errorf("Column with empty id")
  206. }
  207. // Column id must be unique
  208. if t.header.cmap[cdesc.Id] != nil {
  209. return nil, fmt.Errorf("Column with duplicate id")
  210. }
  211. // Creates a column header
  212. c := new(tableColHeader)
  213. c.Initialize(0, 0)
  214. t.applyHeaderStyle(&c.Panel, false)
  215. c.label = NewLabel(cdesc.Header)
  216. c.Add(c.label)
  217. c.id = cdesc.Id
  218. c.minWidth = cdesc.Minwidth
  219. if c.minWidth < tableColMinWidth {
  220. c.minWidth = tableColMinWidth
  221. }
  222. c.width = cdesc.Width
  223. if c.width < c.minWidth {
  224. c.width = c.minWidth
  225. }
  226. c.align = cdesc.Align
  227. c.format = cdesc.Format
  228. c.formatFunc = cdesc.FormatFunc
  229. c.expand = cdesc.Expand
  230. c.sort = cdesc.Sort
  231. c.resize = cdesc.Resize
  232. // Adds optional sort icon
  233. if c.sort != TableSortNone {
  234. c.ricon = NewIconLabel(string(tableSortedNoneIcon))
  235. c.Add(c.ricon)
  236. c.ricon.Subscribe(OnMouseDown, func(evname string, ev interface{}) {
  237. t.onRicon(evname, c)
  238. })
  239. }
  240. // Sets default format and order
  241. if c.format == "" {
  242. c.format = "%v"
  243. }
  244. c.order = ci
  245. c.SetVisible(!cdesc.Hidden)
  246. t.header.cmap[c.id] = c
  247. // Sets column header width and height
  248. width := cdesc.Width
  249. if width < c.label.Width()+c.MinWidth() {
  250. width = c.label.Width() + c.MinWidth()
  251. }
  252. c.SetContentSize(width, c.label.Height())
  253. // Adds the column header to the header panel
  254. t.header.cols = append(t.header.cols, c)
  255. t.header.Panel.Add(c)
  256. }
  257. // Creates last header
  258. t.header.lastPan.Initialize(0, 0)
  259. t.applyHeaderStyle(&t.header.lastPan, true)
  260. t.header.Panel.Add(&t.header.lastPan)
  261. // Add header panel to the table panel
  262. t.Panel.Add(&t.header)
  263. // Creates resizer panel
  264. t.resizerPanel.Initialize(t.styles.Resizer.Width, 0)
  265. t.resizerPanel.SetVisible(false)
  266. t.applyResizerStyle()
  267. t.Panel.Add(&t.resizerPanel)
  268. // Creates status panel
  269. t.statusPanel.Initialize(0, 0)
  270. t.statusPanel.SetVisible(false)
  271. t.statusLabel = NewLabel("")
  272. t.applyStatusStyle()
  273. t.statusPanel.Add(t.statusLabel)
  274. t.Panel.Add(&t.statusPanel)
  275. // Subscribe to events
  276. t.Panel.Subscribe(OnCursorEnter, t.onCursor)
  277. t.Panel.Subscribe(OnCursorLeave, t.onCursor)
  278. t.Panel.Subscribe(OnCursor, t.onCursorPos)
  279. t.Panel.Subscribe(OnScroll, t.onScroll)
  280. t.Panel.Subscribe(OnMouseUp, t.onMouse)
  281. t.Panel.Subscribe(OnMouseDown, t.onMouse)
  282. t.Panel.Subscribe(OnKeyDown, t.onKey)
  283. t.Panel.Subscribe(OnKeyRepeat, t.onKey)
  284. t.Panel.Subscribe(OnResize, t.onResize)
  285. t.recalc()
  286. return t, nil
  287. }
  288. // SetStyles set this table styles overriding the default
  289. func (t *Table) SetStyles(ts *TableStyles) {
  290. t.styles = ts
  291. t.recalc()
  292. }
  293. // SetSelectionType sets this table selection type
  294. // Possible values are: TableSelSingleRow|TableSelMultiRow
  295. func (t *Table) SetSelectionType(sel TableSelType) {
  296. t.selType = sel
  297. }
  298. // ShowHeader shows or hides the table header
  299. func (t *Table) ShowHeader(show bool) {
  300. if t.header.Visible() == show {
  301. return
  302. }
  303. t.header.SetVisible(show)
  304. t.recalc()
  305. }
  306. // ShowColumn sets the visibility of the column with the specified id
  307. // If the column id does not exit the function panics.
  308. func (t *Table) ShowColumn(col string, show bool) {
  309. c := t.header.cmap[col]
  310. if c == nil {
  311. panic(tableErrInvCol)
  312. }
  313. if c.Visible() == show {
  314. return
  315. }
  316. c.SetVisible(show)
  317. t.recalc()
  318. }
  319. // ShowAllColumns shows all the table columns
  320. func (t *Table) ShowAllColumns() {
  321. recalc := false
  322. for ci := 0; ci < len(t.header.cols); ci++ {
  323. c := t.header.cols[ci]
  324. if !c.Visible() {
  325. c.SetVisible(true)
  326. recalc = true
  327. }
  328. }
  329. if !recalc {
  330. return
  331. }
  332. t.recalc()
  333. }
  334. // RowCount returns the current number of rows in the table
  335. func (t *Table) RowCount() int {
  336. return len(t.rows)
  337. }
  338. // SetRows clears all current rows of the table and
  339. // sets new rows from the specifying parameter.
  340. // Each row is a map keyed by the colum id.
  341. // The map value currently can be a string or any number type
  342. // If a row column is not found it is ignored
  343. func (t *Table) SetRows(values []map[string]interface{}) {
  344. // Add missing rows
  345. if len(values) > len(t.rows) {
  346. count := len(values) - len(t.rows)
  347. for row := 0; row < count; row++ {
  348. t.insertRow(len(t.rows), nil)
  349. }
  350. // Remove remaining rows
  351. } else if len(values) < len(t.rows) {
  352. for row := len(values); row < len(t.rows); row++ {
  353. t.removeRow(row)
  354. }
  355. }
  356. // Set rows values
  357. for row := 0; row < len(values); row++ {
  358. t.setRow(row, values[row])
  359. }
  360. t.firstRow = 0
  361. t.rowCursor = -1
  362. t.recalc()
  363. }
  364. // SetRow sets the value of all the cells of the specified row from
  365. // the specified map indexed by column id.
  366. func (t *Table) SetRow(row int, values map[string]interface{}) {
  367. if row < 0 || row >= len(t.rows) {
  368. panic(tableErrInvRow)
  369. }
  370. t.setRow(row, values)
  371. t.recalc()
  372. }
  373. // SetCell sets the value of the cell specified by its row and column id
  374. // The function panics if the passed row or column id is invalid
  375. func (t *Table) SetCell(row int, colid string, value interface{}) {
  376. if row < 0 || row >= len(t.rows) {
  377. panic(tableErrInvRow)
  378. }
  379. if t.header.cmap[colid] == nil {
  380. panic(tableErrInvCol)
  381. }
  382. t.setCell(row, colid, value)
  383. t.recalc()
  384. }
  385. // SetColFormat sets the formatting string (Printf) for the specified column
  386. // Update must be called to update the table.
  387. func (t *Table) SetColFormat(id, format string) {
  388. c := t.header.cmap[id]
  389. if c == nil {
  390. panic(tableErrInvCol)
  391. }
  392. c.format = format
  393. }
  394. // SetColOrder sets the exhibition order of the specified column.
  395. // The previous column which has the specified order will have
  396. // the original column order.
  397. func (t *Table) SetColOrder(colid string, order int) {
  398. // Checks column id
  399. c := t.header.cmap[colid]
  400. if c == nil {
  401. panic(tableErrInvCol)
  402. }
  403. // Checks exhibition order
  404. if order < 0 || order > len(t.header.cols) {
  405. panic(tableErrInvRow)
  406. }
  407. // Find the exhibition order for the specified column
  408. for ci := 0; ci < len(t.header.cols); ci++ {
  409. if t.header.cols[ci] == c {
  410. // If the order of the specified column is the same, nothing to do
  411. if ci == order {
  412. return
  413. }
  414. // Swap column orders
  415. prev := t.header.cols[order]
  416. t.header.cols[order] = c
  417. t.header.cols[ci] = prev
  418. break
  419. }
  420. }
  421. // Recalculates the header and all rows
  422. t.recalc()
  423. }
  424. // EnableColResize enable or disables if the specified column can be resized by the
  425. // user using the mouse.
  426. func (t *Table) EnableColResize(colid string, enable bool) {
  427. // Checks column id
  428. c := t.header.cmap[colid]
  429. if c == nil {
  430. panic(tableErrInvCol)
  431. }
  432. c.resize = enable
  433. }
  434. // SetColWidth sets the specified column width and may
  435. // change the widths of the columns to the right
  436. func (t *Table) SetColWidth(colid string, width float32) {
  437. // Checks column id
  438. c := t.header.cmap[colid]
  439. if c == nil {
  440. panic(tableErrInvCol)
  441. }
  442. t.setColWidth(c, width)
  443. }
  444. // SetColExpand sets the column expand factor.
  445. // When the table width is increased the columns widths are
  446. // increased proportionally to their expand factor.
  447. // A column with expand factor = 0 is not increased.
  448. func (t *Table) SetColExpand(colid string, expand float32) {
  449. // Checks column id
  450. c := t.header.cmap[colid]
  451. if c == nil {
  452. panic(tableErrInvCol)
  453. }
  454. if expand < 0 {
  455. c.expand = 0
  456. } else {
  457. c.expand = expand
  458. }
  459. t.recalc()
  460. }
  461. // AddRow adds a new row at the end of the table with the specified values
  462. func (t *Table) AddRow(values map[string]interface{}) {
  463. t.InsertRow(len(t.rows), values)
  464. }
  465. // InsertRow inserts the specified values in a new row at the specified index
  466. func (t *Table) InsertRow(row int, values map[string]interface{}) {
  467. // Checks row index
  468. if row < 0 || row > len(t.rows) {
  469. panic(tableErrInvRow)
  470. }
  471. t.insertRow(row, values)
  472. t.recalc()
  473. t.Dispatch(OnTableRowCount, nil)
  474. }
  475. // RemoveRow removes from the specified row from the table
  476. func (t *Table) RemoveRow(row int) {
  477. // Checks row index
  478. if row < 0 || row >= len(t.rows) {
  479. panic(tableErrInvRow)
  480. }
  481. t.removeRow(row)
  482. maxFirst := t.calcMaxFirst()
  483. if t.firstRow > maxFirst {
  484. t.firstRow = maxFirst
  485. }
  486. t.recalc()
  487. t.Dispatch(OnTableRowCount, nil)
  488. }
  489. // Clear removes all rows from the table
  490. func (t *Table) Clear() {
  491. for ri := 0; ri < len(t.rows); ri++ {
  492. trow := t.rows[ri]
  493. trow.DisposeChildren(true)
  494. trow.Dispose()
  495. }
  496. t.rows = nil
  497. t.firstRow = 0
  498. t.rowCursor = -1
  499. t.recalc()
  500. t.Dispatch(OnTableRowCount, nil)
  501. }
  502. // SelectedRows returns a slice with the indexes of the currently selected rows
  503. // If no row are selected returns an empty slice
  504. func (t *Table) SelectedRows() []int {
  505. res := make([]int, 0)
  506. if t.rowCursor >= 0 {
  507. res = append(res, t.rowCursor)
  508. }
  509. for ri := 0; ri < len(t.rows); ri++ {
  510. if t.rows[ri].selected && ri != t.rowCursor {
  511. res = append(res, ri)
  512. }
  513. }
  514. return res
  515. }
  516. // ShowStatus sets the visibility of the status lines at the bottom of the table
  517. func (t *Table) ShowStatus(show bool) {
  518. if t.statusPanel.Visible() == show {
  519. return
  520. }
  521. t.statusPanel.SetVisible(show)
  522. t.recalcStatus()
  523. t.recalc()
  524. }
  525. // SetStatusText sets the text of status line at the bottom of the table
  526. // It does not change its current visibility
  527. func (t *Table) SetStatusText(text string) {
  528. t.statusLabel.SetText(text)
  529. }
  530. // Rows returns a slice of maps with the contents of the table rows
  531. // specified by the rows first and last index.
  532. // To get all the table rows, use Rows(0, -1)
  533. func (t *Table) Rows(fi, li int) []map[string]interface{} {
  534. if fi < 0 || fi >= len(t.header.cols) {
  535. panic(tableErrInvRow)
  536. }
  537. if li < 0 {
  538. li = len(t.rows) - 1
  539. } else if li < 0 || li >= len(t.rows) {
  540. panic(tableErrInvRow)
  541. }
  542. if li < fi {
  543. panic("Last index less than first index")
  544. }
  545. res := make([]map[string]interface{}, li-li+1)
  546. for ri := fi; ri <= li; ri++ {
  547. trow := t.rows[ri]
  548. rmap := make(map[string]interface{})
  549. for ci := 0; ci < len(t.header.cols); ci++ {
  550. c := t.header.cols[ci]
  551. rmap[c.id] = trow.cells[c.order].value
  552. }
  553. res = append(res, rmap)
  554. }
  555. return res
  556. }
  557. // Row returns a map with the current contents of the specified row index
  558. func (t *Table) Row(ri int) map[string]interface{} {
  559. if ri < 0 || ri > len(t.header.cols) {
  560. panic(tableErrInvRow)
  561. }
  562. res := make(map[string]interface{})
  563. trow := t.rows[ri]
  564. for ci := 0; ci < len(t.header.cols); ci++ {
  565. c := t.header.cols[ci]
  566. res[c.id] = trow.cells[c.order].value
  567. }
  568. return res
  569. }
  570. // Cell returns the current content of the specified cell
  571. func (t *Table) Cell(col string, ri int) interface{} {
  572. c := t.header.cmap[col]
  573. if c == nil {
  574. panic(tableErrInvCol)
  575. }
  576. if ri < 0 || ri >= len(t.rows) {
  577. panic(tableErrInvRow)
  578. }
  579. trow := t.rows[ri]
  580. return trow.cells[c.order].value
  581. }
  582. // SortColumn sorts the specified column interpreting its values as strings or numbers
  583. // and sorting in ascending or descending order.
  584. // This sorting is independent of the sort configuration of column set when the table was created
  585. func (t *Table) SortColumn(col string, asString bool, asc bool) {
  586. c := t.header.cmap[col]
  587. if c == nil {
  588. panic(tableErrInvCol)
  589. }
  590. if len(t.rows) < 2 {
  591. return
  592. }
  593. if asString {
  594. ts := tableSortString{rows: t.rows, col: c.order, asc: asc, format: c.format}
  595. sort.Sort(ts)
  596. } else {
  597. ts := tableSortNumber{rows: t.rows, col: c.order, asc: asc}
  598. sort.Sort(ts)
  599. }
  600. t.recalc()
  601. }
  602. // setRow sets the value of all the cells of the specified row from
  603. // the specified map indexed by column id.
  604. func (t *Table) setRow(row int, values map[string]interface{}) {
  605. for ci := 0; ci < len(t.header.cols); ci++ {
  606. c := t.header.cols[ci]
  607. cv, ok := values[c.id]
  608. if !ok {
  609. continue
  610. }
  611. t.setCell(row, c.id, cv)
  612. }
  613. }
  614. // setCell sets the value of the cell specified by its row and column id
  615. func (t *Table) setCell(row int, colid string, value interface{}) {
  616. c := t.header.cmap[colid]
  617. if c == nil {
  618. return
  619. }
  620. cell := t.rows[row].cells[c.order]
  621. cell.label.SetText(fmt.Sprintf(c.format, value))
  622. cell.value = value
  623. }
  624. // insertRow is the internal version of InsertRow which does not call recalc()
  625. func (t *Table) insertRow(row int, values map[string]interface{}) {
  626. // Creates tableRow panel
  627. trow := new(tableRow)
  628. trow.Initialize(0, 0)
  629. trow.cells = make([]*tableCell, 0)
  630. for ci := 0; ci < len(t.header.cols); ci++ {
  631. // Creates tableRow cell panel
  632. cell := new(tableCell)
  633. cell.Initialize(0, 0)
  634. cell.label.initialize("", StyleDefault.Font)
  635. cell.Add(&cell.label)
  636. trow.cells = append(trow.cells, cell)
  637. trow.Panel.Add(cell)
  638. }
  639. t.Panel.Add(trow)
  640. // Inserts tableRow in the table rows at the specified index
  641. t.rows = append(t.rows, nil)
  642. copy(t.rows[row+1:], t.rows[row:])
  643. t.rows[row] = trow
  644. t.updateRowStyle(row)
  645. // Sets the new row values from the specified map
  646. if values != nil {
  647. t.SetRow(row, values)
  648. }
  649. t.recalcRow(row)
  650. }
  651. // ScrollDown scrolls the table the specified number of rows down if possible
  652. func (t *Table) scrollDown(n int) {
  653. // Calculates number of rows to scroll down
  654. maxFirst := t.calcMaxFirst()
  655. maxScroll := maxFirst - t.firstRow
  656. if maxScroll <= 0 {
  657. return
  658. }
  659. if n > maxScroll {
  660. n = maxScroll
  661. }
  662. t.firstRow += n
  663. if t.rowCursor < t.firstRow {
  664. t.rowCursor = t.firstRow
  665. t.Dispatch(OnChange, nil)
  666. }
  667. t.recalc()
  668. return
  669. }
  670. // ScrollUp scrolls the table the specified number of rows up if possible
  671. func (t *Table) scrollUp(n int) {
  672. // Calculates number of rows to scroll up
  673. if t.firstRow == 0 {
  674. return
  675. }
  676. if n > t.firstRow {
  677. n = t.firstRow
  678. }
  679. t.firstRow -= n
  680. lastRow := t.lastRow - n
  681. if t.rowCursor > lastRow {
  682. t.rowCursor = lastRow
  683. t.Dispatch(OnChange, nil)
  684. }
  685. t.recalc()
  686. }
  687. // removeRow removes from the table the row specified its index
  688. func (t *Table) removeRow(row int) {
  689. // Get row to be removed
  690. trow := t.rows[row]
  691. // Remove row from table
  692. copy(t.rows[row:], t.rows[row+1:])
  693. t.rows[len(t.rows)-1] = nil
  694. t.rows = t.rows[:len(t.rows)-1]
  695. // Dispose row resources
  696. trow.DisposeChildren(true)
  697. trow.Dispose()
  698. }
  699. // onCursor process subscribed cursor events
  700. func (t *Table) onCursor(evname string, ev interface{}) {
  701. switch evname {
  702. case OnCursorEnter:
  703. t.root.SetScrollFocus(t)
  704. case OnCursorLeave:
  705. t.root.SetScrollFocus(nil)
  706. }
  707. t.root.StopPropagation(Stop3D)
  708. }
  709. // onCursorPos process subscribed cursor position events
  710. func (t *Table) onCursorPos(evname string, ev interface{}) {
  711. // Convert mouse window coordinates to table content coordinates
  712. kev := ev.(*window.CursorEvent)
  713. cx, _ := t.ContentCoords(kev.Xpos, kev.Ypos)
  714. // If user is dragging the resizer, updates its position
  715. if t.resizing {
  716. t.resizerPanel.SetPosition(cx, 0)
  717. return
  718. }
  719. // Checks if the mouse cursor is near the border of a resizable column
  720. found := false
  721. for ci := 0; ci < len(t.header.cols); ci++ {
  722. c := t.header.cols[ci]
  723. dx := math32.Abs(cx - c.xr)
  724. if dx < tableResizerPix {
  725. if c.resize {
  726. found = true
  727. t.resizeCol = ci
  728. t.resizerX = c.xr
  729. t.root.SetCursorHResize()
  730. }
  731. break
  732. }
  733. }
  734. // If column not found but previously was near a resizable column,
  735. // resets the the window cursor.
  736. if !found && t.resizeCol >= 0 {
  737. t.root.SetCursorNormal()
  738. t.resizeCol = -1
  739. }
  740. t.root.StopPropagation(Stop3D)
  741. }
  742. // onMouseEvent process subscribed mouse events
  743. func (t *Table) onMouse(evname string, ev interface{}) {
  744. e := ev.(*window.MouseEvent)
  745. t.root.SetKeyFocus(t)
  746. switch evname {
  747. case OnMouseDown:
  748. // If over a resizable column border, shows the resizer panel
  749. if t.resizeCol >= 0 && e.Button == window.MouseButtonLeft {
  750. t.resizing = true
  751. height := t.ContentHeight()
  752. if t.statusPanel.Visible() {
  753. height -= t.statusPanel.Height()
  754. }
  755. px := t.resizerX - t.resizerPanel.Width()/2
  756. t.resizerPanel.SetPositionX(px)
  757. t.resizerPanel.SetHeight(height)
  758. t.resizerPanel.SetVisible(true)
  759. t.SetTopChild(&t.resizerPanel)
  760. return
  761. }
  762. // Find click position
  763. var tce TableClickEvent
  764. tce.MouseEvent = *e
  765. t.findClick(&tce)
  766. // If row is clicked, selects it
  767. if tce.Row >= 0 && e.Button == window.MouseButtonLeft {
  768. t.rowCursor = tce.Row
  769. if t.selType == TableSelMultiRow && e.Mods == window.ModControl {
  770. t.toggleRowSel(t.rowCursor)
  771. }
  772. t.recalc()
  773. t.Dispatch(OnChange, nil)
  774. }
  775. // Creates and dispatch TableClickEvent for user's context menu
  776. t.Dispatch(OnTableClick, tce)
  777. case OnMouseUp:
  778. // If user was resizing a column, hides the resizer and
  779. // sets the new column width if possible
  780. if t.resizing {
  781. t.resizing = false
  782. t.resizerPanel.SetVisible(false)
  783. t.root.SetCursorNormal()
  784. // Calculates the new column width
  785. cx, _ := t.ContentCoords(e.Xpos, e.Ypos)
  786. c := t.header.cols[t.resizeCol]
  787. width := cx - c.xl
  788. t.setColWidth(c, width)
  789. }
  790. default:
  791. return
  792. }
  793. t.root.StopPropagation(StopAll)
  794. }
  795. // onKeyEvent receives subscribed key events for this table
  796. func (t *Table) onKey(evname string, ev interface{}) {
  797. kev := ev.(*window.KeyEvent)
  798. if kev.Keycode == window.KeyUp && kev.Mods == 0 {
  799. t.selPrev()
  800. } else if kev.Keycode == window.KeyDown && kev.Mods == 0 {
  801. t.selNext()
  802. } else if kev.Keycode == window.KeyPageUp && kev.Mods == 0 {
  803. t.prevPage()
  804. } else if kev.Keycode == window.KeyPageDown && kev.Mods == 0 {
  805. t.nextPage()
  806. } else if kev.Keycode == window.KeyPageUp && kev.Mods == window.ModControl {
  807. t.firstPage()
  808. } else if kev.Keycode == window.KeyPageDown && kev.Mods == window.ModControl {
  809. t.lastPage()
  810. } else if kev.Keycode == window.KeyEnter && kev.Mods == window.ModControl {
  811. if t.selType == TableSelMultiRow {
  812. t.toggleRowSel(t.rowCursor)
  813. }
  814. }
  815. }
  816. // onResize receives subscribed resize events for this table
  817. func (t *Table) onResize(evname string, ev interface{}) {
  818. t.recalc()
  819. t.recalcStatus()
  820. }
  821. // onScroll receives subscribed scroll events for this table
  822. func (t *Table) onScroll(evname string, ev interface{}) {
  823. sev := ev.(*window.ScrollEvent)
  824. if sev.Yoffset > 0 {
  825. t.scrollUp(1)
  826. } else if sev.Yoffset < 0 {
  827. t.scrollDown(1)
  828. }
  829. t.root.StopPropagation(Stop3D)
  830. }
  831. // onRicon receives subscribed events for column header right icon
  832. func (t *Table) onRicon(evname string, c *tableColHeader) {
  833. icon := tableSortedNoneIcon
  834. var asc bool
  835. if c.sorted == tableSortedNone || c.sorted == tableSortedDesc {
  836. c.sorted = tableSortedAsc
  837. icon = tableSortedAscIcon
  838. asc = false
  839. } else {
  840. c.sorted = tableSortedDesc
  841. icon = tableSortedDescIcon
  842. asc = true
  843. }
  844. var asString bool
  845. if c.sort == TableSortString {
  846. asString = true
  847. } else {
  848. asString = false
  849. }
  850. t.SortColumn(c.id, asString, asc)
  851. c.ricon.SetText(string(icon))
  852. }
  853. // findClick finds where in the table the specified mouse click event
  854. // occurred updating the specified TableClickEvent with the click coordinates.
  855. func (t *Table) findClick(ev *TableClickEvent) {
  856. x, y := t.ContentCoords(ev.Xpos, ev.Ypos)
  857. ev.X = x
  858. ev.Y = y
  859. ev.Row = -1
  860. // Find column id
  861. colx := float32(0)
  862. for ci := 0; ci < len(t.header.cols); ci++ {
  863. c := t.header.cols[ci]
  864. if !c.Visible() {
  865. continue
  866. }
  867. colx += t.header.cols[ci].Width()
  868. if x < colx {
  869. ev.Col = c.id
  870. ev.ColOrder = ci
  871. break
  872. }
  873. }
  874. // If column not found the user clicked at the right of rows
  875. if ev.Col == "" {
  876. return
  877. }
  878. // Checks if is in header
  879. if t.header.Visible() && y < t.header.Height() {
  880. ev.Header = true
  881. }
  882. // Find row clicked
  883. rowy := float32(0)
  884. if t.header.Visible() {
  885. rowy = t.header.Height()
  886. }
  887. theight := t.ContentHeight()
  888. for ri := t.firstRow; ri < len(t.rows); ri++ {
  889. trow := t.rows[ri]
  890. rowy += trow.height
  891. if rowy > theight {
  892. break
  893. }
  894. if y < rowy {
  895. ev.Row = ri
  896. break
  897. }
  898. }
  899. }
  900. // selNext selects the next row if possible
  901. func (t *Table) selNext() {
  902. // If selected row is last, nothing to do
  903. if t.rowCursor == len(t.rows)-1 {
  904. return
  905. }
  906. // If no selected row, selects first visible row
  907. if t.rowCursor < 0 {
  908. t.rowCursor = t.firstRow
  909. t.recalc()
  910. t.Dispatch(OnChange, nil)
  911. return
  912. }
  913. // Selects next row
  914. t.rowCursor++
  915. t.Dispatch(OnChange, nil)
  916. // Scroll down if necessary
  917. if t.rowCursor > t.lastRow {
  918. t.scrollDown(1)
  919. } else {
  920. t.recalc()
  921. }
  922. }
  923. // selPrev selects the previous row if possible
  924. func (t *Table) selPrev() {
  925. // If selected row is first, nothing to do
  926. sel := t.rowCursor
  927. if sel == 0 {
  928. return
  929. }
  930. // If no selected row, selects last visible row
  931. if sel < 0 {
  932. t.rowCursor = t.lastRow
  933. t.recalc()
  934. t.Dispatch(OnChange, nil)
  935. return
  936. }
  937. // Selects previous row and selects previous
  938. prev := sel - 1
  939. t.rowCursor = prev
  940. // Scroll up if necessary
  941. if prev < t.firstRow && t.firstRow > 0 {
  942. t.scrollUp(1)
  943. } else {
  944. t.recalc()
  945. }
  946. t.Dispatch(OnChange, nil)
  947. }
  948. // nextPage shows the next page of rows and selects its first row
  949. func (t *Table) nextPage() {
  950. if len(t.rows) == 0 {
  951. return
  952. }
  953. if t.lastRow == len(t.rows)-1 {
  954. t.rowCursor = t.lastRow
  955. t.recalc()
  956. t.Dispatch(OnChange, nil)
  957. return
  958. }
  959. plen := t.lastRow - t.firstRow
  960. if plen <= 0 {
  961. return
  962. }
  963. t.scrollDown(plen)
  964. }
  965. // prevPage shows the previous page of rows and selects its last row
  966. func (t *Table) prevPage() {
  967. if t.firstRow == 0 {
  968. t.rowCursor = 0
  969. t.recalc()
  970. t.Dispatch(OnChange, nil)
  971. return
  972. }
  973. plen := t.lastRow - t.firstRow
  974. if plen <= 0 {
  975. return
  976. }
  977. t.scrollUp(plen)
  978. }
  979. // firstPage shows the first page of rows and selects the first row
  980. func (t *Table) firstPage() {
  981. if len(t.rows) == 0 {
  982. return
  983. }
  984. t.firstRow = 0
  985. t.rowCursor = 0
  986. t.recalc()
  987. t.Dispatch(OnChange, nil)
  988. }
  989. // lastPage shows the last page of rows and selects the last row
  990. func (t *Table) lastPage() {
  991. if len(t.rows) == 0 {
  992. return
  993. }
  994. maxFirst := t.calcMaxFirst()
  995. t.firstRow = maxFirst
  996. t.rowCursor = len(t.rows) - 1
  997. t.recalc()
  998. t.Dispatch(OnChange, nil)
  999. }
  1000. // selectRow selects the specified row.
  1001. // Should be used only when multi row selection is enabled
  1002. func (t *Table) selectRow(ri int) {
  1003. trow := t.rows[ri]
  1004. trow.selected = true
  1005. t.Dispatch(OnChange, nil)
  1006. }
  1007. // toggleRowSel toogles the specified row selection state
  1008. // Should be used only when multi row selection is enabled
  1009. func (t *Table) toggleRowSel(ri int) {
  1010. trow := t.rows[ri]
  1011. trow.selected = !trow.selected
  1012. t.Dispatch(OnChange, nil)
  1013. }
  1014. // setColWidth sets the width of the specified column
  1015. func (t *Table) setColWidth(c *tableColHeader, width float32) {
  1016. // Sets the column width
  1017. if width < c.minWidth {
  1018. width = c.minWidth
  1019. }
  1020. if c.Width() == width {
  1021. return
  1022. }
  1023. dw := width - c.Width()
  1024. c.SetWidth(width)
  1025. // Find the column index and if any column has expand != 0
  1026. hasExpand := false
  1027. ci := -1
  1028. for i := 0; i < len(t.header.cols); i++ {
  1029. current := t.header.cols[i]
  1030. if current == c {
  1031. ci = i
  1032. }
  1033. if current.expand > 0 && current.Visible() {
  1034. hasExpand = true
  1035. }
  1036. }
  1037. if ci >= len(t.header.cols) {
  1038. panic("Internal: column not found")
  1039. }
  1040. // If no column is expandable, nothing more todo
  1041. if !hasExpand {
  1042. t.recalc()
  1043. return
  1044. }
  1045. // Calculates the width of the columns at the right
  1046. rwidth := float32(0)
  1047. for i := ci + 1; i < len(t.header.cols); i++ {
  1048. c := t.header.cols[i]
  1049. if !c.Visible() {
  1050. continue
  1051. }
  1052. rwidth += c.Width()
  1053. }
  1054. // Distributes the delta to the columns at the right
  1055. for i := ci + 1; i < len(t.header.cols); i++ {
  1056. c := t.header.cols[i]
  1057. if !c.Visible() {
  1058. continue
  1059. }
  1060. cdelta := -dw * (c.Width() / rwidth)
  1061. newWidth := c.Width() + cdelta
  1062. if newWidth < c.minWidth {
  1063. newWidth = c.minWidth
  1064. }
  1065. c.SetWidth(newWidth)
  1066. }
  1067. t.recalc()
  1068. }
  1069. // recalcHeader recalculates and sets the position and size of the header panels
  1070. func (t *Table) recalcHeader() {
  1071. // Calculates total width, height, expansion and available width space
  1072. hwidth := float32(0)
  1073. height := float32(0)
  1074. wspace := float32(0)
  1075. totalExpand := float32(0)
  1076. for ci := 0; ci < len(t.header.cols); ci++ {
  1077. // If column is invisible, ignore
  1078. c := t.header.cols[ci]
  1079. if !c.Visible() {
  1080. continue
  1081. }
  1082. if c.Height() > height {
  1083. height = c.Height()
  1084. }
  1085. if c.expand > 0 {
  1086. totalExpand += c.expand
  1087. }
  1088. hwidth += c.Width()
  1089. }
  1090. // Total table width
  1091. twidth := t.ContentWidth()
  1092. if t.vscroll != nil && t.vscroll.Visible() {
  1093. twidth -= t.vscroll.Width()
  1094. }
  1095. // Available space for columns: may be negative
  1096. wspace = twidth - hwidth
  1097. // If no expandable column, keeps the columns widths
  1098. if totalExpand == 0 {
  1099. } else if wspace >= 0 {
  1100. for ci := 0; ci < len(t.header.cols); ci++ {
  1101. // If column is invisible, ignore
  1102. c := t.header.cols[ci]
  1103. if !c.Visible() {
  1104. continue
  1105. }
  1106. // There is space available and if column is expandable,
  1107. // expands it proportionaly to the other expandable columns
  1108. factor := c.expand / totalExpand
  1109. w := factor * wspace
  1110. c.SetWidth(c.Width() + w)
  1111. }
  1112. } else {
  1113. acols := make([]*tableColHeader, 0)
  1114. awidth := float32(0)
  1115. widthAvail := twidth
  1116. // Sets the widths of the columns
  1117. for ci := 0; ci < len(t.header.cols); ci++ {
  1118. // If column is invisible, ignore
  1119. c := t.header.cols[ci]
  1120. if !c.Visible() {
  1121. continue
  1122. }
  1123. // The table was reduced so shrinks this column proportionally to its current width
  1124. factor := c.Width() / hwidth
  1125. newWidth := factor * twidth
  1126. if newWidth < c.minWidth {
  1127. newWidth = c.minWidth
  1128. c.SetWidth(newWidth)
  1129. widthAvail -= c.minWidth
  1130. } else {
  1131. acols = append(acols, c)
  1132. awidth += c.Width()
  1133. }
  1134. }
  1135. for ci := 0; ci < len(acols); ci++ {
  1136. c := acols[ci]
  1137. factor := c.Width() / awidth
  1138. newWidth := factor * widthAvail
  1139. c.SetWidth(newWidth)
  1140. }
  1141. }
  1142. // Sets the header panel and its internal panels positions
  1143. posx := float32(0)
  1144. for ci := 0; ci < len(t.header.cols); ci++ {
  1145. // If column is invisible, ignore
  1146. c := t.header.cols[ci]
  1147. if !c.Visible() {
  1148. continue
  1149. }
  1150. // Sets the right icon position inside the column header panel
  1151. if c.ricon != nil {
  1152. ix := c.ContentWidth() - c.ricon.Width()
  1153. if ix < 0 {
  1154. ix = 0
  1155. }
  1156. c.ricon.SetPosition(ix, 0)
  1157. }
  1158. // Sets the column header panel position
  1159. c.SetPosition(posx, 0)
  1160. c.SetVisible(true)
  1161. c.xl = posx
  1162. posx += c.Width()
  1163. c.xr = posx
  1164. }
  1165. // Last header
  1166. w := t.ContentWidth() - posx
  1167. if w > 0 {
  1168. t.header.lastPan.SetVisible(true)
  1169. t.header.lastPan.SetSize(w, height)
  1170. t.header.lastPan.SetPosition(posx, 0)
  1171. } else {
  1172. t.header.lastPan.SetVisible(false)
  1173. }
  1174. // Header container
  1175. t.header.SetWidth(t.ContentWidth())
  1176. t.header.SetContentHeight(height)
  1177. }
  1178. // recalcStatus recalculates and sets the position and size of the status panel and its label
  1179. func (t *Table) recalcStatus() {
  1180. if !t.statusPanel.Visible() {
  1181. return
  1182. }
  1183. t.statusPanel.SetContentHeight(t.statusLabel.Height())
  1184. py := t.ContentHeight() - t.statusPanel.Height()
  1185. t.statusPanel.SetPosition(0, py)
  1186. t.statusPanel.SetWidth(t.ContentWidth())
  1187. }
  1188. // recalc calculates the visibility, positions and sizes of all row cells.
  1189. // should be called in the following situations:
  1190. // - the table is resized
  1191. // - row is added, inserted or removed
  1192. // - column alignment and expansion changed
  1193. // - column visibility is changed
  1194. // - horizontal or vertical scroll position changed
  1195. func (t *Table) recalc() {
  1196. // Get available row height for rows
  1197. starty, theight := t.rowsHeight()
  1198. // Determines if it is necessary to show the scrollbar or not.
  1199. scroll := false
  1200. py := starty
  1201. for ri := 0; ri < len(t.rows); ri++ {
  1202. trow := t.rows[ri]
  1203. py += trow.height
  1204. if py > starty+theight {
  1205. scroll = true
  1206. break
  1207. }
  1208. }
  1209. t.setVScrollBar(scroll)
  1210. // Recalculates the header
  1211. t.recalcHeader()
  1212. // Sets the position and sizes of all cells of the visible rows
  1213. py = starty
  1214. for ri := 0; ri < len(t.rows); ri++ {
  1215. trow := t.rows[ri]
  1216. // If row is before first row or its y coordinate is greater the table height,
  1217. // sets it invisible
  1218. if ri < t.firstRow || py > starty+theight {
  1219. trow.SetVisible(false)
  1220. continue
  1221. }
  1222. t.recalcRow(ri)
  1223. // Set row y position and visible
  1224. trow.SetPosition(0, py)
  1225. trow.SetVisible(true)
  1226. t.updateRowStyle(ri)
  1227. // Set the last completely visible row index
  1228. if py+trow.Height() <= starty+theight {
  1229. t.lastRow = ri
  1230. }
  1231. //log.Error("ri:%v py:%v theight:%v", ri, py, theight)
  1232. py += trow.height
  1233. }
  1234. // Status panel must be on top of all the row panels
  1235. t.SetTopChild(&t.statusPanel)
  1236. }
  1237. // recalcRow recalculates the positions and sizes of all cells of the specified row
  1238. // Should be called when the row is created and column visibility or order is changed.
  1239. func (t *Table) recalcRow(ri int) {
  1240. trow := t.rows[ri]
  1241. // Calculates and sets row height
  1242. maxheight := float32(0)
  1243. for ci := 0; ci < len(t.header.cols); ci++ {
  1244. // If column is hidden, ignore
  1245. c := t.header.cols[ci]
  1246. if !c.Visible() {
  1247. continue
  1248. }
  1249. cell := trow.cells[c.order]
  1250. cellHeight := cell.MinHeight() + cell.label.Height()
  1251. if cellHeight > maxheight {
  1252. maxheight = cellHeight
  1253. }
  1254. }
  1255. trow.SetContentHeight(maxheight)
  1256. // Sets row cells sizes and positions and sets row width
  1257. px := float32(0)
  1258. for ci := 0; ci < len(t.header.cols); ci++ {
  1259. // If column is hidden, ignore
  1260. c := t.header.cols[ci]
  1261. cell := trow.cells[c.order]
  1262. if !c.Visible() {
  1263. cell.SetVisible(false)
  1264. continue
  1265. }
  1266. // Sets cell position and size
  1267. cell.SetPosition(px, 0)
  1268. cell.SetVisible(true)
  1269. cell.SetSize(c.Width(), trow.ContentHeight())
  1270. // Checks for format function
  1271. if c.formatFunc != nil {
  1272. text := c.formatFunc(TableCell{t, ri, c.id, cell.value})
  1273. cell.label.SetText(text)
  1274. }
  1275. // Sets the cell label alignment inside the cell
  1276. ccw := cell.ContentWidth()
  1277. lw := cell.label.Width()
  1278. space := ccw - lw
  1279. lx := float32(0)
  1280. switch c.align {
  1281. case AlignLeft:
  1282. case AlignRight:
  1283. if space > 0 {
  1284. lx = ccw - lw
  1285. }
  1286. case AlignCenter:
  1287. if space > 0 {
  1288. lx = space / 2
  1289. }
  1290. }
  1291. cell.label.SetPosition(lx, 0)
  1292. px += c.Width()
  1293. }
  1294. trow.SetContentWidth(px)
  1295. }
  1296. // rowsHeight returns the available start y coordinate and height in the table for rows,
  1297. // considering the visibility of the header and status panels.
  1298. func (t *Table) rowsHeight() (float32, float32) {
  1299. start := float32(0)
  1300. height := t.ContentHeight()
  1301. if t.header.Visible() {
  1302. height -= t.header.Height()
  1303. start += t.header.Height()
  1304. }
  1305. if t.statusPanel.Visible() {
  1306. height -= t.statusPanel.Height()
  1307. }
  1308. if height < 0 {
  1309. return 0, 0
  1310. }
  1311. return start, height
  1312. }
  1313. // setVScrollBar sets the visibility state of the vertical scrollbar
  1314. func (t *Table) setVScrollBar(state bool) {
  1315. // Visible
  1316. if state {
  1317. var scrollWidth float32 = 20
  1318. // Creates scroll bar if necessary
  1319. if t.vscroll == nil {
  1320. t.vscroll = NewVScrollBar(0, 0)
  1321. t.vscroll.SetBorders(0, 0, 0, 1)
  1322. t.vscroll.Subscribe(OnChange, t.onVScrollBar)
  1323. t.Panel.Add(t.vscroll)
  1324. }
  1325. // Sets the scroll bar size and positions
  1326. py, height := t.rowsHeight()
  1327. t.vscroll.SetSize(scrollWidth, height)
  1328. t.vscroll.SetPositionX(t.ContentWidth() - scrollWidth)
  1329. t.vscroll.SetPositionY(py)
  1330. t.vscroll.recalc()
  1331. t.vscroll.SetVisible(true)
  1332. if !t.scrollBarEvent {
  1333. maxFirst := t.calcMaxFirst()
  1334. t.vscroll.SetValue(float32(t.firstRow) / float32(maxFirst))
  1335. } else {
  1336. t.scrollBarEvent = false
  1337. }
  1338. // scroll bar must be on top of all table rows
  1339. t.SetTopChild(t.vscroll)
  1340. // Not visible
  1341. } else {
  1342. if t.vscroll != nil {
  1343. t.vscroll.SetVisible(false)
  1344. }
  1345. }
  1346. }
  1347. // onVScrollBar is called when a vertical scroll bar event is received
  1348. func (t *Table) onVScrollBar(evname string, ev interface{}) {
  1349. // Calculates the new first visible line
  1350. pos := t.vscroll.Value()
  1351. maxFirst := t.calcMaxFirst()
  1352. first := int(math.Floor((float64(maxFirst) * pos) + 0.5))
  1353. // Sets the new selected row
  1354. sel := t.rowCursor
  1355. selChange := false
  1356. if sel < first {
  1357. t.rowCursor = first
  1358. selChange = true
  1359. } else {
  1360. lines := first - t.firstRow
  1361. lastRow := t.lastRow + lines
  1362. if sel > lastRow {
  1363. t.rowCursor = lastRow
  1364. selChange = true
  1365. }
  1366. }
  1367. t.scrollBarEvent = true
  1368. t.firstRow = first
  1369. t.recalc()
  1370. if selChange {
  1371. t.Dispatch(OnChange, nil)
  1372. }
  1373. }
  1374. // calcMaxFirst calculates the maximum index of the first visible row
  1375. // such as the remaing rows fits completely inside the table
  1376. // It is used when scrolling the table vertically
  1377. func (t *Table) calcMaxFirst() int {
  1378. _, total := t.rowsHeight()
  1379. ri := len(t.rows) - 1
  1380. if ri < 0 {
  1381. return 0
  1382. }
  1383. height := float32(0)
  1384. for {
  1385. trow := t.rows[ri]
  1386. height += trow.height
  1387. if height > total {
  1388. break
  1389. }
  1390. ri--
  1391. if ri < 0 {
  1392. break
  1393. }
  1394. }
  1395. return ri + 1
  1396. }
  1397. // updateRowStyle applies the correct style for the specified row
  1398. func (t *Table) updateRowStyle(ri int) {
  1399. row := t.rows[ri]
  1400. var trs *TableRowStyle
  1401. if ri == t.rowCursor {
  1402. trs = t.styles.RowCursor
  1403. } else if row.selected {
  1404. trs = t.styles.RowSel
  1405. } else {
  1406. if ri%2 == 0 {
  1407. trs = t.styles.RowEven
  1408. } else {
  1409. trs = t.styles.RowOdd
  1410. }
  1411. }
  1412. t.applyRowStyle(row, trs)
  1413. }
  1414. // applyHeaderStyle applies style to the specified table header
  1415. // the last header panel does not the right border.
  1416. func (t *Table) applyHeaderStyle(h *Panel, last bool) {
  1417. s := t.styles.Header
  1418. borders := s.Border
  1419. if !last {
  1420. h.SetBordersFrom(&borders)
  1421. } else {
  1422. borders.Right = 0
  1423. h.SetBordersFrom(&borders)
  1424. }
  1425. h.SetBordersColor4(&s.BorderColor)
  1426. h.SetPaddingsFrom(&s.Paddings)
  1427. h.SetColor(&s.BgColor)
  1428. }
  1429. // applyRowStyle applies the specified style to all cells for the specified table row
  1430. func (t *Table) applyRowStyle(trow *tableRow, trs *TableRowStyle) {
  1431. for i := 0; i < len(trow.cells); i++ {
  1432. cell := trow.cells[i]
  1433. cell.SetBordersFrom(&trs.Border)
  1434. cell.SetBordersColor4(&trs.BorderColor)
  1435. cell.SetPaddingsFrom(&trs.Paddings)
  1436. cell.SetColor(&trs.BgColor)
  1437. }
  1438. }
  1439. // applyStatusStyle applies the status style
  1440. func (t *Table) applyStatusStyle() {
  1441. s := t.styles.Status
  1442. t.statusPanel.SetBordersFrom(&s.Border)
  1443. t.statusPanel.SetBordersColor4(&s.BorderColor)
  1444. t.statusPanel.SetPaddingsFrom(&s.Paddings)
  1445. t.statusPanel.SetColor(&s.BgColor)
  1446. }
  1447. // applyResizerStyle applies the status style
  1448. func (t *Table) applyResizerStyle() {
  1449. s := t.styles.Resizer
  1450. t.resizerPanel.SetBordersFrom(&s.Border)
  1451. t.resizerPanel.SetBordersColor4(&s.BorderColor)
  1452. t.resizerPanel.SetColor4(&s.BgColor)
  1453. }
  1454. // tableSortString is an internal type implementing the sort.Interface
  1455. // and is used to sort a table column interpreting its values as strings
  1456. type tableSortString struct {
  1457. rows []*tableRow
  1458. col int
  1459. asc bool
  1460. format string
  1461. }
  1462. func (ts tableSortString) Len() int { return len(ts.rows) }
  1463. func (ts tableSortString) Swap(i, j int) { ts.rows[i], ts.rows[j] = ts.rows[j], ts.rows[i] }
  1464. func (ts tableSortString) Less(i, j int) bool {
  1465. vi := ts.rows[i].cells[ts.col].value
  1466. vj := ts.rows[j].cells[ts.col].value
  1467. si := fmt.Sprintf(ts.format, vi)
  1468. sj := fmt.Sprintf(ts.format, vj)
  1469. if ts.asc {
  1470. return si < sj
  1471. } else {
  1472. return sj < si
  1473. }
  1474. }
  1475. // tableSortNumber is an internal type implementing the sort.Interface
  1476. // and is used to sort a table column interpreting its values as numbers
  1477. type tableSortNumber struct {
  1478. rows []*tableRow
  1479. col int
  1480. asc bool
  1481. }
  1482. func (ts tableSortNumber) Len() int { return len(ts.rows) }
  1483. func (ts tableSortNumber) Swap(i, j int) { ts.rows[i], ts.rows[j] = ts.rows[j], ts.rows[i] }
  1484. func (ts tableSortNumber) Less(i, j int) bool {
  1485. vi := ts.rows[i].cells[ts.col].value
  1486. vj := ts.rows[j].cells[ts.col].value
  1487. ni := cv2f64(vi)
  1488. nj := cv2f64(vj)
  1489. if ts.asc {
  1490. return ni < nj
  1491. } else {
  1492. return nj < ni
  1493. }
  1494. }
  1495. // Try to convert an interface value to a float64 number
  1496. func cv2f64(v interface{}) float64 {
  1497. if v == nil {
  1498. return 0
  1499. }
  1500. switch n := v.(type) {
  1501. case uint8:
  1502. return float64(n)
  1503. case uint16:
  1504. return float64(n)
  1505. case uint32:
  1506. return float64(n)
  1507. case uint64:
  1508. return float64(n)
  1509. case uint:
  1510. return float64(n)
  1511. case int8:
  1512. return float64(n)
  1513. case int16:
  1514. return float64(n)
  1515. case int32:
  1516. return float64(n)
  1517. case int64:
  1518. return float64(n)
  1519. case int:
  1520. return float64(n)
  1521. case string:
  1522. sv, err := strconv.ParseFloat(n, 64)
  1523. if err == nil {
  1524. return sv
  1525. }
  1526. return 0
  1527. default:
  1528. return 0
  1529. }
  1530. }