1. /*
  2. * @(#)AbstractDocument.java 1.151 04/07/13
  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;
  8. import java.util.*;
  9. import java.io.*;
  10. import java.awt.font.TextAttribute;
  11. import java.text.Bidi;
  12. import javax.swing.UIManager;
  13. import javax.swing.undo.*;
  14. import javax.swing.event.ChangeListener;
  15. import javax.swing.event.*;
  16. import javax.swing.tree.TreeNode;
  17. import sun.font.BidiUtils;
  18. /**
  19. * An implementation of the document interface to serve as a
  20. * basis for implementing various kinds of documents. At this
  21. * level there is very little policy, so there is a corresponding
  22. * increase in difficulty of use.
  23. * <p>
  24. * This class implements a locking mechanism for the document. It
  25. * allows multiple readers or one writer, and writers must wait until
  26. * all observers of the document have been notified of a previous
  27. * change before beginning another mutation to the document. The
  28. * read lock is acquired and released using the <code>render</code>
  29. * method. A write lock is aquired by the methods that mutate the
  30. * document, and are held for the duration of the method call.
  31. * Notification is done on the thread that produced the mutation,
  32. * and the thread has full read access to the document for the
  33. * duration of the notification, but other readers are kept out
  34. * until the notification has finished. The notification is a
  35. * beans event notification which does not allow any further
  36. * mutations until all listeners have been notified.
  37. * <p>
  38. * Any models subclassed from this class and used in conjunction
  39. * with a text component that has a look and feel implementation
  40. * that is derived from BasicTextUI may be safely updated
  41. * asynchronously, because all access to the View hierarchy
  42. * is serialized by BasicTextUI if the document is of type
  43. * <code>AbstractDocument</code>. The locking assumes that an
  44. * independant thread will access the View hierarchy only from
  45. * the DocumentListener methods, and that there will be only
  46. * one event thread active at a time.
  47. * <p>
  48. * If concurrency support is desired, there are the following
  49. * additional implications. The code path for any DocumentListener
  50. * implementation and any UndoListener implementation must be threadsafe,
  51. * and not access the component lock if trying to be safe from deadlocks.
  52. * The <code>repaint</code> and <code>revalidate</code> methods
  53. * on JComponent are safe.
  54. * <p>
  55. * AbstractDocument models an implied break at the end of the document.
  56. * Among other things this allows you to position the caret after the last
  57. * character. As a result of this, <code>getLength</code> returns one less
  58. * than the length of the Content. If you create your own Content, be
  59. * sure and initialize it to have an additional character. Refer to
  60. * StringContent and GapContent for examples of this. Another implication
  61. * of this is that Elements that model the implied end character will have
  62. * an endOffset == (getLength() + 1). For example, in DefaultStyledDocument
  63. * <code>getParagraphElement(getLength()).getEndOffset() == getLength() + 1
  64. * </code>.
  65. * <p>
  66. * <strong>Warning:</strong>
  67. * Serialized objects of this class will not be compatible with
  68. * future Swing releases. The current serialization support is
  69. * appropriate for short term storage or RMI between applications running
  70. * the same version of Swing. As of 1.4, support for long term storage
  71. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  72. * has been added to the <code>java.beans</code> package.
  73. * Please see {@link java.beans.XMLEncoder}.
  74. *
  75. * @author Timothy Prinzing
  76. * @version 1.151 07/13/04
  77. */
  78. public abstract class AbstractDocument implements Document, Serializable {
  79. /**
  80. * Constructs a new <code>AbstractDocument</code>, wrapped around some
  81. * specified content storage mechanism.
  82. *
  83. * @param data the content
  84. */
  85. protected AbstractDocument(Content data) {
  86. this(data, StyleContext.getDefaultStyleContext());
  87. }
  88. /**
  89. * Constructs a new <code>AbstractDocument</code>, wrapped around some
  90. * specified content storage mechanism.
  91. *
  92. * @param data the content
  93. * @param context the attribute context
  94. */
  95. protected AbstractDocument(Content data, AttributeContext context) {
  96. this.data = data;
  97. this.context = context;
  98. bidiRoot = new BidiRootElement();
  99. if (defaultI18NProperty == null) {
  100. // determine default setting for i18n support
  101. Object o = java.security.AccessController.doPrivileged(
  102. new java.security.PrivilegedAction() {
  103. public Object run() {
  104. return System.getProperty(I18NProperty);
  105. }
  106. }
  107. );
  108. if (o != null) {
  109. defaultI18NProperty = Boolean.valueOf((String)o);
  110. } else {
  111. defaultI18NProperty = Boolean.FALSE;
  112. }
  113. }
  114. putProperty( I18NProperty, defaultI18NProperty);
  115. //REMIND(bcb) This creates an initial bidi element to account for
  116. //the \n that exists by default in the content. Doing it this way
  117. //seems to expose a little too much knowledge of the content given
  118. //to us by the sub-class. Consider having the sub-class' constructor
  119. //make an initial call to insertUpdate.
  120. writeLock();
  121. try {
  122. Element[] p = new Element[1];
  123. p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
  124. bidiRoot.replace(0,0,p);
  125. } finally {
  126. writeUnlock();
  127. }
  128. }
  129. /**
  130. * Supports managing a set of properties. Callers
  131. * can use the <code>documentProperties</code> dictionary
  132. * to annotate the document with document-wide properties.
  133. *
  134. * @return a non-<code>null</code> <code>Dictionary</code>
  135. * @see #setDocumentProperties
  136. */
  137. public Dictionary<Object,Object> getDocumentProperties() {
  138. if (documentProperties == null) {
  139. documentProperties = new Hashtable(2);
  140. }
  141. return documentProperties;
  142. }
  143. /**
  144. * Replaces the document properties dictionary for this document.
  145. *
  146. * @param x the new dictionary
  147. * @see #getDocumentProperties
  148. */
  149. public void setDocumentProperties(Dictionary<Object,Object> x) {
  150. documentProperties = x;
  151. }
  152. /**
  153. * Notifies all listeners that have registered interest for
  154. * notification on this event type. The event instance
  155. * is lazily created using the parameters passed into
  156. * the fire method.
  157. *
  158. * @param e the event
  159. * @see EventListenerList
  160. */
  161. protected void fireInsertUpdate(DocumentEvent e) {
  162. notifyingListeners = true;
  163. try {
  164. // Guaranteed to return a non-null array
  165. Object[] listeners = listenerList.getListenerList();
  166. // Process the listeners last to first, notifying
  167. // those that are interested in this event
  168. for (int i = listeners.length-2; i>=0; i-=2) {
  169. if (listeners[i]==DocumentListener.class) {
  170. // Lazily create the event:
  171. // if (e == null)
  172. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  173. ((DocumentListener)listeners[i+1]).insertUpdate(e);
  174. }
  175. }
  176. } finally {
  177. notifyingListeners = false;
  178. }
  179. }
  180. /**
  181. * Notifies all listeners that have registered interest for
  182. * notification on this event type. The event instance
  183. * is lazily created using the parameters passed into
  184. * the fire method.
  185. *
  186. * @param e the event
  187. * @see EventListenerList
  188. */
  189. protected void fireChangedUpdate(DocumentEvent e) {
  190. notifyingListeners = true;
  191. try {
  192. // Guaranteed to return a non-null array
  193. Object[] listeners = listenerList.getListenerList();
  194. // Process the listeners last to first, notifying
  195. // those that are interested in this event
  196. for (int i = listeners.length-2; i>=0; i-=2) {
  197. if (listeners[i]==DocumentListener.class) {
  198. // Lazily create the event:
  199. // if (e == null)
  200. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  201. ((DocumentListener)listeners[i+1]).changedUpdate(e);
  202. }
  203. }
  204. } finally {
  205. notifyingListeners = false;
  206. }
  207. }
  208. /**
  209. * Notifies all listeners that have registered interest for
  210. * notification on this event type. The event instance
  211. * is lazily created using the parameters passed into
  212. * the fire method.
  213. *
  214. * @param e the event
  215. * @see EventListenerList
  216. */
  217. protected void fireRemoveUpdate(DocumentEvent e) {
  218. notifyingListeners = true;
  219. try {
  220. // Guaranteed to return a non-null array
  221. Object[] listeners = listenerList.getListenerList();
  222. // Process the listeners last to first, notifying
  223. // those that are interested in this event
  224. for (int i = listeners.length-2; i>=0; i-=2) {
  225. if (listeners[i]==DocumentListener.class) {
  226. // Lazily create the event:
  227. // if (e == null)
  228. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  229. ((DocumentListener)listeners[i+1]).removeUpdate(e);
  230. }
  231. }
  232. } finally {
  233. notifyingListeners = false;
  234. }
  235. }
  236. /**
  237. * Notifies all listeners that have registered interest for
  238. * notification on this event type. The event instance
  239. * is lazily created using the parameters passed into
  240. * the fire method.
  241. *
  242. * @param e the event
  243. * @see EventListenerList
  244. */
  245. protected void fireUndoableEditUpdate(UndoableEditEvent e) {
  246. // Guaranteed to return a non-null array
  247. Object[] listeners = listenerList.getListenerList();
  248. // Process the listeners last to first, notifying
  249. // those that are interested in this event
  250. for (int i = listeners.length-2; i>=0; i-=2) {
  251. if (listeners[i]==UndoableEditListener.class) {
  252. // Lazily create the event:
  253. // if (e == null)
  254. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  255. ((UndoableEditListener)listeners[i+1]).undoableEditHappened(e);
  256. }
  257. }
  258. }
  259. /**
  260. * Returns an array of all the objects currently registered
  261. * as <code><em>Foo</em>Listener</code>s
  262. * upon this document.
  263. * <code><em>Foo</em>Listener</code>s are registered using the
  264. * <code>add<em>Foo</em>Listener</code> method.
  265. *
  266. * <p>
  267. * You can specify the <code>listenerType</code> argument
  268. * with a class literal, such as
  269. * <code><em>Foo</em>Listener.class</code>.
  270. * For example, you can query a
  271. * document <code>d</code>
  272. * for its document listeners with the following code:
  273. *
  274. * <pre>DocumentListener[] mls = (DocumentListener[])(d.getListeners(DocumentListener.class));</pre>
  275. *
  276. * If no such listeners exist, this method returns an empty array.
  277. *
  278. * @param listenerType the type of listeners requested; this parameter
  279. * should specify an interface that descends from
  280. * <code>java.util.EventListener</code>
  281. * @return an array of all objects registered as
  282. * <code><em>Foo</em>Listener</code>s on this component,
  283. * or an empty array if no such
  284. * listeners have been added
  285. * @exception ClassCastException if <code>listenerType</code>
  286. * doesn't specify a class or interface that implements
  287. * <code>java.util.EventListener</code>
  288. *
  289. * @see #getDocumentListeners
  290. * @see #getUndoableEditListeners
  291. *
  292. * @since 1.3
  293. */
  294. public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
  295. return listenerList.getListeners(listenerType);
  296. }
  297. /**
  298. * Gets the asynchronous loading priority. If less than zero,
  299. * the document should not be loaded asynchronously.
  300. *
  301. * @return the asynchronous loading priority, or <code>-1</code>
  302. * if the document should not be loaded asynchronously
  303. */
  304. public int getAsynchronousLoadPriority() {
  305. Integer loadPriority = (Integer)
  306. getProperty(AbstractDocument.AsyncLoadPriority);
  307. if (loadPriority != null) {
  308. return loadPriority.intValue();
  309. }
  310. return -1;
  311. }
  312. /**
  313. * Sets the asynchronous loading priority.
  314. * @param p the new asynchronous loading priority; a value
  315. * less than zero indicates that the document should not be
  316. * loaded asynchronously
  317. */
  318. public void setAsynchronousLoadPriority(int p) {
  319. Integer loadPriority = (p >= 0) ? new Integer(p) : null;
  320. putProperty(AbstractDocument.AsyncLoadPriority, loadPriority);
  321. }
  322. /**
  323. * Sets the <code>DocumentFilter</code>. The <code>DocumentFilter</code>
  324. * is passed <code>insert</code> and <code>remove</code> to conditionally
  325. * allow inserting/deleting of the text. A <code>null</code> value
  326. * indicates that no filtering will occur.
  327. *
  328. * @param filter the <code>DocumentFilter</code> used to constrain text
  329. * @see #getDocumentFilter
  330. * @since 1.4
  331. */
  332. public void setDocumentFilter(DocumentFilter filter) {
  333. documentFilter = filter;
  334. }
  335. /**
  336. * Returns the <code>DocumentFilter</code> that is responsible for
  337. * filtering of insertion/removal. A <code>null</code> return value
  338. * implies no filtering is to occur.
  339. *
  340. * @since 1.4
  341. * @see #setDocumentFilter
  342. * @return the DocumentFilter
  343. */
  344. public DocumentFilter getDocumentFilter() {
  345. return documentFilter;
  346. }
  347. // --- Document methods -----------------------------------------
  348. /**
  349. * This allows the model to be safely rendered in the presence
  350. * of currency, if the model supports being updated asynchronously.
  351. * The given runnable will be executed in a way that allows it
  352. * to safely read the model with no changes while the runnable
  353. * is being executed. The runnable itself may <em>not</em>
  354. * make any mutations.
  355. * <p>
  356. * This is implemented to aquire a read lock for the duration
  357. * of the runnables execution. There may be multiple runnables
  358. * executing at the same time, and all writers will be blocked
  359. * while there are active rendering runnables. If the runnable
  360. * throws an exception, its lock will be safely released.
  361. * There is no protection against a runnable that never exits,
  362. * which will effectively leave the document locked for it's
  363. * lifetime.
  364. * <p>
  365. * If the given runnable attempts to make any mutations in
  366. * this implementation, a deadlock will occur. There is
  367. * no tracking of individual rendering threads to enable
  368. * detecting this situation, but a subclass could incur
  369. * the overhead of tracking them and throwing an error.
  370. * <p>
  371. * This method is thread safe, although most Swing methods
  372. * are not. Please see
  373. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  374. * and Swing</A> for more information.
  375. *
  376. * @param r the renderer to execute
  377. */
  378. public void render(Runnable r) {
  379. readLock();
  380. try {
  381. r.run();
  382. } finally {
  383. readUnlock();
  384. }
  385. }
  386. /**
  387. * Returns the length of the data. This is the number of
  388. * characters of content that represents the users data.
  389. *
  390. * @return the length >= 0
  391. * @see Document#getLength
  392. */
  393. public int getLength() {
  394. return data.length() - 1;
  395. }
  396. /**
  397. * Adds a document listener for notification of any changes.
  398. *
  399. * @param listener the <code>DocumentListener</code> to add
  400. * @see Document#addDocumentListener
  401. */
  402. public void addDocumentListener(DocumentListener listener) {
  403. listenerList.add(DocumentListener.class, listener);
  404. }
  405. /**
  406. * Removes a document listener.
  407. *
  408. * @param listener the <code>DocumentListener</code> to remove
  409. * @see Document#removeDocumentListener
  410. */
  411. public void removeDocumentListener(DocumentListener listener) {
  412. listenerList.remove(DocumentListener.class, listener);
  413. }
  414. /**
  415. * Returns an array of all the document listeners
  416. * registered on this document.
  417. *
  418. * @return all of this document's <code>DocumentListener</code>s
  419. * or an empty array if no document listeners are
  420. * currently registered
  421. *
  422. * @see #addDocumentListener
  423. * @see #removeDocumentListener
  424. * @since 1.4
  425. */
  426. public DocumentListener[] getDocumentListeners() {
  427. return (DocumentListener[])listenerList.getListeners(
  428. DocumentListener.class);
  429. }
  430. /**
  431. * Adds an undo listener for notification of any changes.
  432. * Undo/Redo operations performed on the <code>UndoableEdit</code>
  433. * will cause the appropriate DocumentEvent to be fired to keep
  434. * the view(s) in sync with the model.
  435. *
  436. * @param listener the <code>UndoableEditListener</code> to add
  437. * @see Document#addUndoableEditListener
  438. */
  439. public void addUndoableEditListener(UndoableEditListener listener) {
  440. listenerList.add(UndoableEditListener.class, listener);
  441. }
  442. /**
  443. * Removes an undo listener.
  444. *
  445. * @param listener the <code>UndoableEditListener</code> to remove
  446. * @see Document#removeDocumentListener
  447. */
  448. public void removeUndoableEditListener(UndoableEditListener listener) {
  449. listenerList.remove(UndoableEditListener.class, listener);
  450. }
  451. /**
  452. * Returns an array of all the undoable edit listeners
  453. * registered on this document.
  454. *
  455. * @return all of this document's <code>UndoableEditListener</code>s
  456. * or an empty array if no undoable edit listeners are
  457. * currently registered
  458. *
  459. * @see #addUndoableEditListener
  460. * @see #removeUndoableEditListener
  461. *
  462. * @since 1.4
  463. */
  464. public UndoableEditListener[] getUndoableEditListeners() {
  465. return (UndoableEditListener[])listenerList.getListeners(
  466. UndoableEditListener.class);
  467. }
  468. /**
  469. * A convenience method for looking up a property value. It is
  470. * equivalent to:
  471. * <pre>
  472. * getDocumentProperties().get(key);
  473. * </pre>
  474. *
  475. * @param key the non-<code>null</code> property key
  476. * @return the value of this property or <code>null</code>
  477. * @see #getDocumentProperties
  478. */
  479. public final Object getProperty(Object key) {
  480. return getDocumentProperties().get(key);
  481. }
  482. /**
  483. * A convenience method for storing up a property value. It is
  484. * equivalent to:
  485. * <pre>
  486. * getDocumentProperties().put(key, value);
  487. * </pre>
  488. * If <code>value</code> is <code>null</code> this method will
  489. * remove the property.
  490. *
  491. * @param key the non-<code>null</code> key
  492. * @param value the property value
  493. * @see #getDocumentProperties
  494. */
  495. public final void putProperty(Object key, Object value) {
  496. if (value != null) {
  497. getDocumentProperties().put(key, value);
  498. } else {
  499. getDocumentProperties().remove(key);
  500. }
  501. if( key == TextAttribute.RUN_DIRECTION
  502. && Boolean.TRUE.equals(getProperty(I18NProperty)) )
  503. {
  504. //REMIND - this needs to flip on the i18n property if run dir
  505. //is rtl and the i18n property is not already on.
  506. writeLock();
  507. try {
  508. DefaultDocumentEvent e
  509. = new DefaultDocumentEvent(0, getLength(),
  510. DocumentEvent.EventType.INSERT);
  511. updateBidi( e );
  512. } finally {
  513. writeUnlock();
  514. }
  515. }
  516. }
  517. /**
  518. * Removes some content from the document.
  519. * Removing content causes a write lock to be held while the
  520. * actual changes are taking place. Observers are notified
  521. * of the change on the thread that called this method.
  522. * <p>
  523. * This method is thread safe, although most Swing methods
  524. * are not. Please see
  525. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  526. * and Swing</A> for more information.
  527. *
  528. * @param offs the starting offset >= 0
  529. * @param len the number of characters to remove >= 0
  530. * @exception BadLocationException the given remove position is not a valid
  531. * position within the document
  532. * @see Document#remove
  533. */
  534. public void remove(int offs, int len) throws BadLocationException {
  535. DocumentFilter filter = getDocumentFilter();
  536. writeLock();
  537. try {
  538. if (filter != null) {
  539. filter.remove(getFilterBypass(), offs, len);
  540. }
  541. else {
  542. handleRemove(offs, len);
  543. }
  544. } finally {
  545. writeUnlock();
  546. }
  547. }
  548. /**
  549. * Performs the actual work of the remove. It is assumed the caller
  550. * will have obtained a <code>writeLock</code> before invoking this.
  551. */
  552. void handleRemove(int offs, int len) throws BadLocationException {
  553. if (len > 0) {
  554. if (offs < 0 || (offs + len) > getLength()) {
  555. throw new BadLocationException("Invalid remove",
  556. getLength() + 1);
  557. }
  558. DefaultDocumentEvent chng =
  559. new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE);
  560. boolean isComposedTextElement = false;
  561. // Check whether the position of interest is the composed text
  562. isComposedTextElement = Utilities.isComposedTextElement(this, offs);
  563. removeUpdate(chng);
  564. UndoableEdit u = data.remove(offs, len);
  565. if (u != null) {
  566. chng.addEdit(u);
  567. }
  568. postRemoveUpdate(chng);
  569. // Mark the edit as done.
  570. chng.end();
  571. fireRemoveUpdate(chng);
  572. // only fire undo if Content implementation supports it
  573. // undo for the composed text is not supported for now
  574. if ((u != null) && !isComposedTextElement) {
  575. fireUndoableEditUpdate(new UndoableEditEvent(this, chng));
  576. }
  577. }
  578. }
  579. /**
  580. * Indic, Thai, and surrogate char values require complex
  581. * text layout and cursor support.
  582. */
  583. private static final boolean isComplex(char ch) {
  584. return (ch >= '\u0900' && ch <= '\u0D7F') || // Indic
  585. (ch >= '\u0E00' && ch <= '\u0E7F') || // Thai
  586. (ch >= '\uD800' && ch <= '\uDFFF'); // surrogate value range
  587. }
  588. private static final boolean isComplex(char[] text, int start, int limit) {
  589. for (int i = start; i < limit; ++i) {
  590. if (isComplex(text[i])) {
  591. return true;
  592. }
  593. }
  594. return false;
  595. }
  596. /**
  597. * Deletes the region of text from <code>offset</code> to
  598. * <code>offset + length</code>, and replaces it with <code>text</code>.
  599. * It is up to the implementation as to how this is implemented, some
  600. * implementations may treat this as two distinct operations: a remove
  601. * followed by an insert, others may treat the replace as one atomic
  602. * operation.
  603. *
  604. * @param offset index of child element
  605. * @param length length of text to delete, may be 0 indicating don't
  606. * delete anything
  607. * @param text text to insert, <code>null</code> indicates no text to insert
  608. * @param attrs AttributeSet indicating attributes of inserted text,
  609. * <code>null</code>
  610. * is legal, and typically treated as an empty attributeset,
  611. * but exact interpretation is left to the subclass
  612. * @exception BadLocationException the given position is not a valid
  613. * position within the document
  614. * @since 1.4
  615. */
  616. public void replace(int offset, int length, String text,
  617. AttributeSet attrs) throws BadLocationException {
  618. if (length == 0 && (text == null || text.length() == 0)) {
  619. return;
  620. }
  621. DocumentFilter filter = getDocumentFilter();
  622. writeLock();
  623. try {
  624. if (filter != null) {
  625. filter.replace(getFilterBypass(), offset, length, text,
  626. attrs);
  627. }
  628. else {
  629. if (length > 0) {
  630. remove(offset, length);
  631. }
  632. if (text != null && text.length() > 0) {
  633. insertString(offset, text, attrs);
  634. }
  635. }
  636. } finally {
  637. writeUnlock();
  638. }
  639. }
  640. /**
  641. * Inserts some content into the document.
  642. * Inserting content causes a write lock to be held while the
  643. * actual changes are taking place, followed by notification
  644. * to the observers on the thread that grabbed the write lock.
  645. * <p>
  646. * This method is thread safe, although most Swing methods
  647. * are not. Please see
  648. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  649. * and Swing</A> for more information.
  650. *
  651. * @param offs the starting offset >= 0
  652. * @param str the string to insert; does nothing with null/empty strings
  653. * @param a the attributes for the inserted content
  654. * @exception BadLocationException the given insert position is not a valid
  655. * position within the document
  656. * @see Document#insertString
  657. */
  658. public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
  659. if ((str == null) || (str.length() == 0)) {
  660. return;
  661. }
  662. DocumentFilter filter = getDocumentFilter();
  663. writeLock();
  664. try {
  665. if (filter != null) {
  666. filter.insertString(getFilterBypass(), offs, str, a);
  667. }
  668. else {
  669. handleInsertString(offs, str, a);
  670. }
  671. } finally {
  672. writeUnlock();
  673. }
  674. }
  675. /**
  676. * Performs the actual work of inserting the text; it is assumed the
  677. * caller has obtained a write lock before invoking this.
  678. */
  679. void handleInsertString(int offs, String str, AttributeSet a)
  680. throws BadLocationException {
  681. if ((str == null) || (str.length() == 0)) {
  682. return;
  683. }
  684. UndoableEdit u = data.insertString(offs, str);
  685. DefaultDocumentEvent e =
  686. new DefaultDocumentEvent(offs, str.length(), DocumentEvent.EventType.INSERT);
  687. if (u != null) {
  688. e.addEdit(u);
  689. }
  690. // see if complex glyph layout support is needed
  691. if( getProperty(I18NProperty).equals( Boolean.FALSE ) ) {
  692. // if a default direction of right-to-left has been specified,
  693. // we want complex layout even if the text is all left to right.
  694. Object d = getProperty(TextAttribute.RUN_DIRECTION);
  695. if ((d != null) && (d.equals(TextAttribute.RUN_DIRECTION_RTL))) {
  696. putProperty( I18NProperty, Boolean.TRUE);
  697. } else {
  698. char[] chars = str.toCharArray();
  699. if (Bidi.requiresBidi(chars, 0, chars.length) ||
  700. isComplex(chars, 0, chars.length)) {
  701. //
  702. putProperty( I18NProperty, Boolean.TRUE);
  703. }
  704. }
  705. }
  706. insertUpdate(e, a);
  707. // Mark the edit as done.
  708. e.end();
  709. fireInsertUpdate(e);
  710. // only fire undo if Content implementation supports it
  711. // undo for the composed text is not supported for now
  712. if (u != null &&
  713. (a == null || !a.isDefined(StyleConstants.ComposedTextAttribute))) {
  714. fireUndoableEditUpdate(new UndoableEditEvent(this, e));
  715. }
  716. }
  717. /**
  718. * Gets a sequence of text from the document.
  719. *
  720. * @param offset the starting offset >= 0
  721. * @param length the number of characters to retrieve >= 0
  722. * @return the text
  723. * @exception BadLocationException the range given includes a position
  724. * that is not a valid position within the document
  725. * @see Document#getText
  726. */
  727. public String getText(int offset, int length) throws BadLocationException {
  728. if (length < 0) {
  729. throw new BadLocationException("Length must be positive", length);
  730. }
  731. String str = data.getString(offset, length);
  732. return str;
  733. }
  734. /**
  735. * Fetches the text contained within the given portion
  736. * of the document.
  737. * <p>
  738. * If the partialReturn property on the txt parameter is false, the
  739. * data returned in the Segment will be the entire length requested and
  740. * may or may not be a copy depending upon how the data was stored.
  741. * If the partialReturn property is true, only the amount of text that
  742. * can be returned without creating a copy is returned. Using partial
  743. * returns will give better performance for situations where large
  744. * parts of the document are being scanned. The following is an example
  745. * of using the partial return to access the entire document:
  746. * <p>
  747. * <pre>
  748. *   int nleft = doc.getDocumentLength();
  749. *   Segment text = new Segment();
  750. *   int offs = 0;
  751. *   text.setPartialReturn(true);
  752. *   while (nleft > 0) {
  753. *   doc.getText(offs, nleft, text);
  754. *   // do something with text
  755. *   nleft -= text.count;
  756. *   offs += text.count;
  757. *   }
  758. * </pre>
  759. *
  760. * @param offset the starting offset >= 0
  761. * @param length the number of characters to retrieve >= 0
  762. * @param txt the Segment object to retrieve the text into
  763. * @exception BadLocationException the range given includes a position
  764. * that is not a valid position within the document
  765. */
  766. public void getText(int offset, int length, Segment txt) throws BadLocationException {
  767. if (length < 0) {
  768. throw new BadLocationException("Length must be positive", length);
  769. }
  770. data.getChars(offset, length, txt);
  771. }
  772. /**
  773. * Returns a position that will track change as the document
  774. * is altered.
  775. * <p>
  776. * This method is thread safe, although most Swing methods
  777. * are not. Please see
  778. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  779. * and Swing</A> for more information.
  780. *
  781. * @param offs the position in the model >= 0
  782. * @return the position
  783. * @exception BadLocationException if the given position does not
  784. * represent a valid location in the associated document
  785. * @see Document#createPosition
  786. */
  787. public synchronized Position createPosition(int offs) throws BadLocationException {
  788. return data.createPosition(offs);
  789. }
  790. /**
  791. * Returns a position that represents the start of the document. The
  792. * position returned can be counted on to track change and stay
  793. * located at the beginning of the document.
  794. *
  795. * @return the position
  796. */
  797. public final Position getStartPosition() {
  798. Position p;
  799. try {
  800. p = createPosition(0);
  801. } catch (BadLocationException bl) {
  802. p = null;
  803. }
  804. return p;
  805. }
  806. /**
  807. * Returns a position that represents the end of the document. The
  808. * position returned can be counted on to track change and stay
  809. * located at the end of the document.
  810. *
  811. * @return the position
  812. */
  813. public final Position getEndPosition() {
  814. Position p;
  815. try {
  816. p = createPosition(data.length());
  817. } catch (BadLocationException bl) {
  818. p = null;
  819. }
  820. return p;
  821. }
  822. /**
  823. * Gets all root elements defined. Typically, there
  824. * will only be one so the default implementation
  825. * is to return the default root element.
  826. *
  827. * @return the root element
  828. */
  829. public Element[] getRootElements() {
  830. Element[] elems = new Element[2];
  831. elems[0] = getDefaultRootElement();
  832. elems[1] = getBidiRootElement();
  833. return elems;
  834. }
  835. /**
  836. * Returns the root element that views should be based upon
  837. * unless some other mechanism for assigning views to element
  838. * structures is provided.
  839. *
  840. * @return the root element
  841. * @see Document#getDefaultRootElement
  842. */
  843. public abstract Element getDefaultRootElement();
  844. // ---- local methods -----------------------------------------
  845. /**
  846. * Returns the <code>FilterBypass</code>. This will create one if one
  847. * does not yet exist.
  848. */
  849. private DocumentFilter.FilterBypass getFilterBypass() {
  850. if (filterBypass == null) {
  851. filterBypass = new DefaultFilterBypass();
  852. }
  853. return filterBypass;
  854. }
  855. /**
  856. * Returns the root element of the bidirectional structure for this
  857. * document. Its children represent character runs with a given
  858. * Unicode bidi level.
  859. */
  860. public Element getBidiRootElement() {
  861. return bidiRoot;
  862. }
  863. /**
  864. * Returns true if the text in the range <code>p0</code> to
  865. * <code>p1</code> is left to right.
  866. */
  867. boolean isLeftToRight(int p0, int p1) {
  868. if(!getProperty(I18NProperty).equals(Boolean.TRUE)) {
  869. return true;
  870. }
  871. Element bidiRoot = getBidiRootElement();
  872. int index = bidiRoot.getElementIndex(p0);
  873. Element bidiElem = bidiRoot.getElement(index);
  874. if(bidiElem.getEndOffset() >= p1) {
  875. AttributeSet bidiAttrs = bidiElem.getAttributes();
  876. return ((StyleConstants.getBidiLevel(bidiAttrs) % 2) == 0);
  877. }
  878. return true;
  879. }
  880. /**
  881. * Get the paragraph element containing the given position. Sub-classes
  882. * must define for themselves what exactly constitutes a paragraph. They
  883. * should keep in mind however that a paragraph should at least be the
  884. * unit of text over which to run the Unicode bidirectional algorithm.
  885. *
  886. * @param pos the starting offset >= 0
  887. * @return the element */
  888. public abstract Element getParagraphElement(int pos);
  889. /**
  890. * Fetches the context for managing attributes. This
  891. * method effectively establishes the strategy used
  892. * for compressing AttributeSet information.
  893. *
  894. * @return the context
  895. */
  896. protected final AttributeContext getAttributeContext() {
  897. return context;
  898. }
  899. /**
  900. * Updates document structure as a result of text insertion. This
  901. * will happen within a write lock. If a subclass of
  902. * this class reimplements this method, it should delegate to the
  903. * superclass as well.
  904. *
  905. * @param chng a description of the change
  906. * @param attr the attributes for the change
  907. */
  908. protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) {
  909. if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
  910. updateBidi( chng );
  911. // Check if a multi byte is encountered in the inserted text.
  912. if (chng.type == DocumentEvent.EventType.INSERT &&
  913. chng.getLength() > 0 &&
  914. !Boolean.TRUE.equals(getProperty(MultiByteProperty))) {
  915. Segment segment = SegmentCache.getSharedSegment();
  916. try {
  917. getText(chng.getOffset(), chng.getLength(), segment);
  918. segment.first();
  919. do {
  920. if ((int)segment.current() > 255) {
  921. putProperty(MultiByteProperty, Boolean.TRUE);
  922. break;
  923. }
  924. } while (segment.next() != Segment.DONE);
  925. } catch (BadLocationException ble) {
  926. // Should never happen
  927. }
  928. SegmentCache.releaseSharedSegment(segment);
  929. }
  930. }
  931. /**
  932. * Updates any document structure as a result of text removal. This
  933. * method is called before the text is actually removed from the Content.
  934. * This will happen within a write lock. If a subclass
  935. * of this class reimplements this method, it should delegate to the
  936. * superclass as well.
  937. *
  938. * @param chng a description of the change
  939. */
  940. protected void removeUpdate(DefaultDocumentEvent chng) {
  941. }
  942. /**
  943. * Updates any document structure as a result of text removal. This
  944. * method is called after the text has been removed from the Content.
  945. * This will happen within a write lock. If a subclass
  946. * of this class reimplements this method, it should delegate to the
  947. * superclass as well.
  948. *
  949. * @param chng a description of the change
  950. */
  951. protected void postRemoveUpdate(DefaultDocumentEvent chng) {
  952. if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
  953. updateBidi( chng );
  954. }
  955. /**
  956. * Update the bidi element structure as a result of the given change
  957. * to the document. The given change will be updated to reflect the
  958. * changes made to the bidi structure.
  959. *
  960. * This method assumes that every offset in the model is contained in
  961. * exactly one paragraph. This method also assumes that it is called
  962. * after the change is made to the default element structure.
  963. */
  964. void updateBidi( DefaultDocumentEvent chng ) {
  965. // Calculate the range of paragraphs affected by the change.
  966. int firstPStart;
  967. int lastPEnd;
  968. if( chng.type == DocumentEvent.EventType.INSERT
  969. || chng.type == DocumentEvent.EventType.CHANGE )
  970. {
  971. int chngStart = chng.getOffset();
  972. int chngEnd = chngStart + chng.getLength();
  973. firstPStart = getParagraphElement(chngStart).getStartOffset();
  974. lastPEnd = getParagraphElement(chngEnd).getEndOffset();
  975. } else if( chng.type == DocumentEvent.EventType.REMOVE ) {
  976. Element paragraph = getParagraphElement( chng.getOffset() );
  977. firstPStart = paragraph.getStartOffset();
  978. lastPEnd = paragraph.getEndOffset();
  979. } else {
  980. throw new Error("Internal error: unknown event type.");
  981. }
  982. //System.out.println("updateBidi: firstPStart = " + firstPStart + " lastPEnd = " + lastPEnd );
  983. // Calculate the bidi levels for the affected range of paragraphs. The
  984. // levels array will contain a bidi level for each character in the
  985. // affected text.
  986. byte levels[] = calculateBidiLevels( firstPStart, lastPEnd );
  987. Vector newElements = new Vector();
  988. // Calculate the first span of characters in the affected range with
  989. // the same bidi level. If this level is the same as the level of the
  990. // previous bidi element (the existing bidi element containing
  991. // firstPStart-1), then merge in the previous element. If not, but
  992. // the previous element overlaps the affected range, truncate the
  993. // previous element at firstPStart.
  994. int firstSpanStart = firstPStart;
  995. int removeFromIndex = 0;
  996. if( firstSpanStart > 0 ) {
  997. int prevElemIndex = bidiRoot.getElementIndex(firstPStart-1);
  998. removeFromIndex = prevElemIndex;
  999. Element prevElem = bidiRoot.getElement(prevElemIndex);
  1000. int prevLevel=StyleConstants.getBidiLevel(prevElem.getAttributes());
  1001. //System.out.println("createbidiElements: prevElem= " + prevElem + " prevLevel= " + prevLevel + "level[0] = " + levels[0]);
  1002. if( prevLevel==levels[0] ) {
  1003. firstSpanStart = prevElem.getStartOffset();
  1004. } else if( prevElem.getEndOffset() > firstPStart ) {
  1005. newElements.addElement(new BidiElement(bidiRoot,
  1006. prevElem.getStartOffset(),
  1007. firstPStart, prevLevel));
  1008. } else {
  1009. removeFromIndex++;
  1010. }
  1011. }
  1012. int firstSpanEnd = 0;
  1013. while((firstSpanEnd<levels.length) && (levels[firstSpanEnd]==levels[0]))
  1014. firstSpanEnd++;
  1015. // Calculate the last span of characters in the affected range with
  1016. // the same bidi level. If this level is the same as the level of the
  1017. // next bidi element (the existing bidi element containing lastPEnd),
  1018. // then merge in the next element. If not, but the next element
  1019. // overlaps the affected range, adjust the next element to start at
  1020. // lastPEnd.
  1021. int lastSpanEnd = lastPEnd;
  1022. Element newNextElem = null;
  1023. int removeToIndex = bidiRoot.getElementCount() - 1;
  1024. if( lastSpanEnd <= getLength() ) {
  1025. int nextElemIndex = bidiRoot.getElementIndex( lastPEnd );
  1026. removeToIndex = nextElemIndex;
  1027. Element nextElem = bidiRoot.getElement( nextElemIndex );
  1028. int nextLevel = StyleConstants.getBidiLevel(nextElem.getAttributes());
  1029. if( nextLevel == levels[levels.length-1] ) {
  1030. lastSpanEnd = nextElem.getEndOffset();
  1031. } else if( nextElem.getStartOffset() < lastPEnd ) {
  1032. newNextElem = new BidiElement(bidiRoot, lastPEnd,
  1033. nextElem.getEndOffset(),
  1034. nextLevel);
  1035. } else {
  1036. removeToIndex--;
  1037. }
  1038. }
  1039. int lastSpanStart = levels.length;
  1040. while( (lastSpanStart>firstSpanEnd)
  1041. && (levels[lastSpanStart-1]==levels[levels.length-1]) )
  1042. lastSpanStart--;
  1043. // If the first and last spans are contiguous and have the same level,
  1044. // merge them and create a single new element for the entire span.
  1045. // Otherwise, create elements for the first and last spans as well as
  1046. // any spans in between.
  1047. if((firstSpanEnd==lastSpanStart)&&(levels[0]==levels[levels.length-1])){
  1048. newElements.addElement(new BidiElement(bidiRoot, firstSpanStart,
  1049. lastSpanEnd, levels[0]));
  1050. } else {
  1051. // Create an element for the first span.
  1052. newElements.addElement(new BidiElement(bidiRoot, firstSpanStart,
  1053. firstSpanEnd+firstPStart,
  1054. levels[0]));
  1055. // Create elements for the spans in between the first and last
  1056. for( int i=firstSpanEnd; i<lastSpanStart; ) {
  1057. //System.out.println("executed line 872");
  1058. int j;
  1059. for( j=i; (j<levels.length) && (levels[j] == levels[i]); j++ );
  1060. newElements.addElement(new BidiElement(bidiRoot, firstPStart+i,
  1061. firstPStart+j,
  1062. (int)levels[i]));
  1063. i=j;
  1064. }
  1065. // Create an element for the last span.
  1066. newElements.addElement(new BidiElement(bidiRoot,
  1067. lastSpanStart+firstPStart,
  1068. lastSpanEnd,
  1069. levels[levels.length-1]));
  1070. }
  1071. if( newNextElem != null )
  1072. newElements.addElement( newNextElem );
  1073. // Calculate the set of existing bidi elements which must be
  1074. // removed.
  1075. int removedElemCount = 0;
  1076. if( bidiRoot.getElementCount() > 0 ) {
  1077. removedElemCount = removeToIndex - removeFromIndex + 1;
  1078. }
  1079. Element[] removedElems = new Element[removedElemCount];
  1080. for( int i=0; i<removedElemCount; i++ ) {
  1081. removedElems[i] = bidiRoot.getElement(removeFromIndex+i);
  1082. }
  1083. Element[] addedElems = new Element[ newElements.size() ];
  1084. newElements.copyInto( addedElems );
  1085. // Update the change record.
  1086. ElementEdit ee = new ElementEdit( bidiRoot, removeFromIndex,
  1087. removedElems, addedElems );
  1088. chng.addEdit( ee );
  1089. // Update the bidi element structure.
  1090. bidiRoot.replace( removeFromIndex, removedElems.length, addedElems );
  1091. }
  1092. /**
  1093. * Calculate the levels array for a range of paragraphs.
  1094. */
  1095. private byte[] calculateBidiLevels( int firstPStart, int lastPEnd ) {
  1096. byte levels[] = new byte[ lastPEnd - firstPStart ];
  1097. int levelsEnd = 0;
  1098. Boolean defaultDirection = null;
  1099. Object d = getProperty(TextAttribute.RUN_DIRECTION);
  1100. if (d instanceof Boolean) {
  1101. defaultDirection = (Boolean) d;
  1102. }
  1103. // For each paragraph in the given range of paragraphs, get its
  1104. // levels array and add it to the levels array for the entire span.
  1105. for(int o=firstPStart; o<lastPEnd; ) {
  1106. Element p = getParagraphElement( o );
  1107. int pStart = p.getStartOffset();
  1108. int pEnd = p.getEndOffset();
  1109. // default run direction for the paragraph. This will be
  1110. // null if there is no direction override specified (i.e.
  1111. // the direction will be determined from the content).
  1112. Boolean direction = defaultDirection;
  1113. d = p.getAttributes().getAttribute(TextAttribute.RUN_DIRECTION);
  1114. if (d instanceof Boolean) {
  1115. direction = (Boolean) d;
  1116. }
  1117. //System.out.println("updateBidi: paragraph start = " + pStart + " paragraph end = " + pEnd);
  1118. // Create a Bidi over this paragraph then get the level
  1119. // array.
  1120. Segment seg = SegmentCache.getSharedSegment();
  1121. try {
  1122. getText(pStart, pEnd-pStart, seg);
  1123. } catch (BadLocationException e ) {
  1124. throw new Error("Internal error: " + e.toString());
  1125. }
  1126. // REMIND(bcb) we should really be using a Segment here.
  1127. Bidi bidiAnalyzer;
  1128. int bidiflag = Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
  1129. if (direction != null) {
  1130. if (TextAttribute.RUN_DIRECTION_LTR.equals(direction)) {
  1131. bidiflag = Bidi.DIRECTION_LEFT_TO_RIGHT;
  1132. } else {
  1133. bidiflag = Bidi.DIRECTION_RIGHT_TO_LEFT;
  1134. }
  1135. }
  1136. bidiAnalyzer = new Bidi(seg.array, seg.offset, null, 0, seg.count,
  1137. bidiflag);
  1138. BidiUtils.getLevels(bidiAnalyzer, levels, levelsEnd);
  1139. levelsEnd += bidiAnalyzer.getLength();
  1140. o = p.getEndOffset();
  1141. SegmentCache.releaseSharedSegment(seg);
  1142. }
  1143. // REMIND(bcb) remove this code when debugging is done.
  1144. if( levelsEnd != levels.length )
  1145. throw new Error("levelsEnd assertion failed.");
  1146. return levels;
  1147. }
  1148. /**
  1149. * Gives a diagnostic dump.
  1150. *
  1151. * @param out the output stream
  1152. */
  1153. public void dump(PrintStream out) {
  1154. Element root = getDefaultRootElement();
  1155. if (root instanceof AbstractElement) {
  1156. ((AbstractElement)root).dump(out, 0);
  1157. }
  1158. bidiRoot.dump(out,0);
  1159. }
  1160. /**
  1161. * Gets the content for the document.
  1162. *
  1163. * @return the content
  1164. */
  1165. protected final Content getContent() {
  1166. return data;
  1167. }
  1168. /**
  1169. * Creates a document leaf element.
  1170. * Hook through which elements are created to represent the
  1171. * document structure. Because this implementation keeps
  1172. * structure and content separate, elements grow automatically
  1173. * when content is extended so splits of existing elements
  1174. * follow. The document itself gets to decide how to generate
  1175. * elements to give flexibility in the type of elements used.
  1176. *
  1177. * @param parent the parent element
  1178. * @param a the attributes for the element
  1179. * @param p0 the beginning of the range >= 0
  1180. * @param p1 the end of the range >= p0
  1181. * @return the new element
  1182. */
  1183. protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1) {
  1184. return new LeafElement(parent, a, p0, p1);
  1185. }
  1186. /**
  1187. * Creates a document branch element, that can contain other elements.
  1188. *
  1189. * @param parent the parent element
  1190. * @param a the attributes
  1191. * @return the element
  1192. */
  1193. protected Element createBranchElement(Element parent, AttributeSet a) {
  1194. return new BranchElement(parent, a);
  1195. }
  1196. // --- Document locking ----------------------------------
  1197. /**
  1198. * Fetches the current writing thread if there is one.
  1199. * This can be used to distinguish whether a method is
  1200. * being called as part of an existing modification or
  1201. * if a lock needs to be acquired and a new transaction
  1202. * started.
  1203. *
  1204. * @return the thread actively modifying the document
  1205. * or <code>null</code> if there are no modifications in progress
  1206. */
  1207. protected synchronized final Thread getCurrentWriter() {
  1208. return currWriter;
  1209. }
  1210. /**
  1211. * Acquires a lock to begin mutating the document this lock
  1212. * protects. There can be no writing, notification of changes, or
  1213. * reading going on in order to gain the lock. Additionally a thread is
  1214. * allowed to gain more than one <code>writeLock</code>,
  1215. * as long as it doesn't attempt to gain additional <code>writeLock</code>s
  1216. * from within document notification. Attempting to gain a
  1217. * <code>writeLock</code> from within a DocumentListener notification will
  1218. * result in an <code>IllegalStateException</code>. The ability
  1219. * to obtain more than one <code>writeLock</code> per thread allows
  1220. * subclasses to gain a writeLock, perform a number of operations, then
  1221. * release the lock.
  1222. * <p>
  1223. * Calls to <code>writeLock</code>
  1224. * must be balanced with calls to <code>writeUnlock</code>, else the
  1225. * <code>Document</code> will be left in a locked state so that no
  1226. * reading or writing can be done.
  1227. *
  1228. * @exception IllegalStateException thrown on illegal lock
  1229. * attempt. If the document is implemented properly, this can
  1230. * only happen if a document listener attempts to mutate the
  1231. * document. This situation violates the bean event model
  1232. * where order of delivery is not guaranteed and all listeners
  1233. * should be notified before further mutations are allowed.
  1234. */
  1235. protected synchronized final void writeLock() {
  1236. try {
  1237. while ((numReaders > 0) || (currWriter != null)) {
  1238. if (Thread.currentThread() == currWriter) {
  1239. if (notifyingListeners) {
  1240. // Assuming one doesn't do something wrong in a
  1241. // subclass this should only happen if a
  1242. // DocumentListener tries to mutate the document.
  1243. throw new IllegalStateException(
  1244. "Attempt to mutate in notification");
  1245. }
  1246. numWriters++;
  1247. return;
  1248. }
  1249. wait();
  1250. }
  1251. currWriter = Thread.currentThread();
  1252. numWriters = 1;
  1253. } catch (InterruptedException e) {
  1254. throw new Error("Interrupted attempt to aquire write lock");
  1255. }
  1256. }
  1257. /**
  1258. * Releases a write lock previously obtained via <code>writeLock</code>.
  1259. * After decrementing the lock count if there are no oustanding locks
  1260. * this will allow a new writer, or readers.
  1261. *
  1262. * @see #writeLock
  1263. */
  1264. protected synchronized final void writeUnlock() {
  1265. if (--numWriters <= 0) {
  1266. numWriters = 0;
  1267. currWriter = null;
  1268. notifyAll();
  1269. }
  1270. }
  1271. /**
  1272. * Acquires a lock to begin reading some state from the
  1273. * document. There can be multiple readers at the same time.
  1274. * Writing blocks the readers until notification of the change
  1275. * to the listeners has been completed. This method should
  1276. * be used very carefully to avoid unintended compromise
  1277. * of the document. It should always be balanced with a
  1278. * <code>readUnlock</code>.
  1279. *
  1280. * @see #readUnlock
  1281. */
  1282. public synchronized final void readLock() {
  1283. try {
  1284. while (currWriter != null) {
  1285. if (currWriter == Thread.currentThread()) {
  1286. // writer has full read access.... may try to acquire
  1287. // lock in notification
  1288. return;
  1289. }
  1290. wait();
  1291. }
  1292. numReaders += 1;
  1293. } catch (InterruptedException e) {
  1294. throw new Error("Interrupted attempt to aquire read lock");
  1295. }
  1296. }
  1297. /**
  1298. * Does a read unlock. This signals that one
  1299. * of the readers is done. If there are no more readers
  1300. * then writing can begin again. This should be balanced
  1301. * with a readLock, and should occur in a finally statement
  1302. * so that the balance is guaranteed. The following is an
  1303. * example.
  1304. * <pre><code>
  1305. *   readLock();
  1306. *   try {
  1307. *   // do something
  1308. *   } finally {
  1309. *   readUnlock();
  1310. *   }
  1311. * </code></pre>
  1312. *
  1313. * @see #readLock
  1314. */
  1315. public synchronized final void readUnlock() {
  1316. if (currWriter == Thread.currentThread()) {
  1317. // writer has full read access.... may try to acquire
  1318. // lock in notification
  1319. return;
  1320. }
  1321. if (numReaders <= 0) {
  1322. throw new StateInvariantError(BAD_LOCK_STATE);
  1323. }
  1324. numReaders -= 1;
  1325. notify();
  1326. }
  1327. // --- serialization ---------------------------------------------
  1328. private void readObject(ObjectInputStream s)
  1329. throws ClassNotFoundException, IOException
  1330. {
  1331. s.defaultReadObject();
  1332. listenerList = new EventListenerList();
  1333. // Restore bidi structure
  1334. //REMIND(bcb) This creates an initial bidi element to account for
  1335. //the \n that exists by default in the content.
  1336. bidiRoot = new BidiRootElement();
  1337. try {
  1338. writeLock();
  1339. Element[] p = new Element[1];
  1340. p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
  1341. bidiRoot.replace(0,0,p);
  1342. } finally {
  1343. writeUnlock();
  1344. }
  1345. // At this point bidi root is only partially correct. To fully
  1346. // restore it we need access to getDefaultRootElement. But, this
  1347. // is created by the subclass and at this point will be null. We
  1348. // thus use registerValidation.
  1349. s.registerValidation(new ObjectInputValidation() {
  1350. public void validateObject() {
  1351. try {
  1352. writeLock();
  1353. DefaultDocumentEvent e = new DefaultDocumentEvent
  1354. (0, getLength(),
  1355. DocumentEvent.EventType.INSERT);
  1356. updateBidi( e );
  1357. }
  1358. finally {
  1359. writeUnlock();
  1360. }
  1361. }
  1362. }, 0);
  1363. }
  1364. // ----- member variables ------------------------------------------
  1365. private transient int numReaders;
  1366. private transient Thread currWriter;
  1367. /**
  1368. * The number of writers, all obtained from <code>currWriter</code>.
  1369. */
  1370. private transient int numWriters;
  1371. /**
  1372. * True will notifying listeners.
  1373. */
  1374. private transient boolean notifyingListeners;
  1375. private static Boolean defaultI18NProperty;
  1376. /**
  1377. * Storage for document-wide properties.
  1378. */
  1379. private Dictionary<Object,Object> documentProperties = null;
  1380. /**
  1381. * The event listener list for the document.
  1382. */
  1383. protected EventListenerList listenerList = new EventListenerList();
  1384. /**
  1385. * Where the text is actually stored, and a set of marks
  1386. * that track change as the document is edited are managed.
  1387. */
  1388. private Content data;
  1389. /**
  1390. * Factory for the attributes. This is the strategy for
  1391. * attribute compression and control of the lifetime of
  1392. * a set of attributes as a collection. This may be shared
  1393. * with other documents.
  1394. */
  1395. private AttributeContext context;
  1396. /**
  1397. * The root of the bidirectional structure for this document. Its children
  1398. * represent character runs with the same Unicode bidi level.
  1399. */
  1400. private transient BranchElement bidiRoot;
  1401. /**
  1402. * Filter for inserting/removing of text.
  1403. */
  1404. private DocumentFilter documentFilter;
  1405. /**
  1406. * Used by DocumentFilter to do actual insert/remove.
  1407. */
  1408. private transient DocumentFilter.FilterBypass filterBypass;
  1409. private static final String BAD_LOCK_STATE = "document lock failure";
  1410. /**
  1411. * Error message to indicate a bad location.
  1412. */
  1413. protected static final String BAD_LOCATION = "document location failure";
  1414. /**
  1415. * Name of elements used to represent paragraphs
  1416. */
  1417. public static final String ParagraphElementName = "paragraph";
  1418. /**
  1419. * Name of elements used to represent content
  1420. */
  1421. public static final String ContentElementName = "content";
  1422. /**
  1423. * Name of elements used to hold sections (lines/paragraphs).
  1424. */
  1425. public static final String SectionElementName = "section";
  1426. /**
  1427. * Name of elements used to hold a unidirectional run
  1428. */
  1429. public static final String BidiElementName = "bidi level";
  1430. /**
  1431. * Name of the attribute used to specify element
  1432. * names.
  1433. */
  1434. public static final String ElementNameAttribute = "$ename";
  1435. /**
  1436. * Document property that indicates whether internationalization
  1437. * functions such as text reordering or reshaping should be
  1438. * performed. This property should not be publicly exposed,
  1439. * since it is used for implementation convenience only. As a
  1440. * side effect, copies of this property may be in its subclasses
  1441. * that live in different packages (e.g. HTMLDocument as of now),
  1442. * so those copies should also be taken care of when this property
  1443. * needs to be modified.
  1444. */
  1445. static final String I18NProperty = "i18n";
  1446. /**
  1447. * Document property that indicates if a character has been inserted
  1448. * into the document that is more than one byte long. GlyphView uses
  1449. * this to determine if it should use BreakIterator.
  1450. */
  1451. static final Object MultiByteProperty = "multiByte";
  1452. /**
  1453. * Document property that indicates asynchronous loading is
  1454. * desired, with the thread priority given as the value.
  1455. */
  1456. static final String AsyncLoadPriority = "load priority";
  1457. /**
  1458. * Interface to describe a sequence of character content that
  1459. * can be edited. Implementations may or may not support a
  1460. * history mechanism which will be reflected by whether or not
  1461. * mutations return an UndoableEdit implementation.
  1462. * @see AbstractDocument
  1463. */
  1464. public interface Content {
  1465. /**
  1466. * Creates a position within the content that will
  1467. * track change as the content is mutated.
  1468. *
  1469. * @param offset the offset in the content >= 0
  1470. * @return a Position
  1471. * @exception BadLocationException for an invalid offset
  1472. */
  1473. public Position createPosition(int offset) throws BadLocationException;
  1474. /**
  1475. * Current length of the sequence of character content.
  1476. *
  1477. * @return the length >= 0
  1478. */
  1479. public int length();
  1480. /**
  1481. * Inserts a string of characters into the sequence.
  1482. *
  1483. * @param where offset into the sequence to make the insertion >= 0
  1484. * @param str string to insert
  1485. * @return if the implementation supports a history mechanism,
  1486. * a reference to an <code>Edit</code> implementation will be returned,
  1487. * otherwise returns <code>null</code>
  1488. * @exception BadLocationException thrown if the area covered by
  1489. * the arguments is not contained in the character sequence
  1490. */
  1491. public UndoableEdit insertString(int where, String str) throws BadLocationException;
  1492. /**
  1493. * Removes some portion of the sequence.
  1494. *
  1495. * @param where The offset into the sequence to make the
  1496. * insertion >= 0.
  1497. * @param nitems The number of items in the sequence to remove >= 0.
  1498. * @return If the implementation supports a history mechansim,
  1499. * a reference to an Edit implementation will be returned,
  1500. * otherwise null.
  1501. * @exception BadLocationException Thrown if the area covered by
  1502. * the arguments is not contained in the character sequence.
  1503. */
  1504. public UndoableEdit remove(int where, int nitems) throws BadLocationException;
  1505. /**
  1506. * Fetches a string of characters contained in the sequence.
  1507. *
  1508. * @param where Offset into the sequence to fetch >= 0.
  1509. * @param len number of characters to copy >= 0.
  1510. * @return the string
  1511. * @exception BadLocationException Thrown if the area covered by
  1512. * the arguments is not contained in the character sequence.
  1513. */
  1514. public String getString(int where, int len) throws BadLocationException;
  1515. /**
  1516. * Gets a sequence of characters and copies them into a Segment.
  1517. *
  1518. * @param where the starting offset >= 0
  1519. * @param len the number of characters >= 0
  1520. * @param txt the target location to copy into
  1521. * @exception BadLocationException Thrown if the area covered by
  1522. * the arguments is not contained in the character sequence.
  1523. */
  1524. public void getChars(int where, int len, Segment txt) throws BadLocationException;
  1525. }
  1526. /**
  1527. * An interface that can be used to allow MutableAttributeSet
  1528. * implementations to use pluggable attribute compression
  1529. * techniques. Each mutation of the attribute set can be
  1530. * used to exchange a previous AttributeSet instance with
  1531. * another, preserving the possibility of the AttributeSet
  1532. * remaining immutable. An implementation is provided by
  1533. * the StyleContext class.
  1534. *
  1535. * The Element implementations provided by this class use
  1536. * this interface to provide their MutableAttributeSet
  1537. * implementations, so that different AttributeSet compression
  1538. * techniques can be employed. The method
  1539. * <code>getAttributeContext</code> should be implemented to
  1540. * return the object responsible for implementing the desired
  1541. * compression technique.
  1542. *
  1543. * @see StyleContext
  1544. */
  1545. public interface AttributeContext {
  1546. /**
  1547. * Adds an attribute to the given set, and returns
  1548. * the new representative set.
  1549. *
  1550. * @param old the old attribute set
  1551. * @param name the non-null attribute name
  1552. * @param value the attribute value
  1553. * @return the updated attribute set
  1554. * @see MutableAttributeSet#addAttribute
  1555. */
  1556. public AttributeSet addAttribute(AttributeSet old, Object name, Object value);
  1557. /**
  1558. * Adds a set of attributes to the element.
  1559. *
  1560. * @param old the old attribute set
  1561. * @param attr the attributes to add
  1562. * @return the updated attribute set
  1563. * @see MutableAttributeSet#addAttribute
  1564. */
  1565. public AttributeSet addAttributes(AttributeSet old, AttributeSet attr);
  1566. /**
  1567. * Removes an attribute from the set.
  1568. *
  1569. * @param old the old attribute set
  1570. * @param name the non-null attribute name
  1571. * @return the updated attribute set
  1572. * @see MutableAttributeSet#removeAttribute
  1573. */
  1574. public AttributeSet removeAttribute(AttributeSet old, Object name);
  1575. /**
  1576. * Removes a set of attributes for the element.
  1577. *
  1578. * @param old the old attribute set
  1579. * @param names the attribute names
  1580. * @return the updated attribute set
  1581. * @see MutableAttributeSet#removeAttributes
  1582. */
  1583. public AttributeSet removeAttributes(AttributeSet old, Enumeration<?> names);
  1584. /**
  1585. * Removes a set of attributes for the element.
  1586. *
  1587. * @param old the old attribute set
  1588. * @param attrs the attributes
  1589. * @return the updated attribute set
  1590. * @see MutableAttributeSet#removeAttributes
  1591. */
  1592. public AttributeSet removeAttributes(AttributeSet old, AttributeSet attrs);
  1593. /**
  1594. * Fetches an empty AttributeSet.
  1595. *
  1596. * @return the attribute set
  1597. */
  1598. public AttributeSet getEmptySet();
  1599. /**
  1600. * Reclaims an attribute set.
  1601. * This is a way for a MutableAttributeSet to mark that it no
  1602. * longer need a particular immutable set. This is only necessary
  1603. * in 1.1 where there are no weak references. A 1.1 implementation
  1604. * would call this in its finalize method.
  1605. *
  1606. * @param a the attribute set to reclaim
  1607. */
  1608. public void reclaim(AttributeSet a);
  1609. }
  1610. /**
  1611. * Implements the abstract part of an element. By default elements
  1612. * support attributes by having a field that represents the immutable
  1613. * part of the current attribute set for the element. The element itself
  1614. * implements MutableAttributeSet which can be used to modify the set
  1615. * by fetching a new immutable set. The immutable sets are provided
  1616. * by the AttributeContext associated with the document.
  1617. * <p>
  1618. * <strong>Warning:</strong>
  1619. * Serialized objects of this class will not be compatible with
  1620. * future Swing releases. The current serialization support is
  1621. * appropriate for short term storage or RMI between applications running
  1622. * the same version of Swing. As of 1.4, support for long term storage
  1623. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  1624. * has been added to the <code>java.beans</code> package.
  1625. * Please see {@link java.beans.XMLEncoder}.
  1626. */
  1627. public abstract class AbstractElement implements Element, MutableAttributeSet, Serializable, TreeNode {
  1628. /**
  1629. * Creates a new AbstractElement.
  1630. *
  1631. * @param parent the parent element
  1632. * @param a the attributes for the element
  1633. */
  1634. public AbstractElement(Element parent, AttributeSet a) {
  1635. this.parent = parent;
  1636. attributes = getAttributeContext().getEmptySet();
  1637. if (a != null) {
  1638. addAttributes(a);
  1639. }
  1640. }
  1641. private final void indent(PrintWriter out, int n) {
  1642. for (int i = 0; i < n; i++) {
  1643. out.print(" ");
  1644. }
  1645. }
  1646. /**
  1647. * Dumps a debugging representation of the element hierarchy.
  1648. *
  1649. * @param psOut the output stream
  1650. * @param indentAmount the indentation level >= 0
  1651. */
  1652. public void dump(PrintStream psOut, int indentAmount) {
  1653. PrintWriter out;
  1654. try {
  1655. out = new PrintWriter(new OutputStreamWriter(psOut,"JavaEsc"),
  1656. true);
  1657. } catch (UnsupportedEncodingException e){
  1658. out = new PrintWriter(psOut,true);
  1659. }
  1660. indent(out, indentAmount);
  1661. if (getName() == null) {
  1662. out.print("<??");
  1663. } else {
  1664. out.print("<" + getName());
  1665. }
  1666. if (getAttributeCount() > 0) {
  1667. out.println("");
  1668. // dump the attributes
  1669. Enumeration names = attributes.getAttributeNames();
  1670. while (names.hasMoreElements()) {
  1671. Object name = names.nextElement();
  1672. indent(out, indentAmount + 1);
  1673. out.println(name + "=" + getAttribute(name));
  1674. }
  1675. indent(out, indentAmount);
  1676. }
  1677. out.println(">");
  1678. if (isLeaf()) {
  1679. indent(out, indentAmount+1);
  1680. out.print("[" + getStartOffset() + "," + getEndOffset() + "]");
  1681. Content c = getContent();
  1682. try {
  1683. String contentStr = c.getString(getStartOffset(),
  1684. getEndOffset() - getStartOffset())/*.trim()*/;
  1685. if (contentStr.length() > 40) {
  1686. contentStr = contentStr.substring(0, 40) + "...";
  1687. }
  1688. out.println("["+contentStr+"]");
  1689. } catch (BadLocationException e) {
  1690. ;
  1691. }
  1692. } else {
  1693. int n = getElementCount();
  1694. for (int i = 0; i < n; i++) {
  1695. AbstractElement e = (AbstractElement) getElement(i);
  1696. e.dump(psOut, indentAmount+1);
  1697. }
  1698. }
  1699. }
  1700. // --- AttributeSet ----------------------------
  1701. // delegated to the immutable field "attributes"
  1702. /**
  1703. * Gets the number of attributes that are defined.
  1704. *
  1705. * @return the number of attributes >= 0
  1706. * @see AttributeSet#getAttributeCount
  1707. */
  1708. public int getAttributeCount() {
  1709. return attributes.getAttributeCount();
  1710. }
  1711. /**
  1712. * Checks whether a given attribute is defined.
  1713. *
  1714. * @param attrName the non-null attribute name
  1715. * @return true if the attribute is defined
  1716. * @see AttributeSet#isDefined
  1717. */
  1718. public boolean isDefined(Object attrName) {
  1719. return attributes.isDefined(attrName);
  1720. }
  1721. /**
  1722. * Checks whether two attribute sets are equal.
  1723. *
  1724. * @param attr the attribute set to check against
  1725. * @return true if the same
  1726. * @see AttributeSet#isEqual
  1727. */
  1728. public boolean isEqual(AttributeSet attr) {
  1729. return attributes.isEqual(attr);
  1730. }
  1731. /**
  1732. * Copies a set of attributes.
  1733. *
  1734. * @return the copy
  1735. * @see AttributeSet#copyAttributes
  1736. */
  1737. public AttributeSet copyAttributes() {
  1738. return attributes.copyAttributes();
  1739. }
  1740. /**
  1741. * Gets the value of an attribute.
  1742. *
  1743. * @param attrName the non-null attribute name
  1744. * @return the attribute value
  1745. * @see AttributeSet#getAttribute
  1746. */
  1747. public Object getAttribute(Object attrName) {
  1748. Object value = attributes.getAttribute(attrName);
  1749. if (value == null) {
  1750. // The delegate nor it's resolvers had a match,
  1751. // so we'll try to resolve through the parent
  1752. // element.
  1753. AttributeSet a = (parent != null) ? parent.getAttributes() : null;
  1754. if (a != null) {
  1755. value = a.getAttribute(attrName);
  1756. }
  1757. }
  1758. return value;
  1759. }
  1760. /**
  1761. * Gets the names of all attributes.
  1762. *
  1763. * @return the attribute names as an enumeration
  1764. * @see AttributeSet#getAttributeNames
  1765. */
  1766. public Enumeration<?> getAttributeNames() {
  1767. return attributes.getAttributeNames();
  1768. }
  1769. /**
  1770. * Checks whether a given attribute name/value is defined.
  1771. *
  1772. * @param name the non-null attribute name
  1773. * @param value the attribute value
  1774. * @return true if the name/value is defined
  1775. * @see AttributeSet#containsAttribute
  1776. */
  1777. public boolean containsAttribute(Object name, Object value) {
  1778. return attributes.containsAttribute(name, value);
  1779. }
  1780. /**
  1781. * Checks whether the element contains all the attributes.
  1782. *
  1783. * @param attrs the attributes to check
  1784. * @return true if the element contains all the attributes
  1785. * @see AttributeSet#containsAttributes
  1786. */
  1787. public boolean containsAttributes(AttributeSet attrs) {
  1788. return attributes.containsAttributes(attrs);
  1789. }
  1790. /**
  1791. * Gets the resolving parent.
  1792. * If not overridden, the resolving parent defaults to
  1793. * the parent element.
  1794. *
  1795. * @return the attributes from the parent, <code>null</code> if none
  1796. * @see AttributeSet#getResolveParent
  1797. */
  1798. public AttributeSet getResolveParent() {
  1799. AttributeSet a = attributes.getResolveParent();
  1800. if ((a == null) && (parent != null)) {
  1801. a = parent.getAttributes();
  1802. }
  1803. return a;
  1804. }
  1805. // --- MutableAttributeSet ----------------------------------
  1806. // should fetch a new immutable record for the field
  1807. // "attributes".
  1808. /**
  1809. * Adds an attribute to the element.
  1810. *
  1811. * @param name the non-null attribute name
  1812. * @param value the attribute value
  1813. * @see MutableAttributeSet#addAttribute
  1814. */
  1815. public void addAttribute(Object name, Object value) {
  1816. checkForIllegalCast();
  1817. AttributeContext context = getAttributeContext();
  1818. attributes = context.addAttribute(attributes, name, value);
  1819. }
  1820. /**
  1821. * Adds a set of attributes to the element.
  1822. *
  1823. * @param attr the attributes to add
  1824. * @see MutableAttributeSet#addAttribute
  1825. */
  1826. public void addAttributes(AttributeSet attr) {
  1827. checkForIllegalCast();
  1828. AttributeContext context = getAttributeContext();
  1829. attributes = context.addAttributes(attributes, attr);
  1830. }
  1831. /**
  1832. * Removes an attribute from the set.
  1833. *
  1834. * @param name the non-null attribute name
  1835. * @see MutableAttributeSet#removeAttribute
  1836. */
  1837. public void removeAttribute(Object name) {
  1838. checkForIllegalCast();
  1839. AttributeContext context = getAttributeContext();
  1840. attributes = context.removeAttribute(attributes, name);
  1841. }
  1842. /**
  1843. * Removes a set of attributes for the element.
  1844. *
  1845. * @param names the attribute names
  1846. * @see MutableAttributeSet#removeAttributes
  1847. */
  1848. public void removeAttributes(Enumeration<?> names) {
  1849. checkForIllegalCast();
  1850. AttributeContext context = getAttributeContext();
  1851. attributes = context.removeAttributes(attributes, names);
  1852. }
  1853. /**
  1854. * Removes a set of attributes for the element.
  1855. *
  1856. * @param attrs the attributes
  1857. * @see MutableAttributeSet#removeAttributes
  1858. */
  1859. public void removeAttributes(AttributeSet attrs) {
  1860. checkForIllegalCast();
  1861. AttributeContext context = getAttributeContext();
  1862. if (attrs == this) {
  1863. attributes = context.getEmptySet();
  1864. } else {
  1865. attributes = context.removeAttributes(attributes, attrs);
  1866. }
  1867. }
  1868. /**
  1869. * Sets the resolving parent.
  1870. *
  1871. * @param parent the parent, null if none
  1872. * @see MutableAttributeSet#setResolveParent
  1873. */
  1874. public void setResolveParent(AttributeSet parent) {
  1875. checkForIllegalCast();
  1876. AttributeContext context = getAttributeContext();
  1877. if (parent != null) {
  1878. attributes =
  1879. context.addAttribute(attributes, StyleConstants.ResolveAttribute,
  1880. parent);
  1881. } else {
  1882. attributes =
  1883. context.removeAttribute(attributes, StyleConstants.ResolveAttribute);
  1884. }
  1885. }
  1886. private final void checkForIllegalCast() {
  1887. Thread t = getCurrentWriter();
  1888. if ((t == null) || (t != Thread.currentThread())) {
  1889. throw new StateInvariantError("Illegal cast to MutableAttributeSet");
  1890. }
  1891. }
  1892. // --- Element methods -------------------------------------
  1893. /**
  1894. * Retrieves the underlying model.
  1895. *
  1896. * @return the model
  1897. */
  1898. public Document getDocument() {
  1899. return AbstractDocument.this;
  1900. }
  1901. /**
  1902. * Gets the parent of the element.
  1903. *
  1904. * @return the parent
  1905. */
  1906. public Element getParentElement() {
  1907. return parent;
  1908. }
  1909. /**
  1910. * Gets the attributes for the element.
  1911. *
  1912. * @return the attribute set
  1913. */
  1914. public AttributeSet getAttributes() {
  1915. return this;
  1916. }
  1917. /**
  1918. * Gets the name of the element.
  1919. *
  1920. * @return the name, null if none
  1921. */
  1922. public String getName() {
  1923. if (attributes.isDefined(ElementNameAttribute)) {
  1924. return (String) attributes.getAttribute(ElementNameAttribute);
  1925. }
  1926. return null;
  1927. }
  1928. /**
  1929. * Gets the starting offset in the model for the element.
  1930. *
  1931. * @return the offset >= 0
  1932. */
  1933. public abstract int getStartOffset();
  1934. /**
  1935. * Gets the ending offset in the model for the element.
  1936. *
  1937. * @return the offset >= 0
  1938. */
  1939. public abstract int getEndOffset();
  1940. /**
  1941. * Gets a child element.
  1942. *
  1943. * @param index the child index, >= 0 && < getElementCount()
  1944. * @return the child element
  1945. */
  1946. public abstract Element getElement(int index);
  1947. /**
  1948. * Gets the number of children for the element.
  1949. *
  1950. * @return the number of children >= 0
  1951. */
  1952. public abstract int getElementCount();
  1953. /**
  1954. * Gets the child element index closest to the given model offset.
  1955. *
  1956. * @param offset the offset >= 0
  1957. * @return the element index >= 0
  1958. */
  1959. public abstract int getElementIndex(int offset);
  1960. /**
  1961. * Checks whether the element is a leaf.
  1962. *
  1963. * @return true if a leaf
  1964. */
  1965. public abstract boolean isLeaf();
  1966. // --- TreeNode methods -------------------------------------
  1967. /**
  1968. * Returns the child <code>TreeNode</code> at index
  1969. * <code>childIndex</code>.
  1970. */
  1971. public TreeNode getChildAt(int childIndex) {
  1972. return (TreeNode)getElement(childIndex);
  1973. }
  1974. /**
  1975. * Returns the number of children <code>TreeNode</code>'s
  1976. * receiver contains.
  1977. * @return the number of children <code>TreeNodews</code>'s
  1978. * receiver contains
  1979. */
  1980. public int getChildCount() {
  1981. return getElementCount();
  1982. }
  1983. /**
  1984. * Returns the parent <code>TreeNode</code> of the receiver.
  1985. * @return the parent <code>TreeNode</code> of the receiver
  1986. */
  1987. public TreeNode getParent() {
  1988. return (TreeNode)getParentElement();
  1989. }
  1990. /**
  1991. * Returns the index of <code>node</code> in the receivers children.
  1992. * If the receiver does not contain <code>node</code>, -1 will be
  1993. * returned.
  1994. * @param node the location of interest
  1995. * @return the index of <code>node</code> in the receiver's
  1996. * children, or -1 if absent
  1997. */
  1998. public int getIndex(TreeNode node) {
  1999. for(int counter = getChildCount() - 1; counter >= 0; counter--)
  2000. if(getChildAt(counter) == node)
  2001. return counter;
  2002. return -1;
  2003. }
  2004. /**
  2005. * Returns true if the receiver allows children.
  2006. * @return true if the receiver allows children, otherwise false
  2007. */
  2008. public abstract boolean getAllowsChildren();
  2009. /**
  2010. * Returns the children of the receiver as an
  2011. * <code>Enumeration</code>.
  2012. * @return the children of the receiver as an <code>Enumeration</code>
  2013. */
  2014. public abstract Enumeration children();
  2015. // --- serialization ---------------------------------------------
  2016. private void writeObject(ObjectOutputStream s) throws IOException {
  2017. s.defaultWriteObject();
  2018. StyleContext.writeAttributeSet(s, attributes);
  2019. }
  2020. private void readObject(ObjectInputStream s)
  2021. throws ClassNotFoundException, IOException
  2022. {
  2023. s.defaultReadObject();
  2024. MutableAttributeSet attr = new SimpleAttributeSet();
  2025. StyleContext.readAttributeSet(s, attr);
  2026. AttributeContext context = getAttributeContext();
  2027. attributes = context.addAttributes(SimpleAttributeSet.EMPTY, attr);
  2028. }
  2029. // ---- variables -----------------------------------------------------
  2030. private Element parent;
  2031. private transient AttributeSet attributes;
  2032. }
  2033. /**
  2034. * Implements a composite element that contains other elements.
  2035. * <p>
  2036. * <strong>Warning:</strong>
  2037. * Serialized objects of this class will not be compatible with
  2038. * future Swing releases. The current serialization support is
  2039. * appropriate for short term storage or RMI between applications running
  2040. * the same version of Swing. As of 1.4, support for long term storage
  2041. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  2042. * has been added to the <code>java.beans</code> package.
  2043. * Please see {@link java.beans.XMLEncoder}.
  2044. */
  2045. public class BranchElement extends AbstractElement {
  2046. /**
  2047. * Constructs a composite element that initially contains
  2048. * no children.
  2049. *
  2050. * @param parent The parent element
  2051. * @param a the attributes for the element
  2052. */
  2053. public BranchElement(Element parent, AttributeSet a) {
  2054. super(parent, a);
  2055. children = new AbstractElement[1];
  2056. nchildren = 0;
  2057. lastIndex = -1;
  2058. }
  2059. /**
  2060. * Gets the child element that contains
  2061. * the given model position.
  2062. *
  2063. * @param pos the position >= 0
  2064. * @return the element, null if none
  2065. */
  2066. public Element positionToElement(int pos) {
  2067. int index = getElementIndex(pos);
  2068. Element child = children[index];
  2069. int p0 = child.getStartOffset();
  2070. int p1 = child.getEndOffset();
  2071. if ((pos >= p0) && (pos < p1)) {
  2072. return child;
  2073. }
  2074. return null;
  2075. }
  2076. /**
  2077. * Replaces content with a new set of elements.
  2078. *
  2079. * @param offset the starting offset >= 0
  2080. * @param length the length to replace >= 0
  2081. * @param elems the new elements
  2082. */
  2083. public void replace(int offset, int length, Element[] elems) {
  2084. int delta = elems.length - length;
  2085. int src = offset + length;
  2086. int nmove = nchildren - src;
  2087. int dest = src + delta;
  2088. if ((nchildren + delta) >= children.length) {
  2089. // need to grow the array
  2090. int newLength = Math.max(2*children.length, nchildren + delta);
  2091. AbstractElement[] newChildren = new AbstractElement[newLength];
  2092. System.arraycopy(children, 0, newChildren, 0, offset);
  2093. System.arraycopy(elems, 0, newChildren, offset, elems.length);
  2094. System.arraycopy(children, src, newChildren, dest, nmove);
  2095. children = newChildren;
  2096. } else {
  2097. // patch the existing array
  2098. System.arraycopy(children, src, children, dest, nmove);
  2099. System.arraycopy(elems, 0, children, offset, elems.length);
  2100. }
  2101. nchildren = nchildren + delta;
  2102. }
  2103. /**
  2104. * Converts the element to a string.
  2105. *
  2106. * @return the string
  2107. */
  2108. public String toString() {
  2109. return "BranchElement(" + getName() + ") " + getStartOffset() + "," +
  2110. getEndOffset() + "\n";
  2111. }
  2112. // --- Element methods -----------------------------------
  2113. /**
  2114. * Gets the element name.
  2115. *
  2116. * @return the element name
  2117. */
  2118. public String getName() {
  2119. String nm = super.getName();
  2120. if (nm == null) {
  2121. nm = ParagraphElementName;
  2122. }
  2123. return nm;
  2124. }
  2125. /**
  2126. * Gets the starting offset in the model for the element.
  2127. *
  2128. * @return the offset >= 0
  2129. */
  2130. public int getStartOffset() {
  2131. return children[0].getStartOffset();
  2132. }
  2133. /**
  2134. * Gets the ending offset in the model for the element.
  2135. * @throws NullPointerException if this element has no children
  2136. *
  2137. * @return the offset >= 0
  2138. */
  2139. public int getEndOffset() {
  2140. Element child =
  2141. (nchildren > 0) ? children[nchildren - 1] : children[0];
  2142. return child.getEndOffset();
  2143. }
  2144. /**
  2145. * Gets a child element.
  2146. *
  2147. * @param index the child index, >= 0 && < getElementCount()
  2148. * @return the child element, null if none
  2149. */
  2150. public Element getElement(int index) {
  2151. if (index < nchildren) {
  2152. return children[index];
  2153. }
  2154. return null;
  2155. }
  2156. /**
  2157. * Gets the number of children for the element.
  2158. *
  2159. * @return the number of children >= 0
  2160. */
  2161. public int getElementCount() {
  2162. return nchildren;
  2163. }
  2164. /**
  2165. * Gets the child element index closest to the given model offset.
  2166. *
  2167. * @param offset the offset >= 0
  2168. * @return the element index >= 0
  2169. */
  2170. public int getElementIndex(int offset) {
  2171. int index;
  2172. int lower = 0;
  2173. int upper = nchildren - 1;
  2174. int mid = 0;
  2175. int p0 = getStartOffset();
  2176. int p1;
  2177. if (nchildren == 0) {
  2178. return 0;
  2179. }
  2180. if (offset >= getEndOffset()) {
  2181. return nchildren - 1;
  2182. }
  2183. // see if the last index can be used.
  2184. if ((lastIndex >= lower) && (lastIndex <= upper)) {
  2185. Element lastHit = children[lastIndex];
  2186. p0 = lastHit.getStartOffset();
  2187. p1 = lastHit.getEndOffset();
  2188. if ((offset >= p0) && (offset < p1)) {
  2189. return lastIndex;
  2190. }
  2191. // last index wasn't a hit, but it does give useful info about
  2192. // where a hit (if any) would be.
  2193. if (offset < p0) {
  2194. upper = lastIndex;
  2195. } else {
  2196. lower = lastIndex;
  2197. }
  2198. }
  2199. while (lower <= upper) {
  2200. mid = lower + ((upper - lower) / 2);
  2201. Element elem = children[mid];
  2202. p0 = elem.getStartOffset();
  2203. p1 = elem.getEndOffset();
  2204. if ((offset >= p0) && (offset < p1)) {
  2205. // found the location
  2206. index = mid;
  2207. lastIndex = index;
  2208. return index;
  2209. } else if (offset < p0) {
  2210. upper = mid - 1;
  2211. } else {
  2212. lower = mid + 1;
  2213. }
  2214. }
  2215. // didn't find it, but we indicate the index of where it would belong
  2216. if (offset < p0) {
  2217. index = mid;
  2218. } else {
  2219. index = mid + 1;
  2220. }
  2221. lastIndex = index;
  2222. return index;
  2223. }
  2224. /**
  2225. * Checks whether the element is a leaf.
  2226. *
  2227. * @return true if a leaf
  2228. */
  2229. public boolean isLeaf() {
  2230. return false;
  2231. }
  2232. // ------ TreeNode ----------------------------------------------
  2233. /**
  2234. * Returns true if the receiver allows children.
  2235. * @return true if the receiver allows children, otherwise false
  2236. */
  2237. public boolean getAllowsChildren() {
  2238. return true;
  2239. }
  2240. /**
  2241. * Returns the children of the receiver as an
  2242. * <code>Enumeration</code>.
  2243. * @return the children of the receiver
  2244. */
  2245. public Enumeration children() {
  2246. if(nchildren == 0)
  2247. return null;
  2248. Vector tempVector = new Vector(nchildren);
  2249. for(int counter = 0; counter < nchildren; counter++)
  2250. tempVector.addElement(children[counter]);
  2251. return tempVector.elements();
  2252. }
  2253. // ------ members ----------------------------------------------
  2254. private AbstractElement[] children;
  2255. private int nchildren;
  2256. private int lastIndex;
  2257. }
  2258. /**
  2259. * Implements an element that directly represents content of
  2260. * some kind.
  2261. * <p>
  2262. * <strong>Warning:</strong>
  2263. * Serialized objects of this class will not be compatible with
  2264. * future Swing releases. The current serialization support is
  2265. * appropriate for short term storage or RMI between applications running
  2266. * the same version of Swing. As of 1.4, support for long term storage
  2267. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  2268. * has been added to the <code>java.beans</code> package.
  2269. * Please see {@link java.beans.XMLEncoder}.
  2270. *
  2271. * @see Element
  2272. */
  2273. public class LeafElement extends AbstractElement {
  2274. /**
  2275. * Constructs an element that represents content within the
  2276. * document (has no children).
  2277. *
  2278. * @param parent The parent element
  2279. * @param a The element attributes
  2280. * @param offs0 The start offset >= 0
  2281. * @param offs1 The end offset >= offs0
  2282. */
  2283. public LeafElement(Element parent, AttributeSet a, int offs0, int offs1) {
  2284. super(parent, a);
  2285. try {
  2286. p0 = createPosition(offs0);
  2287. p1 = createPosition(offs1);
  2288. } catch (BadLocationException e) {
  2289. p0 = null;
  2290. p1 = null;
  2291. throw new StateInvariantError("Can't create Position references");
  2292. }
  2293. }
  2294. /**
  2295. * Converts the element to a string.
  2296. *
  2297. * @return the string
  2298. */
  2299. public String toString() {
  2300. return "LeafElement(" + getName() + ") " + p0 + "," + p1 + "\n";
  2301. }
  2302. // --- Element methods ---------------------------------------------
  2303. /**
  2304. * Gets the starting offset in the model for the element.
  2305. *
  2306. * @return the offset >= 0
  2307. */
  2308. public int getStartOffset() {
  2309. return p0.getOffset();
  2310. }
  2311. /**
  2312. * Gets the ending offset in the model for the element.
  2313. *
  2314. * @return the offset >= 0
  2315. */
  2316. public int getEndOffset() {
  2317. return p1.getOffset();
  2318. }
  2319. /**
  2320. * Gets the element name.
  2321. *
  2322. * @return the name
  2323. */
  2324. public String getName() {
  2325. String nm = super.getName();
  2326. if (nm == null) {
  2327. nm = ContentElementName;
  2328. }
  2329. return nm;
  2330. }
  2331. /**
  2332. * Gets the child element index closest to the given model offset.
  2333. *
  2334. * @param pos the offset >= 0
  2335. * @return the element index >= 0
  2336. */
  2337. public int getElementIndex(int pos) {
  2338. return -1;
  2339. }
  2340. /**
  2341. * Gets a child element.
  2342. *
  2343. * @param index the child index, >= 0 && < getElementCount()
  2344. * @return the child element
  2345. */
  2346. public Element getElement(int index) {
  2347. return null;
  2348. }
  2349. /**
  2350. * Returns the number of child elements.
  2351. *
  2352. * @return the number of children >= 0
  2353. */
  2354. public int getElementCount() {
  2355. return 0;
  2356. }
  2357. /**
  2358. * Checks whether the element is a leaf.
  2359. *
  2360. * @return true if a leaf
  2361. */
  2362. public boolean isLeaf() {
  2363. return true;
  2364. }
  2365. // ------ TreeNode ----------------------------------------------
  2366. /**
  2367. * Returns true if the receiver allows children.
  2368. * @return true if the receiver allows children, otherwise false
  2369. */
  2370. public boolean getAllowsChildren() {
  2371. return false;
  2372. }
  2373. /**
  2374. * Returns the children of the receiver as an
  2375. * <code>Enumeration</code>.
  2376. * @return the children of the receiver
  2377. */
  2378. public Enumeration children() {
  2379. return null;
  2380. }
  2381. // --- serialization ---------------------------------------------
  2382. private void writeObject(ObjectOutputStream s) throws IOException {
  2383. s.defaultWriteObject();
  2384. s.writeInt(p0.getOffset());
  2385. s.writeInt(p1.getOffset());
  2386. }
  2387. private void readObject(ObjectInputStream s)
  2388. throws ClassNotFoundException, IOException
  2389. {
  2390. s.defaultReadObject();
  2391. // set the range with positions that track change
  2392. int off0 = s.readInt();
  2393. int off1 = s.readInt();
  2394. try {
  2395. p0 = createPosition(off0);
  2396. p1 = createPosition(off1);
  2397. } catch (BadLocationException e) {
  2398. p0 = null;
  2399. p1 = null;
  2400. throw new IOException("Can't restore Position references");
  2401. }
  2402. }
  2403. // ---- members -----------------------------------------------------
  2404. private transient Position p0;
  2405. private transient Position p1;
  2406. }
  2407. /**
  2408. * Represents the root element of the bidirectional element structure.
  2409. * The root element is the only element in the bidi element structure
  2410. * which contains children.
  2411. */
  2412. class BidiRootElement extends BranchElement {
  2413. BidiRootElement() {
  2414. super( null, null );
  2415. }
  2416. /**
  2417. * Gets the name of the element.
  2418. * @return the name
  2419. */
  2420. public String getName() {
  2421. return "bidi root";
  2422. }
  2423. }
  2424. /**
  2425. * Represents an element of the bidirectional element structure.
  2426. */
  2427. class BidiElement extends LeafElement {
  2428. /**
  2429. * Creates a new BidiElement.
  2430. */
  2431. BidiElement(Element parent, int start, int end, int level) {
  2432. super(parent, new SimpleAttributeSet(), start, end);
  2433. addAttribute(StyleConstants.BidiLevel, new Integer(level));
  2434. //System.out.println("BidiElement: start = " + start
  2435. // + " end = " + end + " level = " + level );
  2436. }
  2437. /**
  2438. * Gets the name of the element.
  2439. * @return the name
  2440. */
  2441. public String getName() {
  2442. return BidiElementName;
  2443. }
  2444. int getLevel() {
  2445. Integer o = (Integer) getAttribute(StyleConstants.BidiLevel);
  2446. if (o != null) {
  2447. return o.intValue();
  2448. }
  2449. return 0; // Level 0 is base level (non-embedded) left-to-right
  2450. }
  2451. boolean isLeftToRight() {
  2452. return ((getLevel() % 2) == 0);
  2453. }
  2454. }
  2455. /**
  2456. * Stores document changes as the document is being
  2457. * modified. Can subsequently be used for change notification
  2458. * when done with the document modification transaction.
  2459. * This is used by the AbstractDocument class and its extensions
  2460. * for broadcasting change information to the document listeners.
  2461. */
  2462. public class DefaultDocumentEvent extends CompoundEdit implements DocumentEvent {
  2463. /**
  2464. * Constructs a change record.
  2465. *
  2466. * @param offs the offset into the document of the change >= 0
  2467. * @param len the length of the change >= 0
  2468. * @param type the type of event (DocumentEvent.EventType)
  2469. */
  2470. public DefaultDocumentEvent(int offs, int len, DocumentEvent.EventType type) {
  2471. super();
  2472. offset = offs;
  2473. length = len;
  2474. this.type = type;
  2475. }
  2476. /**
  2477. * Returns a string description of the change event.
  2478. *
  2479. * @return a string
  2480. */
  2481. public String toString() {
  2482. return edits.toString();
  2483. }
  2484. // --- CompoundEdit methods --------------------------
  2485. /**
  2486. * Adds a document edit. If the number of edits crosses
  2487. * a threshold, this switches on a hashtable lookup for
  2488. * ElementChange implementations since access of these
  2489. * needs to be relatively quick.
  2490. *
  2491. * @param anEdit a document edit record
  2492. * @return true if the edit was added
  2493. */
  2494. public boolean addEdit(UndoableEdit anEdit) {
  2495. // if the number of changes gets too great, start using
  2496. // a hashtable for to locate the change for a given element.
  2497. if ((changeLookup == null) && (edits.size() > 10)) {
  2498. changeLookup = new Hashtable();
  2499. int n = edits.size();
  2500. for (int i = 0; i < n; i++) {
  2501. Object o = edits.elementAt(i);
  2502. if (o instanceof DocumentEvent.ElementChange) {
  2503. DocumentEvent.ElementChange ec = (DocumentEvent.ElementChange) o;
  2504. changeLookup.put(ec.getElement(), ec);
  2505. }
  2506. }
  2507. }
  2508. // if we have a hashtable... add the entry if it's
  2509. // an ElementChange.
  2510. if ((changeLookup != null) && (anEdit instanceof DocumentEvent.ElementChange)) {
  2511. DocumentEvent.ElementChange ec = (DocumentEvent.ElementChange) anEdit;
  2512. changeLookup.put(ec.getElement(), ec);
  2513. }
  2514. return super.addEdit(anEdit);
  2515. }
  2516. /**
  2517. * Redoes a change.
  2518. *
  2519. * @exception CannotRedoException if the change cannot be redone
  2520. */
  2521. public void redo() throws CannotRedoException {
  2522. writeLock();
  2523. try {
  2524. // change the state
  2525. super.redo();
  2526. // fire a DocumentEvent to notify the view(s)
  2527. UndoRedoDocumentEvent ev = new UndoRedoDocumentEvent(this, false);
  2528. if (type == DocumentEvent.EventType.INSERT) {
  2529. fireInsertUpdate(ev);
  2530. } else if (type == DocumentEvent.EventType.REMOVE) {
  2531. fireRemoveUpdate(ev);
  2532. } else {
  2533. fireChangedUpdate(ev);
  2534. }
  2535. } finally {
  2536. writeUnlock();
  2537. }
  2538. }
  2539. /**
  2540. * Undoes a change.
  2541. *
  2542. * @exception CannotUndoException if the change cannot be undone
  2543. */
  2544. public void undo() throws CannotUndoException {
  2545. writeLock();
  2546. try {
  2547. // change the state
  2548. super.undo();
  2549. // fire a DocumentEvent to notify the view(s)
  2550. UndoRedoDocumentEvent ev = new UndoRedoDocumentEvent(this, true);
  2551. if (type == DocumentEvent.EventType.REMOVE) {
  2552. fireInsertUpdate(ev);
  2553. } else if (type == DocumentEvent.EventType.INSERT) {
  2554. fireRemoveUpdate(ev);
  2555. } else {
  2556. fireChangedUpdate(ev);
  2557. }
  2558. } finally {
  2559. writeUnlock();
  2560. }
  2561. }
  2562. /**
  2563. * DefaultDocument events are significant. If you wish to aggregate
  2564. * DefaultDocumentEvents to present them as a single edit to the user
  2565. * place them into a CompoundEdit.
  2566. *
  2567. * @return whether the event is significant for edit undo purposes
  2568. */
  2569. public boolean isSignificant() {
  2570. return true;
  2571. }
  2572. /**
  2573. * Provides a localized, human readable description of this edit
  2574. * suitable for use in, say, a change log.
  2575. *
  2576. * @return the description
  2577. */
  2578. public String getPresentationName() {
  2579. DocumentEvent.EventType type = getType();
  2580. if(type == DocumentEvent.EventType.INSERT)
  2581. return UIManager.getString("AbstractDocument.additionText");
  2582. if(type == DocumentEvent.EventType.REMOVE)
  2583. return UIManager.getString("AbstractDocument.deletionText");
  2584. return UIManager.getString("AbstractDocument.styleChangeText");
  2585. }
  2586. /**
  2587. * Provides a localized, human readable description of the undoable
  2588. * form of this edit, e.g. for use as an Undo menu item. Typically
  2589. * derived from getDescription();
  2590. *
  2591. * @return the description
  2592. */
  2593. public String getUndoPresentationName() {
  2594. return UIManager.getString("AbstractDocument.undoText") + " " +
  2595. getPresentationName();
  2596. }
  2597. /**
  2598. * Provides a localized, human readable description of the redoable
  2599. * form of this edit, e.g. for use as a Redo menu item. Typically
  2600. * derived from getPresentationName();
  2601. *
  2602. * @return the description
  2603. */
  2604. public String getRedoPresentationName() {
  2605. return UIManager.getString("AbstractDocument.redoText") + " " +
  2606. getPresentationName();
  2607. }
  2608. // --- DocumentEvent methods --------------------------
  2609. /**
  2610. * Returns the type of event.
  2611. *
  2612. * @return the event type as a DocumentEvent.EventType
  2613. * @see DocumentEvent#getType
  2614. */
  2615. public DocumentEvent.EventType getType() {
  2616. return type;
  2617. }
  2618. /**
  2619. * Returns the offset within the document of the start of the change.
  2620. *
  2621. * @return the offset >= 0
  2622. * @see DocumentEvent#getOffset
  2623. */
  2624. public int getOffset() {
  2625. return offset;
  2626. }
  2627. /**
  2628. * Returns the length of the change.
  2629. *
  2630. * @return the length >= 0
  2631. * @see DocumentEvent#getLength
  2632. */
  2633. public int getLength() {
  2634. return length;
  2635. }
  2636. /**
  2637. * Gets the document that sourced the change event.
  2638. *
  2639. * @return the document
  2640. * @see DocumentEvent#getDocument
  2641. */
  2642. public Document getDocument() {
  2643. return AbstractDocument.this;
  2644. }
  2645. /**
  2646. * Gets the changes for an element.
  2647. *
  2648. * @param elem the element
  2649. * @return the changes
  2650. */
  2651. public DocumentEvent.ElementChange getChange(Element elem) {
  2652. if (changeLookup != null) {
  2653. return (DocumentEvent.ElementChange) changeLookup.get(elem);
  2654. }
  2655. int n = edits.size();
  2656. for (int i = 0; i < n; i++) {
  2657. Object o = edits.elementAt(i);
  2658. if (o instanceof DocumentEvent.ElementChange) {
  2659. DocumentEvent.ElementChange c = (DocumentEvent.ElementChange) o;
  2660. if (elem.equals(c.getElement())) {
  2661. return c;
  2662. }
  2663. }
  2664. }
  2665. return null;
  2666. }
  2667. // --- member variables ------------------------------------
  2668. private int offset;
  2669. private int length;
  2670. private Hashtable changeLookup;
  2671. private DocumentEvent.EventType type;
  2672. }
  2673. /**
  2674. * This event used when firing document changes while Undo/Redo
  2675. * operations. It just wraps DefaultDocumentEvent and delegates
  2676. * all calls to it except getType() which depends on operation
  2677. * (Undo or Redo).
  2678. */
  2679. class UndoRedoDocumentEvent implements DocumentEvent {
  2680. private DefaultDocumentEvent src = null;
  2681. private boolean isUndo;
  2682. private EventType type = null;
  2683. public UndoRedoDocumentEvent(DefaultDocumentEvent src, boolean isUndo) {
  2684. this.src = src;
  2685. this.isUndo = isUndo;
  2686. if(isUndo) {
  2687. if(src.getType().equals(EventType.INSERT)) {
  2688. type = EventType.REMOVE;
  2689. } else if(src.getType().equals(EventType.REMOVE)) {
  2690. type = EventType.INSERT;
  2691. } else {
  2692. type = src.getType();
  2693. }
  2694. } else {
  2695. type = src.getType();
  2696. }
  2697. }
  2698. public DefaultDocumentEvent getSource() {
  2699. return src;
  2700. }
  2701. // DocumentEvent methods delegated to DefaultDocumentEvent source
  2702. // except getType() which depends on operation (Undo or Redo).
  2703. public int getOffset() {
  2704. return src.getOffset();
  2705. }
  2706. public int getLength() {
  2707. return src.getLength();
  2708. }
  2709. public Document getDocument() {
  2710. return src.getDocument();
  2711. }
  2712. public DocumentEvent.EventType getType() {
  2713. return type;
  2714. }
  2715. public DocumentEvent.ElementChange getChange(Element elem) {
  2716. return src.getChange(elem);
  2717. }
  2718. }
  2719. /**
  2720. * An implementation of ElementChange that can be added to the document
  2721. * event.
  2722. */
  2723. public static class ElementEdit extends AbstractUndoableEdit implements DocumentEvent.ElementChange {
  2724. /**
  2725. * Constructs an edit record. This does not modify the element
  2726. * so it can safely be used to <em>catch up</em> a view to the
  2727. * current model state for views that just attached to a model.
  2728. *
  2729. * @param e the element
  2730. * @param index the index into the model >= 0
  2731. * @param removed a set of elements that were removed
  2732. * @param added a set of elements that were added
  2733. */
  2734. public ElementEdit(Element e, int index, Element[] removed, Element[] added) {
  2735. super();
  2736. this.e = e;
  2737. this.index = index;
  2738. this.removed = removed;
  2739. this.added = added;
  2740. }
  2741. /**
  2742. * Returns the underlying element.
  2743. *
  2744. * @return the element
  2745. */
  2746. public Element getElement() {
  2747. return e;
  2748. }
  2749. /**
  2750. * Returns the index into the list of elements.
  2751. *
  2752. * @return the index >= 0
  2753. */
  2754. public int getIndex() {
  2755. return index;
  2756. }
  2757. /**
  2758. * Gets a list of children that were removed.
  2759. *
  2760. * @return the list
  2761. */
  2762. public Element[] getChildrenRemoved() {
  2763. return removed;
  2764. }
  2765. /**
  2766. * Gets a list of children that were added.
  2767. *
  2768. * @return the list
  2769. */
  2770. public Element[] getChildrenAdded() {
  2771. return added;
  2772. }
  2773. /**
  2774. * Redoes a change.
  2775. *
  2776. * @exception CannotRedoException if the change cannot be redone
  2777. */
  2778. public void redo() throws CannotRedoException {
  2779. super.redo();
  2780. // Since this event will be reused, switch around added/removed.
  2781. Element[] tmp = removed;
  2782. removed = added;
  2783. added = tmp;
  2784. // PENDING(prinz) need MutableElement interface, canRedo() should check
  2785. ((AbstractDocument.BranchElement)e).replace(index, removed.length, added);
  2786. }
  2787. /**
  2788. * Undoes a change.
  2789. *
  2790. * @exception CannotUndoException if the change cannot be undone
  2791. */
  2792. public void undo() throws CannotUndoException {
  2793. super.undo();
  2794. // PENDING(prinz) need MutableElement interface, canUndo() should check
  2795. ((AbstractDocument.BranchElement)e).replace(index, added.length, removed);
  2796. // Since this event will be reused, switch around added/removed.
  2797. Element[] tmp = removed;
  2798. removed = added;
  2799. added = tmp;
  2800. }
  2801. private Element e;
  2802. private int index;
  2803. private Element[] removed;
  2804. private Element[] added;
  2805. }
  2806. private class DefaultFilterBypass extends DocumentFilter.FilterBypass {
  2807. public Document getDocument() {
  2808. return AbstractDocument.this;
  2809. }
  2810. public void remove(int offset, int length) throws
  2811. BadLocationException {
  2812. handleRemove(offset, length);
  2813. }
  2814. public void insertString(int offset, String string,
  2815. AttributeSet attr) throws
  2816. BadLocationException {
  2817. handleInsertString(offset, string, attr);
  2818. }
  2819. public void replace(int offset, int length, String text,
  2820. AttributeSet attrs) throws BadLocationException {
  2821. handleRemove(offset, length);
  2822. handleInsertString(offset, text, attrs);
  2823. }
  2824. }
  2825. }