forked from g3n/engine
/
table.go
1681 lines (1497 loc) · 41.5 KB
/
table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gui
import (
"fmt"
"math"
"sort"
"strconv"
"github.com/g3n/engine/gui/assets/icon"
"github.com/g3n/engine/math32"
"github.com/g3n/engine/window"
)
const (
// OnTableClick is the event generated when the table is right or left clicked
// Parameter is TableClickEvent
OnTableClick = "onTableClick"
// OnTableRowCount is the event generated when the table row count changes (no parameters)
OnTableRowCount = "onTableRowCount"
)
// TableSortType is the type used to specify the sort method for a table column
type TableSortType int
// The various sorting types
const (
TableSortNone TableSortType = iota
TableSortString
TableSortNumber
)
// TableSelType is the type used to specify the table row selection
type TableSelType int
const (
// TableSelSingleRow is the single row selection mode (default)
TableSelSingleRow TableSelType = iota
// TableSelMultiRow is the multiple row selection mode
TableSelMultiRow
)
const (
tableSortedNoneIcon = icon.SwapVert
tableSortedAscIcon = icon.ArrowDownward
tableSortedDescIcon = icon.ArrowUpward
tableSortedNone = 0
tableSortedAsc = 1
tableSortedDesc = 2
tableResizerPix = 4
tableColMinWidth = 16
tableErrInvRow = "Invalid row index"
tableErrInvCol = "Invalid column id"
)
//
// Table implements a panel which can contains child panels
// organized in rows and columns.
//
type Table struct {
Panel // Embedded panel
styles *TableStyles // pointer to current styles
header tableHeader // table headers
rows []*tableRow // array of table rows
rowCursor int // index of row cursor
firstRow int // index of the first visible row
lastRow int // index of the last visible row
vscroll *ScrollBar // vertical scroll bar
statusPanel Panel // optional bottom status panel
statusLabel *Label // status label
scrollBarEvent bool // do not update the scrollbar value in recalc() if true
resizerPanel Panel // resizer panel
resizeCol int // column being resized
resizerX float32 // initial resizer x coordinate
resizing bool // dragging the column resizer
selType TableSelType // table selection type
}
// TableColumn describes a table column
type TableColumn struct {
Id string // Column id used to reference the column. Must be unique
Header string // Column name shown in the table header
Width float32 // Initial column width in pixels
Minwidth float32 // Minimum width in pixels for this column
Hidden bool // Hidden flag
Align Align // Cell content alignment: AlignLeft|AlignCenter|AlignRight
Format string // Format string for formatting the columns' cells
FormatFunc TableFormatFunc // Format function (overrides Format string)
Expand float32 // Column width expansion factor (0 for no expansion)
Sort TableSortType // Column sort type
Resize bool // Allow column to be resized by user
}
// TableCell describes a table cell.
// It is used as a parameter for formatting function
type TableCell struct {
Tab *Table // Pointer to table
Row int // Row index
Col string // Column id
Value interface{} // Cell value
}
// TableFormatFunc is the type for formatting functions
type TableFormatFunc func(cell TableCell) string
// TableHeaderStyle describes the style of the table header
type TableHeaderStyle BasicStyle
// TableRowStyle describes the style of the table row
type TableRowStyle BasicStyle
// TableStatusStyle describes the style of the table status line panel
type TableStatusStyle BasicStyle
// TableResizerStyle describes the style of the table resizer panel
type TableResizerStyle struct {
Width float32
Border RectBounds
BorderColor math32.Color4
BgColor math32.Color4
}
// TableStyles describes all styles of the table header and rows
type TableStyles struct {
Header TableHeaderStyle
RowEven TableRowStyle
RowOdd TableRowStyle
RowCursor TableRowStyle
RowSel TableRowStyle
Status TableStatusStyle
Resizer TableResizerStyle
}
// TableClickEvent describes a mouse click event over a table
// It contains the original mouse event plus additional information
type TableClickEvent struct {
window.MouseEvent // Embedded window mouse event
X float32 // Table content area X coordinate
Y float32 // Table content area Y coordinate
Header bool // True if header was clicked
Row int // Index of table row (may be -1)
Col string // Id of table column (may be empty)
ColOrder int // Current column exhibition order
}
// tableHeader is panel which contains the individual header panels for each column
type tableHeader struct {
Panel // embedded panel
cmap map[string]*tableColHeader // maps column id with its panel/descriptor
cols []*tableColHeader // array of individual column headers/descriptors
lastPan Panel // last header panel not associated with a user column
}
// tableColHeader is panel for a column header
type tableColHeader struct {
Panel // header panel
label *Label // header label
ricon *Label // header right icon (sort direction)
id string // column id
width float32 // initial column width
minWidth float32 // minimum width
format string // column format string
formatFunc TableFormatFunc // column format function
align Align // column alignment
expand float32 // column expand factor
sort TableSortType // column sort type
resize bool // column can be resized by user
order int // row columns order
sorted int // current sorted status
xl float32 // left border coordinate in pixels
xr float32 // right border coordinate in pixels
}
// tableRow is panel which contains an entire table row of cells
type tableRow struct {
Panel // embedded panel
selected bool // row selected flag
cells []*tableCell // array of row cells
}
// tableCell is a panel which contains one cell (a label)
type tableCell struct {
Panel // embedded panel
label Label // cell label
value interface{} // cell current value
}
// NewTable creates and returns a pointer to a new Table with the
// specified width, height and columns
func NewTable(width, height float32, cols []TableColumn) (*Table, error) {
t := new(Table)
t.Panel.Initialize(width, height)
t.styles = &StyleDefault().Table
t.rowCursor = -1
// Initialize table header
t.header.Initialize(0, 0)
t.header.cmap = make(map[string]*tableColHeader)
t.header.cols = make([]*tableColHeader, 0)
// Create column header panels
for ci := 0; ci < len(cols); ci++ {
cdesc := cols[ci]
// Column id must not be empty
if cdesc.Id == "" {
return nil, fmt.Errorf("Column with empty id")
}
// Column id must be unique
if t.header.cmap[cdesc.Id] != nil {
return nil, fmt.Errorf("Column with duplicate id")
}
// Creates a column header
c := new(tableColHeader)
c.Initialize(0, 0)
t.applyHeaderStyle(&c.Panel, false)
c.label = NewLabel(cdesc.Header)
c.Add(c.label)
c.id = cdesc.Id
c.minWidth = cdesc.Minwidth
if c.minWidth < tableColMinWidth {
c.minWidth = tableColMinWidth
}
c.width = cdesc.Width
if c.width < c.minWidth {
c.width = c.minWidth
}
c.align = cdesc.Align
c.format = cdesc.Format
c.formatFunc = cdesc.FormatFunc
c.expand = cdesc.Expand
c.sort = cdesc.Sort
c.resize = cdesc.Resize
// Adds optional sort icon
if c.sort != TableSortNone {
c.ricon = NewIcon(string(tableSortedNoneIcon))
c.Add(c.ricon)
c.ricon.Subscribe(OnMouseDown, func(evname string, ev interface{}) {
t.onRicon(evname, c)
})
}
// Sets default format and order
if c.format == "" {
c.format = "%v"
}
c.order = ci
c.SetVisible(!cdesc.Hidden)
t.header.cmap[c.id] = c
// Sets column header width and height
width := cdesc.Width
if width < c.label.Width()+c.MinWidth() {
width = c.label.Width() + c.MinWidth()
}
c.SetContentSize(width, c.label.Height())
// Adds the column header to the header panel
t.header.cols = append(t.header.cols, c)
t.header.Panel.Add(c)
}
// Creates last header
t.header.lastPan.Initialize(0, 0)
t.applyHeaderStyle(&t.header.lastPan, true)
t.header.Panel.Add(&t.header.lastPan)
// Add header panel to the table panel
t.Panel.Add(&t.header)
// Creates resizer panel
t.resizerPanel.Initialize(t.styles.Resizer.Width, 0)
t.resizerPanel.SetVisible(false)
t.applyResizerStyle()
t.Panel.Add(&t.resizerPanel)
// Creates status panel
t.statusPanel.Initialize(0, 0)
t.statusPanel.SetVisible(false)
t.statusLabel = NewLabel("")
t.applyStatusStyle()
t.statusPanel.Add(t.statusLabel)
t.Panel.Add(&t.statusPanel)
// Subscribe to events
t.Panel.Subscribe(OnCursorEnter, t.onCursor)
t.Panel.Subscribe(OnCursorLeave, t.onCursor)
t.Panel.Subscribe(OnCursor, t.onCursorPos)
t.Panel.Subscribe(OnScroll, t.onScroll)
t.Panel.Subscribe(OnMouseUp, t.onMouse)
t.Panel.Subscribe(OnMouseDown, t.onMouse)
t.Panel.Subscribe(OnKeyDown, t.onKey)
t.Panel.Subscribe(OnKeyRepeat, t.onKey)
t.Panel.Subscribe(OnResize, t.onResize)
t.recalc()
return t, nil
}
// SetStyles set this table styles overriding the default
func (t *Table) SetStyles(ts *TableStyles) {
t.styles = ts
t.recalc()
}
// SetSelectionType sets this table selection type
// Possible values are: TableSelSingleRow|TableSelMultiRow
func (t *Table) SetSelectionType(sel TableSelType) {
t.selType = sel
}
// ShowHeader shows or hides the table header
func (t *Table) ShowHeader(show bool) {
if t.header.Visible() == show {
return
}
t.header.SetVisible(show)
t.recalc()
}
// ShowColumn sets the visibility of the column with the specified id
// If the column id does not exit the function panics.
func (t *Table) ShowColumn(col string, show bool) {
c := t.header.cmap[col]
if c == nil {
panic(tableErrInvCol)
}
if c.Visible() == show {
return
}
c.SetVisible(show)
t.recalc()
}
// ShowAllColumns shows all the table columns
func (t *Table) ShowAllColumns() {
recalc := false
for ci := 0; ci < len(t.header.cols); ci++ {
c := t.header.cols[ci]
if !c.Visible() {
c.SetVisible(true)
recalc = true
}
}
if !recalc {
return
}
t.recalc()
}
// RowCount returns the current number of rows in the table
func (t *Table) RowCount() int {
return len(t.rows)
}
// SetRows clears all current rows of the table and
// sets new rows from the specifying parameter.
// Each row is a map keyed by the colum id.
// The map value currently can be a string or any number type
// If a row column is not found it is ignored
func (t *Table) SetRows(values []map[string]interface{}) {
// Add missing rows
if len(values) > len(t.rows) {
count := len(values) - len(t.rows)
for row := 0; row < count; row++ {
t.insertRow(len(t.rows), nil)
}
// Remove remaining rows
} else if len(values) < len(t.rows) {
for row := len(values); row < len(t.rows); row++ {
t.removeRow(row)
}
}
// Set rows values
for row := 0; row < len(values); row++ {
t.setRow(row, values[row])
}
t.firstRow = 0
t.rowCursor = -1
t.recalc()
}
// SetRow sets the value of all the cells of the specified row from
// the specified map indexed by column id.
func (t *Table) SetRow(row int, values map[string]interface{}) {
if row < 0 || row >= len(t.rows) {
panic(tableErrInvRow)
}
t.setRow(row, values)
t.recalc()
}
// SetCell sets the value of the cell specified by its row and column id
// The function panics if the passed row or column id is invalid
func (t *Table) SetCell(row int, colid string, value interface{}) {
if row < 0 || row >= len(t.rows) {
panic(tableErrInvRow)
}
if t.header.cmap[colid] == nil {
panic(tableErrInvCol)
}
t.setCell(row, colid, value)
t.recalc()
}
// SetColFormat sets the formatting string (Printf) for the specified column
// Update must be called to update the table.
func (t *Table) SetColFormat(id, format string) {
c := t.header.cmap[id]
if c == nil {
panic(tableErrInvCol)
}
c.format = format
}
// SetColOrder sets the exhibition order of the specified column.
// The previous column which has the specified order will have
// the original column order.
func (t *Table) SetColOrder(colid string, order int) {
// Checks column id
c := t.header.cmap[colid]
if c == nil {
panic(tableErrInvCol)
}
// Checks exhibition order
if order < 0 || order > len(t.header.cols) {
panic(tableErrInvRow)
}
// Find the exhibition order for the specified column
for ci := 0; ci < len(t.header.cols); ci++ {
if t.header.cols[ci] == c {
// If the order of the specified column is the same, nothing to do
if ci == order {
return
}
// Swap column orders
prev := t.header.cols[order]
t.header.cols[order] = c
t.header.cols[ci] = prev
break
}
}
// Recalculates the header and all rows
t.recalc()
}
// EnableColResize enable or disables if the specified column can be resized by the
// user using the mouse.
func (t *Table) EnableColResize(colid string, enable bool) {
// Checks column id
c := t.header.cmap[colid]
if c == nil {
panic(tableErrInvCol)
}
c.resize = enable
}
// SetColWidth sets the specified column width and may
// change the widths of the columns to the right
func (t *Table) SetColWidth(colid string, width float32) {
// Checks column id
c := t.header.cmap[colid]
if c == nil {
panic(tableErrInvCol)
}
t.setColWidth(c, width)
}
// SetColExpand sets the column expand factor.
// When the table width is increased the columns widths are
// increased proportionally to their expand factor.
// A column with expand factor = 0 is not increased.
func (t *Table) SetColExpand(colid string, expand float32) {
// Checks column id
c := t.header.cmap[colid]
if c == nil {
panic(tableErrInvCol)
}
if expand < 0 {
c.expand = 0
} else {
c.expand = expand
}
t.recalc()
}
// AddRow adds a new row at the end of the table with the specified values
func (t *Table) AddRow(values map[string]interface{}) {
t.InsertRow(len(t.rows), values)
}
// InsertRow inserts the specified values in a new row at the specified index
func (t *Table) InsertRow(row int, values map[string]interface{}) {
// Checks row index
if row < 0 || row > len(t.rows) {
panic(tableErrInvRow)
}
t.insertRow(row, values)
t.recalc()
t.Dispatch(OnTableRowCount, nil)
}
// RemoveRow removes from the specified row from the table
func (t *Table) RemoveRow(row int) {
// Checks row index
if row < 0 || row >= len(t.rows) {
panic(tableErrInvRow)
}
t.removeRow(row)
maxFirst := t.calcMaxFirst()
if t.firstRow > maxFirst {
t.firstRow = maxFirst
}
t.recalc()
t.Dispatch(OnTableRowCount, nil)
}
// Clear removes all rows from the table
func (t *Table) Clear() {
for ri := 0; ri < len(t.rows); ri++ {
trow := t.rows[ri]
t.Panel.Remove(trow)
trow.DisposeChildren(true)
trow.Dispose()
}
t.rows = nil
t.firstRow = 0
t.rowCursor = -1
t.recalc()
t.Dispatch(OnTableRowCount, nil)
}
// SelectedRows returns a slice with the indexes of the currently selected rows
// If no row are selected returns an empty slice
func (t *Table) SelectedRows() []int {
res := make([]int, 0)
if t.rowCursor >= 0 {
res = append(res, t.rowCursor)
}
for ri := 0; ri < len(t.rows); ri++ {
if t.rows[ri].selected && ri != t.rowCursor {
res = append(res, ri)
}
}
return res
}
// ShowStatus sets the visibility of the status lines at the bottom of the table
func (t *Table) ShowStatus(show bool) {
if t.statusPanel.Visible() == show {
return
}
t.statusPanel.SetVisible(show)
t.recalcStatus()
t.recalc()
}
// SetStatusText sets the text of status line at the bottom of the table
// It does not change its current visibility
func (t *Table) SetStatusText(text string) {
t.statusLabel.SetText(text)
}
// Rows returns a slice of maps with the contents of the table rows
// specified by the rows first and last index.
// To get all the table rows, use Rows(0, -1)
func (t *Table) Rows(fi, li int) []map[string]interface{} {
if fi < 0 || fi >= len(t.header.cols) {
panic(tableErrInvRow)
}
if li < 0 {
li = len(t.rows) - 1
} else if li < 0 || li >= len(t.rows) {
panic(tableErrInvRow)
}
if li < fi {
panic("Last index less than first index")
}
res := make([]map[string]interface{}, li-li+1)
for ri := fi; ri <= li; ri++ {
trow := t.rows[ri]
rmap := make(map[string]interface{})
for ci := 0; ci < len(t.header.cols); ci++ {
c := t.header.cols[ci]
rmap[c.id] = trow.cells[c.order].value
}
res = append(res, rmap)
}
return res
}
// Row returns a map with the current contents of the specified row index
func (t *Table) Row(ri int) map[string]interface{} {
if ri < 0 || ri > len(t.header.cols) {
panic(tableErrInvRow)
}
res := make(map[string]interface{})
trow := t.rows[ri]
for ci := 0; ci < len(t.header.cols); ci++ {
c := t.header.cols[ci]
res[c.id] = trow.cells[c.order].value
}
return res
}
// Cell returns the current content of the specified cell
func (t *Table) Cell(col string, ri int) interface{} {
c := t.header.cmap[col]
if c == nil {
panic(tableErrInvCol)
}
if ri < 0 || ri >= len(t.rows) {
panic(tableErrInvRow)
}
trow := t.rows[ri]
return trow.cells[c.order].value
}
// SortColumn sorts the specified column interpreting its values as strings or numbers
// and sorting in ascending or descending order.
// This sorting is independent of the sort configuration of column set when the table was created
func (t *Table) SortColumn(col string, asString bool, asc bool) {
c := t.header.cmap[col]
if c == nil {
panic(tableErrInvCol)
}
if len(t.rows) < 2 {
return
}
if asString {
ts := tableSortString{rows: t.rows, col: c.order, asc: asc, format: c.format}
sort.Sort(ts)
} else {
ts := tableSortNumber{rows: t.rows, col: c.order, asc: asc}
sort.Sort(ts)
}
t.recalc()
}
// setRow sets the value of all the cells of the specified row from
// the specified map indexed by column id.
func (t *Table) setRow(row int, values map[string]interface{}) {
for ci := 0; ci < len(t.header.cols); ci++ {
c := t.header.cols[ci]
cv, ok := values[c.id]
if !ok {
continue
}
t.setCell(row, c.id, cv)
}
}
// setCell sets the value of the cell specified by its row and column id
func (t *Table) setCell(row int, colid string, value interface{}) {
c := t.header.cmap[colid]
if c == nil {
return
}
cell := t.rows[row].cells[c.order]
cell.label.SetText(fmt.Sprintf(c.format, value))
cell.value = value
}
// insertRow is the internal version of InsertRow which does not call recalc()
func (t *Table) insertRow(row int, values map[string]interface{}) {
// Creates tableRow panel
trow := new(tableRow)
trow.Initialize(0, 0)
trow.cells = make([]*tableCell, 0)
for ci := 0; ci < len(t.header.cols); ci++ {
// Creates tableRow cell panel
cell := new(tableCell)
cell.Initialize(0, 0)
cell.label.initialize("", StyleDefault().Font)
cell.Add(&cell.label)
trow.cells = append(trow.cells, cell)
trow.Panel.Add(cell)
}
t.Panel.Add(trow)
// Inserts tableRow in the table rows at the specified index
t.rows = append(t.rows, nil)
copy(t.rows[row+1:], t.rows[row:])
t.rows[row] = trow
t.updateRowStyle(row)
// Sets the new row values from the specified map
if values != nil {
t.SetRow(row, values)
}
t.recalcRow(row)
}
// ScrollDown scrolls the table the specified number of rows down if possible
func (t *Table) scrollDown(n int) {
// Calculates number of rows to scroll down
maxFirst := t.calcMaxFirst()
maxScroll := maxFirst - t.firstRow
if maxScroll <= 0 {
return
}
if n > maxScroll {
n = maxScroll
}
t.firstRow += n
if t.rowCursor < t.firstRow {
t.rowCursor = t.firstRow
t.Dispatch(OnChange, nil)
}
t.recalc()
return
}
// ScrollUp scrolls the table the specified number of rows up if possible
func (t *Table) scrollUp(n int) {
// Calculates number of rows to scroll up
if t.firstRow == 0 {
return
}
if n > t.firstRow {
n = t.firstRow
}
t.firstRow -= n
lastRow := t.lastRow - n
if t.rowCursor > lastRow {
t.rowCursor = lastRow
t.Dispatch(OnChange, nil)
}
t.recalc()
}
// removeRow removes from the table the row specified its index
func (t *Table) removeRow(row int) {
// Get row to be removed
trow := t.rows[row]
// Remove row from table children
t.Panel.Remove(trow)
// Remove row from rows array
copy(t.rows[row:], t.rows[row+1:])
t.rows[len(t.rows)-1] = nil
t.rows = t.rows[:len(t.rows)-1]
// Dispose row resources
trow.DisposeChildren(true)
trow.Dispose()
}
// onCursor process subscribed cursor events
func (t *Table) onCursor(evname string, ev interface{}) {
switch evname {
case OnCursorEnter:
t.root.SetScrollFocus(t)
case OnCursorLeave:
t.root.SetScrollFocus(nil)
}
t.root.StopPropagation(Stop3D)
}
// onCursorPos process subscribed cursor position events
func (t *Table) onCursorPos(evname string, ev interface{}) {
// Convert mouse window coordinates to table content coordinates
cev := ev.(*window.CursorEvent)
cx, _ := t.ContentCoords(cev.Xpos, cev.Ypos)
// If user is dragging the resizer, updates its position
if t.resizing {
t.resizerPanel.SetPosition(cx, 0)
return
}
// Checks if the mouse cursor is near the border of a resizable column
found := false
for ci := 0; ci < len(t.header.cols); ci++ {
c := t.header.cols[ci]
dx := math32.Abs(cx - c.xr)
if dx < tableResizerPix {
if c.resize {
found = true
t.resizeCol = ci
t.resizerX = c.xr
t.root.SetCursorHResize()
}
break
}
}
// If column not found but previously was near a resizable column,
// resets the the window cursor.
if !found && t.resizeCol >= 0 {
t.root.SetCursorNormal()
t.resizeCol = -1
}
t.root.StopPropagation(Stop3D)
}
// onMouseEvent process subscribed mouse events
func (t *Table) onMouse(evname string, ev interface{}) {
e := ev.(*window.MouseEvent)
t.root.SetKeyFocus(t)
switch evname {
case OnMouseDown:
// If over a resizable column border, shows the resizer panel
if t.resizeCol >= 0 && e.Button == window.MouseButtonLeft {
t.resizing = true
height := t.ContentHeight()
if t.statusPanel.Visible() {
height -= t.statusPanel.Height()
}
px := t.resizerX - t.resizerPanel.Width()/2
t.resizerPanel.SetPositionX(px)
t.resizerPanel.SetHeight(height)
t.resizerPanel.SetVisible(true)
t.SetTopChild(&t.resizerPanel)
return
}
// Find click position
var tce TableClickEvent
tce.MouseEvent = *e
t.findClick(&tce)
// If row is clicked, selects it
if tce.Row >= 0 && e.Button == window.MouseButtonLeft {
t.rowCursor = tce.Row
if t.selType == TableSelMultiRow && e.Mods == window.ModControl {
t.toggleRowSel(t.rowCursor)
}
t.recalc()
t.Dispatch(OnChange, nil)
}
// Creates and dispatch TableClickEvent for user's context menu
t.Dispatch(OnTableClick, tce)
case OnMouseUp:
// If user was resizing a column, hides the resizer and
// sets the new column width if possible
if t.resizing {
t.resizing = false
t.resizerPanel.SetVisible(false)
t.root.SetCursorNormal()
// Calculates the new column width
cx, _ := t.ContentCoords(e.Xpos, e.Ypos)
c := t.header.cols[t.resizeCol]
width := cx - c.xl
t.setColWidth(c, width)
}
default:
return
}
t.root.StopPropagation(StopAll)
}
// onKeyEvent receives subscribed key events for this table
func (t *Table) onKey(evname string, ev interface{}) {
kev := ev.(*window.KeyEvent)
if kev.Keycode == window.KeyUp && kev.Mods == 0 {
t.selPrev()
} else if kev.Keycode == window.KeyDown && kev.Mods == 0 {
t.selNext()
} else if kev.Keycode == window.KeyPageUp && kev.Mods == 0 {
t.prevPage()
} else if kev.Keycode == window.KeyPageDown && kev.Mods == 0 {
t.nextPage()
} else if kev.Keycode == window.KeyPageUp && kev.Mods == window.ModControl {
t.firstPage()
} else if kev.Keycode == window.KeyPageDown && kev.Mods == window.ModControl {
t.lastPage()
} else if kev.Keycode == window.KeyEnter && kev.Mods == window.ModControl {
if t.selType == TableSelMultiRow {
t.toggleRowSel(t.rowCursor)
}
}
}
// onResize receives subscribed resize events for this table
func (t *Table) onResize(evname string, ev interface{}) {
t.recalc()
t.recalcStatus()
}
// onScroll receives subscribed scroll events for this table
func (t *Table) onScroll(evname string, ev interface{}) {
sev := ev.(*window.ScrollEvent)
if sev.Yoffset > 0 {
t.scrollUp(1)
} else if sev.Yoffset < 0 {
t.scrollDown(1)
}
t.root.StopPropagation(Stop3D)
}
// onRicon receives subscribed events for column header right icon
func (t *Table) onRicon(evname string, c *tableColHeader) {
icon := tableSortedNoneIcon
var asc bool
if c.sorted == tableSortedNone || c.sorted == tableSortedDesc {
c.sorted = tableSortedAsc
icon = tableSortedAscIcon
asc = false
} else {
c.sorted = tableSortedDesc
icon = tableSortedDescIcon
asc = true
}
var asString bool
if c.sort == TableSortString {
asString = true
} else {
asString = false
}
t.SortColumn(c.id, asString, asc)
c.ricon.SetText(string(icon))
}
// findClick finds where in the table the specified mouse click event
// occurred updating the specified TableClickEvent with the click coordinates.
func (t *Table) findClick(ev *TableClickEvent) {
x, y := t.ContentCoords(ev.Xpos, ev.Ypos)
ev.X = x
ev.Y = y
ev.Row = -1
// Find column id
colx := float32(0)
for ci := 0; ci < len(t.header.cols); ci++ {
c := t.header.cols[ci]
if !c.Visible() {
continue
}
colx += t.header.cols[ci].Width()
if x < colx {
ev.Col = c.id
ev.ColOrder = ci
break
}
}
// If column not found the user clicked at the right of rows
if ev.Col == "" {
return
}
// Checks if is in header
if t.header.Visible() && y < t.header.Height() {
ev.Header = true
}
// Find row clicked
rowy := float32(0)
if t.header.Visible() {
rowy = t.header.Height()
}
theight := t.ContentHeight()
for ri := t.firstRow; ri < len(t.rows); ri++ {
trow := t.rows[ri]
rowy += trow.height
if rowy > theight {
break
}
if y < rowy {
ev.Row = ri
break
}
}