|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object javax.swing.text.AbstractDocument
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.
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 acquired and released using the render
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.
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 BasicTextUI may be safely updated
asynchronously, because all access to the View hierarchy
is serialized by BasicTextUI if the document is of type
AbstractDocument
. The locking assumes that an
independant thread will access the View hierarchy only from
the DocumentListener methods, and that there will be only
one event thread active at a time.
If concurrency support is desired, there are the following
additional implications. The code path for any DocumentListener
implementation and any UndoListener implementation must be threadsafe,
and not access the component lock if trying to be safe from deadlocks.
The repaint
and revalidate
methods
on JComponent are safe.
AbstractDocument models an implied break at the end of the document.
Among other things this allows you to position the caret after the last
character. As a result of this, getLength
returns one less
than the length of the Content. If you create your own Content, be
sure and initialize it to have an additional character. Refer to
StringContent and GapContent for examples of this. Another implication
of this is that Elements that model the implied end character will have
an endOffset == (getLength() + 1). For example, in DefaultStyledDocument
getParagraphElement(getLength()).getEndOffset() == getLength() + 1
.
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 applications running
the same version of Swing. As of 1.4, support for long term storage
of all JavaBeansTM
has been added to the java.beans
package.
Please see XMLEncoder
.
Nested Class Summary | |
class |
AbstractDocument.AbstractElement
Implements the abstract part of an element. |
static interface |
AbstractDocument.AttributeContext
An interface that can be used to allow MutableAttributeSet implementations to use pluggable attribute compression techniques. |
(package private) class |
AbstractDocument.BidiElement
Represents an element of the bidirectional element structure. |
(package private) class |
AbstractDocument.BidiRootElement
Represents the root element of the bidirectional element structure. |
class |
AbstractDocument.BranchElement
Implements a composite element that contains other elements. |
static interface |
AbstractDocument.Content
Interface to describe a sequence of character content that can be edited. |
class |
AbstractDocument.DefaultDocumentEvent
Stores document changes as the document is being modified. |
private class |
AbstractDocument.DefaultFilterBypass
|
static class |
AbstractDocument.ElementEdit
An implementation of ElementChange that can be added to the document event. |
class |
AbstractDocument.LeafElement
Implements an element that directly represents content of some kind. |
Field Summary | |
(package private) static String |
AsyncLoadPriority
Document property that indicates asynchronous loading is desired, with the thread priority given as the value. |
protected static String |
BAD_LOCATION
Error message to indicate a bad location. |
private static String |
BAD_LOCK_STATE
|
static String |
BidiElementName
Name of elements used to hold a unidirectional run |
private AbstractDocument.BranchElement |
bidiRoot
The root of the bidirectional structure for this document. |
static String |
ContentElementName
Name of elements used to represent content |
private AbstractDocument.AttributeContext |
context
Factory for the attributes. |
private Thread |
currWriter
|
private AbstractDocument.Content |
data
Where the text is actually stored, and a set of marks that track change as the document is edited are managed. |
private static Boolean |
defaultI18NProperty
|
private DocumentFilter |
documentFilter
Filter for inserting/removing of text. |
private Dictionary |
documentProperties
Storage for document-wide properties. |
static String |
ElementNameAttribute
Name of the attribute used to specify element names. |
private DocumentFilter.FilterBypass |
filterBypass
Used by DocumentFilter to do actual insert/remove. |
(package private) static String |
I18NProperty
Document property that indicates whether internationalization functions such as text reordering or reshaping should be performed. |
protected EventListenerList |
listenerList
The event listener list for the document. |
(package private) static Object |
MultiByteProperty
Document property that indicates if a character has been inserted into the document that is more than one byte long. |
private boolean |
notifyingListeners
True will notifying listeners. |
private int |
numReaders
|
private int |
numWriters
The number of writers, all obtained from currWriter . |
static String |
ParagraphElementName
Name of elements used to represent paragraphs |
static String |
SectionElementName
Name of elements used to hold sections (lines/paragraphs). |
Fields inherited from interface javax.swing.text.Document |
StreamDescriptionProperty, TitleProperty |
Constructor Summary | |
protected |
AbstractDocument(AbstractDocument.Content data)
Constructs a new AbstractDocument , wrapped around some
specified content storage mechanism. |
protected |
AbstractDocument(AbstractDocument.Content data,
AbstractDocument.AttributeContext context)
Constructs a new AbstractDocument , wrapped around some
specified content storage mechanism. |
Method Summary | |
void |
addDocumentListener(DocumentListener listener)
Adds a document listener for notification of any changes. |
void |
addUndoableEditListener(UndoableEditListener listener)
Adds an undo listener for notification of any changes. |
private byte[] |
calculateBidiLevels(int firstPStart,
int lastPEnd)
Calculate the levels array for a range of paragraphs. |
protected Element |
createBranchElement(Element parent,
AttributeSet a)
Creates a document branch element, that can contain other elements. |
protected Element |
createLeafElement(Element parent,
AttributeSet a,
int p0,
int p1)
Creates a document leaf element. |
Position |
createPosition(int offs)
Returns a position that will track change as the document is altered. |
void |
dump(PrintStream out)
Gives a diagnostic dump. |
protected void |
fireChangedUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. |
protected void |
fireInsertUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. |
protected void |
fireRemoveUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. |
protected void |
fireUndoableEditUpdate(UndoableEditEvent e)
Notifies all listeners that have registered interest for notification on this event type. |
int |
getAsynchronousLoadPriority()
Gets the asynchronous loading priority. |
protected AbstractDocument.AttributeContext |
getAttributeContext()
Fetches the context for managing attributes. |
Element |
getBidiRootElement()
Returns the root element of the bidirectional structure for this document. |
protected AbstractDocument.Content |
getContent()
Gets the content for the document. |
protected Thread |
getCurrentWriter()
Fetches the current writing thread if there is one. |
abstract Element |
getDefaultRootElement()
Returns the root element that views should be based upon unless some other mechanism for assigning views to element structures is provided. |
DocumentFilter |
getDocumentFilter()
Returns the DocumentFilter that is responsible for
filtering of insertion/removal. |
DocumentListener[] |
getDocumentListeners()
Returns an array of all the document listeners registered on this document. |
Dictionary |
getDocumentProperties()
Supports managing a set of properties. |
Position |
getEndPosition()
Returns a position that represents the end of the document. |
private DocumentFilter.FilterBypass |
getFilterBypass()
Returns the FilterBypass . |
int |
getLength()
Returns the length of the data. |
EventListener[] |
getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListener s
upon this document.
|
abstract Element |
getParagraphElement(int pos)
Get the paragraph element containing the given position. |
Object |
getProperty(Object key)
A convenience method for looking up a property value. |
Element[] |
getRootElements()
Gets all root elements defined. |
Position |
getStartPosition()
Returns a position that represents the start of the document. |
String |
getText(int offset,
int length)
Gets a sequence of text from the document. |
void |
getText(int offset,
int length,
Segment txt)
Fetches the text contained within the given portion of the document. |
UndoableEditListener[] |
getUndoableEditListeners()
Returns an array of all the undoable edit listeners registered on this document. |
(package private) void |
handleInsertString(int offs,
String str,
AttributeSet a)
Performs the actual work of inserting the text; it is assumed the caller has obtained a write lock before invoking this. |
(package private) void |
handleRemove(int offs,
int len)
Performs the actual work of the remove. |
void |
insertString(int offs,
String str,
AttributeSet a)
Inserts some content into the document. |
protected void |
insertUpdate(AbstractDocument.DefaultDocumentEvent chng,
AttributeSet attr)
Updates document structure as a result of text insertion. |
private static boolean |
isComplex(char ch)
|
private static boolean |
isComplex(char[] text,
int start,
int limit)
|
(package private) boolean |
isLeftToRight(int p0,
int p1)
Returns true if the text in the range p0 to
p1 is left to right. |
protected void |
postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates any document structure as a result of text removal. |
void |
putProperty(Object key,
Object value)
A convenience method for storing up a property value. |
void |
readLock()
Acquires a lock to begin reading some state from the document. |
private void |
readObject(ObjectInputStream s)
|
void |
readUnlock()
Does a read unlock. |
void |
remove(int offs,
int len)
Removes some content from the document. |
void |
removeDocumentListener(DocumentListener listener)
Removes a document listener. |
void |
removeUndoableEditListener(UndoableEditListener listener)
Removes an undo listener. |
protected void |
removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates any document structure as a result of text removal. |
void |
render(Runnable r)
This allows the model to be safely rendered in the presence of currency, if the model supports being updated asynchronously. |
void |
replace(int offset,
int length,
String text,
AttributeSet attrs)
Deletes the region of text from offset to
offset + length , and replaces it with text .
|
void |
setAsynchronousLoadPriority(int p)
Sets the asynchronous loading priority. |
void |
setDocumentFilter(DocumentFilter filter)
Sets the DocumentFilter . |
void |
setDocumentProperties(Dictionary x)
Replaces the document properties dictionary for this document. |
(package private) void |
updateBidi(AbstractDocument.DefaultDocumentEvent chng)
Update the bidi element structure as a result of the given change to the document. |
protected void |
writeLock()
Acquires a lock to begin mutating the document this lock protects. |
protected void |
writeUnlock()
Releases a write lock previously obtained via writeLock .
|
Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Field Detail |
private transient int numReaders
private transient Thread currWriter
private transient int numWriters
currWriter
.
private transient boolean notifyingListeners
private static Boolean defaultI18NProperty
private Dictionary documentProperties
protected EventListenerList listenerList
private AbstractDocument.Content data
private AbstractDocument.AttributeContext context
private transient AbstractDocument.BranchElement bidiRoot
private DocumentFilter documentFilter
private transient DocumentFilter.FilterBypass filterBypass
private static final String BAD_LOCK_STATE
protected static final String BAD_LOCATION
public static final String ParagraphElementName
public static final String ContentElementName
public static final String SectionElementName
public static final String BidiElementName
public static final String ElementNameAttribute
static final String I18NProperty
static final Object MultiByteProperty
static final String AsyncLoadPriority
Constructor Detail |
protected AbstractDocument(AbstractDocument.Content data)
AbstractDocument
, wrapped around some
specified content storage mechanism.
data
- the contentprotected AbstractDocument(AbstractDocument.Content data, AbstractDocument.AttributeContext context)
AbstractDocument
, wrapped around some
specified content storage mechanism.
data
- the contentcontext
- the attribute contextMethod Detail |
public Dictionary getDocumentProperties()
documentProperties
dictionary
to annotate the document with document-wide properties.
null
Dictionary
setDocumentProperties(java.util.Dictionary)
public void setDocumentProperties(Dictionary x)
x
- the new dictionarygetDocumentProperties()
protected void fireInsertUpdate(DocumentEvent e)
e
- the eventEventListenerList
protected void fireChangedUpdate(DocumentEvent e)
e
- the eventEventListenerList
protected void fireRemoveUpdate(DocumentEvent e)
e
- the eventEventListenerList
protected void fireUndoableEditUpdate(UndoableEditEvent e)
e
- the eventEventListenerList
public EventListener[] getListeners(Class listenerType)
FooListener
s
upon this document.
FooListener
s are registered using the
addFooListener
method.
You can specify the listenerType
argument
with a class literal, such as
FooListener.class
.
For example, you can query a
document d
for its document listeners with the following code:
DocumentListener[] mls = (DocumentListener[])(d.getListeners(DocumentListener.class));If no such listeners exist, this method returns an empty array.
listenerType
- the type of listeners requested; this parameter
should specify an interface that descends from
java.util.EventListener
FooListener
s on this component,
or an empty array if no such
listeners have been added
ClassCastException
- if listenerType
doesn't specify a class or interface that implements
java.util.EventListener
getDocumentListeners()
,
getUndoableEditListeners()
public int getAsynchronousLoadPriority()
-1
if the document should not be loaded asynchronouslypublic void setAsynchronousLoadPriority(int p)
p
- the new asynchronous loading priority; a value
less than zero indicates that the document should not be
loaded asynchronouslypublic void setDocumentFilter(DocumentFilter filter)
DocumentFilter
. The DocumentFilter
is passed insert
and remove
to conditionally
allow inserting/deleting of the text. A null
value
indicates that no filtering will occur.
filter
- the DocumentFilter
used to constrain textgetDocumentFilter()
public DocumentFilter getDocumentFilter()
DocumentFilter
that is responsible for
filtering of insertion/removal. A null
return value
implies no filtering is to occur.
setDocumentFilter(javax.swing.text.DocumentFilter)
public void render(Runnable r)
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, its 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.
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.
This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.
render
in interface Document
r
- the renderer to executepublic int getLength()
getLength
in interface Document
Document.getLength()
public void addDocumentListener(DocumentListener listener)
addDocumentListener
in interface Document
listener
- the DocumentListener
to addDocument.addDocumentListener(javax.swing.event.DocumentListener)
public void removeDocumentListener(DocumentListener listener)
removeDocumentListener
in interface Document
listener
- the DocumentListener
to removeDocument.removeDocumentListener(javax.swing.event.DocumentListener)
public DocumentListener[] getDocumentListeners()
DocumentListener
s
or an empty array if no document listeners are
currently registeredaddDocumentListener(javax.swing.event.DocumentListener)
,
removeDocumentListener(javax.swing.event.DocumentListener)
public void addUndoableEditListener(UndoableEditListener listener)
UndoableEdit
will cause the appropriate DocumentEvent to be fired to keep
the view(s) in sync with the model.
addUndoableEditListener
in interface Document
listener
- the UndoableEditListener
to addDocument.addUndoableEditListener(javax.swing.event.UndoableEditListener)
public void removeUndoableEditListener(UndoableEditListener listener)
removeUndoableEditListener
in interface Document
listener
- the UndoableEditListener
to removeDocument.removeDocumentListener(javax.swing.event.DocumentListener)
public UndoableEditListener[] getUndoableEditListeners()
UndoableEditListener
s
or an empty array if no undoable edit listeners are
currently registeredaddUndoableEditListener(javax.swing.event.UndoableEditListener)
,
removeUndoableEditListener(javax.swing.event.UndoableEditListener)
public final Object getProperty(Object key)
getDocumentProperties().get(key);
getProperty
in interface Document
key
- the non-null
property key
null
getDocumentProperties()
public final void putProperty(Object key, Object value)
getDocumentProperties().put(key, value);If
value
is null
this method will
remove the property.
putProperty
in interface Document
key
- the non-null
keyvalue
- the property valuegetDocumentProperties()
public void remove(int offs, int len) throws BadLocationException
This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.
remove
in interface Document
offs
- the starting offset >= 0len
- the number of characters to remove >= 0
BadLocationException
- the given remove position is not a valid
position within the documentDocument.remove(int, int)
void handleRemove(int offs, int len) throws BadLocationException
writeLock
before invoking this.
BadLocationException
private static final boolean isComplex(char ch)
private static final boolean isComplex(char[] text, int start, int limit)
public void replace(int offset, int length, String text, AttributeSet attrs) throws BadLocationException
offset
to
offset + length
, and replaces it with text
.
It is up to the implementation as to how this is implemented, some
implementations may treat this as two distinct operations: a remove
followed by an insert, others may treat the replace as one atomic
operation.
offset
- index of child elementlength
- length of text to delete, may be 0 indicating don't
delete anythingtext
- text to insert, null
indicates no text to insertattrs
- AttributeSet indicating attributes of inserted text,
null
is legal, and typically treated as an empty attributeset,
but exact interpretation is left to the subclass
BadLocationException
- the given position is not a valid
position within the documentpublic void insertString(int offs, String str, AttributeSet a) throws BadLocationException
This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.
insertString
in interface Document
offs
- the starting offset >= 0str
- the string to insert; does nothing with null/empty stringsa
- the attributes for the inserted content
BadLocationException
- the given insert position is not a valid
position within the documentDocument.insertString(int, java.lang.String, javax.swing.text.AttributeSet)
void handleInsertString(int offs, String str, AttributeSet a) throws BadLocationException
BadLocationException
public String getText(int offset, int length) throws BadLocationException
getText
in interface Document
offset
- the starting offset >= 0length
- the number of characters to retrieve >= 0
BadLocationException
- the range given includes a position
that is not a valid position within the documentDocument.getText(int, int)
public void getText(int offset, int length, Segment txt) throws BadLocationException
If the partialReturn property on the txt parameter is false, the data returned in the Segment will be the entire length requested and may or may not be a copy depending upon how the data was stored. If the partialReturn property is true, only the amount of text that can be returned without creating a copy is returned. Using partial returns will give better performance for situations where large parts of the document are being scanned. The following is an example of using the partial return to access the entire document:
int nleft = doc.getDocumentLength(); Segment text = new Segment(); int offs = 0; text.setPartialReturn(true); while (nleft > 0) { doc.getText(offs, nleft, text); // do something with text nleft -= text.count; offs += text.count; }
getText
in interface Document
offset
- the starting offset >= 0length
- the number of characters to retrieve >= 0txt
- the Segment object to retrieve the text into
BadLocationException
- the range given includes a position
that is not a valid position within the documentpublic Position createPosition(int offs) throws BadLocationException
This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.
createPosition
in interface Document
offs
- the position in the model >= 0
BadLocationException
- if the given position does not
represent a valid location in the associated documentDocument.createPosition(int)
public final Position getStartPosition()
getStartPosition
in interface Document
public final Position getEndPosition()
getEndPosition
in interface Document
public Element[] getRootElements()
getRootElements
in interface Document
public abstract Element getDefaultRootElement()
getDefaultRootElement
in interface Document
Document.getDefaultRootElement()
private DocumentFilter.FilterBypass getFilterBypass()
FilterBypass
. This will create one if one
does not yet exist.
public Element getBidiRootElement()
boolean isLeftToRight(int p0, int p1)
p0
to
p1
is left to right.
public abstract Element getParagraphElement(int pos)
pos
- the starting offset >= 0
protected final AbstractDocument.AttributeContext getAttributeContext()
protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr)
chng
- a description of the changeattr
- the attributes for the changeprotected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
chng
- a description of the changeprotected void postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng)
chng
- a description of the changevoid updateBidi(AbstractDocument.DefaultDocumentEvent chng)
private byte[] calculateBidiLevels(int firstPStart, int lastPEnd)
public void dump(PrintStream out)
out
- the output streamprotected final AbstractDocument.Content getContent()
protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1)
parent
- the parent elementa
- the attributes for the elementp0
- the beginning of the range >= 0p1
- the end of the range >= p0
protected Element createBranchElement(Element parent, AttributeSet a)
parent
- the parent elementa
- the attributes
protected final Thread getCurrentWriter()
null
if there are no modifications in progressprotected final void writeLock()
writeLock
,
as long as it doesn't attempt to gain additional writeLock
s
from within document notification. Attempting to gain a
writeLock
from within a DocumentListener notification will
result in an IllegalStateException
. The ability
to obtain more than one writeLock
per thread allows
subclasses to gain a writeLock, perform a number of operations, then
release the lock.
Calls to writeLock
must be balanced with calls to writeUnlock
, else the
Document
will be left in a locked state so that no
reading or writing can be done.
IllegalStateException
- thrown on illegal lock
attempt. If the document is implemented properly, this can
only happen if a document listener attempts to mutate the
document. This situation violates the bean event model
where order of delivery is not guaranteed and all listeners
should be notified before further mutations are allowed.protected final void writeUnlock()
writeLock
.
After decrementing the lock count if there are no oustanding locks
this will allow a new writer, or readers.
writeLock()
public final void readLock()
readUnlock
.
readUnlock()
public final void readUnlock()
readLock();
try {
// do something
} finally {
readUnlock();
}
readLock()
private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException
ClassNotFoundException
IOException
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |