| Method from org.apache.xerces.dom.DocumentImpl Detail: |
protected void addEventListener(NodeImpl node,
String type,
EventListener listener,
boolean useCapture) {
// We can't dispatch to blank type-name, and of course we need
// a listener to dispatch to
if (type == null || type.equals("") || listener == null)
return;
// Each listener may be registered only once per type per phase.
// Simplest way to code that is to zap the previous entry, if any.
removeEventListener(node, type, listener, useCapture);
Vector nodeListeners = getEventListeners(node);
if(nodeListeners == null) {
nodeListeners = new Vector();
setEventListeners(node, nodeListeners);
}
nodeListeners.addElement(new LEntry(type, listener, useCapture));
// Record active listener
LCount lc = LCount.lookup(type);
if (useCapture) {
++lc.captures;
++lc.total;
}
else {
++lc.bubbles;
++lc.total;
}
}
Introduced in DOM Level 2. Register an event listener with this
Node. A listener may be independently registered as both Capturing and
Bubbling, but may only be registered once per role; redundant
registrations are ignored. |
public Node cloneNode(boolean deep) {
DocumentImpl newdoc = new DocumentImpl();
callUserDataHandlers(this, newdoc, UserDataHandler.NODE_CLONED);
cloneNode(newdoc, deep);
// experimental
newdoc.mutationEvents = mutationEvents;
return newdoc;
}
Deep-clone a document, including fixing ownerDoc for the cloned
children. Note that this requires bypassing the WRONG_DOCUMENT_ERR
protection. I've chosen to implement it by calling importNode
which is DOM Level 2. |
protected void copyEventListeners(NodeImpl src,
NodeImpl tgt) {
Vector nodeListeners = getEventListeners(src);
if (nodeListeners == null) {
return;
}
setEventListeners(tgt, (Vector) nodeListeners.clone());
}
|
public Event createEvent(String type) throws DOMException {
if (type.equalsIgnoreCase("Events") ||
"Event".equals(type)) {
return new EventImpl();
}
else if (type.equalsIgnoreCase("MutationEvents") ||
"MutationEvent".equals(type)) {
return new MutationEventImpl();
}
else if (type.equalsIgnoreCase("UIEvents") ||
"UIEvent".equals(type)) {
return new UIEventImpl();
}
else if (type.equalsIgnoreCase("MouseEvents") ||
"MouseEvent".equals(type)) {
return new MouseEventImpl();
}
else {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null);
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
|
public NodeIterator createNodeIterator(Node root,
short whatToShow,
NodeFilter filter) {
return createNodeIterator(root, whatToShow, filter, true);
}
NON-DOM extension:
Create and return a NodeIterator. The NodeIterator is
added to a list of NodeIterators so that it can be
removed to free up the DOM Nodes it references. |
public NodeIterator createNodeIterator(Node root,
int whatToShow,
NodeFilter filter,
boolean entityReferenceExpansion) {
if (root == null) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null);
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
NodeIterator iterator = new NodeIteratorImpl(this,
root,
whatToShow,
filter,
entityReferenceExpansion);
if (iterators == null) {
iterators = new Vector();
}
iterators.addElement(iterator);
return iterator;
}
Create and return a NodeIterator. The NodeIterator is
added to a list of NodeIterators so that it can be
removed to free up the DOM Nodes it references. |
public Range createRange() {
if (ranges == null) {
ranges = new Vector();
}
Range range = new RangeImpl(this);
ranges.addElement(range);
return range;
}
|
public TreeWalker createTreeWalker(Node root,
short whatToShow,
NodeFilter filter) {
return createTreeWalker(root, whatToShow, filter, true);
}
NON-DOM extension:
Create and return a TreeWalker. |
public TreeWalker createTreeWalker(Node root,
int whatToShow,
NodeFilter filter,
boolean entityReferenceExpansion) {
if (root == null) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null);
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
return new TreeWalkerImpl(root, whatToShow, filter,
entityReferenceExpansion);
}
Create and return a TreeWalker. |
void deletedText(CharacterDataImpl node,
int offset,
int count) {
// notify ranges
if (ranges != null) {
notifyRangesDeletedText(node, offset, count);
}
}
A method to be called when some text was deleted from a text node,
so that live objects can be notified. |
protected void dispatchAggregateEvents(NodeImpl node,
DocumentImpl.EnclosingAttr ea) {
if (ea != null)
dispatchAggregateEvents(node, ea.node, ea.oldvalue,
MutationEvent.MODIFICATION);
else
dispatchAggregateEvents(node, null, null, (short) 0);
}
NON-DOM INTERNAL: Convenience wrapper for calling
dispatchAggregateEvents when the context was established
by savedEnclosingAttr. |
protected void dispatchAggregateEvents(NodeImpl node,
AttrImpl enclosingAttr,
String oldvalue,
short change) {
// We have to send DOMAttrModified.
NodeImpl owner = null;
if (enclosingAttr != null) {
LCount lc = LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
owner = (NodeImpl) enclosingAttr.getOwnerElement();
if (lc.total > 0) {
if (owner != null) {
MutationEventImpl me = new MutationEventImpl();
me.initMutationEvent(MutationEventImpl.DOM_ATTR_MODIFIED,
true, false, enclosingAttr,
oldvalue,
enclosingAttr.getNodeValue(),
enclosingAttr.getNodeName(),
change);
owner.dispatchEvent(me);
}
}
}
// DOMSubtreeModified gets sent to the lowest common root of a
// set of changes.
// "This event is dispatched after all other events caused by the
// mutation have been fired."
LCount lc = LCount.lookup(MutationEventImpl.DOM_SUBTREE_MODIFIED);
if (lc.total > 0) {
MutationEvent me = new MutationEventImpl();
me.initMutationEvent(MutationEventImpl.DOM_SUBTREE_MODIFIED,
true, false, null, null,
null, null, (short) 0);
// If we're within an Attr, DStM gets sent to the Attr
// and to its owningElement. Otherwise we dispatch it
// locally.
if (enclosingAttr != null) {
dispatchEvent(enclosingAttr, me);
if (owner != null)
dispatchEvent(owner, me);
}
else
dispatchEvent(node, me);
}
}
NON-DOM INTERNAL: Generate the "aggregated" post-mutation events
DOMAttrModified and DOMSubtreeModified.
Both of these should be issued only once for each user-requested
mutation operation, even if that involves multiple changes to
the DOM.
For example, if a DOM operation makes multiple changes to a single
Attr before returning, it would be nice to generate only one
DOMAttrModified, and multiple changes over larger scope but within
a recognizable single subtree might want to generate only one
DOMSubtreeModified, sent to their lowest common ancestor.
To manage this, use the "internal" versions of insert and remove
with MUTATION_LOCAL, then make an explicit call to this routine
at the higher level. Some examples now exist in our code. |
protected boolean dispatchEvent(NodeImpl node,
Event event) {
if (event == null) return false;
// Can't use anyone else's implementation, since there's no public
// API for setting the event's processing-state fields.
EventImpl evt = (EventImpl)event;
// VALIDATE -- must have been initialized at least once, must have
// a non-null non-blank name.
if(!evt.initialized || evt.type == null || evt.type.equals("")) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "UNSPECIFIED_EVENT_TYPE_ERR", null);
throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR, msg);
}
// If nobody is listening for this event, discard immediately
LCount lc = LCount.lookup(evt.getType());
if (lc.total == 0)
return evt.preventDefault;
// INITIALIZE THE EVENT'S DISPATCH STATUS
// (Note that Event objects are reusable in our implementation;
// that doesn't seem to be explicitly guaranteed in the DOM, but
// I believe it is the intent.)
evt.target = node;
evt.stopPropagation = false;
evt.preventDefault = false;
// Capture pre-event parentage chain, not including target;
// use pre-event-dispatch ancestors even if event handlers mutate
// document and change the target's context.
// Note that this is parents ONLY; events do not
// cross the Attr/Element "blood/brain barrier".
// DOMAttrModified. which looks like an exception,
// is issued to the Element rather than the Attr
// and causes a _second_ DOMSubtreeModified in the Element's
// tree.
ArrayList pv = new ArrayList(10);
Node p = node;
Node n = p.getParentNode();
while (n != null) {
pv.add(n);
p = n;
n = n.getParentNode();
}
// CAPTURING_PHASE:
if (lc.captures > 0) {
evt.eventPhase = Event.CAPTURING_PHASE;
// Ancestors are scanned, root to target, for
// Capturing listeners.
for (int j = pv.size() - 1; j >= 0; --j) {
if (evt.stopPropagation)
break; // Someone set the flag. Phase ends.
// Handle all capturing listeners on this node
NodeImpl nn = (NodeImpl) pv.get(j);
evt.currentTarget = nn;
Vector nodeListeners = getEventListeners(nn);
if (nodeListeners != null) {
Vector nl = (Vector) nodeListeners.clone();
// call listeners in the order in which they got registered
int nlsize = nl.size();
for (int i = 0; i < nlsize; i++) {
LEntry le = (LEntry) nl.elementAt(i);
if (le.useCapture && le.type.equals(evt.type) &&
nodeListeners.contains(le)) {
try {
le.listener.handleEvent(evt);
}
catch (Exception e) {
// All exceptions are ignored.
}
}
}
}
}
}
// Both AT_TARGET and BUBBLE use non-capturing listeners.
if (lc.bubbles > 0) {
// AT_TARGET PHASE: Event is dispatched to NON-CAPTURING listeners
// on the target node. Note that capturing listeners on the target
// node are _not_ invoked, even during the capture phase.
evt.eventPhase = Event.AT_TARGET;
evt.currentTarget = node;
Vector nodeListeners = getEventListeners(node);
if (!evt.stopPropagation && nodeListeners != null) {
Vector nl = (Vector) nodeListeners.clone();
// call listeners in the order in which they got registered
int nlsize = nl.size();
for (int i = 0; i < nlsize; i++) {
LEntry le = (LEntry) nl.elementAt(i);
if (!le.useCapture && le.type.equals(evt.type) &&
nodeListeners.contains(le)) {
try {
le.listener.handleEvent(evt);
}
catch (Exception e) {
// All exceptions are ignored.
}
}
}
}
// BUBBLING_PHASE: Ancestors are scanned, target to root, for
// non-capturing listeners. If the event's preventBubbling flag
// has been set before processing of a node commences, we
// instead immediately advance to the default phase.
// Note that not all events bubble.
if (evt.bubbles) {
evt.eventPhase = Event.BUBBLING_PHASE;
int pvsize = pv.size();
for (int j = 0; j < pvsize; j++) {
if (evt.stopPropagation)
break; // Someone set the flag. Phase ends.
// Handle all bubbling listeners on this node
NodeImpl nn = (NodeImpl) pv.get(j);
evt.currentTarget = nn;
nodeListeners = getEventListeners(nn);
if (nodeListeners != null) {
Vector nl = (Vector) nodeListeners.clone();
// call listeners in the order in which they got
// registered
int nlsize = nl.size();
for (int i = 0; i < nlsize; i++) {
LEntry le = (LEntry) nl.elementAt(i);
if (!le.useCapture && le.type.equals(evt.type) &&
nodeListeners.contains(le)) {
try {
le.listener.handleEvent(evt);
}
catch (Exception e) {
// All exceptions are ignored.
}
}
}
}
}
}
}
// DEFAULT PHASE: Some DOMs have default behaviors bound to specific
// nodes. If this DOM does, and if the event's preventDefault flag has
// not been set, we now return to the target node and process its
// default handler for this event, if any.
// No specific phase value defined, since this is DOM-internal
if (lc.defaults > 0 && (!evt.cancelable || !evt.preventDefault)) {
// evt.eventPhase = Event.DEFAULT_PHASE;
// evt.currentTarget = node;
// DO_DEFAULT_OPERATION
}
return evt.preventDefault;
}
Introduced in DOM Level 2.
Distribution engine for DOM Level 2 Events.
Event propagation runs as follows:
- Event is dispatched to a particular target node, which invokes
this code. Note that the event's stopPropagation flag is
cleared when dispatch begins; thereafter, if it has
been set before processing of a node commences, we instead
immediately advance to the DEFAULT phase.
- The node's ancestors are established as destinations for events.
For capture and bubble purposes, node ancestry is determined at
the time dispatch starts. If an event handler alters the document
tree, that does not change which nodes will be informed of the event.
- CAPTURING_PHASE: Ancestors are scanned, root to target, for
Capturing listeners. If found, they are invoked (see below).
- AT_TARGET:
Event is dispatched to NON-CAPTURING listeners on the
target node. Note that capturing listeners on this node are _not_
invoked.
- BUBBLING_PHASE: Ancestors are scanned, target to root, for
non-capturing listeners.
- Default processing: Some DOMs have default behaviors bound to
specific nodes. If this DOM does, and if the event's preventDefault
flag has not been set, we now return to the target node and process
its default handler for this event, if any.
Note that registration of handlers during processing of an event does
not take effect during this phase of this event; they will not be called
until the next time this node is visited by dispatchEvent. On the other
hand, removals take effect immediately.
If an event handler itself causes events to be dispatched, they are
processed synchronously, before processing resumes
on the event which triggered them. Please be aware that this may
result in events arriving at listeners "out of order" relative
to the actual sequence of requests.
Note that our implementation resets the event's stop/prevent flags
when dispatch begins.
I believe the DOM's intent is that event objects be redispatchable,
though it isn't stated in those terms. |
protected void dispatchEventToSubtree(Node n,
Event e) {
((NodeImpl) n).dispatchEvent(e);
if (n.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap a = n.getAttributes();
for (int i = a.getLength() - 1; i >= 0; --i)
dispatchingEventToSubtree(a.item(i), e);
}
dispatchingEventToSubtree(n.getFirstChild(), e);
}
NON-DOM INTERNAL: DOMNodeInsertedIntoDocument and ...RemovedFrom...
are dispatched to an entire subtree. This is the distribution code
therefor. They DO NOT bubble, thanks be, but may be captured.
Similar to code in dispatchingEventToSubtree however this method
is only used on the target node and does not start a dispatching chain
on the sibling of the target node as this is not part of the subtree
***** At the moment I'm being sloppy and using the normal
capture dispatcher on every node. This could be optimized hugely
by writing a capture engine that tracks our position in the tree to
update the capture chain without repeated chases up to root. |
protected void dispatchingEventToSubtree(Node n,
Event e) {
if (n==null)
return;
// ***** Recursive implementation. This is excessively expensive,
// and should be replaced in conjunction with optimization
// mentioned above.
((NodeImpl) n).dispatchEvent(e);
if (n.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap a = n.getAttributes();
for (int i = a.getLength() - 1; i >= 0; --i)
dispatchingEventToSubtree(a.item(i), e);
}
dispatchingEventToSubtree(n.getFirstChild(), e);
dispatchingEventToSubtree(n.getNextSibling(), e);
}
Dispatches event to the target node's descendents recursively |
protected Vector getEventListeners(NodeImpl n) {
if (eventListeners == null) {
return null;
}
return (Vector) eventListeners.get(n);
}
Retreive event listener registered on a given node |
public DOMImplementation getImplementation() {
// Currently implemented as a singleton, since it's hardcoded
// information anyway.
return DOMImplementationImpl.getDOMImplementation();
}
Retrieve information describing the abilities of this particular
DOM implementation. Intended to support applications that may be
using DOMs retrieved from several different sources, potentially
with different underlying representations. |
boolean getMutationEvents() {
return mutationEvents;
}
Returns true if the DOM implementation generates mutation events. |
void insertedNode(NodeImpl node,
NodeImpl newInternal,
boolean replace) {
if (mutationEvents) {
mutationEventsInsertedNode(node, newInternal, replace);
}
// notify the range of insertions
if (ranges != null) {
notifyRangesInsertedNode(newInternal);
}
}
A method to be called when a node has been inserted in the tree. |
void insertedText(CharacterDataImpl node,
int offset,
int count) {
// notify ranges
if (ranges != null) {
notifyRangesInsertedText(node, offset, count);
}
}
A method to be called when some text was inserted into a text node,
so that live objects can be notified. |
void insertingNode(NodeImpl node,
boolean replace) {
if (mutationEvents) {
if (!replace) {
saveEnclosingAttr(node);
}
}
}
A method to be called when a node is about to be inserted in the tree. |
void modifiedAttrValue(AttrImpl attr,
String oldvalue) {
if (mutationEvents) {
// MUTATION POST-EVENTS:
dispatchAggregateEvents(attr, attr, oldvalue,
MutationEvent.MODIFICATION);
}
}
A method to be called when an attribute value has been modified |
void modifiedCharacterData(NodeImpl node,
String oldvalue,
String value,
boolean replace) {
if (mutationEvents) {
mutationEventsModifiedCharacterData(node, oldvalue, value, replace);
}
}
A method to be called when a character data node has been modified |
void modifyingCharacterData(NodeImpl node,
boolean replace) {
if (mutationEvents) {
if (!replace) {
saveEnclosingAttr(node);
}
}
}
A method to be called when a character data node has been modified |
protected void removeEventListener(NodeImpl node,
String type,
EventListener listener,
boolean useCapture) {
// If this couldn't be a valid listener registration, ignore request
if (type == null || type.equals("") || listener == null)
return;
Vector nodeListeners = getEventListeners(node);
if (nodeListeners == null)
return;
// Note that addListener has previously ensured that
// each listener may be registered only once per type per phase.
// count-down is OK for deletions!
for (int i = nodeListeners.size() - 1; i >= 0; --i) {
LEntry le = (LEntry) nodeListeners.elementAt(i);
if (le.useCapture == useCapture && le.listener == listener &&
le.type.equals(type)) {
nodeListeners.removeElementAt(i);
// Storage management: Discard empty listener lists
if (nodeListeners.size() == 0)
setEventListeners(node, null);
// Remove active listener
LCount lc = LCount.lookup(type);
if (useCapture) {
--lc.captures;
--lc.total;
}
else {
--lc.bubbles;
--lc.total;
}
break; // Found it; no need to loop farther.
}
}
}
Introduced in DOM Level 2. Deregister an event listener previously
registered with this Node. A listener must be independently removed
from the Capturing and Bubbling roles. Redundant removals (of listeners
not currently registered for this role) are ignored. |
void removeNodeIterator(NodeIterator nodeIterator) {
if (nodeIterator == null) return;
if (iterators == null) return;
iterators.removeElement(nodeIterator);
}
|
void removeRange(Range range) {
if (range == null) return;
if (ranges == null) return;
ranges.removeElement(range);
}
Not a client function. Called by Range.detach(),
so a Range can remove itself from the list of
Ranges. |
void removedAttrNode(AttrImpl attr,
NodeImpl oldOwner,
String name) {
// We can't use the standard dispatchAggregate, since it assumes
// that the Attr is still attached to an owner. This code is
// similar but dispatches to the previous owner, "element".
if (mutationEvents) {
mutationEventsRemovedAttrNode(attr, oldOwner, name);
}
}
A method to be called when an attribute node has been removed |
void removedNode(NodeImpl node,
boolean replace) {
if (mutationEvents) {
// MUTATION POST-EVENTS:
// Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
// if required. (Common to most kinds of mutation)
if (!replace) {
dispatchAggregateEvents(node, savedEnclosingAttr);
}
} // End mutation postprocessing
}
A method to be called when a node has been removed from the tree. |
void removingNode(NodeImpl node,
NodeImpl oldChild,
boolean replace) {
// notify iterators
if (iterators != null) {
notifyIteratorsRemovingNode(oldChild);
}
// notify ranges
if (ranges != null) {
notifyRangesRemovingNode(oldChild);
}
// mutation events
if (mutationEvents) {
mutationEventsRemovingNode(node, oldChild, replace);
}
}
A method to be called when a node is about to be removed from the tree. |
void renamedAttrNode(Attr oldAt,
Attr newAt) {
// REVISIT: To be implemented!!!
}
A method to be called when an attribute node has been renamed |
void renamedElement(Element oldEl,
Element newEl) {
// REVISIT: To be implemented!!!
}
A method to be called when an element has been renamed |
void replacedCharacterData(NodeImpl node,
String oldvalue,
String value) {
//now that we have finished replacing data, we need to perform the same actions
//that are required after a character data node has been modified
//send the value of false for replace parameter so that mutation
//events if appropriate will be initiated
modifiedCharacterData(node, oldvalue, value, false);
}
A method to be called when a character data node has been replaced |
void replacedNode(NodeImpl node) {
if (mutationEvents) {
dispatchAggregateEvents(node, savedEnclosingAttr);
}
}
A method to be called when a node has been replaced in the tree. |
void replacedText(CharacterDataImpl node) {
// notify ranges
if (ranges != null) {
notifyRangesReplacedText(node);
}
}
A method to be called when some text was changed in a text node,
so that live objects can be notified. |
void replacingData(NodeImpl node) {
if (mutationEvents) {
saveEnclosingAttr(node);
}
}
A method to be called when character data is about to be replaced in the tree. |
void replacingNode(NodeImpl node) {
if (mutationEvents) {
saveEnclosingAttr(node);
}
}
A method to be called when a node is about to be replaced in the tree. |
protected void saveEnclosingAttr(NodeImpl node) {
savedEnclosingAttr = null;
// MUTATION PREPROCESSING AND PRE-EVENTS:
// If we're within the scope of an Attr and DOMAttrModified
// was requested, we need to preserve its previous value for
// that event.
LCount lc = LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
if (lc.total > 0) {
NodeImpl eventAncestor = node;
while (true) {
if (eventAncestor == null)
return;
int type = eventAncestor.getNodeType();
if (type == Node.ATTRIBUTE_NODE) {
EnclosingAttr retval = new EnclosingAttr();
retval.node = (AttrImpl) eventAncestor;
retval.oldvalue = retval.node.getNodeValue();
savedEnclosingAttr = retval;
return;
}
else if (type == Node.ENTITY_REFERENCE_NODE)
eventAncestor = eventAncestor.parentNode();
else if (type == Node.TEXT_NODE)
eventAncestor = eventAncestor.parentNode();
else
return;
// Any other parent means we're not in an Attr
}
}
}
NON-DOM INTERNAL: Pre-mutation context check, in
preparation for later generating DOMAttrModified events.
Determines whether this node is within an Attr |
void setAttrNode(AttrImpl attr,
AttrImpl previous) {
if (mutationEvents) {
// MUTATION POST-EVENTS:
if (previous == null) {
dispatchAggregateEvents(attr.ownerNode, attr, null,
MutationEvent.ADDITION);
}
else {
dispatchAggregateEvents(attr.ownerNode, attr,
previous.getNodeValue(),
MutationEvent.MODIFICATION);
}
}
}
A method to be called when an attribute node has been set |
protected void setEventListeners(NodeImpl n,
Vector listeners) {
if (eventListeners == null) {
eventListeners = new Hashtable();
}
if (listeners == null) {
eventListeners.remove(n);
if (eventListeners.isEmpty()) {
// stop firing events when there isn't any listener
mutationEvents = false;
}
} else {
eventListeners.put(n, listeners);
// turn mutation events on
mutationEvents = true;
}
}
Store event listener registered on a given node
This is another place where we could use weak references! Indeed, the
node here won't be GC'ed as long as some listener is registered on it,
since the eventsListeners table will have a reference to the node. |
void setMutationEvents(boolean set) {
mutationEvents = set;
}
Sets whether the DOM implementation generates mutation events
upon operations. |
void splitData(Node node,
Node newNode,
int offset) {
// notify ranges
if (ranges != null) {
notifyRangesSplitData(node, newNode, offset);
}
}
A method to be called when a text node has been split,
so that live objects can be notified. |