aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/com/vaadin/ui/AbstractSelect.java
blob: ac80dfbb74ac022eb108fe320f1977b93d3bfd4b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
/*
 *  * Copyright 2011 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.ui;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.event.DataBoundTransferable;
import com.vaadin.event.Transferable;
import com.vaadin.event.dd.DragAndDropEvent;
import com.vaadin.event.dd.DropTarget;
import com.vaadin.event.dd.TargetDetailsImpl;
import com.vaadin.event.dd.acceptcriteria.ClientSideCriterion;
import com.vaadin.event.dd.acceptcriteria.ContainsDataFlavor;
import com.vaadin.event.dd.acceptcriteria.TargetDetailIs;
import com.vaadin.server.KeyMapper;
import com.vaadin.server.PaintException;
import com.vaadin.server.PaintTarget;
import com.vaadin.server.Resource;
import com.vaadin.shared.ui.combobox.FilteringMode;
import com.vaadin.shared.ui.dd.VerticalDropLocation;

/**
 * <p>
 * A class representing a selection of items the user has selected in a UI. The
 * set of choices is presented as a set of {@link com.vaadin.data.Item}s in a
 * {@link com.vaadin.data.Container}.
 * </p>
 * 
 * <p>
 * A <code>Select</code> component may be in single- or multiselect mode.
 * Multiselect mode means that more than one item can be selected
 * simultaneously.
 * </p>
 * 
 * @author Vaadin Ltd.
 * @since 5.0
 */
@SuppressWarnings("serial")
// TODO currently cannot specify type more precisely in case of multi-select
public abstract class AbstractSelect extends AbstractField<Object> implements
        Container, Container.Viewer, Container.PropertySetChangeListener,
        Container.PropertySetChangeNotifier, Container.ItemSetChangeNotifier,
        Container.ItemSetChangeListener, LegacyComponent {

    public enum ItemCaptionMode {
        /**
         * Item caption mode: Item's ID's <code>String</code> representation is
         * used as caption.
         */
        ID,
        /**
         * Item caption mode: Item's <code>String</code> representation is used
         * as caption.
         */
        ITEM,
        /**
         * Item caption mode: Index of the item is used as caption. The index
         * mode can only be used with the containers implementing the
         * {@link com.vaadin.data.Container.Indexed} interface.
         */
        INDEX,
        /**
         * Item caption mode: If an Item has a caption it's used, if not, Item's
         * ID's <code>String</code> representation is used as caption. <b>This
         * is the default</b>.
         */
        EXPLICIT_DEFAULTS_ID,
        /**
         * Item caption mode: Captions must be explicitly specified.
         */
        EXPLICIT,
        /**
         * Item caption mode: Only icons are shown, captions are hidden.
         */
        ICON_ONLY,
        /**
         * Item caption mode: Item captions are read from property specified
         * with <code>setItemCaptionPropertyId</code>.
         */
        PROPERTY;
    }

    /**
     * @deprecated As of 7.0, use {@link ItemCaptionMode#ID} instead
     */
    @Deprecated
    public static final ItemCaptionMode ITEM_CAPTION_MODE_ID = ItemCaptionMode.ID;

    /**
     * @deprecated As of 7.0, use {@link ItemCaptionMode#ITEM} instead
     */
    @Deprecated
    public static final ItemCaptionMode ITEM_CAPTION_MODE_ITEM = ItemCaptionMode.ITEM;

    /**
     * @deprecated As of 7.0, use {@link ItemCaptionMode#INDEX} instead
     */
    @Deprecated
    public static final ItemCaptionMode ITEM_CAPTION_MODE_INDEX = ItemCaptionMode.INDEX;

    /**
     * @deprecated As of 7.0, use {@link ItemCaptionMode#EXPLICIT_DEFAULTS_ID}
     *             instead
     */
    @Deprecated
    public static final ItemCaptionMode ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID = ItemCaptionMode.EXPLICIT_DEFAULTS_ID;

    /**
     * @deprecated As of 7.0, use {@link ItemCaptionMode#EXPLICIT} instead
     */
    @Deprecated
    public static final ItemCaptionMode ITEM_CAPTION_MODE_EXPLICIT = ItemCaptionMode.EXPLICIT;

    /**
     * @deprecated As of 7.0, use {@link ItemCaptionMode#ICON_ONLY} instead
     */
    @Deprecated
    public static final ItemCaptionMode ITEM_CAPTION_MODE_ICON_ONLY = ItemCaptionMode.ICON_ONLY;

    /**
     * @deprecated As of 7.0, use {@link ItemCaptionMode#PROPERTY} instead
     */
    @Deprecated
    public static final ItemCaptionMode ITEM_CAPTION_MODE_PROPERTY = ItemCaptionMode.PROPERTY;

    /**
     * Interface for option filtering, used to filter options based on user
     * entered value. The value is matched to the item caption.
     * <code>FilteringMode.OFF</code> (0) turns the filtering off.
     * <code>FilteringMode.STARTSWITH</code> (1) matches from the start of the
     * caption. <code>FilteringMode.CONTAINS</code> (1) matches anywhere in the
     * caption.
     */
    public interface Filtering extends Serializable {

        /**
         * @deprecated As of 7.0, use {@link FilteringMode#OFF} instead
         */
        @Deprecated
        public static final FilteringMode FILTERINGMODE_OFF = FilteringMode.OFF;
        /**
         * @deprecated As of 7.0, use {@link FilteringMode#STARTSWITH} instead
         */
        @Deprecated
        public static final FilteringMode FILTERINGMODE_STARTSWITH = FilteringMode.STARTSWITH;
        /**
         * @deprecated As of 7.0, use {@link FilteringMode#CONTAINS} instead
         */
        @Deprecated
        public static final FilteringMode FILTERINGMODE_CONTAINS = FilteringMode.CONTAINS;

        /**
         * Sets the option filtering mode.
         * 
         * @param filteringMode
         *            the filtering mode to use
         */
        public void setFilteringMode(FilteringMode filteringMode);

        /**
         * Gets the current filtering mode.
         * 
         * @return the filtering mode in use
         */
        public FilteringMode getFilteringMode();

    }

    /**
     * Is the select in multiselect mode?
     */
    private boolean multiSelect = false;

    /**
     * Select options.
     */
    protected Container items;

    /**
     * Is the user allowed to add new options?
     */
    private boolean allowNewOptions;

    /**
     * Keymapper used to map key values.
     */
    protected KeyMapper<Object> itemIdMapper = new KeyMapper<Object>();

    /**
     * Item icons.
     */
    private final HashMap<Object, Resource> itemIcons = new HashMap<Object, Resource>();

    /**
     * Item captions.
     */
    private final HashMap<Object, String> itemCaptions = new HashMap<Object, String>();

    /**
     * Item caption mode.
     */
    private ItemCaptionMode itemCaptionMode = ItemCaptionMode.EXPLICIT_DEFAULTS_ID;

    /**
     * Item caption source property id.
     */
    private Object itemCaptionPropertyId = null;

    /**
     * Item icon source property id.
     */
    private Object itemIconPropertyId = null;

    /**
     * List of property set change event listeners.
     */
    private Set<Container.PropertySetChangeListener> propertySetEventListeners = null;

    /**
     * List of item set change event listeners.
     */
    private Set<Container.ItemSetChangeListener> itemSetEventListeners = null;

    /**
     * Item id that represents null selection of this select.
     * 
     * <p>
     * Data interface does not support nulls as item ids. Selecting the item
     * identified by this id is the same as selecting no items at all. This
     * setting only affects the single select mode.
     * </p>
     */
    private Object nullSelectionItemId = null;

    // Null (empty) selection is enabled by default
    private boolean nullSelectionAllowed = true;
    private NewItemHandler newItemHandler;

    // Caption (Item / Property) change listeners
    CaptionChangeListener captionChangeListener;

    /* Constructors */

    /**
     * Creates an empty Select. The caption is not used.
     */
    public AbstractSelect() {
        setContainerDataSource(new IndexedContainer());
    }

    /**
     * Creates an empty Select with caption.
     */
    public AbstractSelect(String caption) {
        setContainerDataSource(new IndexedContainer());
        setCaption(caption);
    }

    /**
     * Creates a new select that is connected to a data-source.
     * 
     * @param caption
     *            the Caption of the component.
     * @param dataSource
     *            the Container datasource to be selected from by this select.
     */
    public AbstractSelect(String caption, Container dataSource) {
        setCaption(caption);
        setContainerDataSource(dataSource);
    }

    /**
     * Creates a new select that is filled from a collection of option values.
     * 
     * @param caption
     *            the Caption of this field.
     * @param options
     *            the Collection containing the options.
     */
    public AbstractSelect(String caption, Collection<?> options) {

        // Creates the options container and add given options to it
        final Container c = new IndexedContainer();
        if (options != null) {
            for (final Iterator<?> i = options.iterator(); i.hasNext();) {
                c.addItem(i.next());
            }
        }

        setCaption(caption);
        setContainerDataSource(c);
    }

    /* Component methods */

    /**
     * Paints the content of this component.
     * 
     * @param target
     *            the Paint Event.
     * @throws PaintException
     *             if the paint operation failed.
     */
    @Override
    public void paintContent(PaintTarget target) throws PaintException {

        // Paints select attributes
        if (isMultiSelect()) {
            target.addAttribute("selectmode", "multi");
        }
        if (isNewItemsAllowed()) {
            target.addAttribute("allownewitem", true);
        }
        if (isNullSelectionAllowed()) {
            target.addAttribute("nullselect", true);
            if (getNullSelectionItemId() != null) {
                target.addAttribute("nullselectitem", true);
            }
        }

        // Constructs selected keys array
        String[] selectedKeys;
        if (isMultiSelect()) {
            selectedKeys = new String[((Set<?>) getValue()).size()];
        } else {
            selectedKeys = new String[(getValue() == null
                    && getNullSelectionItemId() == null ? 0 : 1)];
        }

        // ==
        // first remove all previous item/property listeners
        getCaptionChangeListener().clear();
        // Paints the options and create array of selected id keys

        target.startTag("options");
        int keyIndex = 0;
        // Support for external null selection item id
        final Collection<?> ids = getItemIds();
        if (isNullSelectionAllowed() && getNullSelectionItemId() != null
                && !ids.contains(getNullSelectionItemId())) {
            final Object id = getNullSelectionItemId();
            // Paints option
            target.startTag("so");
            paintItem(target, id);
            if (isSelected(id)) {
                selectedKeys[keyIndex++] = itemIdMapper.key(id);
            }
            target.endTag("so");
        }

        final Iterator<?> i = getItemIds().iterator();
        // Paints the available selection options from data source
        while (i.hasNext()) {
            // Gets the option attribute values
            final Object id = i.next();
            if (!isNullSelectionAllowed() && id != null
                    && id.equals(getNullSelectionItemId())) {
                // Remove item if it's the null selection item but null
                // selection is not allowed
                continue;
            }
            final String key = itemIdMapper.key(id);
            // add listener for each item, to cause repaint if an item changes
            getCaptionChangeListener().addNotifierForItem(id);
            target.startTag("so");
            paintItem(target, id);
            if (isSelected(id) && keyIndex < selectedKeys.length) {
                selectedKeys[keyIndex++] = key;
            }
            target.endTag("so");
        }
        target.endTag("options");
        // ==

        // Paint variables
        target.addVariable(this, "selected", selectedKeys);
        if (isNewItemsAllowed()) {
            target.addVariable(this, "newitem", "");
        }

    }

    protected void paintItem(PaintTarget target, Object itemId)
            throws PaintException {
        final String key = itemIdMapper.key(itemId);
        final String caption = getItemCaption(itemId);
        final Resource icon = getItemIcon(itemId);
        if (icon != null) {
            target.addAttribute("icon", icon);
        }
        target.addAttribute("caption", caption);
        if (itemId != null && itemId.equals(getNullSelectionItemId())) {
            target.addAttribute("nullselection", true);
        }
        target.addAttribute("key", key);
        if (isSelected(itemId)) {
            target.addAttribute("selected", true);
        }
    }

    /**
     * Invoked when the value of a variable has changed.
     * 
     * @see com.vaadin.ui.AbstractComponent#changeVariables(java.lang.Object,
     *      java.util.Map)
     */
    @Override
    public void changeVariables(Object source, Map<String, Object> variables) {

        // New option entered (and it is allowed)
        if (isNewItemsAllowed()) {
            final String newitem = (String) variables.get("newitem");
            if (newitem != null && newitem.length() > 0) {
                getNewItemHandler().addNewItem(newitem);
            }
        }

        // Selection change
        if (variables.containsKey("selected")) {
            final String[] clientSideSelectedKeys = (String[]) variables
                    .get("selected");

            // Multiselect mode
            if (isMultiSelect()) {

                // TODO Optimize by adding repaintNotNeeded when applicable

                // Converts the key-array to id-set
                final LinkedList<Object> acceptedSelections = new LinkedList<Object>();
                for (int i = 0; i < clientSideSelectedKeys.length; i++) {
                    final Object id = itemIdMapper
                            .get(clientSideSelectedKeys[i]);
                    if (!isNullSelectionAllowed()
                            && (id == null || id == getNullSelectionItemId())) {
                        // skip empty selection if nullselection is not allowed
                        markAsDirty();
                    } else if (id != null && containsId(id)) {
                        acceptedSelections.add(id);
                    }
                }

                if (!isNullSelectionAllowed() && acceptedSelections.size() < 1) {
                    // empty selection not allowed, keep old value
                    markAsDirty();
                    return;
                }

                // Limits the deselection to the set of visible items
                // (non-visible items can not be deselected)
                Collection<?> visibleNotSelected = getVisibleItemIds();
                if (visibleNotSelected != null) {
                    visibleNotSelected = new HashSet<Object>(visibleNotSelected);
                    // Don't remove those that will be added to preserve order
                    visibleNotSelected.removeAll(acceptedSelections);

                    @SuppressWarnings("unchecked")
                    Set<Object> newsel = (Set<Object>) getValue();
                    if (newsel == null) {
                        newsel = new LinkedHashSet<Object>();
                    } else {
                        newsel = new LinkedHashSet<Object>(newsel);
                    }
                    newsel.removeAll(visibleNotSelected);
                    newsel.addAll(acceptedSelections);
                    setValue(newsel, true);
                }
            } else {
                // Single select mode
                if (!isNullSelectionAllowed()
                        && (clientSideSelectedKeys.length == 0
                                || clientSideSelectedKeys[0] == null || clientSideSelectedKeys[0] == getNullSelectionItemId())) {
                    markAsDirty();
                    return;
                }
                if (clientSideSelectedKeys.length == 0) {
                    // Allows deselection only if the deselected item is
                    // visible
                    final Object current = getValue();
                    final Collection<?> visible = getVisibleItemIds();
                    if (visible != null && visible.contains(current)) {
                        setValue(null, true);
                    }
                } else {
                    final Object id = itemIdMapper
                            .get(clientSideSelectedKeys[0]);
                    if (!isNullSelectionAllowed() && id == null) {
                        markAsDirty();
                    } else if (id != null
                            && id.equals(getNullSelectionItemId())) {
                        setValue(null, true);
                    } else {
                        setValue(id, true);
                    }
                }
            }
        }
    }

    /**
     * TODO refine doc Setter for new item handler that is called when user adds
     * new item in newItemAllowed mode.
     * 
     * @param newItemHandler
     */
    public void setNewItemHandler(NewItemHandler newItemHandler) {
        this.newItemHandler = newItemHandler;
    }

    /**
     * TODO refine doc
     * 
     * @return
     */
    public NewItemHandler getNewItemHandler() {
        if (newItemHandler == null) {
            newItemHandler = new DefaultNewItemHandler();
        }
        return newItemHandler;
    }

    public interface NewItemHandler extends Serializable {
        void addNewItem(String newItemCaption);
    }

    /**
     * TODO refine doc
     * 
     * This is a default class that handles adding new items that are typed by
     * user to selects container.
     * 
     * By extending this class one may implement some logic on new item addition
     * like database inserts.
     * 
     */
    public class DefaultNewItemHandler implements NewItemHandler {
        @Override
        public void addNewItem(String newItemCaption) {
            // Checks for readonly
            if (isReadOnly()) {
                throw new Property.ReadOnlyException();
            }

            // Adds new option
            if (addItem(newItemCaption) != null) {

                // Sets the caption property, if used
                if (getItemCaptionPropertyId() != null) {
                    getContainerProperty(newItemCaption,
                            getItemCaptionPropertyId())
                            .setValue(newItemCaption);
                }
                if (isMultiSelect()) {
                    Set values = new HashSet((Collection) getValue());
                    values.add(newItemCaption);
                    setValue(values);
                } else {
                    setValue(newItemCaption);
                }
            }
        }
    }

    /**
     * Gets the visible item ids. In Select, this returns list of all item ids,
     * but can be overriden in subclasses if they paint only part of the items
     * to the terminal or null if no items is visible.
     */
    public Collection<?> getVisibleItemIds() {
        return getItemIds();
    }

    /* Property methods */

    /**
     * Returns the type of the property. <code>getValue</code> and
     * <code>setValue</code> methods must be compatible with this type: one can
     * safely cast <code>getValue</code> to given type and pass any variable
     * assignable to this type as a parameter to <code>setValue</code>.
     * 
     * @return the Type of the property.
     */
    @Override
    public Class<?> getType() {
        if (isMultiSelect()) {
            return Set.class;
        } else {
            return Object.class;
        }
    }

    /**
     * Gets the selected item id or in multiselect mode a set of selected ids.
     * 
     * @see com.vaadin.ui.AbstractField#getValue()
     */
    @Override
    public Object getValue() {
        final Object retValue = super.getValue();

        if (isMultiSelect()) {

            // If the return value is not a set
            if (retValue == null) {
                return new HashSet<Object>();
            }
            if (retValue instanceof Set) {
                return Collections.unmodifiableSet((Set<?>) retValue);
            } else if (retValue instanceof Collection) {
                return new HashSet<Object>((Collection<?>) retValue);
            } else {
                final Set<Object> s = new HashSet<Object>();
                if (items.containsId(retValue)) {
                    s.add(retValue);
                }
                return s;
            }

        } else {
            return retValue;
        }
    }

    /**
     * Sets the visible value of the property.
     * 
     * <p>
     * The value of the select is the selected item id. If the select is in
     * multiselect-mode, the value is a set of selected item keys. In
     * multiselect mode all collections of id:s can be assigned.
     * </p>
     * 
     * @param newValue
     *            the New selected item or collection of selected items.
     * @see com.vaadin.ui.AbstractField#setValue(java.lang.Object)
     */
    @Override
    public void setValue(Object newValue) throws Property.ReadOnlyException {
        if (newValue == getNullSelectionItemId()) {
            newValue = null;
        }

        setValue(newValue, false);
    }

    /**
     * Sets the visible value of the property.
     * 
     * <p>
     * The value of the select is the selected item id. If the select is in
     * multiselect-mode, the value is a set of selected item keys. In
     * multiselect mode all collections of id:s can be assigned.
     * </p>
     * 
     * @param newValue
     *            the New selected item or collection of selected items.
     * @param repaintIsNotNeeded
     *            True if caller is sure that repaint is not needed.
     * @see com.vaadin.ui.AbstractField#setValue(java.lang.Object,
     *      java.lang.Boolean)
     */
    @Override
    protected void setValue(Object newValue, boolean repaintIsNotNeeded)
            throws Property.ReadOnlyException {

        if (isMultiSelect()) {
            if (newValue == null) {
                super.setValue(new LinkedHashSet<Object>(), repaintIsNotNeeded);
            } else if (Collection.class.isAssignableFrom(newValue.getClass())) {
                super.setValue(new LinkedHashSet<Object>(
                        (Collection<?>) newValue), repaintIsNotNeeded);
            }
        } else if (newValue == null || items.containsId(newValue)) {
            super.setValue(newValue, repaintIsNotNeeded);
        }
    }

    /* Container methods */

    /**
     * Gets the item from the container with given id. If the container does not
     * contain the requested item, null is returned.
     * 
     * @param itemId
     *            the item id.
     * @return the item from the container.
     */
    @Override
    public Item getItem(Object itemId) {
        return items.getItem(itemId);
    }

    /**
     * Gets the item Id collection from the container.
     * 
     * @return the Collection of item ids.
     */
    @Override
    public Collection<?> getItemIds() {
        return items.getItemIds();
    }

    /**
     * Gets the property Id collection from the container.
     * 
     * @return the Collection of property ids.
     */
    @Override
    public Collection<?> getContainerPropertyIds() {
        return items.getContainerPropertyIds();
    }

    /**
     * Gets the property type.
     * 
     * @param propertyId
     *            the Id identifying the property.
     * @see com.vaadin.data.Container#getType(java.lang.Object)
     */
    @Override
    public Class<?> getType(Object propertyId) {
        return items.getType(propertyId);
    }

    /*
     * Gets the number of items in the container.
     * 
     * @return the Number of items in the container.
     * 
     * @see com.vaadin.data.Container#size()
     */
    @Override
    public int size() {
        return items.size();
    }

    /**
     * Tests, if the collection contains an item with given id.
     * 
     * @param itemId
     *            the Id the of item to be tested.
     */
    @Override
    public boolean containsId(Object itemId) {
        if (itemId != null) {
            return items.containsId(itemId);
        } else {
            return false;
        }
    }

    /**
     * Gets the Property identified by the given itemId and propertyId from the
     * Container
     * 
     * @see com.vaadin.data.Container#getContainerProperty(Object, Object)
     */
    @Override
    public Property getContainerProperty(Object itemId, Object propertyId) {
        return items.getContainerProperty(itemId, propertyId);
    }

    /**
     * Adds the new property to all items. Adds a property with given id, type
     * and default value to all items in the container.
     * 
     * This functionality is optional. If the function is unsupported, it always
     * returns false.
     * 
     * @return True if the operation succeeded.
     * @see com.vaadin.data.Container#addContainerProperty(java.lang.Object,
     *      java.lang.Class, java.lang.Object)
     */
    @Override
    public boolean addContainerProperty(Object propertyId, Class<?> type,
            Object defaultValue) throws UnsupportedOperationException {

        final boolean retval = items.addContainerProperty(propertyId, type,
                defaultValue);
        if (retval && !(items instanceof Container.PropertySetChangeNotifier)) {
            firePropertySetChange();
        }
        return retval;
    }

    /**
     * Removes all items from the container.
     * 
     * This functionality is optional. If the function is unsupported, it always
     * returns false.
     * 
     * @return True if the operation succeeded.
     * @see com.vaadin.data.Container#removeAllItems()
     */
    @Override
    public boolean removeAllItems() throws UnsupportedOperationException {

        final boolean retval = items.removeAllItems();
        itemIdMapper.removeAll();
        if (retval) {
            setValue(null);
            if (!(items instanceof Container.ItemSetChangeNotifier)) {
                fireItemSetChange();
            }
        }
        return retval;
    }

    /**
     * Creates a new item into container with container managed id. The id of
     * the created new item is returned. The item can be fetched with getItem()
     * method. if the creation fails, null is returned.
     * 
     * @return the Id of the created item or null in case of failure.
     * @see com.vaadin.data.Container#addItem()
     */
    @Override
    public Object addItem() throws UnsupportedOperationException {

        final Object retval = items.addItem();
        if (retval != null
                && !(items instanceof Container.ItemSetChangeNotifier)) {
            fireItemSetChange();
        }
        return retval;
    }

    /**
     * Create a new item into container. The created new item is returned and
     * ready for setting property values. if the creation fails, null is
     * returned. In case the container already contains the item, null is
     * returned.
     * 
     * This functionality is optional. If the function is unsupported, it always
     * returns null.
     * 
     * @param itemId
     *            the Identification of the item to be created.
     * @return the Created item with the given id, or null in case of failure.
     * @see com.vaadin.data.Container#addItem(java.lang.Object)
     */
    @Override
    public Item addItem(Object itemId) throws UnsupportedOperationException {

        final Item retval = items.addItem(itemId);
        if (retval != null
                && !(items instanceof Container.ItemSetChangeNotifier)) {
            fireItemSetChange();
        }
        return retval;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.vaadin.data.Container#removeItem(java.lang.Object)
     */
    @Override
    public boolean removeItem(Object itemId)
            throws UnsupportedOperationException {

        unselect(itemId);
        final boolean retval = items.removeItem(itemId);
        itemIdMapper.remove(itemId);
        if (retval && !(items instanceof Container.ItemSetChangeNotifier)) {
            fireItemSetChange();
        }
        return retval;
    }

    /**
     * Removes the property from all items. Removes a property with given id
     * from all the items in the container.
     * 
     * This functionality is optional. If the function is unsupported, it always
     * returns false.
     * 
     * @return True if the operation succeeded.
     * @see com.vaadin.data.Container#removeContainerProperty(java.lang.Object)
     */
    @Override
    public boolean removeContainerProperty(Object propertyId)
            throws UnsupportedOperationException {

        final boolean retval = items.removeContainerProperty(propertyId);
        if (retval && !(items instanceof Container.PropertySetChangeNotifier)) {
            firePropertySetChange();
        }
        return retval;
    }

    /* Container.Viewer methods */

    /**
     * Sets the Container that serves as the data source of the viewer.
     * 
     * As a side-effect the fields value (selection) is set to null due old
     * selection not necessary exists in new Container.
     * 
     * @see com.vaadin.data.Container.Viewer#setContainerDataSource(Container)
     * 
     * @param newDataSource
     *            the new data source.
     */
    @Override
    public void setContainerDataSource(Container newDataSource) {
        if (newDataSource == null) {
            newDataSource = new IndexedContainer();
        }

        getCaptionChangeListener().clear();

        if (items != newDataSource) {

            // Removes listeners from the old datasource
            if (items != null) {
                if (items instanceof Container.ItemSetChangeNotifier) {
                    ((Container.ItemSetChangeNotifier) items)
                            .removeListener(this);
                }
                if (items instanceof Container.PropertySetChangeNotifier) {
                    ((Container.PropertySetChangeNotifier) items)
                            .removeListener(this);
                }
            }

            // Assigns new data source
            items = newDataSource;

            // Clears itemIdMapper also
            itemIdMapper.removeAll();

            // Adds listeners
            if (items != null) {
                if (items instanceof Container.ItemSetChangeNotifier) {
                    ((Container.ItemSetChangeNotifier) items).addListener(this);
                }
                if (items instanceof Container.PropertySetChangeNotifier) {
                    ((Container.PropertySetChangeNotifier) items)
                            .addListener(this);
                }
            }

            /*
             * We expect changing the data source should also clean value. See
             * #810, #4607, #5281
             */
            setValue(null);

            markAsDirty();

        }
    }

    /**
     * Gets the viewing data-source container.
     * 
     * @see com.vaadin.data.Container.Viewer#getContainerDataSource()
     */
    @Override
    public Container getContainerDataSource() {
        return items;
    }

    /* Select attributes */

    /**
     * Is the select in multiselect mode? In multiselect mode
     * 
     * @return the Value of property multiSelect.
     */
    public boolean isMultiSelect() {
        return multiSelect;
    }

    /**
     * Sets the multiselect mode. Setting multiselect mode false may lose
     * selection information: if selected items set contains one or more
     * selected items, only one of the selected items is kept as selected.
     * 
     * Subclasses of AbstractSelect can choose not to support changing the
     * multiselect mode, and may throw {@link UnsupportedOperationException}.
     * 
     * @param multiSelect
     *            the New value of property multiSelect.
     */
    public void setMultiSelect(boolean multiSelect) {
        if (multiSelect && getNullSelectionItemId() != null) {
            throw new IllegalStateException(
                    "Multiselect and NullSelectionItemId can not be set at the same time.");
        }
        if (multiSelect != this.multiSelect) {

            // Selection before mode change
            final Object oldValue = getValue();

            this.multiSelect = multiSelect;

            // Convert the value type
            if (multiSelect) {
                final Set<Object> s = new HashSet<Object>();
                if (oldValue != null) {
                    s.add(oldValue);
                }
                setValue(s);
            } else {
                final Set<?> s = (Set<?>) oldValue;
                if (s == null || s.isEmpty()) {
                    setValue(null);
                } else {
                    // Set the single select to contain only the first
                    // selected value in the multiselect
                    setValue(s.iterator().next());
                }
            }

            markAsDirty();
        }
    }

    /**
     * Does the select allow adding new options by the user. If true, the new
     * options can be added to the Container. The text entered by the user is
     * used as id. Note that data-source must allow adding new items.
     * 
     * @return True if additions are allowed.
     */
    public boolean isNewItemsAllowed() {
        return allowNewOptions;
    }

    /**
     * Enables or disables possibility to add new options by the user.
     * 
     * @param allowNewOptions
     *            the New value of property allowNewOptions.
     */
    public void setNewItemsAllowed(boolean allowNewOptions) {

        // Only handle change requests
        if (this.allowNewOptions != allowNewOptions) {

            this.allowNewOptions = allowNewOptions;

            markAsDirty();
        }
    }

    /**
     * Override the caption of an item. Setting caption explicitly overrides id,
     * item and index captions.
     * 
     * @param itemId
     *            the id of the item to be recaptioned.
     * @param caption
     *            the New caption.
     */
    public void setItemCaption(Object itemId, String caption) {
        if (itemId != null) {
            itemCaptions.put(itemId, caption);
            markAsDirty();
        }
    }

    /**
     * Gets the caption of an item. The caption is generated as specified by the
     * item caption mode. See <code>setItemCaptionMode()</code> for more
     * details.
     * 
     * @param itemId
     *            the id of the item to be queried.
     * @return the caption for specified item.
     */
    public String getItemCaption(Object itemId) {

        // Null items can not be found
        if (itemId == null) {
            return null;
        }

        String caption = null;

        switch (getItemCaptionMode()) {

        case ID:
            caption = itemId.toString();
            break;

        case INDEX:
            if (items instanceof Container.Indexed) {
                caption = String.valueOf(((Container.Indexed) items)
                        .indexOfId(itemId));
            } else {
                caption = "ERROR: Container is not indexed";
            }
            break;

        case ITEM:
            final Item i = getItem(itemId);
            if (i != null) {
                caption = i.toString();
            }
            break;

        case EXPLICIT:
            caption = itemCaptions.get(itemId);
            break;

        case EXPLICIT_DEFAULTS_ID:
            caption = itemCaptions.get(itemId);
            if (caption == null) {
                caption = itemId.toString();
            }
            break;

        case PROPERTY:
            final Property<?> p = getContainerProperty(itemId,
                    getItemCaptionPropertyId());
            if (p != null) {
                Object value = p.getValue();
                if (value != null) {
                    caption = value.toString();
                }
            }
            break;
        }

        // All items must have some captions
        return caption != null ? caption : "";
    }

    /**
     * Sets tqhe icon for an item.
     * 
     * @param itemId
     *            the id of the item to be assigned an icon.
     * @param icon
     *            the icon to use or null.
     */
    public void setItemIcon(Object itemId, Resource icon) {
        if (itemId != null) {
            if (icon == null) {
                itemIcons.remove(itemId);
            } else {
                itemIcons.put(itemId, icon);
            }
            markAsDirty();
        }
    }

    /**
     * Gets the item icon.
     * 
     * @param itemId
     *            the id of the item to be assigned an icon.
     * @return the icon for the item or null, if not specified.
     */
    public Resource getItemIcon(Object itemId) {
        final Resource explicit = itemIcons.get(itemId);
        if (explicit != null) {
            return explicit;
        }

        if (getItemIconPropertyId() == null) {
            return null;
        }

        final Property<?> ip = getContainerProperty(itemId,
                getItemIconPropertyId());
        if (ip == null) {
            return null;
        }
        final Object icon = ip.getValue();
        if (icon instanceof Resource) {
            return (Resource) icon;
        }

        return null;
    }

    /**
     * Sets the item caption mode.
     * 
     * <p>
     * The mode can be one of the following ones:
     * <ul>
     * <li><code>ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID</code> : Items
     * Id-objects <code>toString</code> is used as item caption. If caption is
     * explicitly specified, it overrides the id-caption.
     * <li><code>ITEM_CAPTION_MODE_ID</code> : Items Id-objects
     * <code>toString</code> is used as item caption.</li>
     * <li><code>ITEM_CAPTION_MODE_ITEM</code> : Item-objects
     * <code>toString</code> is used as item caption.</li>
     * <li><code>ITEM_CAPTION_MODE_INDEX</code> : The index of the item is used
     * as item caption. The index mode can only be used with the containers
     * implementing <code>Container.Indexed</code> interface.</li>
     * <li><code>ITEM_CAPTION_MODE_EXPLICIT</code> : The item captions must be
     * explicitly specified.</li>
     * <li><code>ITEM_CAPTION_MODE_PROPERTY</code> : The item captions are read
     * from property, that must be specified with
     * <code>setItemCaptionPropertyId</code>.</li>
     * </ul>
     * The <code>ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID</code> is the default
     * mode.
     * </p>
     * 
     * @param mode
     *            the One of the modes listed above.
     */
    public void setItemCaptionMode(ItemCaptionMode mode) {
        if (mode != null) {
            itemCaptionMode = mode;
            markAsDirty();
        }
    }

    /**
     * Gets the item caption mode.
     * 
     * <p>
     * The mode can be one of the following ones:
     * <ul>
     * <li><code>ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID</code> : Items
     * Id-objects <code>toString</code> is used as item caption. If caption is
     * explicitly specified, it overrides the id-caption.
     * <li><code>ITEM_CAPTION_MODE_ID</code> : Items Id-objects
     * <code>toString</code> is used as item caption.</li>
     * <li><code>ITEM_CAPTION_MODE_ITEM</code> : Item-objects
     * <code>toString</code> is used as item caption.</li>
     * <li><code>ITEM_CAPTION_MODE_INDEX</code> : The index of the item is used
     * as item caption. The index mode can only be used with the containers
     * implementing <code>Container.Indexed</code> interface.</li>
     * <li><code>ITEM_CAPTION_MODE_EXPLICIT</code> : The item captions must be
     * explicitly specified.</li>
     * <li><code>ITEM_CAPTION_MODE_PROPERTY</code> : The item captions are read
     * from property, that must be specified with
     * <code>setItemCaptionPropertyId</code>.</li>
     * </ul>
     * The <code>ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID</code> is the default
     * mode.
     * </p>
     * 
     * @return the One of the modes listed above.
     */
    public ItemCaptionMode getItemCaptionMode() {
        return itemCaptionMode;
    }

    /**
     * Sets the item caption property.
     * 
     * <p>
     * Setting the id to a existing property implicitly sets the item caption
     * mode to <code>ITEM_CAPTION_MODE_PROPERTY</code>. If the object is in
     * <code>ITEM_CAPTION_MODE_PROPERTY</code> mode, setting caption property id
     * null resets the item caption mode to
     * <code>ITEM_CAPTION_EXPLICIT_DEFAULTS_ID</code>.
     * </p>
     * <p>
     * Note that the type of the property used for caption must be String
     * </p>
     * <p>
     * Setting the property id to null disables this feature. The id is null by
     * default
     * </p>
     * .
     * 
     * @param propertyId
     *            the id of the property.
     * 
     */
    public void setItemCaptionPropertyId(Object propertyId) {
        if (propertyId != null) {
            itemCaptionPropertyId = propertyId;
            setItemCaptionMode(ITEM_CAPTION_MODE_PROPERTY);
            markAsDirty();
        } else {
            itemCaptionPropertyId = null;
            if (getItemCaptionMode() == ITEM_CAPTION_MODE_PROPERTY) {
                setItemCaptionMode(ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID);
            }
            markAsDirty();
        }
    }

    /**
     * Gets the item caption property.
     * 
     * @return the Id of the property used as item caption source.
     */
    public Object getItemCaptionPropertyId() {
        return itemCaptionPropertyId;
    }

    /**
     * Sets the item icon property.
     * 
     * <p>
     * If the property id is set to a valid value, each item is given an icon
     * got from the given property of the items. The type of the property must
     * be assignable to Resource.
     * </p>
     * 
     * <p>
     * Note : The icons set with <code>setItemIcon</code> function override the
     * icons from the property.
     * </p>
     * 
     * <p>
     * Setting the property id to null disables this feature. The id is null by
     * default
     * </p>
     * .
     * 
     * @param propertyId
     *            the id of the property that specifies icons for items or null
     * @throws IllegalArgumentException
     *             If the propertyId is not in the container or is not of a
     *             valid type
     */
    public void setItemIconPropertyId(Object propertyId)
            throws IllegalArgumentException {
        if (propertyId == null) {
            itemIconPropertyId = null;
        } else if (!getContainerPropertyIds().contains(propertyId)) {
            throw new IllegalArgumentException(
                    "Property id not found in the container");
        } else if (Resource.class.isAssignableFrom(getType(propertyId))) {
            itemIconPropertyId = propertyId;
        } else {
            throw new IllegalArgumentException(
                    "Property type must be assignable to Resource");
        }
        markAsDirty();
    }

    /**
     * Gets the item icon property.
     * 
     * <p>
     * If the property id is set to a valid value, each item is given an icon
     * got from the given property of the items. The type of the property must
     * be assignable to Icon.
     * </p>
     * 
     * <p>
     * Note : The icons set with <code>setItemIcon</code> function override the
     * icons from the property.
     * </p>
     * 
     * <p>
     * Setting the property id to null disables this feature. The id is null by
     * default
     * </p>
     * .
     * 
     * @return the Id of the property containing the item icons.
     */
    public Object getItemIconPropertyId() {
        return itemIconPropertyId;
    }

    /**
     * Tests if an item is selected.
     * 
     * <p>
     * In single select mode testing selection status of the item identified by
     * {@link #getNullSelectionItemId()} returns true if the value of the
     * property is null.
     * </p>
     * 
     * @param itemId
     *            the Id the of the item to be tested.
     * @see #getNullSelectionItemId()
     * @see #setNullSelectionItemId(Object)
     * 
     */
    public boolean isSelected(Object itemId) {
        if (itemId == null) {
            return false;
        }
        if (isMultiSelect()) {
            return ((Set<?>) getValue()).contains(itemId);
        } else {
            final Object value = getValue();
            return itemId.equals(value == null ? getNullSelectionItemId()
                    : value);
        }
    }

    /**
     * Selects an item.
     * 
     * <p>
     * In single select mode selecting item identified by
     * {@link #getNullSelectionItemId()} sets the value of the property to null.
     * </p>
     * 
     * @param itemId
     *            the identifier of Item to be selected.
     * @see #getNullSelectionItemId()
     * @see #setNullSelectionItemId(Object)
     * 
     */
    public void select(Object itemId) {
        if (!isMultiSelect()) {
            setValue(itemId);
        } else if (!isSelected(itemId) && itemId != null
                && items.containsId(itemId)) {
            final Set<Object> s = new HashSet<Object>((Set<?>) getValue());
            s.add(itemId);
            setValue(s);
        }
    }

    /**
     * Unselects an item.
     * 
     * @param itemId
     *            the identifier of the Item to be unselected.
     * @see #getNullSelectionItemId()
     * @see #setNullSelectionItemId(Object)
     * 
     */
    public void unselect(Object itemId) {
        if (isSelected(itemId)) {
            if (isMultiSelect()) {
                final Set<Object> s = new HashSet<Object>((Set<?>) getValue());
                s.remove(itemId);
                setValue(s);
            } else {
                setValue(null);
            }
        }
    }

    /**
     * Notifies this listener that the Containers contents has changed.
     * 
     * @see com.vaadin.data.Container.PropertySetChangeListener#containerPropertySetChange(com.vaadin.data.Container.PropertySetChangeEvent)
     */
    @Override
    public void containerPropertySetChange(
            Container.PropertySetChangeEvent event) {
        firePropertySetChange();
    }

    /**
     * Adds a new Property set change listener for this Container.
     * 
     * @see com.vaadin.data.Container.PropertySetChangeNotifier#addListener(com.vaadin.data.Container.PropertySetChangeListener)
     */
    @Override
    public void addPropertySetChangeListener(
            Container.PropertySetChangeListener listener) {
        if (propertySetEventListeners == null) {
            propertySetEventListeners = new LinkedHashSet<Container.PropertySetChangeListener>();
        }
        propertySetEventListeners.add(listener);
    }

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #addPropertySetChangeListener(com.vaadin.data.Container.PropertySetChangeListener)}
     **/
    @Override
    @Deprecated
    public void addListener(Container.PropertySetChangeListener listener) {
        addPropertySetChangeListener(listener);
    }

    /**
     * Removes a previously registered Property set change listener.
     * 
     * @see com.vaadin.data.Container.PropertySetChangeNotifier#removeListener(com.vaadin.data.Container.PropertySetChangeListener)
     */
    @Override
    public void removePropertySetChangeListener(
            Container.PropertySetChangeListener listener) {
        if (propertySetEventListeners != null) {
            propertySetEventListeners.remove(listener);
            if (propertySetEventListeners.isEmpty()) {
                propertySetEventListeners = null;
            }
        }
    }

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #removePropertySetChangeListener(com.vaadin.data.Container.PropertySetChangeListener)}
     **/
    @Override
    @Deprecated
    public void removeListener(Container.PropertySetChangeListener listener) {
        removePropertySetChangeListener(listener);
    }

    /**
     * Adds an Item set change listener for the object.
     * 
     * @see com.vaadin.data.Container.ItemSetChangeNotifier#addListener(com.vaadin.data.Container.ItemSetChangeListener)
     */
    @Override
    public void addItemSetChangeListener(
            Container.ItemSetChangeListener listener) {
        if (itemSetEventListeners == null) {
            itemSetEventListeners = new LinkedHashSet<Container.ItemSetChangeListener>();
        }
        itemSetEventListeners.add(listener);
    }

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #addItemSetChangeListener(com.vaadin.data.Container.ItemSetChangeListener)}
     **/
    @Override
    @Deprecated
    public void addListener(Container.ItemSetChangeListener listener) {
        addItemSetChangeListener(listener);
    }

    /**
     * Removes the Item set change listener from the object.
     * 
     * @see com.vaadin.data.Container.ItemSetChangeNotifier#removeListener(com.vaadin.data.Container.ItemSetChangeListener)
     */
    @Override
    public void removeItemSetChangeListener(
            Container.ItemSetChangeListener listener) {
        if (itemSetEventListeners != null) {
            itemSetEventListeners.remove(listener);
            if (itemSetEventListeners.isEmpty()) {
                itemSetEventListeners = null;
            }
        }
    }

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #removeItemSetChangeListener(com.vaadin.data.Container.ItemSetChangeListener)}
     **/
    @Override
    @Deprecated
    public void removeListener(Container.ItemSetChangeListener listener) {
        removeItemSetChangeListener(listener);
    }

    @Override
    public Collection<?> getListeners(Class<?> eventType) {
        if (Container.ItemSetChangeEvent.class.isAssignableFrom(eventType)) {
            if (itemSetEventListeners == null) {
                return Collections.EMPTY_LIST;
            } else {
                return Collections
                        .unmodifiableCollection(itemSetEventListeners);
            }
        } else if (Container.PropertySetChangeEvent.class
                .isAssignableFrom(eventType)) {
            if (propertySetEventListeners == null) {
                return Collections.EMPTY_LIST;
            } else {
                return Collections
                        .unmodifiableCollection(propertySetEventListeners);
            }
        }

        return super.getListeners(eventType);
    }

    /**
     * Lets the listener know a Containers Item set has changed.
     * 
     * @see com.vaadin.data.Container.ItemSetChangeListener#containerItemSetChange(com.vaadin.data.Container.ItemSetChangeEvent)
     */
    @Override
    public void containerItemSetChange(Container.ItemSetChangeEvent event) {
        // Clears the item id mapping table
        itemIdMapper.removeAll();

        // Notify all listeners
        fireItemSetChange();
    }

    /**
     * Fires the property set change event.
     */
    protected void firePropertySetChange() {
        if (propertySetEventListeners != null
                && !propertySetEventListeners.isEmpty()) {
            final Container.PropertySetChangeEvent event = new PropertySetChangeEvent(
                    this);
            final Object[] listeners = propertySetEventListeners.toArray();
            for (int i = 0; i < listeners.length; i++) {
                ((Container.PropertySetChangeListener) listeners[i])
                        .containerPropertySetChange(event);
            }
        }
        markAsDirty();
    }

    /**
     * Fires the item set change event.
     */
    protected void fireItemSetChange() {
        if (itemSetEventListeners != null && !itemSetEventListeners.isEmpty()) {
            final Container.ItemSetChangeEvent event = new ItemSetChangeEvent(
                    this);
            final Object[] listeners = itemSetEventListeners.toArray();
            for (int i = 0; i < listeners.length; i++) {
                ((Container.ItemSetChangeListener) listeners[i])
                        .containerItemSetChange(event);
            }
        }
        markAsDirty();
    }

    /**
     * Implementation of item set change event.
     */
    private static class ItemSetChangeEvent extends EventObject implements
            Serializable, Container.ItemSetChangeEvent {

        private ItemSetChangeEvent(Container source) {
            super(source);
        }

        /**
         * Gets the Property where the event occurred.
         * 
         * @see com.vaadin.data.Container.ItemSetChangeEvent#getContainer()
         */
        @Override
        public Container getContainer() {
            return (Container) getSource();
        }

    }

    /**
     * Implementation of property set change event.
     */
    private static class PropertySetChangeEvent extends EventObject implements
            Container.PropertySetChangeEvent, Serializable {

        private PropertySetChangeEvent(Container source) {
            super(source);
        }

        /**
         * Retrieves the Container whose contents have been modified.
         * 
         * @see com.vaadin.data.Container.PropertySetChangeEvent#getContainer()
         */
        @Override
        public Container getContainer() {
            return (Container) getSource();
        }

    }

    /**
     * For multi-selectable fields, also an empty collection of values is
     * considered to be an empty field.
     * 
     * @see AbstractField#isEmpty().
     */
    @Override
    protected boolean isEmpty() {
        if (!multiSelect) {
            return super.isEmpty();
        } else {
            Object value = getValue();
            return super.isEmpty()
                    || (value instanceof Collection && ((Collection<?>) value)
                            .isEmpty());
        }
    }

    /**
     * Allow or disallow empty selection by the user. If the select is in
     * single-select mode, you can make an item represent the empty selection by
     * calling <code>setNullSelectionItemId()</code>. This way you can for
     * instance set an icon and caption for the null selection item.
     * 
     * @param nullSelectionAllowed
     *            whether or not to allow empty selection
     * @see #setNullSelectionItemId(Object)
     * @see #isNullSelectionAllowed()
     */
    public void setNullSelectionAllowed(boolean nullSelectionAllowed) {
        if (nullSelectionAllowed != this.nullSelectionAllowed) {
            this.nullSelectionAllowed = nullSelectionAllowed;
            markAsDirty();
        }
    }

    /**
     * Checks if null empty selection is allowed by the user.
     * 
     * @return whether or not empty selection is allowed
     * @see #setNullSelectionAllowed(boolean)
     */
    public boolean isNullSelectionAllowed() {
        return nullSelectionAllowed;
    }

    /**
     * Returns the item id that represents null value of this select in single
     * select mode.
     * 
     * <p>
     * Data interface does not support nulls as item ids. Selecting the item
     * identified by this id is the same as selecting no items at all. This
     * setting only affects the single select mode.
     * </p>
     * 
     * @return the Object Null value item id.
     * @see #setNullSelectionItemId(Object)
     * @see #isSelected(Object)
     * @see #select(Object)
     */
    public Object getNullSelectionItemId() {
        return nullSelectionItemId;
    }

    /**
     * Sets the item id that represents null value of this select.
     * 
     * <p>
     * Data interface does not support nulls as item ids. Selecting the item
     * identified by this id is the same as selecting no items at all. This
     * setting only affects the single select mode.
     * </p>
     * 
     * @param nullSelectionItemId
     *            the nullSelectionItemId to set.
     * @see #getNullSelectionItemId()
     * @see #isSelected(Object)
     * @see #select(Object)
     */
    public void setNullSelectionItemId(Object nullSelectionItemId) {
        if (nullSelectionItemId != null && isMultiSelect()) {
            throw new IllegalStateException(
                    "Multiselect and NullSelectionItemId can not be set at the same time.");
        }
        this.nullSelectionItemId = nullSelectionItemId;
    }

    /**
     * Notifies the component that it is connected to an application.
     * 
     * @see com.vaadin.ui.AbstractField#attach()
     */
    @Override
    public void attach() {
        super.attach();
    }

    /**
     * Detaches the component from application.
     * 
     * @see com.vaadin.ui.AbstractComponent#detach()
     */
    @Override
    public void detach() {
        getCaptionChangeListener().clear();
        super.detach();
    }

    // Caption change listener
    protected CaptionChangeListener getCaptionChangeListener() {
        if (captionChangeListener == null) {
            captionChangeListener = new CaptionChangeListener();
        }
        return captionChangeListener;
    }

    /**
     * This is a listener helper for Item and Property changes that should cause
     * a repaint. It should be attached to all items that are displayed, and the
     * default implementation does this in paintContent(). Especially
     * "lazyloading" components should take care to add and remove listeners as
     * appropriate. Call addNotifierForItem() for each painted item (and
     * remember to clear).
     * 
     * NOTE: singleton, use getCaptionChangeListener().
     * 
     */
    protected class CaptionChangeListener implements
            Item.PropertySetChangeListener, Property.ValueChangeListener {

        // TODO clean this up - type is either Item.PropertySetChangeNotifier or
        // Property.ValueChangeNotifier
        HashSet<Object> captionChangeNotifiers = new HashSet<Object>();

        public void addNotifierForItem(Object itemId) {
            switch (getItemCaptionMode()) {
            case ITEM:
                final Item i = getItem(itemId);
                if (i == null) {
                    return;
                }
                if (i instanceof Item.PropertySetChangeNotifier) {
                    ((Item.PropertySetChangeNotifier) i)
                            .addListener(getCaptionChangeListener());
                    captionChangeNotifiers.add(i);
                }
                Collection<?> pids = i.getItemPropertyIds();
                if (pids != null) {
                    for (Iterator<?> it = pids.iterator(); it.hasNext();) {
                        Property<?> p = i.getItemProperty(it.next());
                        if (p != null
                                && p instanceof Property.ValueChangeNotifier) {
                            ((Property.ValueChangeNotifier) p)
                                    .addListener(getCaptionChangeListener());
                            captionChangeNotifiers.add(p);
                        }
                    }

                }
                break;
            case PROPERTY:
                final Property<?> p = getContainerProperty(itemId,
                        getItemCaptionPropertyId());
                if (p != null && p instanceof Property.ValueChangeNotifier) {
                    ((Property.ValueChangeNotifier) p)
                            .addListener(getCaptionChangeListener());
                    captionChangeNotifiers.add(p);
                }
                break;

            }
            if (getItemIconPropertyId() != null) {
                final Property p = getContainerProperty(itemId,
                        getItemIconPropertyId());
                if (p != null && p instanceof Property.ValueChangeNotifier) {
                    ((Property.ValueChangeNotifier) p)
                            .addListener(getCaptionChangeListener());
                    captionChangeNotifiers.add(p);
                }
            }
        }

        public void clear() {
            for (Iterator<Object> it = captionChangeNotifiers.iterator(); it
                    .hasNext();) {
                Object notifier = it.next();
                if (notifier instanceof Item.PropertySetChangeNotifier) {
                    ((Item.PropertySetChangeNotifier) notifier)
                            .removeListener(getCaptionChangeListener());
                } else {
                    ((Property.ValueChangeNotifier) notifier)
                            .removeListener(getCaptionChangeListener());
                }
            }
            captionChangeNotifiers.clear();
        }

        @Override
        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            markAsDirty();
        }

        @Override
        public void itemPropertySetChange(
                com.vaadin.data.Item.PropertySetChangeEvent event) {
            markAsDirty();
        }

    }

    /**
     * Criterion which accepts a drop only if the drop target is (one of) the
     * given Item identifier(s). Criterion can be used only on a drop targets
     * that extends AbstractSelect like {@link Table} and {@link Tree}. The
     * target and identifiers of valid Items are given in constructor.
     * 
     * @since 6.3
     */
    public static class TargetItemIs extends AbstractItemSetCriterion {

        /**
         * @param select
         *            the select implementation that is used as a drop target
         * @param itemId
         *            the identifier(s) that are valid drop locations
         */
        public TargetItemIs(AbstractSelect select, Object... itemId) {
            super(select, itemId);
        }

        @Override
        public boolean accept(DragAndDropEvent dragEvent) {
            AbstractSelectTargetDetails dropTargetData = (AbstractSelectTargetDetails) dragEvent
                    .getTargetDetails();
            if (dropTargetData.getTarget() != select) {
                return false;
            }
            return itemIds.contains(dropTargetData.getItemIdOver());
        }

    }

    /**
     * Abstract helper class to implement item id based criterion.
     * 
     * Note, inner class used not to open itemIdMapper for public access.
     * 
     * @since 6.3
     * 
     */
    private static abstract class AbstractItemSetCriterion extends
            ClientSideCriterion {
        protected final Collection<Object> itemIds = new HashSet<Object>();
        protected AbstractSelect select;

        public AbstractItemSetCriterion(AbstractSelect select, Object... itemId) {
            if (itemIds == null || select == null) {
                throw new IllegalArgumentException(
                        "Accepted item identifiers must be accepted.");
            }
            Collections.addAll(itemIds, itemId);
            this.select = select;
        }

        @Override
        public void paintContent(PaintTarget target) throws PaintException {
            super.paintContent(target);
            String[] keys = new String[itemIds.size()];
            int i = 0;
            for (Object itemId : itemIds) {
                String key = select.itemIdMapper.key(itemId);
                keys[i++] = key;
            }
            target.addAttribute("keys", keys);
            target.addAttribute("s", select);
        }

    }

    /**
     * This criterion accepts a only a {@link Transferable} that contains given
     * Item (practically its identifier) from a specific AbstractSelect.
     * 
     * @since 6.3
     */
    public static class AcceptItem extends AbstractItemSetCriterion {

        /**
         * @param select
         *            the select from which the item id's are checked
         * @param itemId
         *            the item identifier(s) of the select that are accepted
         */
        public AcceptItem(AbstractSelect select, Object... itemId) {
            super(select, itemId);
        }

        @Override
        public boolean accept(DragAndDropEvent dragEvent) {
            DataBoundTransferable transferable = (DataBoundTransferable) dragEvent
                    .getTransferable();
            if (transferable.getSourceComponent() != select) {
                return false;
            }
            return itemIds.contains(transferable.getItemId());
        }

        /**
         * A simple accept criterion which ensures that {@link Transferable}
         * contains an {@link Item} (or actually its identifier). In other words
         * the criterion check that drag is coming from a {@link Container} like
         * {@link Tree} or {@link Table}.
         */
        public static final ClientSideCriterion ALL = new ContainsDataFlavor(
                "itemId");

    }

    /**
     * TargetDetails implementation for subclasses of {@link AbstractSelect}
     * that implement {@link DropTarget}.
     * 
     * @since 6.3
     */
    public class AbstractSelectTargetDetails extends TargetDetailsImpl {

        /**
         * The item id over which the drag event happened.
         */
        protected Object idOver;

        /**
         * Constructor that automatically converts itemIdOver key to
         * corresponding item Id
         * 
         */
        protected AbstractSelectTargetDetails(Map<String, Object> rawVariables) {
            super(rawVariables, (DropTarget) AbstractSelect.this);
            // eagar fetch itemid, mapper may be emptied
            String keyover = (String) getData("itemIdOver");
            if (keyover != null) {
                idOver = itemIdMapper.get(keyover);
            }
        }

        /**
         * If the drag operation is currently over an {@link Item}, this method
         * returns the identifier of that {@link Item}.
         * 
         */
        public Object getItemIdOver() {
            return idOver;
        }

        /**
         * Returns a detailed vertical location where the drop happened on Item.
         */
        public VerticalDropLocation getDropLocation() {
            String detail = (String) getData("detail");
            if (detail == null) {
                return null;
            }
            return VerticalDropLocation.valueOf(detail);
        }

    }

    /**
     * An accept criterion to accept drops only on a specific vertical location
     * of an item.
     * <p>
     * This accept criterion is currently usable in Tree and Table
     * implementations.
     */
    public static class VerticalLocationIs extends TargetDetailIs {
        public static VerticalLocationIs TOP = new VerticalLocationIs(
                VerticalDropLocation.TOP);
        public static VerticalLocationIs BOTTOM = new VerticalLocationIs(
                VerticalDropLocation.BOTTOM);
        public static VerticalLocationIs MIDDLE = new VerticalLocationIs(
                VerticalDropLocation.MIDDLE);

        private VerticalLocationIs(VerticalDropLocation l) {
            super("detail", l.name());
        }
    }

    /**
     * Implement this interface and pass it to Tree.setItemDescriptionGenerator
     * or Table.setItemDescriptionGenerator to generate mouse over descriptions
     * ("tooltips") for the rows and cells in Table or for the items in Tree.
     */
    public interface ItemDescriptionGenerator extends Serializable {

        /**
         * Called by Table when a cell (and row) is painted or a item is painted
         * in Tree
         * 
         * @param source
         *            The source of the generator, the Tree or Table the
         *            generator is attached to
         * @param itemId
         *            The itemId of the painted cell
         * @param propertyId
         *            The propertyId of the cell, null when getting row
         *            description
         * @return The description or "tooltip" of the item.
         */
        public String generateDescription(Component source, Object itemId,
                Object propertyId);
    }
}