1 /*
2  * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 package javax.swing.text.html;
26 
27 import javax.swing.*;
28 import javax.swing.event.*;
29 import java.util.BitSet;
30 import java.io.Serializable;
31 
32 
33 /**
34  * This class extends DefaultListModel, and also implements
35  * the ListSelectionModel interface, allowing for it to store state
36  * relevant to a SELECT form element which is implemented as a List.
37  * If SELECT has a size attribute whose value is greater than 1,
38  * or if allows multiple selection then a JList is used to
39  * represent it and the OptionListModel is used as its model.
40  * It also stores the initial state of the JList, to ensure an
41  * accurate reset, if the user requests a reset of the form.
42  *
43  * @author Sunita Mani
44  */
45 @SuppressWarnings("serial") // Superclass is not serializable across versions
46 class OptionListModel<E> extends DefaultListModel<E> implements ListSelectionModel, Serializable {
47 
48 
49     private static final int MIN = -1;
50     private static final int MAX = Integer.MAX_VALUE;
51     private int selectionMode = SINGLE_SELECTION;
52     private int minIndex = MAX;
53     private int maxIndex = MIN;
54     private int anchorIndex = -1;
55     private int leadIndex = -1;
56     private int firstChangedIndex = MAX;
57     private int lastChangedIndex = MIN;
58     private boolean isAdjusting = false;
59     private BitSet value = new BitSet(32);
60     private BitSet initialValue = new BitSet(32);
61     protected EventListenerList listenerList = new EventListenerList();
62 
63     protected boolean leadAnchorNotificationEnabled = true;
64 
getMinSelectionIndex()65     public int getMinSelectionIndex() { return isSelectionEmpty() ? -1 : minIndex; }
66 
getMaxSelectionIndex()67     public int getMaxSelectionIndex() { return maxIndex; }
68 
getValueIsAdjusting()69     public boolean getValueIsAdjusting() { return isAdjusting; }
70 
getSelectionMode()71     public int getSelectionMode() { return selectionMode; }
72 
setSelectionMode(int selectionMode)73     public void setSelectionMode(int selectionMode) {
74         switch (selectionMode) {
75         case SINGLE_SELECTION:
76         case SINGLE_INTERVAL_SELECTION:
77         case MULTIPLE_INTERVAL_SELECTION:
78             this.selectionMode = selectionMode;
79             break;
80         default:
81             throw new IllegalArgumentException("invalid selectionMode");
82         }
83     }
84 
isSelectedIndex(int index)85     public boolean isSelectedIndex(int index) {
86         return ((index < minIndex) || (index > maxIndex)) ? false : value.get(index);
87     }
88 
isSelectionEmpty()89     public boolean isSelectionEmpty() {
90         return (minIndex > maxIndex);
91     }
92 
addListSelectionListener(ListSelectionListener l)93     public void addListSelectionListener(ListSelectionListener l) {
94         listenerList.add(ListSelectionListener.class, l);
95     }
96 
removeListSelectionListener(ListSelectionListener l)97     public void removeListSelectionListener(ListSelectionListener l) {
98         listenerList.remove(ListSelectionListener.class, l);
99     }
100 
101     /**
102      * Returns an array of all the <code>ListSelectionListener</code>s added
103      * to this OptionListModel with addListSelectionListener().
104      *
105      * @return all of the <code>ListSelectionListener</code>s added or an empty
106      *         array if no listeners have been added
107      * @since 1.4
108      */
getListSelectionListeners()109     public ListSelectionListener[] getListSelectionListeners() {
110         return listenerList.getListeners(ListSelectionListener.class);
111     }
112 
113     /**
114      * Notify listeners that we are beginning or ending a
115      * series of value changes
116      */
fireValueChanged(boolean isAdjusting)117     protected void fireValueChanged(boolean isAdjusting) {
118         fireValueChanged(getMinSelectionIndex(), getMaxSelectionIndex(), isAdjusting);
119     }
120 
121 
122     /**
123      * Notify ListSelectionListeners that the value of the selection,
124      * in the closed interval firstIndex,lastIndex, has changed.
125      */
fireValueChanged(int firstIndex, int lastIndex)126     protected void fireValueChanged(int firstIndex, int lastIndex) {
127         fireValueChanged(firstIndex, lastIndex, getValueIsAdjusting());
128     }
129 
130     /**
131      * @param firstIndex The first index in the interval.
132      * @param lastIndex The last index in the interval.
133      * @param isAdjusting True if this is the final change in a series of them.
134      * @see EventListenerList
135      */
fireValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)136     protected void fireValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
137     {
138         Object[] listeners = listenerList.getListenerList();
139         ListSelectionEvent e = null;
140 
141         for (int i = listeners.length - 2; i >= 0; i -= 2) {
142             if (listeners[i] == ListSelectionListener.class) {
143                 if (e == null) {
144                     e = new ListSelectionEvent(this, firstIndex, lastIndex, isAdjusting);
145                 }
146                 ((ListSelectionListener)listeners[i+1]).valueChanged(e);
147             }
148         }
149     }
150 
fireValueChanged()151     private void fireValueChanged() {
152         if (lastChangedIndex == MIN) {
153             return;
154         }
155         /* Change the values before sending the event to the
156          * listeners in case the event causes a listener to make
157          * another change to the selection.
158          */
159         int oldFirstChangedIndex = firstChangedIndex;
160         int oldLastChangedIndex = lastChangedIndex;
161         firstChangedIndex = MAX;
162         lastChangedIndex = MIN;
163         fireValueChanged(oldFirstChangedIndex, oldLastChangedIndex);
164     }
165 
166 
167     // Update first and last change indices
markAsDirty(int r)168     private void markAsDirty(int r) {
169         firstChangedIndex = Math.min(firstChangedIndex, r);
170         lastChangedIndex =  Math.max(lastChangedIndex, r);
171     }
172 
173     // Set the state at this index and update all relevant state.
set(int r)174     private void set(int r) {
175         if (value.get(r)) {
176             return;
177         }
178         value.set(r);
179         Option option = (Option)get(r);
180         option.setSelection(true);
181         markAsDirty(r);
182 
183         // Update minimum and maximum indices
184         minIndex = Math.min(minIndex, r);
185         maxIndex = Math.max(maxIndex, r);
186     }
187 
188     // Clear the state at this index and update all relevant state.
clear(int r)189     private void clear(int r) {
190         if (!value.get(r)) {
191             return;
192         }
193         value.clear(r);
194         Option option = (Option)get(r);
195         option.setSelection(false);
196         markAsDirty(r);
197 
198         // Update minimum and maximum indices
199         /*
200            If (r > minIndex) the minimum has not changed.
201            The case (r < minIndex) is not possible because r'th value was set.
202            We only need to check for the case when lowest entry has been cleared,
203            and in this case we need to search for the first value set above it.
204         */
205         if (r == minIndex) {
206             for(minIndex = minIndex + 1; minIndex <= maxIndex; minIndex++) {
207                 if (value.get(minIndex)) {
208                     break;
209                 }
210             }
211         }
212         /*
213            If (r < maxIndex) the maximum has not changed.
214            The case (r > maxIndex) is not possible because r'th value was set.
215            We only need to check for the case when highest entry has been cleared,
216            and in this case we need to search for the first value set below it.
217         */
218         if (r == maxIndex) {
219             for(maxIndex = maxIndex - 1; minIndex <= maxIndex; maxIndex--) {
220                 if (value.get(maxIndex)) {
221                     break;
222                 }
223             }
224         }
225         /* Performance note: This method is called from inside a loop in
226            changeSelection() but we will only iterate in the loops
227            above on the basis of one iteration per deselected cell - in total.
228            Ie. the next time this method is called the work of the previous
229            deselection will not be repeated.
230 
231            We also don't need to worry about the case when the min and max
232            values are in their unassigned states. This cannot happen because
233            this method's initial check ensures that the selection was not empty
234            and therefore that the minIndex and maxIndex had 'real' values.
235 
236            If we have cleared the whole selection, set the minIndex and maxIndex
237            to their cannonical values so that the next set command always works
238            just by using Math.min and Math.max.
239         */
240         if (isSelectionEmpty()) {
241             minIndex = MAX;
242             maxIndex = MIN;
243         }
244     }
245 
246     /**
247      * Sets the value of the leadAnchorNotificationEnabled flag.
248      * @see             #isLeadAnchorNotificationEnabled()
249      */
setLeadAnchorNotificationEnabled(boolean flag)250     public void setLeadAnchorNotificationEnabled(boolean flag) {
251         leadAnchorNotificationEnabled = flag;
252     }
253 
254     /**
255      * Returns the value of the leadAnchorNotificationEnabled flag.
256      * When leadAnchorNotificationEnabled is true the model
257      * generates notification events with bounds that cover all the changes to
258      * the selection plus the changes to the lead and anchor indices.
259      * Setting the flag to false causes a norrowing of the event's bounds to
260      * include only the elements that have been selected or deselected since
261      * the last change. Either way, the model continues to maintain the lead
262      * and anchor variables internally. The default is true.
263      * @return          the value of the leadAnchorNotificationEnabled flag
264      * @see             #setLeadAnchorNotificationEnabled(boolean)
265      */
isLeadAnchorNotificationEnabled()266     public boolean isLeadAnchorNotificationEnabled() {
267         return leadAnchorNotificationEnabled;
268     }
269 
updateLeadAnchorIndices(int anchorIndex, int leadIndex)270     private void updateLeadAnchorIndices(int anchorIndex, int leadIndex) {
271         if (leadAnchorNotificationEnabled) {
272             if (this.anchorIndex != anchorIndex) {
273                 if (this.anchorIndex != -1) { // The unassigned state.
274                     markAsDirty(this.anchorIndex);
275                 }
276                 markAsDirty(anchorIndex);
277             }
278 
279             if (this.leadIndex != leadIndex) {
280                 if (this.leadIndex != -1) { // The unassigned state.
281                     markAsDirty(this.leadIndex);
282                 }
283                 markAsDirty(leadIndex);
284             }
285         }
286         this.anchorIndex = anchorIndex;
287         this.leadIndex = leadIndex;
288     }
289 
contains(int a, int b, int i)290     private boolean contains(int a, int b, int i) {
291         return (i >= a) && (i <= b);
292     }
293 
changeSelection(int clearMin, int clearMax, int setMin, int setMax, boolean clearFirst)294     private void changeSelection(int clearMin, int clearMax,
295                                  int setMin, int setMax, boolean clearFirst) {
296         for(int i = Math.min(setMin, clearMin); i <= Math.max(setMax, clearMax); i++) {
297 
298             boolean shouldClear = contains(clearMin, clearMax, i);
299             boolean shouldSet = contains(setMin, setMax, i);
300 
301             if (shouldSet && shouldClear) {
302                 if (clearFirst) {
303                     shouldClear = false;
304                 }
305                 else {
306                     shouldSet = false;
307                 }
308             }
309 
310             if (shouldSet) {
311                 set(i);
312             }
313             if (shouldClear) {
314                 clear(i);
315             }
316         }
317         fireValueChanged();
318     }
319 
320    /*   Change the selection with the effect of first clearing the values
321     *   in the inclusive range [clearMin, clearMax] then setting the values
322     *   in the inclusive range [setMin, setMax]. Do this in one pass so
323     *   that no values are cleared if they would later be set.
324     */
changeSelection(int clearMin, int clearMax, int setMin, int setMax)325     private void changeSelection(int clearMin, int clearMax, int setMin, int setMax) {
326         changeSelection(clearMin, clearMax, setMin, setMax, true);
327     }
328 
clearSelection()329     public void clearSelection() {
330         removeSelectionInterval(minIndex, maxIndex);
331     }
332 
setSelectionInterval(int index0, int index1)333     public void setSelectionInterval(int index0, int index1) {
334         if (index0 == -1 || index1 == -1) {
335             return;
336         }
337 
338         if (getSelectionMode() == SINGLE_SELECTION) {
339             index0 = index1;
340         }
341 
342         updateLeadAnchorIndices(index0, index1);
343 
344         int clearMin = minIndex;
345         int clearMax = maxIndex;
346         int setMin = Math.min(index0, index1);
347         int setMax = Math.max(index0, index1);
348         changeSelection(clearMin, clearMax, setMin, setMax);
349     }
350 
addSelectionInterval(int index0, int index1)351     public void addSelectionInterval(int index0, int index1)
352     {
353         if (index0 == -1 || index1 == -1) {
354             return;
355         }
356 
357         if (getSelectionMode() != MULTIPLE_INTERVAL_SELECTION) {
358             setSelectionInterval(index0, index1);
359             return;
360         }
361 
362         updateLeadAnchorIndices(index0, index1);
363 
364         int clearMin = MAX;
365         int clearMax = MIN;
366         int setMin = Math.min(index0, index1);
367         int setMax = Math.max(index0, index1);
368         changeSelection(clearMin, clearMax, setMin, setMax);
369     }
370 
371 
removeSelectionInterval(int index0, int index1)372     public void removeSelectionInterval(int index0, int index1)
373     {
374         if (index0 == -1 || index1 == -1) {
375             return;
376         }
377 
378         updateLeadAnchorIndices(index0, index1);
379 
380         int clearMin = Math.min(index0, index1);
381         int clearMax = Math.max(index0, index1);
382         int setMin = MAX;
383         int setMax = MIN;
384         changeSelection(clearMin, clearMax, setMin, setMax);
385     }
386 
setState(int index, boolean state)387     private void setState(int index, boolean state) {
388         if (state) {
389             set(index);
390         }
391         else {
392             clear(index);
393         }
394     }
395 
396     /**
397      * Insert length indices beginning before/after index. If the value
398      * at index is itself selected, set all of the newly inserted
399      * items, otherwise leave them unselected. This method is typically
400      * called to sync the selection model with a corresponding change
401      * in the data model.
402      */
insertIndexInterval(int index, int length, boolean before)403     public void insertIndexInterval(int index, int length, boolean before)
404     {
405         /* The first new index will appear at insMinIndex and the last
406          * one will appear at insMaxIndex
407          */
408         int insMinIndex = (before) ? index : index + 1;
409         int insMaxIndex = (insMinIndex + length) - 1;
410 
411         /* Right shift the entire bitset by length, beginning with
412          * index-1 if before is true, index+1 if it's false (i.e. with
413          * insMinIndex).
414          */
415         for(int i = maxIndex; i >= insMinIndex; i--) {
416             setState(i + length, value.get(i));
417         }
418 
419         /* Initialize the newly inserted indices.
420          */
421         boolean setInsertedValues = value.get(index);
422         for(int i = insMinIndex; i <= insMaxIndex; i++) {
423             setState(i, setInsertedValues);
424         }
425     }
426 
427 
428     /**
429      * Remove the indices in the interval index0,index1 (inclusive) from
430      * the selection model.  This is typically called to sync the selection
431      * model width a corresponding change in the data model.  Note
432      * that (as always) index0 can be greater than index1.
433      */
removeIndexInterval(int index0, int index1)434     public void removeIndexInterval(int index0, int index1)
435     {
436         int rmMinIndex = Math.min(index0, index1);
437         int rmMaxIndex = Math.max(index0, index1);
438         int gapLength = (rmMaxIndex - rmMinIndex) + 1;
439 
440         /* Shift the entire bitset to the left to close the index0, index1
441          * gap.
442          */
443         for(int i = rmMinIndex; i <= maxIndex; i++) {
444             setState(i, value.get(i + gapLength));
445         }
446     }
447 
448 
setValueIsAdjusting(boolean isAdjusting)449     public void setValueIsAdjusting(boolean isAdjusting) {
450         if (isAdjusting != this.isAdjusting) {
451             this.isAdjusting = isAdjusting;
452             this.fireValueChanged(isAdjusting);
453         }
454     }
455 
456 
toString()457     public String toString() {
458         String s =  ((getValueIsAdjusting()) ? "~" : "=") + value.toString();
459         return getClass().getName() + " " + Integer.toString(hashCode()) + " " + s;
460     }
461 
462     /**
463      * Returns a clone of the receiver with the same selection.
464      * <code>listenerLists</code> are not duplicated.
465      *
466      * @return a clone of the receiver
467      * @exception CloneNotSupportedException if the receiver does not
468      *    both (a) implement the <code>Cloneable</code> interface
469      *    and (b) define a <code>clone</code> method
470      */
clone()471     public Object clone() throws CloneNotSupportedException {
472         @SuppressWarnings("unchecked")
473         OptionListModel<E> clone = (OptionListModel)super.clone();
474         clone.value = (BitSet)value.clone();
475         clone.listenerList = new EventListenerList();
476         return clone;
477     }
478 
getAnchorSelectionIndex()479     public int getAnchorSelectionIndex() {
480         return anchorIndex;
481     }
482 
getLeadSelectionIndex()483     public int getLeadSelectionIndex() {
484         return leadIndex;
485     }
486 
487     /**
488      * Set the anchor selection index, leaving all selection values unchanged.
489      *
490      * @see #getAnchorSelectionIndex
491      * @see #setLeadSelectionIndex
492      */
setAnchorSelectionIndex(int anchorIndex)493     public void setAnchorSelectionIndex(int anchorIndex) {
494         this.anchorIndex = anchorIndex;
495     }
496 
497     /**
498      * Set the lead selection index, ensuring that values between the
499      * anchor and the new lead are either all selected or all deselected.
500      * If the value at the anchor index is selected, first clear all the
501      * values in the range [anchor, oldLeadIndex], then select all the values
502      * values in the range [anchor, newLeadIndex], where oldLeadIndex is the old
503      * leadIndex and newLeadIndex is the new one.
504      * <p>
505      * If the value at the anchor index is not selected, do the same thing in reverse,
506      * selecting values in the old range and deselecting values in the new one.
507      * <p>
508      * Generate a single event for this change and notify all listeners.
509      * For the purposes of generating minimal bounds in this event, do the
510      * operation in a single pass; that way the first and last index inside the
511      * ListSelectionEvent that is broadcast will refer to cells that actually
512      * changed value because of this method. If, instead, this operation were
513      * done in two steps the effect on the selection state would be the same
514      * but two events would be generated and the bounds around the changed values
515      * would be wider, including cells that had been first cleared and only
516      * to later be set.
517      * <p>
518      * This method can be used in the mouseDragged() method of a UI class
519      * to extend a selection.
520      *
521      * @see #getLeadSelectionIndex
522      * @see #setAnchorSelectionIndex
523      */
setLeadSelectionIndex(int leadIndex)524     public void setLeadSelectionIndex(int leadIndex) {
525         int anchorIndex = this.anchorIndex;
526         if (getSelectionMode() == SINGLE_SELECTION) {
527             anchorIndex = leadIndex;
528         }
529 
530         int oldMin = Math.min(this.anchorIndex, this.leadIndex);
531         int oldMax = Math.max(this.anchorIndex, this.leadIndex);
532         int newMin = Math.min(anchorIndex, leadIndex);
533         int newMax = Math.max(anchorIndex, leadIndex);
534         if (value.get(this.anchorIndex)) {
535             changeSelection(oldMin, oldMax, newMin, newMax);
536         }
537         else {
538             changeSelection(newMin, newMax, oldMin, oldMax, false);
539         }
540         this.anchorIndex = anchorIndex;
541         this.leadIndex = leadIndex;
542     }
543 
544 
545     /**
546      * This method is responsible for storing the state
547      * of the initial selection.  If the selectionMode
548      * is the default, i.e allowing only for SINGLE_SELECTION,
549      * then the very last OPTION that has the selected
550      * attribute set wins.
551      */
setInitialSelection(int i)552     public void setInitialSelection(int i) {
553         if (initialValue.get(i)) {
554             return;
555         }
556         if (selectionMode == SINGLE_SELECTION) {
557             // reset to empty
558             initialValue.and(new BitSet());
559         }
560         initialValue.set(i);
561     }
562 
563     /**
564      * Fetches the BitSet that represents the initial
565      * set of selected items in the list.
566      */
getInitialSelection()567     public BitSet getInitialSelection() {
568         return initialValue;
569     }
570 }
571