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