Bug 1338898 fix 150 char limit for context menu text selection, r?mattw,aswan draft
authorShane Caraveo <scaraveo@mozilla.com>
Thu, 29 Jun 2017 15:11:29 -0700
changeset 602317 dc8bd5962c1454ff9332d715e3f232127446cf39
parent 601524 217b7fcf58944f927118b465769faeb1e613130a
child 635548 88742faf00a196bc250e81ed95ea24e71af94228
push id66377
push usermixedpuppy@gmail.com
push dateThu, 29 Jun 2017 22:13:12 +0000
reviewersmattw, aswan
bugs1338898
milestone56.0a1
Bug 1338898 fix 150 char limit for context menu text selection, r?mattw,aswan MozReview-Commit-ID: IqECfaFSbGZ
browser/base/content/nsContextMenu.js
browser/components/extensions/ext-menus.js
browser/components/extensions/test/browser/browser_ext_contextMenus.js
browser/components/extensions/test/browser/context.html
toolkit/modules/BrowserUtils.jsm
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -111,17 +111,17 @@ nsContextMenu.prototype = {
         onCanvas: this.onCanvas,
         onEditableArea: this.onEditableArea,
         onPassword: this.onPassword,
         srcUrl: this.mediaURL,
         frameUrl: gContextMenuContentData ? gContextMenuContentData.docLocation : undefined,
         pageUrl: this.browser ? this.browser.currentURI.spec : undefined,
         linkText: this.linkTextStr,
         linkUrl: this.linkURL,
-        selectionText: this.isTextSelected ? this.selectionInfo.text : undefined,
+        selectionText: this.isTextSelected ? this.selectionInfo.fullText : undefined,
         frameId: this.frameOuterWindowID,
       };
       subject.wrappedJSObject = subject;
       Services.obs.notifyObservers(subject, "on-build-contextmenu");
     }
 
     this.isFrameImage = document.getElementById("isFrameImage");
     this.ellipsis = "\u2026";
