File: ListSelection.java

package info (click to toggle)
libglazedlists-java 1.9.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,024 kB
  • ctags: 4,252
  • sloc: java: 22,561; xml: 818; sh: 51; makefile: 5
file content (1357 lines) | stat: -rw-r--r-- 52,331 bytes parent folder | download | duplicates (3)
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
/* Glazed Lists                                                 (c) 2003-2006 */
/* http://publicobject.com/glazedlists/                      publicobject.com,*/
/*                                                     O'Dell Engineering Ltd.*/
package ca.odell.glazedlists;

import ca.odell.glazedlists.event.ListEvent;
import ca.odell.glazedlists.event.ListEventAssembler;
import ca.odell.glazedlists.event.ListEventListener;
import ca.odell.glazedlists.impl.adt.Barcode;
import ca.odell.glazedlists.impl.adt.BarcodeIterator;
import ca.odell.glazedlists.matchers.Matcher;

import java.util.*;

/**
 * A class to provide index-based selection features. This class maintains two
 * lists derived from a single {@link EventList}:
 * <ul>
 *   <li>{@link #getSelected() Selected} - an {@link EventList} that contains only the selected values.</li>
 *   <li>{@link #getDeselected() Deselected} - an {@link EventList} that contains only the deselected values.</li>
 * </ul>
 *
 * <p>This design is intended to allow the sharing of selection logic between
 * all supported GUI toolkits as well as being available for use in non-GUI
 * applications and for index-based filtering.
 *
 * <p><strong><font color="#FF0000">Warning:</font></strong> This class is
 * thread ready but not thread safe. See {@link EventList} for an example
 * of thread safe code.
 *
 * @author <a href="mailto:kevin@swank.ca">Kevin Maltby</a>
 */
public class ListSelection<E> implements ListEventListener<E> {

    /**
     * A selection mode where at most one element may be selected at one time.
     * For convenience, this value equals {@link javax.swing.ListSelectionModel#SINGLE_SELECTION}.
     */
    public static final int SINGLE_SELECTION = 0;

    /**
     * A selection mode where at most one range of elements may be selected at one time.
     * For convenience, this value equals {@link javax.swing.ListSelectionModel#SINGLE_INTERVAL_SELECTION}.
     */
    public static final int SINGLE_INTERVAL_SELECTION = 1;

    /**
     * A selection mode where any element may be selected and elements added
     * adjacent to selected elements are selected. For convenience, this value
     * equals {@link javax.swing.ListSelectionModel#MULTIPLE_INTERVAL_SELECTION}.
     */
    public static final int MULTIPLE_INTERVAL_SELECTION = 2;

    /**
     * A selection mode where any element may be selected and freshly added elements
     * are always deselected. No equivalent policy exists in
     * {@link javax.swing.ListSelectionModel}
     */
    public static final int MULTIPLE_INTERVAL_SELECTION_DEFENSIVE = 103;

    /** the current selection colour */
    private static final Object SELECTED = Barcode.BLACK;

    /** the current deselection colour */
    private static final Object DESELECTED = Barcode.WHITE;

    /** the source list */
    private final EventList<E> source;

    /** the selected view */
    private SelectedList<E> selectedList;

    /** the deselected view */
    private DeselectedList<E> deselectedList;

    /** the toggling selected view */
    private SelectionToggleList<E> selectedToggleList;

    /** the toggling deselected view */
    private DeselectionToggleList<E> deselectedToggleList;

    /** the selection state */
    private Barcode barcode = new Barcode();

    /** the lead selection index */
    private int leadSelectionIndex = -1;

    /** the anchor selection index */
    private int anchorSelectionIndex = -1;

    /** the selection mode defines characteristics of the selection */
    private int selectionMode = MULTIPLE_INTERVAL_SELECTION_DEFENSIVE;

    /** the Matchers, if any, which decide whether a source element can be selected or not */
    private final Collection<Matcher<E>> validSelectionMatchers = new ArrayList<Matcher<E>>();

    /**
     * the registered SelectionListeners; also used as a mutex to ensure we
     * build each of the following only once:
     *
     * <ul>
     *   <li>{@link #selectedList}</li>
     *   <li>{@link #deselectedList}</li>
     *   <li>{@link #selectedToggleList}</li>
     *   <li>{@link #deselectedToggleList}</li>
     * </ul>
     */
    private final List<Listener> selectionListeners = new ArrayList<Listener>(1);

    /**
     * Creates a new ListSelection that listens to changes on the given source.
     * When using this constructor, all elements are deselected by default.
     */
    public ListSelection(EventList<E> source) {
        this.source = source;
        barcode.add(0, DESELECTED, source.size());
        source.addListEventListener(this);
    }

    /**
     * Creates a new ListSelection that listens to changes on the given source
     * and initializes selection with the given array of indices.
     */
    public ListSelection(EventList<E> source, int[] initialSelection) {
        this(source);
        select(initialSelection);
    }

