utils.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const { Ci, Cc } = require("chrome");
  6. const nodeFilterConstants = require("devtools/shared/dom-node-filter-constants");
  7. loader.lazyRequireGetter(this, "setIgnoreLayoutChanges", "devtools/server/actors/reflow", true);
  8. exports.setIgnoreLayoutChanges = (...args) =>
  9. this.setIgnoreLayoutChanges(...args);
  10. /**
  11. * Returns the `DOMWindowUtils` for the window given.
  12. *
  13. * @param {DOMWindow} win
  14. * @returns {DOMWindowUtils}
  15. */
  16. const utilsCache = new WeakMap();
  17. function utilsFor(win) {
  18. if (!utilsCache.has(win)) {
  19. utilsCache.set(win, win.QueryInterface(Ci.nsIInterfaceRequestor)
  20. .getInterface(Ci.nsIDOMWindowUtils));
  21. }
  22. return utilsCache.get(win);
  23. }
  24. /**
  25. * like win.top, but goes through mozbrowsers and mozapps iframes.
  26. *
  27. * @param {DOMWindow} win
  28. * @return {DOMWindow}
  29. */
  30. function getTopWindow(win) {
  31. let docShell = win.QueryInterface(Ci.nsIInterfaceRequestor)
  32. .getInterface(Ci.nsIWebNavigation)
  33. .QueryInterface(Ci.nsIDocShell);
  34. if (!docShell.isMozBrowserOrApp) {
  35. return win.top;
  36. }
  37. let topDocShell =
  38. docShell.getSameTypeRootTreeItemIgnoreBrowserAndAppBoundaries();
  39. return topDocShell
  40. ? topDocShell.contentViewer.DOMDocument.defaultView
  41. : null;
  42. }
  43. exports.getTopWindow = getTopWindow;
  44. /**
  45. * Returns `true` is the window given is a top level window.
  46. * like win.top === win, but goes through mozbrowsers and mozapps iframes.
  47. *
  48. * @param {DOMWindow} win
  49. * @return {Boolean}
  50. */
  51. const isTopWindow = win => win && getTopWindow(win) === win;
  52. exports.isTopWindow = isTopWindow;
  53. /**
  54. * Check a window is part of the boundary window given.
  55. *
  56. * @param {DOMWindow} boundaryWindow
  57. * @param {DOMWindow} win
  58. * @return {Boolean}
  59. */
  60. function isWindowIncluded(boundaryWindow, win) {
  61. if (win === boundaryWindow) {
  62. return true;
  63. }
  64. let parent = getParentWindow(win);
  65. if (!parent || parent === win) {
  66. return false;
  67. }
  68. return isWindowIncluded(boundaryWindow, parent);
  69. }
  70. exports.isWindowIncluded = isWindowIncluded;
  71. /**
  72. * like win.parent, but goes through mozbrowsers and mozapps iframes.
  73. *
  74. * @param {DOMWindow} win
  75. * @return {DOMWindow}
  76. */
  77. function getParentWindow(win) {
  78. if (isTopWindow(win)) {
  79. return null;
  80. }
  81. let docShell = win.QueryInterface(Ci.nsIInterfaceRequestor)
  82. .getInterface(Ci.nsIWebNavigation)
  83. .QueryInterface(Ci.nsIDocShell);
  84. if (!docShell.isMozBrowserOrApp) {
  85. return win.parent;
  86. }
  87. let parentDocShell =
  88. docShell.getSameTypeParentIgnoreBrowserAndAppBoundaries();
  89. return parentDocShell
  90. ? parentDocShell.contentViewer.DOMDocument.defaultView
  91. : null;
  92. }
  93. exports.getParentWindow = getParentWindow;
  94. /**
  95. * like win.frameElement, but goes through mozbrowsers and mozapps iframes.
  96. *
  97. * @param {DOMWindow} win
  98. * The window to get the frame for
  99. * @return {DOMNode}
  100. * The element in which the window is embedded.
  101. */
  102. const getFrameElement = (win) =>
  103. isTopWindow(win) ? null : utilsFor(win).containerElement;
  104. exports.getFrameElement = getFrameElement;
  105. /**
  106. * Get the x/y offsets for of all the parent frames of a given node, limited to
  107. * the boundary window given.
  108. *
  109. * @param {DOMWindow} boundaryWindow
  110. * The window where to stop to iterate. If `null` is given, the top
  111. * window is used.
  112. * @param {DOMNode} node
  113. * The node for which we are to get the offset
  114. * @return {Array}
  115. * The frame offset [x, y]
  116. */
  117. function getFrameOffsets(boundaryWindow, node) {
  118. let xOffset = 0;
  119. let yOffset = 0;
  120. let frameWin = getWindowFor(node);
  121. let scale = getCurrentZoom(node);
  122. if (boundaryWindow === null) {
  123. boundaryWindow = getTopWindow(frameWin);
  124. } else if (typeof boundaryWindow === "undefined") {
  125. throw new Error("No boundaryWindow given. Use null for the default one.");
  126. }
  127. while (frameWin !== boundaryWindow) {
  128. let frameElement = getFrameElement(frameWin);
  129. if (!frameElement) {
  130. break;
  131. }
  132. // We are in an iframe.
  133. // We take into account the parent iframe position and its
  134. // offset (borders and padding).
  135. let frameRect = frameElement.getBoundingClientRect();
  136. let [offsetTop, offsetLeft] = getFrameContentOffset(frameElement);
  137. xOffset += frameRect.left + offsetLeft;
  138. yOffset += frameRect.top + offsetTop;
  139. frameWin = getParentWindow(frameWin);
  140. }
  141. return [xOffset * scale, yOffset * scale];
  142. }
  143. exports.getFrameOffsets = getFrameOffsets;
  144. /**
  145. * Get box quads adjusted for iframes and zoom level.
  146. *
  147. * @param {DOMWindow} boundaryWindow
  148. * The window where to stop to iterate. If `null` is given, the top
  149. * window is used.
  150. * @param {DOMNode} node
  151. * The node for which we are to get the box model region
  152. * quads.
  153. * @param {String} region
  154. * The box model region to return: "content", "padding", "border" or
  155. * "margin".
  156. * @return {Array}
  157. * An array of objects that have the same structure as quads returned by
  158. * getBoxQuads. An empty array if the node has no quads or is invalid.
  159. */
  160. function getAdjustedQuads(boundaryWindow, node, region) {
  161. if (!node || !node.getBoxQuads) {
  162. return [];
  163. }
  164. let quads = node.getBoxQuads({
  165. box: region
  166. });
  167. if (!quads.length) {
  168. return [];
  169. }
  170. let [xOffset, yOffset] = getFrameOffsets(boundaryWindow, node);
  171. let scale = getCurrentZoom(node);
  172. let adjustedQuads = [];
  173. for (let quad of quads) {
  174. adjustedQuads.push({
  175. p1: {
  176. w: quad.p1.w * scale,
  177. x: quad.p1.x * scale + xOffset,
  178. y: quad.p1.y * scale + yOffset,
  179. z: quad.p1.z * scale
  180. },
  181. p2: {
  182. w: quad.p2.w * scale,
  183. x: quad.p2.x * scale + xOffset,
  184. y: quad.p2.y * scale + yOffset,
  185. z: quad.p2.z * scale
  186. },
  187. p3: {
  188. w: quad.p3.w * scale,
  189. x: quad.p3.x * scale + xOffset,
  190. y: quad.p3.y * scale + yOffset,
  191. z: quad.p3.z * scale
  192. },
  193. p4: {
  194. w: quad.p4.w * scale,
  195. x: quad.p4.x * scale + xOffset,
  196. y: quad.p4.y * scale + yOffset,
  197. z: quad.p4.z * scale
  198. },
  199. bounds: {
  200. bottom: quad.bounds.bottom * scale + yOffset,
  201. height: quad.bounds.height * scale,
  202. left: quad.bounds.left * scale + xOffset,
  203. right: quad.bounds.right * scale + xOffset,
  204. top: quad.bounds.top * scale + yOffset,
  205. width: quad.bounds.width * scale,
  206. x: quad.bounds.x * scale + xOffset,
  207. y: quad.bounds.y * scale + yOffset
  208. }
  209. });
  210. }
  211. return adjustedQuads;
  212. }
  213. exports.getAdjustedQuads = getAdjustedQuads;
  214. /**
  215. * Compute the absolute position and the dimensions of a node, relativalely
  216. * to the root window.
  217. * @param {DOMWindow} boundaryWindow
  218. * The window where to stop to iterate. If `null` is given, the top
  219. * window is used.
  220. * @param {DOMNode} node
  221. * a DOM element to get the bounds for
  222. * @param {DOMWindow} contentWindow
  223. * the content window holding the node
  224. * @return {Object}
  225. * A rect object with the {top, left, width, height} properties
  226. */
  227. function getRect(boundaryWindow, node, contentWindow) {
  228. let frameWin = node.ownerDocument.defaultView;
  229. let clientRect = node.getBoundingClientRect();
  230. if (boundaryWindow === null) {
  231. boundaryWindow = getTopWindow(frameWin);
  232. } else if (typeof boundaryWindow === "undefined") {
  233. throw new Error("No boundaryWindow given. Use null for the default one.");
  234. }
  235. // Go up in the tree of frames to determine the correct rectangle.
  236. // clientRect is read-only, we need to be able to change properties.
  237. let rect = {
  238. top: clientRect.top + contentWindow.pageYOffset,
  239. left: clientRect.left + contentWindow.pageXOffset,
  240. width: clientRect.width,
  241. height: clientRect.height
  242. };
  243. // We iterate through all the parent windows.
  244. while (frameWin !== boundaryWindow) {
  245. let frameElement = getFrameElement(frameWin);
  246. if (!frameElement) {
  247. break;
  248. }
  249. // We are in an iframe.
  250. // We take into account the parent iframe position and its
  251. // offset (borders and padding).
  252. let frameRect = frameElement.getBoundingClientRect();
  253. let [offsetTop, offsetLeft] = getFrameContentOffset(frameElement);
  254. rect.top += frameRect.top + offsetTop;
  255. rect.left += frameRect.left + offsetLeft;
  256. frameWin = getParentWindow(frameWin);
  257. }
  258. return rect;
  259. }
  260. exports.getRect = getRect;
  261. /**
  262. * Get the 4 bounding points for a node taking iframes into account.
  263. * Note that for transformed nodes, this will return the untransformed bound.
  264. *
  265. * @param {DOMWindow} boundaryWindow
  266. * The window where to stop to iterate. If `null` is given, the top
  267. * window is used.
  268. * @param {DOMNode} node
  269. * @return {Object}
  270. * An object with p1,p2,p3,p4 properties being {x,y} objects
  271. */
  272. function getNodeBounds(boundaryWindow, node) {
  273. if (!node) {
  274. return null;
  275. }
  276. let scale = getCurrentZoom(node);
  277. // Find out the offset of the node in its current frame
  278. let offsetLeft = 0;
  279. let offsetTop = 0;
  280. let el = node;
  281. while (el && el.parentNode) {
  282. offsetLeft += el.offsetLeft;
  283. offsetTop += el.offsetTop;
  284. el = el.offsetParent;
  285. }
  286. // Also take scrolled containers into account
  287. el = node;
  288. while (el && el.parentNode) {
  289. if (el.scrollTop) {
  290. offsetTop -= el.scrollTop;
  291. }
  292. if (el.scrollLeft) {
  293. offsetLeft -= el.scrollLeft;
  294. }
  295. el = el.parentNode;
  296. }
  297. // And add the potential frame offset if the node is nested
  298. let [xOffset, yOffset] = getFrameOffsets(boundaryWindow, node);
  299. xOffset += offsetLeft;
  300. yOffset += offsetTop;
  301. xOffset *= scale;
  302. yOffset *= scale;
  303. // Get the width and height
  304. let width = node.offsetWidth * scale;
  305. let height = node.offsetHeight * scale;
  306. return {
  307. p1: {x: xOffset, y: yOffset},
  308. p2: {x: xOffset + width, y: yOffset},
  309. p3: {x: xOffset + width, y: yOffset + height},
  310. p4: {x: xOffset, y: yOffset + height}
  311. };
  312. }
  313. exports.getNodeBounds = getNodeBounds;
  314. /**
  315. * Same as doing iframe.contentWindow but works with all types of container
  316. * elements that act like frames (e.g. <embed>), where 'contentWindow' isn't a
  317. * property that can be accessed.
  318. * This uses the inIDeepTreeWalker instead.
  319. * @param {DOMNode} frame
  320. * @return {Window}
  321. */
  322. function safelyGetContentWindow(frame) {
  323. if (frame.contentWindow) {
  324. return frame.contentWindow;
  325. }
  326. let walker = Cc["@mozilla.org/inspector/deep-tree-walker;1"]
  327. .createInstance(Ci.inIDeepTreeWalker);
  328. walker.showSubDocuments = true;
  329. walker.showDocumentsAsNodes = true;
  330. walker.init(frame, nodeFilterConstants.SHOW_ALL);
  331. walker.currentNode = frame;
  332. let document = walker.nextNode();
  333. if (!document || !document.defaultView) {
  334. throw new Error("Couldn't get the content window inside frame " + frame);
  335. }
  336. return document.defaultView;
  337. }
  338. /**
  339. * Returns a frame's content offset (frame border + padding).
  340. * Note: this function shouldn't need to exist, had the platform provided a
  341. * suitable API for determining the offset between the frame's content and
  342. * its bounding client rect. Bug 626359 should provide us with such an API.
  343. *
  344. * @param {DOMNode} frame
  345. * The frame.
  346. * @return {Array} [offsetTop, offsetLeft]
  347. * offsetTop is the distance from the top of the frame and the top of
  348. * the content document.
  349. * offsetLeft is the distance from the left of the frame and the left
  350. * of the content document.
  351. */
  352. function getFrameContentOffset(frame) {
  353. let style = safelyGetContentWindow(frame).getComputedStyle(frame, null);
  354. // In some cases, the computed style is null
  355. if (!style) {
  356. return [0, 0];
  357. }
  358. let paddingTop = parseInt(style.getPropertyValue("padding-top"), 10);
  359. let paddingLeft = parseInt(style.getPropertyValue("padding-left"), 10);
  360. let borderTop = parseInt(style.getPropertyValue("border-top-width"), 10);
  361. let borderLeft = parseInt(style.getPropertyValue("border-left-width"), 10);
  362. return [borderTop + paddingTop, borderLeft + paddingLeft];
  363. }
  364. /**
  365. * Find an element from the given coordinates. This method descends through
  366. * frames to find the element the user clicked inside frames.
  367. *
  368. * @param {DOMDocument} document
  369. * The document to look into.
  370. * @param {Number} x
  371. * @param {Number} y
  372. * @return {DOMNode}
  373. * the element node found at the given coordinates, or null if no node
  374. * was found
  375. */
  376. function getElementFromPoint(document, x, y) {
  377. let node = document.elementFromPoint(x, y);
  378. if (node && node.contentDocument) {
  379. if (node instanceof Ci.nsIDOMHTMLIFrameElement) {
  380. let rect = node.getBoundingClientRect();
  381. // Gap between the frame and its content window.
  382. let [offsetTop, offsetLeft] = getFrameContentOffset(node);
  383. x -= rect.left + offsetLeft;
  384. y -= rect.top + offsetTop;
  385. if (x < 0 || y < 0) {
  386. // Didn't reach the content document, still over the frame.
  387. return node;
  388. }
  389. }
  390. if (node instanceof Ci.nsIDOMHTMLIFrameElement ||
  391. node instanceof Ci.nsIDOMHTMLFrameElement) {
  392. let subnode = getElementFromPoint(node.contentDocument, x, y);
  393. if (subnode) {
  394. node = subnode;
  395. }
  396. }
  397. }
  398. return node;
  399. }
  400. exports.getElementFromPoint = getElementFromPoint;
  401. /**
  402. * Check if a node and its document are still alive
  403. * and attached to the window.
  404. *
  405. * @param {DOMNode} node
  406. * @return {Boolean}
  407. */
  408. function isNodeConnected(node) {
  409. if (!node.ownerDocument || !node.ownerDocument.defaultView) {
  410. return false;
  411. }
  412. try {
  413. return !(node.compareDocumentPosition(node.ownerDocument.documentElement) &
  414. node.DOCUMENT_POSITION_DISCONNECTED);
  415. } catch (e) {
  416. // "can't access dead object" error
  417. return false;
  418. }
  419. }
  420. exports.isNodeConnected = isNodeConnected;
  421. /**
  422. * Traverse getBindingParent until arriving upon the bound element
  423. * responsible for the generation of the specified node.
  424. * See https://developer.mozilla.org/en-US/docs/XBL/XBL_1.0_Reference/DOM_Interfaces#getBindingParent.
  425. *
  426. * @param {DOMNode} node
  427. * @return {DOMNode}
  428. * If node is not anonymous, this will return node. Otherwise,
  429. * it will return the bound element
  430. *
  431. */
  432. function getRootBindingParent(node) {
  433. let parent;
  434. let doc = node.ownerDocument;
  435. if (!doc) {
  436. return node;
  437. }
  438. while ((parent = doc.getBindingParent(node))) {
  439. node = parent;
  440. }
  441. return node;
  442. }
  443. exports.getRootBindingParent = getRootBindingParent;
  444. function getBindingParent(node) {
  445. let doc = node.ownerDocument;
  446. if (!doc) {
  447. return null;
  448. }
  449. // If there is no binding parent then it is not anonymous.
  450. let parent = doc.getBindingParent(node);
  451. if (!parent) {
  452. return null;
  453. }
  454. return parent;
  455. }
  456. exports.getBindingParent = getBindingParent;
  457. /**
  458. * Determine whether a node is anonymous by determining if there
  459. * is a bindingParent.
  460. *
  461. * @param {DOMNode} node
  462. * @return {Boolean}
  463. *
  464. */
  465. const isAnonymous = (node) => getRootBindingParent(node) !== node;
  466. exports.isAnonymous = isAnonymous;
  467. /**
  468. * Determine whether a node has a bindingParent.
  469. *
  470. * @param {DOMNode} node
  471. * @return {Boolean}
  472. *
  473. */
  474. const hasBindingParent = (node) => !!getBindingParent(node);
  475. /**
  476. * Determine whether a node is native anonymous content (as opposed
  477. * to XBL anonymous or shadow DOM).
  478. * Native anonymous content includes elements like internals to form
  479. * controls and ::before/::after.
  480. *
  481. * @param {DOMNode} node
  482. * @return {Boolean}
  483. *
  484. */
  485. const isNativeAnonymous = (node) =>
  486. hasBindingParent(node) && !(isXBLAnonymous(node) || isShadowAnonymous(node));
  487. exports.isNativeAnonymous = isNativeAnonymous;
  488. /**
  489. * Determine whether a node is XBL anonymous content (as opposed
  490. * to native anonymous or shadow DOM).
  491. * See https://developer.mozilla.org/en-US/docs/XBL/XBL_1.0_Reference/Anonymous_Content.
  492. *
  493. * @param {DOMNode} node
  494. * @return {Boolean}
  495. *
  496. */
  497. function isXBLAnonymous(node) {
  498. let parent = getBindingParent(node);
  499. if (!parent) {
  500. return false;
  501. }
  502. // Shadow nodes also show up in getAnonymousNodes, so return false.
  503. if (parent.shadowRoot && parent.shadowRoot.contains(node)) {
  504. return false;
  505. }
  506. let anonNodes = [...node.ownerDocument.getAnonymousNodes(parent) || []];
  507. return anonNodes.indexOf(node) > -1;
  508. }
  509. exports.isXBLAnonymous = isXBLAnonymous;
  510. /**
  511. * Determine whether a node is a child of a shadow root.
  512. * See https://w3c.github.io/webcomponents/spec/shadow/
  513. *
  514. * @param {DOMNode} node
  515. * @return {Boolean}
  516. */
  517. function isShadowAnonymous(node) {
  518. let parent = getBindingParent(node);
  519. if (!parent) {
  520. return false;
  521. }
  522. // If there is a shadowRoot and this is part of it then this
  523. // is not native anonymous
  524. return parent.shadowRoot && parent.shadowRoot.contains(node);
  525. }
  526. exports.isShadowAnonymous = isShadowAnonymous;
  527. /**
  528. * Get the current zoom factor applied to the container window of a given node.
  529. * Container windows are used as a weakmap key to store the corresponding
  530. * nsIDOMWindowUtils instance to avoid querying it every time.
  531. *
  532. * @param {DOMNode|DOMWindow}
  533. * The node for which the zoom factor should be calculated, or its
  534. * owner window.
  535. * @return {Number}
  536. */
  537. function getCurrentZoom(node) {
  538. let win = getWindowFor(node);
  539. if (!win) {
  540. throw new Error("Unable to get the zoom from the given argument.");
  541. }
  542. return utilsFor(win).fullZoom;
  543. }
  544. exports.getCurrentZoom = getCurrentZoom;
  545. /**
  546. * Return the default view for a given node, where node can be:
  547. * - a DOM node
  548. * - the document node
  549. * - the window itself
  550. * @param {DOMNode|DOMWindow|DOMDocument} node The node to get the window for.
  551. * @return {DOMWindow}
  552. */
  553. function getWindowFor(node) {
  554. if (node instanceof Ci.nsIDOMNode) {
  555. if (node.nodeType === node.DOCUMENT_NODE) {
  556. return node.defaultView;
  557. }
  558. return node.ownerDocument.defaultView;
  559. } else if (node instanceof Ci.nsIDOMWindow) {
  560. return node;
  561. }
  562. return null;
  563. }