table.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  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 // 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("Invalid column id")
  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.recalc()
  362. }
  363. // SetRow sets the value of all the cells of the specified row from
  364. // the specified map indexed by column id.
  365. func (t *Table) SetRow(row int, values map[string]interface{}) {
  366. if row < 0 || row >= len(t.rows) {
  367. panic("Invalid row index")
  368. }
  369. for ci := 0; ci < len(t.header.cols); ci++ {
  370. c := t.header.cols[ci]
  371. cv, ok := values[c.id]
  372. if !ok {
  373. continue
  374. }
  375. t.SetCell(row, c.id, cv)
  376. }
  377. t.recalcRow(row)
  378. }
  379. // SetCell sets the value of the cell specified by its row and column id
  380. func (t *Table) SetCell(row int, colid string, value interface{}) {
  381. if row < 0 || row >= len(t.rows) {
  382. panic("Invalid row index")
  383. }
  384. c := t.header.cmap[colid]
  385. if c == nil {
  386. return
  387. }
  388. cell := t.rows[row].cells[c.order]
  389. cell.label.SetText(fmt.Sprintf(c.format, value))
  390. cell.value = value
  391. }
  392. // SetColFormat sets the formatting string (Printf) for the specified column
  393. // Update must be called to update the table.
  394. func (t *Table) SetColFormat(id, format string) error {
  395. c := t.header.cmap[id]
  396. if c == nil {
  397. return fmt.Errorf("No column with id:%s", id)
  398. }
  399. c.format = format
  400. return nil
  401. }
  402. // SetColOrder sets the exhibition order of the specified column.
  403. // The previous column which has the specified order will have
  404. // the original column order.
  405. func (t *Table) SetColOrder(colid string, order int) {
  406. // Checks column id
  407. c := t.header.cmap[colid]
  408. if c == nil {
  409. panic(fmt.Sprintf("No column with id:%s", colid))
  410. }
  411. // Checks exhibition order
  412. if order < 0 || order > len(t.header.cols) {
  413. panic("Invalid column id")
  414. }
  415. // Find the exhibition order for the specified column
  416. for ci := 0; ci < len(t.header.cols); ci++ {
  417. if t.header.cols[ci] == c {
  418. // If the order of the specified column is the same, nothing to do
  419. if ci == order {
  420. return
  421. }
  422. // Swap column orders
  423. prev := t.header.cols[order]
  424. t.header.cols[order] = c
  425. t.header.cols[ci] = prev
  426. break
  427. }
  428. }
  429. // Recalculates the header and all rows
  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. t.setColWidth(c, width)
  451. }
  452. // SetColExpand sets the column expand factor.
  453. // When the table width is increased the columns widths are
  454. // increased proportionally to their expand factor.
  455. // A column with expand factor = 0 is not increased.
  456. func (t *Table) SetColExpand(colid string, expand float32) {
  457. // Checks column id
  458. c := t.header.cmap[colid]
  459. if c == nil {
  460. panic(fmt.Sprintf("No column with id:%s", colid))
  461. }
  462. if expand < 0 {
  463. c.expand = 0
  464. } else {
  465. c.expand = expand
  466. }
  467. t.recalc()
  468. }
  469. // AddRow adds a new row at the end of the table with the specified values
  470. func (t *Table) AddRow(values map[string]interface{}) {
  471. t.InsertRow(len(t.rows), values)
  472. }
  473. // InsertRow inserts the specified values in a new row at the specified index
  474. func (t *Table) InsertRow(row int, values map[string]interface{}) {
  475. t.insertRow(row, values)
  476. t.recalc()
  477. t.Dispatch(OnTableRowCount, nil)
  478. }
  479. // RemoveRow removes from the specified row from the table
  480. func (t *Table) RemoveRow(row int) {
  481. // Checks row index
  482. if row < 0 || row >= len(t.rows) {
  483. panic("Invalid row index")
  484. }
  485. t.removeRow(row)
  486. maxFirst := t.calcMaxFirst()
  487. if t.firstRow > maxFirst {
  488. t.firstRow = maxFirst
  489. }
  490. t.recalc()
  491. t.Dispatch(OnTableRowCount, nil)
  492. }
  493. // Clear removes all rows from the table
  494. func (t *Table) Clear() {
  495. for ri := 0; ri < len(t.rows); ri++ {
  496. trow := t.rows[ri]
  497. trow.DisposeChildren(true)
  498. trow.Dispose()
  499. }
  500. t.rows = nil
  501. t.firstRow = 0
  502. t.rowCursor = -1
  503. t.recalc()
  504. t.Dispatch(OnTableRowCount, nil)
  505. }
  506. // SelectedRows returns a slice with the indexes of the currently selected rows
  507. // If no row are selected returns an empty slice
  508. func (t *Table) SelectedRows() []int {
  509. res := make([]int, 0)
  510. if t.rowCursor >= 0 {
  511. res = append(res, t.rowCursor)
  512. }
  513. for ri := 0; ri < len(t.rows); ri++ {
  514. if t.rows[ri].selected && ri != t.rowCursor {
  515. res = append(res, ri)
  516. }
  517. }
  518. return res
  519. }
  520. // ShowStatus sets the visibility of the status lines at the bottom of the table
  521. func (t *Table) ShowStatus(show bool) {
  522. if t.statusPanel.Visible() == show {
  523. return
  524. }
  525. t.statusPanel.SetVisible(show)
  526. t.recalcStatus()
  527. t.recalc()
  528. }
  529. // SetStatusText sets the text of status line at the bottom of the table
  530. // It does not change its current visibility
  531. func (t *Table) SetStatusText(text string) {
  532. t.statusLabel.SetText(text)
  533. }
  534. // Rows returns a slice of maps with the contents of the table rows
  535. // specified by the rows first and last index.
  536. // To get all the table rows, use Rows(0, -1)
  537. func (t *Table) Rows(fi, li int) []map[string]interface{} {
  538. if fi < 0 || fi >= len(t.header.cols) {
  539. panic("Invalid first row index")
  540. }
  541. if li < 0 {
  542. li = len(t.rows) - 1
  543. } else if li < 0 || li >= len(t.rows) {
  544. panic("Invalid last row index")
  545. }
  546. if li < fi {
  547. panic("Last index less than first index")
  548. }
  549. res := make([]map[string]interface{}, li-li+1)
  550. for ri := fi; ri <= li; ri++ {
  551. trow := t.rows[ri]
  552. rmap := make(map[string]interface{})
  553. for ci := 0; ci < len(t.header.cols); ci++ {
  554. c := t.header.cols[ci]
  555. rmap[c.id] = trow.cells[c.order].value
  556. }
  557. res = append(res, rmap)
  558. }
  559. return res
  560. }
  561. // Row returns a map with the current contents of the specified row index
  562. func (t *Table) Row(ri int) map[string]interface{} {
  563. if ri < 0 || ri > len(t.header.cols) {
  564. panic("Invalid row index")
  565. }
  566. res := make(map[string]interface{})
  567. trow := t.rows[ri]
  568. for ci := 0; ci < len(t.header.cols); ci++ {
  569. c := t.header.cols[ci]
  570. res[c.id] = trow.cells[c.order].value
  571. }
  572. return res
  573. }
  574. // Cell returns the current content of the specified cell
  575. func (t *Table) Cell(col string, ri int) interface{} {
  576. c := t.header.cmap[col]
  577. if c == nil {
  578. panic("Invalid column id")
  579. }
  580. if ri < 0 || ri >= len(t.rows) {
  581. panic("Invalid row index")
  582. }
  583. trow := t.rows[ri]
  584. return trow.cells[c.order].value
  585. }
  586. // SortColumn sorts the specified column interpreting its values as strings or numbers
  587. // and sorting in ascending or descending order.
  588. // This sorting is independent of the sort configuration of column set when the table was created
  589. func (t *Table) SortColumn(col string, asString bool, asc bool) {
  590. c := t.header.cmap[col]
  591. if c == nil {
  592. panic("Invalid column id")
  593. }
  594. if len(t.rows) < 2 {
  595. return
  596. }
  597. if asString {
  598. ts := tableSortString{rows: t.rows, col: c.order, asc: asc, format: c.format}
  599. sort.Sort(ts)
  600. } else {
  601. ts := tableSortNumber{rows: t.rows, col: c.order, asc: asc}
  602. sort.Sort(ts)
  603. }
  604. t.recalc()
  605. }
  606. // insertRow is the internal version of InsertRow which does not call recalc()
  607. func (t *Table) insertRow(row int, values map[string]interface{}) {
  608. // Checks row index
  609. if row < 0 || row > len(t.rows) {
  610. panic("Invalid row index")
  611. }
  612. // Creates tableRow panel
  613. trow := new(tableRow)
  614. trow.Initialize(0, 0)
  615. trow.cells = make([]*tableCell, 0)
  616. for ci := 0; ci < len(t.header.cols); ci++ {
  617. // Creates tableRow cell panel
  618. cell := new(tableCell)
  619. cell.Initialize(0, 0)
  620. cell.label.initialize("", StyleDefault.Font)
  621. cell.Add(&cell.label)
  622. trow.cells = append(trow.cells, cell)
  623. trow.Panel.Add(cell)
  624. }
  625. t.Panel.Add(trow)
  626. // Inserts tableRow in the table rows at the specified index
  627. t.rows = append(t.rows, nil)
  628. copy(t.rows[row+1:], t.rows[row:])
  629. t.rows[row] = trow
  630. t.updateRowStyle(row)
  631. // Sets the new row values from the specified map
  632. if values != nil {
  633. t.SetRow(row, values)
  634. }
  635. t.recalcRow(row)
  636. }
  637. // ScrollDown scrolls the table the specified number of rows down if possible
  638. func (t *Table) scrollDown(n int) {
  639. // Calculates number of rows to scroll down
  640. maxFirst := t.calcMaxFirst()
  641. maxScroll := maxFirst - t.firstRow
  642. if maxScroll <= 0 {
  643. return
  644. }
  645. if n > maxScroll {
  646. n = maxScroll
  647. }
  648. t.firstRow += n
  649. if t.rowCursor < t.firstRow {
  650. t.rowCursor = t.firstRow
  651. t.Dispatch(OnChange, nil)
  652. }
  653. t.recalc()
  654. return
  655. }
  656. // ScrollUp scrolls the table the specified number of rows up if possible
  657. func (t *Table) scrollUp(n int) {
  658. // Calculates number of rows to scroll up
  659. if t.firstRow == 0 {
  660. return
  661. }
  662. if n > t.firstRow {
  663. n = t.firstRow
  664. }
  665. t.firstRow -= n
  666. lastRow := t.lastRow - n
  667. if t.rowCursor > lastRow {
  668. t.rowCursor = lastRow
  669. t.Dispatch(OnChange, nil)
  670. }
  671. t.recalc()
  672. }
  673. // removeRow removes from the table the row specified its index
  674. func (t *Table) removeRow(row int) {
  675. // Get row to be removed
  676. trow := t.rows[row]
  677. // Remove row from table
  678. copy(t.rows[row:], t.rows[row+1:])
  679. t.rows[len(t.rows)-1] = nil
  680. t.rows = t.rows[:len(t.rows)-1]
  681. trow.DisposeChildren(true)
  682. trow.Dispose()
  683. // Adjusts table first visible row if necessary
  684. //if t.firstRow == row {
  685. // t.firstRow--
  686. // if t.firstRow < 0 {
  687. // t.firstRow = 0
  688. // }
  689. //}
  690. }
  691. // onCursor process subscribed cursor events
  692. func (t *Table) onCursor(evname string, ev interface{}) {
  693. switch evname {
  694. case OnCursorEnter:
  695. t.root.SetScrollFocus(t)
  696. case OnCursorLeave:
  697. t.root.SetScrollFocus(nil)
  698. }
  699. t.root.StopPropagation(Stop3D)
  700. }
  701. // onCursorPos process subscribed cursor position events
  702. func (t *Table) onCursorPos(evname string, ev interface{}) {
  703. // Convert mouse window coordinates to table content coordinates
  704. kev := ev.(*window.CursorEvent)
  705. cx, _ := t.ContentCoords(kev.Xpos, kev.Ypos)
  706. // If user is dragging the resizer, updates its position
  707. if t.resizing {
  708. t.resizerPanel.SetPosition(cx, 0)
  709. return
  710. }
  711. // Checks if the mouse cursor is near the border of a resizable column
  712. found := false
  713. for ci := 0; ci < len(t.header.cols); ci++ {
  714. c := t.header.cols[ci]
  715. dx := math32.Abs(cx - c.xr)
  716. if dx < tableResizerPix {
  717. if c.resize {
  718. found = true
  719. t.resizeCol = ci
  720. t.resizerX = c.xr
  721. t.root.SetCursorHResize()
  722. }
  723. break
  724. }
  725. }
  726. // If column not found but previously was near a resizable column,
  727. // resets the the window cursor.
  728. if !found && t.resizeCol >= 0 {
  729. t.root.SetCursorNormal()
  730. t.resizeCol = -1
  731. }
  732. t.root.StopPropagation(Stop3D)
  733. }
  734. // onMouseEvent process subscribed mouse events
  735. func (t *Table) onMouse(evname string, ev interface{}) {
  736. e := ev.(*window.MouseEvent)
  737. t.root.SetKeyFocus(t)
  738. switch evname {
  739. case OnMouseDown:
  740. // If over a resizable column border, shows the resizer panel
  741. if t.resizeCol >= 0 && e.Button == window.MouseButtonLeft {
  742. t.resizing = true
  743. height := t.ContentHeight()
  744. if t.statusPanel.Visible() {
  745. height -= t.statusPanel.Height()
  746. }
  747. px := t.resizerX - t.resizerPanel.Width()/2
  748. t.resizerPanel.SetPositionX(px)
  749. t.resizerPanel.SetHeight(height)
  750. t.resizerPanel.SetVisible(true)
  751. t.SetTopChild(&t.resizerPanel)
  752. return
  753. }
  754. // Find click position
  755. var tce TableClickEvent
  756. tce.MouseEvent = *e
  757. t.findClick(&tce)
  758. // If row is clicked, selects it
  759. if tce.Row >= 0 && e.Button == window.MouseButtonLeft {
  760. t.rowCursor = tce.Row
  761. if t.selType == TableSelMultiRow && e.Mods == window.ModControl {
  762. t.toggleRowSel(t.rowCursor)
  763. }
  764. t.recalc()
  765. t.Dispatch(OnChange, nil)
  766. }
  767. // Creates and dispatch TableClickEvent for user's context menu
  768. t.Dispatch(OnTableClick, tce)
  769. case OnMouseUp:
  770. // If user was resizing a column, hides the resizer and
  771. // sets the new column width if possible
  772. if t.resizing {
  773. t.resizing = false
  774. t.resizerPanel.SetVisible(false)
  775. t.root.SetCursorNormal()
  776. // Calculates the new column width
  777. cx, _ := t.ContentCoords(e.Xpos, e.Ypos)
  778. c := t.header.cols[t.resizeCol]
  779. width := cx - c.xl
  780. t.setColWidth(c, width)
  781. }
  782. default:
  783. return
  784. }
  785. t.root.StopPropagation(StopAll)
  786. }
  787. // onKeyEvent receives subscribed key events for this table
  788. func (t *Table) onKey(evname string, ev interface{}) {
  789. kev := ev.(*window.KeyEvent)
  790. if kev.Keycode == window.KeyUp && kev.Mods == 0 {
  791. t.selPrev()
  792. } else if kev.Keycode == window.KeyDown && kev.Mods == 0 {
  793. t.selNext()
  794. } else if kev.Keycode == window.KeyPageUp && kev.Mods == 0 {
  795. t.prevPage()
  796. } else if kev.Keycode == window.KeyPageDown && kev.Mods == 0 {
  797. t.nextPage()
  798. } else if kev.Keycode == window.KeyPageUp && kev.Mods == window.ModControl {
  799. t.firstPage()
  800. } else if kev.Keycode == window.KeyPageDown && kev.Mods == window.ModControl {
  801. t.lastPage()
  802. } else if kev.Keycode == window.KeyEnter && kev.Mods == window.ModControl {
  803. if t.selType == TableSelMultiRow {
  804. t.toggleRowSel(t.rowCursor)
  805. }
  806. }
  807. }
  808. // onResize receives subscribed resize events for this table
  809. func (t *Table) onResize(evname string, ev interface{}) {
  810. t.recalc()
  811. t.recalcStatus()
  812. }
  813. // onScroll receives subscribed scroll events for this table
  814. func (t *Table) onScroll(evname string, ev interface{}) {
  815. sev := ev.(*window.ScrollEvent)
  816. if sev.Yoffset > 0 {
  817. t.scrollUp(1)
  818. } else if sev.Yoffset < 0 {
  819. t.scrollDown(1)
  820. }
  821. t.root.StopPropagation(Stop3D)
  822. }
  823. // onRicon receives subscribed events for column header right icon
  824. func (t *Table) onRicon(evname string, c *tableColHeader) {
  825. icon := tableSortedNoneIcon
  826. var asc bool
  827. if c.sorted == tableSortedNone || c.sorted == tableSortedDesc {
  828. c.sorted = tableSortedAsc
  829. icon = tableSortedAscIcon
  830. asc = false
  831. } else {
  832. c.sorted = tableSortedDesc
  833. icon = tableSortedDescIcon
  834. asc = true
  835. }
  836. var asString bool
  837. if c.sort == TableSortString {
  838. asString = true
  839. } else {
  840. asString = false
  841. }
  842. t.SortColumn(c.id, asString, asc)
  843. c.ricon.SetText(string(icon))
  844. }
  845. // findClick finds where in the table the specified mouse click event
  846. // occurred updating the specified TableClickEvent with the click coordinates.
  847. func (t *Table) findClick(ev *TableClickEvent) {
  848. x, y := t.ContentCoords(ev.Xpos, ev.Ypos)
  849. ev.X = x
  850. ev.Y = y
  851. ev.Row = -1
  852. // Find column id
  853. colx := float32(0)
  854. for ci := 0; ci < len(t.header.cols); ci++ {
  855. c := t.header.cols[ci]
  856. if !c.Visible() {
  857. continue
  858. }
  859. colx += t.header.cols[ci].Width()
  860. if x < colx {
  861. ev.Col = c.id
  862. ev.ColOrder = ci
  863. break
  864. }
  865. }
  866. // If column not found the user clicked at the right of rows
  867. if ev.Col == "" {
  868. return
  869. }
  870. // Checks if is in header
  871. if t.header.Visible() && y < t.header.Height() {
  872. ev.Header = true
  873. }
  874. // Find row clicked
  875. rowy := float32(0)
  876. if t.header.Visible() {
  877. rowy = t.header.Height()
  878. }
  879. theight := t.ContentHeight()
  880. for ri := t.firstRow; ri < len(t.rows); ri++ {
  881. trow := t.rows[ri]
  882. rowy += trow.height
  883. if rowy > theight {
  884. break
  885. }
  886. if y < rowy {
  887. ev.Row = ri
  888. break
  889. }
  890. }
  891. }
  892. // selNext selects the next row if possible
  893. func (t *Table) selNext() {
  894. // If selected row is last, nothing to do
  895. if t.rowCursor == len(t.rows)-1 {
  896. return
  897. }
  898. // If no selected row, selects first visible row
  899. if t.rowCursor < 0 {
  900. t.rowCursor = t.firstRow
  901. t.recalc()
  902. t.Dispatch(OnChange, nil)
  903. return
  904. }
  905. // Selects next row
  906. t.rowCursor++
  907. t.Dispatch(OnChange, nil)
  908. // Scroll down if necessary
  909. if t.rowCursor > t.lastRow {
  910. t.scrollDown(1)
  911. } else {
  912. t.recalc()
  913. }
  914. }
  915. // selPrev selects the previous row if possible
  916. func (t *Table) selPrev() {
  917. // If selected row is first, nothing to do
  918. sel := t.rowCursor
  919. if sel == 0 {
  920. return
  921. }
  922. // If no selected row, selects last visible row
  923. if sel < 0 {
  924. t.rowCursor = t.lastRow
  925. t.recalc()
  926. t.Dispatch(OnChange, nil)
  927. return
  928. }
  929. // Selects previous row and selects previous
  930. prev := sel - 1
  931. t.rowCursor = prev
  932. // Scroll up if necessary
  933. if prev < t.firstRow && t.firstRow > 0 {
  934. t.scrollUp(1)
  935. } else {
  936. t.recalc()
  937. }
  938. t.Dispatch(OnChange, nil)
  939. }
  940. // nextPage shows the next page of rows and selects its first row
  941. func (t *Table) nextPage() {
  942. if len(t.rows) == 0 {
  943. return
  944. }
  945. if t.lastRow == len(t.rows)-1 {
  946. t.rowCursor = t.lastRow
  947. t.recalc()
  948. t.Dispatch(OnChange, nil)
  949. return
  950. }
  951. plen := t.lastRow - t.firstRow
  952. if plen <= 0 {
  953. return
  954. }
  955. t.scrollDown(plen)
  956. }
  957. // prevPage shows the previous page of rows and selects its last row
  958. func (t *Table) prevPage() {
  959. if t.firstRow == 0 {
  960. t.rowCursor = 0
  961. t.recalc()
  962. t.Dispatch(OnChange, nil)
  963. return
  964. }
  965. plen := t.lastRow - t.firstRow
  966. if plen <= 0 {
  967. return
  968. }
  969. t.scrollUp(plen)
  970. }
  971. // firstPage shows the first page of rows and selects the first row
  972. func (t *Table) firstPage() {
  973. if len(t.rows) == 0 {
  974. return
  975. }
  976. t.firstRow = 0
  977. t.rowCursor = 0
  978. t.recalc()
  979. t.Dispatch(OnChange, nil)
  980. }
  981. // lastPage shows the last page of rows and selects the last row
  982. func (t *Table) lastPage() {
  983. if len(t.rows) == 0 {
  984. return
  985. }
  986. maxFirst := t.calcMaxFirst()
  987. t.firstRow = maxFirst
  988. t.rowCursor = len(t.rows) - 1
  989. t.recalc()
  990. t.Dispatch(OnChange, nil)
  991. }
  992. // selectRow selects the specified row.
  993. // Should be used only when multi row selection is enabled
  994. func (t *Table) selectRow(ri int) {
  995. trow := t.rows[ri]
  996. trow.selected = true
  997. t.Dispatch(OnChange, nil)
  998. }
  999. // toggleRowSel toogles the specified row selection state
  1000. // Should be used only when multi row selection is enabled
  1001. func (t *Table) toggleRowSel(ri int) {
  1002. trow := t.rows[ri]
  1003. trow.selected = !trow.selected
  1004. t.Dispatch(OnChange, nil)
  1005. }
  1006. // setColWidth sets the width of the specified column
  1007. func (t *Table) setColWidth(c *tableColHeader, width float32) {
  1008. // Sets the column width
  1009. if width < c.minWidth {
  1010. width = c.minWidth
  1011. }
  1012. if c.Width() == width {
  1013. return
  1014. }
  1015. dw := width - c.Width()
  1016. c.SetWidth(width)
  1017. // Find the column index and if any column has expand != 0
  1018. hasExpand := false
  1019. ci := -1
  1020. for i := 0; i < len(t.header.cols); i++ {
  1021. current := t.header.cols[i]
  1022. if current == c {
  1023. ci = i
  1024. }
  1025. if current.expand > 0 && current.Visible() {
  1026. hasExpand = true
  1027. }
  1028. }
  1029. if ci >= len(t.header.cols) {
  1030. panic("Invalid header pointer")
  1031. }
  1032. // If no column is expandable, nothing more todo
  1033. if !hasExpand {
  1034. t.recalc()
  1035. return
  1036. }
  1037. // Calculates the width of the columns at the right
  1038. rwidth := float32(0)
  1039. for i := ci + 1; i < len(t.header.cols); i++ {
  1040. c := t.header.cols[i]
  1041. if !c.Visible() {
  1042. continue
  1043. }
  1044. rwidth += c.Width()
  1045. }
  1046. // Distributes the delta to the columns at the right
  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. cdelta := -dw * (c.Width() / rwidth)
  1053. newWidth := c.Width() + cdelta
  1054. if newWidth < c.minWidth {
  1055. newWidth = c.minWidth
  1056. }
  1057. c.SetWidth(newWidth)
  1058. }
  1059. t.recalc()
  1060. }
  1061. // recalcHeader recalculates and sets the position and size of the header panels
  1062. func (t *Table) recalcHeader() {
  1063. // Calculates total width, height, expansion and available width space
  1064. hwidth := float32(0)
  1065. height := float32(0)
  1066. wspace := float32(0)
  1067. totalExpand := float32(0)
  1068. for ci := 0; ci < len(t.header.cols); ci++ {
  1069. // If column is invisible, ignore
  1070. c := t.header.cols[ci]
  1071. if !c.Visible() {
  1072. continue
  1073. }
  1074. if c.Height() > height {
  1075. height = c.Height()
  1076. }
  1077. if c.expand > 0 {
  1078. totalExpand += c.expand
  1079. }
  1080. hwidth += c.Width()
  1081. }
  1082. // Total table width
  1083. twidth := t.ContentWidth()
  1084. if t.vscroll != nil && t.vscroll.Visible() {
  1085. twidth -= t.vscroll.Width()
  1086. }
  1087. // Available space for columns: may be negative
  1088. wspace = twidth - hwidth
  1089. // If no expandable column, keeps the columns widths
  1090. if totalExpand == 0 {
  1091. } else if wspace >= 0 {
  1092. for ci := 0; ci < len(t.header.cols); ci++ {
  1093. // If column is invisible, ignore
  1094. c := t.header.cols[ci]
  1095. if !c.Visible() {
  1096. continue
  1097. }
  1098. // There is space available and if column is expandable,
  1099. // expands it proportionaly to the other expandable columns
  1100. factor := c.expand / totalExpand
  1101. w := factor * wspace
  1102. c.SetWidth(c.Width() + w)
  1103. }
  1104. } else {
  1105. acols := make([]*tableColHeader, 0)
  1106. awidth := float32(0)
  1107. widthAvail := twidth
  1108. // Sets the widths of the columns
  1109. for ci := 0; ci < len(t.header.cols); ci++ {
  1110. // If column is invisible, ignore
  1111. c := t.header.cols[ci]
  1112. if !c.Visible() {
  1113. continue
  1114. }
  1115. // The table was reduced so shrinks this column proportionally to its current width
  1116. factor := c.Width() / hwidth
  1117. newWidth := factor * twidth
  1118. if newWidth < c.minWidth {
  1119. newWidth = c.minWidth
  1120. c.SetWidth(newWidth)
  1121. widthAvail -= c.minWidth
  1122. } else {
  1123. acols = append(acols, c)
  1124. awidth += c.Width()
  1125. }
  1126. }
  1127. for ci := 0; ci < len(acols); ci++ {
  1128. c := acols[ci]
  1129. factor := c.Width() / awidth
  1130. newWidth := factor * widthAvail
  1131. c.SetWidth(newWidth)
  1132. }
  1133. }
  1134. // Sets the header panel and its internal panels positions
  1135. posx := float32(0)
  1136. for ci := 0; ci < len(t.header.cols); ci++ {
  1137. // If column is invisible, ignore
  1138. c := t.header.cols[ci]
  1139. if !c.Visible() {
  1140. continue
  1141. }
  1142. // Sets the right icon position inside the column header panel
  1143. if c.ricon != nil {
  1144. ix := c.ContentWidth() - c.ricon.Width()
  1145. if ix < 0 {
  1146. ix = 0
  1147. }
  1148. c.ricon.SetPosition(ix, 0)
  1149. }
  1150. // Sets the column header panel position
  1151. c.SetPosition(posx, 0)
  1152. c.SetVisible(true)
  1153. c.xl = posx
  1154. posx += c.Width()
  1155. c.xr = posx
  1156. }
  1157. // Last header
  1158. w := t.ContentWidth() - posx
  1159. if w > 0 {
  1160. t.header.lastPan.SetVisible(true)
  1161. t.header.lastPan.SetSize(w, height)
  1162. t.header.lastPan.SetPosition(posx, 0)
  1163. } else {
  1164. t.header.lastPan.SetVisible(false)
  1165. }
  1166. // Header container
  1167. t.header.SetWidth(t.ContentWidth())
  1168. t.header.SetContentHeight(height)
  1169. }
  1170. // recalcStatus recalculates and sets the position and size of the status panel and its label
  1171. func (t *Table) recalcStatus() {
  1172. if !t.statusPanel.Visible() {
  1173. return
  1174. }
  1175. t.statusPanel.SetContentHeight(t.statusLabel.Height())
  1176. py := t.ContentHeight() - t.statusPanel.Height()
  1177. t.statusPanel.SetPosition(0, py)
  1178. t.statusPanel.SetWidth(t.ContentWidth())
  1179. }
  1180. // recalc calculates the visibility, positions and sizes of all row cells.
  1181. // should be called in the following situations:
  1182. // - the table is resized
  1183. // - row is added, inserted or removed
  1184. // - column alignment and expansion changed
  1185. // - column visibility is changed
  1186. // - horizontal or vertical scroll position changed
  1187. func (t *Table) recalc() {
  1188. // Get available row height for rows
  1189. starty, theight := t.rowsHeight()
  1190. // Determines if it is necessary to show the scrollbar or not.
  1191. scroll := false
  1192. py := starty
  1193. for ri := 0; ri < len(t.rows); ri++ {
  1194. trow := t.rows[ri]
  1195. py += trow.height
  1196. if py > starty+theight {
  1197. scroll = true
  1198. break
  1199. }
  1200. }
  1201. t.setVScrollBar(scroll)
  1202. // Recalculates the header
  1203. t.recalcHeader()
  1204. // Sets the position and sizes of all cells of the visible rows
  1205. py = starty
  1206. for ri := 0; ri < len(t.rows); ri++ {
  1207. trow := t.rows[ri]
  1208. // If row is before first row or its y coordinate is greater the table height,
  1209. // sets it invisible
  1210. if ri < t.firstRow || py > starty+theight {
  1211. trow.SetVisible(false)
  1212. continue
  1213. }
  1214. t.recalcRow(ri)
  1215. // Set row y position and visible
  1216. trow.SetPosition(0, py)
  1217. trow.SetVisible(true)
  1218. t.updateRowStyle(ri)
  1219. // Set the last completely visible row index
  1220. if py+trow.Height() <= starty+theight {
  1221. t.lastRow = ri
  1222. }
  1223. //log.Error("ri:%v py:%v theight:%v", ri, py, theight)
  1224. py += trow.height
  1225. }
  1226. // Status panel must be on top of all the row panels
  1227. t.SetTopChild(&t.statusPanel)
  1228. }
  1229. // recalcRow recalculates the positions and sizes of all cells of the specified row
  1230. // Should be called when the row is created and column visibility or order is changed.
  1231. func (t *Table) recalcRow(ri int) {
  1232. trow := t.rows[ri]
  1233. // Calculates and sets row height
  1234. maxheight := float32(0)
  1235. for ci := 0; ci < len(t.header.cols); ci++ {
  1236. // If column is hidden, ignore
  1237. c := t.header.cols[ci]
  1238. if !c.Visible() {
  1239. continue
  1240. }
  1241. cell := trow.cells[c.order]
  1242. cellHeight := cell.MinHeight() + cell.label.Height()
  1243. if cellHeight > maxheight {
  1244. maxheight = cellHeight
  1245. }
  1246. }
  1247. trow.SetContentHeight(maxheight)
  1248. // Sets row cells sizes and positions and sets row width
  1249. px := float32(0)
  1250. for ci := 0; ci < len(t.header.cols); ci++ {
  1251. // If column is hidden, ignore
  1252. c := t.header.cols[ci]
  1253. cell := trow.cells[c.order]
  1254. if !c.Visible() {
  1255. cell.SetVisible(false)
  1256. continue
  1257. }
  1258. // Sets cell position and size
  1259. cell.SetPosition(px, 0)
  1260. cell.SetVisible(true)
  1261. cell.SetSize(c.Width(), trow.ContentHeight())
  1262. // Checks for format function
  1263. if c.formatFunc != nil {
  1264. text := c.formatFunc(TableCell{t, ri, c.id, cell.value})
  1265. cell.label.SetText(text)
  1266. }
  1267. // Sets the cell label alignment inside the cell
  1268. ccw := cell.ContentWidth()
  1269. lw := cell.label.Width()
  1270. space := ccw - lw
  1271. lx := float32(0)
  1272. switch c.align {
  1273. case AlignLeft:
  1274. case AlignRight:
  1275. if space > 0 {
  1276. lx = ccw - lw
  1277. }
  1278. case AlignCenter:
  1279. if space > 0 {
  1280. lx = space / 2
  1281. }
  1282. }
  1283. cell.label.SetPosition(lx, 0)
  1284. px += c.Width()
  1285. }
  1286. trow.SetContentWidth(px)
  1287. }
  1288. // rowsHeight returns the available start y coordinate and height in the table for rows,
  1289. // considering the visibility of the header and status panels.
  1290. func (t *Table) rowsHeight() (float32, float32) {
  1291. start := float32(0)
  1292. height := t.ContentHeight()
  1293. if t.header.Visible() {
  1294. height -= t.header.Height()
  1295. start += t.header.Height()
  1296. }
  1297. if t.statusPanel.Visible() {
  1298. height -= t.statusPanel.Height()
  1299. }
  1300. if height < 0 {
  1301. return 0, 0
  1302. }
  1303. return start, height
  1304. }
  1305. // setVScrollBar sets the visibility state of the vertical scrollbar
  1306. func (t *Table) setVScrollBar(state bool) {
  1307. // Visible
  1308. if state {
  1309. var scrollWidth float32 = 20
  1310. // Creates scroll bar if necessary
  1311. if t.vscroll == nil {
  1312. t.vscroll = NewVScrollBar(0, 0)
  1313. t.vscroll.SetBorders(0, 0, 0, 1)
  1314. t.vscroll.Subscribe(OnChange, t.onVScrollBar)
  1315. t.Panel.Add(t.vscroll)
  1316. }
  1317. // Sets the scroll bar size and positions
  1318. py, height := t.rowsHeight()
  1319. t.vscroll.SetSize(scrollWidth, height)
  1320. t.vscroll.SetPositionX(t.ContentWidth() - scrollWidth)
  1321. t.vscroll.SetPositionY(py)
  1322. t.vscroll.recalc()
  1323. t.vscroll.SetVisible(true)
  1324. if !t.scrollBarEvent {
  1325. maxFirst := t.calcMaxFirst()
  1326. t.vscroll.SetValue(float32(t.firstRow) / float32(maxFirst))
  1327. } else {
  1328. t.scrollBarEvent = false
  1329. }
  1330. // scroll bar must be on top of all table rows
  1331. t.SetTopChild(t.vscroll)
  1332. // Not visible
  1333. } else {
  1334. if t.vscroll != nil {
  1335. t.vscroll.SetVisible(false)
  1336. }
  1337. }
  1338. }
  1339. // onVScrollBar is called when a vertical scroll bar event is received
  1340. func (t *Table) onVScrollBar(evname string, ev interface{}) {
  1341. // Calculates the new first visible line
  1342. pos := t.vscroll.Value()
  1343. maxFirst := t.calcMaxFirst()
  1344. first := int(math.Floor((float64(maxFirst) * pos) + 0.5))
  1345. // Sets the new selected row
  1346. sel := t.rowCursor
  1347. selChange := false
  1348. if sel < first {
  1349. t.rowCursor = first
  1350. selChange = true
  1351. } else {
  1352. lines := first - t.firstRow
  1353. lastRow := t.lastRow + lines
  1354. if sel > lastRow {
  1355. t.rowCursor = lastRow
  1356. selChange = true
  1357. }
  1358. }
  1359. t.scrollBarEvent = true
  1360. t.firstRow = first
  1361. t.recalc()
  1362. if selChange {
  1363. t.Dispatch(OnChange, nil)
  1364. }
  1365. }
  1366. // calcMaxFirst calculates the maximum index of the first visible row
  1367. // such as the remaing rows fits completely inside the table
  1368. // It is used when scrolling the table vertically
  1369. func (t *Table) calcMaxFirst() int {
  1370. _, total := t.rowsHeight()
  1371. ri := len(t.rows) - 1
  1372. if ri < 0 {
  1373. return 0
  1374. }
  1375. height := float32(0)
  1376. for {
  1377. trow := t.rows[ri]
  1378. height += trow.height
  1379. if height > total {
  1380. break
  1381. }
  1382. ri--
  1383. if ri < 0 {
  1384. break
  1385. }
  1386. }
  1387. return ri + 1
  1388. }
  1389. // updateRowStyle applies the correct style for the specified row
  1390. func (t *Table) updateRowStyle(ri int) {
  1391. row := t.rows[ri]
  1392. var trs *TableRowStyle
  1393. if ri == t.rowCursor {
  1394. trs = t.styles.RowCursor
  1395. } else if row.selected {
  1396. trs = t.styles.RowSel
  1397. } else {
  1398. if ri%2 == 0 {
  1399. trs = t.styles.RowEven
  1400. } else {
  1401. trs = t.styles.RowOdd
  1402. }
  1403. }
  1404. t.applyRowStyle(row, trs)
  1405. }
  1406. // applyHeaderStyle applies style to the specified table header
  1407. // the last header panel does not the right border.
  1408. func (t *Table) applyHeaderStyle(h *Panel, last bool) {
  1409. s := t.styles.Header
  1410. borders := s.Border
  1411. if !last {
  1412. h.SetBordersFrom(&borders)
  1413. } else {
  1414. borders.Right = 0
  1415. h.SetBordersFrom(&borders)
  1416. }
  1417. h.SetBordersColor4(&s.BorderColor)
  1418. h.SetPaddingsFrom(&s.Paddings)
  1419. h.SetColor(&s.BgColor)
  1420. }
  1421. // applyRowStyle applies the specified style to all cells for the specified table row
  1422. func (t *Table) applyRowStyle(trow *tableRow, trs *TableRowStyle) {
  1423. for i := 0; i < len(trow.cells); i++ {
  1424. cell := trow.cells[i]
  1425. cell.SetBordersFrom(&trs.Border)
  1426. cell.SetBordersColor4(&trs.BorderColor)
  1427. cell.SetPaddingsFrom(&trs.Paddings)
  1428. cell.SetColor(&trs.BgColor)
  1429. }
  1430. }
  1431. // applyStatusStyle applies the status style
  1432. func (t *Table) applyStatusStyle() {
  1433. s := t.styles.Status
  1434. t.statusPanel.SetBordersFrom(&s.Border)
  1435. t.statusPanel.SetBordersColor4(&s.BorderColor)
  1436. t.statusPanel.SetPaddingsFrom(&s.Paddings)
  1437. t.statusPanel.SetColor(&s.BgColor)
  1438. }
  1439. // applyResizerStyle applies the status style
  1440. func (t *Table) applyResizerStyle() {
  1441. s := t.styles.Resizer
  1442. t.resizerPanel.SetBordersFrom(&s.Border)
  1443. t.resizerPanel.SetBordersColor4(&s.BorderColor)
  1444. t.resizerPanel.SetColor4(&s.BgColor)
  1445. }
  1446. // tableSortString is an internal type implementing the sort.Interface
  1447. // and is used to sort a table column interpreting its values as strings
  1448. type tableSortString struct {
  1449. rows []*tableRow
  1450. col int
  1451. asc bool
  1452. format string
  1453. }
  1454. func (ts tableSortString) Len() int { return len(ts.rows) }
  1455. func (ts tableSortString) Swap(i, j int) { ts.rows[i], ts.rows[j] = ts.rows[j], ts.rows[i] }
  1456. func (ts tableSortString) Less(i, j int) bool {
  1457. vi := ts.rows[i].cells[ts.col].value
  1458. vj := ts.rows[j].cells[ts.col].value
  1459. si := fmt.Sprintf(ts.format, vi)
  1460. sj := fmt.Sprintf(ts.format, vj)
  1461. if ts.asc {
  1462. return si < sj
  1463. } else {
  1464. return sj < si
  1465. }
  1466. }
  1467. // tableSortNumber is an internal type implementing the sort.Interface
  1468. // and is used to sort a table column interpreting its values as numbers
  1469. type tableSortNumber struct {
  1470. rows []*tableRow
  1471. col int
  1472. asc bool
  1473. }
  1474. func (ts tableSortNumber) Len() int { return len(ts.rows) }
  1475. func (ts tableSortNumber) Swap(i, j int) { ts.rows[i], ts.rows[j] = ts.rows[j], ts.rows[i] }
  1476. func (ts tableSortNumber) Less(i, j int) bool {
  1477. vi := ts.rows[i].cells[ts.col].value
  1478. vj := ts.rows[j].cells[ts.col].value
  1479. ni := cv2f64(vi)
  1480. nj := cv2f64(vj)
  1481. if ts.asc {
  1482. return ni < nj
  1483. } else {
  1484. return nj < ni
  1485. }
  1486. }
  1487. // Try to convert an interface value to a float64 number
  1488. func cv2f64(v interface{}) float64 {
  1489. if v == nil {
  1490. return 0
  1491. }
  1492. switch n := v.(type) {
  1493. case uint8:
  1494. return float64(n)
  1495. case uint16:
  1496. return float64(n)
  1497. case uint32:
  1498. return float64(n)
  1499. case uint64:
  1500. return float64(n)
  1501. case uint:
  1502. return float64(n)
  1503. case int8:
  1504. return float64(n)
  1505. case int16:
  1506. return float64(n)
  1507. case int32:
  1508. return float64(n)
  1509. case int64:
  1510. return float64(n)
  1511. case int:
  1512. return float64(n)
  1513. case string:
  1514. sv, err := strconv.ParseFloat(n, 64)
  1515. if err == nil {
  1516. return sv
  1517. }
  1518. return 0
  1519. default:
  1520. return 0
  1521. }
  1522. }