home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 1998 November
/
Chip_1998-11_cd.bin
/
tema
/
Cafe
/
jfc.bin
/
AbstractDocument.java
< prev
next >
Wrap
Text File
|
1998-02-26
|
61KB
|
2,046 lines
/*
* @(#)AbstractDocument.java 1.74 98/02/05
*
* Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
package com.sun.java.swing.text;
import java.util.*;
import java.io.*;
import com.sun.java.swing.undo.*;
import com.sun.java.swing.event.ChangeListener;
import com.sun.java.swing.event.*;
/**
* An implementation of the document interface to serve as a
* basis for implementing various kinds of documents. At this
* level there is very little policy, so there is a corresponding
* increase in difficulty of use.
* <p>
* This class implements a locking mechanism for the document. It
* allows multiple readers or one writer, and writers must wait until
* all observers of the document have been notified of a previous
* change before beginning another mutation to the document. The
* read lock is aquired and released using the <code>render</code>
* method. A write lock is aquired by the methods that mutate the
* document, and are held for the duration of the method call.
* Notification is done on the thread that produced the mutation,
* and the thread has full read access to the document for the
* duration of the notification, but other readers are kept out
* until the notification has finished. The notification is a
* beans event notification which does not allow any further
* mutations until all listeners have been notified.
* <p>
* Any models subclassed from this class and used in conjunction
* with a text component that has a look and feel implementation
* that is derived from DefaultTextUI may be safely updated
* asynchronously. The rendering in DefaultTextUI occurs under
* the protection of the <code>render</code> method, which makes
* rendering safe if it is running on the event thread (which
* happens if using repaint to schedule updates). The code path
* for any DocumentListener implementation must not access the
* component lock if trying to be safe from deadlocks.
* The <cod>repaint</code> and <code>revalidate</code> methods
* on JComponent are safe.
* <p>
* Warning: serialized objects of this class will not be compatible with
* future swing releases. The current serialization support is appropriate
* for short term storage or RMI between Swing1.0 applications. It will
* not be possible to load serialized Swing1.0 objects with future releases
* of Swing. The JDK1.2 release of Swing will be the compatibility
* baseline for the serialized form of Swing objects.
*
* @author Timothy Prinzing
* @version 1.74 02/05/98
*/
public abstract class AbstractDocument implements Document, Serializable {
/**
* Constructs a new AbstractDocument, wrapped around some
* specified content storage mechanism.
*
* @param data the content
*/
protected AbstractDocument(Content data) {
this(data, StyleContext.getDefaultStyleContext());
}
/**
* Constructs a new AbstractDocument, wrapped around some
* specified content storage mechanism.
*
* @param data the content
*/
protected AbstractDocument(Content data, AttributeContext context) {
this.data = data;
this.context = context;
}
/**
* Support for managing a set of properties. Callers
* can use the documentProperties dictionary to annotate the
* document with document-wide properties.
*
* @return a non null Dictionary
* @see #setDocumentProperties
*/
public Dictionary getDocumentProperties() {
if (documentProperties == null) {
documentProperties = new Hashtable(2);
}
return documentProperties;
}
/**
* Replace the document properties dictionary for this document.
*
* @see #getDocumentProperties
*/
public void setDocumentProperties(Dictionary x) {
documentProperties = x;
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireInsertUpdate(DocumentEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).insertUpdate(e);
}
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireChangedUpdate(DocumentEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).changedUpdate(e);
}
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireRemoveUpdate(DocumentEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).removeUpdate(e);
}
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireUndoableEditUpdate(UndoableEditEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==UndoableEditListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((UndoableEditListener)listeners[i+1]).undoableEditHappened(e);
}
}
}
// --- Document methods -----------------------------------------
/**
* This allows the model to be safely rendered in the presence
* of currency, if the model supports being updated asynchronously.
* The given runnable will be executed in a way that allows it
* to safely read the model with no changes while the runnable
* is being executed. The runnable itself may <em>not</em>
* make any mutations.
* <p>
* This is implemented to aquire a read lock for the duration
* of the runnables execution. There may be multiple runnables
* executing at the same time, and all writers will be blocked
* while there are active rendering runnables. If the runnable
* throws an exception, it's lock will be safely released.
* There is no protection against a runnable that never exits,
* which will effectively leave the document locked for it's
* lifetime.
* <p>
* If the given runnable attempts to make any mutations in
* this implementation, a deadlock will occur. There is
* no tracking of individual rendering threads to enable
* detecting this situation, but a subclass could incur
* the overhead of tracking them and throwing an error.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/products/jfc/swingdoc/threads.html">Threads
* and Swing</A> for more information.
*
* @param r the renderer to execute.
*/
public void render(Runnable r) {
try {
readLock();
r.run();
} finally {
readUnlock();
}
}
/**
* Returns the length of the data. This is the number of
* characters of content that represents the users data.
*
* @return the length
* @see Document#getLength
*/
public int getLength() {
return data.length() - 1;
}
/**
* Adds a document listener for notification of any changes.
*
* @param listener the listener
* @see Document#addDocumentListener
*/
public void addDocumentListener(DocumentListener listener) {
listenerList.add(DocumentListener.class, listener);
}
/**
* Removes a document listener.
*
* @param listener the listener
* @see Document#removeDocumentListener
*/
public void removeDocumentListener(DocumentListener listener) {
listenerList.remove(DocumentListener.class, listener);
}
/**
* Adds an undo listener for notification of any changes.
* Undo/Redo operations performed on the UndoableEdit will
* cause the appropriate DocumentEvent to be fired to keep
* the view(s) in sync with the model.
*
* @param listener the listener
* @see Document#addUndoableEditListener
*/
public void addUndoableEditListener(UndoableEditListener listener) {
listenerList.add(UndoableEditListener.class, listener);
}
/**
* Removes an undo listener.
*
* @param listener the listener
* @see Document#removeDocumentListener
*/
public void removeUndoableEditListener(UndoableEditListener listener) {
listenerList.remove(UndoableEditListener.class, listener);
}
/**
* A convenience method for looking up a property value. It is
* equivalent to:
* <pre>
* getDocumentProperties().get(key);
* </pre>
*
* @return the value of this property or null
* @see #getDocumentProperties
*/
public final Object getProperty(Object key) {
return getDocumentProperties().get(key);
}
/**
* A convenience method for storing up a property value. It is
* equivalent to:
* <pre>
* getDocumentProperties().put(key, value);
* </pre>
* If value is null this method will remove the property
*
* @see #getDocumentProperties
*/
public final void putProperty(Object key, Object value) {
if (value != null) {
getDocumentProperties().put(key, value);
} else
getDocumentProperties().remove(key);
}
/**
* Removes some content from the document.
* Removing content causes a write lock to be held while the
* actual changes are taking place. Observers are notified
* of the change on the thread that called this method.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/products/jfc/swingdoc/threads.html">Threads
* and Swing</A> for more information.
*
* @param offs the starting offset
* @param len the number of characters to remove
* @exception BadLocationException the given remove position is not a valid
* position within the document
* @see Document#remove
*/
public void remove(int offs, int len) throws BadLocationException {
if (len > 0) {
try {
writeLock();
DefaultDocumentEvent chng =
new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE);
removeUpdate(chng);
UndoableEdit u = data.remove(offs, len);
if (u != null) {
chng.addEdit(u);
}
// Mark the edit as done.
chng.end();
fireRemoveUpdate(chng);
// only fire undo if Content implementation supports it
if (u != null) {
fireUndoableEditUpdate(new UndoableEditEvent(this, chng));
}
} finally {
writeUnlock();
}
}
}
/**
* Inserts some content into the document.
* Inserting content causes a write lock to be held while the
* actual changes are taking place, followed by notification
* to the observers on the thread that grabbed the write lock.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/products/jfc/swingdoc/threads.html">Threads
* and Swing</A> for more information.
*
* @param offs the starting offset
* @param str the string to insert
* @param a the attributes for the inserted content
* @exception BadLocationException the given insert position is not a valid
* position within the document
* @see Document#insertString
*/
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if ((str == null) || (str.length() == 0)) {
return;
}
try {
writeLock();
UndoableEdit u = data.insertString(offs, str);
DefaultDocumentEvent e =
new DefaultDocumentEvent(offs, str.length(), DocumentEvent.EventType.INSERT);
if (u != null) {
e.addEdit(u);
}
insertUpdate(e, a);
// Mark the edit as done.
e.end();
fireInsertUpdate(e);
// only fire undo if Content implementation supports it
if (u != null) {
fireUndoableEditUpdate(new UndoableEditEvent(this, e));
}
} finally {
writeUnlock();
}
}
/**
* Gets a sequence of text from the document.
*
* @param offset the starting offset
* @param length the number of characters to retrieve
* @return the text
* @exception BadLocationException the range given includes a position
* that is not a valid position within the document
* @see Document#getText
*/
public String getText(int offset, int length) throws BadLocationException {
String str = data.getString(offset, length);
return str;
}
/**
* Gets some text from the document potentially without
* making a copy. The character array returned in the
* given <code>Segment</code> should never be mutated.
* This kind of access to the characters of the document
* is provided to help make the rendering potentially more
* efficient. The caller should make no assumptions about
* the lifetime of the returned character array, which
* should be copied if needed beyond the use for rendering.
*
* @param offset the starting offset
* @param length the number of characters to retrieve
* @param txt the Segment object to retrieve the text into
* @exception BadLocationException the range given includes a position
* that is not a valid position within the document
*/
public void getText(int offset, int length, Segment txt) throws BadLocationException {
data.getChars(offset, length, txt);
}
/**
* Returns a position that will track change as the document
* is altered.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/products/jfc/swingdoc/threads.html">Threads
* and Swing</A> for more information.
*
* @param offs the position
* @return the position
* @exception BadLocationException if the given position does not
* represent a valid location in the associated document
* @see Document#createPosition
*/
public synchronized Position createPosition(int offs) throws BadLocationException {
return data.createPosition(offs);
}
/**
* Returns a position that represents the start of the document. The
* position returned can be counted on to track change and stay
* located at the beginning of the document.
*
* @return the position
*/
public final Position getStartPosition() {
Position p;
try {
p = createPosition(0);
} catch (BadLocationException bl) {
p = null;
}
return p;
}
/**
* Returns a position that represents the end of the document. The
* position returned can be counted on to track change and stay
* located at the end of the document.
*
* @return the position
*/
public final Position getEndPosition() {
Position p;
try {
p = createPosition(data.length());
} catch (BadLocationException bl) {
p = null;
}
return p;
}
/**
* Gets all root elements defined. Typically, there
* will only be one so the default implementation
* is to return the default root element.
*
* @return the root element
*/
public Element[] getRootElements() {
Element[] elems = new Element[1];
elems[0] = getDefaultRootElement();
return elems;
}
/**
* Returns the root element that views should be based upon
* unless some other mechanism for assigning views to element
* structures is provided.
*
* @return the root element
* @see Document#getDefaultRootElement
*/
public abstract Element getDefaultRootElement();
// ---- local methods -----------------------------------------
/**
* Fetches the context for managing attributes. This
* method effectively establishes the strategy used
* for compressing AttributeSet information.
*
* @return the context
*/
protected final AttributeContext getAttributeContext() {
return context;
}
/**
* Updates document structure as a result of text insertion. This
* will happen within a write lock. If a subclass of
* this class reimplements this method, it should delegate to the
* superclass as well.
*
* @param chng a description of the change
* @param attr the attributes for the change
*/
protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) {
}
/**
* Updates any document structure as a result of text removal.
* This will happen within a write lock. If a subclass
* of this class reimplements this method, it should delegate to the
* superclass as well.
*
* @param chng a description of the change
*/
protected void removeUpdate(DefaultDocumentEvent chng) {
}
/**
* Gives a diagnostic dump.
*
* @param out the output stream
*/
public void dump(PrintStream out) {
Element root = getDefaultRootElement();
if (root instanceof AbstractElement) {
((AbstractElement)root).dump(out, 0);
}
}
/**
* Gets the content for the document.
*
* @return the content
*/
protected final Content getContent() {
return data;
}
/**
* Creates a document leaf element.
* Hook through which elements are created to represent the
* document structure. Because this implementation keeps
* structure and content seperate, elements grow automatically
* when content is extended so splits of existing elements
* follow. The document itself gets to decide how to generate
* elements to give flexibility in the type of elements used.
*
* @param parent the parent element
* @param a the attributes for the element
* @param p0 the beginning of the range
* @param p1 the end of the range
* @return the new element
*/
protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1) {
return new LeafElement(parent, a, p0, p1);
}
/**
* Creates a document branch element, that can contain other elements.
*
* @param parent the parent element
* @param a the attributes
* @return the element
*/
protected Element createBranchElement(Element parent, AttributeSet a) {
return new BranchElement(parent, a);
}
// --- Document locking ----------------------------------
/**
* Fetches the current writing thread if there is one.
* This can be used to distinguish whether a method is
* being called as part of an existing modification or
* if a lock needs to be acquired and a new transaction
* started.
*
* @returns the thread actively modifying the document
* or null if there are no modifications in progress
*/
protected synchronized final Thread getCurrentWriter() {
return currWriter;
}
/**
* Acquires a lock to begin mutating the document this lock
* protects. There can be no notification of changes or
* reading going on in order to gain the lock.
*/
protected synchronized final void writeLock() {
try {
while ((numReaders > 0) || (currWriter != null)) {
wait();
}
currWriter = Thread.currentThread();
} catch (InterruptedException e) {
// safe to let this pass... write lock not
// held if the thread lands here.
}
}
/**
* Releases the write lock held because the write
* operation is finished. This allows either a new
* writer or readers to aquire a lock.
*/
protected synchronized final void writeUnlock() {
if ((numReaders > 0) || (currWriter == null)) {
throw new StateInvariantError(BAD_LOCK_STATE);
}
currWriter = null;
notify();
}
/**
* Acquires a lock to begin reading some state from the
* document. There can be multiple readers at the same time
* and reading can occur while notification to the listeners
* is going on, but writing blocks the readers.
*/
protected synchronized final void readLock() {
try {
while (currWriter != null) {
wait();
}
numReaders += 1;
} catch (InterruptedException e) {
// safe to let this pass... read lock not
// held if the thread lands here.
}
}
/**
* Does a read unlock.
* One of the readers is done. If there are no more readers
* then writing can begin again.
*/
protected synchronized final void readUnlock() {
if (numReaders <= 0) {
throw new StateInvariantError(BAD_LOCK_STATE);
}
numReaders -= 1;
notify();
}
// --- serialization ---------------------------------------------
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
listenerList = new EventListenerList();
}
// ----- member variables ------------------------------------------
private transient int numReaders;
private transient Thread currWriter;
/**
* Storage for document-wide properties.
*/
private Dictionary documentProperties = null;
/**
* The event listener list for the document.
*/
protected EventListenerList listenerList = new EventListenerList();
/**
* Where the text is actually stored, and a set of marks
* that track change as the document is edited are managed.
*/
private Content data;
/**
* Factory for the attributes. This is the strategy for
* attribute compression and control of the lifetime of
* a set of attributes as a collection. This may be shared
* with other documents.
*/
private AttributeContext context;
private static final String BAD_LOCK_STATE = "document lock failure";
/**
* Error message to indicate a bad location.
*/
protected static final String BAD_LOCATION = "document location failure";
/**
* Name of elements used to represent paragraphs
*/
public static final String ParagraphElementName = "paragraph";
/**
* Name of elements used to represent content
*/
public static final String ContentElementName = "content";
/**
* Name of elements used to hold sections (lines/paragraphs).
*/
public static final String SectionElementName = "section";
/**
* Name of the attribute used to specify element
* names.
*/
public static final String ElementNameAttribute = "$ename";
/**
* Interface to describe a sequence of character content that
* can be edited. Implementations may or may not support a
* history mechanism which will be reflected by whether or not
* mutations return an UndoableEdit implementation.
* @see AbstractDocument
*/
public interface Content {
/**
* Creates a position within the content that will
* track change as the content is mutated.
*
* @param offset the offset in the content
* @return a Position
* @exception BadLocationException for an invalid offset
*/
public Position createPosition(int offset) throws BadLocationException;
/**
* Current length of the sequence of character content.
*
* @return the length
*/
public int length();
/**
* Inserts a string of characters into the sequence.
*
* @param where Offset into the sequence to make the insertion.
* @param str String to insert.
* @return If the implementation supports a history mechansim,
* a reference to an Edit implementation will be returned,
* otherwise null.
* @exception BadLocationException Thrown if the area covered by
* the arguments is not contained in the character sequence.
*/
public UndoableEdit insertString(int where, String str) throws BadLocationException;
/**
* Removes some portion of the sequence.
*
* @param where The offset into the sequence to make the insertion.
* @param nitems The number of items in the sequence to remove.
* @return If the implementation supports a history mechansim,
* a reference to an Edit implementation will be returned,
* otherwise null.
* @exception BadLocationException Thrown if the area covered by
* the arguments is not contained in the character sequence.
*/
public UndoableEdit remove(int where, int nitems) throws BadLocationException;
/**
* Fetches a string of characters contained in the sequence.
*
* @param where Offset into the sequence to fetch.
* @param len number of characters to copy.
* @return the string
* @exception BadLocationException Thrown if the area covered by
* the arguments is not contained in the character sequence.
*/
public String getString(int where, int len) throws BadLocationException;
/**
* Gets a sequence of characters and copies them into a Segment.
*
* @param where the starting offset
* @param len the number of characters
* @param txt the target location to copy into
* @exception BadLocationException Thrown if the area covered by
* the arguments is not contained in the character sequence.
*/
public void getChars(int where, int len, Segment txt) throws BadLocationException;
}
/**
* An interface that can be used to allow MutableAttributeSet
* implementations to use pluggable attribute compression
* techniques. Each mutation of the attribute set can be
* used to exchange a previous AttributeSet instance with
* another, preserving the possibility of the AttributeSet
* remaining immutable. An implementation is provided by
* the StyleContext class.
*
* The Element implementations provided by this class use
* this interface to provide their MutableAttributeSet
* implementations, so that different AttributeSet compression
* techniques can be employed. The method
* <code>getAttributeContext</code> should be implemented to
* return the object responsible for implementing the desired
* compression technique.
*
* @see StyleContext
*/
public interface AttributeContext {
/**
* Adds an attribute to the given set, and returns
* the new representative set.
*
* @param old the old attribute set
* @param name the attribute name
* @param value the attribute value
* @return the updated attribute set
* @see MutableAttributeSet#addAttribute
*/
public AttributeSet addAttribute(AttributeSet old, Object name, Object value);
/**
* Adds a set of attributes to the element.
*
* @param old the old attribute set
* @param attr the attributes to add
* @return the updated attribute set
* @see MutableAttributeSet#addAttribute
*/
public AttributeSet addAttributes(AttributeSet old, AttributeSet attr);
/**
* Removes an attribute from the set.
*
* @param old the old attribute set
* @param name the attribute name
* @return the updated attribute set
* @see MutableAttributeSet#removeAttribute
*/
public AttributeSet removeAttribute(AttributeSet old, Object name);
/**
* Removes a set of attributes for the element.
*
* @param old the old attribute set
* @param names the attribute names
* @return the updated attribute set
* @see MutableAttributeSet#removeAttributes
*/
public AttributeSet removeAttributes(AttributeSet old, Enumeration names);
/**
* Removes a set of attributes for the element.
*
* @param old the old attribute set
* @param attrs the attributes
* @return the updated attribute set
* @see MutableAttributeSet#removeAttributes
*/
public AttributeSet removeAttributes(AttributeSet old, AttributeSet attrs);
/**
* Fetches an empty AttributeSet.
*
* @return the attribute set
*/
public AttributeSet getEmptySet();
/**
* Reclaims an attribute set.
* This is a way for a MutableAttributeSet to mark that it no
* longer need a particular immutable set. This is only necessary
* in 1.1 where there are no weak references. A 1.1 implementation
* would call this in its finalize method.
*
* @param a the attribute set to reclaim
*/
public void reclaim(AttributeSet a);
}
/**
* Implements the abstract part of an element. By default elements
* support attributes by having a field that represents the immutable
* part of the current attribute set for the element. The element itself
* implements MutableAttributeSet which can be used to modify the set
* by fetching a new immutable set. The immutable sets are provided
* by the AttributeContext associated with the document.
* <p>
* Warning: serialized objects of this class will not be compatible with
* future swing releases. The current serialization support is appropriate
* for short term storage or RMI between Swing1.0 applications. It will
* not be possible to load serialized Swing1.0 objects with future releases
* of Swing. The JDK1.2 release of Swing will be the compatibility
* baseline for the serialized form of Swing objects.
*/
public abstract class AbstractElement implements Element, MutableAttributeSet, Serializable {
/**
* Creates a new AbstractElement.
*
* @param parent the parent element
* @param a the attributes for the element
*/
public AbstractElement(Element parent, AttributeSet a) {
attributes = (a != null) ? a.copyAttributes() :
getAttributeContext().getEmptySet();
this.parent = parent;
}
private final void indent(PrintStream out, int n) {
for (int i = 0; i < n; i++) {
out.print(" ");
}
}
/**
* Dumps a debugging representation of the element hierarchy.
*
* @param out the output stream
* @param indentAmount the indentation level
*/
public void dump(PrintStream out, int indentAmount) {
indent(out, indentAmount);
if (getName() == null) {
out.print("<??");
} else {
out.print("<" + getName());
}
if (getAttributeCount() > 0) {
out.println("");
// dump the attributes
Enumeration names = attributes.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
indent(out, indentAmount + 1);
out.println(name + "=" + getAttribute(name));
}
indent(out, indentAmount);
}
out.println(">");
if (isLeaf()) {
indent(out, indentAmount+1);
out.print("[" + getStartOffset() + "," + getEndOffset() + "]");
Content c = getContent();
try {
String contentStr = c.getString(getStartOffset(),
getEndOffset() - getStartOffset()).trim();
if (contentStr.length() > 40) {
contentStr = contentStr.substring(0, 40) + "...";
}
out.println(contentStr);
} catch (BadLocationException e) {
;
}
} else {
int n = getElementCount();
for (int i = 0; i < n; i++) {
AbstractElement e = (AbstractElement) getElement(i);
e.dump(out, indentAmount+1);
}
}
}
// --- Object methods ---------------------------
/**
* Finalizes an AbstractElement.
*/
protected void finalize() throws Throwable {
AttributeContext context = getAttributeContext();
context.reclaim(attributes);
}
// --- AttributeSet ----------------------------
// delegated to the immutable field "attributes"
/**
* Gets the number of attributes that are defined.
*
* @return the number of attributes
* @see AttributeSet#getAttributeCount
*/
public int getAttributeCount() {
return attributes.getAttributeCount();
}
/**
* Checks whether a given attribute is defined.
*
* @param attrName the attribute name
* @return true if the attribute is defined
* @see AttributeSet#isDefined
*/
public boolean isDefined(Object attrName) {
return attributes.isDefined(attrName);
}
/**
* Checks whether two attribute sets are equal.
*
* @param attr the attribute set to check against
* @return true if the same
* @see AttributeSet#isEqual
*/
public boolean isEqual(AttributeSet attr) {
return attributes.isEqual(attr);
}
/**
* Copies a set of attributes.
*
* @return the copy
* @see AttributeSet#copyAttributes
*/
public AttributeSet copyAttributes() {
return attributes;
}
/**
* Gets the value of an attribute.
*
* @param attrName the attribute name
* @return the attribute value
* @see AttributeSet#getAttribute
*/
public Object getAttribute(Object attrName) {
Object value = attributes.getAttribute(attrName);
if (value == null) {
AttributeSet parent = getResolveParent();
if (parent != null)
value = parent.getAttribute(attrName);
}
return value;
}
/**
* Gets the names of all attributes.
*
* @return the attribute names
* @see AttributeSet#getAttributeNames
*/
public Enumeration getAttributeNames() {
return attributes.getAttributeNames();
}
/**
* Checks whether a given attribute name/value is defined.
*
* @param name the attribute name
* @param value the attribute value
* @return true if the name/value is defined
* @see AttributeSet#containsAttribute
*/
public boolean containsAttribute(Object name, Object value) {
return attributes.containsAttribute(name, value);
}
/**
* Checks whether the element contains all the attributes.
*
* @param attrs the attributes to check
* @return true if the element contains all the attributes
* @see AttributeSet#containsAttributes
*/
public boolean containsAttributes(AttributeSet attrs) {
return attributes.containsAttributes(attrs);
}
/**
* Gets the resolving parent.
* If not overriden, the resolving parent defaults to
* the parent element.
*
* @return the attributes from the parent
* @see AttributeSet#getResolveParent
*/
public AttributeSet getResolveParent() {
AttributeSet a = attributes.getResolveParent();
if ((a == null) && (parent != null)) {
a = parent.getAttributes();
}
return a;
}
// --- MutableAttributeSet ----------------------------------
// should fetch a new immutable record for the field
// "attributes".
/**
* Adds an attribute to the element.
*
* @param name the attribute name
* @param value the attribute value
* @see MutableAttributeSet#addAttribute
*/
public void addAttribute(Object name, Object value) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
attributes = context.addAttribute(attributes, name, value);
}
/**
* Adds a set of attributes to the element.
*
* @param attr the attributes to add
* @see MutableAttributeSet#addAttribute
*/
public void addAttributes(AttributeSet attr) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
attributes = context.addAttributes(attributes, attr);
}
/**
* Removes an attribute from the set.
*
* @param name the attribute name
* @see MutableAttributeSet#removeAttribute
*/
public void removeAttribute(Object name) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
attributes = context.removeAttribute(attributes, name);
}
/**
* Removes a set of attributes for the element.
*
* @param names the attribute names
* @see MutableAttributeSet#removeAttributes
*/
public void removeAttributes(Enumeration names) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
attributes = context.removeAttributes(attributes, names);
}
/**
* Removes a set of attributes for the element.
*
* @param attrs the attributes
* @see MutableAttributeSet#removeAttributes
*/
public void removeAttributes(AttributeSet attrs) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
if (attrs == this) {
attributes = context.getEmptySet();
} else {
attributes = context.removeAttributes(attributes, attrs);
}
}
/**
* Sets the resolving parent.
*
* @param parent the parent
* @see MutableAttributeSet#setResolveParent
*/
public void setResolveParent(AttributeSet parent) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
if (parent != null) {
attributes =
context.addAttribute(attributes, StyleConstants.ResolveAttribute,
parent);
} else {
attributes =
context.removeAttribute(attributes, StyleConstants.ResolveAttribute);
}
}
private final void checkForIllegalCast() {
Thread t = getCurrentWriter();
if ((t == null) || (t != Thread.currentThread())) {
throw new StateInvariantError("Illegal cast to MutableAttributeSet");
}
}
// --- Element methods -------------------------------------
/**
* Retrieves the underlying model.
*
* @return the model
*/
public Document getDocument() {
return AbstractDocument.this;
}
/**
* Gets the parent of the element.
*
* @return the parent
*/
public Element getParentElement() {
return parent;
}
/**
* Gets the attributes for the element.
*
* @return the attribute set
*/
public AttributeSet getAttributes() {
return this;
}
/**
* Gets the name of the element.
*
* @return the name
*/
public String getName() {
if (attributes.isDefined(ElementNameAttribute)) {
return (String) attributes.getAttribute(ElementNameAttribute);
}
return null;
}
/**
* Gets the starting offset in the model for the element.
*
* @return the offset
*/
public abstract int getStartOffset();
/**
* Gets the ending offset in the model for the element.
*
* @return the offset
*/
public abstract int getEndOffset();
/**
* Gets a child element.
*
* @param index the child index
* @return the child element
*/
public abstract Element getElement(int index);
/**
* Gets the number of children for the element.
*
* @return the number of children
*/
public abstract int getElementCount();
/**
* Gets the child element index closest to the given model offset.
*
* @param offset the offset
* @return the element index
*/
public abstract int getElementIndex(int offset);
/**
* Checks whether the element is a leaf.
*
* @return true if a leaf
*/
public abstract boolean isLeaf();
// --- serialization ---------------------------------------------
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
StyleContext.writeAttributeSet(s, attributes);
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
MutableAttributeSet attr = new SimpleAttributeSet();
StyleContext.readAttributeSet(s, attr);
AttributeContext context = getAttributeContext();
attributes = context.addAttributes(SimpleAttributeSet.EMPTY, attr);
}
// ---- variables -----------------------------------------------------
private Element parent;
private transient AttributeSet attributes;
}
/**
* Implements a composite element that contains other elements.
* <p>
* Warning: serialized objects of this class will not be compatible with
* future swing releases. The current serialization support is appropriate
* for short term storage or RMI between Swing1.0 applications. It will
* not be possible to load serialized Swing1.0 objects with future releases
* of Swing. The JDK1.2 release of Swing will be the compatibility
* baseline for the serialized form of Swing objects.
*/
public class BranchElement extends AbstractElement {
/**
* Constructs a composite element that initially contains
* no children.
*
* @param parent The parent element
* @param a the attributes for the element
*/
public BranchElement(Element parent, AttributeSet a) {
super(parent, a);
children = new AbstractElement[1];
nchildren = 0;
lastIndex = -1;
}
/**
* Gets the child element that contains
* the given position.
*
* @param pos the position
* @return the element
*/
public Element positionToElement(int pos) {
int index = getElementIndex(pos);
Element child = children[index];
int p0 = child.getStartOffset();
int p1 = child.getEndOffset();
if ((pos >= p0) && (pos < p1)) {
return child;
}
return null;
}
/**
* Replaces content with a new set of elements.
*
* @param offset the starting offset
* @param length the length to replace
* @param elems the new elements
*/
public void replace(int offset, int length, Element[] elems) {
int delta = elems.length - length;
int src = offset + length;
int nmove = nchildren - src;
int dest = src + delta;
if ((nchildren + delta) >= children.length) {
// need to grow the array
int newLength = Math.max(2*children.length, nchildren + delta);
AbstractElement[] newChildren = new AbstractElement[newLength];
System.arraycopy(children, 0, newChildren, 0, offset);
System.arraycopy(elems, 0, newChildren, offset, elems.length);
System.arraycopy(children, src, newChildren, dest, nmove);
children = newChildren;
} else {
// patch the existing array
System.arraycopy(children, src, children, dest, nmove);
System.arraycopy(elems, 0, children, offset, elems.length);
}
nchildren = nchildren + delta;
}
/**
* Converts the element to a string.
*
* @return the string
*/
public String toString() {
return "BranchElement(" + getName() + ") " + getStartOffset() + "," +
getEndOffset() + "\n";
}
// --- Element methods -----------------------------------
/**
* Gets the element name.
*
* @return the element name
*/
public String getName() {
String nm = super.getName();
if (nm == null) {
nm = ParagraphElementName;
}
return nm;
}
/**
* Gets the starting offset in the model for the element.
*
* @return the offset
*/
public int getStartOffset() {
return children[0].getStartOffset();
}
/**
* Gets the ending offset in the model for the element.
*
* @return the offset
*/
public int getEndOffset() {
Element child = children[nchildren - 1];
return child.getEndOffset();
}
/**
* Gets a child element.
*
* @param index the child index
* @return the child element
*/
public Element getElement(int index) {
if (index < nchildren) {
return children[index];
}
return null;
}
/**
* Gets the number of children for the element.
*
* @return the number of children
*/
public int getElementCount() {
return nchildren;
}
/**
* Gets the child element index closest to the given model offset.
*
* @param offset the offset
* @return the element index
*/
public int getElementIndex(int offset) {
int index;
int lower = 0;
int upper = nchildren - 1;
int mid = 0;
int p0 = getStartOffset();
int p1;
if (nchildren == 0) {
return 0;
}
if (offset >= getEndOffset()) {
return nchildren - 1;
}
// see if the last index can be used.
if ((lastIndex >= lower) && (lastIndex <= upper)) {
Element lastHit = children[lastIndex];
p0 = lastHit.getStartOffset();
p1 = lastHit.getEndOffset();
if ((offset >= p0) && (offset < p1)) {
return lastIndex;
}
// last index wasn't a hit, but it does give useful info about
// where a hit (if any) would be.
if (offset < p0) {
upper = lastIndex;
} else {
lower = lastIndex;
}
}
while (lower <= upper) {
mid = lower + ((upper - lower) / 2);
Element elem = children[mid];
p0 = elem.getStartOffset();
p1 = elem.getEndOffset();
if ((offset >= p0) && (offset < p1)) {
// found the location
index = mid;
lastIndex = index;
return index;
} else if (offset < p0) {
upper = mid - 1;
} else {
lower = mid + 1;
}
}
// didn't find it, but we indicate the index of where it would belong
if (offset < p0) {
index = mid;
} else {
index = mid + 1;
}
lastIndex = index;
return index;
}
/**
* Checks whether the element is a leaf.
*
* @return true if a leaf
*/
public boolean isLeaf() {
return false;
}
// ------ members ----------------------------------------------
private AbstractElement[] children;
private int nchildren;
private int lastIndex;
}
/**
* Implements an element that directly represents content of
* some kind.
* <p>
* Warning: serialized objects of this class will not be compatible with
* future swing releases. The current serialization support is appropriate
* for short term storage or RMI between Swing1.0 applications. It will
* not be possible to load serialized Swing1.0 objects with future releases
* of Swing. The JDK1.2 release of Swing will be the compatibility
* baseline for the serialized form of Swing objects.
*
* @see Element
*/
public class LeafElement extends AbstractElement {
/**
* Constructs an element that represents content within the
* document (has no children).
*
* @param parent The parent element
* @param a The element attributes
* @param offs0 The start offset
* @param offs1 The end offset
*/
public LeafElement(Element parent, AttributeSet a, int offs0, int offs1) {
super(parent, a);
try {
p0 = createPosition(offs0);
p1 = createPosition(offs1);
} catch (BadLocationException e) {
p0 = null;
p1 = null;
throw new StateInvariantError("Can't create Position references");
}
}
/**
* Converts the element to a string.
*
* @return the string
*/
public String toString() {
return "LeafElement(" + getName() + ") " + p0 + "," + p1 + "\n";
}
// --- Element methods ---------------------------------------------
/**
* Gets the starting offset in the model for the element.
*
* @return the offset
*/
public int getStartOffset() {
return p0.getOffset();
}
/**
* Gets the ending offset in the model for the element.
*
* @return the offset
*/
public int getEndOffset() {
return p1.getOffset();
}
/**
* Gets the element name.
*
* @return the name
*/
public String getName() {
String nm = super.getName();
if (nm == null) {
nm = ContentElementName;
}
return nm;
}
/**
* Gets the child element index closest to the given model offset.
*
* @param pos the offset
* @return the element index
*/
public int getElementIndex(int pos) {
return -1;
}
/**
* Gets a child element.
*
* @param index the child index
* @return the child element
*/
public Element getElement(int index) {
return null;
}
/**
* Returns the number of child elements.
*
* @return the number of children
*/
public int getElementCount() {
return 0;
}
/**
* Checks whether the element is a leaf.
*
* @return true if a leaf
*/
public boolean isLeaf() {
return true;
}
// --- serialization ---------------------------------------------
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(p0.getOffset());
s.writeInt(p1.getOffset());
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
// set the range with positions that track change
int off0 = s.readInt();
int off1 = s.readInt();
try {
p0 = createPosition(off0);
p1 = createPosition(off1);
} catch (BadLocationException e) {
p0 = null;
p1 = null;
throw new IOException("Can't restore Position references");
}
}
// ---- members -----------------------------------------------------
private transient Position p0;
private transient Position p1;
}
/**
* Stores document changes as the document is being
* modified. Can subsequently be used for change notification
* when done with the document modification transaction.
* This is used by the AbstractDocument class and its extensions
* for broadcasting change information to the document listeners.
*/
public class DefaultDocumentEvent extends CompoundEdit implements DocumentEvent {
/**
* Constructs a change record.
*
* @param doc document that is being changed
* @param offs the offset into the document of the change
* @param len the length of the change
* @param type the type of event.
*/
public DefaultDocumentEvent(int offs, int len, DocumentEvent.EventType type) {
super();
offset = offs;
length = len;
this.type = type;
}
/**
* Returns a string description of the change event.
*
* @return a string
*/
public String toString() {
return edits.toString();
}
// --- CompoundEdit methods --------------------------
/**
* Adds a document edit. If the number of edits crosses
* a threshold, this switches on a hashtable lookup for
* ElementChange implementations since access of these
* needs to be relatively quick.
*
* @param anEdit a document edit record
* @return ???
*/
public boolean addEdit(UndoableEdit anEdit) {
// if the number of changes gets too great, start using
// a hashtable for to locate the change for a given element.
if ((changeLookup == null) && (edits.size() > 10)) {
changeLookup = new Hashtable();
int n = edits.size();
for (int i = 0; i < n; i++) {
Object o = edits.elementAt(i);
if (o instanceof DocumentEvent.ElementChange) {
DocumentEvent.ElementChange ec = (DocumentEvent.ElementChange) o;
changeLookup.put(ec.getElement(), ec);
}
}
}
// if we have a hashtable... add the entry if it's
// an ElementChange.
if ((changeLookup != null) && (anEdit instanceof DocumentEvent.ElementChange)) {
DocumentEvent.ElementChange ec = (DocumentEvent.ElementChange) anEdit;
changeLookup.put(ec.getElement(), ec);
}
return super.addEdit(anEdit);
}
/**
* Redoes a change.
*
* @exception CannotRedoException if the change cannot be redone
*/
public void redo() throws CannotRedoException {
writeLock();
try {
// change the state
super.redo();
// fire a DocumentEvent to notify the view(s)
if (type == DocumentEvent.EventType.INSERT) {
fireInsertUpdate(this);
} else if (type == DocumentEvent.EventType.REMOVE) {
fireRemoveUpdate(this);
} else {
fireChangedUpdate(this);
}
} finally {
writeUnlock();
}
}
/**
* Undoes a change.
*
* @exception CannotUndoException if the change cannot be undone
*/
public void undo() throws CannotUndoException {
writeLock();
try {
// change the state
super.undo();
// fire a DocumentEvent to notify the view(s)
if (type == DocumentEvent.EventType.REMOVE) {
fireInsertUpdate(this);
} else if (type == DocumentEvent.EventType.INSERT) {
fireRemoveUpdate(this);
} else {
fireChangedUpdate(this);
}
} finally {
writeUnlock();
}
}
/**
* DefaultDocument events are significant. If you wish to aggregate
* DefaultDocumentEvents to present them as a single edit to the user
* place them into a CompoundEdit.
*/
public boolean isSignificant() {
return true;
}
/**
* Provide a localized, human readable description of this edit
* suitable for use in, say, a change log.
*/
public String getPresentationName() {
DocumentEvent.EventType type = getType();
if(type == DocumentEvent.EventType.INSERT)
return "addition";
if(type == DocumentEvent.EventType.REMOVE)
return "deletion";
return "style change";
}
/**
* Provide a localized, human readable description of the undoable
* form of this edit, e.g. for use as an Undo menu item. Typically
* derived from getDescription();
*/
public String getUndoPresentationName() {
return "Undo " + getPresentationName();
}
/**
* Provide a localized, human readable description of the redoable
* form of this edit, e.g. for use as a Redo menu item. Typically
* derived from getPresentationName();
*/
public String getRedoPresentationName() {
return "Redo " + getPresentationName();
}
// --- DocumentEvent methods --------------------------
/**
* Returns the type of event
* @see DocumentEvent#getType
*/
public DocumentEvent.EventType getType() {
return type;
}
/**
* Returns the offset within the document of the start of the change.
*
* @return the offset
* @see DocumentEvent#getOffset
*/
public int getOffset() {
return offset;
}
/**
* Returns the length of the change.
*
* @return the length
* @see DocumentEvent#getLength
*/
public int getLength() {
return length;
}
/**
* Gets the document that sourced the change event.
*
* @return the document
* @see DocumentEvent#getDocument
*/
public Document getDocument() {
return AbstractDocument.this;
}
/**
* Gets the changes for an element.
*
* @param elem the element
* @return the changes
*/
public DocumentEvent.ElementChange getChange(Element elem) {
if (changeLookup != null) {
return (DocumentEvent.ElementChange) changeLookup.get(elem);
}
int n = edits.size();
for (int i = 0; i < n; i++) {
Object o = edits.elementAt(i);
if (o instanceof DocumentEvent.ElementChange) {
DocumentEvent.ElementChange c = (DocumentEvent.ElementChange) o;
if (c.getElement() == elem) {
return c;
}
}
}
return null;
}
// --- member variables ------------------------------------
private int offset;
private int length;
private Hashtable changeLookup;
private DocumentEvent.EventType type;
}
/**
* An implementation of ElementChange that can be added to the document
* event.
*/
public static class ElementEdit extends AbstractUndoableEdit implements DocumentEvent.ElementChange {
/**
* Constructs an edit record. This does not modify the element
* so it can safely be used to <em>catch up</em> a view to the
* current model state for views that just attached to a model.
*
* @param e the element
* @param index the index into the model
* @param removed a set of elements that were removed
* @param added a set of elements that were added
*/
public ElementEdit(Element e, int index, Element[] removed, Element[] added) {
super();
this.e = e;
this.index = index;
this.removed = removed;
this.added = added;
}
/**
* Returns the underlying element.
*
* @return the element
*/
public Element getElement() {
return e;
}
/**
* Returns the index into the list of elements.
*
* @return the index
*/
public int getIndex() {
return index;
}
/**
* Gets a list of children that were removed.
*
* @return the list
*/
public Element[] getChildrenRemoved() {
return removed;
}
/**
* Gets a list of children that were added.
*
* @return the list
*/
public Element[] getChildrenAdded() {
return added;
}
/**
* Redoes a change.
*
* @exception CannotRedoException if the change cannot be redone
*/
public void redo() throws CannotRedoException {
super.redo();
// Since this event will be reused, switch around added/removed.
Element[] tmp = removed;
removed = added;
added = tmp;
// PENDING(prinz) need MutableElement interface, canRedo() should check
((AbstractDocument.BranchElement)e).replace(index, removed.length, added);
}
/**
* Undoes a change.
*
* @exception CannotUndoException if the change cannot be undone
*/
public void undo() throws CannotUndoException {
super.undo();
// PENDING(prinz) need MutableElement interface, canUndo() should check
((AbstractDocument.BranchElement)e).replace(index, added.length, removed);
// Since this event will be reused, switch around added/removed.
Element[] tmp = removed;
removed = added;
added = tmp;
}
private Element e;
private int index;
private Element[] removed;
private Element[] added;
}
}