--- a/browser/components/extensions/ext-menus.js
+++ b/browser/components/extensions/ext-menus.js
@@ -188,17 +188,17 @@ var gMenuBuilder = {
     element.appendChild(menupopup);
     return element;
   },
 
   customizeElement(element, item, contextData) {
     let label = item.title;
     if (label) {
       if (contextData.isTextSelected && label.indexOf("%s") > -1) {
-        let selection = contextData.selectionText;
+        let selection = contextData.selectionText.trim();
         // The rendering engine will truncate the title if it's longer than 64 characters.
         // But if it makes sense let's try truncate selection text only, to handle cases like
         // 'look up "%s" in MyDictionary' more elegantly.
         let maxSelectionLength = gMaxLabelLength - label.length + 2;
         if (maxSelectionLength > 4) {
           selection = selection.substring(0, maxSelectionLength - 3) + "...";
         }
         label = label.replace(/%s/g, selection);
--- a/browser/components/extensions/test/browser/browser_ext_contextMenus.js
+++ b/browser/components/extensions/test/browser/browser_ext_contextMenus.js
@@ -54,16 +54,23 @@ add_task(async function() {
   gBrowser.selectedTab = tab1;
 
   let extension = ExtensionTestUtils.loadExtension({
     manifest: {
       "permissions": ["contextMenus"],
     },
 
     background: async function() {
+      browser.test.onMessage.addListener(msg => {
+        if (msg == "removeall") {
+          browser.contextMenus.removeAll();
+          browser.test.sendMessage("removed");
+        }
+      });
+
       // A generic onclick callback function.
       function genericOnClick(info, tab) {
         browser.test.sendMessage("onclick", {info, tab});
       }
 
       browser.contextMenus.onClicked.addListener((info, tab) => {
         browser.test.sendMessage("browser.contextMenus.onClicked", {info, tab});
       });
@@ -81,20 +88,17 @@ add_task(async function() {
           title: title,
           contexts: [context],
           id: "ext-" + context,
           onclick: genericOnClick,
         });
         if (context == "selection") {
           browser.contextMenus.update("ext-selection", {
             title: "selection is: '%s'",
-            onclick: (info, tab) => {
-              browser.contextMenus.removeAll();
-              genericOnClick(info, tab);
-            },
+            onclick: genericOnClick,
           });
         }
       }
 
       let parent = browser.contextMenus.create({
         title: "parent",
       });
       browser.contextMenus.create({
@@ -285,23 +289,89 @@ add_task(async function() {
   items = extensionMenuRoot.getElementsByAttribute("label", "selection");
   is(items.length, 0, "contextMenu item label update worked (context=selection)");
 
   await closeExtensionContextMenu(selectionItem);
 
   expectedClickInfo = {
     menuItemId: "ext-selection",
     pageUrl: PAGE,
-    selectionText: "just some text 1234567890123456789012345678901234567890123456789012345678901234567890123456789012",
+    selectionText: " just some text 1234567890123456789012345678901234567890123456789012345678901234567890123456789012",
+  };
+
+  result = await extension.awaitMessage("onclick");
+  checkClickInfo(result);
+  result = await extension.awaitMessage("browser.contextMenus.onClicked");
+  checkClickInfo(result);
+
+  // Select a lot of text
+  await ContentTask.spawn(gBrowser.selectedBrowser, { }, function* (arg) {
+    let doc = content.document;
+    let range = doc.createRange();
+    let selection = content.getSelection();
+    selection.removeAllRanges();
+    let textNode = doc.getElementById("longtext").firstChild;
+    range.setStart(textNode, 0);
+    range.setEnd(textNode, textNode.length);
+    selection.addRange(range);
+  });
+
+  // Bring up context menu again
+  extensionMenuRoot = await openExtensionContextMenu("#longtext");
+
+  // Check some menu items
+  items = extensionMenuRoot.getElementsByAttribute("label", "selection is: 'Sed ut perspiciatis unde omnis iste natus err...'");
+  is(items.length, 1, `contextMenu item for longtext selection was found (context=selection)`);
+  await closeExtensionContextMenu(items[0]);
+
+  expectedClickInfo = {
+    menuItemId: "ext-selection",
+    pageUrl: PAGE,
   };
 
   result = await extension.awaitMessage("onclick");
   checkClickInfo(result);
   result = await extension.awaitMessage("browser.contextMenus.onClicked");
   checkClickInfo(result);
+  ok(result.info.selectionText.endsWith("quo voluptas nulla pariatur?"), "long text selection worked");
+
+
+  // Select a lot of text, excercise the nsIDOMNSEditableElement code path in
+  // the Browser:GetSelection handler.
+  await ContentTask.spawn(gBrowser.selectedBrowser, { }, function(arg) {
+    let doc = content.document;
+    let node = doc.getElementById("editabletext");
+    // content.js handleContentContextMenu fails intermittently without focus.
+    node.focus();
+    node.selectionStart = 0;
+    node.selectionEnd = 844;
+  });
+
+  // Bring up context menu again
+  extensionMenuRoot = await openExtensionContextMenu("#editabletext");
+
+  // Check some menu items
+  items = extensionMenuRoot.getElementsByAttribute("label", "editable");
+  is(items.length, 1, "contextMenu item for text input element was found (context=editable)");
+  await closeExtensionContextMenu(items[0]);
+
+  expectedClickInfo = {
+    menuItemId: "ext-editable",
+    editable: true,
+    pageUrl: PAGE,
+  };
+
+  result = await extension.awaitMessage("onclick");
+  checkClickInfo(result);
+  result = await extension.awaitMessage("browser.contextMenus.onClicked");
+  checkClickInfo(result);
+  ok(result.info.selectionText.endsWith("perferendis doloribus asperiores repellat."), "long text selection worked");
+
+  extension.sendMessage("removeall");
+  await extension.awaitMessage("removed");
 
   let contentAreaContextMenu = await openContextMenu("#img1");
   items = contentAreaContextMenu.getElementsByAttribute("ext-type", "top-level-menu");
   is(items.length, 0, "top level item was not found (after removeAll()");
   await closeContextMenu();
 
   await extension.unload();
   await BrowserTestUtils.removeTab(tab1);
--- a/browser/components/extensions/test/browser/context.html
+++ b/browser/components/extensions/test/browser/context.html
@@ -1,8 +1,9 @@
+<!DOCTYPE html>
 <html>
   <head>
     <meta charset="utf-8">
   </head>
   <body>
   just some text 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
   <img src="ctxmenu-image.png" id="img1">
 
@@ -15,11 +16,25 @@
       <img src="ctxmenu-image.png" id="img-wrapped-in-link">
     </a>
   </p>
 
   <p>
     <input type="text" id="edit-me"><br>
     <input type="password" id="password">
   </p>
-  <iframe id="frame" src="context_frame.html"/>
+  <iframe id="frame" src="context_frame.html"></iframe>
+  <p id="longtext">Sed ut perspiciatis unde omnis iste natus error sit
+  voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque
+  ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta
+  sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut
+  odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem
+  sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit
+  amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
+  incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad
+  minima veniam, quis nostrum exercitationem ullam corporis suscipit
+  laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum
+  iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae
+  consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>
+
+  <input id="editabletext" type="text" value="At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." />
   </body>
 </html>
--- a/toolkit/modules/BrowserUtils.jsm
+++ b/toolkit/modules/BrowserUtils.jsm
@@ -409,16 +409,17 @@ this.BrowserUtils = {
     const charLen = Math.min(aCharLen || kMaxSelectionLen, kMaxSelectionLen);
 
     let focusedWindow = {};
     let focusedElement = Services.focus.getFocusedElementForWindow(topWindow, true, focusedWindow);
     focusedWindow = focusedWindow.value;
 
     let selection = focusedWindow.getSelection();
     let selectionStr = selection.toString();
+    let fullText;
 
     let collapsed = selection.isCollapsed;
 
     let url;
     let linkText;
     if (selectionStr) {
       // Have some text, let's figure out if it looks like a URL that isn't
       // actually a link.
@@ -477,16 +478,20 @@ this.BrowserUtils = {
       if (focusedElement instanceof Ci.nsIDOMHTMLTextAreaElement ||
           (focusedElement instanceof Ci.nsIDOMHTMLInputElement &&
            focusedElement.mozIsTextField(true))) {
         selectionStr = focusedElement.editor.selection.toString();
       }
     }
 
     if (selectionStr) {
+      // Pass up to 16K through unmolested.  If an add-on needs more, they will
+      // have to use a content script.
+      fullText = selectionStr.substr(0, 16384);
+
       if (selectionStr.length > charLen) {
         // only use the first charLen important chars. see bug 221361
         var pattern = new RegExp("^(?:\\s*.){0," + charLen + "}");
         pattern.test(selectionStr);
         selectionStr = RegExp.lastMatch;
       }
 
       selectionStr = selectionStr.trim().replace(/\s+/g, " ");
@@ -495,17 +500,17 @@ this.BrowserUtils = {
         selectionStr = selectionStr.substr(0, charLen);
       }
     }
 
     if (url && !url.host) {
       url = null;
     }
 
-    return { text: selectionStr, docSelectionIsCollapsed: collapsed,
+    return { text: selectionStr, docSelectionIsCollapsed: collapsed, fullText,
              linkURL: url ? url.spec : null, linkText: url ? linkText : "" };
   },
 
   // Iterates through every docshell in the window and calls PermitUnload.
   canCloseWindow(window) {
     let docShell = window.QueryInterface(Ci.nsIInterfaceRequestor)
                          .getInterface(Ci.nsIWebNavigation);
     let node = docShell.QueryInterface(Ci.nsIDocShellTreeItem);