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