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