table.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  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. )
  46. //
  47. // Table implements a panel which can contains child panels
  48. // organized in rows and columns.
  49. // In this implementation the table data model is keep and
  50. // mantained by the table itself
  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 // Inital column width in pixels
  75. Hidden bool // Hidden flag
  76. Align Align // Cell content alignment: AlignLeft|AlignCenter|AlignRight
  77. Format string // Format string for formatting the columns' cells
  78. FormatFunc TableFormatFunc // Format function (overrides Format string)
  79. Expand int // Column width expansion factor (0 no expansion)
  80. Sort TableSortType // Column sort type
  81. Resize bool // Allow column to be resized by user
  82. }
  83. // TableCell describes a table cell.
  84. // It is used as a parameter for formatting function
  85. type TableCell struct {
  86. Tab *Table // Pointer to table
  87. Row int // Row index
  88. Col string // Column id
  89. Value interface{} // Cell value
  90. }
  91. // TableFormatFunc is the type for formatting functions
  92. type TableFormatFunc func(cell TableCell) string
  93. // TableHeaderStyle describes the style of the table header
  94. type TableHeaderStyle struct {
  95. Border BorderSizes
  96. Paddings BorderSizes
  97. BorderColor math32.Color4
  98. BgColor math32.Color
  99. FgColor math32.Color
  100. }
  101. // TableRowStyle describes the style of the table row
  102. type TableRowStyle struct {
  103. Border BorderSizes
  104. Paddings BorderSizes
  105. BorderColor math32.Color4
  106. BgColor math32.Color
  107. FgColor math32.Color
  108. }
  109. // TableRowStyles describes all styles for the table row
  110. type TableRowStyles struct {
  111. Normal TableRowStyle
  112. Selected TableRowStyle
  113. }
  114. // TableStatusStyle describes the style of the table status line panel
  115. type TableStatusStyle struct {
  116. Border BorderSizes
  117. Paddings BorderSizes
  118. BorderColor math32.Color4
  119. BgColor math32.Color
  120. FgColor math32.Color
  121. }
  122. // TableResizerStyle describes the style of the table resizer panel
  123. type TableResizerStyle struct {
  124. Width float32
  125. Border BorderSizes
  126. BorderColor math32.Color4
  127. BgColor math32.Color4
  128. }
  129. // TableStyles describes all styles of the table header and rows
  130. type TableStyles struct {
  131. Header *TableHeaderStyle
  132. RowEven *TableRowStyle
  133. RowOdd *TableRowStyle
  134. RowCursor *TableRowStyle
  135. RowSel *TableRowStyle
  136. Status *TableStatusStyle
  137. Resizer *TableResizerStyle
  138. }
  139. // TableClickEvent describes a mouse click event over a table
  140. // It contains the original mouse event plus additional information
  141. type TableClickEvent struct {
  142. window.MouseEvent // Embedded window mouse event
  143. X float32 // Table content area X coordinate
  144. Y float32 // Table content area Y coordinate
  145. Header bool // True if header was clicked
  146. Row int // Index of table row (may be -1)
  147. Col string // Id of table column (may be empty)
  148. ColOrder int // Current column exhibition order
  149. }
  150. // tableHeader is panel which contains the individual header panels for each column
  151. type tableHeader struct {
  152. Panel // embedded panel
  153. cmap map[string]*tableColHeader // maps column id with its panel/descriptor
  154. cols []*tableColHeader // array of individual column headers/descriptors
  155. }
  156. // tableColHeader is panel for a column header
  157. type tableColHeader struct {
  158. Panel // header panel
  159. label *Label // header label
  160. ricon *Label // header right icon (sort direction)
  161. id string // column id
  162. width float32 // initial column width
  163. format string // column format string
  164. formatFunc TableFormatFunc // column format function
  165. align Align // column alignment
  166. expand int // column expand factor
  167. sort TableSortType // column sort type
  168. resize bool // column can be resized by user
  169. order int // row columns order
  170. sorted int // current sorted status
  171. xl float32 // left border coordinate in pixels
  172. xr float32 // right border coordinate in pixels
  173. }
  174. // tableRow is panel which contains an entire table row of cells
  175. type tableRow struct {
  176. Panel // embedded panel
  177. selected bool // row selected flag
  178. cells []*tableCell // array of row cells
  179. }
  180. // tableCell is a panel which contains one cell (a label)
  181. type tableCell struct {
  182. Panel // embedded panel
  183. label Label // cell label
  184. value interface{} // cell current value
  185. }
  186. // NewTable creates and returns a pointer to a new Table with the
  187. // specified width, height and columns
  188. func NewTable(width, height float32, cols []TableColumn) (*Table, error) {
  189. t := new(Table)
  190. t.Panel.Initialize(width, height)
  191. t.styles = &StyleDefault.Table
  192. t.rowCursor = -1
  193. // Initialize table header
  194. t.header.Initialize(0, 0)
  195. t.header.cmap = make(map[string]*tableColHeader)
  196. t.header.cols = make([]*tableColHeader, 0)
  197. // Create column header panels
  198. for ci := 0; ci < len(cols); ci++ {
  199. cdesc := cols[ci]
  200. // Column id must not be empty
  201. if cdesc.Id == "" {
  202. return nil, fmt.Errorf("Column with empty id")
  203. }
  204. // Column id must be unique
  205. if t.header.cmap[cdesc.Id] != nil {
  206. return nil, fmt.Errorf("Column with duplicate id")
  207. }
  208. // Creates a column header
  209. c := new(tableColHeader)
  210. c.Initialize(0, 0)
  211. t.applyHeaderStyle(c)
  212. c.label = NewLabel(cdesc.Header)
  213. c.Add(c.label)
  214. c.id = cdesc.Id
  215. c.width = cdesc.Width
  216. c.align = cdesc.Align
  217. c.format = cdesc.Format
  218. c.formatFunc = cdesc.FormatFunc
  219. c.expand = cdesc.Expand
  220. c.sort = cdesc.Sort
  221. c.resize = cdesc.Resize
  222. // Adds optional sort icon
  223. if c.sort != TableSortNone {
  224. c.ricon = NewIconLabel(string(tableSortedNoneIcon))
  225. c.Add(c.ricon)
  226. c.ricon.Subscribe(OnMouseDown, func(evname string, ev interface{}) {
  227. t.onRicon(evname, c)
  228. })
  229. }
  230. // Sets default format and order
  231. if c.format == "" {
  232. c.format = "%v"
  233. }
  234. c.order = ci
  235. c.SetVisible(!cdesc.Hidden)
  236. t.header.cmap[c.id] = c
  237. // Sets column header width and height
  238. width := cdesc.Width
  239. if width < c.label.Width()+c.MinWidth() {
  240. width = c.label.Width() + c.MinWidth()
  241. }
  242. c.SetContentSize(width, c.label.Height())
  243. // Adds the column header to the header panel
  244. t.header.cols = append(t.header.cols, c)
  245. t.header.Panel.Add(c)
  246. }
  247. t.Panel.Add(&t.header)
  248. t.recalcHeader()
  249. // Creates resizer panel
  250. t.resizerPanel.Initialize(t.styles.Resizer.Width, 0)
  251. t.resizerPanel.SetVisible(false)
  252. t.applyResizerStyle()
  253. t.Panel.Add(&t.resizerPanel)
  254. // Creates status panel
  255. t.statusPanel.Initialize(0, 0)
  256. t.statusPanel.SetVisible(false)
  257. t.statusLabel = NewLabel("")
  258. t.applyStatusStyle()
  259. t.statusPanel.Add(t.statusLabel)
  260. t.Panel.Add(&t.statusPanel)
  261. t.recalcStatus()
  262. // Subscribe to events
  263. t.Panel.Subscribe(OnCursorEnter, t.onCursor)
  264. t.Panel.Subscribe(OnCursorLeave, t.onCursor)
  265. t.Panel.Subscribe(OnCursor, t.onCursorPos)
  266. t.Panel.Subscribe(OnScroll, t.onScroll)
  267. t.Panel.Subscribe(OnMouseUp, t.onMouse)
  268. t.Panel.Subscribe(OnMouseDown, t.onMouse)
  269. t.Panel.Subscribe(OnKeyDown, t.onKey)
  270. t.Panel.Subscribe(OnKeyRepeat, t.onKey)
  271. t.Panel.Subscribe(OnResize, t.onResize)
  272. return t, nil
  273. }
  274. // SetStyles set this table styles overriding the default
  275. func (t *Table) SetStyles(ts *TableStyles) {
  276. t.styles = ts
  277. t.recalc()
  278. }
  279. // SetSelectionType sets this table selection type
  280. // Possible values are: TableSelSingleRow|TableSelMultiRow
  281. func (t *Table) SetSelectionType(sel TableSelType) {
  282. t.selType = sel
  283. }
  284. // ShowHeader shows or hides the table header
  285. func (t *Table) ShowHeader(show bool) {
  286. if t.header.Visible() == show {
  287. return
  288. }
  289. t.header.SetVisible(show)
  290. t.recalc()
  291. }
  292. // ShowColumn sets the visibility of the column with the specified id
  293. // If the column id does not exit the function panics.
  294. func (t *Table) ShowColumn(col string, show bool) {
  295. c := t.header.cmap[col]
  296. if c == nil {
  297. panic("Invalid column id")
  298. }
  299. if c.Visible() == show {
  300. return
  301. }
  302. c.SetVisible(show)
  303. t.recalcHeader()
  304. // Recalculates all rows
  305. for ri := 0; ri < len(t.rows); ri++ {
  306. t.recalcRow(ri)
  307. }
  308. t.recalc()
  309. }
  310. // ShowAllColumns shows all the table columns
  311. func (t *Table) ShowAllColumns() {
  312. recalc := false
  313. for ci := 0; ci < len(t.header.cols); ci++ {
  314. c := t.header.cols[ci]
  315. if !c.Visible() {
  316. c.SetVisible(true)
  317. recalc = true
  318. }
  319. }
  320. if !recalc {
  321. return
  322. }
  323. t.recalcHeader()
  324. // Recalculates all rows
  325. for ri := 0; ri < len(t.rows); ri++ {
  326. t.recalcRow(ri)
  327. }
  328. t.recalc()
  329. }
  330. // RowCount returns the current number of rows in the table
  331. func (t *Table) RowCount() int {
  332. return len(t.rows)
  333. }
  334. // SetRows clears all current rows of the table and
  335. // sets new rows from the specifying parameter.
  336. // Each row is a map keyed by the colum id.
  337. // The map value currently can be a string or any number type
  338. // If a row column is not found it is ignored
  339. func (t *Table) SetRows(values []map[string]interface{}) {
  340. // Add missing rows
  341. if len(values) > len(t.rows) {
  342. count := len(values) - len(t.rows)
  343. for row := 0; row < count; row++ {
  344. t.insertRow(len(t.rows), nil)
  345. }
  346. // Remove remaining rows
  347. } else if len(values) < len(t.rows) {
  348. for row := len(values); row < len(t.rows); row++ {
  349. t.removeRow(row)
  350. }
  351. }
  352. // Set rows values
  353. for row := 0; row < len(values); row++ {
  354. t.SetRow(row, values[row])
  355. }
  356. t.firstRow = 0
  357. t.recalc()
  358. }
  359. // SetRow sets the value of all the cells of the specified row from
  360. // the specified map indexed by column id.
  361. func (t *Table) SetRow(row int, values map[string]interface{}) {
  362. if row < 0 || row >= len(t.rows) {
  363. panic("Invalid row index")
  364. }
  365. for ci := 0; ci < len(t.header.cols); ci++ {
  366. c := t.header.cols[ci]
  367. cv, ok := values[c.id]
  368. if !ok {
  369. continue
  370. }
  371. t.SetCell(row, c.id, cv)
  372. }
  373. t.recalcRow(row)
  374. }
  375. // SetCell sets the value of the cell specified by its row and column id
  376. func (t *Table) SetCell(row int, colid string, value interface{}) {
  377. if row < 0 || row >= len(t.rows) {
  378. panic("Invalid row index")
  379. }
  380. c := t.header.cmap[colid]
  381. if c == nil {
  382. return
  383. }
  384. cell := t.rows[row].cells[c.order]
  385. cell.label.SetText(fmt.Sprintf(c.format, value))
  386. cell.value = value
  387. }
  388. // SetColFormat sets the formatting string (Printf) for the specified column
  389. // Update must be called to update the table.
  390. func (t *Table) SetColFormat(id, format string) error {
  391. c := t.header.cmap[id]
  392. if c == nil {
  393. return fmt.Errorf("No column with id:%s", id)
  394. }
  395. c.format = format
  396. return nil
  397. }
  398. // SetColOrder sets the exhibition order of the specified column.
  399. // The previous column which has the specified order will have
  400. // the original column order.
  401. func (t *Table) SetColOrder(colid string, order int) {
  402. // Checks column id
  403. c := t.header.cmap[colid]
  404. if c == nil {
  405. panic(fmt.Sprintf("No column with id:%s", colid))
  406. }
  407. // Checks exhibition order
  408. if order < 0 || order > len(t.header.cols) {
  409. panic("Invalid column id")
  410. }
  411. // Find the exhibition order for the specified column
  412. for ci := 0; ci < len(t.header.cols); ci++ {
  413. if t.header.cols[ci] == c {
  414. // If the order of the specified column is the same, nothing to do
  415. if ci == order {
  416. return
  417. }
  418. // Swap column orders
  419. prev := t.header.cols[order]
  420. t.header.cols[order] = c
  421. t.header.cols[ci] = prev
  422. break
  423. }
  424. }
  425. // Recalculates the header and all rows
  426. t.recalcHeader()
  427. for ri := 0; ri < len(t.rows); ri++ {
  428. t.recalcRow(ri)
  429. }
  430. t.recalc()
  431. }
  432. // EnableColResize enable or disables if the specified column can be resized by the
  433. // user using the mouse.
  434. func (t *Table) EnableColResize(colid string, enable bool) {
  435. // Checks column id
  436. c := t.header.cmap[colid]
  437. if c == nil {
  438. panic(fmt.Sprintf("No column with id:%s", colid))
  439. }
  440. c.resize = enable
  441. }
  442. // SetColWidth sets the specified column width and may
  443. // change the widths of the columns to the right
  444. func (t *Table) SetColWidth(colid string, width float32) {
  445. // Checks column id
  446. c := t.header.cmap[colid]
  447. if c == nil {
  448. panic(fmt.Sprintf("No column with id:%s", colid))
  449. }
  450. // Checks width minimum and maximuns
  451. if width < tableColMinWidth {
  452. width = tableColMinWidth
  453. }
  454. if width > t.ContentHeight() {
  455. width = t.ContentHeight()
  456. }
  457. c.SetWidth(width)
  458. // Recalculates the header and all rows
  459. t.recalcHeader()
  460. for ri := 0; ri < len(t.rows); ri++ {
  461. t.recalcRow(ri)
  462. }
  463. t.recalc()
  464. }
  465. // AddRow adds a new row at the end of the table with the specified values
  466. func (t *Table) AddRow(values map[string]interface{}) {
  467. t.InsertRow(len(t.rows), values)
  468. }
  469. // InsertRow inserts the specified values in a new row at the specified index
  470. func (t *Table) InsertRow(row int, values map[string]interface{}) {
  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("Invalid row index")
  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("Invalid first row index")
  536. }
  537. if li < 0 {
  538. li = len(t.rows) - 1
  539. } else if li < 0 || li >= len(t.rows) {
  540. panic("Invalid last row index")
  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("Invalid row index")
  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("Invalid column id")
  575. }
  576. if ri < 0 || ri >= len(t.rows) {
  577. panic("Invalid row index")
  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("Invalid column id")
  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. // insertRow is the internal version of InsertRow which does not call recalc()
  603. func (t *Table) insertRow(row int, values map[string]interface{}) {
  604. // Checks row index
  605. if row < 0 || row > len(t.rows) {
  606. panic("Invalid row index")
  607. }
  608. // Creates tableRow panel
  609. trow := new(tableRow)
  610. trow.Initialize(0, 0)
  611. trow.cells = make([]*tableCell, 0)
  612. for ci := 0; ci < len(t.header.cols); ci++ {
  613. // Creates tableRow cell panel
  614. cell := new(tableCell)
  615. cell.Initialize(0, 0)
  616. cell.label.initialize("", StyleDefault.Font)
  617. cell.Add(&cell.label)
  618. trow.cells = append(trow.cells, cell)
  619. trow.Panel.Add(cell)
  620. }
  621. t.Panel.Add(trow)
  622. // Inserts tableRow in the table rows at the specified index
  623. t.rows = append(t.rows, nil)
  624. copy(t.rows[row+1:], t.rows[row:])
  625. t.rows[row] = trow
  626. t.updateRowStyle(row)
  627. // Sets the new row values from the specified map
  628. if values != nil {
  629. t.SetRow(row, values)
  630. }
  631. t.recalcRow(row)
  632. }
  633. // ScrollDown scrolls the table the specified number of rows down if possible
  634. func (t *Table) scrollDown(n int) {
  635. // Calculates number of rows to scroll down
  636. maxFirst := t.calcMaxFirst()
  637. maxScroll := maxFirst - t.firstRow
  638. if maxScroll <= 0 {
  639. return
  640. }
  641. if n > maxScroll {
  642. n = maxScroll
  643. }
  644. t.firstRow += n
  645. if t.rowCursor < t.firstRow {
  646. t.rowCursor = t.firstRow
  647. t.Dispatch(OnChange, nil)
  648. }
  649. t.recalc()
  650. return
  651. }
  652. // ScrollUp scrolls the table the specified number of rows up if possible
  653. func (t *Table) scrollUp(n int) {
  654. // Calculates number of rows to scroll up
  655. if t.firstRow == 0 {
  656. return
  657. }
  658. if n > t.firstRow {
  659. n = t.firstRow
  660. }
  661. t.firstRow -= n
  662. lastRow := t.lastRow - n
  663. if t.rowCursor > lastRow {
  664. t.rowCursor = lastRow
  665. t.Dispatch(OnChange, nil)
  666. }
  667. t.recalc()
  668. }
  669. // removeRow removes from the table the row specified its index
  670. func (t *Table) removeRow(row int) {
  671. // Get row to be removed
  672. trow := t.rows[row]
  673. // Remove row from table
  674. copy(t.rows[row:], t.rows[row+1:])
  675. t.rows[len(t.rows)-1] = nil
  676. t.rows = t.rows[:len(t.rows)-1]
  677. trow.DisposeChildren(true)
  678. trow.Dispose()
  679. // Adjusts table first visible row if necessary
  680. //if t.firstRow == row {
  681. // t.firstRow--
  682. // if t.firstRow < 0 {
  683. // t.firstRow = 0
  684. // }
  685. //}
  686. }
  687. // onCursor process subscribed cursor events
  688. func (t *Table) onCursor(evname string, ev interface{}) {
  689. switch evname {
  690. case OnCursorEnter:
  691. t.root.SetScrollFocus(t)
  692. case OnCursorLeave:
  693. t.root.SetScrollFocus(nil)
  694. }
  695. t.root.StopPropagation(Stop3D)
  696. }
  697. // onCursorPos process subscribed cursor position events
  698. func (t *Table) onCursorPos(evname string, ev interface{}) {
  699. // Convert mouse window coordinates to table content coordinates
  700. kev := ev.(*window.CursorEvent)
  701. cx, _ := t.ContentCoords(kev.Xpos, kev.Ypos)
  702. // If user is dragging the resizer, updates its position
  703. if t.resizing {
  704. t.resizerPanel.SetPosition(cx, 0)
  705. return
  706. }
  707. // Checks if the mouse cursor is near the border of a resizable column
  708. found := false
  709. for ci := 0; ci < len(t.header.cols); ci++ {
  710. c := t.header.cols[ci]
  711. dx := math32.Abs(cx - c.xr)
  712. if dx < tableResizerPix {
  713. if c.resize {
  714. found = true
  715. t.resizeCol = ci
  716. t.resizerX = c.xr
  717. t.root.SetCursorHResize()
  718. }
  719. break
  720. }
  721. }
  722. // If column not found but previously was near a resizable column,
  723. // resets the the window cursor.
  724. if !found && t.resizeCol >= 0 {
  725. t.root.SetCursorNormal()
  726. t.resizeCol = -1
  727. }
  728. t.root.StopPropagation(Stop3D)
  729. }
  730. // onMouseEvent process subscribed mouse events
  731. func (t *Table) onMouse(evname string, ev interface{}) {
  732. e := ev.(*window.MouseEvent)
  733. t.root.SetKeyFocus(t)
  734. switch evname {
  735. case OnMouseDown:
  736. // If over a resizable column border, shows the resizer panel
  737. if t.resizeCol >= 0 && e.Button == window.MouseButtonLeft {
  738. t.resizing = true
  739. height := t.ContentHeight()
  740. if t.statusPanel.Visible() {
  741. height -= t.statusPanel.Height()
  742. }
  743. px := t.resizerX - t.resizerPanel.Width()/2
  744. t.resizerPanel.SetPositionX(px)
  745. t.resizerPanel.SetHeight(height)
  746. t.resizerPanel.SetVisible(true)
  747. t.SetTopChild(&t.resizerPanel)
  748. return
  749. }
  750. // Find click position
  751. var tce TableClickEvent
  752. tce.MouseEvent = *e
  753. t.findClick(&tce)
  754. // If row is clicked, selects it
  755. if tce.Row >= 0 && e.Button == window.MouseButtonLeft {
  756. t.rowCursor = tce.Row
  757. if t.selType == TableSelMultiRow && e.Mods == window.ModControl {
  758. t.toggleRowSel(t.rowCursor)
  759. }
  760. t.recalc()
  761. t.Dispatch(OnChange, nil)
  762. }
  763. // Creates and dispatch TableClickEvent for user's context menu
  764. t.Dispatch(OnTableClick, tce)
  765. case OnMouseUp:
  766. // If user was resizing a column, hides the resizer and
  767. // sets the new column width if possible
  768. if t.resizing {
  769. t.resizing = false
  770. t.resizerPanel.SetVisible(false)
  771. t.root.SetCursorNormal()
  772. // Calculates the new column width
  773. cx, _ := t.ContentCoords(e.Xpos, e.Ypos)
  774. c := t.header.cols[t.resizeCol]
  775. width := cx - c.xl
  776. t.SetColWidth(c.id, width)
  777. }
  778. default:
  779. return
  780. }
  781. t.root.StopPropagation(StopAll)
  782. }
  783. // onKeyEvent receives subscribed key events for this table
  784. func (t *Table) onKey(evname string, ev interface{}) {
  785. kev := ev.(*window.KeyEvent)
  786. if kev.Keycode == window.KeyUp && kev.Mods == 0 {
  787. t.selPrev()
  788. } else if kev.Keycode == window.KeyDown && kev.Mods == 0 {
  789. t.selNext()
  790. } else if kev.Keycode == window.KeyPageUp && kev.Mods == 0 {
  791. t.prevPage()
  792. } else if kev.Keycode == window.KeyPageDown && kev.Mods == 0 {
  793. t.nextPage()
  794. } else if kev.Keycode == window.KeyPageUp && kev.Mods == window.ModControl {
  795. t.firstPage()
  796. } else if kev.Keycode == window.KeyPageDown && kev.Mods == window.ModControl {
  797. t.lastPage()
  798. } else if kev.Keycode == window.KeyEnter && kev.Mods == window.ModControl {
  799. if t.selType == TableSelMultiRow {
  800. t.toggleRowSel(t.rowCursor)
  801. }
  802. }
  803. }
  804. // onResize receives subscribed resize events for this table
  805. func (t *Table) onResize(evname string, ev interface{}) {
  806. t.recalc()
  807. t.recalcStatus()
  808. }
  809. // onScroll receives subscribed scroll events for this table
  810. func (t *Table) onScroll(evname string, ev interface{}) {
  811. sev := ev.(*window.ScrollEvent)
  812. if sev.Yoffset > 0 {
  813. t.scrollUp(1)
  814. } else if sev.Yoffset < 0 {
  815. t.scrollDown(1)
  816. }
  817. t.root.StopPropagation(Stop3D)
  818. }
  819. // onRicon receives subscribed events for column header right icon
  820. func (t *Table) onRicon(evname string, c *tableColHeader) {
  821. icon := tableSortedNoneIcon
  822. var asc bool
  823. if c.sorted == tableSortedNone || c.sorted == tableSortedDesc {
  824. c.sorted = tableSortedAsc
  825. icon = tableSortedAscIcon
  826. asc = false
  827. } else {
  828. c.sorted = tableSortedDesc
  829. icon = tableSortedDescIcon
  830. asc = true
  831. }
  832. var asString bool
  833. if c.sort == TableSortString {
  834. asString = true
  835. } else {
  836. asString = false
  837. }
  838. t.SortColumn(c.id, asString, asc)
  839. c.ricon.SetText(string(icon))
  840. }
  841. // findClick finds where in the table the specified mouse click event
  842. // occurred updating the specified TableClickEvent with the click coordinates.
  843. func (t *Table) findClick(ev *TableClickEvent) {
  844. x, y := t.ContentCoords(ev.Xpos, ev.Ypos)
  845. ev.X = x
  846. ev.Y = y
  847. ev.Row = -1
  848. // Find column id
  849. colx := float32(0)
  850. for ci := 0; ci < len(t.header.cols); ci++ {
  851. c := t.header.cols[ci]
  852. if !c.Visible() {
  853. continue
  854. }
  855. colx += t.header.cols[ci].Width()
  856. if x < colx {
  857. ev.Col = c.id
  858. ev.ColOrder = ci
  859. break
  860. }
  861. }
  862. // If column not found the user clicked at the right of rows
  863. if ev.Col == "" {
  864. return
  865. }
  866. // Checks if is in header
  867. if t.header.Visible() && y < t.header.Height() {
  868. ev.Header = true
  869. }
  870. // Find row clicked
  871. rowy := float32(0)
  872. if t.header.Visible() {
  873. rowy = t.header.Height()
  874. }
  875. theight := t.ContentHeight()
  876. for ri := t.firstRow; ri < len(t.rows); ri++ {
  877. trow := t.rows[ri]
  878. rowy += trow.height
  879. if rowy > theight {
  880. break
  881. }
  882. if y < rowy {
  883. ev.Row = ri
  884. break
  885. }
  886. }
  887. }
  888. // selNext selects the next row if possible
  889. func (t *Table) selNext() {
  890. // If selected row is last, nothing to do
  891. if t.rowCursor == len(t.rows)-1 {
  892. return
  893. }
  894. // If no selected row, selects first visible row
  895. if t.rowCursor < 0 {
  896. t.rowCursor = t.firstRow
  897. t.recalc()
  898. t.Dispatch(OnChange, nil)
  899. return
  900. }
  901. // Selects next row
  902. t.rowCursor++
  903. t.Dispatch(OnChange, nil)
  904. // Scroll down if necessary
  905. if t.rowCursor > t.lastRow {
  906. t.scrollDown(1)
  907. } else {
  908. t.recalc()
  909. }
  910. }
  911. // selPrev selects the previous row if possible
  912. func (t *Table) selPrev() {
  913. // If selected row is first, nothing to do
  914. sel := t.rowCursor
  915. if sel == 0 {
  916. return
  917. }
  918. // If no selected row, selects last visible row
  919. if sel < 0 {
  920. t.rowCursor = t.lastRow
  921. t.recalc()
  922. t.Dispatch(OnChange, nil)
  923. return
  924. }
  925. // Selects previous row and selects previous
  926. prev := sel - 1
  927. t.rowCursor = prev
  928. // Scroll up if necessary
  929. if prev < t.firstRow && t.firstRow > 0 {
  930. t.scrollUp(1)
  931. } else {
  932. t.recalc()
  933. }
  934. t.Dispatch(OnChange, nil)
  935. }
  936. // nextPage shows the next page of rows and selects its first row
  937. func (t *Table) nextPage() {
  938. if len(t.rows) == 0 {
  939. return
  940. }
  941. if t.lastRow == len(t.rows)-1 {
  942. t.rowCursor = t.lastRow
  943. t.recalc()
  944. t.Dispatch(OnChange, nil)
  945. return
  946. }
  947. plen := t.lastRow - t.firstRow
  948. if plen <= 0 {
  949. return
  950. }
  951. t.scrollDown(plen)
  952. }
  953. // prevPage shows the previous page of rows and selects its last row
  954. func (t *Table) prevPage() {
  955. if t.firstRow == 0 {
  956. t.rowCursor = 0
  957. t.recalc()
  958. t.Dispatch(OnChange, nil)
  959. return
  960. }
  961. plen := t.lastRow - t.firstRow
  962. if plen <= 0 {
  963. return
  964. }
  965. t.scrollUp(plen)
  966. }
  967. // firstPage shows the first page of rows and selects the first row
  968. func (t *Table) firstPage() {
  969. if len(t.rows) == 0 {
  970. return
  971. }
  972. t.firstRow = 0
  973. t.rowCursor = 0
  974. t.recalc()
  975. t.Dispatch(OnChange, nil)
  976. }
  977. // lastPage shows the last page of rows and selects the last row
  978. func (t *Table) lastPage() {
  979. if len(t.rows) == 0 {
  980. return
  981. }
  982. maxFirst := t.calcMaxFirst()
  983. t.firstRow = maxFirst
  984. t.rowCursor = len(t.rows) - 1
  985. t.recalc()
  986. t.Dispatch(OnChange, nil)
  987. }
  988. // selectRow selects the specified row.
  989. // Should be used only when multi row selection is enabled
  990. func (t *Table) selectRow(ri int) {
  991. trow := t.rows[ri]
  992. trow.selected = true
  993. t.Dispatch(OnChange, nil)
  994. }
  995. // toggleRowSel toogles the specified row selection state
  996. // Should be used only when multi row selection is enabled
  997. func (t *Table) toggleRowSel(ri int) {
  998. trow := t.rows[ri]
  999. trow.selected = !trow.selected
  1000. t.Dispatch(OnChange, nil)
  1001. }
  1002. // recalcHeader recalculates and sets the position and size of the header panels
  1003. func (t *Table) recalcHeader() {
  1004. posx := float32(0)
  1005. height := float32(0)
  1006. for ci := 0; ci < len(t.header.cols); ci++ {
  1007. c := t.header.cols[ci]
  1008. if !c.Visible() {
  1009. continue
  1010. }
  1011. if c.Height() > height {
  1012. height = c.Height()
  1013. }
  1014. // Sets right icon position
  1015. if c.ricon != nil {
  1016. ix := c.ContentWidth() - c.ricon.Width()
  1017. if ix < 0 {
  1018. ix = 0
  1019. }
  1020. c.ricon.SetPosition(ix, 0)
  1021. }
  1022. c.SetPosition(posx, 0)
  1023. c.SetVisible(true)
  1024. c.xl = posx
  1025. posx += c.Width()
  1026. c.xr = posx
  1027. }
  1028. t.header.SetContentSize(posx, height)
  1029. }
  1030. // recalcStatus recalculates and sets the position and size of the status panel and its label
  1031. func (t *Table) recalcStatus() {
  1032. if !t.statusPanel.Visible() {
  1033. return
  1034. }
  1035. t.statusPanel.SetContentHeight(t.statusLabel.Height())
  1036. py := t.ContentHeight() - t.statusPanel.Height()
  1037. t.statusPanel.SetPosition(0, py)
  1038. t.statusPanel.SetWidth(t.ContentWidth())
  1039. }
  1040. // recalc calculates the visibility, positions and sizes of all row cells.
  1041. // should be called in the following situations:
  1042. // - the table is resized
  1043. // - row is added, inserted or removed
  1044. // - column alignment and expansion changed
  1045. // - column visibility is changed
  1046. // - horizontal or vertical scroll position changed
  1047. func (t *Table) recalc() {
  1048. // Get available row height for rows
  1049. starty, theight := t.rowsHeight()
  1050. // Determines if it is necessary to show the scrollbar or not.
  1051. scroll := false
  1052. py := starty
  1053. for ri := 0; ri < len(t.rows); ri++ {
  1054. trow := t.rows[ri]
  1055. py += trow.height
  1056. if py > starty+theight {
  1057. scroll = true
  1058. break
  1059. }
  1060. }
  1061. t.setVScrollBar(scroll)
  1062. // Sets the position and sizes of all cells of the visible rows
  1063. py = starty
  1064. for ri := 0; ri < len(t.rows); ri++ {
  1065. trow := t.rows[ri]
  1066. // If row is before first row or its y coordinate is greater the table height,
  1067. // sets it invisible
  1068. if ri < t.firstRow || py > starty+theight {
  1069. trow.SetVisible(false)
  1070. continue
  1071. }
  1072. // Set row y position and visible
  1073. trow.SetPosition(0, py)
  1074. trow.SetVisible(true)
  1075. t.updateRowStyle(ri)
  1076. // Set the last completely visible row index
  1077. if py+trow.Height() <= starty+theight {
  1078. t.lastRow = ri
  1079. }
  1080. //log.Error("ri:%v py:%v theight:%v", ri, py, theight)
  1081. py += trow.height
  1082. }
  1083. // Status panel must be on top of all the row panels
  1084. t.SetTopChild(&t.statusPanel)
  1085. }
  1086. // recalcRow recalculates the positions and sizes of all cells of the specified row
  1087. // Should be called when the row is created and column visibility or order is changed.
  1088. func (t *Table) recalcRow(ri int) {
  1089. trow := t.rows[ri]
  1090. // Calculates and sets row height
  1091. maxheight := float32(0)
  1092. for ci := 0; ci < len(t.header.cols); ci++ {
  1093. // If column is hidden, ignore
  1094. c := t.header.cols[ci]
  1095. if !c.Visible() {
  1096. continue
  1097. }
  1098. cell := trow.cells[c.order]
  1099. cellHeight := cell.MinHeight() + cell.label.Height()
  1100. if cellHeight > maxheight {
  1101. maxheight = cellHeight
  1102. }
  1103. }
  1104. trow.SetContentHeight(maxheight)
  1105. // Sets row cells sizes and positions and sets row width
  1106. px := float32(0)
  1107. for ci := 0; ci < len(t.header.cols); ci++ {
  1108. // If column is hidden, ignore
  1109. c := t.header.cols[ci]
  1110. cell := trow.cells[c.order]
  1111. if !c.Visible() {
  1112. cell.SetVisible(false)
  1113. continue
  1114. }
  1115. // Sets cell position and size
  1116. cell.SetPosition(px, 0)
  1117. cell.SetVisible(true)
  1118. cell.SetSize(c.Width(), trow.ContentHeight())
  1119. // Checks for format function
  1120. if c.formatFunc != nil {
  1121. text := c.formatFunc(TableCell{t, ri, c.id, cell.value})
  1122. cell.label.SetText(text)
  1123. }
  1124. // Sets the cell label alignment inside the cell
  1125. ccw := cell.ContentWidth()
  1126. lw := cell.label.Width()
  1127. space := ccw - lw
  1128. lx := float32(0)
  1129. switch c.align {
  1130. case AlignLeft:
  1131. case AlignRight:
  1132. if space > 0 {
  1133. lx = ccw - lw
  1134. }
  1135. case AlignCenter:
  1136. if space > 0 {
  1137. lx = space / 2
  1138. }
  1139. }
  1140. cell.label.SetPosition(lx, 0)
  1141. px += c.Width()
  1142. }
  1143. trow.SetContentWidth(px)
  1144. }
  1145. // rowsHeight returns the available start y coordinate and height in the table for rows,
  1146. // considering the visibility of the header and status panels.
  1147. func (t *Table) rowsHeight() (float32, float32) {
  1148. start := float32(0)
  1149. height := t.ContentHeight()
  1150. if t.header.Visible() {
  1151. height -= t.header.Height()
  1152. start += t.header.Height()
  1153. }
  1154. if t.statusPanel.Visible() {
  1155. height -= t.statusPanel.Height()
  1156. }
  1157. if height < 0 {
  1158. return 0, 0
  1159. }
  1160. return start, height
  1161. }
  1162. // setVScrollBar sets the visibility state of the vertical scrollbar
  1163. func (t *Table) setVScrollBar(state bool) {
  1164. // Visible
  1165. if state {
  1166. var scrollWidth float32 = 20
  1167. // Creates scroll bar if necessary
  1168. if t.vscroll == nil {
  1169. t.vscroll = NewVScrollBar(0, 0)
  1170. t.vscroll.SetBorders(0, 0, 0, 1)
  1171. t.vscroll.Subscribe(OnChange, t.onVScrollBar)
  1172. t.Panel.Add(t.vscroll)
  1173. }
  1174. // Sets the scroll bar size and positions
  1175. py, height := t.rowsHeight()
  1176. t.vscroll.SetSize(scrollWidth, height)
  1177. t.vscroll.SetPositionX(t.ContentWidth() - scrollWidth)
  1178. t.vscroll.SetPositionY(py)
  1179. t.vscroll.recalc()
  1180. t.vscroll.SetVisible(true)
  1181. if !t.scrollBarEvent {
  1182. maxFirst := t.calcMaxFirst()
  1183. t.vscroll.SetValue(float32(t.firstRow) / float32(maxFirst))
  1184. } else {
  1185. t.scrollBarEvent = false
  1186. }
  1187. // Not visible
  1188. } else {
  1189. if t.vscroll != nil {
  1190. t.vscroll.SetVisible(false)
  1191. }
  1192. }
  1193. }
  1194. // onVScrollBar is called when a vertical scroll bar event is received
  1195. func (t *Table) onVScrollBar(evname string, ev interface{}) {
  1196. // Calculates the new first visible line
  1197. pos := t.vscroll.Value()
  1198. maxFirst := t.calcMaxFirst()
  1199. first := int(math.Floor((float64(maxFirst) * pos) + 0.5))
  1200. // Sets the new selected row
  1201. sel := t.rowCursor
  1202. selChange := false
  1203. if sel < first {
  1204. t.rowCursor = first
  1205. selChange = true
  1206. } else {
  1207. lines := first - t.firstRow
  1208. lastRow := t.lastRow + lines
  1209. if sel > lastRow {
  1210. t.rowCursor = lastRow
  1211. selChange = true
  1212. }
  1213. }
  1214. t.scrollBarEvent = true
  1215. t.firstRow = first
  1216. t.recalc()
  1217. if selChange {
  1218. t.Dispatch(OnChange, nil)
  1219. }
  1220. }
  1221. // calcMaxFirst calculates the maximum index of the first visible row
  1222. // such as the remaing rows fits completely inside the table
  1223. // It is used when scrolling the table vertically
  1224. func (t *Table) calcMaxFirst() int {
  1225. _, total := t.rowsHeight()
  1226. ri := len(t.rows) - 1
  1227. if ri < 0 {
  1228. return 0
  1229. }
  1230. height := float32(0)
  1231. for {
  1232. trow := t.rows[ri]
  1233. height += trow.height
  1234. if height > total {
  1235. break
  1236. }
  1237. ri--
  1238. if ri < 0 {
  1239. break
  1240. }
  1241. }
  1242. return ri + 1
  1243. }
  1244. // updateRowStyle applies the correct style for the specified row
  1245. func (t *Table) updateRowStyle(ri int) {
  1246. row := t.rows[ri]
  1247. var trs *TableRowStyle
  1248. if ri == t.rowCursor {
  1249. trs = t.styles.RowCursor
  1250. } else if row.selected {
  1251. trs = t.styles.RowSel
  1252. } else {
  1253. if ri%2 == 0 {
  1254. trs = t.styles.RowEven
  1255. } else {
  1256. trs = t.styles.RowOdd
  1257. }
  1258. }
  1259. t.applyRowStyle(row, trs)
  1260. }
  1261. // applyHeaderStyle applies style to the specified table header
  1262. func (t *Table) applyHeaderStyle(h *tableColHeader) {
  1263. s := t.styles.Header
  1264. h.SetBordersFrom(&s.Border)
  1265. h.SetBordersColor4(&s.BorderColor)
  1266. h.SetPaddingsFrom(&s.Paddings)
  1267. h.SetColor(&s.BgColor)
  1268. }
  1269. // applyRowStyle applies the specified style to all cells for the specified table row
  1270. func (t *Table) applyRowStyle(trow *tableRow, trs *TableRowStyle) {
  1271. for i := 0; i < len(trow.cells); i++ {
  1272. cell := trow.cells[i]
  1273. cell.SetBordersFrom(&trs.Border)
  1274. cell.SetBordersColor4(&trs.BorderColor)
  1275. cell.SetPaddingsFrom(&trs.Paddings)
  1276. cell.SetColor(&trs.BgColor)
  1277. }
  1278. }
  1279. // applyStatusStyle applies the status style
  1280. func (t *Table) applyStatusStyle() {
  1281. s := t.styles.Status
  1282. t.statusPanel.SetBordersFrom(&s.Border)
  1283. t.statusPanel.SetBordersColor4(&s.BorderColor)
  1284. t.statusPanel.SetPaddingsFrom(&s.Paddings)
  1285. t.statusPanel.SetColor(&s.BgColor)
  1286. }
  1287. // applyResizerStyle applies the status style
  1288. func (t *Table) applyResizerStyle() {
  1289. s := t.styles.Resizer
  1290. t.resizerPanel.SetBordersFrom(&s.Border)
  1291. t.resizerPanel.SetBordersColor4(&s.BorderColor)
  1292. t.resizerPanel.SetColor4(&s.BgColor)
  1293. }
  1294. // tableSortString is an internal type implementing the sort.Interface
  1295. // and is used to sort a table column interpreting its values as strings
  1296. type tableSortString struct {
  1297. rows []*tableRow
  1298. col int
  1299. asc bool
  1300. format string
  1301. }
  1302. func (ts tableSortString) Len() int { return len(ts.rows) }
  1303. func (ts tableSortString) Swap(i, j int) { ts.rows[i], ts.rows[j] = ts.rows[j], ts.rows[i] }
  1304. func (ts tableSortString) Less(i, j int) bool {
  1305. vi := ts.rows[i].cells[ts.col].value
  1306. vj := ts.rows[j].cells[ts.col].value
  1307. si := fmt.Sprintf(ts.format, vi)
  1308. sj := fmt.Sprintf(ts.format, vj)
  1309. if ts.asc {
  1310. return si < sj
  1311. } else {
  1312. return sj < si
  1313. }
  1314. }
  1315. // tableSortNumber is an internal type implementing the sort.Interface
  1316. // and is used to sort a table column interpreting its values as numbers
  1317. type tableSortNumber struct {
  1318. rows []*tableRow
  1319. col int
  1320. asc bool
  1321. }
  1322. func (ts tableSortNumber) Len() int { return len(ts.rows) }
  1323. func (ts tableSortNumber) Swap(i, j int) { ts.rows[i], ts.rows[j] = ts.rows[j], ts.rows[i] }
  1324. func (ts tableSortNumber) Less(i, j int) bool {
  1325. vi := ts.rows[i].cells[ts.col].value
  1326. vj := ts.rows[j].cells[ts.col].value
  1327. ni := cv2f64(vi)
  1328. nj := cv2f64(vj)
  1329. if ts.asc {
  1330. return ni < nj
  1331. } else {
  1332. return nj < ni
  1333. }
  1334. }
  1335. // Try to convert an interface value to a float64 number
  1336. func cv2f64(v interface{}) float64 {
  1337. if v == nil {
  1338. return 0
  1339. }
  1340. switch n := v.(type) {
  1341. case uint8:
  1342. return float64(n)
  1343. case uint16:
  1344. return float64(n)
  1345. case uint32:
  1346. return float64(n)
  1347. case uint64:
  1348. return float64(n)
  1349. case uint:
  1350. return float64(n)
  1351. case int8:
  1352. return float64(n)
  1353. case int16:
  1354. return float64(n)
  1355. case int32:
  1356. return float64(n)
  1357. case int64:
  1358. return float64(n)
  1359. case int:
  1360. return float64(n)
  1361. case string:
  1362. sv, err := strconv.ParseFloat(n, 64)
  1363. if err == nil {
  1364. return sv
  1365. }
  1366. return 0
  1367. default:
  1368. return 0
  1369. }
  1370. }