    /**
     * Handle changes to the source list by adjusting our selection state and
     * the contents of the selected and deselected lists.
     */
    public void listChanged(ListEvent<E> listChanges) {

        // keep track of what used to be selected
        final int minSelectionIndexBefore = getMinSelectionIndex();
        final int maxSelectionIndexBefore = getMaxSelectionIndex();

        boolean selectionChanged = false;

        // handle reordering events
        if(listChanges.isReordering()) {
            // prepare for the reordering event
            beginSelected();
            int[] sourceReorderMap = listChanges.getReorderMap();
            int[] selectReorderMap = new int[barcode.colourSize(SELECTED)];
            int[] deselectReorderMap = new int[barcode.colourSize(DESELECTED)];

            // adjust the flaglist & construct a reorder map to propagate
            Barcode previousBarcode = barcode;
            barcode = new Barcode();
            for(int c = 0; c < sourceReorderMap.length; c++) {
                Object flag = previousBarcode.get(sourceReorderMap[c]);
                boolean wasSelected = (flag != DESELECTED);
                barcode.add(c, flag, 1);
                if(wasSelected) {
                    int previousIndex = previousBarcode.getColourIndex(sourceReorderMap[c], SELECTED);
                    int currentIndex = barcode.getColourIndex(c, SELECTED);
                    selectReorderMap[currentIndex] = previousIndex;
                } else {
                    int previousIndex = previousBarcode.getColourIndex(sourceReorderMap[c], DESELECTED);
                    int currentIndex = barcode.getColourIndex(c, DESELECTED);
                    deselectReorderMap[currentIndex] = previousIndex;
                }
            }

            // adjust other internal state
            anchorSelectionIndex = -1;
            leadSelectionIndex = -1;

            // fire the reorder on the selected list
            addSelectedReorder(selectReorderMap);
            commitSelected();

            // fire the reorder on the deselected list
            beginDeselected();
            addDeselectedReorder(deselectReorderMap);
            commitDeselected();

            // all reordering events are assumed to have changed the selection
            selectionChanged = true;

        // handle non-reordering events
        } else {
            // prepare a sequence of changes
            beginAll();
            // for all changes update the barcode
            while(listChanges.next()) {
                int index = listChanges.getIndex();
                int changeType = listChanges.getType();

                // learn about what it was
                int previousSelectionIndex = barcode.getColourIndex(index, SELECTED);
                boolean previouslySelected = previousSelectionIndex != -1;

                // when an element is deleted, blow it away
                if(changeType == ListEvent.DELETE) {

                    // if the change occurred anywhere before the maxSelectionIndexBefore
                    // then it effects the current selection and we must fire a ListSelectionEvent
                    if (index <= maxSelectionIndexBefore)
                        selectionChanged = true;

                    // delete selected values
                    if(previouslySelected) {
                        barcode.remove(index, 1);
                        addSelectedDelete(previousSelectionIndex, listChanges.getOldValue());

                    // delete deselected values
                    } else {
                        int deselectedIndex = barcode.getColourIndex(index, DESELECTED);
                        addDeselectedDelete(deselectedIndex, listChanges.getOldValue());
                        barcode.remove(index, 1);
                    }

                // when an element is inserted, it is selected if its index was selected
                } else if(changeType == ListEvent.INSERT) {

                    // if the change occurred anywhere before the maxSelectionIndexBefore
                    // then it effects the current selection and we must fire a ListSelectionEvent
                    if (index <= maxSelectionIndexBefore)
                        selectionChanged = true;

                    // when selected, decide based on selection mode
                    if(previouslySelected) {

                        // select the inserted for single interval and multiple interval selection
                        if(selectionMode == SINGLE_INTERVAL_SELECTION
                        || selectionMode == MULTIPLE_INTERVAL_SELECTION) {
                            barcode.add(index, SELECTED, 1);
                            addSelectedInsert(previousSelectionIndex, listChanges.getNewValue());

                        // do not select the inserted for single selection and defensive selection
                        } else {
                            barcode.add(index, DESELECTED, 1);
                            int deselectedIndex = barcode.getColourIndex(index, DESELECTED);
                            addDeselectedInsert(deselectedIndex, listChanges.getNewValue());
                        }

                    // add a deselected value
                    } else {
                        barcode.add(index, DESELECTED, 1);
                        int deselectedIndex = barcode.getColourIndex(index, DESELECTED);
                        addDeselectedInsert(deselectedIndex, listChanges.getNewValue());
                    }

                // when an element is changed, assume selection stays the same
                } else if(changeType == ListEvent.UPDATE) {
                    // update a selected value
                    if(previouslySelected) {
                        addSelectedUpdate(previousSelectionIndex, listChanges.getOldValue(), listChanges.getNewValue());

                    // update a deselected value
                    } else {
                        int deselectedIndex = barcode.getColourIndex(index, DESELECTED);
                        addDeselectedUpdate(deselectedIndex, listChanges.getOldValue(), listChanges.getNewValue());
                    }
                }

                // adjust other internal state
                anchorSelectionIndex = adjustIndex(anchorSelectionIndex, changeType, index);
                leadSelectionIndex = adjustIndex(leadSelectionIndex, changeType, index);
            }
            commitAll();
        }

        // notify listeners of the selection change
        if(minSelectionIndexBefore != -1 && maxSelectionIndexBefore != -1 && selectionChanged) {
            final int minSelectionIndexAfter = getMinSelectionIndex();
            final int maxSelectionIndexAfter = getMaxSelectionIndex();

            int changeStart = minSelectionIndexBefore;
            int changeFinish = maxSelectionIndexBefore;

            if(minSelectionIndexAfter != -1 && minSelectionIndexAfter < changeStart) changeStart = minSelectionIndexAfter;
            if(maxSelectionIndexAfter != -1 && maxSelectionIndexAfter > changeFinish) changeFinish = maxSelectionIndexAfter;

            fireSelectionChanged(changeStart, changeFinish);
        }
    }

    /**
     * Add a matcher which decides when source elements are valid for selection.
     *
     * @param validSelectionMatcher returns <tt>true</tt> if a source elements
     *      can be selected; <tt>false</tt> otherwise
     */
    public void addValidSelectionMatcher(Matcher<E> validSelectionMatcher) {
        validSelectionMatchers.add(validSelectionMatcher);

        // walk through the existing selections deselecting anything that is no longer selectable
        for (int i = getMinSelectionIndex(), n = getMaxSelectionIndex(); i <= n; i++)
            if (isSelected(i) && !isSelectable(i))
                deselect(i);
    }

