/
GridConnector.java
916 lines (784 loc) · 31.6 KB
/
GridConnector.java
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
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.client.connectors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ConnectorHierarchyChangeEvent;
import com.vaadin.client.annotations.OnStateChange;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.connectors.RpcDataSourceConnector.RpcDataSource;
import com.vaadin.client.data.DataSource.RowHandle;
import com.vaadin.client.renderers.Renderer;
import com.vaadin.client.ui.AbstractFieldConnector;
import com.vaadin.client.ui.AbstractHasComponentsConnector;
import com.vaadin.client.ui.SimpleManagedLayout;
import com.vaadin.client.widget.grid.CellReference;
import com.vaadin.client.widget.grid.CellStyleGenerator;
import com.vaadin.client.widget.grid.EditorHandler;
import com.vaadin.client.widget.grid.RowReference;
import com.vaadin.client.widget.grid.RowStyleGenerator;
import com.vaadin.client.widget.grid.events.SelectAllEvent;
import com.vaadin.client.widget.grid.events.SelectAllHandler;
import com.vaadin.client.widget.grid.selection.AbstractRowHandleSelectionModel;
import com.vaadin.client.widget.grid.selection.SelectionEvent;
import com.vaadin.client.widget.grid.selection.SelectionHandler;
import com.vaadin.client.widget.grid.selection.SelectionModelMulti;
import com.vaadin.client.widget.grid.selection.SelectionModelNone;
import com.vaadin.client.widget.grid.selection.SelectionModelSingle;
import com.vaadin.client.widget.grid.sort.SortEvent;
import com.vaadin.client.widget.grid.sort.SortHandler;
import com.vaadin.client.widget.grid.sort.SortOrder;
import com.vaadin.client.widgets.Grid;
import com.vaadin.client.widgets.Grid.Column;
import com.vaadin.client.widgets.Grid.FooterCell;
import com.vaadin.client.widgets.Grid.FooterRow;
import com.vaadin.client.widgets.Grid.HeaderCell;
import com.vaadin.client.widgets.Grid.HeaderRow;
import com.vaadin.shared.data.sort.SortDirection;
import com.vaadin.shared.ui.Connect;
import com.vaadin.shared.ui.grid.EditorClientRpc;
import com.vaadin.shared.ui.grid.EditorServerRpc;
import com.vaadin.shared.ui.grid.GridClientRpc;
import com.vaadin.shared.ui.grid.GridColumnState;
import com.vaadin.shared.ui.grid.GridServerRpc;
import com.vaadin.shared.ui.grid.GridState;
import com.vaadin.shared.ui.grid.GridState.SharedSelectionMode;
import com.vaadin.shared.ui.grid.GridStaticSectionState;
import com.vaadin.shared.ui.grid.GridStaticSectionState.CellState;
import com.vaadin.shared.ui.grid.GridStaticSectionState.RowState;
import com.vaadin.shared.ui.grid.ScrollDestination;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
/**
* Connects the client side {@link Grid} widget with the server side
* {@link com.vaadin.ui.components.grid.Grid} component.
* <p>
* The Grid is typed to JSONObject. The structure of the JSONObject is described
* at {@link com.vaadin.shared.data.DataProviderRpc#setRowData(int, List)
* DataProviderRpc.setRowData(int, List)}.
*
* @since 7.4
* @author Vaadin Ltd
*/
@Connect(com.vaadin.ui.Grid.class)
public class GridConnector extends AbstractHasComponentsConnector implements
SimpleManagedLayout {
private static final class CustomCellStyleGenerator implements
CellStyleGenerator<JsonObject> {
@Override
public String getStyle(CellReference<JsonObject> cellReference) {
JsonObject row = cellReference.getRow();
if (!row.hasKey(GridState.JSONKEY_CELLSTYLES)) {
return null;
}
Column<?, JsonObject> column = cellReference.getColumn();
if (!(column instanceof CustomGridColumn)) {
// Selection checkbox column
return null;
}
CustomGridColumn c = (CustomGridColumn) column;
JsonObject cellStylesObject = row
.getObject(GridState.JSONKEY_CELLSTYLES);
assert cellStylesObject != null;
if (cellStylesObject.hasKey(c.id)) {
return cellStylesObject.getString(c.id);
} else {
return null;
}
}
}
private static final class CustomRowStyleGenerator implements
RowStyleGenerator<JsonObject> {
@Override
public String getStyle(RowReference<JsonObject> rowReference) {
JsonObject row = rowReference.getRow();
if (row.hasKey(GridState.JSONKEY_ROWSTYLE)) {
return row.getString(GridState.JSONKEY_ROWSTYLE);
} else {
return null;
}
}
}
/**
* Custom implementation of the custom grid column using a JSONObject to
* represent the cell value and String as a column type.
*/
private class CustomGridColumn extends Grid.Column<Object, JsonObject> {
private final String id;
private AbstractRendererConnector<Object> rendererConnector;
private AbstractFieldConnector editorConnector;
public CustomGridColumn(String id,
AbstractRendererConnector<Object> rendererConnector) {
super(rendererConnector.getRenderer());
this.rendererConnector = rendererConnector;
this.id = id;
}
@Override
public Object getValue(final JsonObject obj) {
final JsonObject rowData = obj.getObject(GridState.JSONKEY_DATA);
assert rowData.hasKey(id) : "Could not find data for column with id "
+ id;
final JsonValue columnValue = rowData.get(id);
return rendererConnector.decode(columnValue);
}
/*
* Only used to check that the renderer connector will not change during
* the column lifetime.
*
* TODO remove once support for changing renderers is implemented
*/
private AbstractRendererConnector<Object> getRendererConnector() {
return rendererConnector;
}
private AbstractFieldConnector getEditorConnector() {
return editorConnector;
}
private void setEditorConnector(AbstractFieldConnector editorConnector) {
this.editorConnector = editorConnector;
}
}
/*
* An editor handler using Vaadin RPC to manage the editor state.
*/
private class CustomEditorHandler implements EditorHandler<JsonObject> {
private EditorServerRpc rpc = getRpcProxy(EditorServerRpc.class);
private EditorRequest<?> currentRequest = null;
private boolean serverInitiated = false;
public CustomEditorHandler() {
registerRpc(EditorClientRpc.class, new EditorClientRpc() {
@Override
public void bind(final int rowIndex) {
/*
* Because most shared state handling is deferred, we must
* defer this too to ensure the editorConnector references
* in shared state are up to date before opening the editor.
* Yes, this is a hack on top of a hack.
*/
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
serverInitiated = true;
GridConnector.this.getWidget().editRow(rowIndex);
}
});
}
@Override
public void cancel(int rowIndex) {
serverInitiated = true;
GridConnector.this.getWidget().cancelEditor();
}
@Override
public void confirmBind() {
/*
* See comment in bind()
*/
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
endRequest();
}
});
}
@Override
public void confirmSave() {
endRequest();
}
});
}
@Override
public void bind(EditorRequest<JsonObject> request) {
if (!handleServerInitiated(request)) {
startRequest(request);
rpc.bind(request.getRowIndex());
}
}
@Override
public void save(EditorRequest<JsonObject> request) {
if (!handleServerInitiated(request)) {
startRequest(request);
rpc.save(request.getRowIndex());
}
}
@Override
public void cancel(EditorRequest<JsonObject> request) {
if (!handleServerInitiated(request)) {
// No startRequest as we don't get (or need)
// a confirmation from the server
rpc.cancel(request.getRowIndex());
}
}
@Override
public Widget getWidget(Grid.Column<?, JsonObject> column) {
assert column != null;
if (column instanceof CustomGridColumn) {
AbstractFieldConnector c = ((CustomGridColumn) column)
.getEditorConnector();
return c != null ? c.getWidget() : null;
} else {
throw new IllegalStateException("Unexpected column type: "
+ column.getClass().getName());
}
}
/**
* Used to handle the case where the editor calls us because it was
* invoked by the server via RPC and not by the client. In that case,
* the request can be simply synchronously completed.
*
* @param request
* the request object
* @return true if the request was originally triggered by the server,
* false otherwise
*/
private boolean handleServerInitiated(EditorRequest<?> request) {
assert request != null : "Cannot handle null request";
assert currentRequest == null : "Earlier request not yet finished";
if (serverInitiated) {
serverInitiated = false;
return true;
} else {
return false;
}
}
private void startRequest(EditorRequest<?> request) {
currentRequest = request;
request.startAsync();
}
private void endRequest() {
assert currentRequest != null;
/*
* Clear current request first to ensure the state is valid if
* another request is made in the callback.
*/
EditorRequest<?> request = currentRequest;
currentRequest = null;
request.complete();
}
}
/**
* Maps a generated column id to a grid column instance
*/
private Map<String, CustomGridColumn> columnIdToColumn = new HashMap<String, CustomGridColumn>();
private AbstractRowHandleSelectionModel<JsonObject> selectionModel;
private Set<String> selectedKeys = new LinkedHashSet<String>();
private List<String> columnOrder = new ArrayList<String>();
/**
* updateFromState is set to true when {@link #updateSelectionFromState()}
* makes changes to selection. This flag tells the
* {@code internalSelectionChangeHandler} to not send same data straight
* back to server. Said listener sets it back to false when handling that
* event.
*/
private boolean updatedFromState = false;
private RpcDataSource dataSource;
private SelectionHandler<JsonObject> internalSelectionChangeHandler = new SelectionHandler<JsonObject>() {
@Override
public void onSelect(SelectionEvent<JsonObject> event) {
if (event.isBatchedSelection()) {
return;
}
if (!updatedFromState) {
for (JsonObject row : event.getRemoved()) {
selectedKeys.remove(dataSource.getRowKey(row));
}
for (JsonObject row : event.getAdded()) {
selectedKeys.add(dataSource.getRowKey(row));
}
getRpcProxy(GridServerRpc.class).select(
new ArrayList<String>(selectedKeys));
} else {
updatedFromState = false;
}
}
};
@Override
@SuppressWarnings("unchecked")
public Grid<JsonObject> getWidget() {
return (Grid<JsonObject>) super.getWidget();
}
@Override
public GridState getState() {
return (GridState) super.getState();
}
@Override
protected void init() {
super.init();
registerRpc(GridClientRpc.class, new GridClientRpc() {
@Override
public void scrollToStart() {
getWidget().scrollToStart();
}
@Override
public void scrollToEnd() {
getWidget().scrollToEnd();
}
@Override
public void scrollToRow(int row, ScrollDestination destination) {
getWidget().scrollToRow(row, destination);
}
});
getWidget().addSelectionHandler(internalSelectionChangeHandler);
getWidget().addSortHandler(new SortHandler<JsonObject>() {
@Override
public void sort(SortEvent<JsonObject> event) {
List<SortOrder> order = event.getOrder();
String[] columnIds = new String[order.size()];
SortDirection[] directions = new SortDirection[order.size()];
for (int i = 0; i < order.size(); i++) {
SortOrder sortOrder = order.get(i);
CustomGridColumn column = (CustomGridColumn) sortOrder
.getColumn();
columnIds[i] = column.id;
directions[i] = sortOrder.getDirection();
}
if (!Arrays.equals(columnIds, getState().sortColumns)
|| !Arrays.equals(directions, getState().sortDirs)) {
// Report back to server if changed
getRpcProxy(GridServerRpc.class).sort(columnIds,
directions, event.isUserOriginated());
}
}
});
getWidget().addSelectAllHandler(new SelectAllHandler<JsonObject>() {
@Override
public void onSelectAll(SelectAllEvent<JsonObject> event) {
getRpcProxy(GridServerRpc.class).selectAll();
}
});
getWidget().setEditorHandler(new CustomEditorHandler());
getLayoutManager().registerDependency(this, getWidget().getElement());
layout();
}
@Override
public void onStateChanged(final StateChangeEvent stateChangeEvent) {
super.onStateChanged(stateChangeEvent);
if (stateChangeEvent.hasPropertyChanged("selectionMode")) {
onSelectionModeChange();
}
if (stateChangeEvent.hasPropertyChanged("selectedKeys")) {
updateSelectionFromState();
}
/*
* The operations in here have been made deferred.
*
* The row data needed to react to column changes comes in the RPC
* calls. Since state is always updated before RPCs are called, we need
* to be sure that RPC is called before Grid reacts to state changes.
*
* Note that there are still some methods annotated with @OnStateChange
* that aren't deferred. That's okay, though.
*/
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
// Column updates
if (stateChangeEvent.hasPropertyChanged("columns")) {
// Remove old columns
purgeRemovedColumns();
// Add new columns
for (GridColumnState state : getState().columns) {
if (!columnIdToColumn.containsKey(state.id)) {
addColumnFromStateChangeEvent(state);
}
updateColumnFromState(columnIdToColumn.get(state.id),
state);
}
}
if (stateChangeEvent.hasPropertyChanged("columnOrder")) {
if (orderNeedsUpdate(getState().columnOrder)) {
updateColumnOrderFromState(getState().columnOrder);
}
}
if (stateChangeEvent.hasPropertyChanged("header")) {
updateHeaderFromState(getState().header);
}
if (stateChangeEvent.hasPropertyChanged("footer")) {
updateFooterFromState(getState().footer);
}
if (stateChangeEvent.hasPropertyChanged("editorEnabled")) {
getWidget().setEditorEnabled(getState().editorEnabled);
}
if (stateChangeEvent.hasPropertyChanged("frozenColumnCount")) {
getWidget().setFrozenColumnCount(
getState().frozenColumnCount);
}
}
});
}
private void updateColumnOrderFromState(List<String> stateColumnOrder) {
CustomGridColumn[] columns = new CustomGridColumn[stateColumnOrder
.size()];
int i = 0;
for (String id : stateColumnOrder) {
columns[i] = columnIdToColumn.get(id);
i++;
}
getWidget().setColumnOrder(columns);
columnOrder = stateColumnOrder;
}
private boolean orderNeedsUpdate(List<String> stateColumnOrder) {
if (stateColumnOrder.size() == columnOrder.size()) {
for (int i = 0; i < columnOrder.size(); ++i) {
if (!stateColumnOrder.get(i).equals(columnOrder.get(i))) {
return true;
}
}
return false;
}
return true;
}
private void updateHeaderFromState(GridStaticSectionState state) {
getWidget().setHeaderVisible(state.visible);
while (getWidget().getHeaderRowCount() > 0) {
getWidget().removeHeaderRow(0);
}
for (RowState rowState : state.rows) {
HeaderRow row = getWidget().appendHeaderRow();
for (CellState cellState : rowState.cells) {
CustomGridColumn column = columnIdToColumn
.get(cellState.columnId);
updateHeaderCellFromState(row.getCell(column), cellState);
}
for (Set<String> group : rowState.cellGroups.keySet()) {
Grid.Column<?, ?>[] columns = new Grid.Column<?, ?>[group
.size()];
CellState cellState = rowState.cellGroups.get(group);
int i = 0;
for (String columnId : group) {
columns[i] = columnIdToColumn.get(columnId);
i++;
}
// Set state to be the same as first in group.
updateHeaderCellFromState(row.join(columns), cellState);
}
if (rowState.defaultRow) {
getWidget().setDefaultHeaderRow(row);
}
row.setStyleName(rowState.styleName);
}
}
private void updateHeaderCellFromState(HeaderCell cell, CellState cellState) {
switch (cellState.type) {
case TEXT:
cell.setText(cellState.text);
break;
case HTML:
cell.setHtml(cellState.html);
break;
case WIDGET:
ComponentConnector connector = (ComponentConnector) cellState.connector;
cell.setWidget(connector.getWidget());
break;
default:
throw new IllegalStateException("unexpected cell type: "
+ cellState.type);
}
cell.setStyleName(cellState.styleName);
}
private void updateFooterFromState(GridStaticSectionState state) {
getWidget().setFooterVisible(state.visible);
while (getWidget().getFooterRowCount() > 0) {
getWidget().removeFooterRow(0);
}
for (RowState rowState : state.rows) {
FooterRow row = getWidget().appendFooterRow();
for (CellState cellState : rowState.cells) {
CustomGridColumn column = columnIdToColumn
.get(cellState.columnId);
updateFooterCellFromState(row.getCell(column), cellState);
}
for (Set<String> group : rowState.cellGroups.keySet()) {
Grid.Column<?, ?>[] columns = new Grid.Column<?, ?>[group
.size()];
CellState cellState = rowState.cellGroups.get(group);
int i = 0;
for (String columnId : group) {
columns[i] = columnIdToColumn.get(columnId);
i++;
}
// Set state to be the same as first in group.
updateFooterCellFromState(row.join(columns), cellState);
}
row.setStyleName(rowState.styleName);
}
}
private void updateFooterCellFromState(FooterCell cell, CellState cellState) {
switch (cellState.type) {
case TEXT:
cell.setText(cellState.text);
break;
case HTML:
cell.setHtml(cellState.html);
break;
case WIDGET:
ComponentConnector connector = (ComponentConnector) cellState.connector;
cell.setWidget(connector.getWidget());
break;
default:
throw new IllegalStateException("unexpected cell type: "
+ cellState.type);
}
cell.setStyleName(cellState.styleName);
}
/**
* Updates a column from a state change event.
*
* @param columnIndex
* The index of the column to update
*/
private void updateColumnFromStateChangeEvent(GridColumnState columnState) {
CustomGridColumn column = columnIdToColumn.get(columnState.id);
updateColumnFromState(column, columnState);
if (columnState.rendererConnector != column.getRendererConnector()) {
throw new UnsupportedOperationException(
"Changing column renderer after initialization is currently unsupported");
}
}
/**
* Adds a new column to the grid widget from a state change event
*
* @param columnIndex
* The index of the column, according to how it
*/
private void addColumnFromStateChangeEvent(GridColumnState state) {
@SuppressWarnings("unchecked")
CustomGridColumn column = new CustomGridColumn(state.id,
((AbstractRendererConnector<Object>) state.rendererConnector));
columnIdToColumn.put(state.id, column);
/*
* Add column to grid. Reordering is handled as a separate problem.
*/
getWidget().addColumn(column);
columnOrder.add(state.id);
}
/**
* If we have a selection column renderer, we need to offset the index by
* one when referring to the column index in the widget.
*/
private int getWidgetColumnIndex(final int columnIndex) {
Renderer<Boolean> selectionColumnRenderer = getWidget()
.getSelectionModel().getSelectionColumnRenderer();
int widgetColumnIndex = columnIndex;
if (selectionColumnRenderer != null) {
widgetColumnIndex++;
}
return widgetColumnIndex;
}
/**
* Updates the column values from a state
*
* @param column
* The column to update
* @param state
* The state to get the data from
*/
private static void updateColumnFromState(CustomGridColumn column,
GridColumnState state) {
column.setWidth(state.width);
column.setMinimumWidth(state.minWidth);
column.setMaximumWidth(state.maxWidth);
column.setExpandRatio(state.expandRatio);
column.setSortable(state.sortable);
column.setEditorConnector((AbstractFieldConnector) state.editorConnector);
}
/**
* Removes any orphan columns that has been removed from the state from the
* grid
*/
private void purgeRemovedColumns() {
// Get columns still registered in the state
Set<String> columnsInState = new HashSet<String>();
for (GridColumnState columnState : getState().columns) {
columnsInState.add(columnState.id);
}
// Remove column no longer in state
Iterator<String> columnIdIterator = columnIdToColumn.keySet()
.iterator();
while (columnIdIterator.hasNext()) {
String id = columnIdIterator.next();
if (!columnsInState.contains(id)) {
CustomGridColumn column = columnIdToColumn.get(id);
columnIdIterator.remove();
getWidget().removeColumn(column);
columnOrder.remove(id);
}
}
}
public void setDataSource(RpcDataSource dataSource) {
this.dataSource = dataSource;
getWidget().setDataSource(this.dataSource);
}
private void onSelectionModeChange() {
SharedSelectionMode mode = getState().selectionMode;
if (mode == null) {
getLogger().fine("ignored mode change");
return;
}
AbstractRowHandleSelectionModel<JsonObject> model = createSelectionModel(mode);
if (selectionModel == null
|| !model.getClass().equals(selectionModel.getClass())) {
selectionModel = model;
getWidget().setSelectionModel(model);
selectedKeys.clear();
}
}
@OnStateChange("hasCellStyleGenerator")
private void onCellStyleGeneratorChange() {
if (getState().hasCellStyleGenerator) {
getWidget().setCellStyleGenerator(new CustomCellStyleGenerator());
} else {
getWidget().setCellStyleGenerator(null);
}
}
@OnStateChange("hasRowStyleGenerator")
private void onRowStyleGeneratorChange() {
if (getState().hasRowStyleGenerator) {
getWidget().setRowStyleGenerator(new CustomRowStyleGenerator());
} else {
getWidget().setRowStyleGenerator(null);
}
}
private void updateSelectionFromState() {
boolean changed = false;
List<String> stateKeys = getState().selectedKeys;
// find new deselections
for (String key : selectedKeys) {
if (!stateKeys.contains(key)) {
changed = true;
deselectByHandle(dataSource.getHandleByKey(key));
}
}
// find new selections
for (String key : stateKeys) {
if (!selectedKeys.contains(key)) {
changed = true;
selectByHandle(dataSource.getHandleByKey(key));
}
}
/*
* A defensive copy in case the collection in the state is mutated
* instead of re-assigned.
*/
selectedKeys = new LinkedHashSet<String>(stateKeys);
/*
* We need to fire this event so that Grid is able to re-render the
* selection changes (if applicable).
*/
if (changed) {
// At least for now there's no way to send the selected and/or
// deselected row data. Some data is only stored as keys
updatedFromState = true;
getWidget().fireEvent(
new SelectionEvent<JsonObject>(getWidget(),
(List<JsonObject>) null, null, false));
}
}
@OnStateChange({ "sortColumns", "sortDirs" })
private void onSortStateChange() {
List<SortOrder> sortOrder = new ArrayList<SortOrder>();
String[] sortColumns = getState().sortColumns;
SortDirection[] sortDirs = getState().sortDirs;
for (int i = 0; i < sortColumns.length; i++) {
sortOrder.add(new SortOrder(columnIdToColumn.get(sortColumns[i]),
sortDirs[i]));
}
getWidget().setSortOrder(sortOrder);
}
private Logger getLogger() {
return Logger.getLogger(getClass().getName());
}
@SuppressWarnings("static-method")
private AbstractRowHandleSelectionModel<JsonObject> createSelectionModel(
SharedSelectionMode mode) {
switch (mode) {
case SINGLE:
return new SelectionModelSingle<JsonObject>();
case MULTI:
return new SelectionModelMulti<JsonObject>();
case NONE:
return new SelectionModelNone<JsonObject>();
default:
throw new IllegalStateException("unexpected mode value: " + mode);
}
}
/**
* A workaround method for accessing the protected method
* {@code AbstractRowHandleSelectionModel.selectByHandle}
*/
private native void selectByHandle(RowHandle<JsonObject> handle)
/*-{
var model = this.@com.vaadin.client.connectors.GridConnector::selectionModel;
model.@com.vaadin.client.widget.grid.selection.AbstractRowHandleSelectionModel::selectByHandle(*)(handle);
}-*/;
/**
* A workaround method for accessing the protected method
* {@code AbstractRowHandleSelectionModel.deselectByHandle}
*/
private native void deselectByHandle(RowHandle<JsonObject> handle)
/*-{
var model = this.@com.vaadin.client.connectors.GridConnector::selectionModel;
model.@com.vaadin.client.widget.grid.selection.AbstractRowHandleSelectionModel::deselectByHandle(*)(handle);
}-*/;
/**
* Gets the row key for a row object.
*
* @param row
* the row object
* @return the key for the given row
*/
public String getRowKey(JsonObject row) {
final Object key = dataSource.getRowKey(row);
assert key instanceof String : "Internal key was not a String but a "
+ key.getClass().getSimpleName() + " (" + key + ")";
return (String) key;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.client.HasComponentsConnector#updateCaption(com.vaadin.client
* .ComponentConnector)
*/
@Override
public void updateCaption(ComponentConnector connector) {
// TODO Auto-generated method stub
}
@Override
public void onConnectorHierarchyChange(
ConnectorHierarchyChangeEvent connectorHierarchyChangeEvent) {
}
public String getColumnId(Grid.Column<?, JsonObject> column) {
if (column instanceof CustomGridColumn) {
return ((CustomGridColumn) column).id;
}
return null;
}
@Override
public void layout() {
getWidget().onResize();
}
}