2 * Copyright (C) 2009, 2012 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "web/ContextMenuClientImpl.h"
34 #include "CSSPropertyNames.h"
35 #include "HTMLNames.h"
36 #include "bindings/v8/ExceptionStatePlaceholder.h"
37 #include "core/css/CSSStyleDeclaration.h"
38 #include "core/dom/Document.h"
39 #include "core/dom/DocumentMarkerController.h"
40 #include "core/editing/Editor.h"
41 #include "core/editing/SpellChecker.h"
42 #include "core/frame/FrameView.h"
43 #include "core/frame/Settings.h"
44 #include "core/html/HTMLFormElement.h"
45 #include "core/html/HTMLInputElement.h"
46 #include "core/html/HTMLMediaElement.h"
47 #include "core/html/HTMLPlugInElement.h"
48 #include "core/html/MediaError.h"
49 #include "core/loader/DocumentLoader.h"
50 #include "core/loader/FrameLoader.h"
51 #include "core/loader/HistoryItem.h"
52 #include "core/page/ContextMenuController.h"
53 #include "core/page/EventHandler.h"
54 #include "core/page/Page.h"
55 #include "core/rendering/HitTestResult.h"
56 #include "core/rendering/RenderWidget.h"
57 #include "platform/ContextMenu.h"
58 #include "platform/Widget.h"
59 #include "platform/text/TextBreakIterator.h"
60 #include "platform/weborigin/KURL.h"
61 #include "public/platform/WebPoint.h"
62 #include "public/platform/WebString.h"
63 #include "public/platform/WebURL.h"
64 #include "public/platform/WebURLResponse.h"
65 #include "public/platform/WebVector.h"
66 #include "public/web/WebContextMenuData.h"
67 #include "public/web/WebFormElement.h"
68 #include "public/web/WebFrameClient.h"
69 #include "public/web/WebMenuItemInfo.h"
70 #include "public/web/WebPlugin.h"
71 #include "public/web/WebSearchableFormData.h"
72 #include "public/web/WebSpellCheckClient.h"
73 #include "public/web/WebViewClient.h"
74 #include "web/WebDataSourceImpl.h"
75 #include "web/WebLocalFrameImpl.h"
76 #include "web/WebPluginContainerImpl.h"
77 #include "web/WebViewImpl.h"
78 #include "wtf/text/WTFString.h"
80 using namespace WebCore;
84 // Figure out the URL of a page or subframe. Returns |page_type| as the type,
85 // which indicates page or subframe, or ContextNodeType::NONE if the URL could not
86 // be determined for some reason.
87 static WebURL urlFromFrame(LocalFrame* frame)
90 DocumentLoader* dl = frame->loader().documentLoader();
92 WebDataSource* ds = WebDataSourceImpl::fromDocumentLoader(dl);
94 return ds->hasUnreachableURL() ? ds->unreachableURL() : ds->request().url();
100 // Helper function to determine whether text is a single word.
101 static bool isASingleWord(const String& text)
103 TextBreakIterator* it = wordBreakIterator(text, 0, text.length());
104 return it && it->next() == static_cast<int>(text.length());
107 // Helper function to get misspelled word on which context menu
108 // is to be invoked. This function also sets the word on which context menu
109 // has been invoked to be the selected word, as required. This function changes
110 // the selection only when there were no selected characters on OS X.
111 static String selectMisspelledWord(LocalFrame* selectedFrame)
113 // First select from selectedText to check for multiple word selection.
114 String misspelledWord = selectedFrame->selectedText().stripWhiteSpace();
116 // If some texts were already selected, we don't change the selection.
117 if (!misspelledWord.isEmpty()) {
118 // Don't provide suggestions for multiple words.
119 if (!isASingleWord(misspelledWord))
121 return misspelledWord;
124 // Selection is empty, so change the selection to the word under the cursor.
125 HitTestResult hitTestResult = selectedFrame->eventHandler().
126 hitTestResultAtPoint(selectedFrame->page()->contextMenuController().hitTestResult().pointInInnerNodeFrame());
127 Node* innerNode = hitTestResult.innerNode();
128 VisiblePosition pos(innerNode->renderer()->positionForPoint(
129 hitTestResult.localPoint()));
132 return misspelledWord; // It is empty.
134 WebLocalFrameImpl::selectWordAroundPosition(selectedFrame, pos);
135 misspelledWord = selectedFrame->selectedText().stripWhiteSpace();
138 // If misspelled word is still empty, then that portion should not be
139 // selected. Set the selection to that position only, and do not expand.
140 if (misspelledWord.isEmpty())
141 selectedFrame->selection().setSelection(VisibleSelection(pos));
143 // On non-Mac, right-click should not make a range selection in any case.
144 selectedFrame->selection().setSelection(VisibleSelection(pos));
146 return misspelledWord;
149 static bool IsWhiteSpaceOrPunctuation(UChar c)
151 return isSpaceOrNewline(c) || WTF::Unicode::isPunct(c);
154 static String selectMisspellingAsync(LocalFrame* selectedFrame, DocumentMarker& marker)
156 VisibleSelection selection = selectedFrame->selection().selection();
157 if (!selection.isCaretOrRange())
160 // Caret and range selections always return valid normalized ranges.
161 RefPtrWillBeRawPtr<Range> selectionRange = selection.toNormalizedRange();
162 Vector<DocumentMarker*> markers = selectedFrame->document()->markers().markersInRange(selectionRange.get(), DocumentMarker::MisspellingMarkers());
163 if (markers.size() != 1)
165 marker = *markers[0];
167 // Cloning a range fails only for invalid ranges.
168 RefPtrWillBeRawPtr<Range> markerRange = selectionRange->cloneRange();
169 markerRange->setStart(markerRange->startContainer(), marker.startOffset());
170 markerRange->setEnd(markerRange->endContainer(), marker.endOffset());
172 if (markerRange->text().stripWhiteSpace(&IsWhiteSpaceOrPunctuation) != selectionRange->text().stripWhiteSpace(&IsWhiteSpaceOrPunctuation))
175 return markerRange->text();
178 void ContextMenuClientImpl::showContextMenu(const WebCore::ContextMenu* defaultMenu)
180 // Displaying the context menu in this function is a big hack as we don't
181 // have context, i.e. whether this is being invoked via a script or in
182 // response to user input (Mouse event WM_RBUTTONDOWN,
183 // Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked
184 // in response to the above input events before popping up the context menu.
185 if (!m_webView->contextMenuAllowed())
188 HitTestResult r = m_webView->page()->contextMenuController().hitTestResult();
189 LocalFrame* selectedFrame = r.innerNodeFrame();
191 WebContextMenuData data;
192 IntPoint mousePoint = selectedFrame->view()->contentsToWindow(r.roundedPointInInnerNodeFrame());
193 mousePoint.scale(m_webView->pageScaleFactor(), m_webView->pageScaleFactor());
194 data.mousePosition = mousePoint;
196 // Compute edit flags.
197 data.editFlags = WebContextMenuData::CanDoNone;
198 if (toLocalFrame(m_webView->focusedWebCoreFrame())->editor().canUndo())
199 data.editFlags |= WebContextMenuData::CanUndo;
200 if (toLocalFrame(m_webView->focusedWebCoreFrame())->editor().canRedo())
201 data.editFlags |= WebContextMenuData::CanRedo;
202 if (toLocalFrame(m_webView->focusedWebCoreFrame())->editor().canCut())
203 data.editFlags |= WebContextMenuData::CanCut;
204 if (toLocalFrame(m_webView->focusedWebCoreFrame())->editor().canCopy())
205 data.editFlags |= WebContextMenuData::CanCopy;
206 if (toLocalFrame(m_webView->focusedWebCoreFrame())->editor().canPaste())
207 data.editFlags |= WebContextMenuData::CanPaste;
208 if (toLocalFrame(m_webView->focusedWebCoreFrame())->editor().canDelete())
209 data.editFlags |= WebContextMenuData::CanDelete;
210 // We can always select all...
211 data.editFlags |= WebContextMenuData::CanSelectAll;
212 data.editFlags |= WebContextMenuData::CanTranslate;
214 // Links, Images, Media tags, and Image/Media-Links take preference over
216 data.linkURL = r.absoluteLinkURL();
218 if (isHTMLCanvasElement(r.innerNonSharedNode())) {
219 data.mediaType = WebContextMenuData::MediaTypeCanvas;
220 } else if (!r.absoluteImageURL().isEmpty()) {
221 data.srcURL = r.absoluteImageURL();
222 data.mediaType = WebContextMenuData::MediaTypeImage;
223 data.mediaFlags |= WebContextMenuData::MediaCanPrint;
224 } else if (!r.absoluteMediaURL().isEmpty()) {
225 data.srcURL = r.absoluteMediaURL();
227 // We know that if absoluteMediaURL() is not empty, then this
228 // is a media element.
229 HTMLMediaElement* mediaElement = toHTMLMediaElement(r.innerNonSharedNode());
230 if (isHTMLVideoElement(*mediaElement))
231 data.mediaType = WebContextMenuData::MediaTypeVideo;
232 else if (isHTMLAudioElement(*mediaElement))
233 data.mediaType = WebContextMenuData::MediaTypeAudio;
235 if (mediaElement->error())
236 data.mediaFlags |= WebContextMenuData::MediaInError;
237 if (mediaElement->paused())
238 data.mediaFlags |= WebContextMenuData::MediaPaused;
239 if (mediaElement->muted())
240 data.mediaFlags |= WebContextMenuData::MediaMuted;
241 if (mediaElement->loop())
242 data.mediaFlags |= WebContextMenuData::MediaLoop;
243 if (mediaElement->supportsSave())
244 data.mediaFlags |= WebContextMenuData::MediaCanSave;
245 if (mediaElement->hasAudio())
246 data.mediaFlags |= WebContextMenuData::MediaHasAudio;
247 // Media controls can be toggled only for video player. If we toggle
248 // controls for audio then the player disappears, and there is no way to
249 // return it back. Don't set this bit for fullscreen video, since
250 // toggling is ignored in that case.
251 if (mediaElement->hasVideo() && !mediaElement->isFullscreen())
252 data.mediaFlags |= WebContextMenuData::MediaCanToggleControls;
253 if (mediaElement->controls())
254 data.mediaFlags |= WebContextMenuData::MediaControls;
255 } else if (isHTMLObjectElement(*r.innerNonSharedNode()) || isHTMLEmbedElement(*r.innerNonSharedNode())) {
256 RenderObject* object = r.innerNonSharedNode()->renderer();
257 if (object && object->isWidget()) {
258 Widget* widget = toRenderWidget(object)->widget();
259 if (widget && widget->isPluginContainer()) {
260 data.mediaType = WebContextMenuData::MediaTypePlugin;
261 WebPluginContainerImpl* plugin = toWebPluginContainerImpl(widget);
262 WebString text = plugin->plugin()->selectionAsText();
263 if (!text.isEmpty()) {
264 data.selectedText = text;
265 data.editFlags |= WebContextMenuData::CanCopy;
267 data.editFlags &= ~WebContextMenuData::CanTranslate;
268 data.linkURL = plugin->plugin()->linkAtPosition(data.mousePosition);
269 if (plugin->plugin()->supportsPaginatedPrint())
270 data.mediaFlags |= WebContextMenuData::MediaCanPrint;
272 HTMLPlugInElement* pluginElement = toHTMLPlugInElement(r.innerNonSharedNode());
273 data.srcURL = pluginElement->document().completeURL(pluginElement->url());
274 data.mediaFlags |= WebContextMenuData::MediaCanSave;
276 // Add context menu commands that are supported by the plugin.
277 if (plugin->plugin()->canRotateView())
278 data.mediaFlags |= WebContextMenuData::MediaCanRotate;
283 // An image can to be null for many reasons, like being blocked, no image
284 // data received from server yet.
285 data.hasImageContents =
286 (data.mediaType == WebContextMenuData::MediaTypeImage)
287 && r.image() && !(r.image()->isNull());
289 // If it's not a link, an image, a media element, or an image/media link,
290 // show a selection menu or a more generic page menu.
291 if (selectedFrame->document()->loader())
292 data.frameEncoding = selectedFrame->document()->encodingName();
294 // Send the frame and page URLs in any case.
295 data.pageURL = urlFromFrame(m_webView->mainFrameImpl()->frame());
296 if (selectedFrame != m_webView->mainFrameImpl()->frame()) {
297 data.frameURL = urlFromFrame(selectedFrame);
298 RefPtr<HistoryItem> historyItem = selectedFrame->loader().currentItem();
300 data.frameHistoryItem = WebHistoryItem(historyItem);
303 if (r.isSelected()) {
304 if (!isHTMLInputElement(*r.innerNonSharedNode()) || !toHTMLInputElement(r.innerNonSharedNode())->isPasswordField())
305 data.selectedText = selectedFrame->selectedText().stripWhiteSpace();
308 if (r.isContentEditable()) {
309 data.isEditable = true;
311 // When Chrome enables asynchronous spellchecking, its spellchecker adds spelling markers to misspelled
312 // words and attaches suggestions to these markers in the background. Therefore, when a user right-clicks
313 // a mouse on a word, Chrome just needs to find a spelling marker on the word instead of spellchecking it.
314 if (selectedFrame->settings() && selectedFrame->settings()->asynchronousSpellCheckingEnabled()) {
315 DocumentMarker marker;
316 data.misspelledWord = selectMisspellingAsync(selectedFrame, marker);
317 data.misspellingHash = marker.hash();
318 if (marker.description().length()) {
319 Vector<String> suggestions;
320 marker.description().split('\n', suggestions);
321 data.dictionarySuggestions = suggestions;
322 } else if (m_webView->spellCheckClient()) {
323 int misspelledOffset, misspelledLength;
324 m_webView->spellCheckClient()->spellCheck(data.misspelledWord, misspelledOffset, misspelledLength, &data.dictionarySuggestions);
327 data.isSpellCheckingEnabled =
328 toLocalFrame(m_webView->focusedWebCoreFrame())->spellChecker().isContinuousSpellCheckingEnabled();
329 // Spellchecking might be enabled for the field, but could be disabled on the node.
330 if (toLocalFrame(m_webView->focusedWebCoreFrame())->spellChecker().isSpellCheckingEnabledInFocusedNode()) {
331 data.misspelledWord = selectMisspelledWord(selectedFrame);
332 if (m_webView->spellCheckClient()) {
333 int misspelledOffset, misspelledLength;
334 m_webView->spellCheckClient()->spellCheck(
335 data.misspelledWord, misspelledOffset, misspelledLength,
336 &data.dictionarySuggestions);
337 if (!misspelledLength)
338 data.misspelledWord.reset();
342 HTMLFormElement* form = selectedFrame->selection().currentForm();
343 if (form && isHTMLInputElement(*r.innerNonSharedNode())) {
344 HTMLInputElement& selectedElement = toHTMLInputElement(*r.innerNonSharedNode());
345 WebSearchableFormData ws = WebSearchableFormData(WebFormElement(form), WebInputElement(&selectedElement));
346 if (ws.url().isValid())
347 data.keywordURL = ws.url();
351 if (selectedFrame->editor().selectionHasStyle(CSSPropertyDirection, "ltr") != FalseTriState)
352 data.writingDirectionLeftToRight |= WebContextMenuData::CheckableMenuItemChecked;
353 if (selectedFrame->editor().selectionHasStyle(CSSPropertyDirection, "rtl") != FalseTriState)
354 data.writingDirectionRightToLeft |= WebContextMenuData::CheckableMenuItemChecked;
356 // Now retrieve the security info.
357 DocumentLoader* dl = selectedFrame->loader().documentLoader();
358 WebDataSource* ds = WebDataSourceImpl::fromDocumentLoader(dl);
360 data.securityInfo = ds->response().securityInfo();
362 data.referrerPolicy = static_cast<WebReferrerPolicy>(selectedFrame->document()->referrerPolicy());
364 // Filter out custom menu elements and add them into the data.
365 populateCustomMenuItems(defaultMenu, &data);
367 data.node = r.innerNonSharedNode();
369 WebLocalFrameImpl* selectedWebFrame = WebLocalFrameImpl::fromFrame(selectedFrame);
370 if (selectedWebFrame->client())
371 selectedWebFrame->client()->showContextMenu(data);
374 void ContextMenuClientImpl::clearContextMenu()
376 HitTestResult r = m_webView->page()->contextMenuController().hitTestResult();
377 LocalFrame* selectedFrame = r.innerNodeFrame();
381 WebLocalFrameImpl* selectedWebFrame = WebLocalFrameImpl::fromFrame(selectedFrame);
382 if (selectedWebFrame->client())
383 selectedWebFrame->client()->clearContextMenu();
386 static void populateSubMenuItems(const Vector<ContextMenuItem>& inputMenu, WebVector<WebMenuItemInfo>& subMenuItems)
388 Vector<WebMenuItemInfo> subItems;
389 for (size_t i = 0; i < inputMenu.size(); ++i) {
390 const ContextMenuItem* inputItem = &inputMenu.at(i);
391 if (inputItem->action() < ContextMenuItemBaseCustomTag || inputItem->action() > ContextMenuItemLastCustomTag)
394 WebMenuItemInfo outputItem;
395 outputItem.label = inputItem->title();
396 outputItem.enabled = inputItem->enabled();
397 outputItem.checked = inputItem->checked();
398 outputItem.action = static_cast<unsigned>(inputItem->action() - ContextMenuItemBaseCustomTag);
399 switch (inputItem->type()) {
401 outputItem.type = WebMenuItemInfo::Option;
403 case CheckableActionType:
404 outputItem.type = WebMenuItemInfo::CheckableOption;
407 outputItem.type = WebMenuItemInfo::Separator;
410 outputItem.type = WebMenuItemInfo::SubMenu;
411 populateSubMenuItems(inputItem->subMenuItems(), outputItem.subMenuItems);
414 subItems.append(outputItem);
417 WebVector<WebMenuItemInfo> outputItems(subItems.size());
418 for (size_t i = 0; i < subItems.size(); ++i)
419 outputItems[i] = subItems[i];
420 subMenuItems.swap(outputItems);
423 void ContextMenuClientImpl::populateCustomMenuItems(const WebCore::ContextMenu* defaultMenu, WebContextMenuData* data)
425 populateSubMenuItems(defaultMenu->items(), data->customItems);