1. /*
  2. * @(#)AbstractDocument.java 1.151 04/07/13
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.text;
  8. import java.util.*;
  9. import java.io.*;
  10. import java.awt.font.TextAttribute;
  11. import java.text.Bidi;
  12. import javax.swing.UIManager;
  13. import javax.swing.undo.*;
  14. import javax.swing.event.ChangeListener;
  15. import javax.swing.event.*;
  16. import javax.swing.tree.TreeNode;
  17. import sun.font.BidiUtils;
  18. /**
  19. * An implementation of the document interface to serve as a
  20. * basis for implementing various kinds of documents. At this
  21. * level there is very little policy, so there is a corresponding
  22. * increase in difficulty of use.
  23. * <p>
  24. * This class implements a locking mechanism for the document. It
  25. * allows multiple readers or one writer, and writers must wait until
  26. * all observers of the document have been notified of a previous
  27. * change before beginning another mutation to the document. The
  28. * read lock is acquired and released using the <code>render</code>
  29. * method. A write lock is aquired by the methods that mutate the
  30. * document, and are held for the duration of the method call.
  31. * Notification is done on the thread that produced the mutation,
  32. * and the thread has full read access to the document for the
  33. * duration of the notification, but other readers are kept out
  34. * until the notification has finished. The notification is a
  35. * beans event notification which does not allow any further
  36. * mutations until all listeners have been notified.
  37. * <p>
  38. * Any models subclassed from this class and used in conjunction
  39. * with a text component that has a look and feel implementation
  40. * that is derived from BasicTextUI may be safely updated
  41. * asynchronously, because all access to the View hierarchy
  42. * is serialized by BasicTextUI if the document is of type
  43. * <code>AbstractDocument</code>. The locking assumes that an
  44. * independant thread will access the View hierarchy only from
  45. * the DocumentListener methods, and that there will be only
  46. * one event thread active at a time.
  47. * <p>
  48. * If concurrency support is desired, there are the following
  49. * additional implications. The code path for any DocumentListener
  50. * implementation and any UndoListener implementation must be threadsafe,
  51. * and not access the component lock if trying to be safe from deadlocks.
  52. * The <code>repaint</code> and <code>revalidate</code> methods
  53. * on JComponent are safe.
  54. * <p>
  55. * AbstractDocument models an implied break at the end of the document.
  56. * Among other things this allows you to position the caret after the last
  57. * character. As a result of this, <code>getLength</code> returns one less
  58. * than the length of the Content. If you create your own Content, be
  59. * sure and initialize it to have an additional character. Refer to
  60. * StringContent and GapContent for examples of this. Another implication
  61. * of this is that Elements that model the implied end character will have
  62. * an endOffset == (getLength() + 1). For example, in DefaultStyledDocument
  63. * <code>getParagraphElement(getLength()).getEndOffset() == getLength() + 1
  64. * </code>.
  65. * <p>
  66. * <strong>Warning:</strong>
  67. * Serialized objects of this class will not be compatible with
  68. * future Swing releases. The current serialization support is
  69. * appropriate for short term storage or RMI between applications running
  70. * the same version of Swing. As of 1.4, support for long term storage
  71. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  72. * has been added to the <code>java.beans</code> package.
  73. * Please see {@link java.beans.XMLEncoder}.
  74. *
  75. * @author Timothy Prinzing
  76. * @version 1.151 07/13/04
  77. */
  78. public abstract class AbstractDocument implements Document, Serializable {
  79. /**
  80. * Constructs a new <code>AbstractDocument</code>, wrapped around some
  81. * specified content storage mechanism.
  82. *
  83. * @param data the content
  84. */
  85. protected AbstractDocument(Content data) {
  86. this(data, StyleContext.getDefaultStyleContext());
  87. }
  88. /**
  89. * Constructs a new <code>AbstractDocument</code>, wrapped around some
  90. * specified content storage mechanism.
  91. *
  92. * @param data the content
  93. * @param context the attribute context
  94. */
  95. protected AbstractDocument(Content data, AttributeContext context) {
  96. this.data = data;
  97. this.context = context;
  98. bidiRoot = new BidiRootElement();
  99. if (defaultI18NProperty == null) {
  100. // determine default setting for i18n support
  101. Object o = java.security.AccessController.doPrivileged(
  102. new java.security.PrivilegedAction() {
  103. public Object run() {
  104. return System.getProperty(I18NProperty);
  105. }
  106. }
  107. );
  108. if (o != null) {
  109. defaultI18NProperty = Boolean.valueOf((String)o);
  110. } else {
  111. defaultI18NProperty = Boolean.FALSE;
  112. }
  113. }
  114. putProperty( I18NProperty, defaultI18NProperty);
  115. //REMIND(bcb) This creates an initial bidi element to account for
  116. //the \n that exists by default in the content. Doing it this way
  117. //seems to expose a little too much knowledge of the content given
  118. //to us by the sub-class. Consider having the sub-class' constructor
  119. //make an initial call to insertUpdate.
  120. writeLock();
  121. try {
  122. Element[] p = new Element[1];
  123. p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
  124. bidiRoot.replace(0,0,p);
  125. } finally {
  126. writeUnlock();
  127. }
  128. }
  129. /**
  130. * Supports managing a set of properties. Callers
  131. * can use the <code>documentProperties</code> dictionary
  132. * to annotate the document with document-wide properties.
  133. *
  134. * @return a non-<code>null</code> <code>Dictionary</code>
  135. * @see #setDocumentProperties
  136. */
  137. public Dictionary<Object,Object> getDocumentProperties() {
  138. if (documentProperties == null) {
  139. documentProperties = new Hashtable(2);
  140. }
  141. return documentProperties;
  142. }
  143. /**
  144. * Replaces the document properties dictionary for this document.
  145. *
  146. * @param x the new dictionary
  147. * @see #getDocumentProperties
  148. */
  149. public void setDocumentProperties(Dictionary<Object,Object> x) {
  150. documentProperties = x;
  151. }
  152. /**
  153. * Notifies all listeners that have registered interest for
  154. * notification on this event type. The event instance
  155. * is lazily created using the parameters passed into
  156. * the fire method.
  157. *
  158. * @param e the event
  159. * @see EventListenerList
  160. */
  161. protected void fireInsertUpdate(DocumentEvent e) {
  162. notifyingListeners = true;
  163. try {
  164. // Guaranteed to return a non-null array
  165. Object[] listeners = listenerList.getListenerList();
  166. // Process the listeners last to first, notifying
  167. // those that are interested in this event
  168. for (int i = listeners.length-2; i>=0; i-=2) {
  169. if (listeners[i]==DocumentListener.class) {
  170. // Lazily create the event:
  171. // if (e == null)
  172. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  173. ((DocumentListener)listeners[i+1]).insertUpdate(e);
  174. }
  175. }
  176. } finally {
  177. notifyingListeners = false;
  178. }
  179. }
  180. /**
  181. * Notifies all listeners that have registered interest for
  182. * notification on this event type. The event instance
  183. * is lazily created using the parameters passed into
  184. * the fire method.
  185. *
  186. * @param e the event
  187. * @see EventListenerList
  188. */
  189. protected void fireChangedUpdate(DocumentEvent e) {
  190. notifyingListeners = true;
  191. try {
  192. // Guaranteed to return a non-null array
  193. Object[] listeners = listenerList.getListenerList();
  194. // Process the listeners last to first, notifying
  195. // those that are interested in this event
  196. for (int i = listeners.length-2; i>=0; i-=2) {
  197. if (listeners[i]==DocumentListener.class) {
  198. // Lazily create the event:
  199. // if (e == null)
  200. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  201. ((DocumentListener)listeners[i+1]).changedUpdate(e);
  202. }
  203. }
  204. } finally {
  205. notifyingListeners = false;
  206. }
  207. }
  208. /**
  209. * Notifies all listeners that have registered interest for
  210. * notification on this event type. The event instance
  211. * is lazily created using the parameters passed into
  212. * the fire method.
  213. *
  214. * @param e the event
  215. * @see EventListenerList
  216. */
  217. protected void fireRemoveUpdate(DocumentEvent e) {
  218. notifyingListeners = true;
  219. try {
  220. // Guaranteed to return a non-null array
  221. Object[] listeners = listenerList.getListenerList();
  222. // Process the listeners last to first, notifying
  223. // those that are interested in this event
  224. for (int i = listeners.length-2; i>=0; i-=2) {
  225. if (listeners[i]==DocumentListener.class) {
  226. // Lazily create the event:
  227. // if (e == null)
  228. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  229. ((DocumentListener)listeners[i+1]).removeUpdate(e);
  230. }
  231. }
  232. } finally {
  233. notifyingListeners = false;
  234. }
  235. }
  236. /**
  237. * Notifies all listeners that have registered interest for
  238. * notification on this event type. The event instance
  239. * is lazily created using the parameters passed into
  240. * the fire method.
  241. *
  242. * @param e the event
  243. * @see EventListenerList
  244. */
  245. protected void fireUndoableEditUpdate(UndoableEditEvent e) {
  246. // Guaranteed to return a non-null array
  247. Object[] listeners = listenerList.getListenerList();
  248. // Process the listeners last to first, notifying
  249. // those that are interested in this event
  250. for (int i = listeners.length-2; i>=0; i-=2) {
  251. if (listeners[i]==UndoableEditListener.class) {
  252. // Lazily create the event:
  253. // if (e == null)
  254. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  255. ((UndoableEditListener)listeners[i+1]).undoableEditHappened(e);
  256. }
  257. }
  258. }
  259. /**
  260. * Returns an array of all the objects currently registered
  261. * as <code><em>Foo</em>Listener</code>s
  262. * upon this document.
  263. * <code><em>Foo</em>Listener</code>s are registered using the
  264. * <code>add<em>Foo</em>Listener</code> method.
  265. *
  266. * <p>
  267. * You can specify the <code>listenerType</code> argument
  268. * with a class literal, such as
  269. * <code><em>Foo</em>Listener.class</code>.
  270. * For example, you can query a
  271. * document <code>d</code>
  272. * for its document listeners with the following code:
  273. *
  274. * <pre>DocumentListener[] mls = (DocumentListener[])(d.getListeners(DocumentListener.class));</pre>
  275. *
  276. * If no such listeners exist, this method returns an empty array.
  277. *
  278. * @param listenerType the type of listeners requested; this parameter
  279. * should specify an interface that descends from
  280. * <code>java.util.EventListener</code>
  281. * @return an array of all objects registered as
  282. * <code><em>Foo</em>Listener</code>s on this component,
  283. * or an empty array if no such
  284. * listeners have been added
  285. * @exception ClassCastException if <code>listenerType</code>
  286. * doesn't specify a class or interface that implements
  287. * <code>java.util.EventListener</code>
  288. *
  289. * @see #getDocumentListeners
  290. * @see #getUndoableEditListeners
  291. *
  292. * @since 1.3
  293. */
  294. public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
  295. return listenerList.getListeners(listenerType);
  296. }
  297. /**
  298. * Gets the asynchronous loading priority. If less than zero,
  299. * the document should not be loaded asynchronously.
  300. *
  301. * @return the asynchronous loading priority, or <code>-1</code>
  302. * if the document should not be loaded asynchronously
  303. */
  304. public int getAsynchronousLoadPriority() {
  305. Integer loadPriority = (Integer)
  306. getProperty(AbstractDocument.AsyncLoadPriority);
  307. if (loadPriority != null) {
  308. return loadPriority.intValue();
  309. }
  310. return -1;
  311. }
  312. /**
  313. * Sets the asynchronous loading priority.
  314. * @param p the new asynchronous loading priority; a value
  315. * less than zero indicates that the document should not be
  316. * loaded asynchronously
  317. */
  318. public void setAsynchronousLoadPriority(int p) {
  319. Integer loadPriority = (p >= 0) ? new Integer(p) : null;
  320. putProperty(AbstractDocument.AsyncLoadPriority, loadPriority);
  321. }
  322. /**
  323. * Sets the <code>DocumentFilter</code>. The <code>DocumentFilter</code>
  324. * is passed <code>insert</code> and <code>remove</code> to conditionally
  325. * allow inserting/deleting of the text. A <code>null</code> value
  326. * indicates that no filtering will occur.
  327. *
  328. * @param filter the <code>DocumentFilter</code> used to constrain text
  329. * @see #getDocumentFilter
  330. * @since 1.4
  331. */
  332. public void setDocumentFilter(DocumentFilter filter) {
  333. documentFilter = filter;
  334. }
  335. /**
  336. * Returns the <code>DocumentFilter</code> that is responsible for
  337. * filtering of insertion/removal. A <code>null</code> return value
  338. * implies no filtering is to occur.
  339. *
  340. * @since 1.4
  341. * @see #setDocumentFilter
  342. * @return the DocumentFilter
  343. */
  344. public DocumentFilter getDocumentFilter() {
  345. return documentFilter;
  346. }
  347. // --- Document methods -----------------------------------------
  348. /**
  349. * This allows the model to be safely rendered in the presence
  350. * of currency, if the model supports being updated asynchronously.
  351. * The given runnable will be executed in a way that allows it
  352. * to safely read the model with no changes while the runnable
  353. * is being executed. The runnable itself may <em>not</em>
  354. * make any mutations.
  355. * <p>
  356. * This is implemented to aquire a read lock for the duration
  357. * of the runnables execution. There may be multiple runnables
  358. * executing at the same time, and all writers will be blocked
  359. * while there are active rendering runnables. If the runnable
  360. * throws an exception, its lock will be safely released.
  361. * There is no protection against a runnable that never exits,
  362. * which will effectively leave the document locked for it's
  363. * lifetime.
  364. * <p>
  365. * If the given runnable attempts to make any mutations in
  366. * this implementation, a deadlock will occur. There is
  367. * no tracking of individual rendering threads to enable
  368. * detecting this situation, but a subclass could incur
  369. * the overhead of tracking them and throwing an error.
  370. * <p>
  371. * This method is thread safe, although most Swing methods
  372. * are not. Please see
  373. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  374. * and Swing</A> for more information.
  375. *
  376. * @param r the renderer to execute
  377. */
  378. public void render(Runnable r) {
  379. readLock();
  380. try {
  381. r.run();
  382. } finally {
  383. readUnlock();
  384. }
  385. }
  386. /**
  387. * Returns the length of the data. This is the number of
  388. * characters of content that represents the users data.
  389. *
  390. * @return the length >= 0
  391. * @see Document#getLength
  392. */
  393. public int getLength() {
  394. return data.length() - 1;
  395. }
  396. /**
  397. * Adds a document listener for notification of any changes.
  398. *
  399. * @param listener the <code>DocumentListener</code> to add
  400. * @see Document#addDocumentListener
  401. */
  402. public void addDocumentListener(DocumentListener listener) {
  403. listenerList.add(DocumentListener.class, listener);
  404. }
  405. /**
  406. * Removes a document listener.
  407. *
  408. * @param listener the <code>DocumentListener</code> to remove
  409. * @see Document#removeDocumentListener
  410. */
  411. public void removeDocumentListener(DocumentListener listener) {
  412. listenerList.remove(DocumentListener.class, listener);
  413. }
  414. /**
  415. * Returns an array of all the document listeners
  416. * registered on this document.
  417. *
  418. * @return all of this document's <code>DocumentListener</code>s
  419. * or an empty array if no document listeners are
  420. * currently registered
  421. *
  422. * @see #addDocumentListener
  423. * @see #removeDocumentListener
  424. * @since 1.4
  425. */
  426. public DocumentListener[] getDocumentListeners() {
  427. return (DocumentListener[])listenerList.getListeners(
  428. DocumentListener.class);
  429. }
  430. /**
  431. * Adds an undo listener for notification of any changes.
  432. * Undo/Redo operations performed on the <code>UndoableEdit</code>
  433. * will cause the appropriate DocumentEvent to be fired to keep
  434. * the view(s) in sync with the model.
  435. *
  436. * @param listener the <code>UndoableEditListener</code> to add
  437. * @see Document#addUndoableEditListener
  438. */
  439. public void addUndoableEditListener(UndoableEditListener listener) {
  440. listenerList.add(UndoableEditListener.class, listener);
  441. }
  442. /**
  443. * Removes an undo listener.
  444. *
  445. * @param listener the <code>UndoableEditListener</code> to remove
  446. * @see Document#removeDocumentListener
  447. */
  448. public void removeUndoableEditListener(UndoableEditListener listener) {
  449. listenerList.remove(UndoableEditListener.class, listener);
  450. }
  451. /**
  452. * Returns an array of all the undoable edit listeners
  453. * registered on this document.
  454. *
  455. * @return all of this document's <code>UndoableEditListener</code>s
  456. * or an empty array if no undoable edit listeners are
  457. * currently registered
  458. *
  459. * @see #addUndoableEditListener
  460. * @see #removeUndoableEditListener
  461. *
  462. * @since 1.4
  463. */
  464. public UndoableEditListener[] getUndoableEditListeners() {
  465. return (UndoableEditListener[])listenerList.getListeners(
  466. UndoableEditListener.class);
  467. }
  468. /**
  469. * A convenience method for looking up a property value. It is
  470. * equivalent to:
  471. * <pre>
  472. * getDocumentProperties().get(key);
  473. * </pre>
  474. *
  475. * @param key the non-<code>null</code> property key
  476. * @return the value of this property or <code>null</code>
  477. * @see #getDocumentProperties
  478. */
  479. public final Object getProperty(Object key) {
  480. return getDocumentProperties().get(key);
  481. }
  482. /**
  483. * A convenience method for storing up a property value. It is
  484. * equivalent to:
  485. * <pre>
  486. * getDocumentProperties().put(key, value);
  487. * </pre>
  488. * If <code>value</code> is <code>null</code> this method will
  489. * remove the property.
  490. *
  491. * @param key the non-<code>null</code> key
  492. * @param value the property value
  493. * @see #getDocumentProperties
  494. */
  495. public final void putProperty(Object key, Object value) {
  496. if (value != null) {
  497. getDocumentProperties().put(key, value);
  498. } else {
  499. getDocumentProperties().remove(key);
  500. }
  501. if( key == TextAttribute.RUN_DIRECTION
  502. && Boolean.TRUE.equals(getProperty(I18NProperty)) )
  503. {
  504. //REMIND - this needs to flip on the i18n property if run dir
  505. //is rtl and the i18n property is not already on.
  506. writeLock();
  507. try {
  508. DefaultDocumentEvent e
  509. = new DefaultDocumentEvent(0, getLength(),
  510. DocumentEvent.EventType.INSERT);
  511. updateBidi( e );
  512. } finally {
  513. writeUnlock();
  514. }
  515. }
  516. }
  517. /**
  518. * Removes some content from the document.
  519. * Removing content causes a write lock to be held while the
  520. * actual changes are taking place. Observers are notified
  521. * of the change on the thread that called this method.
  522. * <p>
  523. * This method is thread safe, although most Swing methods
  524. * are not. Please see
  525. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  526. * and Swing</A> for more information.
  527. *
  528. * @param offs the starting offset >= 0
  529. * @param len the number of characters to remove >= 0
  530. * @exception BadLocationException the given remove position is not a valid
  531. * position within the document
  532. * @see Document#remove
  533. */
  534. public void remove(int offs, int len) throws BadLocationException {
  535. DocumentFilter filter = getDocumentFilter();
  536. writeLock();
  537. try {
  538. if (filter != null) {
  539. filter.remove(getFilterBypass(), offs, len);
  540. }
  541. else {
  542. handleRemove(offs, len);
  543. }
  544. } finally {
  545. writeUnlock();
  546. }
  547. }
  548. /**
  549. * Performs the actual work of the remove. It is assumed the caller
  550. * will have obtained a <code>writeLock</code> before invoking this.
  551. */
  552. void handleRemove(int offs, int len) throws BadLocationException {
  553. if (len > 0) {
  554. if (offs < 0 || (offs + len) > getLength()) {
  555. throw new BadLocationException("Invalid remove",
  556. getLength() + 1);
  557. }
  558. DefaultDocumentEvent chng =
  559. new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE);
  560. boolean isComposedTextElement = false;
  561. // Check whether the position of interest is the composed text
  562. isComposedTextElement = Utilities.isComposedTextElement(this, offs);
  563. removeUpdate(chng);
  564. UndoableEdit u = data.remove(offs, len);
  565. if (u != null) {
  566. chng.addEdit(u);
  567. }
  568. postRemoveUpdate(chng);
  569. // Mark the edit as done.
  570. chng.end();
  571. fireRemoveUpdate(chng);
  572. // only fire undo if Content implementation supports it
  573. // undo for the composed text is not supported for now
  574. if ((u != null) && !isComposedTextElement) {
  575. fireUndoableEditUpdate(new UndoableEditEvent(this, chng));
  576. }
  577. }
  578. }
  579. /**
  580. * Indic, Thai, and surrogate char values require complex
  581. * text layout and cursor support.
  582. */
  583. private static final boolean isComplex(char ch) {
  584. return (ch >= '\u0900' && ch <= '\u0D7F') || // Indic
  585. (ch >= '\u0E00' && ch <= '\u0E7F') || // Thai
  586. (ch >= '\uD800' && ch <= '\uDFFF'); // surrogate value range
  587. }
  588. private static final boolean isComplex(char[] text, int start, int limit) {
  589. for (int i = start; i < limit; ++i) {
  590. if (isComplex(text[i])) {
  591. return true;
  592. }
  593. }
  594. return false;
  595. }
  596. /**
  597. * Deletes the region of text from <code>offset</code> to
  598. * <code>offset + length</code>, and replaces it with <code>text</code>.
  599. * It is up to the implementation as to how this is implemented, some
  600. * implementations may treat this as two distinct operations: a remove
  601. * followed by an insert, others may treat the replace as one atomic
  602. * operation.
  603. *
  604. * @param offset index of child element
  605. * @param length length of text to delete, may be 0 indicating don't
  606. * delete anything
  607. * @param text text to insert, <code>null</code> indicates no text to insert
  608. * @param attrs AttributeSet indicating attributes of inserted text,
  609. * <code>null</code>
  610. * is legal, and typically treated as an empty attributeset,
  611. * but exact interpretation is left to the subclass
  612. * @exception BadLocationException the given position is not a valid
  613. * position within the document
  614. * @since 1.4
  615. */
  616. public void replace(int offset, int length, String text,
  617. AttributeSet attrs) throws BadLocationException {
  618. if (length == 0 && (text == null || text.length() == 0)) {
  619. return;
  620. }
  621. DocumentFilter filter = getDocumentFilter();
  622. writeLock();
  623. try {
  624. if (filter != null) {
  625. filter.replace(getFilterBypass(), offset, length, text,
  626. attrs);
  627. }
  628. else {
  629. if (length > 0) {
  630. remove(offset, length);
  631. }
  632. if (text != null && text.length() > 0) {
  633. insertString(offset, text, attrs);
  634. }
  635. }
  636. } finally {
  637. writeUnlock();
  638. }
  639. }
  640. /**
  641. * Inserts some content into the document.
  642. * Inserting content causes a write lock to be held while the
  643. * actual changes are taking place, followed by notification
  644. * to the observers on the thread that grabbed the write lock.
  645. * <p>
  646. * This method is thread safe, although most Swing methods
  647. * are not. Please see
  648. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  649. * and Swing</A> for more information.
  650. *
  651. * @param offs the starting offset >= 0
  652. * @param str the string to insert; does nothing with null/empty strings
  653. * @param a the attributes for the inserted content
  654. * @exception BadLocationException the given insert position is not a valid
  655. * position within the document
  656. * @see Document#insertString
  657. */
  658. public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
  659. if ((str == null) || (str.length() == 0)) {
  660. return;
  661. }
  662. DocumentFilter filter = getDocumentFilter();
  663. writeLock();
  664. try {
  665. if (filter != null) {
  666. filter.insertString(getFilterBypass(), offs, str, a);
  667. }
  668. else {
  669. handleInsertString(offs, str, a);
  670. }
  671. } finally {
  672. writeUnlock();
  673. }
  674. }
  675. /**
  676. * Performs the actual work of inserting the text; it is assumed the
  677. * caller has obtained a write lock before invoking this.
  678. */
  679. void handleInsertString(int offs, String str, AttributeSet a)
  680. throws BadLocationException {
  681. if ((str == null) || (str.length() == 0)) {
  682. return;
  683. }
  684. UndoableEdit u = data.insertString(offs, str);
  685. DefaultDocumentEvent e =
  686. new DefaultDocumentEvent(offs, str.length(), DocumentEvent.EventType.INSERT);
  687. if (u != null) {
  688. e.addEdit(u);
  689. }
  690. // see if complex glyph layout support is needed
  691. if( getProperty(I18NProperty).equals( Boolean.FALSE ) ) {
  692. // if a default direction of right-to-left has been specified,
  693. // we want complex layout even if the text is all left to right.
  694. Object d = getProperty(TextAttribute.RUN_DIRECTION);
  695. if ((d != null) && (d.equals(TextAttribute.RUN_DIRECTION_RTL))) {
  696. putProperty( I18NProperty, Boolean.TRUE);
  697. } else {
  698. char[] chars = str.toCharArray();
  699. if (Bidi.requiresBidi(chars, 0, chars.length) ||
  700. isComplex(chars, 0, chars.length)) {
  701. //
  702. putProperty( I18NProperty, Boolean.TRUE);
  703. }
  704. }
  705. }
  706. insertUpdate(e, a);
  707. // Mark the edit as done.
  708. e.end();
  709. fireInsertUpdate(e);
  710. // only fire undo if Content implementation supports it
  711. // undo for the composed text is not supported for now
  712. if (u != null &&
  713. (a == null || !a.isDefined(StyleConstants.ComposedTextAttribute))) {
  714. fireUndoableEditUpdate(new UndoableEditEvent(this, e));
  715. }
  716. }
  717. /**
  718. * Gets a sequence of text from the document.
  719. *
  720. * @param offset the starting offset >= 0
  721. * @param length the number of characters to retrieve >= 0
  722. * @return the text
  723. * @exception BadLocationException the range given includes a position
  724. * that is not a valid position within the document
  725. * @see Document#getText
  726. */
  727. public String getText(int offset, int length) throws BadLocationException {
  728. if (length < 0) {
  729. throw new BadLocationException("Length must be positive", length);
  730. }
  731. String str = data.getString(offset, length);
  732. return str;
  733. }
  734. /**
  735. * Fetches the text contained within the given portion
  736. * of the document.
  737. * <p>
  738. * If the partialReturn property on the txt parameter is false, the
  739. * data returned in the Segment will be the entire length requested and
  740. * may or may not be a copy depending upon how the data was stored.
  741. * If the partialReturn property is true, only the amount of text that
  742. * can be returned without creating a copy is returned. Using partial
  743. * returns will give better performance for situations where large
  744. * parts of the document are being scanned. The following is an example
  745. * of using the partial return to access the entire document:
  746. * <p>
  747. * <pre>
  748. *   int nleft = doc.getDocumentLength();
  749. *   Segment text = new Segment();
  750. *   int offs = 0;
  751. *   text.setPartialReturn(true);
  752. *   while (nleft > 0) {
  753. *   doc.getText(offs, nleft, text);
  754. *   // do something with text
  755. *   nleft -= text.count;
  756. *   offs += text.count;
  757. *   }
  758. * </pre>
  759. *
  760. * @param offset the starting offset >= 0
  761. * @param length the number of characters to retrieve >= 0
  762. * @param txt the Segment object to retrieve the text into
  763. * @exception BadLocationException the range given includes a position
  764. * that is not a valid position within the document
  765. */
  766. public void getText(int offset, int length, Segment txt) throws BadLocationException {
  767. if (length < 0) {
  768. throw new BadLocationException("Length must be positive", length);
  769. }
  770. data.getChars(offset, length, txt);
  771. }
  772. /**
  773. * Returns a position that will track change as the document
  774. * is altered.
  775. * <p>
  776. * This method is thread safe, although most Swing methods
  777. * are not. Please see
  778. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  779. * and Swing</A> for more information.
  780. *
  781. * @param offs the position in the model >= 0
  782. * @return the position
  783. * @exception BadLocationException if the given position does not
  784. * represent a valid location in the associated document
  785. * @see Document#createPosition
  786. */
  787. public synchronized Position createPosition(int offs) throws BadLocationException {
  788. return data.createPosition(offs);
  789. }
  790. /**
  791. * Returns a position that represents the start of the document. The
  792. * position returned can be counted on to track change and stay
  793. * located at the beginning of the document.
  794. *
  795. * @return the position
  796. */
  797. public final Position getStartPosition() {
  798. Position p;
  799. try {
  800. p = createPosition(0);
  801. } catch (BadLocationException bl) {
  802. p = null;
  803. }
  804. return p;
  805. }
  806. /**
  807. * Returns a position that represents the end of the document. The
  808. * position returned can be counted on to track change and stay
  809. * located at the end of the document.
  810. *
  811. * @return the position
  812. */
  813. public final Position getEndPosition() {
  814. Position p;
  815. try {
  816. p = createPosition(data.length());
  817. } catch (BadLocationException bl) {
  818. p = null;
  819. }
  820. return p;
  821. }
  822. /**
  823. * Gets all root elements defined. Typically, there
  824. * will only be one so the default implementation
  825. * is to return the default root element.
  826. *
  827. * @return the root element
  828. */
  829. public Element[] getRootElements() {
  830. Element[] elems = new Element[2];
  831. elems[0] = getDefaultRootElement();
  832. elems[1] = getBidiRootElement();
  833. return elems;
  834. }
  835. /**
  836. * Returns the root element that views should be based upon
  837. * unless some other mechanism for assigning views to element
  838. * structures is provided.
  839. *
  840. * @return the root element
  841. * @see Document#getDefaultRootElement
  842. */
  843. public abstract Element getDefaultRootElement();
  844. // ---- local methods -----------------------------------------
  845. /**
  846. * Returns the <code>FilterBypass</code>. This will create one if one
  847. * does not yet exist.
  848. */
  849. private DocumentFilter.FilterBypass getFilterBypass() {
  850. if (filterBypass == null) {
  851. filterBypass = new DefaultFilterBypass();
  852. }
  853. return filterBypass;
  854. }
  855. /**
  856. * Returns the root element of the bidirectional structure for this
  857. * document. Its children represent character runs with a given
  858. * Unicode bidi level.
  859. */
  860. public Element getBidiRootElement() {
  861. return bidiRoot;
  862. }
  863. /**
  864. * Returns true if the text in the range <code>p0</code> to
  865. * <code>p1</code> is left to right.
  866. */
  867. boolean isLeftToRight(int p0, int p1) {
  868. if(!getProperty(I18NProperty).equals(Boolean.TRUE)) {
  869. return true;
  870. }
  871. Element bidiRoot = getBidiRootElement();
  872. int index = bidiRoot.getElementIndex(p0);
  873. Element bidiElem = bidiRoot.getElement(index);
  874. if(bidiElem.getEndOffset() >= p1) {
  875. AttributeSet bidiAttrs = bidiElem.getAttributes();
  876. return ((StyleConstants.getBidiLevel(bidiAttrs) % 2) == 0);
  877. }
  878. return true;
  879. }
  880. /**
  881. * Get the paragraph element containing the given position. Sub-classes
  882. * must define for themselves what exactly constitutes a paragraph. They
  883. * should keep in mind however that a paragraph should at least be the
  884. * unit of text over which to run the Unicode bidirectional algorithm.
  885. *
  886. * @param pos the starting offset >= 0
  887. * @return the element */
  888. public abstract Element getParagraphElement(int pos);
  889. /**
  890. * Fetches the context for managing attributes. This
  891. * method effectively establishes the strategy used
  892. * for compressing AttributeSet information.
  893. *
  894. * @return the context
  895. */
  896. protected final AttributeContext getAttributeContext() {
  897. return context;
  898. }
  899. /**
  900. * Updates document structure as a result of text insertion. This
  901. * will happen within a write lock. If a subclass of
  902. * this class reimplements this method, it should delegate to the
  903. * superclass as well.
  904. *
  905. * @param chng a description of the change
  906. * @param attr the attributes for the change
  907. */
  908. protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) {
  909. if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
  910. updateBidi( chng );
  911. // Check if a multi byte is encountered in the inserted text.
  912. if (chng.type == DocumentEvent.EventType.INSERT &&
  913. chng.getLength() > 0 &&
  914. !Boolean.TRUE.equals(getProperty(MultiByteProperty))) {
  915. Segment segment = SegmentCache.getSharedSegment();
  916. try {
  917. getText(chng.getOffset(), chng.getLength(), segment);
  918. segment.first();
  919. do {
  920. if ((int)segment.current() > 255) {
  921. putProperty(MultiByteProperty, Boolean.TRUE);
  922. break;
  923. }
  924. } while (segment.next() != Segment.DONE);
  925. } catch (BadLocationException ble) {
  926. // Should never happen
  927. }
  928. SegmentCache.releaseSharedSegment(segment);
  929. }
  930. }
  931. /**
  932. * Updates any document structure as a result of text removal. This
  933. * method is called before the text is actually removed from the Content.
  934. * This will happen within a write lock. If a subclass
  935. * of this class reimplements this method, it should delegate to the
  936. * superclass as well.
  937. *
  938. * @param chng a description of the change
  939. */
  940. protected void removeUpdate(DefaultDocumentEvent chng) {
  941. }
  942. /**
  943. * Updates any document structure as a result of text removal. This
  944. * method is called after the text has been removed from the Content.
  945. * This will happen within a write lock. If a subclass
  946. * of this class reimplements this method, it should delegate to the
  947. * superclass as well.
  948. *
  949. * @param chng a description of the change
  950. */
  951. protected void postRemoveUpdate(DefaultDocumentEvent chng) {
  952. if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
  953. updateBidi( chng );
  954. }
  955. /**
  956. * Update the bidi element structure as a result of the given change
  957. * to the document. The given change will be updated to reflect the
  958. * changes made to the bidi structure.
  959. *
  960. * This method assumes that every offset in the model is contained in
  961. * exactly one paragraph. This method also assumes that it is called
  962. * after the change is made to the default element structure.
  963. */
  964. void updateBidi( DefaultDocumentEvent chng ) {
  965. // Calculate the range of paragraphs affected by the change.
  966. int firstPStart;
  967. int lastPEnd;
  968. if( chng.type == DocumentEvent.EventType.INSERT
  969. || chng.type == DocumentEvent.EventType.CHANGE )
  970. {
  971. int chngStart = chng.getOffset();
  972. int chngEnd = chngStart + chng.getLength();
  973. firstPStart = getParagraphElement(chngStart).getStartOffset();
  974. lastPEnd = getParagraphElement(chngEnd).getEndOffset();
  975. } else if( chng.type == DocumentEvent.EventType.REMOVE ) {
  976. Element paragraph = getParagraphElement( chng.getOffset() );
  977. firstPStart = paragraph.getStartOffset();
  978. lastPEnd = paragraph.getEndOffset();
  979. } else {
  980. throw new Error("Internal error: unknown event type.");
  981. }
  982. //System.out.println("updateBidi: firstPStart = " + firstPStart + " lastPEnd = " + lastPEnd );
  983. // Calculate the bidi levels for the affected range of paragraphs. The
  984. // levels array will contain a bidi level for each character in the
  985. // affected text.
  986. byte levels[] = calculateBidiLevels( firstPStart, lastPEnd );
  987. Vector newElements = new Vector();
  988. // Calculate the first span of characters in the affected range with
  989. // the same bidi level. If this level is the same as the level of the
  990. // previous bidi element (the existing bidi element containing
  991. // firstPStart-1), then merge in the previous element. If not, but
  992. // the previous element overlaps the affected range, truncate the
  993. // previous element at firstPStart.
  994. int firstSpanStart = firstPStart;
  995. int removeFromIndex = 0;
  996. if( firstSpanStart > 0 ) {
  997. int prevElemIndex = bidiRoot.getElementIndex(firstPStart-1);
  998. removeFromIndex = prevElemIndex;
  999. Element prevElem = bidiRoot.getElement(prevElemIndex);
  1000. int prevLevel=StyleConstants.getBidiLevel(prevElem.getAttributes());
  1001. //System.out.println("createbidiElements: prevElem= " + prevElem + " prevLevel= " + prevLevel + "level[0] = " + levels[0]);
  1002. if( prevLevel==levels[0] ) {
  1003. firstSpanStart = prevElem.getStartOffset();
  1004. } else if( prevElem.getEndOffset() > firstPStart ) {
  1005. newElements.addElement(new BidiElement(bidiRoot,
  1006. prevElem.getStartOffset(),
  1007. firstPStart, prevLevel));
  1008. } else {
  1009. removeFromIndex++;
  1010. }
  1011. }
  1012. int firstSpanEnd = 0;
  1013. while((firstSpanEnd<levels.length) && (levels[firstSpanEnd]==levels[0]))
  1014. firstSpanEnd++;
  1015. // Calculate the last span of characters in the affected range with
  1016. // the same bidi level. If this level is the same as the level of the
  1017. // next bidi element (the existing bidi element containing lastPEnd),
  1018. // then merge in the next element. If not, but the next element
  1019. // overlaps the affected range, adjust the next element to start at
  1020. // lastPEnd.
  1021. int lastSpanEnd = lastPEnd;
  1022. Element newNextElem = null;
  1023. int removeToIndex = bidiRoot.getElementCount() - 1;
  1024. if( lastSpanEnd <= getLength() ) {
  1025. int nextElemIndex = bidiRoot.getElementIndex( lastPEnd );
  1026. removeToIndex = nextElemIndex;
  1027. Element nextElem = bidiRoot.getElement( nextElemIndex );
  1028. int nextLevel = StyleConstants.getBidiLevel(nextElem.getAttributes());
  1029. if( nextLevel == levels[levels.length-1] ) {
  1030. lastSpanEnd = nextElem.getEndOffset();
  1031. } else if( nextElem.getStartOffset() < lastPEnd ) {
  1032. newNextElem = new BidiElement(bidiRoot, lastPEnd,
  1033. nextElem.getEndOffset(),
  1034. nextLevel);
  1035. } else {
  1036. removeToIndex--;
  1037. }
  1038. }
  1039. int lastSpanStart = levels.length;
  1040. while( (lastSpanStart>firstSpanEnd)
  1041. && (levels[lastSpanStart-1]==levels[levels.length-1]) )
  1042. lastSpanStart--;
  1043. // If the first and last spans are contiguous and have the same level,
  1044. // merge them and create a single new element for the entire span.
  1045. // Otherwise, create elements for the first and last spans as well as
  1046. // any spans in between.
  1047. if((firstSpanEnd==lastSpanStart)&&(levels[0]==levels[levels.length-1])){
  1048. newElements.addElement(new BidiElement(bidiRoot, firstSpanStart,
  1049. lastSpanEnd, levels[0]));
  1050. } else {
  1051. // Create an element for the first span.
  1052. newElements.addElement(new BidiElement(bidiRoot, firstSpanStart,
  1053. firstSpanEnd+firstPStart,
  1054. levels[0]));
  1055. // Create elements for the spans in between the first and last
  1056. for( int i=firstSpanEnd; i<lastSpanStart; ) {
  1057. //System.out.println("executed line 872");
  1058. int j;
  1059. for( j=i; (j<levels.length) && (levels[j] == levels[i]); j++ );
  1060. newElements.addElement(new BidiElement(bidiRoot, firstPStart+i,
  1061. firstPStart+j,
  1062. (int)levels[i]));
  1063. i=j;
  1064. }
  1065. // Create an element for the last span.
  1066. newElements.addElement(new BidiElement(bidiRoot,
  1067. lastSpanStart+firstPStart,
  1068. lastSpanEnd,
  1069. levels[levels.length-1]));
  1070. }
  1071. if( newNextElem != null )
  1072. newElements.addElement( newNextElem );
  1073. // Calculate the set of existing bidi elements which must be
  1074. // removed.
  1075. int removedElemCount = 0;
  1076. if( bidiRoot.getElementCount() > 0 ) {
  1077. removedElemCount = removeToIndex - removeFromIndex + 1;
  1078. }
  1079. Element[] removedElems = new Element[removedElemCount];
  1080. for( int i=0; i<removedElemCount; i++ ) {
  1081. removedElems[i] = bidiRoot.getElement(removeFromIndex+i);
  1082. }
  1083. Element[] addedElems = new Element[ newElements.size() ];
  1084. newElements.copyInto( addedElems );
  1085. // Update the change record.
  1086. ElementEdit ee = new ElementEdit( bidiRoot, removeFromIndex,
  1087. removedElems, addedElems );
  1088. chng.addEdit( ee );
  1089. // Update the bidi element structure.
  1090. bidiRoot.replace( removeFromIndex, removedElems.length, addedElems );
  1091. }
  1092. /**
  1093. * Calculate the levels array for a range of paragraphs.
  1094. */
  1095. private byte[] calculateBidiLevels( int firstPStart, int lastPEnd ) {
  1096. byte levels[] = new byte[ lastPEnd - firstPStart ];
  1097. int levelsEnd = 0;
  1098. Boolean defaultDirection = null;
  1099. Object d = getProperty(TextAttribute.RUN_DIRECTION);
  1100. if (d instanceof Boolean) {
  1101. defaultDirection = (Boolean) d;
  1102. }
  1103. // For each paragraph in the given range of paragraphs, get its
  1104. // levels array and add it to the levels array for the entire span.
  1105. for(int o=firstPStart; o<lastPEnd; ) {
  1106. Element p = getParagraphElement( o );
  1107. int pStart = p.getStartOffset();
  1108. int pEnd = p.getEndOffset();
  1109. // default run direction for the paragraph. This will be
  1110. // null if there is no direction override specified (i.e.
  1111. // the direction will be determined from the content).
  1112. Boolean direction = defaultDirection;
  1113. d = p.getAttributes().getAttribute(TextAttribute.RUN_DIRECTION);
  1114. if (d instanceof Boolean) {
  1115. direction = (Boolean) d;
  1116. }
  1117. //System.out.println("updateBidi: paragraph start = " + pStart + " paragraph end = " + pEnd);
  1118. // Create a Bidi over this paragraph then get the level
  1119. // array.
  1120. Segment seg = SegmentCache.getSharedSegment();
  1121. try {
  1122. getText(pStart, pEnd-pStart, seg);
  1123. } catch (BadLocationException e ) {
  1124. throw new Error("Internal error: " + e.toString());
  1125. }
  1126. // REMIND(bcb) we should really be using a Segment here.
  1127. Bidi bidiAnalyzer;
  1128. int bidiflag = Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
  1129. if (direction != null) {
  1130. if (TextAttribute.RUN_DIRECTION_LTR.equals(direction)) {
  1131. bidiflag = Bidi.DIRECTION_LEFT_TO_RIGHT;
  1132. } else {
  1133. bidiflag = Bidi.DIRECTION_RIGHT_TO_LEFT;
  1134. }
  1135. }
  1136. bidiAnalyzer = new Bidi(seg.array, seg.offset, null, 0, seg.count,
  1137. bidiflag);
  1138. BidiUtils.getLevels(bidiAnalyzer, levels, levelsEnd);
  1139. levelsEnd += bidiAnalyzer.getLength();
  1140. o = p.getEndOffset();
  1141. SegmentCache.releaseSharedSegment(seg);
  1142. }
  1143. // REMIND(bcb) remove this code when debugging is done.
  1144. if( levelsEnd != levels.length )
  1145. throw new Error("levelsEnd assertion failed.");
  1146. return levels;
  1147. }
  1148. /**
  1149. * Gives a diagnostic dump.
  1150. *
  1151. * @param out the output stream
  1152. */
  1153. public void dump(PrintStream out) {
  1154. Element root = getDefaultRootElement();
  1155. if (root instanceof AbstractElement) {
  1156. ((AbstractElement)root).dump(out, 0);
  1157. }
  1158. bidiRoot.dump(out,0);
  1159. }
  1160. /**
  1161. * Gets the content for the document.
  1162. *
  1163. * @return the content
  1164. */
  1165. protected final Content getContent() {
  1166. return data;
  1167. }
  1168. /**
  1169. * Creates a document leaf element.
  1170. * Hook through which elements are created to represent the
  1171. * document structure. Because this implementation keeps
  1172. * structure and content separate, elements grow automatically
  1173. * when content is extended so splits of existing elements
  1174. * follow. The document itself gets to decide how to generate
  1175. * elements to give flexibility in the type of elements used.
  1176. *
  1177. * @param parent the parent element
  1178. * @param a the attributes for the element
  1179. * @param p0 the beginning of the range >= 0
  1180. * @param p1 the end of the range >= p0
  1181. * @return the new element
  1182. */
  1183. protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1) {
  1184. return new LeafElement(parent, a, p0, p1);
  1185. }
  1186. /**
  1187. * Creates a document branch element, that can contain other elements.
  1188. *
  1189. * @param parent the parent element
  1190. * @param a the attributes
  1191. * @return the element
  1192. */
  1193. protected Element createBranchElement(Element parent, AttributeSet a) {
  1194. return new BranchElement(parent, a);
  1195. }
  1196. // --- Document locking ----------------------------------
  1197. /**
  1198. * Fetches the current writing thread if there is one.
  1199. * This can be used to distinguish whether a method is
  1200. * being called as part of an existing modification or
  1201. * if a lock needs to be acquired and a new transaction
  1202. * started.
  1203. *
  1204. * @return the thread actively modifying the document
  1205. * or <code>null</code> if there are no modifications in progress
  1206. */
  1207. protected synchronized final Thread getCurrentWriter() {
  1208. return currWriter;
  1209. }
  1210. /**
  1211. * Acquires a lock to begin mutating the document this lock
  1212. * protects. There can be no writing, notification of changes, or
  1213. * reading going on in order to gain the lock. Additionally a thread is
  1214. * allowed to gain more than one <code>writeLock</code>,
  1215. * as long as it doesn't attempt to gain additional <code>writeLock</code>s
  1216. * from within document notification. Attempting to gain a
  1217. * <code>writeLock</code> from within a DocumentListener notification will
  1218. * result in an <code>IllegalStateException</code>. The ability
  1219. * to obtain more than one <code>writeLock</code> per thread allows
  1220. * subclasses to gain a writeLock, perform a number of operations, then
  1221. * release the lock.
  1222. * <p>
  1223. * Calls to <code>writeLock</code>
  1224. * must be balanced with calls to <code>writeUnlock</code>, else the
  1225. * <code>Document</code> will be left in a locked state so that no
  1226. * reading or writing can be done.
  1227. *
  1228. * @exception IllegalStateException thrown on illegal lock
  1229. * attempt. If the document is implemented properly, this can
  1230. * only happen if a document listener attempts to mutate the
  1231. * document. This situation violates the bean event model
  1232. * where order of delivery is not guaranteed and all listeners
  1233. * should be notified before further mutations are allowed.
  1234. */
  1235. protected synchronized final void writeLock() {
  1236. try {
  1237. while ((numReaders > 0) || (currWriter != null)) {
  1238. if (Thread.currentThread() == currWriter) {
  1239. if (notifyingListeners) {
  1240. // Assuming one doesn't do something wrong in a
  1241. // subclass this should only happen if a
  1242. // DocumentListener tries to mutate the document.
  1243. throw new IllegalStateException(
  1244. "Attempt to mutate in notification");
  1245. }
  1246. numWriters++;
  1247. return;
  1248. }
  1249. wait();
  1250. }
  1251. currWriter = Thread.currentThread();
  1252. numWriters = 1;
  1253. } catch (InterruptedException e) {
  1254. throw new Error("Interrupted attempt to aquire write lock");
  1255. }
  1256. }
  1257. /**
  1258. * Releases a write lock previously obtained via <code>writeLock</code>.
  1259. * After decrementing the lock count if there are no oustanding locks
  1260. * this will allow a new writer, or readers.
  1261. *
  1262. * @see #writeLock
  1263. */
  1264. protected synchronized final void writeUnlock() {
  1265. if (--numWriters <= 0) {
  1266. numWriters = 0;
  1267. currWriter = null;
  1268. notifyAll();
  1269. }
  1270. }
  1271. /**
  1272. * Acquires a lock to begin reading some state from the
  1273. * document. There can be multiple readers at the same time.
  1274. * Writing blocks the readers until notification of the change
  1275. * to the listeners has been completed. This method should
  1276. * be used very carefully to avoid unintended compromise
  1277. * of the document. It should always be balanced with a
  1278. * <code>readUnlock</code>.
  1279. *
  1280. * @see #readUnlock
  1281. */
  1282. public synchronized final void readLock() {
  1283. try {
  1284. while (currWriter != null) {
  1285. if (currWriter == Thread.currentThread()) {
  1286. // writer has full read access.... may try to acquire
  1287. // lock in notification
  1288. return;
  1289. }
  1290. wait();
  1291. }
  1292. numReaders += 1;
  1293. } catch (InterruptedException e) {
  1294. throw new Error("Interrupted attempt to aquire read lock");
  1295. }
  1296. }
  1297. /**
  1298. * Does a read unlock. This signals that one
  1299. * of the readers is done. If there are no more readers
  1300. * then writing can begin again. This should be balanced
  1301. * with a readLock, and should occur in a finally statement
  1302. * so that the balance is guaranteed. The following is an
  1303. * example.
  1304. * <pre><code>
  1305. *   readLock();
  1306. *   try {
  1307. *   // do something
  1308. *   } finally {
  1309. *   readUnlock();
  1310. *   }
  1311. * </code></pre>
  1312. *
  1313. * @see #readLock
  1314. */
  1315. public synchronized final void readUnlock() {
  1316. if (currWriter == Thread.currentThread()) {
  1317. // writer has full read access.... may try to acquire
  1318. // lock in notification
  1319. return;
  1320. }
  1321. if (numReaders <= 0) {
  1322. throw new StateInvariantError(BAD_LOCK_STATE);
  1323. }
  1324. numReaders -= 1;
  1325. notify();
  1326. }
  1327. // --- serialization ---------------------------------------------
  1328. private void readObject(ObjectInputStream s)
  1329. throws ClassNotFoundException, IOException
  1330. {
  1331. s.defaultReadObject();
  1332. listenerList = new EventListenerList();
  1333. // Restore bidi structure
  1334. //REMIND(bcb) This creates an initial bidi element to account for
  1335. //the \n that exists by default in the content.
  1336. bidiRoot = new BidiRootElement();
  1337. try {
  1338. writeLock();
  1339. Element[] p = new Element[1];
  1340. p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
  1341. bidiRoot.replace(0,0,p);
  1342. } finally {
  1343. writeUnlock();
  1344. }
  1345. // At this point bidi root is only partially correct. To fully
  1346. // restore it we need access to getDefaultRootElement. But, this
  1347. // is created by the subclass and at this point will be null. We
  1348. // thus use registerValidation.
  1349. s.registerValidation(new ObjectInputValidation() {
  1350. public void validateObject() {
  1351. try {
  1352. writeLock();
  1353. DefaultDocumentEvent e = new DefaultDocumentEvent
  1354. (0, getLength(),
  1355. DocumentEvent.EventType.INSERT);
  1356. updateBidi( e );
  1357. }
  1358. finally {
  1359. writeUnlock();
  1360. }
  1361. }
  1362. }, 0);
  1363. }
  1364. // ----- member variables ------------------------------------------
  1365. private transient int numReaders;
  1366. private transient Thread currWriter;
  1367. /**
  1368. * The number of writers, all obtained from <code>currWriter</code>.
  1369. */
  1370. private transient int numWriters;
  1371. /**
  1372. * True will notifying listeners.
  1373. */
  1374. private transient boolean notifyingListeners;
  1375. private static Boolean defaultI18NProperty;
  1376. /**
  1377. * Storage for document-wide properties.
  1378. */