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