DomNode.java 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223
  1. /* DomNode.java --
  2. Copyright (C) 1999,2000,2001,2004 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.xml.dom;
  32. import gnu.java.lang.CPStringBuilder;
  33. import java.util.HashMap;
  34. import java.util.HashSet;
  35. import java.util.Iterator;
  36. import java.util.Map;
  37. import org.w3c.dom.Document;
  38. import org.w3c.dom.DOMException;
  39. import org.w3c.dom.DOMImplementation;
  40. import org.w3c.dom.NamedNodeMap;
  41. import org.w3c.dom.Node;
  42. import org.w3c.dom.NodeList;
  43. import org.w3c.dom.Text;
  44. import org.w3c.dom.UserDataHandler;
  45. import org.w3c.dom.events.DocumentEvent;
  46. import org.w3c.dom.events.Event;
  47. import org.w3c.dom.events.EventException;
  48. import org.w3c.dom.events.EventListener;
  49. import org.w3c.dom.events.EventTarget;
  50. import org.w3c.dom.events.MutationEvent;
  51. import org.w3c.dom.traversal.NodeFilter;
  52. import org.w3c.dom.traversal.NodeIterator;
  53. /**
  54. * <p> "Node", "EventTarget", and "DocumentEvent" implementation.
  55. * This provides most of the core DOM functionality; only more
  56. * specialized features are provided by subclasses. Those subclasses may
  57. * have some particular constraints they must implement, by overriding
  58. * methods defined here. Such constraints are noted here in the method
  59. * documentation. </p>
  60. *
  61. * <p> Note that you can create events with type names prefixed with "USER-",
  62. * and pass them through this DOM. This lets you use the DOM event scheme
  63. * for application specific purposes, although you must use a predefined event
  64. * structure (such as MutationEvent) to pass data along with those events.
  65. * Test for existence of this feature with the "USER-Events" DOM feature
  66. * name.</p>
  67. *
  68. * <p> Other kinds of events you can send include the "html" events,
  69. * like "load", "unload", "abort", "error", and "blur"; and the mutation
  70. * events. If this DOM has been compiled with mutation event support
  71. * enabled, it will send mutation events when you change parts of the
  72. * tree; otherwise you may create and send such events yourself, but
  73. * they won't be generated by the DOM itself. </p>
  74. *
  75. * <p> Note that there is a namespace-aware name comparison method,
  76. * <em>nameAndTypeEquals</em>, which compares the names (and types) of
  77. * two nodes in conformance with the "Namespaces in XML" specification.
  78. * While mostly intended for use with elements and attributes, this should
  79. * also be helpful for ProcessingInstruction nodes and some others which
  80. * do not have namespace URIs.
  81. *
  82. * @author David Brownell
  83. * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
  84. */
  85. public abstract class DomNode
  86. implements Node, NodeList, EventTarget, DocumentEvent, Cloneable, Comparable
  87. {
  88. // package private
  89. //final static String xmlNamespace = "http://www.w3.org/XML/1998/namespace";
  90. //final static String xmlnsURI = "http://www.w3.org/2000/xmlns/";
  91. // tunable
  92. // NKIDS_* affects arrays of children (which grow)
  93. // (currently) fixed size:
  94. // ANCESTORS_* is for event capture/bubbling, # ancestors
  95. // NOTIFICATIONS_* is for per-node event delivery, # events
  96. private static final int NKIDS_DELTA = 8;
  97. private static final int ANCESTORS_INIT = 20;
  98. private static final int NOTIFICATIONS_INIT = 10;
  99. // tunable: enable mutation events or not? Enabling it costs about
  100. // 10-15% in DOM construction time, last time it was measured.
  101. // package private !!!
  102. static final boolean reportMutations = true;
  103. // locking protocol changeable only within this class
  104. private static final Object lockNode = new Object();
  105. // NON-FINAL class data
  106. // Optimize event dispatch by not allocating memory each time
  107. private static boolean dispatchDataLock;
  108. private static DomNode[] ancestors = new DomNode[ANCESTORS_INIT];
  109. private static ListenerRecord[] notificationSet
  110. = new ListenerRecord[NOTIFICATIONS_INIT];
  111. // Ditto for the (most common) event object itself!
  112. private static boolean eventDataLock;
  113. private static DomEvent.DomMutationEvent mutationEvent
  114. = new DomEvent.DomMutationEvent(null);
  115. //
  116. // PER-INSTANCE DATA
  117. //
  118. DomDocument owner;
  119. DomNode parent; // parent node;
  120. DomNode previous; // previous sibling node
  121. DomNode next; // next sibling node
  122. DomNode first; // first child node
  123. DomNode last; // last child node
  124. int index; // index of this node in its parent's children
  125. int depth; // depth of the node in the document
  126. int length; // number of children
  127. final short nodeType;
  128. // Bleech ... "package private" so a builder can populate entity refs.
  129. // writable during construction. DOM spec is nasty.
  130. boolean readonly;
  131. // event registrations
  132. private HashSet listeners;
  133. private int nListeners;
  134. // DOM Level 3 userData dictionary.
  135. private HashMap userData;
  136. private HashMap userDataHandlers;
  137. //
  138. // Some of the methods here are declared 'final' because
  139. // knowledge about their implementation is built into this
  140. // class -- for both integrity and performance.
  141. //
  142. /**
  143. * Reduces space utilization for this node.
  144. */
  145. public void compact()
  146. {
  147. }
  148. /**
  149. * Constructs a node and associates it with its owner. Only
  150. * Document and DocumentType nodes may be created with no owner,
  151. * and DocumentType nodes get an owner as soon as they are
  152. * associated with a document.
  153. */
  154. protected DomNode(short nodeType, DomDocument owner)
  155. {
  156. this.nodeType = nodeType;
  157. if (owner == null)
  158. {
  159. // DOM calls never go down this path
  160. if (nodeType != DOCUMENT_NODE && nodeType != DOCUMENT_TYPE_NODE)
  161. {
  162. throw new IllegalArgumentException ("no owner!");
  163. }
  164. }
  165. this.owner = owner;
  166. this.listeners = new HashSet();
  167. }
  168. /**
  169. * <b>DOM L1</b>
  170. * Returns null; Element subclasses must override this method.
  171. */
  172. public NamedNodeMap getAttributes()
  173. {
  174. return null;
  175. }
  176. /**
  177. * <b>DOM L2></b>
  178. * Returns true iff this is an element node with attributes.
  179. */
  180. public boolean hasAttributes()
  181. {
  182. return false;
  183. }
  184. /**
  185. * <b>DOM L1</b>
  186. * Returns a list, possibly empty, of the children of this node.
  187. * In this implementation, to conserve memory, nodes are the same
  188. * as their list of children. This can have ramifications for
  189. * subclasses, which may need to provide their own getLength method
  190. * for reasons unrelated to the NodeList method of the same name.
  191. */
  192. public NodeList getChildNodes()
  193. {
  194. return this;
  195. }
  196. /**
  197. * <b>DOM L1</b>
  198. * Returns the first child of this node, or null if there are none.
  199. */
  200. public Node getFirstChild()
  201. {
  202. return first;
  203. }
  204. /**
  205. * <b>DOM L1</b>
  206. * Returns the last child of this node, or null if there are none.
  207. */
  208. public Node getLastChild()
  209. {
  210. return last;
  211. }
  212. /**
  213. * <b>DOM L1</b>
  214. * Returns true if this node has children.
  215. */
  216. public boolean hasChildNodes()
  217. {
  218. return length != 0;
  219. }
  220. /**
  221. * Exposes the internal "readonly" flag. In DOM, children of
  222. * entities and entity references are readonly, as are the
  223. * objects associated with DocumentType objets.
  224. */
  225. public final boolean isReadonly()
  226. {
  227. return readonly;
  228. }
  229. /**
  230. * Sets the internal "readonly" flag so this subtree can't be changed.
  231. * Subclasses need to override this method for any associated content
  232. * that's not a child node, such as an element's attributes or the
  233. * (few) declarations associated with a DocumentType.
  234. */
  235. public void makeReadonly()
  236. {
  237. readonly = true;
  238. for (DomNode child = first; child != null; child = child.next)
  239. {
  240. child.makeReadonly();
  241. }
  242. }
  243. /**
  244. * Used to adopt a node to a new document.
  245. */
  246. void setOwner(DomDocument doc)
  247. {
  248. this.owner = doc;
  249. for (DomNode ctx = first; ctx != null; ctx = ctx.next)
  250. {
  251. ctx.setOwner(doc);
  252. }
  253. }
  254. // just checks the node for inclusion -- may be called many
  255. // times (docfrag) before anything is allowed to change
  256. private void checkMisc(DomNode child)
  257. {
  258. if (readonly && !owner.building)
  259. {
  260. throw new DomDOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
  261. null, this, 0);
  262. }
  263. for (DomNode ctx = this; ctx != null; ctx = ctx.parent)
  264. {
  265. if (child == ctx)
  266. {
  267. throw new DomDOMException(DOMException.HIERARCHY_REQUEST_ERR,
  268. "can't make ancestor into a child",
  269. this, 0);
  270. }
  271. }
  272. DomDocument owner = (nodeType == DOCUMENT_NODE) ? (DomDocument) this :
  273. this.owner;
  274. DomDocument childOwner = child.owner;
  275. short childNodeType = child.nodeType;
  276. if (childOwner != owner)
  277. {
  278. // new in DOM L2, this case -- patch it up later, in reparent()
  279. if (!(childNodeType == DOCUMENT_TYPE_NODE && childOwner == null))
  280. {
  281. throw new DomDOMException(DOMException.WRONG_DOCUMENT_ERR,
  282. null, child, 0);
  283. }
  284. }
  285. // enforce various structural constraints
  286. switch (nodeType)
  287. {
  288. case DOCUMENT_NODE:
  289. switch (childNodeType)
  290. {
  291. case ELEMENT_NODE:
  292. case PROCESSING_INSTRUCTION_NODE:
  293. case COMMENT_NODE:
  294. case DOCUMENT_TYPE_NODE:
  295. return;
  296. }
  297. break;
  298. case ATTRIBUTE_NODE:
  299. switch (childNodeType)
  300. {
  301. case TEXT_NODE:
  302. case ENTITY_REFERENCE_NODE:
  303. return;
  304. }
  305. break;
  306. case DOCUMENT_FRAGMENT_NODE:
  307. case ENTITY_REFERENCE_NODE:
  308. case ELEMENT_NODE:
  309. case ENTITY_NODE:
  310. switch (childNodeType)
  311. {
  312. case ELEMENT_NODE:
  313. case TEXT_NODE:
  314. case COMMENT_NODE:
  315. case PROCESSING_INSTRUCTION_NODE:
  316. case CDATA_SECTION_NODE:
  317. case ENTITY_REFERENCE_NODE:
  318. return;
  319. }
  320. break;
  321. case DOCUMENT_TYPE_NODE:
  322. if (!owner.building)
  323. break;
  324. switch (childNodeType)
  325. {
  326. case COMMENT_NODE:
  327. case PROCESSING_INSTRUCTION_NODE:
  328. return;
  329. }
  330. break;
  331. }
  332. if (owner.checkingWellformedness)
  333. {
  334. throw new DomDOMException(DOMException.HIERARCHY_REQUEST_ERR,
  335. "can't append " +
  336. nodeTypeToString(childNodeType) +
  337. " to node of type " +
  338. nodeTypeToString(nodeType),
  339. this, 0);
  340. }
  341. }
  342. // Here's hoping a good optimizer will detect the case when the
  343. // next several methods are never called, and won't allocate
  344. // object code space of any kind. (Case: not reporting any
  345. // mutation events. We can also remove some static variables
  346. // listed above.)
  347. private void insertionEvent(DomEvent.DomMutationEvent event,
  348. DomNode target)
  349. {
  350. if (owner == null || owner.building)
  351. {
  352. return;
  353. }
  354. boolean doFree = false;
  355. if (event == null)
  356. {
  357. event = getMutationEvent();
  358. }
  359. if (event != null)
  360. {
  361. doFree = true;
  362. }
  363. else
  364. {
  365. event = new DomEvent.DomMutationEvent(null);
  366. }
  367. event.initMutationEvent("DOMNodeInserted",
  368. true /* bubbles */, false /* nocancel */,
  369. this /* related */, null, null, null, (short) 0);
  370. target.dispatchEvent(event);
  371. // XXX should really visit every descendant of 'target'
  372. // and sent a DOMNodeInsertedIntoDocument event to it...
  373. // bleech, there's no way to keep that acceptably fast.
  374. if (doFree)
  375. {
  376. event.target = null;
  377. event.relatedNode = null;
  378. event.currentNode = null;
  379. eventDataLock = false;
  380. } // else we created work for the GC
  381. }
  382. private void removalEvent(DomEvent.DomMutationEvent event,
  383. DomNode target)
  384. {
  385. if (owner == null || owner.building)
  386. {
  387. return;
  388. }
  389. boolean doFree = false;
  390. if (event == null)
  391. {
  392. event = getMutationEvent();
  393. }
  394. if (event != null)
  395. {
  396. doFree = true;
  397. }
  398. else
  399. {
  400. event = new DomEvent.DomMutationEvent(null);
  401. }
  402. event.initMutationEvent("DOMNodeRemoved",
  403. true /* bubbles */, false /* nocancel */,
  404. this /* related */, null, null, null, (short) 0);
  405. target.dispatchEvent(event);
  406. // XXX should really visit every descendant of 'target'
  407. // and sent a DOMNodeRemovedFromDocument event to it...
  408. // bleech, there's no way to keep that acceptably fast.
  409. event.target = null;
  410. event.relatedNode = null;
  411. event.currentNode = null;
  412. if (doFree)
  413. {
  414. eventDataLock = false;
  415. }
  416. // else we created more work for the GC
  417. }
  418. //
  419. // Avoid creating lots of memory management work, by using a simple
  420. // allocation strategy for the mutation event objects that get used
  421. // at least once per tree modification. We can't use stack allocation,
  422. // so we do the next simplest thing -- more or less, static allocation.
  423. // Concurrent notifications should be rare, anyway.
  424. //
  425. // Returns the preallocated object, which needs to be carefully freed,
  426. // or null to indicate the caller needs to allocate their own.
  427. //
  428. static private DomEvent.DomMutationEvent getMutationEvent()
  429. {
  430. synchronized (lockNode)
  431. {
  432. if (eventDataLock)
  433. {
  434. return null;
  435. }
  436. eventDataLock = true;
  437. return mutationEvent;
  438. }
  439. }
  440. // NOTE: this is manually inlined in the insertion
  441. // and removal event methods above; change in sync.
  442. static private void freeMutationEvent()
  443. {
  444. // clear fields to enable GC
  445. mutationEvent.clear();
  446. eventDataLock = false;
  447. }
  448. void setDepth(int depth)
  449. {
  450. this.depth = depth;
  451. for (DomNode ctx = first; ctx != null; ctx = ctx.next)
  452. {
  453. ctx.setDepth(depth + 1);
  454. }
  455. }
  456. /**
  457. * <b>DOM L1</b>
  458. * Appends the specified node to this node's list of children.
  459. * Document subclasses must override this to enforce the restrictions
  460. * that there be only one element and document type child.
  461. *
  462. * <p> Causes a DOMNodeInserted mutation event to be reported.
  463. * Will first cause a DOMNodeRemoved event to be reported if the
  464. * parameter already has a parent. If the new child is a document
  465. * fragment node, both events will be reported for each child of
  466. * the fragment; the order in which children are removed and
  467. * inserted is implementation-specific.
  468. *
  469. * <p> If this DOM has been compiled without mutation event support,
  470. * these events will not be reported.
  471. */
  472. public Node appendChild(Node newChild)
  473. {
  474. try
  475. {
  476. DomNode child = (DomNode) newChild;
  477. if (child.nodeType == DOCUMENT_FRAGMENT_NODE)
  478. {
  479. // Append all nodes in the fragment to this node
  480. for (DomNode ctx = child.first; ctx != null; ctx = ctx.next)
  481. {
  482. checkMisc(ctx);
  483. }
  484. for (DomNode ctx = child.first; ctx != null; )
  485. {
  486. DomNode ctxNext = ctx.next;
  487. appendChild(ctx);
  488. ctx = ctxNext;
  489. }
  490. }
  491. else
  492. {
  493. checkMisc(child);
  494. if (child.parent != null)
  495. {
  496. child.parent.removeChild(child);
  497. }
  498. child.parent = this;
  499. child.index = length++;
  500. child.setDepth(depth + 1);
  501. child.next = null;
  502. if (last == null)
  503. {
  504. first = child;
  505. child.previous = null;
  506. }
  507. else
  508. {
  509. last.next = child;
  510. child.previous = last;
  511. }
  512. last = child;
  513. if (reportMutations)
  514. {
  515. insertionEvent(null, child);
  516. }
  517. }
  518. return child;
  519. }
  520. catch (ClassCastException e)
  521. {
  522. throw new DomDOMException(DOMException.WRONG_DOCUMENT_ERR,
  523. null, newChild, 0);
  524. }
  525. }
  526. /**
  527. * <b>DOM L1</b>
  528. * Inserts the specified node in this node's list of children.
  529. * Document subclasses must override this to enforce the restrictions
  530. * that there be only one element and document type child.
  531. *
  532. * <p> Causes a DOMNodeInserted mutation event to be reported. Will
  533. * first cause a DOMNodeRemoved event to be reported if the newChild
  534. * parameter already has a parent. If the new child is a document
  535. * fragment node, both events will be reported for each child of
  536. * the fragment; the order in which children are removed and inserted
  537. * is implementation-specific.
  538. *
  539. * <p> If this DOM has been compiled without mutation event support,
  540. * these events will not be reported.
  541. */
  542. public Node insertBefore(Node newChild, Node refChild)
  543. {
  544. if (refChild == null)
  545. {
  546. return appendChild(newChild);
  547. }
  548. try
  549. {
  550. DomNode child = (DomNode) newChild;
  551. DomNode ref = (DomNode) refChild;
  552. if (child.nodeType == DOCUMENT_FRAGMENT_NODE)
  553. {
  554. // Append all nodes in the fragment to this node
  555. for (DomNode ctx = child.first; ctx != null; ctx = ctx.next)
  556. {
  557. checkMisc(ctx);
  558. }
  559. for (DomNode ctx = child.first; ctx != null; )
  560. {
  561. DomNode ctxNext = ctx.next;
  562. insertBefore(ctx, ref);
  563. ctx = ctxNext;
  564. }
  565. }
  566. else
  567. {
  568. checkMisc(child);
  569. if (ref == null || ref.parent != this)
  570. {
  571. throw new DomDOMException(DOMException.NOT_FOUND_ERR,
  572. null, ref, 0);
  573. }
  574. if (ref == child)
  575. {
  576. throw new DomDOMException(DOMException.HIERARCHY_REQUEST_ERR,
  577. "can't insert node before itself",
  578. ref, 0);
  579. }
  580. if (child.parent != null)
  581. {
  582. child.parent.removeChild(child);
  583. }
  584. child.parent = this;
  585. int i = ref.index;
  586. child.setDepth(depth + 1);
  587. child.next = ref;
  588. if (ref.previous != null)
  589. {
  590. ref.previous.next = child;
  591. }
  592. child.previous = ref.previous;
  593. ref.previous = child;
  594. if (first == ref)
  595. {
  596. first = child;
  597. }
  598. // index renumbering
  599. for (DomNode ctx = child; ctx != null; ctx = ctx.next)
  600. {
  601. ctx.index = i++;
  602. }
  603. if (reportMutations)
  604. {
  605. insertionEvent(null, child);
  606. }
  607. length++;
  608. }
  609. return child;
  610. }
  611. catch (ClassCastException e)
  612. {
  613. throw new DomDOMException(DOMException.WRONG_DOCUMENT_ERR,
  614. null, newChild, 0);
  615. }
  616. }
  617. /**
  618. * <b>DOM L1</b>
  619. * Replaces the specified node in this node's list of children.
  620. * Document subclasses must override this to test the restrictions
  621. * that there be only one element and document type child.
  622. *
  623. * <p> Causes DOMNodeRemoved and DOMNodeInserted mutation event to be
  624. * reported. Will cause another DOMNodeRemoved event to be reported if
  625. * the newChild parameter already has a parent. These events may be
  626. * delivered in any order, except that the event reporting removal
  627. * from such an existing parent will always be delivered before the
  628. * event reporting its re-insertion as a child of some other node.
  629. * The order in which children are removed and inserted is implementation
  630. * specific.
  631. *
  632. * <p> If your application needs to depend on the in which those removal
  633. * and insertion events are delivered, don't use this API. Instead,
  634. * invoke the removeChild and insertBefore methods directly, to guarantee
  635. * a specific delivery order. Similarly, don't use document fragments,
  636. * Otherwise your application code may not work on a DOM which implements
  637. * this method differently.
  638. *
  639. * <p> If this DOM has been compiled without mutation event support,
  640. * these events will not be reported.
  641. */
  642. public Node replaceChild(Node newChild, Node refChild)
  643. {
  644. try
  645. {
  646. DomNode child = (DomNode) newChild;
  647. DomNode ref = (DomNode) refChild;
  648. DomEvent.DomMutationEvent event = getMutationEvent();
  649. boolean doFree = (event != null);
  650. if (child.nodeType == DOCUMENT_FRAGMENT_NODE)
  651. {
  652. // Append all nodes in the fragment to this node
  653. for (DomNode ctx = child.first; ctx != null; ctx = ctx.next)
  654. {
  655. checkMisc(ctx);
  656. }
  657. if (ref == null || ref.parent != this)
  658. {
  659. throw new DomDOMException(DOMException.NOT_FOUND_ERR,
  660. null, ref, 0);
  661. }
  662. if (reportMutations)
  663. {
  664. removalEvent(event, ref);
  665. }
  666. length--;
  667. length += child.length;
  668. if (child.length == 0)
  669. {
  670. // Removal
  671. if (ref.previous != null)
  672. {
  673. ref.previous.next = ref.next;
  674. }
  675. if (ref.next != null)
  676. {
  677. ref.next.previous = ref.previous;
  678. }
  679. if (first == ref)
  680. {
  681. first = ref.next;
  682. }
  683. if (last == ref)
  684. {
  685. last = ref.previous;
  686. }
  687. }
  688. else
  689. {
  690. int i = ref.index;
  691. for (DomNode ctx = child.first; ctx != null; ctx = ctx.next)
  692. {
  693. // Insertion
  694. ctx.parent = this;
  695. ctx.index = i++;
  696. ctx.setDepth(ref.depth);
  697. if (ctx == child.first)
  698. {
  699. ctx.previous = ref.previous;
  700. }
  701. if (ctx == child.last)
  702. {
  703. ctx.next = ref.next;
  704. }
  705. }
  706. if (first == ref)
  707. {
  708. first = child.first;
  709. }
  710. if (last == ref)
  711. {
  712. last = child.last;
  713. }
  714. }
  715. }
  716. else
  717. {
  718. checkMisc(child);
  719. if (ref == null || ref.parent != this)
  720. {
  721. throw new DomDOMException(DOMException.NOT_FOUND_ERR,
  722. null, ref, 0);
  723. }
  724. if (reportMutations)
  725. {
  726. removalEvent(event, ref);
  727. }
  728. if (child.parent != null)
  729. {
  730. child.parent.removeChild(child);
  731. }
  732. child.parent = this;
  733. child.index = ref.index;
  734. child.setDepth(ref.depth);
  735. if (ref.previous != null)
  736. {
  737. ref.previous.next = child;
  738. }
  739. child.previous = ref.previous;
  740. if (ref.next != null)
  741. {
  742. ref.next.previous = child;
  743. }
  744. child.next = ref.next;
  745. if (first == ref)
  746. {
  747. first = child;
  748. }
  749. if (last == ref)
  750. {
  751. last = child;
  752. }
  753. if (reportMutations)
  754. {
  755. insertionEvent(event, child);
  756. }
  757. if (doFree)
  758. {
  759. freeMutationEvent();
  760. }
  761. }
  762. ref.parent = null;
  763. ref.index = 0;
  764. ref.setDepth(0);
  765. ref.previous = null;
  766. ref.next = null;
  767. return ref;
  768. }
  769. catch (ClassCastException e)
  770. {
  771. throw new DomDOMException(DOMException.WRONG_DOCUMENT_ERR,
  772. null, newChild, 0);
  773. }
  774. }
  775. /**
  776. * <b>DOM L1</b>
  777. * Removes the specified child from this node's list of children,
  778. * or else reports an exception.
  779. *
  780. * <p> Causes a DOMNodeRemoved mutation event to be reported.
  781. *
  782. * <p> If this DOM has been compiled without mutation event support,
  783. * these events will not be reported.
  784. */
  785. public Node removeChild(Node refChild)
  786. {
  787. try
  788. {
  789. DomNode ref = (DomNode) refChild;
  790. if (ref == null || ref.parent != this)
  791. {
  792. throw new DomDOMException(DOMException.NOT_FOUND_ERR,
  793. null, ref, 0);
  794. }
  795. if (readonly && !owner.building)
  796. {
  797. throw new DomDOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
  798. null, this, 0);
  799. }
  800. for (DomNode child = first; child != null; child = child.next)
  801. {
  802. if (child == ref)
  803. {
  804. if (reportMutations)
  805. {
  806. removalEvent(null, child);
  807. }
  808. length--;
  809. if (ref.previous != null)
  810. {
  811. ref.previous.next = ref.next;
  812. }
  813. if (ref.next != null)
  814. {
  815. ref.next.previous = ref.previous;
  816. }
  817. if (first == ref)
  818. {
  819. first = ref.next;
  820. }
  821. if (last == ref)
  822. {
  823. last = ref.previous;
  824. }
  825. // renumber indices
  826. int i = 0;
  827. for (DomNode ctx = first; ctx != null; ctx = ctx.next)
  828. {
  829. ctx.index = i++;
  830. }
  831. ref.parent = null;
  832. ref.setDepth(0);
  833. ref.index = 0;
  834. ref.previous = null;
  835. ref.next = null;
  836. return ref;
  837. }
  838. }
  839. throw new DomDOMException(DOMException.NOT_FOUND_ERR,
  840. "that's no child of mine", refChild, 0);
  841. }
  842. catch (ClassCastException e)
  843. {
  844. throw new DomDOMException(DOMException.WRONG_DOCUMENT_ERR,
  845. null, refChild, 0);
  846. }
  847. }
  848. /**
  849. * <b>DOM L1 (NodeList)</b>
  850. * Returns the item with the specified index in this NodeList,
  851. * else null.
  852. */
  853. public Node item(int index)
  854. {
  855. DomNode child = first;
  856. int count = 0;
  857. while (child != null && count < index)
  858. {
  859. child = child.next;
  860. count++;
  861. }
  862. return child;
  863. }
  864. /**
  865. * <b>DOM L1 (NodeList)</b>
  866. * Returns the number of elements in this NodeList.
  867. * (Note that many interfaces have a "Length" property, not just
  868. * NodeList, and if a node subtype must implement one of those,
  869. * it will also need to override getChildNodes.)
  870. */
  871. public int getLength()
  872. {
  873. return length;
  874. }
  875. /**
  876. * Minimize extra space consumed by this node to hold children and event
  877. * listeners.
  878. */
  879. public void trimToSize()
  880. {
  881. }
  882. /**
  883. * <b>DOM L1</b>
  884. * Returns the previous sibling, if one is known.
  885. */
  886. public Node getNextSibling()
  887. {
  888. return next;
  889. }
  890. /**
  891. * <b>DOM L1</b>
  892. * Returns the previous sibling, if one is known.
  893. */
  894. public Node getPreviousSibling()
  895. {
  896. return previous;
  897. }
  898. /**
  899. * <b>DOM L1</b>
  900. * Returns the parent node, if one is known.
  901. */
  902. public Node getParentNode()
  903. {
  904. return parent;
  905. }
  906. /**
  907. * <b>DOM L2</b>
  908. * Consults the DOM implementation to determine if the requested
  909. * feature is supported. DocumentType subclasses must override
  910. * this method, and associate themselves directly with the
  911. * DOMImplementation node used. (This method relies on being able
  912. * to access the DOMImplementation from the owner document, but
  913. * DocumentType nodes can be created without an owner.)
  914. */
  915. public boolean isSupported(String feature, String version)
  916. {
  917. Document doc = owner;
  918. DOMImplementation impl = null;
  919. if (doc == null && nodeType == DOCUMENT_NODE)
  920. {
  921. doc = (Document) this;
  922. }
  923. if (doc == null)
  924. {
  925. // possible for DocumentType
  926. throw new IllegalStateException ("unbound ownerDocument");
  927. }
  928. impl = doc.getImplementation();
  929. return impl.hasFeature(feature, version);
  930. }
  931. /**
  932. * <b>DOM L1 (modified in L2)</b>
  933. * Returns the owner document. This is only null for Document nodes,
  934. * and (new in L2) for DocumentType nodes which have not yet been
  935. * associated with the rest of their document.
  936. */
  937. final public Document getOwnerDocument()
  938. {
  939. return owner;
  940. }
  941. /**
  942. * <b>DOM L1</b>
  943. * Does nothing; this must be overridden (along with the
  944. * getNodeValue method) for nodes with a non-null defined value.
  945. */
  946. public void setNodeValue(String value)
  947. {
  948. }
  949. /**
  950. * <b>DOM L1</b>
  951. * Returns null; this must be overridden for nodes types with
  952. * a defined value, along with the setNodeValue method.
  953. */
  954. public String getNodeValue()
  955. {
  956. return null;
  957. }
  958. /** This forces GCJ compatibility.
  959. * Without this method GCJ is unable to compile to byte code.
  960. */
  961. public final short getNodeType()
  962. {
  963. return nodeType;
  964. }
  965. /** This forces GCJ compatibility.
  966. * Without this method GCJ seems unable to natively compile GNUJAXP.
  967. */
  968. public abstract String getNodeName();
  969. /**
  970. * <b>DOM L2</b>
  971. * Does nothing; this must be overridden (along with the
  972. * getPrefix method) for element and attribute nodes.
  973. */
  974. public void setPrefix(String prefix)
  975. {
  976. }
  977. /**
  978. * <b>DOM L2</b>
  979. * Returns null; this must be overridden for element and
  980. * attribute nodes.
  981. */
  982. public String getPrefix()
  983. {
  984. return null;
  985. }
  986. /**
  987. * <b>DOM L2</b>
  988. * Returns null; this must be overridden for element and
  989. * attribute nodes.
  990. */
  991. public String getNamespaceURI()
  992. {
  993. return null;
  994. }
  995. /**
  996. * <b>DOM L2</b>
  997. * Returns the node name; this must be overridden for element and
  998. * attribute nodes.
  999. */
  1000. public String getLocalName()
  1001. {
  1002. return null;
  1003. }
  1004. /**
  1005. * <b>DOM L1</b>
  1006. * Returns a clone of this node which optionally includes cloned
  1007. * versions of child nodes. Clones are always mutable, except for
  1008. * entity reference nodes.
  1009. */
  1010. public Node cloneNode(boolean deep)
  1011. {
  1012. if (deep)
  1013. {
  1014. return cloneNodeDeepInternal(true, null);
  1015. }
  1016. DomNode node = (DomNode) clone();
  1017. if (nodeType == ENTITY_REFERENCE_NODE)
  1018. {
  1019. node.makeReadonly();
  1020. }
  1021. notifyUserDataHandlers(UserDataHandler.NODE_CLONED, this, node);
  1022. return node;
  1023. }
  1024. /**
  1025. * Returns a deep clone of this node.
  1026. */
  1027. private DomNode cloneNodeDeepInternal(boolean root, DomDocument doc)
  1028. {
  1029. DomNode node = (DomNode) clone();
  1030. boolean building = false; // Never used unless root is true
  1031. if (root)
  1032. {
  1033. doc = (nodeType == DOCUMENT_NODE) ? (DomDocument) node : node.owner;
  1034. building = doc.building;
  1035. doc.building = true; // Permit certain structural rules
  1036. }
  1037. node.owner = doc;
  1038. for (DomNode ctx = first; ctx != null; ctx = ctx.next)
  1039. {
  1040. DomNode newChild = ctx.cloneNodeDeepInternal(false, doc);
  1041. node.appendChild(newChild);
  1042. }
  1043. if (nodeType == ENTITY_REFERENCE_NODE)
  1044. {
  1045. node.makeReadonly();
  1046. }
  1047. if (root)
  1048. {
  1049. doc.building = building;
  1050. }
  1051. notifyUserDataHandlers(UserDataHandler.NODE_CLONED, this, node);
  1052. return node;
  1053. }
  1054. void notifyUserDataHandlers(short op, Node src, Node dst)
  1055. {
  1056. if (userDataHandlers != null)
  1057. {
  1058. for (Iterator i = userDataHandlers.entrySet().iterator(); i.hasNext(); )
  1059. {
  1060. Map.Entry entry = (Map.Entry) i.next();
  1061. String key = (String) entry.getKey();
  1062. UserDataHandler handler = (UserDataHandler) entry.getValue();
  1063. Object data = userData.get(key);
  1064. handler.handle(op, key, data, src, dst);
  1065. }
  1066. }
  1067. }
  1068. /**
  1069. * Clones this node; roughly equivalent to cloneNode(false).
  1070. * Element subclasses must provide a new implementation which
  1071. * invokes this method to handle the basics, and then arranges
  1072. * to clone any element attributes directly. Attribute subclasses
  1073. * must make similar arrangements, ensuring that existing ties to
  1074. * elements are broken by cloning.
  1075. */
  1076. public Object clone()
  1077. {
  1078. try
  1079. {
  1080. DomNode node = (DomNode) super.clone();
  1081. node.parent = null;
  1082. node.depth = 0;
  1083. node.index = 0;
  1084. node.length = 0;
  1085. node.first = null;
  1086. node.last = null;
  1087. node.previous = null;
  1088. node.next = null;
  1089. node.readonly = false;
  1090. node.listeners = new HashSet();
  1091. node.nListeners = 0;
  1092. return node;
  1093. }
  1094. catch (CloneNotSupportedException x)
  1095. {
  1096. throw new Error("clone didn't work");
  1097. }
  1098. }
  1099. // the elements-by-tagname stuff is needed for both
  1100. // elements and documents ... this is in lieu of a
  1101. // common base class between Node and NodeNS.
  1102. /**
  1103. * <b>DOM L1</b>
  1104. * Creates a NodeList giving array-style access to elements with
  1105. * the specified name. Access is fastest if indices change by
  1106. * small values, and the DOM is not modified.
  1107. */
  1108. public NodeList getElementsByTagName(String tag)
  1109. {
  1110. return new ShadowList(null, tag);
  1111. }
  1112. /**
  1113. * <b>DOM L2</b>
  1114. * Creates a NodeList giving array-style access to elements with
  1115. * the specified namespace and local name. Access is fastest if
  1116. * indices change by small values, and the DOM is not modified.
  1117. */
  1118. public NodeList getElementsByTagNameNS(String namespace, String local)
  1119. {
  1120. return new ShadowList(namespace, local);
  1121. }
  1122. //
  1123. // This shadow class is GC-able even when the live list it shadows
  1124. // can't be, because of event registration hookups. Its finalizer
  1125. // makes that live list become GC-able.
  1126. //
  1127. final class ShadowList
  1128. implements NodeList
  1129. {
  1130. private LiveNodeList liveList;
  1131. ShadowList(String ns, String local)
  1132. {
  1133. liveList = new LiveNodeList(ns, local);
  1134. }
  1135. public void finalize()
  1136. {
  1137. liveList.detach();
  1138. liveList = null;
  1139. }
  1140. public Node item(int index)
  1141. {
  1142. return liveList.item(index);
  1143. }
  1144. public int getLength()
  1145. {
  1146. return liveList.getLength();
  1147. }
  1148. }
  1149. final class LiveNodeList
  1150. implements NodeList, EventListener, NodeFilter
  1151. {
  1152. private final boolean matchAnyURI;
  1153. private final boolean matchAnyName;
  1154. private final String elementURI;
  1155. private final String elementName;
  1156. private DomIterator current;
  1157. private int lastIndex;
  1158. LiveNodeList(String uri, String name)
  1159. {
  1160. elementURI = uri;
  1161. elementName = name;
  1162. matchAnyURI = "*".equals(uri);
  1163. matchAnyName = "*".equals(name);
  1164. DomNode.this.addEventListener("DOMNodeInserted", this, true);
  1165. DomNode.this.addEventListener("DOMNodeRemoved", this, true);
  1166. }
  1167. void detach()
  1168. {
  1169. if (current != null)
  1170. current.detach();
  1171. current = null;
  1172. DomNode.this.removeEventListener("DOMNodeInserted", this, true);
  1173. DomNode.this.removeEventListener("DOMNodeRemoved", this, true);
  1174. }
  1175. public short acceptNode(Node element)
  1176. {
  1177. if (element == DomNode.this)
  1178. {
  1179. return FILTER_SKIP;
  1180. }
  1181. // use namespace-aware matching ...
  1182. if (elementURI != null)
  1183. {
  1184. if (!(matchAnyURI
  1185. || elementURI.equals(element.getNamespaceURI())))
  1186. {
  1187. return FILTER_SKIP;
  1188. }
  1189. if (!(matchAnyName
  1190. || elementName.equals(element.getLocalName())))
  1191. {
  1192. return FILTER_SKIP;
  1193. }
  1194. // ... or qName-based kind.
  1195. }
  1196. else
  1197. {
  1198. if (!(matchAnyName
  1199. || elementName.equals(element.getNodeName())))
  1200. {
  1201. return FILTER_SKIP;
  1202. }
  1203. }
  1204. return FILTER_ACCEPT;
  1205. }
  1206. private DomIterator createIterator()
  1207. {
  1208. return new DomIterator(DomNode.this,
  1209. NodeFilter.SHOW_ELEMENT,
  1210. this, /* filter */
  1211. true /* expand entity refs */
  1212. );
  1213. }
  1214. public void handleEvent(Event e)
  1215. {
  1216. MutationEvent mutation = (MutationEvent) e;
  1217. Node related = mutation.getRelatedNode();
  1218. // XXX if it's got children ... check all kids too, they
  1219. // will invalidate our saved index
  1220. if (related.getNodeType() != Node.ELEMENT_NODE ||
  1221. related.getNodeName() != elementName ||
  1222. related.getNamespaceURI() != elementURI)
  1223. {
  1224. return;
  1225. }
  1226. if (current != null)
  1227. current.detach();
  1228. current = null;
  1229. }
  1230. public Node item(int index)
  1231. {
  1232. if (current == null)
  1233. {
  1234. current = createIterator();
  1235. lastIndex = -1;
  1236. }
  1237. // last node or before? go backwards
  1238. if (index <= lastIndex) {
  1239. while (index != lastIndex) {
  1240. current.previousNode ();
  1241. lastIndex--;
  1242. }
  1243. Node ret = current.previousNode ();
  1244. current.detach();
  1245. current = null;
  1246. return ret;
  1247. }
  1248. // somewhere after last node
  1249. while (++lastIndex != index)
  1250. current.nextNode ();
  1251. Node ret = current.nextNode ();
  1252. current.detach();
  1253. current = null;
  1254. return ret;
  1255. }
  1256. public int getLength()
  1257. {
  1258. int retval = 0;
  1259. NodeIterator iter = createIterator();
  1260. while (iter.nextNode() != null)
  1261. {
  1262. retval++;
  1263. }
  1264. iter.detach();
  1265. return retval;
  1266. }
  1267. }
  1268. //
  1269. // EventTarget support
  1270. //
  1271. static final class ListenerRecord
  1272. {
  1273. String type;
  1274. EventListener listener;
  1275. boolean useCapture;
  1276. // XXX use JDK 1.2 java.lang.ref.WeakReference to listener,
  1277. // and we can both get rid of "shadow" classes and remove
  1278. // the need for applications to apply similar trix ... but
  1279. // JDK 1.2 support isn't generally available yet
  1280. ListenerRecord(String type, EventListener listener, boolean useCapture)
  1281. {
  1282. this.type = type.intern();
  1283. this.listener = listener;
  1284. this.useCapture = useCapture;
  1285. }
  1286. public boolean equals(Object o)
  1287. {
  1288. ListenerRecord rec = (ListenerRecord)o;
  1289. return listener == rec.listener
  1290. && useCapture == rec.useCapture
  1291. && type == rec.type;
  1292. }
  1293. public int hashCode()
  1294. {
  1295. return listener.hashCode() ^ type.hashCode();
  1296. }
  1297. }
  1298. /**
  1299. * <b>DOM L2 (Events)</b>
  1300. * Returns an instance of the specified type of event object.
  1301. * Understands about DOM Mutation, HTML, and UI events.
  1302. *
  1303. * <p>If the name of the event type begins with "USER-", then an object
  1304. * implementing the "Event" class will be returned; this provides a
  1305. * limited facility for application-defined events to use the DOM event
  1306. * infrastructure. Alternatively, use one of the standard DOM event
  1307. * classes and initialize it using use such a "USER-" event type name;
  1308. * or defin, instantiate, and initialize an application-specific subclass
  1309. * of DomEvent and pass that to dispatchEvent().
  1310. *
  1311. * @param eventType Identifies the particular DOM feature module
  1312. * defining the type of event, such as "MutationEvents".
  1313. * <em>The event "name" is a different kind of "type".</em>
  1314. */
  1315. public Event createEvent(String eventType)
  1316. {
  1317. eventType = eventType.toLowerCase();
  1318. if ("mutationevents".equals(eventType))
  1319. {
  1320. return new DomEvent.DomMutationEvent(null);
  1321. }
  1322. if ("htmlevents".equals(eventType)
  1323. || "events".equals(eventType)
  1324. || "user-events".equals(eventType))
  1325. {
  1326. return new DomEvent(null);
  1327. }
  1328. if ("uievents".equals(eventType))
  1329. {
  1330. return new DomEvent.DomUIEvent(null);
  1331. }
  1332. // mouse events
  1333. throw new DomDOMException(DOMException.NOT_SUPPORTED_ERR,
  1334. eventType, null, 0);
  1335. }
  1336. /**
  1337. * <b>DOM L2 (Events)</b>
  1338. * Registers an event listener's interest in a class of events.
  1339. */
  1340. public final void addEventListener(String type,
  1341. EventListener listener,
  1342. boolean useCapture)
  1343. {
  1344. // prune duplicates
  1345. ListenerRecord record;
  1346. record = new ListenerRecord(type, listener, useCapture);
  1347. listeners.add(record);
  1348. nListeners = listeners.size();
  1349. }
  1350. // XXX this exception should be discarded from DOM
  1351. // this class can be instantiated, unlike the one in the spec
  1352. static final class DomEventException
  1353. extends EventException
  1354. {
  1355. DomEventException()
  1356. {
  1357. super(UNSPECIFIED_EVENT_TYPE_ERR, "unspecified event type");
  1358. }
  1359. }
  1360. /**
  1361. * <b>DOM L2 (Events)</b>
  1362. * Delivers an event to all relevant listeners, returning true if the
  1363. * caller should perform their default action. Note that the event
  1364. * must have been provided by the createEvent() method on this
  1365. * class, else it can't be dispatched.
  1366. *
  1367. * @see #createEvent
  1368. *
  1369. * @exception NullPointerException When a null event is passed.
  1370. * @exception ClassCastException When the event wasn't provided by
  1371. * the createEvent method, or otherwise isn't a DomEvent.
  1372. * @exception EventException If the event type wasn't specified
  1373. */
  1374. public final boolean dispatchEvent(Event event)
  1375. throws EventException
  1376. {
  1377. DomEvent e = (DomEvent) event;
  1378. DomNode[] ancestors = null;
  1379. int ancestorMax = 0;
  1380. boolean haveDispatchDataLock = false;
  1381. if (e.type == null)
  1382. {
  1383. throw new DomEventException();
  1384. }
  1385. e.doDefault = true;
  1386. e.target = this;
  1387. //
  1388. // Typical case: one nonrecursive dispatchEvent call at a time
  1389. // for this class. If that's our case, we can avoid allocating
  1390. // garbage, which is overall a big win. Even with advanced GCs
  1391. // that deal well with short-lived garbage, and wayfast allocators,
  1392. // it still helps.
  1393. //
  1394. // Remember -- EVERY mutation goes though here at least once.
  1395. //
  1396. // When populating a DOM tree, trying to send mutation events is
  1397. // the primary cost; this dominates the critical path.
  1398. //
  1399. try
  1400. {
  1401. DomNode current;
  1402. int index;
  1403. boolean haveAncestorRegistrations = false;
  1404. ListenerRecord[] notificationSet;
  1405. int ancestorLen;
  1406. synchronized (lockNode)
  1407. {
  1408. if (!dispatchDataLock)
  1409. {
  1410. haveDispatchDataLock = dispatchDataLock = true;
  1411. notificationSet = DomNode.notificationSet;
  1412. ancestors = DomNode.ancestors;
  1413. }
  1414. else
  1415. {
  1416. notificationSet = new ListenerRecord[NOTIFICATIONS_INIT];
  1417. ancestors = new DomNode[ANCESTORS_INIT];
  1418. }
  1419. ancestorLen = ancestors.length;
  1420. }
  1421. // Climb to the top of this subtree and handle capture, letting
  1422. // each node (from the top down) capture until one stops it or
  1423. // until we get to this one.
  1424. current = (parent == null) ? this : parent;
  1425. if (current.depth >= ANCESTORS_INIT)
  1426. {
  1427. DomNode[] newants = new DomNode[current.depth + 1];
  1428. System.arraycopy(ancestors, 0, newants, 0, ancestors.length);
  1429. ancestors = newants;
  1430. ancestorLen = ancestors.length;
  1431. }
  1432. for (index = 0; index < ancestorLen; index++)
  1433. {
  1434. if (current == null || current.depth == 0)
  1435. break;
  1436. if (current.nListeners != 0)
  1437. {
  1438. haveAncestorRegistrations = true;
  1439. }
  1440. ancestors [index] = current;
  1441. current = current.parent;
  1442. }
  1443. if (current.depth > 0)
  1444. {
  1445. throw new RuntimeException("dispatchEvent capture stack size");
  1446. }
  1447. ancestorMax = index;
  1448. e.stop = false;
  1449. if (haveAncestorRegistrations)
  1450. {
  1451. e.eventPhase = Event.CAPTURING_PHASE;
  1452. while (!e.stop && index-- > 0)
  1453. {
  1454. current = ancestors [index];
  1455. if (current.nListeners != 0)
  1456. {
  1457. notifyNode(e, current, true, notificationSet);
  1458. }
  1459. }
  1460. }
  1461. // Always deliver events to the target node (this)
  1462. // unless stopPropagation was called. If we saw
  1463. // no registrations yet (typical!), we never will.
  1464. if (!e.stop && nListeners != 0)
  1465. {
  1466. e.eventPhase = Event.AT_TARGET;
  1467. notifyNode (e, this, false, notificationSet);
  1468. }
  1469. else if (!haveAncestorRegistrations)
  1470. {
  1471. e.stop = true;
  1472. }
  1473. // If the event bubbles and propagation wasn't halted,
  1474. // walk back up the ancestor list. Stop bubbling when
  1475. // any bubbled event handler stops it.
  1476. if (!e.stop && e.bubbles)
  1477. {
  1478. e.eventPhase = Event.BUBBLING_PHASE;
  1479. for (index = 0;
  1480. !e.stop
  1481. && index < ancestorMax
  1482. && (current = ancestors[index]) != null;
  1483. index++)
  1484. {
  1485. if (current.nListeners != 0)
  1486. {
  1487. notifyNode(e, current, false, notificationSet);
  1488. }
  1489. }
  1490. }
  1491. e.eventPhase = 0;
  1492. // Caller chooses whether to perform the default
  1493. // action based on return from this method.
  1494. return e.doDefault;
  1495. }
  1496. finally
  1497. {
  1498. if (haveDispatchDataLock)
  1499. {
  1500. // synchronize to force write ordering
  1501. synchronized (lockNode)
  1502. {
  1503. // null out refs to ensure they'll be GC'd
  1504. for (int i = 0; i < ancestorMax; i++)
  1505. {
  1506. ancestors [i] = null;
  1507. }
  1508. // notificationSet handled by notifyNode
  1509. dispatchDataLock = false;
  1510. }
  1511. }
  1512. }
  1513. }
  1514. private void notifyNode(DomEvent e,
  1515. DomNode current,
  1516. boolean capture,
  1517. ListenerRecord[] notificationSet)
  1518. {
  1519. int count = 0;
  1520. Iterator iter;
  1521. iter = current.listeners.iterator();
  1522. // do any of this set of listeners get notified?
  1523. while (iter.hasNext())
  1524. {
  1525. ListenerRecord rec = (ListenerRecord)iter.next();
  1526. if (rec.useCapture != capture)
  1527. {
  1528. continue;
  1529. }
  1530. if (!e.type.equals (rec.type))
  1531. {
  1532. continue;
  1533. }
  1534. if (count >= notificationSet.length)
  1535. {
  1536. // very simple growth algorithm
  1537. int len = Math.max(notificationSet.length, 1);
  1538. ListenerRecord[] tmp = new ListenerRecord[len * 2];
  1539. System.arraycopy(notificationSet, 0, tmp, 0,
  1540. notificationSet.length);
  1541. notificationSet = tmp;
  1542. }
  1543. notificationSet[count++] = rec;
  1544. }
  1545. iter = null;
  1546. // Notify just those listeners
  1547. e.currentNode = current;
  1548. for (int i = 0; i < count; i++)
  1549. {
  1550. try
  1551. {
  1552. iter = current.listeners.iterator();
  1553. // Late in the DOM CR process (3rd or 4th CR?) the
  1554. // removeEventListener spec became asymmetric with respect
  1555. // to addEventListener ... effect is now immediate.
  1556. while (iter.hasNext())
  1557. {
  1558. ListenerRecord rec = (ListenerRecord)iter.next();
  1559. if (rec.equals(notificationSet[i]))
  1560. {
  1561. notificationSet[i].listener.handleEvent(e);
  1562. break;
  1563. }
  1564. }
  1565. iter = null;
  1566. }
  1567. catch (Exception x)
  1568. {
  1569. // ignore all exceptions
  1570. }
  1571. notificationSet[i] = null; // free for GC
  1572. }
  1573. }
  1574. /**
  1575. * <b>DOM L2 (Events)</b>
  1576. * Unregisters an event listener.
  1577. */
  1578. public final void removeEventListener(String type,
  1579. EventListener listener,
  1580. boolean useCapture)
  1581. {
  1582. listeners.remove(new ListenerRecord(type, listener, useCapture));
  1583. nListeners = listeners.size();
  1584. // no exceptions reported
  1585. }
  1586. /**
  1587. * <b>DOM L1 (relocated in DOM L2)</b>
  1588. * In this node and all contained nodes (including attributes if
  1589. * relevant) merge adjacent text nodes. This is done while ignoring
  1590. * text which happens to use CDATA delimiters).
  1591. */
  1592. public final void normalize()
  1593. {
  1594. // Suspend readonly status
  1595. boolean saved = readonly;
  1596. readonly = false;
  1597. for (DomNode ctx = first; ctx != null; ctx = ctx.next)
  1598. {
  1599. boolean saved2 = ctx.readonly;
  1600. ctx.readonly = false;
  1601. switch (ctx.nodeType)
  1602. {
  1603. case TEXT_NODE:
  1604. case CDATA_SECTION_NODE:
  1605. while (ctx.next != null &&
  1606. (ctx.next.nodeType == TEXT_NODE ||
  1607. ctx.next.nodeType == CDATA_SECTION_NODE))
  1608. {
  1609. Text text = (Text) ctx;
  1610. text.appendData(ctx.next.getNodeValue());
  1611. removeChild(ctx.next);
  1612. }
  1613. break;
  1614. case ELEMENT_NODE:
  1615. NamedNodeMap attrs = ctx.getAttributes();
  1616. int len = attrs.getLength();
  1617. for (int i = 0; i < len; i++)
  1618. {
  1619. DomNode attr = (DomNode) attrs.item(i);
  1620. boolean saved3 = attr.readonly;
  1621. attr.readonly = false;
  1622. attr.normalize();
  1623. attr.readonly = saved3;
  1624. }
  1625. // Fall through
  1626. case DOCUMENT_NODE:
  1627. case DOCUMENT_FRAGMENT_NODE:
  1628. case ATTRIBUTE_NODE:
  1629. case ENTITY_REFERENCE_NODE:
  1630. ctx.normalize();
  1631. break;
  1632. }
  1633. ctx.readonly = saved2;
  1634. }
  1635. readonly = saved;
  1636. }
  1637. /**
  1638. * Returns true iff node types match, and either (a) both nodes have no
  1639. * namespace and their getNodeName() values are the same, or (b) both
  1640. * nodes have the same getNamespaceURI() and same getLocalName() values.
  1641. *
  1642. * <p>Note that notion of a "Per-Element-Type" attribute name scope, as
  1643. * found in a non-normative appendix of the XML Namespaces specification,
  1644. * is not supported here. Your application must implement that notion,
  1645. * typically by not bothering to check nameAndTypeEquals for attributes
  1646. * without namespace URIs unless you already know their elements are
  1647. * nameAndTypeEquals.
  1648. */
  1649. public boolean nameAndTypeEquals(Node other)
  1650. {
  1651. if (other == this)
  1652. {
  1653. return true;
  1654. }
  1655. // node types must match
  1656. if (nodeType != other.getNodeType())
  1657. {
  1658. return false;
  1659. }
  1660. // if both have namespaces, do a "full" comparision
  1661. // this is a "global" partition
  1662. String ns1 = this.getNamespaceURI();
  1663. String ns2 = other.getNamespaceURI();
  1664. if (ns1 != null && ns2 != null)
  1665. {
  1666. return ns1.equals(ns2) &&
  1667. equal(getLocalName(), other.getLocalName());
  1668. }
  1669. // if neither has a namespace, this is a "no-namespace" name.
  1670. if (ns1 == null && ns2 == null)
  1671. {
  1672. if (!getNodeName().equals(other.getNodeName()))
  1673. {
  1674. return false;
  1675. }
  1676. // can test the non-normative "per-element-type" scope here.
  1677. // if this is an attribute node and both nodes have been bound
  1678. // to elements (!!), then return the nameAndTypeEquals()
  1679. // comparison of those elements.
  1680. return true;
  1681. }
  1682. // otherwise they're unequal: one scoped, one not.
  1683. return false;
  1684. }
  1685. // DOM Level 3 methods
  1686. public String getBaseURI()
  1687. {
  1688. return (parent != null) ? parent.getBaseURI() : null;
  1689. }
  1690. public short compareDocumentPosition(Node other)
  1691. throws DOMException
  1692. {
  1693. return (short) compareTo(other);
  1694. }
  1695. /**
  1696. * DOM nodes have a natural ordering: document order.
  1697. */
  1698. public final int compareTo(Object other)
  1699. {
  1700. if (other instanceof DomNode)
  1701. {
  1702. DomNode n1 = this;
  1703. DomNode n2 = (DomNode) other;
  1704. if (n1.owner != n2.owner)
  1705. {
  1706. return 0;
  1707. }
  1708. int d1 = n1.depth, d2 = n2.depth;
  1709. int delta = d1 - d2;
  1710. while (d1 > d2)
  1711. {
  1712. n1 = n1.parent;
  1713. d1--;
  1714. }
  1715. while (d2 > d1)
  1716. {
  1717. n2 = n2.parent;
  1718. d2--;
  1719. }
  1720. int c = compareTo2(n1, n2);
  1721. return (c != 0) ? c : delta;
  1722. }
  1723. return 0;
  1724. }
  1725. /**
  1726. * Compare two nodes at the same depth.
  1727. */
  1728. final int compareTo2(DomNode n1, DomNode n2)
  1729. {
  1730. if (n1 == n2 || n1.depth == 0 || n2.depth == 0)
  1731. {
  1732. return 0;
  1733. }
  1734. int c = compareTo2(n1.parent, n2.parent);
  1735. return (c != 0) ? c : n1.index - n2.index;
  1736. }
  1737. public final String getTextContent()
  1738. throws DOMException
  1739. {
  1740. return getTextContent(true);
  1741. }
  1742. final String getTextContent(boolean topLevel)
  1743. throws DOMException
  1744. {
  1745. switch (nodeType)
  1746. {
  1747. case ELEMENT_NODE:
  1748. case ENTITY_NODE:
  1749. case ENTITY_REFERENCE_NODE:
  1750. case DOCUMENT_FRAGMENT_NODE:
  1751. CPStringBuilder buffer = new CPStringBuilder();
  1752. for (DomNode ctx = first; ctx != null; ctx = ctx.next)
  1753. {
  1754. String textContent = ctx.getTextContent(false);
  1755. if (textContent != null)
  1756. {
  1757. buffer.append(textContent);
  1758. }
  1759. }
  1760. return buffer.toString();
  1761. case TEXT_NODE:
  1762. case CDATA_SECTION_NODE:
  1763. if (((Text) this).isElementContentWhitespace())
  1764. {
  1765. return "";
  1766. }
  1767. return getNodeValue();
  1768. case ATTRIBUTE_NODE:
  1769. return getNodeValue();
  1770. case COMMENT_NODE:
  1771. case PROCESSING_INSTRUCTION_NODE:
  1772. return topLevel ? getNodeValue() : "";
  1773. default:
  1774. return null;
  1775. }
  1776. }
  1777. public void setTextContent(String textContent)
  1778. throws DOMException
  1779. {
  1780. switch (nodeType)
  1781. {
  1782. case ELEMENT_NODE:
  1783. case ATTRIBUTE_NODE:
  1784. case ENTITY_NODE:
  1785. case ENTITY_REFERENCE_NODE:
  1786. case DOCUMENT_FRAGMENT_NODE:
  1787. for (DomNode ctx = first; ctx != null; )
  1788. {
  1789. DomNode n = ctx.next;
  1790. removeChild(ctx);
  1791. ctx = n;
  1792. }
  1793. if (textContent != null)
  1794. {
  1795. Text text = owner.createTextNode(textContent);
  1796. appendChild(text);
  1797. }
  1798. break;
  1799. case TEXT_NODE:
  1800. case CDATA_SECTION_NODE:
  1801. case COMMENT_NODE:
  1802. case PROCESSING_INSTRUCTION_NODE:
  1803. setNodeValue(textContent);
  1804. break;
  1805. }
  1806. }
  1807. public boolean isSameNode(Node other)
  1808. {
  1809. return this == other;
  1810. }
  1811. public String lookupPrefix(String namespaceURI)
  1812. {
  1813. return (parent == null || parent == owner) ? null :
  1814. parent.lookupPrefix(namespaceURI);
  1815. }
  1816. public boolean isDefaultNamespace(String namespaceURI)
  1817. {
  1818. return (parent == null || parent == owner) ? false :
  1819. parent.isDefaultNamespace(namespaceURI);
  1820. }
  1821. public String lookupNamespaceURI(String prefix)
  1822. {
  1823. return (parent == null || parent == owner) ? null :
  1824. parent.lookupNamespaceURI(prefix);
  1825. }
  1826. public boolean isEqualNode(Node arg)
  1827. {
  1828. if (this == arg)
  1829. return true;
  1830. if (arg == null)
  1831. return false;
  1832. if (nodeType != arg.getNodeType())
  1833. return false;
  1834. switch (nodeType)
  1835. {
  1836. case ELEMENT_NODE:
  1837. case ATTRIBUTE_NODE:
  1838. if (!equal(getLocalName(), arg.getLocalName()) ||
  1839. !equal(getNamespaceURI(), arg.getNamespaceURI()))
  1840. return false;
  1841. break;
  1842. case PROCESSING_INSTRUCTION_NODE:
  1843. if (!equal(getNodeName(), arg.getNodeName()) ||
  1844. !equal(getNodeValue(), arg.getNodeValue()))
  1845. return false;
  1846. break;
  1847. case COMMENT_NODE:
  1848. case TEXT_NODE:
  1849. case CDATA_SECTION_NODE:
  1850. if (!equal(getNodeValue(), arg.getNodeValue()))
  1851. return false;
  1852. break;
  1853. }
  1854. // Children
  1855. Node argCtx = arg.getFirstChild();
  1856. getFirstChild(); // because of DomAttr lazy children
  1857. DomNode ctx = first;
  1858. for (; ctx != null && argCtx != null; ctx = ctx.next)
  1859. {
  1860. if (nodeType == DOCUMENT_NODE)
  1861. {
  1862. // Ignore whitespace outside document element
  1863. while (ctx != null && ctx.nodeType == TEXT_NODE)
  1864. ctx = ctx.next;
  1865. while (argCtx != null && ctx.getNodeType() == TEXT_NODE)
  1866. argCtx = argCtx.getNextSibling();
  1867. if (ctx == null && argCtx != null)
  1868. return false;
  1869. else if (argCtx == null && ctx != null)
  1870. return false;
  1871. }
  1872. if (!ctx.isEqualNode(argCtx))
  1873. return false;
  1874. argCtx = argCtx.getNextSibling();
  1875. }
  1876. if (ctx != null || argCtx != null)
  1877. return false;
  1878. // TODO DocumentType
  1879. return true;
  1880. }
  1881. boolean equal(String arg1, String arg2)
  1882. {
  1883. return ((arg1 == null && arg2 == null) ||
  1884. (arg1 != null && arg1.equals(arg2)));
  1885. }
  1886. public Object getFeature(String feature, String version)
  1887. {
  1888. DOMImplementation impl = (nodeType == DOCUMENT_NODE) ?
  1889. ((Document) this).getImplementation() : owner.getImplementation();
  1890. if (impl.hasFeature(feature, version))
  1891. {
  1892. return this;
  1893. }
  1894. return null;
  1895. }
  1896. public Object setUserData(String key, Object data, UserDataHandler handler)
  1897. {
  1898. if (userData == null)
  1899. {
  1900. userData = new HashMap();
  1901. }
  1902. if (handler != null)
  1903. {
  1904. if (userDataHandlers == null)
  1905. {
  1906. userDataHandlers = new HashMap();
  1907. }
  1908. userDataHandlers.put(key, handler);
  1909. }
  1910. return userData.put(key, data);
  1911. }
  1912. public Object getUserData(String key)
  1913. {
  1914. if (userData == null)
  1915. {
  1916. return null;
  1917. }
  1918. return userData.get(key);
  1919. }
  1920. public String toString()
  1921. {
  1922. String nodeName = getNodeName();
  1923. String nodeValue = getNodeValue();
  1924. CPStringBuilder buf = new CPStringBuilder(getClass().getName());
  1925. buf.append('[');
  1926. if (nodeName != null)
  1927. {
  1928. buf.append(nodeName);
  1929. }
  1930. if (nodeValue != null)
  1931. {
  1932. if (nodeName != null)
  1933. {
  1934. buf.append('=');
  1935. }
  1936. buf.append('\'');
  1937. buf.append(encode(nodeValue));
  1938. buf.append('\'');
  1939. }
  1940. buf.append(']');
  1941. return buf.toString();
  1942. }
  1943. String encode(String value)
  1944. {
  1945. CPStringBuilder buf = null;
  1946. int len = value.length();
  1947. for (int i = 0; i < len; i++)
  1948. {
  1949. char c = value.charAt(i);
  1950. if (c == '\n')
  1951. {
  1952. if (buf == null)
  1953. {
  1954. buf = new CPStringBuilder(value.substring(0, i));
  1955. }
  1956. buf.append("\\n");
  1957. }
  1958. else if (c == '\r')
  1959. {
  1960. if (buf == null)
  1961. {
  1962. buf = new CPStringBuilder(value.substring(0, i));
  1963. }
  1964. buf.append("\\r");
  1965. }
  1966. else if (buf != null)
  1967. {
  1968. buf.append(c);
  1969. }
  1970. }
  1971. return (buf != null) ? buf.toString() : value;
  1972. }
  1973. String nodeTypeToString(short nodeType)
  1974. {
  1975. switch (nodeType)
  1976. {
  1977. case ELEMENT_NODE:
  1978. return "ELEMENT_NODE";
  1979. case ATTRIBUTE_NODE:
  1980. return "ATTRIBUTE_NODE";
  1981. case TEXT_NODE:
  1982. return "TEXT_NODE";
  1983. case CDATA_SECTION_NODE:
  1984. return "CDATA_SECTION_NODE";
  1985. case DOCUMENT_NODE:
  1986. return "DOCUMENT_NODE";
  1987. case DOCUMENT_TYPE_NODE:
  1988. return "DOCUMENT_TYPE_NODE";
  1989. case COMMENT_NODE:
  1990. return "COMMENT_NODE";
  1991. case PROCESSING_INSTRUCTION_NODE:
  1992. return "PROCESSING_INSTRUCTION_NODE";
  1993. case DOCUMENT_FRAGMENT_NODE:
  1994. return "DOCUMENT_FRAGMENT_NODE";
  1995. case ENTITY_NODE:
  1996. return "ENTITY_NODE";
  1997. case ENTITY_REFERENCE_NODE:
  1998. return "ENTITY_REFERENCE_NODE";
  1999. case NOTATION_NODE:
  2000. return "NOTATION_NODE";
  2001. default:
  2002. return "UNKNOWN";
  2003. }
  2004. }
  2005. public void list(java.io.PrintStream out, int indent)
  2006. {
  2007. for (int i = 0; i < indent; i++)
  2008. out.print(" ");
  2009. out.println(toString());
  2010. for (DomNode ctx = first; ctx != null; ctx = ctx.next)
  2011. ctx.list(out, indent + 1);
  2012. }
  2013. }