    /**
     * Remove a matcher which decides when source elements are valid for selection.
     *
     * @param validSelectionMatcher returns <tt>true</tt> if a source elements
     *      can be selected; <tt>false</tt> otherwise
     */
    public void removeValidSelectionMatcher(Matcher<E> validSelectionMatcher) {
        validSelectionMatchers.remove(validSelectionMatcher);
    }

    /**
     * Adjusts the specified index to the specified change. This is used to adjust
     * the anchor and lead selection indices when list changes occur.
     */
    private int adjustIndex(int indexBefore, int changeType, int changeIndex) {
        if(indexBefore == -1) return -1;
        if(changeType == ListEvent.DELETE) {
            if(changeIndex < indexBefore) return indexBefore-1;
            else if(changeIndex == indexBefore) return -1;
            else return indexBefore;
        } else if(changeType == ListEvent.UPDATE) {
            return indexBefore;
        } else if(changeType == ListEvent.INSERT) {
            if(changeIndex <= indexBefore) return indexBefore+1;
            else return indexBefore;
        } else {
            throw new IllegalStateException();
        }
    }

    /**
     * Gets an {@link EventList} that contains only selected values and modifies
     * the source list on mutation.
     *
     * Adding and removing items from this list performs the same operation on
     * the source list.
     */
    public EventList<E> getSelected() {
        synchronized (selectionListeners) {
            if(selectedList == null){
                selectedList = new SelectedList<E>(source);
                source.getPublisher().setRelatedListener(selectedList, this);
            }
        }
        return selectedList;
    }

    /**
     * Gets an {@link EventList} that contains only selected values and modifies
     * the selection state on mutation.
     *
     * <p>Adding an item to this list selects it and removing an item deselects it.
     * If an item not in the source list is added an
     * {@link IllegalArgumentException} is thrown. This list does not support
     * the {@link List#set set} method.
     */
    public EventList<E> getTogglingSelected() {
        synchronized (selectionListeners) {
            if(selectedToggleList == null) {
                selectedToggleList = new SelectionToggleList<E>(source);
                source.getPublisher().setRelatedListener(selectedToggleList, this);
            }
        }
        return selectedToggleList;
    }

    /**
     * Gets an {@link EventList} that contains only deselected values add
     * modifies the source list on mutation.
     *
     * Adding and removing items from this list performs the same operation on
     * the source list.
     */
    public EventList<E> getDeselected() {
        synchronized (selectionListeners) {
            if(deselectedList == null) {
                deselectedList = new DeselectedList<E>(source);
                source.getPublisher().setRelatedListener(deselectedList, this);
            }
        }
        return deselectedList;
    }

    /**
     * Gets an {@link EventList} that contains only deselected values and
     * modifies the selection state on mutation.
     *
     * <p>Adding an item to this list deselects it and removing an item selects it.
     * If an item not in the source list is added an
     * {@link IllegalArgumentException} is thrown. This list does not support
     * the {@link List#set set} method.
     */
    public EventList<E> getTogglingDeselected() {
        synchronized (selectionListeners) {
            if(deselectedToggleList == null) {
                deselectedToggleList = new DeselectionToggleList<E>(source);
                source.getPublisher().setRelatedListener(deselectedToggleList, this);
            }
        }
        return deselectedToggleList;
    }

    /**
     * Get the {@link EventList} that selection is being managed for.
     */
    public EventList<E> getSource() {
        return source;
    }

    /**
     * Inverts the current selection.
     */
    public void invertSelection() {
        // Clear the anchor and lead
        anchorSelectionIndex = -1;
        leadSelectionIndex = -1;

        // Update the selected list to reflect the selection inversion
        beginAll();
        for(BarcodeIterator i = barcode.iterator(); i.hasNext(); ) {
            Object color = i.next();
            E value = source.get(i.getIndex());
            int originalIndex = i.getColourIndex(color);

            if(color == SELECTED) {
                i.set(DESELECTED);
                int newIndex = i.getColourIndex(DESELECTED);
                addDeselectEvent(originalIndex, newIndex, value);

            } else {
                i.set(SELECTED);
                int newIndex = i.getColourIndex(SELECTED);
                addSelectEvent(newIndex, originalIndex, value);
            }
        }
        commitAll();

        // notify selection listeners that selection has been inverted
        fireSelectionChanged(0, source.size() - 1);
    }

    /**
     * Returns whether or not the item with the given source index
     * is selected.
     */
    public boolean isSelected(int sourceIndex) {
        if(sourceIndex < 0 || sourceIndex >= source.size()) {
            return false;
        }
        return barcode.getColourIndex(sourceIndex, SELECTED) != -1;
    }

    /**
     * Deselects the element at the given index.
     */
    public void deselect(int index) {
        deselect(index, index);
    }

    /**
     * Deselects all of the elements within the given range.
     */
    public void deselect(int start, int end) {
        // fast fail if the range is invalid
        if(start == -1 || end == -1) {
            return;

        // use single value deselection in single selection mode
        } else if(selectionMode == SINGLE_SELECTION) {
            int selectedIndex = getMaxSelectionIndex();
            // only change selection if you have to
            if(selectedIndex >= start && selectedIndex <= end) {
                deselectAll();
            }
            return;

        // adjust the range to prevent the creation of multiple intervals
        } else if(selectionMode == SINGLE_INTERVAL_SELECTION && start > getMinSelectionIndex()) {
            end = Math.max(end, getMaxSelectionIndex());
        }

        // record the original anchor and lead if they are about to change
        final int oldAnchor = anchorSelectionIndex == start ? -1 : anchorSelectionIndex;
        final int oldLead = leadSelectionIndex == end ? -1 : leadSelectionIndex;

        // update anchor and lead
        anchorSelectionIndex = start;
        leadSelectionIndex = end;

        // alter selection accordingly
        setSubRangeOfRange(false, start, end, -1, -1, oldLead, oldAnchor);
    }

