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