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