    /**
     * Deselects all of the elements in the given array of indices.  The
     * array must contain indices in sorted, ascending order.
     */
    public void deselect(int[] indices) {
        // keep track of the range of values that were affected
        int firstAffectedIndex = -1;
        int lastAffectedIndex = -1;

        // iterate through the barcode updating the selected list as you go
        beginAll();
        int currentIndex = 0;
        for(BarcodeIterator i = barcode.iterator(); i.hasNext() && currentIndex != indices.length;) {
            Object value = i.next();
            if(i.getIndex() == indices[currentIndex]) {
                // selection changed
                if(value == SELECTED) {
                    if(firstAffectedIndex == -1) firstAffectedIndex = i.getIndex();
                    lastAffectedIndex = i.getIndex();
                    addDeselectEvent(i);
                }
                currentIndex++;
            }
        }
        commitAll();

        // notify listeners of selection change
        if(firstAffectedIndex > -1) fireSelectionChanged(firstAffectedIndex, lastAffectedIndex);
    }

    /**
     * Deselect all elements.
     */
    public void deselectAll() {
        setAllColor(DESELECTED);
    }

    /**
     * @param color either selected or deselected.
     */
    private void setAllColor(Object color) {
        // if there is nothing selected, we're done
        Object oppositeColor = (color == SELECTED) ? DESELECTED : SELECTED;
        if(barcode.colourSize(oppositeColor) == 0) return;

        // keep track of the range of values that were affected
        int firstAffectedIndex = -1;
        int lastAffectedIndex = -1;

        // prepare the change events
        beginAll();
        for(BarcodeIterator i = barcode.iterator(); i.hasNextColour(oppositeColor);) {
            i.nextColour(oppositeColor);
            int index = i.getIndex();
            E value = source.get(index);
            if(color == SELECTED) {
                addDeselectedDelete(0, value);
                addSelectedInsert(index, value);
            } else {
                addSelectedDelete(0, value);
                addDeselectedInsert(index, value);
            }

            if(firstAffectedIndex == -1) firstAffectedIndex = index;
            lastAffectedIndex = index;
        }

        // reset barcode state
        barcode.clear();
        barcode.add(0, color, source.size());

        // fire events
        commitAll();
        fireSelectionChanged(firstAffectedIndex, lastAffectedIndex);
    }

    /**
     * Selects the element at the given index.
     */
    public void select(int index) {
        select(index, index);
    }

    /**
     * Selects all of the elements within the given range.
     */
    public void select(int start, int end) {
        // fast fail if the range is an no-op
        if(start == -1 || end == -1) {
            return;

        // use single value deselection in single selection mode
        } else if(selectionMode == SINGLE_SELECTION) {
            setSelection(start);
            return;

        // adjust the range to prevent the creation of multiple intervals
        } else if(selectionMode == SINGLE_INTERVAL_SELECTION) {
            // test if the current and new selection overlap
            boolean overlap = false;
            int minSelectedIndex = getMinSelectionIndex();
            int maxSelectedIndex = getMaxSelectionIndex();
            if(minSelectedIndex - 1 <= start && start <= maxSelectedIndex + 1) overlap = true;
            if(minSelectedIndex - 1 <= end && end <= maxSelectedIndex + 1) overlap = true;

            if(!overlap) {
                setSelection(start, end);
                return;
            }
        }

        // record the original anchor and lead if they are about to change
        final int oldAnchor = anchorSelectionIndex == start ? -1 : anchorSelectionIndex;
        final int oldLead = leadSelectionIndex == end ? -1 : leadSelectionIndex;

        // update anchor and lead
        anchorSelectionIndex = start;
        leadSelectionIndex = end;

        // alter selection accordingly
        setSubRangeOfRange(true, start, end, -1, -1, oldLead, oldAnchor);
    }

    /**
     * Selects all of the elements in the given array of indices.  The
     * array must contain indices in sorted, ascending order.
     */
    public void select(int[] indices) {

        // keep track of the range of values that were affected
        int firstAffectedIndex = -1;
        int lastAffectedIndex = -1;

        // iterate through the barcode updating the selected list as you go
        beginAll();
        int currentIndex = 0;
        for(BarcodeIterator i = barcode.iterator(); i.hasNext() && currentIndex != indices.length;) {
            Object value = i.next();
            if(i.getIndex() == indices[currentIndex]) {
                // selection changed
                if(value != SELECTED) {
                    if(firstAffectedIndex == -1) firstAffectedIndex = i.getIndex();
                    lastAffectedIndex = i.getIndex();
                    addSelectEvent(i);
                }
                currentIndex++;
            }
        }
        commitAll();

        // notify listeners of selection change
        if(firstAffectedIndex > -1) fireSelectionChanged(firstAffectedIndex, lastAffectedIndex);
    }

    /**
     * Select the specified element, if it exists.
     *
     * @return the index of the newly selected element, or -1 if no
     *     element was found.
     */
    public int select(E value) {
        int index = source.indexOf(value);
        if(index != -1) select(index);
        return index;
    }

    /**
     * Select all of the specified values.
     *
     * @return <code>true</code> if the selection changed as a result of the call.
     */
    public boolean select(Collection<E> values) {
        // This implementation leaves a lot to be desired. It's inefficient and
        // awkward. If possible, we should clean up the entire SelectionList so
        // we don't need to worry as much about the deselection list.

        // 1. Convert our Collection of values into a SortedSet of indices
        SortedSet<Integer> indicesToSelect = new TreeSet<Integer>();
        for(Iterator<E> v = values.iterator(); v.hasNext(); ) {
            E value = v.next();
            int index = source.indexOf(value);
            if(index == -1) continue;
            indicesToSelect.add(new Integer(index));
        }
        if(indicesToSelect.isEmpty()) return false;

        // 2. convert the sorted set of Integers into an int[]
        int[] indicesToSelectAsInts = new int[indicesToSelect.size()];
        int arrayIndex = 0;
        for(Iterator<Integer> i = indicesToSelect.iterator(); i.hasNext(); ) {
            Integer selectIndex = i.next();
            indicesToSelectAsInts[arrayIndex] = selectIndex.intValue();
            arrayIndex++;
        }

        // 3. Delegate to the other method, and return true if the selection grew
        int selectionSizeBefore = getSelected().size();
        select(indicesToSelectAsInts);
        int selectionSizeAfter = getSelected().size();
        return selectionSizeAfter > selectionSizeBefore;
    }

