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