1. /*
  2. * @(#)DefaultStyledDocument.java 1.121 03/01/23
  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.awt.Color;
  9. import java.awt.Component;
  10. import java.awt.Font;
  11. import java.awt.FontMetrics;
  12. import java.awt.font.TextAttribute;
  13. import java.util.Enumeration;
  14. import java.util.Hashtable;
  15. import java.util.Stack;
  16. import java.util.Vector;
  17. import java.util.ArrayList;
  18. import java.io.IOException;
  19. import java.io.ObjectInputStream;
  20. import java.io.ObjectOutputStream;
  21. import java.io.Serializable;
  22. import javax.swing.Icon;
  23. import javax.swing.event.*;
  24. import javax.swing.undo.AbstractUndoableEdit;
  25. import javax.swing.undo.CannotRedoException;
  26. import javax.swing.undo.CannotUndoException;
  27. import javax.swing.undo.UndoableEdit;
  28. import javax.swing.SwingUtilities;
  29. /**
  30. * A document that can be marked up with character and paragraph
  31. * styles in a manner similar to the Rich Text Format. The element
  32. * structure for this document represents style crossings for
  33. * style runs. These style runs are mapped into a paragraph element
  34. * structure (which may reside in some other structure). The
  35. * style runs break at paragraph boundaries since logical styles are
  36. * assigned to paragraph boundaries.
  37. * <p>
  38. * <strong>Warning:</strong>
  39. * Serialized objects of this class will not be compatible with
  40. * future Swing releases. The current serialization support is
  41. * appropriate for short term storage or RMI between applications running
  42. * the same version of Swing. As of 1.4, support for long term storage
  43. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  44. * has been added to the <code>java.beans</code> package.
  45. * Please see {@link java.beans.XMLEncoder}.
  46. *
  47. * @author Timothy Prinzing
  48. * @version 1.121 01/23/03
  49. * @see Document
  50. * @see AbstractDocument
  51. */
  52. public class DefaultStyledDocument extends AbstractDocument implements StyledDocument {
  53. /**
  54. * Constructs a styled document.
  55. *
  56. * @param c the container for the content
  57. * @param styles resources and style definitions which may
  58. * be shared across documents
  59. */
  60. public DefaultStyledDocument(Content c, StyleContext styles) {
  61. super(c, styles);
  62. listeningStyles = new Vector();
  63. buffer = new ElementBuffer(createDefaultRoot());
  64. Style defaultStyle = styles.getStyle(StyleContext.DEFAULT_STYLE);
  65. setLogicalStyle(0, defaultStyle);
  66. }
  67. /**
  68. * Constructs a styled document with the default content
  69. * storage implementation and a shared set of styles.
  70. *
  71. * @param styles the styles
  72. */
  73. public DefaultStyledDocument(StyleContext styles) {
  74. this(new GapContent(BUFFER_SIZE_DEFAULT), styles);
  75. }
  76. /**
  77. * Constructs a default styled document. This buffers
  78. * input content by a size of <em>BUFFER_SIZE_DEFAULT</em>
  79. * and has a style context that is scoped by the lifetime
  80. * of the document and is not shared with other documents.
  81. */
  82. public DefaultStyledDocument() {
  83. this(new GapContent(BUFFER_SIZE_DEFAULT), new StyleContext());
  84. }
  85. /**
  86. * Gets the default root element.
  87. *
  88. * @return the root
  89. * @see Document#getDefaultRootElement
  90. */
  91. public Element getDefaultRootElement() {
  92. return buffer.getRootElement();
  93. }
  94. /**
  95. * Initialize the document to reflect the given element
  96. * structure (i.e. the structure reported by the
  97. * <code>getDefaultRootElement</code> method. If the
  98. * document contained any data it will first be removed.
  99. */
  100. protected void create(ElementSpec[] data) {
  101. try {
  102. if (getLength() != 0) {
  103. remove(0, getLength());
  104. }
  105. writeLock();
  106. // install the content
  107. Content c = getContent();
  108. int n = data.length;
  109. StringBuffer sb = new StringBuffer();
  110. for (int i = 0; i < n; i++) {
  111. ElementSpec es = data[i];
  112. if (es.getLength() > 0) {
  113. sb.append(es.getArray(), es.getOffset(), es.getLength());
  114. }
  115. }
  116. UndoableEdit cEdit = c.insertString(0, sb.toString());
  117. // build the event and element structure
  118. int length = sb.length();
  119. DefaultDocumentEvent evnt =
  120. new DefaultDocumentEvent(0, length, DocumentEvent.EventType.INSERT);
  121. evnt.addEdit(cEdit);
  122. buffer.create(length, data, evnt);
  123. // update bidi (possibly)
  124. super.insertUpdate(evnt, null);
  125. // notify the listeners
  126. evnt.end();
  127. fireInsertUpdate(evnt);
  128. fireUndoableEditUpdate(new UndoableEditEvent(this, evnt));
  129. } catch (BadLocationException ble) {
  130. throw new StateInvariantError("problem initializing");
  131. } finally {
  132. writeUnlock();
  133. }
  134. }
  135. /**
  136. * Inserts new elements in bulk. This is useful to allow
  137. * parsing with the document in an unlocked state and
  138. * prepare an element structure modification. This method
  139. * takes an array of tokens that describe how to update an
  140. * element structure so the time within a write lock can
  141. * be greatly reduced in an asynchronous update situation.
  142. * <p>
  143. * This method is thread safe, although most Swing methods
  144. * are not. Please see
  145. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  146. * and Swing</A> for more information.
  147. *
  148. * @param offset the starting offset >= 0
  149. * @param data the element data
  150. * @exception BadLocationException for an invalid starting offset
  151. */
  152. protected void insert(int offset, ElementSpec[] data) throws BadLocationException {
  153. if (data == null || data.length == 0) {
  154. return;
  155. }
  156. try {
  157. writeLock();
  158. // install the content
  159. Content c = getContent();
  160. int n = data.length;
  161. StringBuffer sb = new StringBuffer();
  162. for (int i = 0; i < n; i++) {
  163. ElementSpec es = data[i];
  164. if (es.getLength() > 0) {
  165. sb.append(es.getArray(), es.getOffset(), es.getLength());
  166. }
  167. }
  168. if (sb.length() == 0) {
  169. // Nothing to insert, bail.
  170. return;
  171. }
  172. UndoableEdit cEdit = c.insertString(offset, sb.toString());
  173. // create event and build the element structure
  174. int length = sb.length();
  175. DefaultDocumentEvent evnt =
  176. new DefaultDocumentEvent(offset, length, DocumentEvent.EventType.INSERT);
  177. evnt.addEdit(cEdit);
  178. buffer.insert(offset, length, data, evnt);
  179. // update bidi (possibly)
  180. super.insertUpdate(evnt, null);
  181. // notify the listeners
  182. evnt.end();
  183. fireInsertUpdate(evnt);
  184. fireUndoableEditUpdate(new UndoableEditEvent(this, evnt));
  185. } finally {
  186. writeUnlock();
  187. }
  188. }
  189. /**
  190. * Adds a new style into the logical style hierarchy. Style attributes
  191. * resolve from bottom up so an attribute specified in a child
  192. * will override an attribute specified in the parent.
  193. *
  194. * @param nm the name of the style (must be unique within the
  195. * collection of named styles). The name may be null if the style
  196. * is unnamed, but the caller is responsible
  197. * for managing the reference returned as an unnamed style can't
  198. * be fetched by name. An unnamed style may be useful for things
  199. * like character attribute overrides such as found in a style
  200. * run.
  201. * @param parent the parent style. This may be null if unspecified
  202. * attributes need not be resolved in some other style.
  203. * @return the style
  204. */
  205. public Style addStyle(String nm, Style parent) {
  206. StyleContext styles = (StyleContext) getAttributeContext();
  207. return styles.addStyle(nm, parent);
  208. }
  209. /**
  210. * Removes a named style previously added to the document.
  211. *
  212. * @param nm the name of the style to remove
  213. */
  214. public void removeStyle(String nm) {
  215. StyleContext styles = (StyleContext) getAttributeContext();
  216. styles.removeStyle(nm);
  217. }
  218. /**
  219. * Fetches a named style previously added.
  220. *
  221. * @param nm the name of the style
  222. * @return the style
  223. */
  224. public Style getStyle(String nm) {
  225. StyleContext styles = (StyleContext) getAttributeContext();
  226. return styles.getStyle(nm);
  227. }
  228. /**
  229. * Fetches the list of of style names.
  230. *
  231. * @return all the style names
  232. */
  233. public Enumeration getStyleNames() {
  234. return ((StyleContext) getAttributeContext()).getStyleNames();
  235. }
  236. /**
  237. * Sets the logical style to use for the paragraph at the
  238. * given position. If attributes aren't explicitly set
  239. * for character and paragraph attributes they will resolve
  240. * through the logical style assigned to the paragraph, which
  241. * in turn may resolve through some hierarchy completely
  242. * independent of the element hierarchy in the document.
  243. * <p>
  244. * This method is thread safe, although most Swing methods
  245. * are not. Please see
  246. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  247. * and Swing</A> for more information.
  248. *
  249. * @param pos the offset from the start of the document >= 0
  250. * @param s the logical style to assign to the paragraph, null if none
  251. */
  252. public void setLogicalStyle(int pos, Style s) {
  253. Element paragraph = getParagraphElement(pos);
  254. if ((paragraph != null) && (paragraph instanceof AbstractElement)) {
  255. try {
  256. writeLock();
  257. StyleChangeUndoableEdit edit = new StyleChangeUndoableEdit((AbstractElement)paragraph, s);
  258. ((AbstractElement)paragraph).setResolveParent(s);
  259. int p0 = paragraph.getStartOffset();
  260. int p1 = paragraph.getEndOffset();
  261. DefaultDocumentEvent e =
  262. new DefaultDocumentEvent(p0, p1 - p0, DocumentEvent.EventType.CHANGE);
  263. e.addEdit(edit);
  264. e.end();
  265. fireChangedUpdate(e);
  266. fireUndoableEditUpdate(new UndoableEditEvent(this, e));
  267. } finally {
  268. writeUnlock();
  269. }
  270. }
  271. }
  272. /**
  273. * Fetches the logical style assigned to the paragraph
  274. * represented by the given position.
  275. *
  276. * @param p the location to translate to a paragraph
  277. * and determine the logical style assigned >= 0. This
  278. * is an offset from the start of the document.
  279. * @return the style, null if none
  280. */
  281. public Style getLogicalStyle(int p) {
  282. Style s = null;
  283. Element paragraph = getParagraphElement(p);
  284. if (paragraph != null) {
  285. AttributeSet a = paragraph.getAttributes();
  286. AttributeSet parent = a.getResolveParent();
  287. if (parent instanceof Style) {
  288. s = (Style) parent;
  289. }
  290. }
  291. return s;
  292. }
  293. /**
  294. * Sets attributes for some part of the document.
  295. * A write lock is held by this operation while changes
  296. * are being made, and a DocumentEvent is sent to the listeners
  297. * after the change has been successfully completed.
  298. * <p>
  299. * This method is thread safe, although most Swing methods
  300. * are not. Please see
  301. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  302. * and Swing</A> for more information.
  303. *
  304. * @param offset the offset in the document >= 0
  305. * @param length the length >= 0
  306. * @param s the attributes
  307. * @param replace true if the previous attributes should be replaced
  308. * before setting the new attributes
  309. */
  310. public void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) {
  311. try {
  312. writeLock();
  313. DefaultDocumentEvent changes =
  314. new DefaultDocumentEvent(offset, length, DocumentEvent.EventType.CHANGE);
  315. // split elements that need it
  316. buffer.change(offset, length, changes);
  317. AttributeSet sCopy = s.copyAttributes();
  318. // PENDING(prinz) - this isn't a very efficient way to iterate
  319. int lastEnd = Integer.MAX_VALUE;
  320. for (int pos = offset; pos < (offset + length); pos = lastEnd) {
  321. Element run = getCharacterElement(pos);
  322. lastEnd = run.getEndOffset();
  323. if (pos == lastEnd) {
  324. // offset + length beyond length of document, bail.
  325. break;
  326. }
  327. MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes();
  328. changes.addEdit(new AttributeUndoableEdit(run, sCopy, replace));
  329. if (replace) {
  330. attr.removeAttributes(attr);
  331. }
  332. attr.addAttributes(s);
  333. }
  334. changes.end();
  335. fireChangedUpdate(changes);
  336. fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
  337. } finally {
  338. writeUnlock();
  339. }
  340. }
  341. /**
  342. * Sets attributes for a paragraph.
  343. * <p>
  344. * This method is thread safe, although most Swing methods
  345. * are not. Please see
  346. * <A HREF="http://java.sun.com/products/jfc/swingdoc-archive/threads.html">Threads
  347. * and Swing</A> for more information.
  348. *
  349. * @param offset the offset into the paragraph >= 0
  350. * @param length the number of characters affected >= 0
  351. * @param s the attributes
  352. * @param replace whether to replace existing attributes, or merge them
  353. */
  354. public void setParagraphAttributes(int offset, int length, AttributeSet s,
  355. boolean replace) {
  356. try {
  357. writeLock();
  358. DefaultDocumentEvent changes =
  359. new DefaultDocumentEvent(offset, length, DocumentEvent.EventType.CHANGE);
  360. AttributeSet sCopy = s.copyAttributes();
  361. // PENDING(prinz) - this assumes a particular element structure
  362. Element section = getDefaultRootElement();
  363. int index0 = section.getElementIndex(offset);
  364. int index1 = section.getElementIndex(offset + ((length > 0) ? length - 1 : 0));
  365. boolean isI18N = Boolean.TRUE.equals(getProperty(I18NProperty));
  366. boolean hasRuns = false;
  367. for (int i = index0; i <= index1; i++) {
  368. Element paragraph = section.getElement(i);
  369. MutableAttributeSet attr = (MutableAttributeSet) paragraph.getAttributes();
  370. changes.addEdit(new AttributeUndoableEdit(paragraph, sCopy, replace));
  371. if (replace) {
  372. attr.removeAttributes(attr);
  373. }
  374. attr.addAttributes(s);
  375. if (isI18N && !hasRuns) {
  376. hasRuns = (attr.getAttribute(TextAttribute.RUN_DIRECTION) != null);
  377. }
  378. }
  379. if (hasRuns) {
  380. updateBidi( changes );
  381. }
  382. changes.end();
  383. fireChangedUpdate(changes);
  384. fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
  385. } finally {
  386. writeUnlock();
  387. }
  388. }
  389. /**
  390. * Gets the paragraph element at the offset <code>pos</code>.
  391. * A paragraph consists of at least one child Element, which is usually
  392. * a leaf.
  393. *
  394. * @param pos the starting offset >= 0
  395. * @return the element
  396. */
  397. public Element getParagraphElement(int pos) {
  398. Element e = null;
  399. for (e = getDefaultRootElement(); ! e.isLeaf(); ) {
  400. int index = e.getElementIndex(pos);
  401. e = e.getElement(index);
  402. }
  403. if(e != null)
  404. return e.getParentElement();
  405. return e;
  406. }
  407. /**
  408. * Gets a character element based on a position.
  409. *
  410. * @param pos the position in the document >= 0
  411. * @return the element
  412. */
  413. public Element getCharacterElement(int pos) {
  414. Element e = null;
  415. for (e = getDefaultRootElement(); ! e.isLeaf(); ) {
  416. int index = e.getElementIndex(pos);
  417. e = e.getElement(index);
  418. }
  419. return e;
  420. }
  421. // --- local methods -------------------------------------------------
  422. /**
  423. * Updates document structure as a result of text insertion. This
  424. * will happen within a write lock. This implementation simply
  425. * parses the inserted content for line breaks and builds up a set
  426. * of instructions for the element buffer.
  427. *
  428. * @param chng a description of the document change
  429. * @param attr the attributes
  430. */
  431. protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) {
  432. int offset = chng.getOffset();
  433. int length = chng.getLength();
  434. if (attr == null) {
  435. attr = SimpleAttributeSet.EMPTY;
  436. }
  437. // Paragraph attributes should come from point after insertion.
  438. // You really only notice this when inserting at a paragraph
  439. // boundary.
  440. Element paragraph = getParagraphElement(offset + length);
  441. AttributeSet pattr = paragraph.getAttributes();
  442. // Character attributes should come from actual insertion point.
  443. Element pParagraph = getParagraphElement(offset);
  444. Element run = pParagraph.getElement(pParagraph.getElementIndex
  445. (offset));
  446. int endOffset = offset + length;
  447. boolean insertingAtBoundry = (run.getEndOffset() == endOffset);
  448. AttributeSet cattr = run.getAttributes();
  449. try {
  450. Segment s = new Segment();
  451. Vector parseBuffer = new Vector();
  452. ElementSpec lastStartSpec = null;
  453. boolean insertingAfterNewline = false;
  454. short lastStartDirection = ElementSpec.OriginateDirection;
  455. // Check if the previous character was a newline.
  456. if (offset > 0) {
  457. getText(offset - 1, 1, s);
  458. if (s.array[s.offset] == '\n') {
  459. // Inserting after a newline.
  460. insertingAfterNewline = true;
  461. lastStartDirection = createSpecsForInsertAfterNewline
  462. (paragraph, pParagraph, pattr, parseBuffer,
  463. offset, endOffset);
  464. for(int counter = parseBuffer.size() - 1; counter >= 0;
  465. counter--) {
  466. ElementSpec spec = (ElementSpec)parseBuffer.
  467. elementAt(counter);
  468. if(spec.getType() == ElementSpec.StartTagType) {
  469. lastStartSpec = spec;
  470. break;
  471. }
  472. }
  473. }
  474. }
  475. // If not inserting after a new line, pull the attributes for
  476. // new paragraphs from the paragraph under the insertion point.
  477. if(!insertingAfterNewline)
  478. pattr = pParagraph.getAttributes();
  479. getText(offset, length, s);
  480. char[] txt = s.array;
  481. int n = s.offset + s.count;
  482. int lastOffset = s.offset;
  483. for (int i = s.offset; i < n; i++) {
  484. if (txt[i] == '\n') {
  485. int breakOffset = i + 1;
  486. parseBuffer.addElement(
  487. new ElementSpec(attr, ElementSpec.ContentType,
  488. breakOffset - lastOffset));
  489. parseBuffer.addElement(
  490. new ElementSpec(null, ElementSpec.EndTagType));
  491. lastStartSpec = new ElementSpec(pattr, ElementSpec.
  492. StartTagType);
  493. parseBuffer.addElement(lastStartSpec);
  494. lastOffset = breakOffset;
  495. }
  496. }
  497. if (lastOffset < n) {
  498. parseBuffer.addElement(
  499. new ElementSpec(attr, ElementSpec.ContentType,
  500. n - lastOffset));
  501. }
  502. ElementSpec first = (ElementSpec) parseBuffer.firstElement();
  503. int docLength = getLength();
  504. // Check for join previous of first content.
  505. if(first.getType() == ElementSpec.ContentType &&
  506. cattr.isEqual(attr)) {
  507. first.setDirection(ElementSpec.JoinPreviousDirection);
  508. }
  509. // Do a join fracture/next for last start spec if necessary.
  510. if(lastStartSpec != null) {
  511. if(insertingAfterNewline) {
  512. lastStartSpec.setDirection(lastStartDirection);
  513. }
  514. // Join to the fracture if NOT inserting at the end
  515. // (fracture only happens when not inserting at end of
  516. // paragraph).
  517. else if(pParagraph.getEndOffset() != endOffset) {
  518. lastStartSpec.setDirection(ElementSpec.
  519. JoinFractureDirection);
  520. }
  521. // Join to next if parent of pParagraph has another
  522. // element after pParagraph, and it isn't a leaf.
  523. else {
  524. Element parent = pParagraph.getParentElement();
  525. int pParagraphIndex = parent.getElementIndex(offset);
  526. if((pParagraphIndex + 1) < parent.getElementCount() &&
  527. !parent.getElement(pParagraphIndex + 1).isLeaf()) {
  528. lastStartSpec.setDirection(ElementSpec.
  529. JoinNextDirection);
  530. }
  531. }
  532. }
  533. // Do a JoinNext for last spec if it is content, it doesn't
  534. // already have a direction set, no new paragraphs have been
  535. // inserted or a new paragraph has been inserted and its join
  536. // direction isn't originate, and the element at endOffset
  537. // is a leaf.
  538. if(insertingAtBoundry && endOffset < docLength) {
  539. ElementSpec last = (ElementSpec) parseBuffer.lastElement();
  540. if(last.getType() == ElementSpec.ContentType &&
  541. last.getDirection() != ElementSpec.JoinPreviousDirection &&
  542. ((lastStartSpec == null && (paragraph == pParagraph ||
  543. insertingAfterNewline)) ||
  544. (lastStartSpec != null && lastStartSpec.getDirection() !=
  545. ElementSpec.OriginateDirection))) {
  546. Element nextRun = paragraph.getElement(paragraph.
  547. getElementIndex(endOffset));
  548. // Don't try joining to a branch!
  549. if(nextRun.isLeaf() &&
  550. attr.isEqual(nextRun.getAttributes())) {
  551. last.setDirection(ElementSpec.JoinNextDirection);
  552. }
  553. }
  554. }
  555. // If not inserting at boundary and there is going to be a
  556. // fracture, then can join next on last content if cattr
  557. // matches the new attributes.
  558. else if(!insertingAtBoundry && lastStartSpec != null &&
  559. lastStartSpec.getDirection() ==
  560. ElementSpec.JoinFractureDirection) {
  561. ElementSpec last = (ElementSpec) parseBuffer.lastElement();
  562. if(last.getType() == ElementSpec.ContentType &&
  563. last.getDirection() != ElementSpec.JoinPreviousDirection &&
  564. attr.isEqual(cattr)) {
  565. last.setDirection(ElementSpec.JoinNextDirection);
  566. }
  567. }
  568. // Check for the composed text element. If it is, merge the character attributes
  569. // into this element as well.
  570. if (Utilities.isComposedTextAttributeDefined(attr)) {
  571. ((MutableAttributeSet)attr).addAttributes(cattr);
  572. ((MutableAttributeSet)attr).addAttribute(AbstractDocument.ElementNameAttribute,
  573. AbstractDocument.ContentElementName);
  574. }
  575. ElementSpec[] spec = new ElementSpec[parseBuffer.size()];
  576. parseBuffer.copyInto(spec);
  577. buffer.insert(offset, length, spec, chng);
  578. } catch (BadLocationException bl) {
  579. }
  580. super.insertUpdate( chng, attr );
  581. }
  582. /**
  583. * This is called by insertUpdate when inserting after a new line.
  584. * It generates, in <code>parseBuffer</code>, ElementSpecs that will
  585. * position the stack in <code>paragraph</code>.<p>
  586. * It returns the direction the last StartSpec should have (this don't
  587. * necessarily create the last start spec).
  588. */
  589. short createSpecsForInsertAfterNewline(Element paragraph,
  590. Element pParagraph, AttributeSet pattr, Vector parseBuffer,
  591. int offset, int endOffset) {
  592. // Need to find the common parent of pParagraph and paragraph.
  593. if(paragraph.getParentElement() == pParagraph.getParentElement()) {
  594. // The simple (and common) case that pParagraph and
  595. // paragraph have the same parent.
  596. ElementSpec spec = new ElementSpec(pattr, ElementSpec.EndTagType);
  597. parseBuffer.addElement(spec);
  598. spec = new ElementSpec(pattr, ElementSpec.StartTagType);
  599. parseBuffer.addElement(spec);
  600. if(pParagraph.getEndOffset() != endOffset)
  601. return ElementSpec.JoinFractureDirection;
  602. Element parent = pParagraph.getParentElement();
  603. if((parent.getElementIndex(offset) + 1) < parent.getElementCount())
  604. return ElementSpec.JoinNextDirection;
  605. }
  606. else {
  607. // Will only happen for text with more than 2 levels.
  608. // Find the common parent of a paragraph and pParagraph
  609. Vector leftParents = new Vector();
  610. Vector rightParents = new Vector();
  611. Element e = pParagraph;
  612. while(e != null) {
  613. leftParents.addElement(e);
  614. e = e.getParentElement();
  615. }
  616. e = paragraph;
  617. int leftIndex = -1;
  618. while(e != null && (leftIndex = leftParents.indexOf(e)) == -1) {
  619. rightParents.addElement(e);
  620. e = e.getParentElement();
  621. }
  622. if(e != null) {
  623. // e identifies the common parent.
  624. // Build the ends.
  625. for(int counter = 0; counter < leftIndex;
  626. counter++) {
  627. parseBuffer.addElement(new ElementSpec
  628. (null, ElementSpec.EndTagType));
  629. }
  630. // And the starts.
  631. ElementSpec spec = null;
  632. for(int counter = rightParents.size() - 1;
  633. counter >= 0; counter--) {
  634. spec = new ElementSpec(((Element)rightParents.
  635. elementAt(counter)).getAttributes(),
  636. ElementSpec.StartTagType);
  637. if(counter > 0)
  638. spec.setDirection(ElementSpec.JoinNextDirection);
  639. parseBuffer.addElement(spec);
  640. }
  641. // If there are right parents, then we generated starts
  642. // down the right subtree and there will be an element to
  643. // join to.
  644. if(rightParents.size() > 0)
  645. return ElementSpec.JoinNextDirection;
  646. // No right subtree, e.getElement(endOffset) is a
  647. // leaf. There will be a facture.
  648. return ElementSpec.JoinFractureDirection;
  649. }
  650. // else: Could throw an exception here, but should never get here!
  651. }
  652. return ElementSpec.OriginateDirection;
  653. }
  654. /**
  655. * Updates document structure as a result of text removal.
  656. *
  657. * @param chng a description of the document change
  658. */
  659. protected void removeUpdate(DefaultDocumentEvent chng) {
  660. super.removeUpdate(chng);
  661. buffer.remove(chng.getOffset(), chng.getLength(), chng);
  662. }
  663. /**
  664. * Creates the root element to be used to represent the
  665. * default document structure.
  666. *
  667. * @return the element base
  668. */
  669. protected AbstractElement createDefaultRoot() {
  670. // grabs a write-lock for this initialization and
  671. // abandon it during initialization so in normal
  672. // operation we can detect an illegitimate attempt
  673. // to mutate attributes.
  674. writeLock();
  675. BranchElement section = new SectionElement();
  676. BranchElement paragraph = new BranchElement(section, null);
  677. LeafElement brk = new LeafElement(paragraph, null, 0, 1);
  678. Element[] buff = new Element[1];
  679. buff[0] = brk;
  680. paragraph.replace(0, 0, buff);
  681. buff[0] = paragraph;
  682. section.replace(0, 0, buff);
  683. writeUnlock();
  684. return section;
  685. }
  686. /**
  687. * Gets the foreground color from an attribute set.
  688. *
  689. * @param attr the attribute set
  690. * @return the color
  691. */
  692. public Color getForeground(AttributeSet attr) {
  693. StyleContext styles = (StyleContext) getAttributeContext();
  694. return styles.getForeground(attr);
  695. }
  696. /**
  697. * Gets the background color from an attribute set.
  698. *
  699. * @param attr the attribute set
  700. * @return the color
  701. */
  702. public Color getBackground(AttributeSet attr) {
  703. StyleContext styles = (StyleContext) getAttributeContext();
  704. return styles.getBackground(attr);
  705. }
  706. /**
  707. * Gets the font from an attribute set.
  708. *
  709. * @param attr the attribute set
  710. * @return the font
  711. */
  712. public Font getFont(AttributeSet attr) {
  713. StyleContext styles = (StyleContext) getAttributeContext();
  714. return styles.getFont(attr);
  715. }
  716. /**
  717. * Called when any of this document's styles have changed.
  718. * Subclasses may wish to be intelligent about what gets damaged.
  719. *
  720. * @param style The Style that has changed.
  721. */
  722. protected void styleChanged(Style style) {
  723. // Only propagate change updated if have content
  724. if (getLength() != 0) {
  725. // lazily create a ChangeUpdateRunnable
  726. if (updateRunnable == null) {
  727. updateRunnable = new ChangeUpdateRunnable();
  728. }
  729. // We may get a whole batch of these at once, so only
  730. // queue the runnable if it is not already pending
  731. synchronized(updateRunnable) {
  732. if (!updateRunnable.isPending) {
  733. SwingUtilities.invokeLater(updateRunnable);
  734. updateRunnable.isPending = true;
  735. }
  736. }
  737. }
  738. }
  739. /**
  740. * Adds a document listener for notification of any changes.
  741. *
  742. * @param listener the listener
  743. * @see Document#addDocumentListener
  744. */
  745. public void addDocumentListener(DocumentListener listener) {
  746. synchronized(listeningStyles) {
  747. int oldDLCount = listenerList.getListenerCount
  748. (DocumentListener.class);
  749. super.addDocumentListener(listener);
  750. if (oldDLCount == 0) {
  751. if (styleContextChangeListener == null) {
  752. styleContextChangeListener =
  753. createStyleContextChangeListener();
  754. }
  755. if (styleContextChangeListener != null) {
  756. StyleContext styles = (StyleContext)getAttributeContext();
  757. styles.addChangeListener(styleContextChangeListener);
  758. }
  759. updateStylesListeningTo();
  760. }
  761. }
  762. }
  763. /**
  764. * Removes a document listener.
  765. *
  766. * @param listener the listener
  767. * @see Document#removeDocumentListener
  768. */
  769. public void removeDocumentListener(DocumentListener listener) {
  770. synchronized(listeningStyles) {
  771. super.removeDocumentListener(listener);
  772. if (listenerList.getListenerCount(DocumentListener.class) == 0) {
  773. for (int counter = listeningStyles.size() - 1; counter >= 0;
  774. counter--) {
  775. ((Style)listeningStyles.elementAt(counter)).
  776. removeChangeListener(styleChangeListener);
  777. }
  778. listeningStyles.removeAllElements();
  779. if (styleContextChangeListener != null) {
  780. StyleContext styles = (StyleContext)getAttributeContext();
  781. styles.removeChangeListener(styleContextChangeListener);
  782. }
  783. }
  784. }
  785. }
  786. /**
  787. * Returns a new instance of StyleChangeHandler.
  788. */
  789. ChangeListener createStyleChangeListener() {
  790. return new StyleChangeHandler();
  791. }
  792. /**
  793. * Returns a new instance of StyleContextChangeHandler.
  794. */
  795. ChangeListener createStyleContextChangeListener() {
  796. return new StyleContextChangeHandler();
  797. }
  798. /**
  799. * Adds a ChangeListener to new styles, and removes ChangeListener from
  800. * old styles.
  801. */
  802. void updateStylesListeningTo() {
  803. synchronized(listeningStyles) {
  804. StyleContext styles = (StyleContext)getAttributeContext();
  805. if (styleChangeListener == null) {
  806. styleChangeListener = createStyleChangeListener();
  807. }
  808. if (styleChangeListener != null && styles != null) {
  809. Enumeration styleNames = styles.getStyleNames();
  810. Vector v = (Vector)listeningStyles.clone();
  811. listeningStyles.removeAllElements();
  812. while (styleNames.hasMoreElements()) {
  813. String name = (String)styleNames.nextElement();
  814. Style aStyle = styles.getStyle(name);
  815. int index = v.indexOf(aStyle);
  816. listeningStyles.addElement(aStyle);
  817. if (index == -1) {
  818. aStyle.addChangeListener(styleChangeListener);
  819. }
  820. else {
  821. v.removeElementAt(index);
  822. }
  823. }
  824. for (int counter = v.size() - 1; counter >= 0; counter--) {
  825. Style aStyle = (Style)v.elementAt(counter);
  826. aStyle.removeChangeListener(styleChangeListener);
  827. }
  828. if (listeningStyles.size() == 0) {
  829. styleChangeListener = null;
  830. }
  831. }
  832. }
  833. }
  834. private void readObject(ObjectInputStream s)
  835. throws ClassNotFoundException, IOException {
  836. listeningStyles = new Vector();
  837. s.defaultReadObject();
  838. // Reinstall style listeners.
  839. if (styleContextChangeListener == null &&
  840. listenerList.getListenerCount(DocumentListener.class) > 0) {
  841. styleContextChangeListener = createStyleContextChangeListener();
  842. if (styleContextChangeListener != null) {
  843. StyleContext styles = (StyleContext)getAttributeContext();
  844. styles.addChangeListener(styleContextChangeListener);
  845. }
  846. updateStylesListeningTo();
  847. }
  848. }
  849. // --- member variables -----------------------------------------------------------
  850. /**
  851. * The default size of the initial content buffer.
  852. */
  853. public static final int BUFFER_SIZE_DEFAULT = 4096;
  854. protected ElementBuffer buffer;
  855. /** Styles listening to. */
  856. private transient Vector listeningStyles;
  857. /** Listens to Styles. */
  858. private transient ChangeListener styleChangeListener;
  859. /** Listens to Styles. */
  860. private transient ChangeListener styleContextChangeListener;
  861. /** Run to create a change event for the document */
  862. private transient ChangeUpdateRunnable updateRunnable;
  863. /**
  864. * Default root element for a document... maps out the
  865. * paragraphs/lines contained.
  866. * <p>
  867. * <strong>Warning:</strong>
  868. * Serialized objects of this class will not be compatible with
  869. * future Swing releases. The current serialization support is
  870. * appropriate for short term storage or RMI between applications running
  871. * the same version of Swing. As of 1.4, support for long term storage
  872. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  873. * has been added to the <code>java.beans</code> package.
  874. * Please see {@link java.beans.XMLEncoder}.
  875. */
  876. protected class SectionElement extends BranchElement {
  877. /**
  878. * Creates a new SectionElement.
  879. */
  880. public SectionElement() {
  881. super(null, null);
  882. }
  883. /**
  884. * Gets the name of the element.
  885. *
  886. * @return the name
  887. */
  888. public String getName() {
  889. return SectionElementName;
  890. }
  891. }
  892. /**
  893. * Specification for building elements.
  894. * <p>
  895. * <strong>Warning:</strong>
  896. * Serialized objects of this class will not be compatible with
  897. * future Swing releases. The current serialization support is
  898. * appropriate for short term storage or RMI between applications running
  899. * the same version of Swing. As of 1.4, support for long term storage
  900. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  901. * has been added to the <code>java.beans</code> package.
  902. * Please see {@link java.beans.XMLEncoder}.
  903. */
  904. public static class ElementSpec {
  905. /**
  906. * A possible value for getType. This specifies
  907. * that this record type is a start tag and
  908. * represents markup that specifies the start
  909. * of an element.
  910. */
  911. public static final short StartTagType = 1;
  912. /**
  913. * A possible value for getType. This specifies
  914. * that this record type is a end tag and
  915. * represents markup that specifies the end
  916. * of an element.
  917. */
  918. public static final short EndTagType = 2;
  919. /**
  920. * A possible value for getType. This specifies
  921. * that this record type represents content.
  922. */
  923. public static final short ContentType = 3;
  924. /**
  925. * A possible value for getDirection. This specifies
  926. * that the data associated with this record should
  927. * be joined to what precedes it.
  928. */
  929. public static final short JoinPreviousDirection = 4;
  930. /**
  931. * A possible value for getDirection. This specifies
  932. * that the data associated with this record should
  933. * be joined to what follows it.
  934. */
  935. public static final short JoinNextDirection = 5;
  936. /**
  937. * A possible value for getDirection. This specifies
  938. * that the data associated with this record should
  939. * be used to originate a new element. This would be
  940. * the normal value.
  941. */
  942. public static final short OriginateDirection = 6;
  943. /**
  944. * A possible value for getDirection. This specifies
  945. * that the data associated with this record should
  946. * be joined to the fractured element.
  947. */
  948. public static final short JoinFractureDirection = 7;
  949. /**
  950. * Constructor useful for markup when the markup will not
  951. * be stored in the document.
  952. *
  953. * @param a the attributes for the element
  954. * @param type the type of the element (StartTagType, EndTagType,
  955. * ContentType)
  956. */
  957. public ElementSpec(AttributeSet a, short type) {
  958. this(a, type, null, 0, 0);
  959. }
  960. /**
  961. * Constructor for parsing inside the document when
  962. * the data has already been added, but len information
  963. * is needed.
  964. *
  965. * @param a the attributes for the element
  966. * @param type the type of the element (StartTagType, EndTagType,
  967. * ContentType)
  968. * @param len the length >= 0
  969. */
  970. public ElementSpec(AttributeSet a, short type, int len) {
  971. this(a, type, null, 0, len);
  972. }
  973. /**
  974. * Constructor for creating a spec externally for batch
  975. * input of content and markup into the document.
  976. *
  977. * @param a the attributes for the element
  978. * @param type the type of the element (StartTagType, EndTagType,
  979. * ContentType)
  980. * @param txt the text for the element
  981. * @param offs the offset into the text >= 0
  982. * @param len the length of the text >= 0
  983. */
  984. public ElementSpec(AttributeSet a, short type, char[] txt,
  985. int offs, int len) {
  986. attr = a;
  987. this.type = type;
  988. this.data = txt;
  989. this.offs = offs;
  990. this.len = len;
  991. this.direction = OriginateDirection;
  992. }
  993. /**
  994. * Sets the element type.
  995. *
  996. * @param type the type of the element (StartTagType, EndTagType,
  997. * ContentType)
  998. */
  999. public void setType(short type) {
  1000. this.type = type;
  1001. }
  1002. /**
  1003. * Gets the element type.
  1004. *
  1005. * @return the type of the element (StartTagType, EndTagType,
  1006. * ContentType)
  1007. */
  1008. public short getType() {
  1009. return type;
  1010. }
  1011. /**
  1012. * Sets the direction.
  1013. *
  1014. * @param direction the direction (JoinPreviousDirection,
  1015. * JoinNextDirection)
  1016. */
  1017. public void setDirection(short direction) {
  1018. this.direction = direction;
  1019. }
  1020. /**
  1021. * Gets the direction.
  1022. *
  1023. * @return the direction (JoinPreviousDirection, JoinNextDirection)
  1024. */
  1025. public short getDirection() {
  1026. return direction;
  1027. }
  1028. /**
  1029. * Gets the element attributes.
  1030. *
  1031. * @return the attribute set
  1032. */
  1033. public AttributeSet getAttributes() {
  1034. return attr;
  1035. }
  1036. /**
  1037. * Gets the array of characters.
  1038. *
  1039. * @return the array
  1040. */
  1041. public char[] getArray() {
  1042. return data;
  1043. }
  1044. /**
  1045. * Gets the starting offset.
  1046. *
  1047. * @return the offset >= 0
  1048. */
  1049. public int getOffset() {
  1050. return offs;
  1051. }
  1052. /**
  1053. * Gets the length.
  1054. *
  1055. * @return the length >= 0
  1056. */
  1057. public int getLength() {
  1058. return len;
  1059. }
  1060. /**
  1061. * Converts the element to a string.
  1062. *
  1063. * @return the string
  1064. */
  1065. public String toString() {
  1066. String tlbl = "??";
  1067. String plbl = "??";
  1068. switch(type) {
  1069. case StartTagType:
  1070. tlbl = "StartTag";
  1071. break;
  1072. case ContentType:
  1073. tlbl = "Content";
  1074. break;
  1075. case EndTagType:
  1076. tlbl = "EndTag";
  1077. break;
  1078. }
  1079. switch(direction) {
  1080. case JoinPreviousDirection:
  1081. plbl = "JoinPrevious";
  1082. break;
  1083. case JoinNextDirection:
  1084. plbl = "JoinNext";
  1085. break;
  1086. case OriginateDirection:
  1087. plbl = "Originate";
  1088. break;
  1089. case JoinFractureDirection:
  1090. plbl = "Fracture";
  1091. break;
  1092. }
  1093. return tlbl + ":" + plbl + ":" + getLength();
  1094. }
  1095. private AttributeSet attr;
  1096. private int len;
  1097. private short type;
  1098. private short direction;
  1099. private int offs;
  1100. private char[] data;
  1101. }
  1102. /**
  1103. * Class to manage changes to the element
  1104. * hierarchy.
  1105. * <p>
  1106. * <strong>Warning:</strong>
  1107. * Serialized objects of this class will not be compatible with
  1108. * future Swing releases. The current serialization support is
  1109. * appropriate for short term storage or RMI between applications running
  1110. * the same version of Swing. As of 1.4, support for long term storage
  1111. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  1112. * has been added to the <code>java.beans</code> package.
  1113. * Please see {@link java.beans.XMLEncoder}.
  1114. */
  1115. public class ElementBuffer implements Serializable {
  1116. /**
  1117. * Creates a new ElementBuffer.
  1118. *
  1119. * @param root the root element
  1120. */
  1121. public ElementBuffer(Element root) {
  1122. this.root = root;
  1123. changes = new Vector();
  1124. path = new Stack();
  1125. }
  1126. /**
  1127. * Gets the root element.
  1128. *
  1129. * @return the root element
  1130. */
  1131. public Element getRootElement() {
  1132. return root;
  1133. }
  1134. /**
  1135. * Inserts new content.
  1136. *
  1137. * @param offset the starting offset >= 0
  1138. * @param length the length >= 0
  1139. * @param data the data to insert
  1140. * @param de the event capturing this edit
  1141. */
  1142. public void insert(int offset, int length, ElementSpec[] data,
  1143. DefaultDocumentEvent de) {
  1144. if (length == 0) {
  1145. // Nothing was inserted, no structure change.
  1146. return;
  1147. }
  1148. insertOp = true;
  1149. beginEdits(offset, length);
  1150. insertUpdate(data);
  1151. endEdits(de);
  1152. insertOp = false;
  1153. }
  1154. void create(int length, ElementSpec[] data, DefaultDocumentEvent de) {
  1155. insertOp = true;
  1156. beginEdits(offset, length);
  1157. // PENDING(prinz) this needs to be fixed to create a new
  1158. // root element as well, but requires changes to the
  1159. // DocumentEvent to inform the views that there is a new
  1160. // root element.
  1161. // Recreate the ending fake element to have the correct offsets.
  1162. Element elem = root;
  1163. int index = elem.getElementIndex(0);
  1164. while (! elem.isLeaf()) {
  1165. Element child = elem.getElement(index);
  1166. push(elem, index);
  1167. elem = child;
  1168. index = elem.getElementIndex(0);
  1169. }
  1170. ElemChanges ec = (ElemChanges) path.peek();
  1171. Element child = ec.parent.getElement(ec.index);
  1172. ec.added.addElement(createLeafElement(ec.parent,
  1173. child.getAttributes(), getLength(),
  1174. child.getEndOffset()));
  1175. ec.removed.addElement(child);
  1176. while (path.size() > 1) {
  1177. pop();
  1178. }
  1179. int n = data.length;
  1180. // Reset the root elements attributes.
  1181. AttributeSet newAttrs = null;
  1182. if (n > 0 && data[0].getType() == ElementSpec.StartTagType) {
  1183. newAttrs = data[0].getAttributes();
  1184. }
  1185. if (newAttrs == null) {
  1186. newAttrs = SimpleAttributeSet.EMPTY;
  1187. }
  1188. MutableAttributeSet attr = (MutableAttributeSet)root.
  1189. getAttributes();
  1190. de.addEdit(new AttributeUndoableEdit(root, newAttrs, true));
  1191. attr.removeAttributes(attr);
  1192. attr.addAttributes(newAttrs);
  1193. // fold in the specified subtree
  1194. for (int i = 1; i < n; i++) {
  1195. insertElement(data[i]);
  1196. }
  1197. // pop the remaining path
  1198. while (path.size() != 0) {
  1199. pop();
  1200. }
  1201. endEdits(de);
  1202. insertOp = false;
  1203. }
  1204. /**
  1205. * Removes content.
  1206. *
  1207. * @param offset the starting offset >= 0
  1208. * @param length the length >= 0
  1209. * @param de the event capturing this edit
  1210. */
  1211. public void remove(int offset, int length, DefaultDocumentEvent de) {
  1212. beginEdits(offset, length);
  1213. removeUpdate();
  1214. endEdits(de);
  1215. }
  1216. /**
  1217. * Changes content.
  1218. *
  1219. * @param offset the starting offset >= 0
  1220. * @param length the length >= 0
  1221. * @param de the event capturing this edit
  1222. */
  1223. public void change(int offset, int length, DefaultDocumentEvent de) {
  1224. beginEdits(offset, length);
  1225. changeUpdate();
  1226. endEdits(de);
  1227. }
  1228. /**
  1229. * Inserts an update into the document.
  1230. *
  1231. * @param data the elements to insert
  1232. */
  1233. protected void insertUpdate(ElementSpec[] data) {
  1234. // push the path
  1235. Element elem = root;
  1236. int index = elem.getElementIndex(offset);
  1237. while (! elem.isLeaf()) {
  1238. Element child = elem.getElement(index);
  1239. push(elem, (child.isLeaf() ? index : index+1));
  1240. elem = child;
  1241. index = elem.getElementIndex(offset);
  1242. }
  1243. // Build a copy of the original path.
  1244. insertPath = new ElemChanges[path.size()];
  1245. path.copyInto(insertPath);
  1246. // Haven't created the fracture yet.
  1247. createdFracture = false;
  1248. // Insert the first content.
  1249. int i;
  1250. recreateLeafs = false;
  1251. if(data[0].getType() == ElementSpec.ContentType) {
  1252. insertFirstContent(data);
  1253. pos += data[0].getLength();
  1254. i = 1;
  1255. }
  1256. else {
  1257. fractureDeepestLeaf(data);
  1258. i = 0;
  1259. }
  1260. // fold in the specified subtree
  1261. int n = data.length;
  1262. for (; i < n; i++) {
  1263. insertElement(data[i]);
  1264. }
  1265. // Fracture, if we haven't yet.
  1266. if(!createdFracture)
  1267. fracture(-1);
  1268. // pop the remaining path
  1269. while (path.size() != 0) {
  1270. pop();
  1271. }
  1272. // Offset the last index if necessary.
  1273. if(offsetLastIndex && offsetLastIndexOnReplace) {
  1274. insertPath[insertPath.length - 1].index++;
  1275. }
  1276. // Make sure an edit is going to be created for each of the
  1277. // original path items that have a change.
  1278. for(int counter = insertPath.length - 1; counter >= 0;
  1279. counter--) {
  1280. ElemChanges change = insertPath[counter];
  1281. if(change.parent == fracturedParent)
  1282. change.added.addElement(fracturedChild);
  1283. if((change.added.size() > 0 ||
  1284. change.removed.size() > 0) && !changes.contains(change)) {
  1285. // PENDING(sky): Do I need to worry about order here?
  1286. changes.addElement(change);
  1287. }
  1288. }
  1289. // An insert at 0 with an initial end implies some elements
  1290. // will have no children (the bottomost leaf would have length 0)
  1291. // this will find what element need to be removed and remove it.
  1292. if (offset == 0 && fracturedParent != null &&
  1293. data[0].getType() == ElementSpec.EndTagType) {
  1294. int counter = 0;
  1295. while (counter < data.length &&
  1296. data[counter].getType() == ElementSpec.EndTagType) {
  1297. counter++;
  1298. }
  1299. ElemChanges change = insertPath[insertPath.length -
  1300. counter - 1];
  1301. change.removed.insertElementAt(change.parent.getElement
  1302. (--change.index), 0);
  1303. }
  1304. }
  1305. /**
  1306. * Updates the element structure in response to a removal from the
  1307. * associated sequence in the document. Any elements consumed by the
  1308. * span of the removal are removed.
  1309. */
  1310. protected void removeUpdate() {
  1311. removeElements(root, offset, offset + length);
  1312. }
  1313. /**
  1314. * Updates the element structure in response to a change in the
  1315. * document.
  1316. */
  1317. protected void changeUpdate() {
  1318. boolean didEnd = split(offset, length);
  1319. if (! didEnd) {
  1320. // need to do the other end
  1321. while (path.size() != 0) {
  1322. pop();
  1323. }
  1324. split(offset + length, 0);
  1325. }
  1326. while (path.size() != 0) {
  1327. pop();
  1328. }
  1329. }
  1330. boolean split(int offs, int len) {
  1331. boolean splitEnd = false;
  1332. // push the path
  1333. Element e = root;
  1334. int index = e.getElementIndex(offs);
  1335. while (! e.isLeaf()) {
  1336. push(e, index);
  1337. e = e.getElement(index);
  1338. index = e.getElementIndex(offs);
  1339. }
  1340. ElemChanges ec = (ElemChanges) path.peek();
  1341. Element child = ec.parent.getElement(ec.index);
  1342. // make sure there is something to do... if the
  1343. // offset is already at a boundary then there is
  1344. // nothing to do.
  1345. if (child.getStartOffset() < offs && offs < child.getEndOffset()) {
  1346. // we need to split, now see if the other end is within
  1347. // the same parent.
  1348. int index0 = ec.index;
  1349. int index1 = index0;
  1350. if (((offs + len) < ec.parent.getEndOffset()) && (len != 0)) {
  1351. // it's a range split in the same parent
  1352. index1 = ec.parent.getElementIndex(offs+len);
  1353. if (index1 == index0) {
  1354. // it's a three-way split
  1355. ec.removed.addElement(child);
  1356. e = createLeafElement(ec.parent, child.getAttributes(),
  1357. child.getStartOffset(), offs);
  1358. ec.added.addElement(e);
  1359. e = createLeafElement(ec.parent, child.getAttributes(),
  1360. offs, offs + len);
  1361. ec.added.addElement(e);
  1362. e = createLeafElement(ec.parent, child.getAttributes(),
  1363. offs + len, child.getEndOffset());
  1364. ec.added.addElement(e);
  1365. return true;
  1366. } else {
  1367. child = ec.parent.getElement(index1);
  1368. if ((offs + len) == child.getStartOffset()) {
  1369. // end is already on a boundary
  1370. index1 = index0;
  1371. }
  1372. }
  1373. splitEnd = true;
  1374. }
  1375. // split the first location
  1376. pos = offs;
  1377. child = ec.parent.getElement(index0);
  1378. ec.removed.addElement(child);
  1379. e = createLeafElement(ec.parent, child.getAttributes(),
  1380. child.getStartOffset(), pos);
  1381. ec.added.addElement(e);
  1382. e = createLeafElement(ec.parent, child.getAttributes(),
  1383. pos, child.getEndOffset());
  1384. ec.added.addElement(e);
  1385. // pick up things in the middle
  1386. for (int i = index0 + 1; i < index1; i++) {
  1387. child = ec.parent.getElement(i);
  1388. ec.removed.addElement(child);
  1389. ec.added.addElement(child);
  1390. }
  1391. if (index1 != index0) {
  1392. child = ec.parent.getElement(index1);
  1393. pos = offs + len;
  1394. ec.removed.addElement(child);
  1395. e = createLeafElement(ec.parent, child.getAttributes(),
  1396. child.getStartOffset(), pos);
  1397. ec.added.addElement(e);
  1398. e = createLeafElement(ec.parent, child.getAttributes(),
  1399. pos, child.getEndOffset());
  1400. ec.added.addElement(e);
  1401. }
  1402. }
  1403. return splitEnd;
  1404. }
  1405. /**
  1406. * Creates the UndoableEdit record for the edits made
  1407. * in the buffer.
  1408. */
  1409. void endEdits(DefaultDocumentEvent de) {
  1410. int n = changes.size();
  1411. for (int i = 0; i < n; i++) {
  1412. ElemChanges ec = (ElemChanges) changes.elementAt(i);
  1413. Element[] removed = new Element[ec.removed.size()];
  1414. ec.removed.copyInto(removed);
  1415. Element[] added = new Element[ec.added.size()];
  1416. ec.added.copyInto(added);
  1417. int index = ec.index;
  1418. ((BranchElement) ec.parent).replace(index, removed.length, added);
  1419. ElementEdit ee = new ElementEdit((BranchElement) ec.parent,
  1420. index, removed, added);
  1421. de.addEdit(ee);
  1422. }
  1423. changes.removeAllElements();
  1424. path.removeAllElements();
  1425. /*
  1426. for (int i = 0; i < n; i++) {
  1427. ElemChanges ec = (ElemChanges) changes.elementAt(i);
  1428. System.err.print("edited: " + ec.parent + " at: " + ec.index +
  1429. " removed " + ec.removed.size());
  1430. if (ec.removed.size() > 0) {
  1431. int r0 = ((Element) ec.removed.firstElement()).getStartOffset();
  1432. int r1 = ((Element) ec.removed.lastElement()).getEndOffset();
  1433. System.err.print("[" + r0 + "," + r1 + "]");
  1434. }
  1435. System.err.print(" added " + ec.added.size());
  1436. if (ec.added.size() > 0) {
  1437. int p0 = ((Element) ec.added.firstElement()).getStartOffset();
  1438. int p1 = ((Element) ec.added.lastElement()).getEndOffset();
  1439. System.err.print("[" + p0 + "," + p1 + "]");
  1440. }
  1441. System.err.println("");
  1442. }
  1443. */
  1444. }
  1445. /**
  1446. * Initialize the buffer
  1447. */
  1448. void beginEdits(int offset, int length) {
  1449. this.offset = offset;
  1450. this.length = length;
  1451. this.endOffset = offset + length;
  1452. pos = offset;
  1453. if (changes == null) {
  1454. changes = new Vector();
  1455. } else {
  1456. changes.removeAllElements();
  1457. }
  1458. if (path == null) {
  1459. path = new Stack();
  1460. } else {
  1461. path.removeAllElements();
  1462. }
  1463. fracturedParent = null;
  1464. fracturedChild = null;
  1465. offsetLastIndex = offsetLastIndexOnReplace = false;
  1466. }
  1467. /**
  1468. * Pushes a new element onto the stack that represents
  1469. * the current path.
  1470. * @param record Whether or not the push should be
  1471. * recorded as an element change or not.
  1472. * @param isFracture true if pushing on an element that was created
  1473. * as the result of a fracture.
  1474. */
  1475. void push(Element e, int index, boolean isFracture) {
  1476. ElemChanges ec = new ElemChanges(e, index, isFracture);
  1477. path.push(ec);
  1478. }
  1479. void push(Element e, int index) {
  1480. push(e, index, false);
  1481. }
  1482. void pop() {
  1483. ElemChanges ec = (ElemChanges) path.peek();
  1484. path.pop();
  1485. if ((ec.added.size() > 0) || (ec.removed.size() > 0)) {
  1486. changes.addElement(ec);
  1487. } else if (! path.isEmpty()) {
  1488. Element e = ec.parent;
  1489. if(e.getElementCount() == 0) {
  1490. // if we pushed a branch element that didn't get
  1491. // used, make sure its not marked as having been added.
  1492. ec = (ElemChanges) path.peek();
  1493. ec.added.removeElement(e);
  1494. }
  1495. }
  1496. }
  1497. /**
  1498. * move the current offset forward by n.
  1499. */
  1500. void advance(int n) {
  1501. pos += n;
  1502. }
  1503. void insertElement(ElementSpec es) {
  1504. ElemChanges ec = (ElemChanges) path.peek();
  1505. switch(es.getType()) {
  1506. case ElementSpec.StartTagType:
  1507. switch(es.getDirection()) {
  1508. case ElementSpec.JoinNextDirection:
  1509. // Don't create a new element, use the existing one
  1510. // at the specified location.
  1511. Element parent = ec.parent.getElement(ec.index);
  1512. if(parent.isLeaf()) {
  1513. // This happens if inserting into a leaf, followed
  1514. // by a join next where next sibling is not a leaf.
  1515. if((ec.index + 1) < ec.parent.getElementCount())
  1516. parent = ec.parent.getElement(ec.index + 1);
  1517. else
  1518. throw new StateInvariantError("Join next to leaf");
  1519. }
  1520. // Not really a fracture, but need to treat it like
  1521. // one so that content join next will work correctly.
  1522. // We can do this because there will never be a join
  1523. // next followed by a join fracture.
  1524. push(parent, 0, true);
  1525. break;
  1526. case ElementSpec.JoinFractureDirection:
  1527. if(!createdFracture) {
  1528. // Should always be something on the stack!
  1529. fracture(path.size() - 1);
  1530. }
  1531. // If parent isn't a fracture, fracture will be
  1532. // fracturedChild.
  1533. if(!ec.isFracture) {
  1534. push(fracturedChild, 0, true);
  1535. }
  1536. else
  1537. // Parent is a fracture, use 1st element.
  1538. push(ec.parent.getElement(0), 0, true);
  1539. break;
  1540. default:
  1541. Element belem = createBranchElement(ec.parent,
  1542. es.getAttributes());
  1543. ec.added.addElement(belem);
  1544. push(belem, 0);
  1545. break;
  1546. }
  1547. break;
  1548. case ElementSpec.EndTagType:
  1549. pop();
  1550. break;
  1551. case ElementSpec.ContentType:
  1552. int len = es.getLength();
  1553. if (es.getDirection() != ElementSpec.JoinNextDirection) {
  1554. Element leaf = createLeafElement(ec.parent, es.getAttributes(),
  1555. pos, pos + len);
  1556. ec.added.addElement(leaf);
  1557. }
  1558. else {
  1559. // JoinNext on tail is only applicable if last element
  1560. // and attributes come from that of first element.
  1561. // With a little extra testing it would be possible
  1562. // to NOT due this again, as more than likely fracture()
  1563. // created this element.
  1564. if(!ec.isFracture) {
  1565. Element first = null;
  1566. if(insertPath != null) {
  1567. for(int counter = insertPath.length - 1;
  1568. counter >= 0; counter--) {
  1569. if(insertPath[counter] == ec) {
  1570. if(counter != (insertPath.length - 1))
  1571. first = ec.parent.getElement(ec.index);
  1572. break;
  1573. }
  1574. }
  1575. }
  1576. if(first == null)
  1577. first = ec.parent.getElement(ec.index + 1);
  1578. Element leaf = createLeafElement(ec.parent, first.
  1579. getAttributes(), pos, first.getEndOffset());
  1580. ec.added.addElement(leaf);
  1581. ec.removed.addElement(first);
  1582. }
  1583. else {
  1584. // Parent was fractured element.
  1585. Element first = ec.parent.getElement(0);
  1586. Element leaf = createLeafElement(ec.parent, first.
  1587. getAttributes(), pos, first.getEndOffset());
  1588. ec.added.addElement(leaf);
  1589. ec.removed.addElement(first);
  1590. }
  1591. }
  1592. pos += len;
  1593. break;
  1594. }
  1595. }
  1596. /**
  1597. * Remove the elements from <code>elem</code> in range
  1598. * <code>rmOffs0</code>, <code>rmOffs1</code>. This uses
  1599. * <code>canJoin</code> and <code>join</code> to handle joining
  1600. * the endpoints of the insertion.
  1601. *
  1602. * @return true if elem will no longer have any elements.
  1603. */
  1604. boolean removeElements(Element elem, int rmOffs0, int rmOffs1) {
  1605. if (! elem.isLeaf()) {
  1606. // update path for changes
  1607. int index0 = elem.getElementIndex(rmOffs0);
  1608. int index1 = elem.getElementIndex(rmOffs1);
  1609. push(elem, index0);
  1610. ElemChanges ec = (ElemChanges)path.peek();
  1611. // if the range is contained by one element,
  1612. // we just forward the request
  1613. if (index0 == index1) {
  1614. Element child0 = elem.getElement(index0);
  1615. if(rmOffs0 <= child0.getStartOffset() &&
  1616. rmOffs1 >= child0.getEndOffset()) {
  1617. // Element totally removed.
  1618. ec.removed.addElement(child0);
  1619. }
  1620. else if(removeElements(child0, rmOffs0, rmOffs1)) {
  1621. ec.removed.addElement(child0);
  1622. }
  1623. } else {
  1624. // the removal range spans elements. If we can join
  1625. // the two endpoints, do it. Otherwise we remove the
  1626. // interior and forward to the endpoints.
  1627. Element child0 = elem.getElement(index0);
  1628. Element child1 = elem.getElement(index1);
  1629. boolean containsOffs1 = (rmOffs1 < elem.getEndOffset());
  1630. if (containsOffs1 && canJoin(child0, child1)) {
  1631. // remove and join
  1632. for (int i = index0; i <= index1; i++) {
  1633. ec.removed.addElement(elem.getElement(i));
  1634. }
  1635. Element e = join(elem, child0, child1, rmOffs0, rmOffs1);
  1636. ec.added.addElement(e);
  1637. } else {
  1638. // remove interior and forward
  1639. int rmIndex0 = index0 + 1;
  1640. int rmIndex1 = index1 - 1;
  1641. if (child0.getStartOffset() == rmOffs0 ||
  1642. (index0 == 0 &&
  1643. child0.getStartOffset() > rmOffs0 &&
  1644. child0.getEndOffset() <= rmOffs1)) {
  1645. // start element completely consumed
  1646. child0 = null;
  1647. rmIndex0 = index0;
  1648. }
  1649. if (!containsOffs1) {
  1650. child1 = null;
  1651. rmIndex1++;
  1652. }
  1653. else if (child1.getStartOffset() == rmOffs1) {
  1654. // end element not touched
  1655. child1 = null;
  1656. }
  1657. if (rmIndex0 <= rmIndex1) {
  1658. ec.index = rmIndex0;
  1659. }
  1660. for (int i = rmIndex0; i <= rmIndex1; i++) {
  1661. ec.removed.addElement(elem.getElement(i));
  1662. }
  1663. if (child0 != null) {
  1664. if(removeElements(child0, rmOffs0, rmOffs1)) {
  1665. ec.removed.insertElementAt(child0, 0);
  1666. ec.index = index0;
  1667. }
  1668. }
  1669. if (child1 != null) {
  1670. if(removeElements(child1, rmOffs0, rmOffs1)) {
  1671. ec.removed.addElement(child1);
  1672. }
  1673. }
  1674. }
  1675. }
  1676. // publish changes
  1677. pop();
  1678. // Return true if we no longer have any children.
  1679. if(elem.getElementCount() == (ec.removed.size() -
  1680. ec.added.size())) {
  1681. return true;
  1682. }
  1683. }
  1684. return false;
  1685. }
  1686. /**
  1687. * Can the two given elements be coelesced together
  1688. * into one element?
  1689. */
  1690. boolean canJoin(Element e0, Element e1) {
  1691. if ((e0 == null) || (e1 == null)) {
  1692. return false;
  1693. }
  1694. // Don't join a leaf to a branch.
  1695. boolean leaf0 = e0.isLeaf();
  1696. boolean leaf1 = e1.isLeaf();
  1697. if(leaf0 != leaf1) {
  1698. return false;
  1699. }
  1700. if (leaf0) {
  1701. // Only join leaves if the attributes match, otherwise
  1702. // style information will be lost.
  1703. return e0.getAttributes().isEqual(e1.getAttributes());
  1704. }
  1705. // Only join non-leafs if the names are equal. This may result
  1706. // in loss of style information, but this is typically acceptable
  1707. // for non-leafs.
  1708. String name0 = e0.getName();
  1709. String name1 = e1.getName();
  1710. if (name0 != null) {
  1711. return name0.equals(name1);
  1712. }
  1713. if (name1 != null) {
  1714. return name1.equals(name0);
  1715. }
  1716. // Both names null, treat as equal.
  1717. return true;
  1718. }
  1719. /**
  1720. * Joins the two elements carving out a hole for the
  1721. * given removed range.
  1722. */
  1723. Element join(Element p, Element left, Element right, int rmOffs0, int rmOffs1) {
  1724. if (left.isLeaf() && right.isLeaf()) {
  1725. return createLeafElement(p, left.getAttributes(), left.getStartOffset(),
  1726. right.getEndOffset());
  1727. } else if ((!left.isLeaf()) && (!right.isLeaf())) {
  1728. // join two branch elements. This copies the children before
  1729. // the removal range on the left element, and after the removal
  1730. // range on the right element. The two elements on the edge
  1731. // are joined if possible and needed.
  1732. Element to = createBranchElement(p, left.getAttributes());
  1733. int ljIndex = left.getElementIndex(rmOffs0);
  1734. int rjIndex = right.getElementIndex(rmOffs1);
  1735. Element lj = left.getElement(ljIndex);
  1736. if (lj.getStartOffset() >= rmOffs0) {
  1737. lj = null;
  1738. }
  1739. Element rj = right.getElement(rjIndex);
  1740. if (rj.getStartOffset() == rmOffs1) {
  1741. rj = null;
  1742. }
  1743. Vector children = new Vector();
  1744. // transfer the left
  1745. for (int i = 0; i < ljIndex; i++) {
  1746. children.addElement(clone(to, left.getElement(i)));
  1747. }
  1748. // transfer the join/middle
  1749. if (canJoin(lj, rj)) {
  1750. Element e = join(to, lj, rj, rmOffs0, rmOffs1);
  1751. children.addElement(e);
  1752. } else {
  1753. if (lj != null) {
  1754. children.addElement(cloneAsNecessary(to, lj, rmOffs0, rmOffs1));
  1755. }
  1756. if (rj != null) {
  1757. children.addElement(cloneAsNecessary(to, rj, rmOffs0, rmOffs1));
  1758. }
  1759. }
  1760. // transfer the right
  1761. int n = right.getElementCount();
  1762. for (int i = (rj == null) ? rjIndex : rjIndex + 1; i < n; i++) {
  1763. children.addElement(clone(to, right.getElement(i)));
  1764. }
  1765. // install the children
  1766. Element[] c = new Element[children.size()];
  1767. children.copyInto(c);
  1768. ((BranchElement)to).replace(0, 0, c);
  1769. return to;
  1770. } else {
  1771. throw new StateInvariantError(
  1772. "No support to join leaf element with non-leaf element");
  1773. }
  1774. }
  1775. /**
  1776. * Creates a copy of this element, with a different
  1777. * parent.
  1778. *
  1779. * @param parent the parent element
  1780. * @param clonee the element to be cloned
  1781. * @return the copy
  1782. */
  1783. public Element clone(Element parent, Element clonee) {
  1784. if (clonee.isLeaf()) {
  1785. return createLeafElement(parent, clonee.getAttributes(),
  1786. clonee.getStartOffset(),
  1787. clonee.getEndOffset());
  1788. }
  1789. Element e = createBranchElement(parent, clonee.getAttributes());
  1790. int n = clonee.getElementCount();
  1791. Element[] children = new Element[n];
  1792. for (int i = 0; i < n; i++) {
  1793. children[i] = clone(e, clonee.getElement(i));
  1794. }
  1795. ((BranchElement)e).replace(0, 0, children);
  1796. return e;
  1797. }
  1798. /**
  1799. * Creates a copy of this element, with a different
  1800. * parent. Children of this element included in the
  1801. * removal range will be discarded.
  1802. */
  1803. Element cloneAsNecessary(Element parent, Element clonee, int rmOffs0, int rmOffs1) {
  1804. if (clonee.isLeaf()) {
  1805. return createLeafElement(parent, clonee.getAttributes(),
  1806. clonee.getStartOffset(),
  1807. clonee.getEndOffset());
  1808. }
  1809. Element e = createBranchElement(parent, clonee.getAttributes());
  1810. int n = clonee.getElementCount();
  1811. ArrayList childrenList = new ArrayList(n);
  1812. for (int i = 0; i < n; i++) {
  1813. Element elem = clonee.getElement(i);
  1814. if (elem.getStartOffset() < rmOffs0 || elem.getEndOffset() > rmOffs1) {
  1815. childrenList.add(cloneAsNecessary(e, elem, rmOffs0, rmOffs1));
  1816. }
  1817. }
  1818. Element[] children = new Element[childrenList.size()];
  1819. children = (Element[])childrenList.toArray(children);
  1820. ((BranchElement)e).replace(0, 0, children);
  1821. return e;
  1822. }
  1823. /**
  1824. * Determines if a fracture needs to be performed. A fracture
  1825. * can be thought of as moving the right part of a tree to a
  1826. * new location, where the right part is determined by what has
  1827. * been inserted. <code>depth</code> is used to indicate a
  1828. * JoinToFracture is needed to an element at a depth
  1829. * of <code>depth</code>. Where the root is 0, 1 is the children
  1830. * of the root...
  1831. * <p>This will invoke <code>fractureFrom</code> if it is determined
  1832. * a fracture needs to happen.
  1833. */
  1834. void fracture(int depth) {
  1835. int cLength = insertPath.length;
  1836. int lastIndex = -1;
  1837. boolean needRecreate = recreateLeafs;
  1838. ElemChanges lastChange = insertPath[cLength - 1];
  1839. // Use childAltered to determine when a child has been altered,
  1840. // that is the point of insertion is less than the element count.
  1841. boolean childAltered = ((lastChange.index + 1) <
  1842. lastChange.parent.getElementCount());
  1843. int deepestAlteredIndex = (needRecreate) ? cLength : -1;
  1844. int lastAlteredIndex = cLength - 1;
  1845. createdFracture = true;
  1846. // Determine where to start recreating from.
  1847. // Start at - 2, as first one is indicated by recreateLeafs and
  1848. // childAltered.
  1849. for(int counter = cLength - 2; counter >= 0; counter--) {
  1850. ElemChanges change = insertPath[counter];
  1851. if(change.added.size() > 0 || counter == depth) {
  1852. lastIndex = counter;
  1853. if(!needRecreate && childAltered) {
  1854. needRecreate = true;
  1855. if(deepestAlteredIndex == -1)
  1856. deepestAlteredIndex = lastAlteredIndex + 1;
  1857. }
  1858. }
  1859. if(!childAltered && change.index <
  1860. change.parent.getElementCount()) {
  1861. childAltered = true;
  1862. lastAlteredIndex = counter;
  1863. }
  1864. }
  1865. if(needRecreate) {
  1866. // Recreate all children to right of parent starting
  1867. // at lastIndex.
  1868. if(lastIndex == -1)
  1869. lastIndex = cLength - 1;
  1870. fractureFrom(insertPath, lastIndex, deepestAlteredIndex);
  1871. }
  1872. }
  1873. /**
  1874. * Recreates the elements to the right of the insertion point.
  1875. * This starts at <code>startIndex</code> in <code>changed</code>,
  1876. * and calls duplicate to duplicate existing elements.
  1877. * This will also duplicate the elements along the insertion
  1878. * point, until a depth of <code>endFractureIndex</code> is
  1879. * reached, at which point only the elements to the right of
  1880. * the insertion point are duplicated.
  1881. */
  1882. void fractureFrom(ElemChanges[] changed, int startIndex,
  1883. int endFractureIndex) {
  1884. // Recreate the element representing the inserted index.
  1885. ElemChanges change = changed[startIndex];
  1886. Element child;
  1887. Element newChild;
  1888. int changeLength = changed.length;
  1889. if((startIndex + 1) == changeLength)
  1890. child = change.parent.getElement(change.index);
  1891. else
  1892. child = change.parent.getElement(change.index - 1);
  1893. if(child.isLeaf()) {
  1894. newChild = createLeafElement(change.parent,
  1895. child.getAttributes(), Math.max(endOffset,
  1896. child.getStartOffset()), child.getEndOffset());
  1897. }
  1898. else {
  1899. newChild = createBranchElement(change.parent,
  1900. child.getAttributes());
  1901. }
  1902. fracturedParent = change.parent;
  1903. fracturedChild = newChild;
  1904. // Recreate all the elements to the right of the
  1905. // insertion point.
  1906. Element parent = newChild;
  1907. while(++startIndex < endFractureIndex) {
  1908. boolean isEnd = ((startIndex + 1) == endFractureIndex);
  1909. boolean isEndLeaf = ((startIndex + 1) == changeLength);
  1910. // Create the newChild, a duplicate of the elment at
  1911. // index. This isn't done if isEnd and offsetLastIndex are true
  1912. // indicating a join previous was done.
  1913. change = changed[startIndex];
  1914. // Determine the child to duplicate, won't have to duplicate
  1915. // if at end of fracture, or offseting index.
  1916. if(isEnd) {
  1917. if(offsetLastIndex || !isEndLeaf)
  1918. child = null;
  1919. else
  1920. child = change.parent.getElement(change.index);
  1921. }
  1922. else {
  1923. child = change.parent.getElement(change.index - 1);
  1924. }
  1925. // Duplicate it.
  1926. if(child != null) {
  1927. if(child.isLeaf()) {
  1928. newChild = createLeafElement(parent,
  1929. child.getAttributes(), Math.max(endOffset,
  1930. child.getStartOffset()), child.getEndOffset());
  1931. }
  1932. else {
  1933. newChild = createBranchElement(parent,
  1934. child.getAttributes());
  1935. }
  1936. }
  1937. else
  1938. newChild = null;
  1939. // Recreate the remaining children (there may be none).
  1940. int kidsToMove = change.parent.getElementCount() -
  1941. change.index;
  1942. Element[] kids;
  1943. int moveStartIndex;
  1944. int kidStartIndex = 1;
  1945. if(newChild == null) {
  1946. // Last part of fracture.
  1947. if(isEndLeaf) {
  1948. kidsToMove--;
  1949. moveStartIndex = change.index + 1;
  1950. }
  1951. else {
  1952. moveStartIndex = change.index;
  1953. }
  1954. kidStartIndex = 0;
  1955. kids = new Element[kidsToMove];
  1956. }
  1957. else {
  1958. if(!isEnd) {
  1959. // Branch.
  1960. kidsToMove++;
  1961. moveStartIndex = change.index;
  1962. }
  1963. else {
  1964. // Last leaf, need to recreate part of it.
  1965. moveStartIndex = change.index + 1;
  1966. }
  1967. kids = new Element[kidsToMove];
  1968. kids[0] = newChild;
  1969. }
  1970. for(int counter = kidStartIndex; counter < kidsToMove;
  1971. counter++) {
  1972. Element toMove =change.parent.getElement(moveStartIndex++);
  1973. kids[counter] = recreateFracturedElement(parent, toMove);
  1974. change.removed.addElement(toMove);
  1975. }
  1976. ((BranchElement)parent).replace(0, 0, kids);
  1977. parent = newChild;
  1978. }
  1979. }
  1980. /**
  1981. * Recreates <code>toDuplicate</code>. This is called when an
  1982. * element needs to be created as the result of an insertion. This
  1983. * will recurse and create all the children. This is similiar to
  1984. * <code>clone</code>, but deteremines the offsets differently.
  1985. */
  1986. Element recreateFracturedElement(Element parent, Element toDuplicate) {
  1987. if(toDuplicate.isLeaf()) {
  1988. return createLeafElement(parent, toDuplicate.getAttributes(),
  1989. Math.max(toDuplicate.getStartOffset(),
  1990. endOffset),
  1991. toDuplicate.getEndOffset());
  1992. }
  1993. // Not a leaf
  1994. Element newParent = createBranchElement(parent, toDuplicate.
  1995. getAttributes());
  1996. int childCount = toDuplicate.getElementCount();
  1997. Element[] newKids = new Element[childCount];
  1998. for(int counter = 0; counter < childCount; counter++) {
  1999. newKids[counter] = recreateFracturedElement(newParent,
  2000. toDuplicate.getElement(counter));
  2001. }
  2002. ((BranchElement)newParent).replace(0, 0, newKids);
  2003. return newParent;
  2004. }
  2005. /**
  2006. * Splits the bottommost leaf in <code>path</code>.
  2007. * This is called from insert when the first element is NOT content.
  2008. */
  2009. void fractureDeepestLeaf(ElementSpec[] specs) {
  2010. // Split the bottommost leaf. It will be recreated elsewhere.
  2011. ElemChanges ec = (ElemChanges) path.peek();
  2012. Element child = ec.parent.getElement(ec.index);
  2013. // Inserts at offset 0 do not need to recreate child (it would
  2014. // have a length of 0!).
  2015. if (offset != 0) {
  2016. Element newChild = createLeafElement(ec.parent,
  2017. child.getAttributes(),
  2018. child.getStartOffset(),
  2019. offset);
  2020. ec.added.addElement(newChild);
  2021. }
  2022. ec.removed.addElement(child);
  2023. if(child.getEndOffset() != endOffset)
  2024. recreateLeafs = true;
  2025. else
  2026. offsetLastIndex = true;
  2027. }
  2028. /**
  2029. * Inserts the first content. This needs to be separate to handle
  2030. * joining.
  2031. */
  2032. void insertFirstContent(ElementSpec[] specs) {
  2033. ElementSpec firstSpec = specs[0];
  2034. ElemChanges ec = (ElemChanges) path.peek();
  2035. Element child = ec.parent.getElement(ec.index);
  2036. int firstEndOffset = offset + firstSpec.getLength();
  2037. boolean isOnlyContent = (specs.length == 1);
  2038. switch(firstSpec.getDirection()) {
  2039. case ElementSpec.JoinPreviousDirection:
  2040. if(child.getEndOffset() != firstEndOffset &&
  2041. !isOnlyContent) {
  2042. // Create the left split part containing new content.
  2043. Element newE = createLeafElement(ec.parent,
  2044. child.getAttributes(), child.getStartOffset(),
  2045. firstEndOffset);
  2046. ec.added.addElement(newE);
  2047. ec.removed.addElement(child);
  2048. // Remainder will be created later.
  2049. if(child.getEndOffset() != endOffset)
  2050. recreateLeafs = true;
  2051. else
  2052. offsetLastIndex = true;
  2053. }
  2054. else {
  2055. offsetLastIndex = true;
  2056. offsetLastIndexOnReplace = true;
  2057. }
  2058. // else Inserted at end, and is total length.
  2059. // Update index incase something added/removed.
  2060. break;
  2061. case ElementSpec.JoinNextDirection:
  2062. if(offset != 0) {
  2063. // Recreate the first element, its offset will have
  2064. // changed.
  2065. Element newE = createLeafElement(ec.parent,
  2066. child.getAttributes(), child.getStartOffset(),
  2067. offset);
  2068. ec.added.addElement(newE);
  2069. // Recreate the second, merge part. We do no checking
  2070. // to see if JoinNextDirection is valid here!
  2071. Element nextChild = ec.parent.getElement(ec.index + 1);
  2072. if(isOnlyContent)
  2073. newE = createLeafElement(ec.parent, nextChild.
  2074. getAttributes(), offset, nextChild.getEndOffset());
  2075. else
  2076. newE = createLeafElement(ec.parent, nextChild.
  2077. getAttributes(), offset, firstEndOffset);
  2078. ec.added.addElement(newE);
  2079. ec.removed.addElement(child);
  2080. ec.removed.addElement(nextChild);
  2081. }
  2082. // else nothin to do.
  2083. // PENDING: if !isOnlyContent could raise here!
  2084. break;
  2085. default:
  2086. // Inserted into middle, need to recreate split left
  2087. // new content, and split right.
  2088. if(child.getStartOffset() != offset) {
  2089. Element newE = createLeafElement(ec.parent,
  2090. child.getAttributes(), child.getStartOffset(),
  2091. offset);
  2092. ec.added.addElement(newE);
  2093. }
  2094. ec.removed.addElement(child);
  2095. // new content
  2096. Element newE = createLeafElement(ec.parent,
  2097. firstSpec.getAttributes(),
  2098. offset, firstEndOffset);
  2099. ec.added.addElement(newE);
  2100. if(child.getEndOffset() != endOffset) {
  2101. // Signals need to recreate right split later.
  2102. recreateLeafs = true;
  2103. }
  2104. else {
  2105. offsetLastIndex = true;
  2106. }
  2107. break;
  2108. }
  2109. }
  2110. Element root;
  2111. transient int pos; // current position
  2112. transient int offset;
  2113. transient int length;
  2114. transient int endOffset;
  2115. transient Vector changes; // Vector<ElemChanges>
  2116. transient Stack path; // Stack<ElemChanges>
  2117. transient boolean insertOp;
  2118. transient boolean recreateLeafs; // For insert.
  2119. /** For insert, path to inserted elements. */
  2120. transient ElemChanges[] insertPath;
  2121. /** Only for insert, set to true when the fracture has been created. */
  2122. transient boolean createdFracture;
  2123. /** Parent that contains the fractured child. */
  2124. transient Element fracturedParent;
  2125. /** Fractured child. */
  2126. transient Element fracturedChild;
  2127. /** Used to indicate when fracturing that the last leaf should be
  2128. * skipped. */
  2129. transient boolean offsetLastIndex;
  2130. /** Used to indicate that the parent of the deepest leaf should
  2131. * offset the index by 1 when adding/removing elements in an
  2132. * insert. */
  2133. transient boolean offsetLastIndexOnReplace;
  2134. /*
  2135. * Internal record used to hold element change specifications
  2136. */
  2137. class ElemChanges {
  2138. ElemChanges(Element parent, int index, boolean isFracture) {
  2139. this.parent = parent;
  2140. this.index = index;
  2141. this.isFracture = isFracture;
  2142. added = new Vector();
  2143. removed = new Vector();
  2144. }
  2145. public String toString() {
  2146. return "added: " + added + "\nremoved: " + removed + "\n";
  2147. }
  2148. Element parent;
  2149. int index;
  2150. Vector added;
  2151. Vector removed;
  2152. boolean isFracture;
  2153. }
  2154. }
  2155. /**
  2156. * An UndoableEdit used to remember AttributeSet changes to an
  2157. * Element.
  2158. */
  2159. public static class AttributeUndoableEdit extends AbstractUndoableEdit {
  2160. public AttributeUndoableEdit(Element element, AttributeSet newAttributes,
  2161. boolean isReplacing) {
  2162. super();
  2163. this.element = element;
  2164. this.newAttributes = newAttributes;
  2165. this.isReplacing = isReplacing;
  2166. // If not replacing, it may be more efficient to only copy the
  2167. // changed values...
  2168. copy = element.getAttributes().copyAttributes();
  2169. }
  2170. /**
  2171. * Redoes a change.
  2172. *
  2173. * @exception CannotRedoException if the change cannot be redone
  2174. */
  2175. public void redo() throws CannotRedoException {
  2176. super.redo();
  2177. MutableAttributeSet as = (MutableAttributeSet)element
  2178. .getAttributes();
  2179. if(isReplacing)
  2180. as.removeAttributes(as);
  2181. as.addAttributes(newAttributes);
  2182. }
  2183. /**
  2184. * Undoes a change.
  2185. *
  2186. * @exception CannotUndoException if the change cannot be undone
  2187. */
  2188. public void undo() throws CannotUndoException {
  2189. super.undo();
  2190. MutableAttributeSet as = (MutableAttributeSet)element.getAttributes();
  2191. as.removeAttributes(as);
  2192. as.addAttributes(copy);
  2193. }
  2194. // AttributeSet containing additional entries, must be non-mutable!
  2195. protected AttributeSet newAttributes;
  2196. // Copy of the AttributeSet the Element contained.
  2197. protected AttributeSet copy;
  2198. // true if all the attributes in the element were removed first.
  2199. protected boolean isReplacing;
  2200. // Efected Element.
  2201. protected Element element;
  2202. }
  2203. /**
  2204. * UndoableEdit for changing the resolve parent of an Element.
  2205. */
  2206. static class StyleChangeUndoableEdit extends AbstractUndoableEdit {
  2207. public StyleChangeUndoableEdit(AbstractElement element,
  2208. Style newStyle) {
  2209. super();
  2210. this.element = element;
  2211. this.newStyle = newStyle;
  2212. oldStyle = element.getResolveParent();
  2213. }
  2214. /**
  2215. * Redoes a change.
  2216. *
  2217. * @exception CannotRedoException if the change cannot be redone
  2218. */
  2219. public void redo() throws CannotRedoException {
  2220. super.redo();
  2221. element.setResolveParent(newStyle);
  2222. }
  2223. /**
  2224. * Undoes a change.
  2225. *
  2226. * @exception CannotUndoException if the change cannot be undone
  2227. */
  2228. public void undo() throws CannotUndoException {
  2229. super.undo();
  2230. element.setResolveParent(oldStyle);
  2231. }
  2232. /** Element to change resolve parent of. */
  2233. protected AbstractElement element;
  2234. /** New style. */
  2235. protected Style newStyle;
  2236. /** Old style, before setting newStyle. */
  2237. protected AttributeSet oldStyle;
  2238. }
  2239. /**
  2240. * Added to all the Styles. When instances of this receive a
  2241. * stateChanged method, styleChanged is invoked.
  2242. */
  2243. class StyleChangeHandler implements ChangeListener {
  2244. public void stateChanged(ChangeEvent e) {
  2245. Object source = e.getSource();
  2246. if (source instanceof Style) {
  2247. styleChanged((Style)source);
  2248. }
  2249. else {
  2250. styleChanged(null);
  2251. }
  2252. }
  2253. }
  2254. /**
  2255. * Added to the StyleContext. When the StyleContext changes, this invokes
  2256. * <code>updateStylesListeningTo</code>.
  2257. */
  2258. class StyleContextChangeHandler implements ChangeListener {
  2259. public void stateChanged(ChangeEvent e) {
  2260. updateStylesListeningTo();
  2261. }
  2262. }
  2263. /**
  2264. * When run this creates a change event for the complete document
  2265. * and fires it.
  2266. */
  2267. class ChangeUpdateRunnable implements Runnable {
  2268. boolean isPending = false;
  2269. public void run() {
  2270. synchronized(this) {
  2271. isPending = false;
  2272. }
  2273. try {
  2274. writeLock();
  2275. DefaultDocumentEvent dde = new DefaultDocumentEvent(0,
  2276. getLength(),
  2277. DocumentEvent.EventType.CHANGE);
  2278. dde.end();
  2279. fireChangedUpdate(dde);
  2280. } finally {
  2281. writeUnlock();
  2282. }
  2283. }
  2284. }
  2285. }