    /**
     * Selects all elements.
     */
    public void selectAll() {
        setAllColor(SELECTED);
    }

    /**
     * Sets the selection to be only the element at the given index.  If the
     * given index is -1, the selection will be cleared.
     */
    public void setSelection(int index) {
        setSelection(index, index);
    }

    /**
     * Sets the selection to be only elements within the given range.  If the
     * endpoints of the range are -1, the selection will be cleared.
     */
    public void setSelection(int start, int end) {
        // a range including -1 implies a deselectAll()
        if(start == -1 || end == -1) {
            deselectAll();
            return;

        } else if(selectionMode == SINGLE_SELECTION) {
            end = start;
        }

        // record the original anchor and lead if they are about to change
        final int oldAnchor = anchorSelectionIndex == start ? -1 : anchorSelectionIndex;
        final int oldLead = leadSelectionIndex == end ? -1 : leadSelectionIndex;

        // update anchor and lead
        anchorSelectionIndex = start;
        leadSelectionIndex = end;

        // alter selection accordingly
        setSubRangeOfRange(true, start, end, getMinSelectionIndex(), getMaxSelectionIndex(), oldLead, oldAnchor);
    }

    /**
     * Sets the selection to be only the element in the given array of indices.
     * Unlike {@link #setSelection(int)} and {@link #setSelection(int,int)},
     * providing a value of -1 is an error.  The array must contain indices in
     * sorted, ascending order.
     */
    public void setSelection(int[] indices) {
        // fast fail is the selection is empty
        if(indices.length == 0) {
            deselectAll();
            return;
        }

        // keep track of the range of values that were affected
        int firstAffectedIndex = -1;
        int lastAffectedIndex = -1;

        // iterate through the barcode updating the selected list as you go
        beginAll();
        int currentIndex = 0;
        for(BarcodeIterator i = barcode.iterator(); i.hasNext();) {
            Object value = i.next();
            // this element should be selected
            if(i.getIndex() == indices[currentIndex]) {
                // selection changed
                if(value != SELECTED) {
                    if(firstAffectedIndex == -1) firstAffectedIndex = i.getIndex();
                    lastAffectedIndex = i.getIndex();
                    addSelectEvent(i);
                }

                // look at the next value
                if(currentIndex < indices.length - 1) currentIndex++;

            // element was selected and isn't within the new selection
            } else if(value == SELECTED) {
                if(firstAffectedIndex == -1) firstAffectedIndex = i.getIndex();
                lastAffectedIndex = i.getIndex();
                addDeselectEvent(i);
            }
        }
        commitAll();

        // notify listeners of selection change
        if(firstAffectedIndex > -1) fireSelectionChanged(firstAffectedIndex, lastAffectedIndex);
    }

    /**
     * Return the anchor of the current selection.
     */
    public int getAnchorSelectionIndex() {
        return anchorSelectionIndex;
    }

    /**
     * Set the anchor selection index.
     */
    public void setAnchorSelectionIndex(int anchorSelectionIndex) {
        // record the original anchor and lead if they are about to change
        final int oldAnchor = this.anchorSelectionIndex == anchorSelectionIndex ? -1 : anchorSelectionIndex;

        // update anchor
        this.anchorSelectionIndex = anchorSelectionIndex;

        // a value of -1 clears selection
        if(anchorSelectionIndex == -1 || leadSelectionIndex == -1) {
            deselectAll();

        // only the anchor should be selected
        } else if(selectionMode == SINGLE_SELECTION) {
            setSubRangeOfRange(true, anchorSelectionIndex, anchorSelectionIndex, getMinSelectionIndex(), getMaxSelectionIndex(), -1, oldAnchor);

        // select the interval between anchor and lead
        } else if(selectionMode == SINGLE_INTERVAL_SELECTION) {
            setSubRangeOfRange(true, anchorSelectionIndex, leadSelectionIndex, getMinSelectionIndex(), getMaxSelectionIndex(), -1, oldAnchor);

        // select the interval between anchor and lead without deselecting anything
        } else {
            setSubRangeOfRange(true, anchorSelectionIndex, leadSelectionIndex, -1, -1, -1, oldAnchor);
        }
    }

    /**
     * Return the lead of the current selection.
     */
    public int getLeadSelectionIndex() {
        return leadSelectionIndex;
    }

    /**
     * Set the lead selection index.
     */
    public void setLeadSelectionIndex(int leadSelectionIndex) {
        // record the original anchor and lead if they are about to change
        final int oldLead = this.leadSelectionIndex == leadSelectionIndex ? -1 : leadSelectionIndex;

        // update lead
        int originalLeadIndex = this.leadSelectionIndex;
        this.leadSelectionIndex = leadSelectionIndex;

        // a value of -1 clears selection
        if(leadSelectionIndex == -1 || anchorSelectionIndex == -1) {
            deselectAll();

        // select only the lead
        } else if(selectionMode == SINGLE_SELECTION) {
            setSubRangeOfRange(true, leadSelectionIndex, leadSelectionIndex, getMinSelectionIndex(), getMaxSelectionIndex(), oldLead, -1);

        // select the interval between anchor and lead
        } else if(selectionMode == SINGLE_INTERVAL_SELECTION) {
            setSubRangeOfRange(true, anchorSelectionIndex, leadSelectionIndex, getMinSelectionIndex(), getMaxSelectionIndex(), oldLead, -1);

        // select the interval between anchor and lead deselecting as necessary
        } else {
            setSubRangeOfRange(true, anchorSelectionIndex, leadSelectionIndex, anchorSelectionIndex, originalLeadIndex, oldLead, -1);
        }
    }

