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