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