    private void addSelectedReorder(int[] selectReorderMap) {
        if(selectedList != null)  selectedList.updates().reorder(selectReorderMap);
        if(selectedToggleList != null) selectedToggleList.updates().reorder(selectReorderMap);
    }
    private void addDeselectedReorder(int[] deselectReorderMap) {
        if(deselectedList != null) deselectedList.updates().reorder(deselectReorderMap);
        if(deselectedToggleList != null) deselectedToggleList.updates().reorder(deselectReorderMap);
    }

    private void addSelectEvent(BarcodeIterator i) {
        E value = source.get(i.getIndex());
        int deselectedIndex = i.getColourIndex(DESELECTED);
        int selectedIndex = i.set(SELECTED);
        addSelectEvent(selectedIndex, deselectedIndex, value);
    }
    private void addSelectEvent(int selectIndex, int deselectIndex, E value) {
        addDeselectedDelete(deselectIndex, value);
        addSelectedInsert(selectIndex, value);
    }
    private void addDeselectEvent(BarcodeIterator i) {
        E value = source.get(i.getIndex());
        int selectedIndex = i.getColourIndex(SELECTED);
        int deselectedIndex = i.set(DESELECTED);
        addDeselectEvent(selectedIndex, deselectedIndex, value);
    }
    private void addDeselectEvent(int selectIndex, int deselectIndex, E value) {
        addSelectedDelete(selectIndex, value);
        addDeselectedInsert(deselectIndex, value);
    }

    private void addSelectedInsert(int index, E newValue){
        if(selectedList != null) selectedList.updates().elementInserted(index, newValue);
        if(selectedToggleList != null) selectedToggleList.updates().elementInserted(index, newValue);
    }
    private void addSelectedUpdate(int index, E oldValue, E newValue){
        if(selectedList != null) selectedList.updates().elementUpdated(index, oldValue, newValue);
        if(selectedToggleList != null) selectedToggleList.updates().elementUpdated(index, oldValue, newValue);
    }
    private void addSelectedDelete(int index, E oldValue){
        if(selectedList != null) selectedList.updates().elementDeleted(index, oldValue);
        if(selectedToggleList != null) selectedToggleList.updates().elementDeleted(index, oldValue);
    }
    private void addDeselectedInsert(int index, E value){
        if(deselectedList != null) deselectedList.updates().elementInserted(index, value);
        if(deselectedToggleList != null) deselectedToggleList.updates().elementInserted(index, value);
    }
    private void addDeselectedDelete(int index, E oldValue){
        if(deselectedList != null) deselectedList.updates().elementDeleted(index, oldValue);
        if(deselectedToggleList != null) deselectedToggleList.updates().elementDeleted(index, oldValue);
    }
    private void addDeselectedUpdate(int index, E oldValue, E newValue) {
        if(deselectedList != null) deselectedList.updates().elementUpdated(index, oldValue, newValue);
        if(deselectedToggleList != null) deselectedToggleList.updates().elementUpdated(index, oldValue, newValue);
    }


    private void beginAll() {
        beginSelected();
        beginDeselected();
    }
    private void commitAll() {
        commitSelected();
        commitDeselected();
    }
    private void beginSelected() {
        if(selectedList != null) {
            selectedList.updates().beginEvent();
        }
        if(selectedToggleList != null) {
            selectedToggleList.updates().beginEvent();
        }
    }
    private void commitSelected() {
        if(selectedList != null) {
            selectedList.updates().commitEvent();
        }
        if(selectedToggleList != null) {
            selectedToggleList.updates().commitEvent();
        }
    }
    private void beginDeselected() {
        if(deselectedList != null) deselectedList.updates().beginEvent();
        if(deselectedToggleList != null) deselectedToggleList.updates().beginEvent();
    }
    private void commitDeselected() {
        if(deselectedList != null) deselectedList.updates().commitEvent();
        if(deselectedToggleList != null) deselectedToggleList.updates().commitEvent();
    }

    /**
     * Set the selection mode.
     */
    public void setSelectionMode(int selectionMode) {
        this.selectionMode = selectionMode;
        setSelection(getMinSelectionIndex(), getMaxSelectionIndex());
    }

    /**
     * Returns the current selection mode.
     */
    public int getSelectionMode() {
        return selectionMode;
    }

    /**
     * Returns the first selected index or -1 if nothing is selected.
     */
    public int getMinSelectionIndex() {
        if(barcode.colourSize(SELECTED) == 0) return -1;
        return barcode.getIndex(0, SELECTED);
    }

    /**
     * Returns the last selected index or -1 if nothing is selected.
     */
    public int getMaxSelectionIndex() {
        if(barcode.colourSize(SELECTED) == 0) return -1;
        return barcode.getIndex(barcode.colourSize(SELECTED) - 1, SELECTED);
    }

