context-menu.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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. module.metadata = {
  6. "stability": "stable",
  7. "engines": {
  8. // TODO Fennec support Bug 788334
  9. "Firefox": "*"
  10. }
  11. };
  12. const { Class, mix } = require("./core/heritage");
  13. const { addCollectionProperty } = require("./util/collection");
  14. const { ns } = require("./core/namespace");
  15. const { validateOptions, getTypeOf } = require("./deprecated/api-utils");
  16. const { URL, isValidURI } = require("./url");
  17. const { WindowTracker, browserWindowIterator } = require("./deprecated/window-utils");
  18. const { isBrowser, getInnerId } = require("./window/utils");
  19. const { Ci } = require("chrome");
  20. const { MatchPattern } = require("./util/match-pattern");
  21. const { Worker } = require("./content/worker");
  22. const { EventTarget } = require("./event/target");
  23. const { emit } = require('./event/core');
  24. const { when } = require('./system/unload');
  25. const selection = require('./selection');
  26. // All user items we add have this class.
  27. const ITEM_CLASS = "addon-context-menu-item";
  28. // Items in the top-level context menu also have this class.
  29. const TOPLEVEL_ITEM_CLASS = "addon-context-menu-item-toplevel";
  30. // Items in the overflow submenu also have this class.
  31. const OVERFLOW_ITEM_CLASS = "addon-context-menu-item-overflow";
  32. // The class of the menu separator that separates standard context menu items
  33. // from our user items.
  34. const SEPARATOR_CLASS = "addon-context-menu-separator";
  35. // If more than this number of items are added to the context menu, all items
  36. // overflow into a "Jetpack" submenu.
  37. const OVERFLOW_THRESH_DEFAULT = 10;
  38. const OVERFLOW_THRESH_PREF =
  39. "extensions.addon-sdk.context-menu.overflowThreshold";
  40. // The label of the overflow sub-xul:menu.
  41. //
  42. // TODO: Localize this.
  43. const OVERFLOW_MENU_LABEL = "Add-ons";
  44. // The class of the overflow sub-xul:menu.
  45. const OVERFLOW_MENU_CLASS = "addon-content-menu-overflow-menu";
  46. // The class of the overflow submenu's xul:menupopup.
  47. const OVERFLOW_POPUP_CLASS = "addon-content-menu-overflow-popup";
  48. //These are used by PageContext.isCurrent below. If the popupNode or any of
  49. //its ancestors is one of these, Firefox uses a tailored context menu, and so
  50. //the page context doesn't apply.
  51. const NON_PAGE_CONTEXT_ELTS = [
  52. Ci.nsIDOMHTMLAnchorElement,
  53. Ci.nsIDOMHTMLAppletElement,
  54. Ci.nsIDOMHTMLAreaElement,
  55. Ci.nsIDOMHTMLButtonElement,
  56. Ci.nsIDOMHTMLCanvasElement,
  57. Ci.nsIDOMHTMLEmbedElement,
  58. Ci.nsIDOMHTMLImageElement,
  59. Ci.nsIDOMHTMLInputElement,
  60. Ci.nsIDOMHTMLMapElement,
  61. Ci.nsIDOMHTMLMediaElement,
  62. Ci.nsIDOMHTMLMenuElement,
  63. Ci.nsIDOMHTMLObjectElement,
  64. Ci.nsIDOMHTMLOptionElement,
  65. Ci.nsIDOMHTMLSelectElement,
  66. Ci.nsIDOMHTMLTextAreaElement,
  67. ];
  68. // Holds private properties for API objects
  69. let internal = ns();
  70. function getScheme(spec) {
  71. try {
  72. return URL(spec).scheme;
  73. }
  74. catch(e) {
  75. return null;
  76. }
  77. }
  78. let Context = Class({
  79. // Returns the node that made this context current
  80. adjustPopupNode: function adjustPopupNode(popupNode) {
  81. return popupNode;
  82. },
  83. // Returns whether this context is current for the current node
  84. isCurrent: function isCurrent(popupNode) {
  85. return false;
  86. }
  87. });
  88. // Matches when the context-clicked node doesn't have any of
  89. // NON_PAGE_CONTEXT_ELTS in its ancestors
  90. let PageContext = Class({
  91. extends: Context,
  92. isCurrent: function isCurrent(popupNode) {
  93. // If there is a selection in the window then this context does not match
  94. if (!popupNode.ownerDocument.defaultView.getSelection().isCollapsed)
  95. return false;
  96. // If the clicked node or any of its ancestors is one of the blacklisted
  97. // NON_PAGE_CONTEXT_ELTS then this context does not match
  98. while (!(popupNode instanceof Ci.nsIDOMDocument)) {
  99. if (NON_PAGE_CONTEXT_ELTS.some(function(type) popupNode instanceof type))
  100. return false;
  101. popupNode = popupNode.parentNode;
  102. }
  103. return true;
  104. }
  105. });
  106. exports.PageContext = PageContext;
  107. // Matches when there is an active selection in the window
  108. let SelectionContext = Class({
  109. extends: Context,
  110. isCurrent: function isCurrent(popupNode) {
  111. if (!popupNode.ownerDocument.defaultView.getSelection().isCollapsed)
  112. return true;
  113. try {
  114. // The node may be a text box which has selectionStart and selectionEnd
  115. // properties. If not this will throw.
  116. let { selectionStart, selectionEnd } = popupNode;
  117. return !isNaN(selectionStart) && !isNaN(selectionEnd) &&
  118. selectionStart !== selectionEnd;
  119. }
  120. catch (e) {
  121. return false;
  122. }
  123. }
  124. });
  125. exports.SelectionContext = SelectionContext;
  126. // Matches when the context-clicked node or any of its ancestors matches the
  127. // selector given
  128. let SelectorContext = Class({
  129. extends: Context,
  130. initialize: function initialize(selector) {
  131. let options = validateOptions({ selector: selector }, {
  132. selector: {
  133. is: ["string"],
  134. msg: "selector must be a string."
  135. }
  136. });
  137. internal(this).selector = options.selector;
  138. },
  139. adjustPopupNode: function adjustPopupNode(popupNode) {
  140. let selector = internal(this).selector;
  141. while (!(popupNode instanceof Ci.nsIDOMDocument)) {
  142. if (popupNode.mozMatchesSelector(selector))
  143. return popupNode;
  144. popupNode = popupNode.parentNode;
  145. }
  146. return null;
  147. },
  148. isCurrent: function isCurrent(popupNode) {
  149. return !!this.adjustPopupNode(popupNode);
  150. }
  151. });
  152. exports.SelectorContext = SelectorContext;
  153. // Matches when the page url matches any of the patterns given
  154. let URLContext = Class({
  155. extends: Context,
  156. initialize: function initialize(patterns) {
  157. patterns = Array.isArray(patterns) ? patterns : [patterns];
  158. try {
  159. internal(this).patterns = patterns.map(function (p) new MatchPattern(p));
  160. }
  161. catch (err) {
  162. throw new Error("Patterns must be a string, regexp or an array of " +
  163. "strings or regexps: " + err);
  164. }
  165. },
  166. isCurrent: function isCurrent(popupNode) {
  167. let url = popupNode.ownerDocument.URL;
  168. return internal(this).patterns.some(function (p) p.test(url));
  169. }
  170. });
  171. exports.URLContext = URLContext;
  172. // Matches when the user-supplied predicate returns true
  173. let PredicateContext = Class({
  174. extends: Context,
  175. initialize: function initialize(predicate) {
  176. let options = validateOptions({ predicate: predicate }, {
  177. predicate: {
  178. is: ["function"],
  179. msg: "predicate must be a function."
  180. }
  181. });
  182. internal(this).predicate = options.predicate;
  183. },
  184. isCurrent: function isCurrent(popupNode) {
  185. return internal(this).predicate(populateCallbackNodeData(popupNode));
  186. }
  187. });
  188. exports.PredicateContext = PredicateContext;
  189. // List all editable types of inputs. Or is it better to have a list
  190. // of non-editable inputs?
  191. let editableInputs = {
  192. email: true,
  193. number: true,
  194. password: true,
  195. search: true,
  196. tel: true,
  197. text: true,
  198. textarea: true,
  199. url: true
  200. };
  201. function populateCallbackNodeData(node) {
  202. let window = node.ownerDocument.defaultView;
  203. let data = {};
  204. data.documentType = node.ownerDocument.contentType;
  205. data.documentURL = node.ownerDocument.location.href;
  206. data.targetName = node.nodeName.toLowerCase();
  207. data.targetID = node.id || null ;
  208. if ((data.targetName === 'input' && editableInputs[node.type]) ||
  209. data.targetName === 'textarea') {
  210. data.isEditable = !node.readOnly && !node.disabled;
  211. }
  212. else {
  213. data.isEditable = node.isContentEditable;
  214. }
  215. data.selectionText = selection.text;
  216. data.srcURL = node.src || null;
  217. data.linkURL = node.href || null;
  218. data.value = node.value || null;
  219. return data;
  220. }
  221. function removeItemFromArray(array, item) {
  222. return array.filter(function(i) i !== item);
  223. }
  224. // Converts anything that isn't false, null or undefined into a string
  225. function stringOrNull(val) val ? String(val) : val;
  226. // Shared option validation rules for Item and Menu
  227. let baseItemRules = {
  228. parentMenu: {
  229. is: ["object", "undefined"],
  230. ok: function (v) {
  231. if (!v)
  232. return true;
  233. return (v instanceof ItemContainer) || (v instanceof Menu);
  234. },
  235. msg: "parentMenu must be a Menu or not specified."
  236. },
  237. context: {
  238. is: ["undefined", "object", "array"],
  239. ok: function (v) {
  240. if (!v)
  241. return true;
  242. let arr = Array.isArray(v) ? v : [v];
  243. return arr.every(function (o) o instanceof Context);
  244. },
  245. msg: "The 'context' option must be a Context object or an array of " +
  246. "Context objects."
  247. },
  248. contentScript: {
  249. is: ["string", "array", "undefined"],
  250. ok: function (v) {
  251. return !Array.isArray(v) ||
  252. v.every(function (s) typeof(s) === "string");
  253. }
  254. },
  255. contentScriptFile: {
  256. is: ["string", "array", "undefined"],
  257. ok: function (v) {
  258. if (!v)
  259. return true;
  260. let arr = Array.isArray(v) ? v : [v];
  261. return arr.every(function (s) {
  262. return getTypeOf(s) === "string" &&
  263. getScheme(s) === 'resource';
  264. });
  265. },
  266. msg: "The 'contentScriptFile' option must be a local file URL or " +
  267. "an array of local file URLs."
  268. },
  269. onMessage: {
  270. is: ["function", "undefined"]
  271. }
  272. };
  273. let labelledItemRules = mix(baseItemRules, {
  274. label: {
  275. map: stringOrNull,
  276. is: ["string"],
  277. ok: function (v) !!v,
  278. msg: "The item must have a non-empty string label."
  279. },
  280. image: {
  281. map: stringOrNull,
  282. is: ["string", "undefined", "null"],
  283. ok: function (url) {
  284. if (!url)
  285. return true;
  286. return isValidURI(url);
  287. },
  288. msg: "Image URL validation failed"
  289. }
  290. });
  291. // Additional validation rules for Item
  292. let itemRules = mix(labelledItemRules, {
  293. data: {
  294. map: stringOrNull,
  295. is: ["string", "undefined", "null"]
  296. }
  297. });
  298. // Additional validation rules for Menu
  299. let menuRules = mix(labelledItemRules, {
  300. items: {
  301. is: ["array", "undefined"],
  302. ok: function (v) {
  303. if (!v)
  304. return true;
  305. return v.every(function (item) {
  306. return item instanceof BaseItem;
  307. });
  308. },
  309. msg: "items must be an array, and each element in the array must be an " +
  310. "Item, Menu, or Separator."
  311. }
  312. });
  313. let ContextWorker = Class({
  314. implements: [ Worker ],
  315. //Returns true if any context listeners are defined in the worker's port.
  316. anyContextListeners: function anyContextListeners() {
  317. return this.getSandbox().hasListenerFor("context");
  318. },
  319. // Calls the context workers context listeners and returns the first result
  320. // that is either a string or a value that evaluates to true. If all of the
  321. // listeners returned false then returns false. If there are no listeners
  322. // then returns null.
  323. getMatchedContext: function getCurrentContexts(popupNode) {
  324. let results = this.getSandbox().emitSync("context", popupNode);
  325. return results.reduce(function(val, result) val || result, null);
  326. },
  327. // Emits a click event in the worker's port. popupNode is the node that was
  328. // context-clicked, and clickedItemData is the data of the item that was
  329. // clicked.
  330. fireClick: function fireClick(popupNode, clickedItemData) {
  331. this.getSandbox().emitSync("click", popupNode, clickedItemData);
  332. }
  333. });
  334. // Returns true if any contexts match. If there are no contexts then a
  335. // PageContext is tested instead
  336. function hasMatchingContext(contexts, popupNode) {
  337. for (let context in contexts) {
  338. if (!context.isCurrent(popupNode))
  339. return false;
  340. }
  341. return true;
  342. }
  343. // Gets the matched context from any worker for this item. If there is no worker
  344. // or no matched context then returns false.
  345. function getCurrentWorkerContext(item, popupNode) {
  346. let worker = getItemWorkerForWindow(item, popupNode.ownerDocument.defaultView);
  347. if (!worker || !worker.anyContextListeners())
  348. return true;
  349. return worker.getMatchedContext(popupNode);
  350. }
  351. // Tests whether an item should be visible or not based on its contexts and
  352. // content scripts
  353. function isItemVisible(item, popupNode, defaultVisibility) {
  354. if (!item.context.length) {
  355. let worker = getItemWorkerForWindow(item, popupNode.ownerDocument.defaultView);
  356. if (!worker || !worker.anyContextListeners())
  357. return defaultVisibility;
  358. }
  359. if (!hasMatchingContext(item.context, popupNode))
  360. return false;
  361. let context = getCurrentWorkerContext(item, popupNode);
  362. if (typeof(context) === "string" && context != "")
  363. item.label = context;
  364. return !!context;
  365. }
  366. // Gets the item's content script worker for a window, creating one if necessary
  367. // Once created it will be automatically destroyed when the window unloads.
  368. // If there is not content scripts for the item then null will be returned.
  369. function getItemWorkerForWindow(item, window) {
  370. if (!item.contentScript && !item.contentScriptFile)
  371. return null;
  372. let id = getInnerId(window);
  373. let worker = internal(item).workerMap.get(id);
  374. if (worker)
  375. return worker;
  376. worker = ContextWorker({
  377. window: window,
  378. contentScript: item.contentScript,
  379. contentScriptFile: item.contentScriptFile,
  380. onMessage: function(msg) {
  381. emit(item, "message", msg);
  382. },
  383. onDetach: function() {
  384. internal(item).workerMap.delete(id);
  385. }
  386. });
  387. internal(item).workerMap.set(id, worker);
  388. return worker;
  389. }
  390. // Called when an item is clicked to send out click events to the content
  391. // scripts
  392. function itemClicked(item, clickedItem, popupNode) {
  393. let worker = getItemWorkerForWindow(item, popupNode.ownerDocument.defaultView);
  394. if (worker) {
  395. let adjustedNode = popupNode;
  396. for (let context in item.context)
  397. adjustedNode = context.adjustPopupNode(adjustedNode);
  398. worker.fireClick(adjustedNode, clickedItem.data);
  399. }
  400. if (item.parentMenu)
  401. itemClicked(item.parentMenu, clickedItem, popupNode);
  402. }
  403. // All things that appear in the context menu extend this
  404. let BaseItem = Class({
  405. initialize: function initialize() {
  406. addCollectionProperty(this, "context");
  407. // Used to cache content script workers and the windows they have been
  408. // created for
  409. internal(this).workerMap = new Map();
  410. if ("context" in internal(this).options && internal(this).options.context) {
  411. let contexts = internal(this).options.context;
  412. if (Array.isArray(contexts)) {
  413. for (let context of contexts)
  414. this.context.add(context);
  415. }
  416. else {
  417. this.context.add(contexts);
  418. }
  419. }
  420. let parentMenu = internal(this).options.parentMenu;
  421. if (!parentMenu)
  422. parentMenu = contentContextMenu;
  423. parentMenu.addItem(this);
  424. Object.defineProperty(this, "contentScript", {
  425. enumerable: true,
  426. value: internal(this).options.contentScript
  427. });
  428. Object.defineProperty(this, "contentScriptFile", {
  429. enumerable: true,
  430. value: internal(this).options.contentScriptFile
  431. });
  432. },
  433. destroy: function destroy() {
  434. if (this.parentMenu)
  435. this.parentMenu.removeItem(this);
  436. },
  437. get parentMenu() {
  438. return internal(this).parentMenu;
  439. },
  440. });
  441. // All things that have a label on the context menu extend this
  442. let LabelledItem = Class({
  443. extends: BaseItem,
  444. implements: [ EventTarget ],
  445. initialize: function initialize(options) {
  446. BaseItem.prototype.initialize.call(this);
  447. EventTarget.prototype.initialize.call(this, options);
  448. },
  449. destroy: function destroy() {
  450. for (let [,worker] of internal(this).workerMap)
  451. worker.destroy();
  452. BaseItem.prototype.destroy.call(this);
  453. },
  454. get label() {
  455. return internal(this).options.label;
  456. },
  457. set label(val) {
  458. internal(this).options.label = val;
  459. MenuManager.updateItem(this);
  460. },
  461. get image() {
  462. return internal(this).options.image;
  463. },
  464. set image(val) {
  465. internal(this).options.image = val;
  466. MenuManager.updateItem(this);
  467. },
  468. get data() {
  469. return internal(this).options.data;
  470. },
  471. set data(val) {
  472. internal(this).options.data = val;
  473. }
  474. });
  475. let Item = Class({
  476. extends: LabelledItem,
  477. initialize: function initialize(options) {
  478. internal(this).options = validateOptions(options, itemRules);
  479. LabelledItem.prototype.initialize.call(this, options);
  480. },
  481. toString: function toString() {
  482. return "[object Item \"" + this.label + "\"]";
  483. },
  484. get data() {
  485. return internal(this).options.data;
  486. },
  487. set data(val) {
  488. internal(this).options.data = val;
  489. MenuManager.updateItem(this);
  490. },
  491. });
  492. exports.Item = Item;
  493. let ItemContainer = Class({
  494. initialize: function initialize() {
  495. internal(this).children = [];
  496. },
  497. destroy: function destroy() {
  498. // Destroys the entire hierarchy
  499. for (let item of internal(this).children)
  500. item.destroy();
  501. },
  502. addItem: function addItem(item) {
  503. let oldParent = item.parentMenu;
  504. // Don't just call removeItem here as that would remove the corresponding
  505. // UI element which is more costly than just moving it to the right place
  506. if (oldParent)
  507. internal(oldParent).children = removeItemFromArray(internal(oldParent).children, item);
  508. let after = null;
  509. let children = internal(this).children;
  510. if (children.length > 0)
  511. after = children[children.length - 1];
  512. children.push(item);
  513. internal(item).parentMenu = this;
  514. // If there was an old parent then we just have to move the item, otherwise
  515. // it needs to be created
  516. if (oldParent)
  517. MenuManager.moveItem(item, after);
  518. else
  519. MenuManager.createItem(item, after);
  520. },
  521. removeItem: function removeItem(item) {
  522. // If the item isn't a child of this menu then ignore this call
  523. if (item.parentMenu !== this)
  524. return;
  525. MenuManager.removeItem(item);
  526. internal(this).children = removeItemFromArray(internal(this).children, item);
  527. internal(item).parentMenu = null;
  528. },
  529. get items() {
  530. return internal(this).children.slice(0);
  531. },
  532. set items(val) {
  533. // Validate the arguments before making any changes
  534. if (!Array.isArray(val))
  535. throw new Error(menuOptionRules.items.msg);
  536. for (let item of val) {
  537. if (!(item instanceof BaseItem))
  538. throw new Error(menuOptionRules.items.msg);
  539. }
  540. // Remove the old items and add the new ones
  541. for (let item of internal(this).children)
  542. this.removeItem(item);
  543. for (let item of val)
  544. this.addItem(item);
  545. },
  546. });
  547. let Menu = Class({
  548. extends: LabelledItem,
  549. implements: [ItemContainer],
  550. initialize: function initialize(options) {
  551. internal(this).options = validateOptions(options, menuRules);
  552. LabelledItem.prototype.initialize.call(this, options);
  553. ItemContainer.prototype.initialize.call(this);
  554. if (internal(this).options.items) {
  555. for (let item of internal(this).options.items)
  556. this.addItem(item);
  557. }
  558. },
  559. destroy: function destroy() {
  560. ItemContainer.prototype.destroy.call(this);
  561. LabelledItem.prototype.destroy.call(this);
  562. },
  563. toString: function toString() {
  564. return "[object Menu \"" + this.label + "\"]";
  565. },
  566. });
  567. exports.Menu = Menu;
  568. let Separator = Class({
  569. extends: BaseItem,
  570. initialize: function initialize(options) {
  571. internal(this).options = validateOptions(options, baseItemRules);
  572. BaseItem.prototype.initialize.call(this);
  573. },
  574. toString: function toString() {
  575. return "[object Separator]";
  576. }
  577. });
  578. exports.Separator = Separator;
  579. // Holds items for the content area context menu
  580. let contentContextMenu = ItemContainer();
  581. exports.contentContextMenu = contentContextMenu;
  582. when(function() {
  583. contentContextMenu.destroy();
  584. });
  585. // App specific UI code lives here, it should handle populating the context
  586. // menu and passing clicks etc. through to the items.
  587. function countVisibleItems(nodes) {
  588. return Array.reduce(nodes, function(sum, node) {
  589. return node.hidden ? sum : sum + 1;
  590. }, 0);
  591. }
  592. let MenuWrapper = Class({
  593. initialize: function initialize(winWrapper, items, contextMenu) {
  594. this.winWrapper = winWrapper;
  595. this.window = winWrapper.window;
  596. this.items = items;
  597. this.contextMenu = contextMenu;
  598. this.populated = false;
  599. this.menuMap = new Map();
  600. // updateItemVisibilities will run first, updateOverflowState will run after
  601. // all other instances of this module have run updateItemVisibilities
  602. this._updateItemVisibilities = this.updateItemVisibilities.bind(this);
  603. this.contextMenu.addEventListener("popupshowing", this._updateItemVisibilities, true);
  604. this._updateOverflowState = this.updateOverflowState.bind(this);
  605. this.contextMenu.addEventListener("popupshowing", this._updateOverflowState, false);
  606. },
  607. destroy: function destroy() {
  608. this.contextMenu.removeEventListener("popupshowing", this._updateOverflowState, false);
  609. this.contextMenu.removeEventListener("popupshowing", this._updateItemVisibilities, true);
  610. if (!this.populated)
  611. return;
  612. // If we're getting unloaded at runtime then we must remove all the
  613. // generated XUL nodes
  614. let oldParent = null;
  615. for (let item of internal(this.items).children) {
  616. let xulNode = this.getXULNodeForItem(item);
  617. oldParent = xulNode.parentNode;
  618. oldParent.removeChild(xulNode);
  619. }
  620. if (oldParent)
  621. this.onXULRemoved(oldParent);
  622. },
  623. get separator() {
  624. return this.contextMenu.querySelector("." + SEPARATOR_CLASS);
  625. },
  626. get overflowMenu() {
  627. return this.contextMenu.querySelector("." + OVERFLOW_MENU_CLASS);
  628. },
  629. get overflowPopup() {
  630. return this.contextMenu.querySelector("." + OVERFLOW_POPUP_CLASS);
  631. },
  632. get topLevelItems() {
  633. return this.contextMenu.querySelectorAll("." + TOPLEVEL_ITEM_CLASS);
  634. },
  635. get overflowItems() {
  636. return this.contextMenu.querySelectorAll("." + OVERFLOW_ITEM_CLASS);
  637. },
  638. getXULNodeForItem: function getXULNodeForItem(item) {
  639. return this.menuMap.get(item);
  640. },
  641. // Recurses through the item hierarchy creating XUL nodes for everything
  642. populate: function populate(menu) {
  643. for (let i = 0; i < internal(menu).children.length; i++) {
  644. let item = internal(menu).children[i];
  645. let after = i === 0 ? null : internal(menu).children[i - 1];
  646. this.createItem(item, after);
  647. if (item instanceof Menu)
  648. this.populate(item);
  649. }
  650. },
  651. // Recurses through the menu setting the visibility of items. Returns true
  652. // if any of the items in this menu were visible
  653. setVisibility: function setVisibility(menu, popupNode, defaultVisibility) {
  654. let anyVisible = false;
  655. for (let item of internal(menu).children) {
  656. let visible = isItemVisible(item, popupNode, defaultVisibility);
  657. // Recurse through Menus, if none of the sub-items were visible then the
  658. // menu is hidden too.
  659. if (visible && (item instanceof Menu))
  660. visible = this.setVisibility(item, popupNode, true);
  661. let xulNode = this.getXULNodeForItem(item);
  662. xulNode.hidden = !visible;
  663. anyVisible = anyVisible || visible;
  664. }
  665. return anyVisible;
  666. },
  667. // Works out where to insert a XUL node for an item in a browser window
  668. insertIntoXUL: function insertIntoXUL(item, node, after) {
  669. let menupopup = null;
  670. let before = null;
  671. let menu = item.parentMenu;
  672. if (menu === this.items) {
  673. // Insert into the overflow popup if it exists, otherwise the normal
  674. // context menu
  675. menupopup = this.overflowPopup;
  676. if (!menupopup)
  677. menupopup = this.contextMenu;
  678. }
  679. else {
  680. let xulNode = this.getXULNodeForItem(menu);
  681. menupopup = xulNode.firstChild;
  682. }
  683. if (after) {
  684. let afterNode = this.getXULNodeForItem(after);
  685. before = afterNode.nextSibling;
  686. }
  687. else if (menupopup === this.contextMenu) {
  688. let topLevel = this.topLevelItems;
  689. if (topLevel.length > 0)
  690. before = topLevel[topLevel.length - 1].nextSibling;
  691. else
  692. before = this.separator.nextSibling;
  693. }
  694. menupopup.insertBefore(node, before);
  695. },
  696. // Sets the right class for XUL nodes
  697. updateXULClass: function updateXULClass(xulNode) {
  698. if (xulNode.parentNode == this.contextMenu)
  699. xulNode.classList.add(TOPLEVEL_ITEM_CLASS);
  700. else
  701. xulNode.classList.remove(TOPLEVEL_ITEM_CLASS);
  702. if (xulNode.parentNode == this.overflowPopup)
  703. xulNode.classList.add(OVERFLOW_ITEM_CLASS);
  704. else
  705. xulNode.classList.remove(OVERFLOW_ITEM_CLASS);
  706. },
  707. // Creates a XUL node for an item
  708. createItem: function createItem(item, after) {
  709. if (!this.populated)
  710. return;
  711. // Create the separator if it doesn't already exist
  712. if (!this.separator) {
  713. let separator = this.window.document.createElement("menuseparator");
  714. separator.setAttribute("class", SEPARATOR_CLASS);
  715. // Insert before the separator created by the old context-menu if it
  716. // exists to avoid bug 832401
  717. let oldSeparator = this.window.document.getElementById("jetpack-context-menu-separator");
  718. if (oldSeparator && oldSeparator.parentNode != this.contextMenu)
  719. oldSeparator = null;
  720. this.contextMenu.insertBefore(separator, oldSeparator);
  721. }
  722. let type = "menuitem";
  723. if (item instanceof Menu)
  724. type = "menu";
  725. else if (item instanceof Separator)
  726. type = "menuseparator";
  727. let xulNode = this.window.document.createElement(type);
  728. xulNode.setAttribute("class", ITEM_CLASS);
  729. if (item instanceof LabelledItem) {
  730. xulNode.setAttribute("label", item.label);
  731. if (item.image) {
  732. xulNode.setAttribute("image", item.image);
  733. if (item instanceof Menu)
  734. xulNode.classList.add("menu-iconic");
  735. else
  736. xulNode.classList.add("menuitem-iconic");
  737. }
  738. if (item.data)
  739. xulNode.setAttribute("value", item.data);
  740. let self = this;
  741. xulNode.addEventListener("command", function(event) {
  742. // Only care about clicks directly on this item
  743. if (event.target !== xulNode)
  744. return;
  745. itemClicked(item, item, self.contextMenu.triggerNode);
  746. }, false);
  747. }
  748. this.insertIntoXUL(item, xulNode, after);
  749. this.updateXULClass(xulNode);
  750. xulNode.data = item.data;
  751. if (item instanceof Menu) {
  752. let menupopup = this.window.document.createElement("menupopup");
  753. xulNode.appendChild(menupopup);
  754. }
  755. this.menuMap.set(item, xulNode);
  756. },
  757. // Updates the XUL node for an item in this window
  758. updateItem: function updateItem(item) {
  759. if (!this.populated)
  760. return;
  761. let xulNode = this.getXULNodeForItem(item);
  762. // TODO figure out why this requires setAttribute
  763. xulNode.setAttribute("label", item.label);
  764. if (item.image) {
  765. xulNode.setAttribute("image", item.image);
  766. if (item instanceof Menu)
  767. xulNode.classList.add("menu-iconic");
  768. else
  769. xulNode.classList.add("menuitem-iconic");
  770. }
  771. else {
  772. xulNode.removeAttribute("image");
  773. xulNode.classList.remove("menu-iconic");
  774. xulNode.classList.remove("menuitem-iconic");
  775. }
  776. if (item.data)
  777. xulNode.setAttribute("value", item.data);
  778. else
  779. xulNode.removeAttribute("value");
  780. },
  781. // Moves the XUL node for an item in this window to its new place in the
  782. // hierarchy
  783. moveItem: function moveItem(item, after) {
  784. if (!this.populated)
  785. return;
  786. let xulNode = this.getXULNodeForItem(item);
  787. let oldParent = xulNode.parentNode;
  788. this.insertIntoXUL(item, xulNode, after);
  789. this.updateXULClass(xulNode);
  790. this.onXULRemoved(oldParent);
  791. },
  792. // Removes the XUL nodes for an item in every window we've ever populated.
  793. removeItem: function removeItem(item) {
  794. if (!this.populated)
  795. return;
  796. let xulItem = this.getXULNodeForItem(item);
  797. let oldParent = xulItem.parentNode;
  798. oldParent.removeChild(xulItem);
  799. this.menuMap.delete(item);
  800. this.onXULRemoved(oldParent);
  801. },
  802. // Called when any XUL nodes have been removed from a menupopup. This handles
  803. // making sure the separator and overflow are correct
  804. onXULRemoved: function onXULRemoved(parent) {
  805. if (parent == this.contextMenu) {
  806. let toplevel = this.topLevelItems;
  807. // If there are no more items then remove the separator
  808. if (toplevel.length == 0) {
  809. let separator = this.separator;
  810. if (separator)
  811. separator.parentNode.removeChild(separator);
  812. }
  813. }
  814. else if (parent == this.overflowPopup) {
  815. // If there are no more items then remove the overflow menu and separator
  816. if (parent.childNodes.length == 0) {
  817. let separator = this.separator;
  818. separator.parentNode.removeChild(separator);
  819. this.contextMenu.removeChild(parent.parentNode);
  820. }
  821. }
  822. },
  823. // Recurses through all the items owned by this module and sets their hidden
  824. // state
  825. updateItemVisibilities: function updateItemVisibilities(event) {
  826. try {
  827. if (event.type != "popupshowing")
  828. return;
  829. if (event.target != this.contextMenu)
  830. return;
  831. if (internal(this.items).children.length == 0)
  832. return;
  833. if (!this.populated) {
  834. this.populated = true;
  835. this.populate(this.items);
  836. }
  837. let popupNode = event.target.triggerNode;
  838. this.setVisibility(this.items, popupNode, PageContext().isCurrent(popupNode));
  839. }
  840. catch (e) {
  841. console.exception(e);
  842. }
  843. },
  844. // Counts the number of visible items across all modules and makes sure they
  845. // are in the right place between the top level context menu and the overflow
  846. // menu
  847. updateOverflowState: function updateOverflowState(event) {
  848. try {
  849. if (event.type != "popupshowing")
  850. return;
  851. if (event.target != this.contextMenu)
  852. return;
  853. // The main items will be in either the top level context menu or the
  854. // overflow menu at this point. Count the visible ones and if they are in
  855. // the wrong place move them
  856. let toplevel = this.topLevelItems;
  857. let overflow = this.overflowItems;
  858. let visibleCount = countVisibleItems(toplevel) +
  859. countVisibleItems(overflow);
  860. if (visibleCount == 0) {
  861. let separator = this.separator;
  862. if (separator)
  863. separator.hidden = true;
  864. let overflowMenu = this.overflowMenu;
  865. if (overflowMenu)
  866. overflowMenu.hidden = true;
  867. }
  868. else if (visibleCount > MenuManager.overflowThreshold) {
  869. this.separator.hidden = false;
  870. let overflowPopup = this.overflowPopup;
  871. if (overflowPopup)
  872. overflowPopup.parentNode.hidden = false;
  873. if (toplevel.length > 0) {
  874. // The overflow menu shouldn't exist here but let's play it safe
  875. if (!overflowPopup) {
  876. let overflowMenu = this.window.document.createElement("menu");
  877. overflowMenu.setAttribute("class", OVERFLOW_MENU_CLASS);
  878. overflowMenu.setAttribute("label", OVERFLOW_MENU_LABEL);
  879. this.contextMenu.insertBefore(overflowMenu, this.separator.nextSibling);
  880. overflowPopup = this.window.document.createElement("menupopup");
  881. overflowPopup.setAttribute("class", OVERFLOW_POPUP_CLASS);
  882. overflowMenu.appendChild(overflowPopup);
  883. }
  884. for (let xulNode of toplevel) {
  885. overflowPopup.appendChild(xulNode);
  886. this.updateXULClass(xulNode);
  887. }
  888. }
  889. }
  890. else {
  891. this.separator.hidden = false;
  892. if (overflow.length > 0) {
  893. // Move all the overflow nodes out of the overflow menu and position
  894. // them immediately before it
  895. for (let xulNode of overflow) {
  896. this.contextMenu.insertBefore(xulNode, xulNode.parentNode.parentNode);
  897. this.updateXULClass(xulNode);
  898. }
  899. this.contextMenu.removeChild(this.overflowMenu);
  900. }
  901. }
  902. }
  903. catch (e) {
  904. console.exception(e);
  905. }
  906. }
  907. });
  908. // This wraps every window that we've seen
  909. let WindowWrapper = Class({
  910. initialize: function initialize(window) {
  911. this.window = window;
  912. this.menus = [
  913. new MenuWrapper(this, contentContextMenu, window.document.getElementById("contentAreaContextMenu")),
  914. ];
  915. },
  916. destroy: function destroy() {
  917. for (let menuWrapper of this.menus)
  918. menuWrapper.destroy();
  919. },
  920. getMenuWrapperForItem: function getMenuWrapperForItem(item) {
  921. let root = item.parentMenu;
  922. while (root.parentMenu)
  923. root = root.parentMenu;
  924. for (let wrapper of this.menus) {
  925. if (wrapper.items === root)
  926. return wrapper;
  927. }
  928. return null;
  929. }
  930. });
  931. let MenuManager = {
  932. windowMap: new Map(),
  933. get overflowThreshold() {
  934. let prefs = require("./preferences/service");
  935. return prefs.get(OVERFLOW_THRESH_PREF, OVERFLOW_THRESH_DEFAULT);
  936. },
  937. // When a new window is added start watching it for context menu shows
  938. onTrack: function onTrack(window) {
  939. if (!isBrowser(window))
  940. return;
  941. // Generally shouldn't happen, but just in case
  942. if (this.windowMap.has(window)) {
  943. console.warn("Already seen this window");
  944. return;
  945. }
  946. let winWrapper = WindowWrapper(window);
  947. this.windowMap.set(window, winWrapper);
  948. },
  949. onUntrack: function onUntrack(window) {
  950. if (!isBrowser(window))
  951. return;
  952. let winWrapper = this.windowMap.get(window);
  953. // This shouldn't happen but protect against it anyway
  954. if (!winWrapper)
  955. return;
  956. winWrapper.destroy();
  957. this.windowMap.delete(window);
  958. },
  959. // Creates a XUL node for an item in every window we've already populated
  960. createItem: function createItem(item, after) {
  961. for (let [window, winWrapper] of this.windowMap) {
  962. let menuWrapper = winWrapper.getMenuWrapperForItem(item);
  963. if (menuWrapper)
  964. menuWrapper.createItem(item, after);
  965. }
  966. },
  967. // Updates the XUL node for an item in every window we've already populated
  968. updateItem: function updateItem(item) {
  969. for (let [window, winWrapper] of this.windowMap) {
  970. let menuWrapper = winWrapper.getMenuWrapperForItem(item);
  971. if (menuWrapper)
  972. menuWrapper.updateItem(item);
  973. }
  974. },
  975. // Moves the XUL node for an item in every window we've ever populated to its
  976. // new place in the hierarchy
  977. moveItem: function moveItem(item, after) {
  978. for (let [window, winWrapper] of this.windowMap) {
  979. let menuWrapper = winWrapper.getMenuWrapperForItem(item);
  980. if (menuWrapper)
  981. menuWrapper.moveItem(item, after);
  982. }
  983. },
  984. // Removes the XUL nodes for an item in every window we've ever populated.
  985. removeItem: function removeItem(item) {
  986. for (let [window, winWrapper] of this.windowMap) {
  987. let menuWrapper = winWrapper.getMenuWrapperForItem(item);
  988. if (menuWrapper)
  989. menuWrapper.removeItem(item);
  990. }
  991. }
  992. };
  993. WindowTracker(MenuManager);