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