    /**
     * Walks through the union of the specified ranges. All values in the
     * first range are given the specified selection value. All values in
     * the second range but not in the first range are given the opposite
     * selection value. In effect, the first range and the intersection of
     * the two ranges are given the specified value. The parts that are
     * in the second range but not in the first range (ie. everything else)
     * is given the opposite selection value.
     *
     * @param select true to set values in the first range as selected and
     *      the other values in the second range as not selected. false to
     *      set values in the first range as not selected and the other
     *      values in the second range as selected.
     * @param changeIndex0 one end of the first range, inclusive.
     * @param changeIndex1 the opposite end of the first range, inclusive.
     *      This may be lower than changeIndex0.
     * @param invertIndex0 one end of the second range, inclusive. To
     *      specify an empty second range, specify -1 for this value.
     * @param invertIndex1 the opposite end of the second range, inclusive.
     *      This may be lower than invertIndex0. To specify an empty second
     *      range, specify -1 for this value.
     */
    private void setSubRangeOfRange(boolean select, int changeIndex0, int changeIndex1, int invertIndex0, int invertIndex1, int oldLead, int oldAnchor) {
        // verify that the first range is legitimate
        if(changeIndex0 >= source.size() || changeIndex1 >= source.size()
        || ((changeIndex0 == -1 || changeIndex1 == -1) && changeIndex0 != changeIndex1)) {
            throw new IndexOutOfBoundsException("Invalid range for selection: " + changeIndex0 + "-" + changeIndex1 + ", list size is " + source.size());
        }
        // verify that the second range is legitimate
        if(invertIndex0 >= source.size() || invertIndex1 >= source.size()
        || ((invertIndex0 == -1 || invertIndex1 == -1) && invertIndex0 != invertIndex1)) {
            throw new IndexOutOfBoundsException("Invalid range for invert selection: " + invertIndex0 + "-" + invertIndex1 + ", list size is " + source.size());
        }

        // when the first range is empty
        if(changeIndex0 == -1 && changeIndex1 == -1) {
            // if the second range is empty, we're done
            if(invertIndex0 == -1 && invertIndex1 == -1) return;
            // otherwise set the first range to the second range and invert the goal
            changeIndex0 = invertIndex0;
            changeIndex1 = invertIndex1;
            select = !select;
        }
        // when the second range is empty
        if(invertIndex0 == -1 && invertIndex1 == -1) {
            // make this a subset of the first index which behaves the same as empty
            invertIndex0 = changeIndex0;
            invertIndex1 = changeIndex1;
        }

        // now get the change interval and invert interval
        int minChangeIndex = Math.min(changeIndex0, changeIndex1);
        int maxChangeIndex = Math.max(changeIndex0, changeIndex1);
        int minInvertIndex = Math.min(invertIndex0, invertIndex1);
        int maxInvertIndex = Math.max(invertIndex0, invertIndex1);

        // get the union of the two ranges
        int minUnionIndex = Math.min(minChangeIndex, minInvertIndex);
        int maxUnionIndex = Math.max(maxChangeIndex, maxInvertIndex);

        int minChangedIndex = maxUnionIndex + 1;
        int maxChangedIndex = minUnionIndex - 1;
        beginAll();

        // walk through the effected range updating selection
        for(int i = minUnionIndex; i <= maxUnionIndex; i++) {
            int selectionIndex = barcode.getColourIndex(i, SELECTED);
            boolean selectedBefore = (selectionIndex != -1);
            boolean inChangeRange = (i >= minChangeIndex && i <= maxChangeIndex);
            boolean selectedAfter = (inChangeRange == select) && isSelectable(i);

            // when there's a change
            if(selectedBefore != selectedAfter) {
                E value = source.get(i);

                // update change range
                if(i < minChangedIndex) minChangedIndex = i;
                if(i > maxChangedIndex) maxChangedIndex = i;

                // it is being deselected
                if(selectedBefore) {
                    barcode.set(i, DESELECTED, 1);
                    addDeselectEvent(selectionIndex, i - selectionIndex, value);

                // it is being selected
                } else {
                    barcode.set(i, SELECTED, 1);
                    int newSelectionIndex = barcode.getColourIndex(i, SELECTED);
                    addSelectEvent(newSelectionIndex, i - newSelectionIndex, value);
                }
            }
        }
        commitAll();

        // consider the original lead/anchor indexes, if any, when firing the "selection changed" event
        // (this forces a redraw of the old lead/anchor rows when the lead/anchor changes)
        if (oldLead != -1) {
            minChangedIndex = Math.min(minChangedIndex, oldLead);
            maxChangedIndex = Math.max(maxChangedIndex, oldLead);
        }

        if (oldAnchor != -1) {
            minChangedIndex = Math.min(minChangedIndex, oldAnchor);
            maxChangedIndex = Math.max(maxChangedIndex, oldAnchor);
        }

        // notify selection listeners
        if(minChangedIndex <= maxChangedIndex) fireSelectionChanged(minChangedIndex, maxChangedIndex);
    }

    /**
     * Checks the {@link #validSelectionMatchers} to determine if the value at
     * the given <code>index</code> is allowed to be selected.
     *
     * @param index the index to check
     * @return <tt>true</tt> if the index can be selected; <tt>false</tt>
     *      otherwise
     */
    private boolean isSelectable(int index) {
        // no matchers implies the index is selectable
        if (validSelectionMatchers.isEmpty())
            return true;

        // otherwise fetch the row object and validate it against all matchers
        final E rowObject = source.get(index);
        for (Iterator<Matcher<E>> iterator = validSelectionMatchers.iterator(); iterator.hasNext();)
            if (!iterator.next().matches(rowObject))
                return false;

        return true;
    }

    /**
     * Register a {@link ca.odell.glazedlists.ListSelection.Listener Listener}
     * that will be notified when selection is changed.
     */
    public void addSelectionListener(Listener selectionListener) {
        selectionListeners.add(selectionListener);
    }

    /**
     * Remove a {@link ca.odell.glazedlists.ListSelection.Listener Listener}
     * so that it will no longer be notified when selection changes.
     */
    public void removeSelectionListener(Listener selectionListener) {
        selectionListeners.remove(selectionListener);
    }

    /**
     * Fire changes in selection to all registered listeners.
     */
    private void fireSelectionChanged(int start, int end) {
        // notify all
        for(Iterator<Listener> i = selectionListeners.iterator(); i.hasNext(); ) {
            i.next().selectionChanged(start, end);
        }
    }

