Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / devtools / front_end / sdk / DOMModel.js
1 /*
2  * Copyright (C) 2009, 2010 Google Inc. All rights reserved.
3  * Copyright (C) 2009 Joseph Pecoraro
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 /**
33  * @constructor
34  * @extends {WebInspector.SDKObject}
35  * @param {!WebInspector.DOMModel} domModel
36  * @param {?WebInspector.DOMDocument} doc
37  * @param {boolean} isInShadowTree
38  * @param {!DOMAgent.Node} payload
39  */
40 WebInspector.DOMNode = function(domModel, doc, isInShadowTree, payload) {
41     WebInspector.SDKObject.call(this, domModel.target());
42     this._domModel = domModel;
43     this._agent = domModel._agent;
44     this.ownerDocument = doc;
45     this._isInShadowTree = isInShadowTree;
46
47     this.id = payload.nodeId;
48     domModel._idToDOMNode[this.id] = this;
49     this._nodeType = payload.nodeType;
50     this._nodeName = payload.nodeName;
51     this._localName = payload.localName;
52     this._nodeValue = payload.nodeValue;
53     this._pseudoType = payload.pseudoType;
54     this._shadowRootType = payload.shadowRootType;
55     this._frameId = payload.frameId || null;
56
57     this._shadowRoots = [];
58
59     this._attributes = [];
60     this._attributesMap = {};
61     if (payload.attributes)
62         this._setAttributesPayload(payload.attributes);
63
64     this._userProperties = {};
65     this._descendantUserPropertyCounters = {};
66
67     this._childNodeCount = payload.childNodeCount || 0;
68     this._children = null;
69
70     this.nextSibling = null;
71     this.previousSibling = null;
72     this.firstChild = null;
73     this.lastChild = null;
74     this.parentNode = null;
75
76     if (payload.shadowRoots) {
77         for (var i = 0; i < payload.shadowRoots.length; ++i) {
78             var root = payload.shadowRoots[i];
79             var node = new WebInspector.DOMNode(this._domModel, this.ownerDocument, true, root);
80             this._shadowRoots.push(node);
81             node.parentNode = this;
82         }
83     }
84
85     if (payload.templateContent) {
86         this._templateContent = new WebInspector.DOMNode(this._domModel, this.ownerDocument, true, payload.templateContent);
87         this._templateContent.parentNode = this;
88     }
89
90     if (payload.importedDocument) {
91         this._importedDocument = new WebInspector.DOMNode(this._domModel, this.ownerDocument, true, payload.importedDocument);
92         this._importedDocument.parentNode = this;
93     }
94
95     if (payload.children)
96         this._setChildrenPayload(payload.children);
97
98     this._setPseudoElements(payload.pseudoElements);
99
100     if (payload.contentDocument) {
101         this._contentDocument = new WebInspector.DOMDocument(domModel, payload.contentDocument);
102         this._children = [this._contentDocument];
103         this._renumber();
104     }
105
106     if (this._nodeType === Node.ELEMENT_NODE) {
107         // HTML and BODY from internal iframes should not overwrite top-level ones.
108         if (this.ownerDocument && !this.ownerDocument.documentElement && this._nodeName === "HTML")
109             this.ownerDocument.documentElement = this;
110         if (this.ownerDocument && !this.ownerDocument.body && this._nodeName === "BODY")
111             this.ownerDocument.body = this;
112     } else if (this._nodeType === Node.DOCUMENT_TYPE_NODE) {
113         this.publicId = payload.publicId;
114         this.systemId = payload.systemId;
115         this.internalSubset = payload.internalSubset;
116     } else if (this._nodeType === Node.ATTRIBUTE_NODE) {
117         this.name = payload.name;
118         this.value = payload.value;
119     }
120 }
121
122 /**
123  * @enum {string}
124  */
125 WebInspector.DOMNode.PseudoElementNames = {
126     Before: "before",
127     After: "after"
128 }
129
130 /**
131  * @enum {string}
132  */
133 WebInspector.DOMNode.ShadowRootTypes = {
134     UserAgent: "user-agent",
135     Author: "author"
136 }
137
138 WebInspector.DOMNode.prototype = {
139     /**
140      * @return {!WebInspector.DOMModel}
141      */
142     domModel: function()
143     {
144         return this._domModel;
145     },
146
147     /**
148      * @return {?Array.<!WebInspector.DOMNode>}
149      */
150     children: function()
151     {
152         return this._children ? this._children.slice() : null;
153     },
154
155     /**
156      * @return {boolean}
157      */
158     hasAttributes: function()
159     {
160         return this._attributes.length > 0;
161     },
162
163     /**
164      * @return {number}
165      */
166     childNodeCount: function()
167     {
168         return this._childNodeCount;
169     },
170
171     /**
172      * @return {boolean}
173      */
174     hasShadowRoots: function()
175     {
176         return !!this._shadowRoots.length;
177     },
178
179     /**
180      * @return {!Array.<!WebInspector.DOMNode>}
181      */
182     shadowRoots: function()
183     {
184         return this._shadowRoots.slice();
185     },
186
187     /**
188      * @return {?WebInspector.DOMNode}
189      */
190     templateContent: function()
191     {
192         return this._templateContent || null;
193     },
194
195     /**
196      * @return {?WebInspector.DOMNode}
197      */
198     importedDocument: function()
199     {
200         return this._importedDocument || null;
201     },
202
203     /**
204      * @return {number}
205      */
206     nodeType: function()
207     {
208         return this._nodeType;
209     },
210
211     /**
212      * @return {string}
213      */
214     nodeName: function()
215     {
216         return this._nodeName;
217     },
218
219     /**
220      * @return {string|undefined}
221      */
222     pseudoType: function()
223     {
224         return this._pseudoType;
225     },
226
227     /**
228      * @return {boolean}
229      */
230     hasPseudoElements: function()
231     {
232         return Object.keys(this._pseudoElements).length !== 0;
233     },
234
235     /**
236      * @return {!Object.<string, !WebInspector.DOMNode>}
237      */
238     pseudoElements: function()
239     {
240         return this._pseudoElements;
241     },
242
243     /**
244      * @return {boolean}
245      */
246     isInShadowTree: function()
247     {
248         return this._isInShadowTree;
249     },
250
251     /**
252      * @return {?WebInspector.DOMNode}
253      */
254     ancestorUserAgentShadowRoot: function()
255     {
256         if (!this._isInShadowTree)
257             return null;
258
259         var current = this;
260         while (!current.isShadowRoot())
261             current = current.parentNode;
262         return current.shadowRootType() === WebInspector.DOMNode.ShadowRootTypes.UserAgent ? current : null;
263     },
264
265     /**
266      * @return {boolean}
267      */
268     isShadowRoot: function()
269     {
270         return !!this._shadowRootType;
271     },
272
273     /**
274      * @return {?string}
275      */
276     shadowRootType: function()
277     {
278         return this._shadowRootType || null;
279     },
280
281     /**
282      * @return {string}
283      */
284     nodeNameInCorrectCase: function()
285     {
286         var shadowRootType = this.shadowRootType();
287         if (shadowRootType)
288             return "#shadow-root" + (shadowRootType === WebInspector.DOMNode.ShadowRootTypes.UserAgent ? " (user-agent)" : "");
289         return this.isXMLNode() ? this.nodeName() : this.nodeName().toLowerCase();
290     },
291
292     /**
293      * @param {string} name
294      * @param {function(?Protocol.Error, number)=} callback
295      */
296     setNodeName: function(name, callback)
297     {
298         this._agent.setNodeName(this.id, name, this._domModel._markRevision(this, callback));
299     },
300
301     /**
302      * @return {string}
303      */
304     localName: function()
305     {
306         return this._localName;
307     },
308
309     /**
310      * @return {string}
311      */
312     nodeValue: function()
313     {
314         return this._nodeValue;
315     },
316
317     /**
318      * @param {string} value
319      * @param {function(?Protocol.Error)=} callback
320      */
321     setNodeValue: function(value, callback)
322     {
323         this._agent.setNodeValue(this.id, value, this._domModel._markRevision(this, callback));
324     },
325
326     /**
327      * @param {string} name
328      * @return {string}
329      */
330     getAttribute: function(name)
331     {
332         var attr = this._attributesMap[name];
333         return attr ? attr.value : undefined;
334     },
335
336     /**
337      * @param {string} name
338      * @param {string} text
339      * @param {function(?Protocol.Error)=} callback
340      */
341     setAttribute: function(name, text, callback)
342     {
343         this._agent.setAttributesAsText(this.id, text, name, this._domModel._markRevision(this, callback));
344     },
345
346     /**
347      * @param {string} name
348      * @param {string} value
349      * @param {function(?Protocol.Error)=} callback
350      */
351     setAttributeValue: function(name, value, callback)
352     {
353         this._agent.setAttributeValue(this.id, name, value, this._domModel._markRevision(this, callback));
354     },
355
356     /**
357      * @return {!Object}
358      */
359     attributes: function()
360     {
361         return this._attributes;
362     },
363
364     /**
365      * @param {string} name
366      * @param {function(?Protocol.Error)=} callback
367      */
368     removeAttribute: function(name, callback)
369     {
370         /**
371          * @param {?Protocol.Error} error
372          * @this {WebInspector.DOMNode}
373          */
374         function mycallback(error)
375         {
376             if (!error) {
377                 delete this._attributesMap[name];
378                 for (var i = 0;  i < this._attributes.length; ++i) {
379                     if (this._attributes[i].name === name) {
380                         this._attributes.splice(i, 1);
381                         break;
382                     }
383                 }
384             }
385
386             this._domModel._markRevision(this, callback)(error);
387         }
388         this._agent.removeAttribute(this.id, name, mycallback.bind(this));
389     },
390
391     /**
392      * @param {function(?Array.<!WebInspector.DOMNode>)=} callback
393      */
394     getChildNodes: function(callback)
395     {
396         if (this._children) {
397             if (callback)
398                 callback(this.children());
399             return;
400         }
401
402         /**
403          * @this {WebInspector.DOMNode}
404          * @param {?Protocol.Error} error
405          */
406         function mycallback(error)
407         {
408             if (callback)
409                 callback(error ? null : this.children());
410         }
411
412         this._agent.requestChildNodes(this.id, undefined, mycallback.bind(this));
413     },
414
415     /**
416      * @param {number} depth
417      * @param {function(?Array.<!WebInspector.DOMNode>)=} callback
418      */
419     getSubtree: function(depth, callback)
420     {
421         /**
422          * @this {WebInspector.DOMNode}
423          * @param {?Protocol.Error} error
424          */
425         function mycallback(error)
426         {
427             if (callback)
428                 callback(error ? null : this._children);
429         }
430
431         this._agent.requestChildNodes(this.id, depth, mycallback.bind(this));
432     },
433
434     /**
435      * @param {function(?Protocol.Error, string)=} callback
436      */
437     getOuterHTML: function(callback)
438     {
439         this._agent.getOuterHTML(this.id, callback);
440     },
441
442     /**
443      * @param {string} html
444      * @param {function(?Protocol.Error)=} callback
445      */
446     setOuterHTML: function(html, callback)
447     {
448         this._agent.setOuterHTML(this.id, html, this._domModel._markRevision(this, callback));
449     },
450
451     /**
452      * @param {function(?Protocol.Error, !DOMAgent.NodeId=)=} callback
453      */
454     removeNode: function(callback)
455     {
456         this._agent.removeNode(this.id, this._domModel._markRevision(this, callback));
457     },
458
459     /**
460      * @param {function(?string)=} callback
461      */
462     copyNode: function(callback)
463     {
464         function copy(error, text)
465         {
466             if (!error)
467                 InspectorFrontendHost.copyText(text);
468             if (callback)
469                 callback(error ? null : text);
470         }
471         this._agent.getOuterHTML(this.id, copy);
472     },
473
474     /**
475      * @param {string} objectGroupId
476      * @param {function(?Array.<!WebInspector.DOMModel.EventListener>)} callback
477      */
478     eventListeners: function(objectGroupId, callback)
479     {
480         var target = this.target();
481
482         /**
483          * @param {?Protocol.Error} error
484          * @param {!Array.<!DOMAgent.EventListener>} payloads
485          */
486         function mycallback(error, payloads)
487         {
488             if (error) {
489                 callback(null);
490                 return;
491             }
492             callback(payloads.map(function(payload) {
493                 return new WebInspector.DOMModel.EventListener(target, payload);
494             }));
495         }
496         this._agent.getEventListenersForNode(this.id, objectGroupId, mycallback);
497     },
498
499     /**
500      * @return {string}
501      */
502     path: function()
503     {
504         /**
505          * @param {?WebInspector.DOMNode} node
506          */
507         function canPush(node)
508         {
509             return node && ("index" in node || (node.isShadowRoot() && node.parentNode)) && node._nodeName.length;
510         }
511
512         var path = [];
513         var node = this;
514         while (canPush(node)) {
515             var index = typeof node.index === "number" ? node.index : (node.shadowRootType() === WebInspector.DOMNode.ShadowRootTypes.UserAgent ? "u" : "a");
516             path.push([index, node._nodeName]);
517             node = node.parentNode;
518         }
519         path.reverse();
520         return path.join(",");
521     },
522
523     /**
524      * @param {!WebInspector.DOMNode} node
525      * @return {boolean}
526      */
527     isAncestor: function(node)
528     {
529         if (!node)
530             return false;
531
532         var currentNode = node.parentNode;
533         while (currentNode) {
534             if (this === currentNode)
535                 return true;
536             currentNode = currentNode.parentNode;
537         }
538         return false;
539     },
540
541     /**
542      * @param {!WebInspector.DOMNode} descendant
543      * @return {boolean}
544      */
545     isDescendant: function(descendant)
546     {
547         return descendant !== null && descendant.isAncestor(this);
548     },
549
550     /**
551      * @return {?PageAgent.FrameId}
552      */
553     frameId: function()
554     {
555         var node = this;
556         while (!node._frameId && node.parentNode)
557             node = node.parentNode;
558         return node._frameId;
559     },
560
561     /**
562      * @param {!Array.<string>} attrs
563      * @return {boolean}
564      */
565     _setAttributesPayload: function(attrs)
566     {
567         var attributesChanged = !this._attributes || attrs.length !== this._attributes.length * 2;
568         var oldAttributesMap = this._attributesMap || {};
569
570         this._attributes = [];
571         this._attributesMap = {};
572
573         for (var i = 0; i < attrs.length; i += 2) {
574             var name = attrs[i];
575             var value = attrs[i + 1];
576             this._addAttribute(name, value);
577
578             if (attributesChanged)
579                 continue;
580
581             if (!oldAttributesMap[name] || oldAttributesMap[name].value !== value)
582               attributesChanged = true;
583         }
584         return attributesChanged;
585     },
586
587     /**
588      * @param {!WebInspector.DOMNode} prev
589      * @param {!DOMAgent.Node} payload
590      * @return {!WebInspector.DOMNode}
591      */
592     _insertChild: function(prev, payload)
593     {
594         var node = new WebInspector.DOMNode(this._domModel, this.ownerDocument, this._isInShadowTree, payload);
595         this._children.splice(this._children.indexOf(prev) + 1, 0, node);
596         this._renumber();
597         return node;
598     },
599
600     /**
601      * @param {!WebInspector.DOMNode} node
602      */
603     _removeChild: function(node)
604     {
605         if (node.pseudoType()) {
606             delete this._pseudoElements[node.pseudoType()];
607         } else {
608             var shadowRootIndex = this._shadowRoots.indexOf(node);
609             if (shadowRootIndex !== -1)
610                 this._shadowRoots.splice(shadowRootIndex, 1);
611             else
612                 this._children.splice(this._children.indexOf(node), 1);
613         }
614         node.parentNode = null;
615         node._updateChildUserPropertyCountsOnRemoval(this);
616         this._renumber();
617     },
618
619     /**
620      * @param {!Array.<!DOMAgent.Node>} payloads
621      */
622     _setChildrenPayload: function(payloads)
623     {
624         // We set children in the constructor.
625         if (this._contentDocument)
626             return;
627
628         this._children = [];
629         for (var i = 0; i < payloads.length; ++i) {
630             var payload = payloads[i];
631             var node = new WebInspector.DOMNode(this._domModel, this.ownerDocument, this._isInShadowTree, payload);
632             this._children.push(node);
633         }
634         this._renumber();
635     },
636
637     /**
638      * @param {!Array.<!DOMAgent.Node>|undefined} payloads
639      */
640     _setPseudoElements: function(payloads)
641     {
642         this._pseudoElements = {};
643         if (!payloads)
644             return;
645
646         for (var i = 0; i < payloads.length; ++i) {
647             var node = new WebInspector.DOMNode(this._domModel, this.ownerDocument, this._isInShadowTree, payloads[i]);
648             node.parentNode = this;
649             this._pseudoElements[node.pseudoType()] = node;
650         }
651     },
652
653     _renumber: function()
654     {
655         this._childNodeCount = this._children.length;
656         if (this._childNodeCount == 0) {
657             this.firstChild = null;
658             this.lastChild = null;
659             return;
660         }
661         this.firstChild = this._children[0];
662         this.lastChild = this._children[this._childNodeCount - 1];
663         for (var i = 0; i < this._childNodeCount; ++i) {
664             var child = this._children[i];
665             child.index = i;
666             child.nextSibling = i + 1 < this._childNodeCount ? this._children[i + 1] : null;
667             child.previousSibling = i - 1 >= 0 ? this._children[i - 1] : null;
668             child.parentNode = this;
669         }
670     },
671
672     /**
673      * @param {string} name
674      * @param {string} value
675      */
676     _addAttribute: function(name, value)
677     {
678         var attr = {
679             name: name,
680             value: value,
681             _node: this
682         };
683         this._attributesMap[name] = attr;
684         this._attributes.push(attr);
685     },
686
687     /**
688      * @param {string} name
689      * @param {string} value
690      */
691     _setAttribute: function(name, value)
692     {
693         var attr = this._attributesMap[name];
694         if (attr)
695             attr.value = value;
696         else
697             this._addAttribute(name, value);
698     },
699
700     /**
701      * @param {string} name
702      */
703     _removeAttribute: function(name)
704     {
705         var attr = this._attributesMap[name];
706         if (attr) {
707             this._attributes.remove(attr);
708             delete this._attributesMap[name];
709         }
710     },
711
712     /**
713      * @param {!WebInspector.DOMNode} targetNode
714      * @param {?WebInspector.DOMNode} anchorNode
715      * @param {function(?Protocol.Error, !DOMAgent.NodeId=)=} callback
716      */
717     copyTo: function(targetNode, anchorNode, callback)
718     {
719         this._agent.copyTo(this.id, targetNode.id, anchorNode ? anchorNode.id : undefined, this._domModel._markRevision(this, callback));
720     },
721
722     /**
723      * @param {!WebInspector.DOMNode} targetNode
724      * @param {?WebInspector.DOMNode} anchorNode
725      * @param {function(?Protocol.Error, !DOMAgent.NodeId=)=} callback
726      */
727     moveTo: function(targetNode, anchorNode, callback)
728     {
729         this._agent.moveTo(this.id, targetNode.id, anchorNode ? anchorNode.id : undefined, this._domModel._markRevision(this, callback));
730     },
731
732     /**
733      * @return {boolean}
734      */
735     isXMLNode: function()
736     {
737         return !!this.ownerDocument && !!this.ownerDocument.xmlVersion;
738     },
739
740     _updateChildUserPropertyCountsOnRemoval: function(parentNode)
741     {
742         var result = {};
743         if (this._userProperties) {
744             for (var name in this._userProperties)
745                 result[name] = (result[name] || 0) + 1;
746         }
747
748         if (this._descendantUserPropertyCounters) {
749             for (var name in this._descendantUserPropertyCounters) {
750                 var counter = this._descendantUserPropertyCounters[name];
751                 result[name] = (result[name] || 0) + counter;
752             }
753         }
754
755         for (var name in result)
756             parentNode._updateDescendantUserPropertyCount(name, -result[name]);
757     },
758
759     _updateDescendantUserPropertyCount: function(name, delta)
760     {
761         if (!this._descendantUserPropertyCounters.hasOwnProperty(name))
762             this._descendantUserPropertyCounters[name] = 0;
763         this._descendantUserPropertyCounters[name] += delta;
764         if (!this._descendantUserPropertyCounters[name])
765             delete this._descendantUserPropertyCounters[name];
766         if (this.parentNode)
767             this.parentNode._updateDescendantUserPropertyCount(name, delta);
768     },
769
770     setUserProperty: function(name, value)
771     {
772         if (value === null) {
773             this.removeUserProperty(name);
774             return;
775         }
776
777         if (this.parentNode && !this._userProperties.hasOwnProperty(name))
778             this.parentNode._updateDescendantUserPropertyCount(name, 1);
779
780         this._userProperties[name] = value;
781     },
782
783     removeUserProperty: function(name)
784     {
785         if (!this._userProperties.hasOwnProperty(name))
786             return;
787
788         delete this._userProperties[name];
789         if (this.parentNode)
790             this.parentNode._updateDescendantUserPropertyCount(name, -1);
791     },
792
793     /**
794      * @param {string} name
795      * @return {?T}
796      * @template T
797      */
798     getUserProperty: function(name)
799     {
800         return (this._userProperties && this._userProperties[name]) || null;
801     },
802
803     /**
804      * @param {string} name
805      * @return {number}
806      */
807     descendantUserPropertyCount: function(name)
808     {
809         return this._descendantUserPropertyCounters && this._descendantUserPropertyCounters[name] ? this._descendantUserPropertyCounters[name] : 0;
810     },
811
812     /**
813      * @param {string} url
814      * @return {?string}
815      */
816     resolveURL: function(url)
817     {
818         if (!url)
819             return url;
820         for (var frameOwnerCandidate = this; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
821             if (frameOwnerCandidate.baseURL)
822                 return WebInspector.ParsedURL.completeURL(frameOwnerCandidate.baseURL, url);
823         }
824         return null;
825     },
826
827     /**
828      * @param {string=} mode
829      * @param {!RuntimeAgent.RemoteObjectId=} objectId
830      */
831     highlight: function(mode, objectId)
832     {
833         this._domModel.highlightDOMNode(this.id, mode, objectId);
834     },
835
836     highlightForTwoSeconds: function()
837     {
838         this._domModel.highlightDOMNodeForTwoSeconds(this.id);
839     },
840
841     /**
842      * @param {string=} objectGroup
843      * @param {function(?WebInspector.RemoteObject)=} callback
844      */
845     resolveToObject: function(objectGroup, callback)
846     {
847         this._agent.resolveNode(this.id, objectGroup, mycallback.bind(this));
848
849         /**
850          * @param {?Protocol.Error} error
851          * @param {!RuntimeAgent.RemoteObject} object
852          * @this {WebInspector.DOMNode}
853          */
854         function mycallback(error, object)
855         {
856             if (!callback)
857                 return;
858
859             if (error || !object)
860                 callback(null);
861             else
862                 callback(this.target().runtimeModel.createRemoteObject(object));
863         }
864     },
865
866     /**
867      * @param {function(?DOMAgent.BoxModel)} callback
868      */
869     boxModel: function(callback)
870     {
871         this._agent.getBoxModel(this.id, this._domModel._wrapClientCallback(callback));
872     },
873
874     __proto__: WebInspector.SDKObject.prototype
875 }
876
877 /**
878  * @param {!WebInspector.Target} target
879  * @param {number} backendNodeId
880  * @constructor
881  */
882 WebInspector.DeferredDOMNode = function(target, backendNodeId)
883 {
884     this._target = target;
885     this._backendNodeId = backendNodeId;
886 }
887
888 WebInspector.DeferredDOMNode.prototype = {
889     /**
890      * @param {function(?WebInspector.DOMNode)} callback
891      */
892     resolve: function(callback)
893     {
894         this._target.domModel.pushNodesByBackendIdsToFrontend([this._backendNodeId], onGotNode.bind(this));
895
896         /**
897          * @param {?Array.<number>} nodeIds
898          * @this {WebInspector.DeferredDOMNode}
899          */
900         function onGotNode(nodeIds)
901         {
902             if (!nodeIds || !nodeIds[0]) {
903                 callback(null);
904                 return;
905             }
906             callback(this._target.domModel.nodeForId(nodeIds[0]));
907         }
908     }
909 }
910
911 /**
912  * @extends {WebInspector.DOMNode}
913  * @constructor
914  * @param {!WebInspector.DOMModel} domModel
915  * @param {!DOMAgent.Node} payload
916  */
917 WebInspector.DOMDocument = function(domModel, payload)
918 {
919     WebInspector.DOMNode.call(this, domModel, this, false, payload);
920     this.documentURL = payload.documentURL || "";
921     this.baseURL = payload.baseURL || "";
922     this.xmlVersion = payload.xmlVersion;
923     this._listeners = {};
924 }
925
926 WebInspector.DOMDocument.prototype = {
927     __proto__: WebInspector.DOMNode.prototype
928 }
929
930 /**
931  * @constructor
932  * @extends {WebInspector.SDKModel}
933  * @param {!WebInspector.Target} target
934  */
935 WebInspector.DOMModel = function(target) {
936     WebInspector.SDKModel.call(this, WebInspector.DOMModel, target);
937
938     this._agent = target.domAgent();
939
940     /** @type {!Object.<number, !WebInspector.DOMNode>} */
941     this._idToDOMNode = {};
942     /** @type {?WebInspector.DOMDocument} */
943     this._document = null;
944     /** @type {!Object.<number, boolean>} */
945     this._attributeLoadNodeIds = {};
946     target.registerDOMDispatcher(new WebInspector.DOMDispatcher(this));
947
948     this._defaultHighlighter = new WebInspector.DefaultDOMNodeHighlighter(this._agent);
949     this._highlighter = this._defaultHighlighter;
950
951     this._agent.enable();
952 }
953
954 WebInspector.DOMModel.Events = {
955     AttrModified: "AttrModified",
956     AttrRemoved: "AttrRemoved",
957     CharacterDataModified: "CharacterDataModified",
958     NodeInserted: "NodeInserted",
959     NodeInspected: "NodeInspected",
960     NodeRemoved: "NodeRemoved",
961     DocumentUpdated: "DocumentUpdated",
962     ChildNodeCountUpdated: "ChildNodeCountUpdated",
963     UndoRedoRequested: "UndoRedoRequested",
964     UndoRedoCompleted: "UndoRedoCompleted",
965 }
966
967 WebInspector.DOMModel.prototype = {
968     suspendModel: function()
969     {
970         this._agent.disable();
971     },
972
973     resumeModel: function()
974     {
975         this._agent.enable();
976     },
977
978     /**
979      * @param {function(!WebInspector.DOMDocument)=} callback
980      */
981     requestDocument: function(callback)
982     {
983         if (this._document) {
984             if (callback)
985                 callback(this._document);
986             return;
987         }
988
989         if (this._pendingDocumentRequestCallbacks) {
990             this._pendingDocumentRequestCallbacks.push(callback);
991             return;
992         }
993
994         this._pendingDocumentRequestCallbacks = [callback];
995
996         /**
997          * @this {WebInspector.DOMModel}
998          * @param {?Protocol.Error} error
999          * @param {!DOMAgent.Node} root
1000          */
1001         function onDocumentAvailable(error, root)
1002         {
1003             if (!error)
1004                 this._setDocument(root);
1005
1006             for (var i = 0; i < this._pendingDocumentRequestCallbacks.length; ++i) {
1007                 var callback = this._pendingDocumentRequestCallbacks[i];
1008                 if (callback)
1009                     callback(this._document);
1010             }
1011             delete this._pendingDocumentRequestCallbacks;
1012         }
1013
1014         this._agent.getDocument(onDocumentAvailable.bind(this));
1015     },
1016
1017     /**
1018      * @return {?WebInspector.DOMDocument}
1019      */
1020     existingDocument: function()
1021     {
1022         return this._document;
1023     },
1024
1025     /**
1026      * @param {!RuntimeAgent.RemoteObjectId} objectId
1027      * @param {function(?WebInspector.DOMNode)=} callback
1028      */
1029     pushNodeToFrontend: function(objectId, callback)
1030     {
1031         /**
1032          * @param {?DOMAgent.NodeId} nodeId
1033          * @this {!WebInspector.DOMModel}
1034          */
1035         function mycallback(nodeId)
1036         {
1037             callback(nodeId ? this.nodeForId(nodeId) : null);
1038         }
1039         this._dispatchWhenDocumentAvailable(this._agent.requestNode.bind(this._agent, objectId), mycallback.bind(this));
1040     },
1041
1042     /**
1043      * @param {string} path
1044      * @param {function(?number)=} callback
1045      */
1046     pushNodeByPathToFrontend: function(path, callback)
1047     {
1048         this._dispatchWhenDocumentAvailable(this._agent.pushNodeByPathToFrontend.bind(this._agent, path), callback);
1049     },
1050
1051     /**
1052      * @param {!Array.<number>} backendNodeIds
1053      * @param {function(?Array.<number>)=} callback
1054      */
1055     pushNodesByBackendIdsToFrontend: function(backendNodeIds, callback)
1056     {
1057         this._dispatchWhenDocumentAvailable(this._agent.pushNodesByBackendIdsToFrontend.bind(this._agent, backendNodeIds), callback);
1058     },
1059
1060     /**
1061      * @param {function(!T)=} callback
1062      * @return {function(?Protocol.Error, !T=)|undefined}
1063      * @template T
1064      */
1065     _wrapClientCallback: function(callback)
1066     {
1067         if (!callback)
1068             return;
1069         /**
1070          * @param {?Protocol.Error} error
1071          * @param {!T=} result
1072          * @template T
1073          */
1074         var wrapper = function(error, result)
1075         {
1076             // Caller is responsible for handling the actual error.
1077             callback(error ? null : result);
1078         };
1079         return wrapper;
1080     },
1081
1082     /**
1083      * @param {function(function(?Protocol.Error, !T=)=)} func
1084      * @param {function(!T)=} callback
1085      * @template T
1086      */
1087     _dispatchWhenDocumentAvailable: function(func, callback)
1088     {
1089         var callbackWrapper = this._wrapClientCallback(callback);
1090
1091         /**
1092          * @this {WebInspector.DOMModel}
1093          */
1094         function onDocumentAvailable()
1095         {
1096             if (this._document)
1097                 func(callbackWrapper);
1098             else {
1099                 if (callbackWrapper)
1100                     callbackWrapper("No document");
1101             }
1102         }
1103         this.requestDocument(onDocumentAvailable.bind(this));
1104     },
1105
1106     /**
1107      * @param {!DOMAgent.NodeId} nodeId
1108      * @param {string} name
1109      * @param {string} value
1110      */
1111     _attributeModified: function(nodeId, name, value)
1112     {
1113         var node = this._idToDOMNode[nodeId];
1114         if (!node)
1115             return;
1116
1117         node._setAttribute(name, value);
1118         this.dispatchEventToListeners(WebInspector.DOMModel.Events.AttrModified, { node: node, name: name });
1119     },
1120
1121     /**
1122      * @param {!DOMAgent.NodeId} nodeId
1123      * @param {string} name
1124      */
1125     _attributeRemoved: function(nodeId, name)
1126     {
1127         var node = this._idToDOMNode[nodeId];
1128         if (!node)
1129             return;
1130         node._removeAttribute(name);
1131         this.dispatchEventToListeners(WebInspector.DOMModel.Events.AttrRemoved, { node: node, name: name });
1132     },
1133
1134     /**
1135      * @param {!Array.<!DOMAgent.NodeId>} nodeIds
1136      */
1137     _inlineStyleInvalidated: function(nodeIds)
1138     {
1139         for (var i = 0; i < nodeIds.length; ++i)
1140             this._attributeLoadNodeIds[nodeIds[i]] = true;
1141         if ("_loadNodeAttributesTimeout" in this)
1142             return;
1143         this._loadNodeAttributesTimeout = setTimeout(this._loadNodeAttributes.bind(this), 20);
1144     },
1145
1146     _loadNodeAttributes: function()
1147     {
1148         /**
1149          * @this {WebInspector.DOMModel}
1150          * @param {!DOMAgent.NodeId} nodeId
1151          * @param {?Protocol.Error} error
1152          * @param {!Array.<string>} attributes
1153          */
1154         function callback(nodeId, error, attributes)
1155         {
1156             if (error) {
1157                 // We are calling _loadNodeAttributes asynchronously, it is ok if node is not found.
1158                 return;
1159             }
1160             var node = this._idToDOMNode[nodeId];
1161             if (node) {
1162                 if (node._setAttributesPayload(attributes))
1163                     this.dispatchEventToListeners(WebInspector.DOMModel.Events.AttrModified, { node: node, name: "style" });
1164             }
1165         }
1166
1167         delete this._loadNodeAttributesTimeout;
1168
1169         for (var nodeId in this._attributeLoadNodeIds) {
1170             var nodeIdAsNumber = parseInt(nodeId, 10);
1171             this._agent.getAttributes(nodeIdAsNumber, callback.bind(this, nodeIdAsNumber));
1172         }
1173         this._attributeLoadNodeIds = {};
1174     },
1175
1176     /**
1177      * @param {!DOMAgent.NodeId} nodeId
1178      * @param {string} newValue
1179      */
1180     _characterDataModified: function(nodeId, newValue)
1181     {
1182         var node = this._idToDOMNode[nodeId];
1183         node._nodeValue = newValue;
1184         this.dispatchEventToListeners(WebInspector.DOMModel.Events.CharacterDataModified, node);
1185     },
1186
1187     /**
1188      * @param {!DOMAgent.NodeId} nodeId
1189      * @return {?WebInspector.DOMNode}
1190      */
1191     nodeForId: function(nodeId)
1192     {
1193         return this._idToDOMNode[nodeId] || null;
1194     },
1195
1196     _documentUpdated: function()
1197     {
1198         this._setDocument(null);
1199     },
1200
1201     /**
1202      * @param {?DOMAgent.Node} payload
1203      */
1204     _setDocument: function(payload)
1205     {
1206         this._idToDOMNode = {};
1207         if (payload && "nodeId" in payload)
1208             this._document = new WebInspector.DOMDocument(this, payload);
1209         else
1210             this._document = null;
1211         this.dispatchEventToListeners(WebInspector.DOMModel.Events.DocumentUpdated, this._document);
1212     },
1213
1214     /**
1215      * @param {!DOMAgent.Node} payload
1216      */
1217     _setDetachedRoot: function(payload)
1218     {
1219         if (payload.nodeName === "#document")
1220             new WebInspector.DOMDocument(this, payload);
1221         else
1222             new WebInspector.DOMNode(this, null, false, payload);
1223     },
1224
1225     /**
1226      * @param {!DOMAgent.NodeId} parentId
1227      * @param {!Array.<!DOMAgent.Node>} payloads
1228      */
1229     _setChildNodes: function(parentId, payloads)
1230     {
1231         if (!parentId && payloads.length) {
1232             this._setDetachedRoot(payloads[0]);
1233             return;
1234         }
1235
1236         var parent = this._idToDOMNode[parentId];
1237         parent._setChildrenPayload(payloads);
1238     },
1239
1240     /**
1241      * @param {!DOMAgent.NodeId} nodeId
1242      * @param {number} newValue
1243      */
1244     _childNodeCountUpdated: function(nodeId, newValue)
1245     {
1246         var node = this._idToDOMNode[nodeId];
1247         node._childNodeCount = newValue;
1248         this.dispatchEventToListeners(WebInspector.DOMModel.Events.ChildNodeCountUpdated, node);
1249     },
1250
1251     /**
1252      * @param {!DOMAgent.NodeId} parentId
1253      * @param {!DOMAgent.NodeId} prevId
1254      * @param {!DOMAgent.Node} payload
1255      */
1256     _childNodeInserted: function(parentId, prevId, payload)
1257     {
1258         var parent = this._idToDOMNode[parentId];
1259         var prev = this._idToDOMNode[prevId];
1260         var node = parent._insertChild(prev, payload);
1261         this._idToDOMNode[node.id] = node;
1262         this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInserted, node);
1263     },
1264
1265     /**
1266      * @param {!DOMAgent.NodeId} parentId
1267      * @param {!DOMAgent.NodeId} nodeId
1268      */
1269     _childNodeRemoved: function(parentId, nodeId)
1270     {
1271         var parent = this._idToDOMNode[parentId];
1272         var node = this._idToDOMNode[nodeId];
1273         parent._removeChild(node);
1274         this._unbind(node);
1275         this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeRemoved, {node: node, parent: parent});
1276     },
1277
1278     /**
1279      * @param {!DOMAgent.NodeId} hostId
1280      * @param {!DOMAgent.Node} root
1281      */
1282     _shadowRootPushed: function(hostId, root)
1283     {
1284         var host = this._idToDOMNode[hostId];
1285         if (!host)
1286             return;
1287         var node = new WebInspector.DOMNode(this, host.ownerDocument, true, root);
1288         node.parentNode = host;
1289         this._idToDOMNode[node.id] = node;
1290         host._shadowRoots.push(node);
1291         this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInserted, node);
1292     },
1293
1294     /**
1295      * @param {!DOMAgent.NodeId} hostId
1296      * @param {!DOMAgent.NodeId} rootId
1297      */
1298     _shadowRootPopped: function(hostId, rootId)
1299     {
1300         var host = this._idToDOMNode[hostId];
1301         if (!host)
1302             return;
1303         var root = this._idToDOMNode[rootId];
1304         if (!root)
1305             return;
1306         host._removeChild(root);
1307         this._unbind(root);
1308         this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeRemoved, {node: root, parent: host});
1309     },
1310
1311     /**
1312      * @param {!DOMAgent.NodeId} parentId
1313      * @param {!DOMAgent.Node} pseudoElement
1314      */
1315     _pseudoElementAdded: function(parentId, pseudoElement)
1316     {
1317         var parent = this._idToDOMNode[parentId];
1318         if (!parent)
1319             return;
1320         var node = new WebInspector.DOMNode(this, parent.ownerDocument, false, pseudoElement);
1321         node.parentNode = parent;
1322         this._idToDOMNode[node.id] = node;
1323         console.assert(!parent._pseudoElements[node.pseudoType()]);
1324         parent._pseudoElements[node.pseudoType()] = node;
1325         this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInserted, node);
1326     },
1327
1328     /**
1329      * @param {!DOMAgent.NodeId} parentId
1330      * @param {!DOMAgent.NodeId} pseudoElementId
1331      */
1332     _pseudoElementRemoved: function(parentId, pseudoElementId)
1333     {
1334         var parent = this._idToDOMNode[parentId];
1335         if (!parent)
1336             return;
1337         var pseudoElement = this._idToDOMNode[pseudoElementId];
1338         if (!pseudoElement)
1339             return;
1340         parent._removeChild(pseudoElement);
1341         this._unbind(pseudoElement);
1342         this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeRemoved, {node: pseudoElement, parent: parent});
1343     },
1344
1345     /**
1346      * @param {!WebInspector.DOMNode} node
1347      */
1348     _unbind: function(node)
1349     {
1350         delete this._idToDOMNode[node.id];
1351         for (var i = 0; node._children && i < node._children.length; ++i)
1352             this._unbind(node._children[i]);
1353         for (var i = 0; i < node._shadowRoots.length; ++i)
1354             this._unbind(node._shadowRoots[i]);
1355         var pseudoElements = node.pseudoElements();
1356         for (var id in pseudoElements)
1357             this._unbind(pseudoElements[id]);
1358         if (node._templateContent)
1359             this._unbind(node._templateContent);
1360     },
1361
1362     /**
1363      * @param {!DOMAgent.NodeId} nodeId
1364      */
1365     _inspectNodeRequested: function(nodeId)
1366     {
1367         this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInspected, this.nodeForId(nodeId));
1368     },
1369
1370     /**
1371      * @param {string} query
1372      * @param {boolean} includeUserAgentShadowDOM
1373      * @param {function(number)} searchCallback
1374      */
1375     performSearch: function(query, includeUserAgentShadowDOM, searchCallback)
1376     {
1377         this.cancelSearch();
1378
1379         /**
1380          * @param {?Protocol.Error} error
1381          * @param {string} searchId
1382          * @param {number} resultsCount
1383          * @this {WebInspector.DOMModel}
1384          */
1385         function callback(error, searchId, resultsCount)
1386         {
1387             this._searchId = searchId;
1388             searchCallback(resultsCount);
1389         }
1390         this._agent.performSearch(query, includeUserAgentShadowDOM, callback.bind(this));
1391     },
1392
1393     /**
1394      * @param {string} query
1395      * @param {boolean} includeUserAgentShadowDOM
1396      * @return {!Promise.<number>}
1397      */
1398     performSearchPromise: function(query, includeUserAgentShadowDOM)
1399     {
1400         return new Promise(performSearch.bind(this));
1401
1402         /**
1403          * @param {function(number)} resolve
1404          * @this {WebInspector.DOMModel}
1405          */
1406         function performSearch(resolve)
1407         {
1408             this._agent.performSearch(query, includeUserAgentShadowDOM, callback.bind(this));
1409
1410             /**
1411              * @param {?Protocol.Error} error
1412              * @param {string} searchId
1413              * @param {number} resultsCount
1414              * @this {WebInspector.DOMModel}
1415              */
1416             function callback(error, searchId, resultsCount)
1417             {
1418                 if (!error)
1419                     this._searchId = searchId;
1420                 resolve(error ? 0 : resultsCount);
1421             }
1422         }
1423     },
1424
1425     /**
1426      * @param {number} index
1427      * @param {?function(?WebInspector.DOMNode)} callback
1428      */
1429     searchResult: function(index, callback)
1430     {
1431         if (this._searchId)
1432             this._agent.getSearchResults(this._searchId, index, index + 1, searchResultsCallback.bind(this));
1433         else
1434             callback(null);
1435
1436         /**
1437          * @param {?Protocol.Error} error
1438          * @param {!Array.<number>} nodeIds
1439          * @this {WebInspector.DOMModel}
1440          */
1441         function searchResultsCallback(error, nodeIds)
1442         {
1443             if (error) {
1444                 console.error(error);
1445                 callback(null);
1446                 return;
1447             }
1448             if (nodeIds.length != 1)
1449                 return;
1450
1451             callback(this.nodeForId(nodeIds[0]));
1452         }
1453     },
1454
1455     cancelSearch: function()
1456     {
1457         if (this._searchId) {
1458             this._agent.discardSearchResults(this._searchId);
1459             delete this._searchId;
1460         }
1461     },
1462
1463     /**
1464      * @param {!DOMAgent.NodeId} nodeId
1465      * @param {string} selectors
1466      * @param {function(?DOMAgent.NodeId)=} callback
1467      */
1468     querySelector: function(nodeId, selectors, callback)
1469     {
1470         this._agent.querySelector(nodeId, selectors, this._wrapClientCallback(callback));
1471     },
1472
1473     /**
1474      * @param {!DOMAgent.NodeId} nodeId
1475      * @param {string} selectors
1476      * @param {function(!Array.<!DOMAgent.NodeId>=)=} callback
1477      */
1478     querySelectorAll: function(nodeId, selectors, callback)
1479     {
1480         this._agent.querySelectorAll(nodeId, selectors, this._wrapClientCallback(callback));
1481     },
1482
1483     /**
1484      * @param {!DOMAgent.NodeId=} nodeId
1485      * @param {string=} mode
1486      * @param {!RuntimeAgent.RemoteObjectId=} objectId
1487      */
1488     highlightDOMNode: function(nodeId, mode, objectId)
1489     {
1490         this.highlightDOMNodeWithConfig(nodeId, { mode: mode }, objectId);
1491     },
1492
1493     /**
1494      * @param {!DOMAgent.NodeId=} nodeId
1495      * @param {!{mode: (string|undefined), showInfo: (boolean|undefined)}=} config
1496      * @param {!RuntimeAgent.RemoteObjectId=} objectId
1497      */
1498     highlightDOMNodeWithConfig: function(nodeId, config, objectId)
1499     {
1500         config = config || { mode: "all", showInfo: undefined };
1501         if (this._hideDOMNodeHighlightTimeout) {
1502             clearTimeout(this._hideDOMNodeHighlightTimeout);
1503             delete this._hideDOMNodeHighlightTimeout;
1504         }
1505         var highlightConfig = this._buildHighlightConfig(config.mode);
1506         if (typeof config.showInfo !== "undefined")
1507             highlightConfig.showInfo = config.showInfo;
1508         this._highlighter.highlightDOMNode(this.nodeForId(nodeId || 0), highlightConfig, objectId);
1509     },
1510
1511     hideDOMNodeHighlight: function()
1512     {
1513         this.highlightDOMNode(0);
1514     },
1515
1516     /**
1517      * @param {!DOMAgent.NodeId} nodeId
1518      */
1519     highlightDOMNodeForTwoSeconds: function(nodeId)
1520     {
1521         this.highlightDOMNode(nodeId);
1522         this._hideDOMNodeHighlightTimeout = setTimeout(this.hideDOMNodeHighlight.bind(this), 2000);
1523     },
1524
1525     /**
1526      * @param {boolean} enabled
1527      * @param {boolean} inspectUAShadowDOM
1528      * @param {function(?Protocol.Error)=} callback
1529      */
1530     setInspectModeEnabled: function(enabled, inspectUAShadowDOM, callback)
1531     {
1532         /**
1533          * @this {WebInspector.DOMModel}
1534          */
1535         function onDocumentAvailable()
1536         {
1537             this._highlighter.setInspectModeEnabled(enabled, inspectUAShadowDOM, this._buildHighlightConfig(), callback);
1538         }
1539         this.requestDocument(onDocumentAvailable.bind(this));
1540     },
1541
1542     /**
1543      * @param {string=} mode
1544      * @return {!DOMAgent.HighlightConfig}
1545      */
1546     _buildHighlightConfig: function(mode)
1547     {
1548         mode = mode || "all";
1549         var highlightConfig = { showInfo: mode === "all", showRulers: WebInspector.overridesSupport.showMetricsRulers(), showExtensionLines: WebInspector.overridesSupport.showExtensionLines()};
1550         if (mode === "all" || mode === "content")
1551             highlightConfig.contentColor = WebInspector.Color.PageHighlight.Content.toProtocolRGBA();
1552
1553         if (mode === "all" || mode === "padding")
1554             highlightConfig.paddingColor = WebInspector.Color.PageHighlight.Padding.toProtocolRGBA();
1555
1556         if (mode === "all" || mode === "border")
1557             highlightConfig.borderColor = WebInspector.Color.PageHighlight.Border.toProtocolRGBA();
1558
1559         if (mode === "all" || mode === "margin")
1560             highlightConfig.marginColor = WebInspector.Color.PageHighlight.Margin.toProtocolRGBA();
1561
1562         if (mode === "all") {
1563             highlightConfig.eventTargetColor = WebInspector.Color.PageHighlight.EventTarget.toProtocolRGBA();
1564             highlightConfig.shapeColor = WebInspector.Color.PageHighlight.Shape.toProtocolRGBA();
1565             highlightConfig.shapeMarginColor = WebInspector.Color.PageHighlight.ShapeMargin.toProtocolRGBA();
1566         }
1567         return highlightConfig;
1568     },
1569
1570     /**
1571      * @param {!WebInspector.DOMNode} node
1572      * @param {function(?Protocol.Error, ...)=} callback
1573      * @return {function(...)}
1574      * @template T
1575      */
1576     _markRevision: function(node, callback)
1577     {
1578         /**
1579          * @param {?Protocol.Error} error
1580          * @this {WebInspector.DOMModel}
1581          */
1582         function wrapperFunction(error)
1583         {
1584             if (!error)
1585                 this.markUndoableState();
1586
1587             if (callback)
1588                 callback.apply(this, arguments);
1589         }
1590         return wrapperFunction.bind(this);
1591     },
1592
1593     /**
1594      * @param {boolean} emulationEnabled
1595      */
1596     emulateTouchEventObjects: function(emulationEnabled)
1597     {
1598         /**
1599          * @suppressGlobalPropertiesCheck
1600          */
1601         const injectedFunction = function() {
1602             const touchEvents = ["ontouchstart", "ontouchend", "ontouchmove", "ontouchcancel"];
1603             var recepients = [window.__proto__, document.__proto__];
1604             for (var i = 0; i < touchEvents.length; ++i) {
1605                 for (var j = 0; j < recepients.length; ++j) {
1606                     if (!(touchEvents[i] in recepients[j]))
1607                         Object.defineProperty(recepients[j], touchEvents[i], { value: null, writable: true, configurable: true, enumerable: true });
1608                 }
1609             }
1610         }
1611
1612         if (emulationEnabled && !this._addTouchEventsScriptInjecting) {
1613             this._addTouchEventsScriptInjecting = true;
1614             PageAgent.addScriptToEvaluateOnLoad("(" + injectedFunction.toString() + ")()", scriptAddedCallback.bind(this));
1615         } else {
1616             if (typeof this._addTouchEventsScriptId !== "undefined") {
1617                 PageAgent.removeScriptToEvaluateOnLoad(this._addTouchEventsScriptId);
1618                 delete this._addTouchEventsScriptId;
1619             }
1620         }
1621
1622         /**
1623          * @param {?Protocol.Error} error
1624          * @param {string} scriptId
1625          * @this {WebInspector.DOMModel}
1626          */
1627         function scriptAddedCallback(error, scriptId)
1628         {
1629             delete this._addTouchEventsScriptInjecting;
1630             if (error)
1631                 return;
1632             this._addTouchEventsScriptId = scriptId;
1633         }
1634
1635         PageAgent.setTouchEmulationEnabled(emulationEnabled);
1636     },
1637
1638     markUndoableState: function()
1639     {
1640         this._agent.markUndoableState();
1641     },
1642
1643     /**
1644      * @param {function(?Protocol.Error)=} callback
1645      */
1646     undo: function(callback)
1647     {
1648         /**
1649          * @param {?Protocol.Error} error
1650          * @this {WebInspector.DOMModel}
1651          */
1652         function mycallback(error)
1653         {
1654             this.dispatchEventToListeners(WebInspector.DOMModel.Events.UndoRedoCompleted);
1655             callback(error);
1656         }
1657
1658         this.dispatchEventToListeners(WebInspector.DOMModel.Events.UndoRedoRequested);
1659         this._agent.undo(callback);
1660     },
1661
1662     /**
1663      * @param {function(?Protocol.Error)=} callback
1664      */
1665     redo: function(callback)
1666     {
1667         /**
1668          * @param {?Protocol.Error} error
1669          * @this {WebInspector.DOMModel}
1670          */
1671         function mycallback(error)
1672         {
1673             this.dispatchEventToListeners(WebInspector.DOMModel.Events.UndoRedoCompleted);
1674             callback(error);
1675         }
1676
1677         this.dispatchEventToListeners(WebInspector.DOMModel.Events.UndoRedoRequested);
1678         this._agent.redo(callback);
1679     },
1680
1681     /**
1682      * @param {?WebInspector.DOMNodeHighlighter} highlighter
1683      */
1684     setHighlighter: function(highlighter)
1685     {
1686         this._highlighter = highlighter || this._defaultHighlighter;
1687     },
1688
1689     /**
1690      * @param {number} x
1691      * @param {number} y
1692      * @param {function(?WebInspector.DOMNode)} callback
1693      */
1694     nodeForLocation: function(x, y, callback)
1695     {
1696         this._agent.getNodeForLocation(x, y, mycallback.bind(this));
1697
1698         /**
1699          * @param {?Protocol.Error} error
1700          * @param {number} nodeId
1701          * @this {WebInspector.DOMModel}
1702          */
1703         function mycallback(error, nodeId)
1704         {
1705             if (error) {
1706                 callback(null);
1707                 return;
1708             }
1709             callback(this.nodeForId(nodeId));
1710         }
1711     },
1712
1713     __proto__: WebInspector.SDKModel.prototype
1714 }
1715
1716 /**
1717  * @constructor
1718  * @implements {DOMAgent.Dispatcher}
1719  * @param {!WebInspector.DOMModel} domModel
1720  */
1721 WebInspector.DOMDispatcher = function(domModel)
1722 {
1723     this._domModel = domModel;
1724 }
1725
1726 WebInspector.DOMDispatcher.prototype = {
1727     documentUpdated: function()
1728     {
1729         this._domModel._documentUpdated();
1730     },
1731
1732     /**
1733      * @param {!DOMAgent.NodeId} nodeId
1734      */
1735     inspectNodeRequested: function(nodeId)
1736     {
1737         this._domModel._inspectNodeRequested(nodeId);
1738     },
1739
1740     /**
1741      * @param {!DOMAgent.NodeId} nodeId
1742      * @param {string} name
1743      * @param {string} value
1744      */
1745     attributeModified: function(nodeId, name, value)
1746     {
1747         this._domModel._attributeModified(nodeId, name, value);
1748     },
1749
1750     /**
1751      * @param {!DOMAgent.NodeId} nodeId
1752      * @param {string} name
1753      */
1754     attributeRemoved: function(nodeId, name)
1755     {
1756         this._domModel._attributeRemoved(nodeId, name);
1757     },
1758
1759     /**
1760      * @param {!Array.<!DOMAgent.NodeId>} nodeIds
1761      */
1762     inlineStyleInvalidated: function(nodeIds)
1763     {
1764         this._domModel._inlineStyleInvalidated(nodeIds);
1765     },
1766
1767     /**
1768      * @param {!DOMAgent.NodeId} nodeId
1769      * @param {string} characterData
1770      */
1771     characterDataModified: function(nodeId, characterData)
1772     {
1773         this._domModel._characterDataModified(nodeId, characterData);
1774     },
1775
1776     /**
1777      * @param {!DOMAgent.NodeId} parentId
1778      * @param {!Array.<!DOMAgent.Node>} payloads
1779      */
1780     setChildNodes: function(parentId, payloads)
1781     {
1782         this._domModel._setChildNodes(parentId, payloads);
1783     },
1784
1785     /**
1786      * @param {!DOMAgent.NodeId} nodeId
1787      * @param {number} childNodeCount
1788      */
1789     childNodeCountUpdated: function(nodeId, childNodeCount)
1790     {
1791         this._domModel._childNodeCountUpdated(nodeId, childNodeCount);
1792     },
1793
1794     /**
1795      * @param {!DOMAgent.NodeId} parentNodeId
1796      * @param {!DOMAgent.NodeId} previousNodeId
1797      * @param {!DOMAgent.Node} payload
1798      */
1799     childNodeInserted: function(parentNodeId, previousNodeId, payload)
1800     {
1801         this._domModel._childNodeInserted(parentNodeId, previousNodeId, payload);
1802     },
1803
1804     /**
1805      * @param {!DOMAgent.NodeId} parentNodeId
1806      * @param {!DOMAgent.NodeId} nodeId
1807      */
1808     childNodeRemoved: function(parentNodeId, nodeId)
1809     {
1810         this._domModel._childNodeRemoved(parentNodeId, nodeId);
1811     },
1812
1813     /**
1814      * @param {!DOMAgent.NodeId} hostId
1815      * @param {!DOMAgent.Node} root
1816      */
1817     shadowRootPushed: function(hostId, root)
1818     {
1819         this._domModel._shadowRootPushed(hostId, root);
1820     },
1821
1822     /**
1823      * @param {!DOMAgent.NodeId} hostId
1824      * @param {!DOMAgent.NodeId} rootId
1825      */
1826     shadowRootPopped: function(hostId, rootId)
1827     {
1828         this._domModel._shadowRootPopped(hostId, rootId);
1829     },
1830
1831     /**
1832      * @param {!DOMAgent.NodeId} parentId
1833      * @param {!DOMAgent.Node} pseudoElement
1834      */
1835     pseudoElementAdded: function(parentId, pseudoElement)
1836     {
1837         this._domModel._pseudoElementAdded(parentId, pseudoElement);
1838     },
1839
1840     /**
1841      * @param {!DOMAgent.NodeId} parentId
1842      * @param {!DOMAgent.NodeId} pseudoElementId
1843      */
1844     pseudoElementRemoved: function(parentId, pseudoElementId)
1845     {
1846         this._domModel._pseudoElementRemoved(parentId, pseudoElementId);
1847     }
1848 }
1849
1850 /**
1851  * @constructor
1852  * @extends {WebInspector.SDKObject}
1853  * @param {!WebInspector.Target} target
1854  * @param {!DOMAgent.EventListener} payload
1855  */
1856 WebInspector.DOMModel.EventListener = function(target, payload)
1857 {
1858     WebInspector.SDKObject.call(this, target);
1859     this._payload = payload;
1860     var sourceName = this._payload.sourceName;
1861     if (!sourceName) {
1862         var script = target.debuggerModel.scriptForId(payload.location.scriptId);
1863         sourceName = script ? script.contentURL() : "";
1864     }
1865     this._sourceName = sourceName;
1866 }
1867
1868 WebInspector.DOMModel.EventListener.prototype = {
1869     /**
1870      * @return {!DOMAgent.EventListener}
1871      */
1872     payload: function()
1873     {
1874         return this._payload;
1875     },
1876
1877     /**
1878      * @return {?WebInspector.DOMNode}
1879      */
1880     node: function()
1881     {
1882         return this.target().domModel.nodeForId(this._payload.nodeId);
1883     },
1884
1885     /**
1886      * @return {!WebInspector.DebuggerModel.Location}
1887      */
1888     location: function()
1889     {
1890         return WebInspector.DebuggerModel.Location.fromPayload(this.target(), this._payload.location);
1891     },
1892
1893     /**
1894      * @return {?WebInspector.RemoteObject}
1895      */
1896     handler: function()
1897     {
1898         return this._payload.handler ? this.target().runtimeModel.createRemoteObject(this._payload.handler) : null;
1899     },
1900
1901     /**
1902      * @return {string}
1903      */
1904     sourceName: function()
1905     {
1906         return this._sourceName;
1907     },
1908
1909     __proto__: WebInspector.SDKObject.prototype
1910 }
1911
1912 /**
1913  * @interface
1914  */
1915 WebInspector.DOMNodeHighlighter = function() {
1916 }
1917
1918 WebInspector.DOMNodeHighlighter.prototype = {
1919     /**
1920      * @param {?WebInspector.DOMNode} node
1921      * @param {!DOMAgent.HighlightConfig} config
1922      * @param {!RuntimeAgent.RemoteObjectId=} objectId
1923      */
1924     highlightDOMNode: function(node, config, objectId) {},
1925
1926     /**
1927      * @param {boolean} enabled
1928      * @param {boolean} inspectUAShadowDOM
1929      * @param {!DOMAgent.HighlightConfig} config
1930      * @param {function(?Protocol.Error)=} callback
1931      */
1932     setInspectModeEnabled: function(enabled, inspectUAShadowDOM, config, callback) {}
1933 }
1934
1935 /**
1936  * @constructor
1937  * @implements {WebInspector.DOMNodeHighlighter}
1938  * @param {!Protocol.DOMAgent} agent
1939  */
1940 WebInspector.DefaultDOMNodeHighlighter = function(agent)
1941 {
1942     this._agent = agent;
1943 }
1944
1945 WebInspector.DefaultDOMNodeHighlighter.prototype = {
1946     /**
1947      * @param {?WebInspector.DOMNode} node
1948      * @param {!DOMAgent.HighlightConfig} config
1949      * @param {!RuntimeAgent.RemoteObjectId=} objectId
1950      */
1951     highlightDOMNode: function(node, config, objectId)
1952     {
1953         if (objectId || node)
1954             this._agent.highlightNode(config, objectId ? undefined : node.id, objectId);
1955         else
1956             this._agent.hideHighlight();
1957     },
1958
1959     /**
1960      * @param {boolean} enabled
1961      * @param {boolean} inspectUAShadowDOM
1962      * @param {!DOMAgent.HighlightConfig} config
1963      * @param {function(?Protocol.Error)=} callback
1964      */
1965     setInspectModeEnabled: function(enabled, inspectUAShadowDOM, config, callback)
1966     {
1967         WebInspector.overridesSupport.setTouchEmulationSuspended(enabled);
1968         this._agent.setInspectModeEnabled(enabled, inspectUAShadowDOM, config, callback);
1969     }
1970 }