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. */