    /**
     * Disposes of this ListSelection freeing up it's resources for
     * garbage collection.  It is an error to use a ListSelection after
     * dispose() has been called.
     */
    public void dispose() {
        source.removeListEventListener(this);
        selectionListeners.clear();

        // detach the publisher dependencies
        if(selectedList != null) source.getPublisher().clearRelatedListener(selectedList, this);
        if(deselectedList != null) source.getPublisher().clearRelatedListener(deselectedList, this);
        if(selectedToggleList != null) source.getPublisher().clearRelatedListener(selectedToggleList, this);
        if(deselectedToggleList != null) source.getPublisher().clearRelatedListener(deselectedToggleList, this);
    }

    /**
     * A generic interface to respond to changes in selection that doesn't
     * require including a particular GUI toolkit.
     */
    public interface Listener {

        /**
         * Notifies this SelectionListener of a change in selection.
         *
         * @param changeStart The first zero-relative index affected by a change in selection.
         * @param changeEnd   The last zero-relative index affected by a change in selection.
         */
        public void selectionChanged(int changeStart, int changeEnd);

    }

    /**
     * The {@link EventList} that contains only values that are currently
     * selected.
     */
    private class SelectedList<E> extends TransformedList<E, E> {

        /**
         * Creates an {@link EventList} that provides a view of the
         * selected items in a ListSelection.
         */
        SelectedList(EventList<E> source) {
            super(source);
        }

        /** {@inheritDoc} */
        @Override
        public int size() {
            return barcode.colourSize(SELECTED);
        }

        /** {@inheritDoc} */
        @Override
        protected int getSourceIndex(int mutationIndex) {
            return barcode.getIndex(mutationIndex, SELECTED);
        }

        /** {@inheritDoc} */
        @Override
        public void listChanged(ListEvent<E> listChanges) {
            // Do nothing as all state changes are handled in ListSelection.listChanged()
        }

        /**
         * This allows access to the EventAssembler for this list.
         */
        public ListEventAssembler<E> updates() {
            return updates;
        }

        /** {@inheritDoc} */
        @Override
        protected boolean isWritable() {
            return true;
        }

        /**
         * A no-op dispose method to prevent the user from shooting themselves
         * in the foot. To dispose a {@link ListSelection}, call
         * {@link ListSelection#dispose()} on that class directly.
         */
        @Override
        public void dispose() {
            // Do Nothing
        }
    }

    /**
     * A SelectedList that mutates the selection instead of the underlying list.
     */
    private class SelectionToggleList<E> extends SelectedList<E>{

        SelectionToggleList(EventList<E> source) {
            super(source);
        }

        /** @throws UnsupportedOperationException unconditionally */
        @Override
        public E set(int index, E item){
            throw new UnsupportedOperationException("Toggling lists don't support setting items");
        }

        /**
         * Select the specified value in the source list, regardless of its
         * index. If the given item is found in the source list, it is selected.
         *
         * @throws IllegalArgumentException if the element isn't found
         */
        @Override
        public void add(int index, E item) {
            index = source.indexOf(item);
            if(index != -1) {
                select(index);
            } else {
                throw new IllegalArgumentException("Added item " + item + " must be in source list");
            }
        }

        /**
         * Deselect the specified index.
         */
        @Override
        public E remove(int index){
            if(index < 0 || index >= size()) throw new IndexOutOfBoundsException("Cannot remove at " + index + " on list of size " + size());
            int sourceIndex = getSourceIndex(index);
            deselect(sourceIndex);
            return source.get(sourceIndex);
        }
    }

    /**
     * The {@link EventList} that contains only values that are not currently
     * selected.
     */
    private class DeselectedList<E> extends TransformedList<E, E> {

        /**
         * Creates an {@link EventList} that provides a view of the
         * deselected items in a ListSelection.
         */
        DeselectedList(EventList<E> source) {
            super(source);
        }

        /** {@inheritDoc} */
        @Override
        public int size() {
            return barcode.colourSize(DESELECTED);
        }

        /** {@inheritDoc} */
        @Override
        protected int getSourceIndex(int mutationIndex) {
            return barcode.getIndex(mutationIndex, DESELECTED);
        }

        /** {@inheritDoc} */
        @Override
        public void listChanged(ListEvent<E> listChanges) {
            // Do nothing as all state changes are handled in ListSelection.listChanged()
        }

        /**
         * This allows access to the EventAssembler for this list.
         */
        public ListEventAssembler<E> updates() {
            return updates;
        }

        /** {@inheritDoc} */
        @Override
        protected boolean isWritable() {
            return true;
        }

        /**
         * A no-op dispose method to prevent the user from shooting themselves
         * in the foot. To dispose a {@link ListSelection}, call
         * {@link ListSelection#dispose()} on that class directly.
         */
        @Override
        public void dispose() {
            // Do Nothing
        }
    }

    /**
     * A DeselectedList that mutates the selection instead of the underlying list.
     */
    private class DeselectionToggleList<E> extends DeselectedList<E>{

        DeselectionToggleList(EventList<E> source) {
            super(source);
        }

        /** @throws UnsupportedOperationException unconditionally */
        @Override
        public E set(int index, E item){
            throw new UnsupportedOperationException("Toggling lists don't support setting items");
        }

        /**
         * Deselect the specified value.
         *
         * @throws IllegalArgumentException if the element isn't found
         */
        @Override
        public void add(int index, E item) {
            index = source.indexOf(item);
            if(index != -1) {
                deselect(index);
            } else {
                throw new IllegalArgumentException("Added item " + item + " must be in source list");
            }
        }

        /**
         * Select the specified index.
         */
        @Override
        public E remove(int index){
            if(index < 0 || index >= size()) throw new IndexOutOfBoundsException("Cannot remove at " + index + " on list of size " + size());
            int sourceIndex = getSourceIndex(index);
            select(sourceIndex);
            return source.get(sourceIndex);
        }
    }
}