1. /*
  2. * @(#)DefaultListSelectionModel.java 1.53 01/11/29
  3. *
  4. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing;
  8. import java.util.EventListener;
  9. import java.util.BitSet;
  10. import java.io.Serializable;
  11. import javax.swing.event.*;
  12. /**
  13. * Default data model for list selections.
  14. * <p>
  15. * <strong>Warning:</strong>
  16. * Serialized objects of this class will not be compatible with
  17. * future Swing releases. The current serialization support is appropriate
  18. * for short term storage or RMI between applications running the same
  19. * version of Swing. A future release of Swing will provide support for
  20. * long term persistence.
  21. *
  22. * @version 1.53 11/29/01
  23. * @author Philip Milne
  24. * @author Hans Muller
  25. * @see ListSelectionModel
  26. */
  27. public class DefaultListSelectionModel implements ListSelectionModel, Cloneable, Serializable
  28. {
  29. private static final int MIN = -1;
  30. private static final int MAX = Integer.MAX_VALUE;
  31. private int selectionMode = MULTIPLE_INTERVAL_SELECTION;
  32. private int minIndex = MAX;
  33. private int maxIndex = MIN;
  34. private int anchorIndex = -1;
  35. private int leadIndex = -1;
  36. private int firstAdjustedIndex = MAX;
  37. private int lastAdjustedIndex = MIN;
  38. private boolean isAdjusting = false;
  39. private int firstChangedIndex = MAX;
  40. private int lastChangedIndex = MIN;
  41. private BitSet value = new BitSet(32);
  42. protected EventListenerList listenerList = new EventListenerList();
  43. protected boolean leadAnchorNotificationEnabled = true;
  44. // implements javax.swing.ListSelectionModel
  45. public int getMinSelectionIndex() { return isSelectionEmpty() ? -1 : minIndex; }
  46. // implements javax.swing.ListSelectionModel
  47. public int getMaxSelectionIndex() { return maxIndex; }
  48. // implements javax.swing.ListSelectionModel
  49. public boolean getValueIsAdjusting() { return isAdjusting; }
  50. // implements javax.swing.ListSelectionModel
  51. public int getSelectionMode() { return selectionMode; }
  52. // implements javax.swing.ListSelectionModel
  53. public void setSelectionMode(int selectionMode) {
  54. switch (selectionMode) {
  55. case SINGLE_SELECTION:
  56. case SINGLE_INTERVAL_SELECTION:
  57. case MULTIPLE_INTERVAL_SELECTION:
  58. this.selectionMode = selectionMode;
  59. break;
  60. default:
  61. throw new IllegalArgumentException("invalid selectionMode");
  62. }
  63. }
  64. // implements javax.swing.ListSelectionModel
  65. public boolean isSelectedIndex(int index) {
  66. return ((index < minIndex) || (index > maxIndex)) ? false : value.get(index);
  67. }
  68. // implements javax.swing.ListSelectionModel
  69. public boolean isSelectionEmpty() {
  70. return (minIndex > maxIndex);
  71. }
  72. // implements javax.swing.ListSelectionModel
  73. public void addListSelectionListener(ListSelectionListener l) {
  74. listenerList.add(ListSelectionListener.class, l);
  75. }
  76. // implements javax.swing.ListSelectionModel
  77. public void removeListSelectionListener(ListSelectionListener l) {
  78. listenerList.remove(ListSelectionListener.class, l);
  79. }
  80. /**
  81. * Notify listeners that we have ended a series of adjustments.
  82. */
  83. protected void fireValueChanged(boolean isAdjusting) {
  84. if (lastChangedIndex == MIN) {
  85. return;
  86. }
  87. /* Change the values before sending the event to the
  88. * listeners in case the event causes a listener to make
  89. * another change to the selection.
  90. */
  91. int oldFirstChangedIndex = firstChangedIndex;
  92. int oldLastChangedIndex = lastChangedIndex;
  93. firstChangedIndex = MAX;
  94. lastChangedIndex = MIN;
  95. fireValueChanged(oldFirstChangedIndex, oldLastChangedIndex, isAdjusting);
  96. }
  97. /**
  98. * Notify ListSelectionListeners that the value of the selection,
  99. * in the closed interval firstIndex,lastIndex, has changed.
  100. */
  101. protected void fireValueChanged(int firstIndex, int lastIndex) {
  102. fireValueChanged(firstIndex, lastIndex, getValueIsAdjusting());
  103. }
  104. /**
  105. * @param firstIndex The first index in the interval.
  106. * @param index1 The last index in the interval.
  107. * @param isAdjusting True if this is the final change in a series of them.
  108. * @see EventListenerList
  109. */
  110. protected void fireValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
  111. {
  112. Object[] listeners = listenerList.getListenerList();
  113. ListSelectionEvent e = null;
  114. for (int i = listeners.length - 2; i >= 0; i -= 2) {
  115. if (listeners[i] == ListSelectionListener.class) {
  116. if (e == null) {
  117. e = new ListSelectionEvent(this, firstIndex, lastIndex, isAdjusting);
  118. }
  119. ((ListSelectionListener)listeners[i+1]).valueChanged(e);
  120. }
  121. }
  122. }
  123. private void fireValueChanged() {
  124. if (lastAdjustedIndex == MIN) {
  125. return;
  126. }
  127. /* If getValueAdjusting() is true, (eg. during a drag opereration)
  128. * record the bounds of the changes so that, when the drag finishes (and
  129. * setValueAdjusting(false) is called) we can post a single event
  130. * with bounds covering all of these individual adjustments.
  131. */
  132. if (getValueIsAdjusting()) {
  133. firstChangedIndex = Math.min(firstChangedIndex, firstAdjustedIndex);
  134. lastChangedIndex = Math.max(lastChangedIndex, lastAdjustedIndex);
  135. }
  136. /* Change the values before sending the event to the
  137. * listeners in case the event causes a listener to make
  138. * another change to the selection.
  139. */
  140. int oldFirstAdjustedIndex = firstAdjustedIndex;
  141. int oldLastAdjustedIndex = lastAdjustedIndex;
  142. firstAdjustedIndex = MAX;
  143. lastAdjustedIndex = MIN;
  144. fireValueChanged(oldFirstAdjustedIndex, oldLastAdjustedIndex);
  145. }
  146. // Update first and last change indices
  147. private void markAsDirty(int r) {
  148. firstAdjustedIndex = Math.min(firstAdjustedIndex, r);
  149. lastAdjustedIndex = Math.max(lastAdjustedIndex, r);
  150. }
  151. // Set the state at this index and update all relevant state.
  152. private void set(int r) {
  153. if (value.get(r)) {
  154. return;
  155. }
  156. value.set(r);
  157. markAsDirty(r);
  158. // Update minimum and maximum indices
  159. minIndex = Math.min(minIndex, r);
  160. maxIndex = Math.max(maxIndex, r);
  161. }
  162. // Clear the state at this index and update all relevant state.
  163. private void clear(int r) {
  164. if (!value.get(r)) {
  165. return;
  166. }
  167. value.clear(r);
  168. markAsDirty(r);
  169. // Update minimum and maximum indices
  170. /*
  171. If (r > minIndex) the minimum has not changed.
  172. The case (r < minIndex) is not possible because r'th value was set.
  173. We only need to check for the case when lowest entry has been cleared,
  174. and in this case we need to search for the first value set above it.
  175. */
  176. if (r == minIndex) {
  177. for(minIndex = minIndex + 1; minIndex <= maxIndex; minIndex++) {
  178. if (value.get(minIndex)) {
  179. break;
  180. }
  181. }
  182. }
  183. /*
  184. If (r < maxIndex) the maximum has not changed.
  185. The case (r > maxIndex) is not possible because r'th value was set.
  186. We only need to check for the case when highest entry has been cleared,
  187. and in this case we need to search for the first value set below it.
  188. */
  189. if (r == maxIndex) {
  190. for(maxIndex = maxIndex - 1; minIndex <= maxIndex; maxIndex--) {
  191. if (value.get(maxIndex)) {
  192. break;
  193. }
  194. }
  195. }
  196. /* Performance note: This method is called from inside a loop in
  197. changeSelection() but we will only iterate in the loops
  198. above on the basis of one iteration per deselected cell - in total.
  199. Ie. the next time this method is called the work of the previous
  200. deselection will not be repeated.
  201. We also don't need to worry about the case when the min and max
  202. values are in their unassigned states. This cannot happen because
  203. this method's initial check ensures that the selection was not empty
  204. and therefore that the minIndex and maxIndex had 'real' values.
  205. If we have cleared the whole selection, set the minIndex and maxIndex
  206. to their cannonical values so that the next set command always works
  207. just by using Math.min and Math.max.
  208. */
  209. if (isSelectionEmpty()) {
  210. minIndex = MAX;
  211. maxIndex = MIN;
  212. }
  213. }
  214. /**
  215. * Sets the value of the leadAnchorNotificationEnabled flag.
  216. * @see #isLeadAnchorNotificationEnabled()
  217. */
  218. public void setLeadAnchorNotificationEnabled(boolean flag) {
  219. leadAnchorNotificationEnabled = flag;
  220. }
  221. /**
  222. * Returns the value of the leadAnchorNotificationEnabled flag.
  223. * When leadAnchorNotificationEnabled is true the model
  224. * generates notification events with bounds that cover all the changes to
  225. * the selection plus the changes to the lead and anchor indices.
  226. * Setting the flag to false causes a norrowing of the event's bounds to
  227. * include only the elements that have been selected or deselected since
  228. * the last change. Either way, the model continues to maintain the lead
  229. * and anchor variables internally. The default is true.
  230. * @return the value of the leadAnchorNotificationEnabled flag
  231. * @see #setLeadAnchorNotificationEnabled(boolean)
  232. */
  233. public boolean isLeadAnchorNotificationEnabled() {
  234. return leadAnchorNotificationEnabled;
  235. }
  236. private void updateLeadAnchorIndices(int anchorIndex, int leadIndex) {
  237. if (leadAnchorNotificationEnabled) {
  238. if (this.anchorIndex != anchorIndex) {
  239. if (this.anchorIndex != -1) { // The unassigned state.
  240. markAsDirty(this.anchorIndex);
  241. }
  242. markAsDirty(anchorIndex);
  243. }
  244. if (this.leadIndex != leadIndex) {
  245. if (this.leadIndex != -1) { // The unassigned state.
  246. markAsDirty(this.leadIndex);
  247. }
  248. markAsDirty(leadIndex);
  249. }
  250. }
  251. this.anchorIndex = anchorIndex;
  252. this.leadIndex = leadIndex;
  253. }
  254. private boolean contains(int a, int b, int i) {
  255. return (i >= a) && (i <= b);
  256. }
  257. private void changeSelection(int clearMin, int clearMax,
  258. int setMin, int setMax, boolean clearFirst) {
  259. for(int i = Math.min(setMin, clearMin); i <= Math.max(setMax, clearMax); i++) {
  260. boolean shouldClear = contains(clearMin, clearMax, i);
  261. boolean shouldSet = contains(setMin, setMax, i);
  262. if (shouldSet && shouldClear) {
  263. if (clearFirst) {
  264. shouldClear = false;
  265. }
  266. else {
  267. shouldSet = false;
  268. }
  269. }
  270. if (shouldSet) {
  271. set(i);
  272. }
  273. if (shouldClear) {
  274. clear(i);
  275. }
  276. }
  277. fireValueChanged();
  278. }
  279. /* Change the selection with the effect of first clearing the values
  280. * in the inclusive range [clearMin, clearMax] then setting the values
  281. * in the inclusive range [setMin, setMax]. Do this in one pass so
  282. * that no values are cleared if they would later be set.
  283. */
  284. private void changeSelection(int clearMin, int clearMax, int setMin, int setMax) {
  285. changeSelection(clearMin, clearMax, setMin, setMax, true);
  286. }
  287. // implements javax.swing.ListSelectionModel
  288. public void clearSelection() {
  289. removeSelectionInterval(minIndex, maxIndex);
  290. }
  291. // implements javax.swing.ListSelectionModel
  292. public void setSelectionInterval(int index0, int index1) {
  293. if (index0 == -1 || index1 == -1) {
  294. return;
  295. }
  296. if (getSelectionMode() == SINGLE_SELECTION) {
  297. index0 = index1;
  298. }
  299. updateLeadAnchorIndices(index0, index1);
  300. int clearMin = minIndex;
  301. int clearMax = maxIndex;
  302. int setMin = Math.min(index0, index1);
  303. int setMax = Math.max(index0, index1);
  304. changeSelection(clearMin, clearMax, setMin, setMax);
  305. }
  306. // implements javax.swing.ListSelectionModel
  307. public void addSelectionInterval(int index0, int index1)
  308. {
  309. if (index0 == -1 || index1 == -1) {
  310. return;
  311. }
  312. if (getSelectionMode() != MULTIPLE_INTERVAL_SELECTION) {
  313. setSelectionInterval(index0, index1);
  314. return;
  315. }
  316. updateLeadAnchorIndices(index0, index1);
  317. int clearMin = MAX;
  318. int clearMax = MIN;
  319. int setMin = Math.min(index0, index1);
  320. int setMax = Math.max(index0, index1);
  321. changeSelection(clearMin, clearMax, setMin, setMax);
  322. }
  323. // implements javax.swing.ListSelectionModel
  324. public void removeSelectionInterval(int index0, int index1)
  325. {
  326. if (index0 == -1 || index1 == -1) {
  327. return;
  328. }
  329. updateLeadAnchorIndices(index0, index1);
  330. int clearMin = Math.min(index0, index1);
  331. int clearMax = Math.max(index0, index1);
  332. int setMin = MAX;
  333. int setMax = MIN;
  334. // If the removal would produce to two disjoint selections in a mode
  335. // that only allows one, extend the removal to the end of the selection.
  336. if (getSelectionMode() != MULTIPLE_INTERVAL_SELECTION &&
  337. clearMin > minIndex && clearMax < maxIndex) {
  338. clearMax = maxIndex;
  339. }
  340. changeSelection(clearMin, clearMax, setMin, setMax);
  341. }
  342. private void setState(int index, boolean state) {
  343. if (state) {
  344. set(index);
  345. }
  346. else {
  347. clear(index);
  348. }
  349. }
  350. /**
  351. * Insert length indices beginning before/after index. If the value
  352. * at index is itself selected, set all of the newly inserted
  353. * items, otherwise leave them unselected. This method is typically
  354. * called to sync the selection model with a corresponding change
  355. * in the data model.
  356. */
  357. public void insertIndexInterval(int index, int length, boolean before)
  358. {
  359. /* The first new index will appear at insMinIndex and the last
  360. * one will appear at insMaxIndex
  361. */
  362. int insMinIndex = (before) ? index : index + 1;
  363. int insMaxIndex = (insMinIndex + length) - 1;
  364. /* Right shift the entire bitset by length, beginning with
  365. * index-1 if before is true, index+1 if it's false (i.e. with
  366. * insMinIndex).
  367. */
  368. for(int i = maxIndex; i >= insMinIndex; i--) {
  369. setState(i + length, value.get(i));
  370. }
  371. /* Initialize the newly inserted indices.
  372. */
  373. boolean setInsertedValues = value.get(index);
  374. for(int i = insMinIndex; i <= insMaxIndex; i++) {
  375. setState(i, setInsertedValues);
  376. }
  377. }
  378. /**
  379. * Remove the indices in the interval index0,index1 (inclusive) from
  380. * the selection model. This is typically called to sync the selection
  381. * model width a corresponding change in the data model. Note
  382. * that (as always) index0 need not be <= index1.
  383. */
  384. public void removeIndexInterval(int index0, int index1)
  385. {
  386. int rmMinIndex = Math.min(index0, index1);
  387. int rmMaxIndex = Math.max(index0, index1);
  388. int gapLength = (rmMaxIndex - rmMinIndex) + 1;
  389. /* Shift the entire bitset to the left to close the index0, index1
  390. * gap.
  391. */
  392. for(int i = rmMinIndex; i <= maxIndex; i++) {
  393. setState(i, value.get(i + gapLength));
  394. }
  395. }
  396. // implements javax.swing.ListSelectionModel
  397. public void setValueIsAdjusting(boolean isAdjusting) {
  398. if (isAdjusting != this.isAdjusting) {
  399. this.isAdjusting = isAdjusting;
  400. this.fireValueChanged(isAdjusting);
  401. }
  402. }
  403. /**
  404. * Returns a string that displays and identifies this
  405. * object's properties.
  406. *
  407. * @return a String representation of this object
  408. */
  409. public String toString() {
  410. String s = ((getValueIsAdjusting()) ? "~" : "=") + value.toString();
  411. return getClass().getName() + " " + Integer.toString(hashCode()) + " " + s;
  412. }
  413. /**
  414. * Returns a clone of the reciever with the same selection.
  415. * listenerLists are not duplicated.
  416. *
  417. * @exception CloneNotSupportedException if the receiver does not
  418. * both (a) implement the Cloneable interface and (b) define a
  419. * <code>clone</code> method.
  420. */
  421. public Object clone() throws CloneNotSupportedException {
  422. DefaultListSelectionModel clone = (DefaultListSelectionModel)super.clone();
  423. clone.value = (BitSet)value.clone();
  424. clone.listenerList = new EventListenerList();
  425. return clone;
  426. }
  427. // implements javax.swing.ListSelectionModel
  428. public int getAnchorSelectionIndex() {
  429. return anchorIndex;
  430. }
  431. // implements javax.swing.ListSelectionModel
  432. public int getLeadSelectionIndex() {
  433. return leadIndex;
  434. }
  435. /**
  436. * Set the anchor selection index, leaving all selection values unchanged.
  437. * If leadAnchorNotificationEnabled is true, send a notification covering
  438. * the old and new anchor cells.
  439. *
  440. * @see #getAnchorSelectionIndex
  441. * @see #setLeadSelectionIndex
  442. */
  443. public void setAnchorSelectionIndex(int anchorIndex) {
  444. updateLeadAnchorIndices(anchorIndex, this.leadIndex);
  445. this.anchorIndex = anchorIndex;
  446. fireValueChanged();
  447. }
  448. /**
  449. * Set the lead selection index, ensuring that values between the
  450. * anchor and the new lead are either all selected or all deselected.
  451. * If the value at the anchor index is selected, first clear all the
  452. * values in the range [anchor, oldLeadIndex], then select all the values
  453. * values in the range [anchor, newLeadIndex], where oldLeadIndex is the old
  454. * leadIndex and newLeadIndex is the new one.
  455. * <p>
  456. * If the value at the anchor index is not selected, do the same thing in reverse,
  457. * selecting values in the old range and deslecting values in the new one.
  458. * <p>
  459. * Generate a single event for this change and notify all listeners.
  460. * For the purposes of generating minimal bounds in this event, do the
  461. * operation in a single pass; that way the first and last index inside the
  462. * ListSelectionEvent that is broadcast will refer to cells that actually
  463. * changed value because of this method. If, instead, this operation were
  464. * done in two steps the effect on the selection state would be the same
  465. * but two events would be generated and the bounds around the changed values
  466. * would be wider, including cells that had been first cleared only
  467. * to later be set.
  468. * <p>
  469. * This method can be used in the mouseDragged() method of a UI class
  470. * to extend a selection.
  471. *
  472. * @see #getLeadSelectionIndex
  473. * @see #setAnchorSelectionIndex
  474. */
  475. public void setLeadSelectionIndex(int leadIndex) {
  476. int anchorIndex = this.anchorIndex;
  477. if ((anchorIndex == -1) || (leadIndex == -1)) {
  478. return;
  479. }
  480. if (this.leadIndex == -1) {
  481. this.leadIndex = leadIndex;
  482. }
  483. if (getSelectionMode() == SINGLE_SELECTION) {
  484. anchorIndex = leadIndex;
  485. }
  486. int oldMin = Math.min(this.anchorIndex, this.leadIndex);
  487. int oldMax = Math.max(this.anchorIndex, this.leadIndex);
  488. int newMin = Math.min(anchorIndex, leadIndex);
  489. int newMax = Math.max(anchorIndex, leadIndex);
  490. if (value.get(this.anchorIndex)) {
  491. changeSelection(oldMin, oldMax, newMin, newMax);
  492. }
  493. else {
  494. changeSelection(newMin, newMax, oldMin, oldMax, false);
  495. }
  496. this.anchorIndex = anchorIndex;
  497. this.leadIndex = leadIndex;
  498. }
  499. }