Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(407)

Side by Side Diff: Source/web/WebFrameImpl.cpp

Issue 241303002: Rename WebFrameImpl to WebLocalFrameImpl. (Closed) Base URL: svn://svn.chromium.org/blink/trunk
Patch Set: Fix Mac too Created 6 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « Source/web/WebFrameImpl.h ('k') | Source/web/WebHelperPluginImpl.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
2 * Copyright (C) 2009 Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
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
13 * distribution.
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.
17 *
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.
29 */
30
31 // How ownership works
32 // -------------------
33 //
34 // Big oh represents a refcounted relationship: owner O--- ownee
35 //
36 // WebView (for the toplevel frame only)
37 // O
38 // | WebFrame
39 // | O
40 // | |
41 // Page O------- LocalFrame (m_mainFrame) O-------O FrameView
42 // ||
43 // ||
44 // FrameLoader
45 //
46 // FrameLoader and LocalFrame are formerly one object that was split apart becau se
47 // it got too big. They basically have the same lifetime, hence the double line.
48 //
49 // From the perspective of the embedder, WebFrame is simply an object that it
50 // allocates by calling WebFrame::create() and must be freed by calling close().
51 // Internally, WebFrame is actually refcounted and it holds a reference to its
52 // corresponding LocalFrame in WebCore.
53 //
54 // How frames are destroyed
55 // ------------------------
56 //
57 // The main frame is never destroyed and is re-used. The FrameLoader is re-used
58 // and a reference to the main frame is kept by the Page.
59 //
60 // When frame content is replaced, all subframes are destroyed. This happens
61 // in FrameLoader::detachFromParent for each subframe in a pre-order depth-first
62 // traversal. Note that child node order may not match DOM node order!
63 // detachFromParent() calls FrameLoaderClient::detachedFromParent(), which calls
64 // WebFrame::frameDetached(). This triggers WebFrame to clear its reference to
65 // LocalFrame, and also notifies the embedder via WebFrameClient that the frame is
66 // detached. Most embedders will invoke close() on the WebFrame at this point,
67 // triggering its deletion unless something else is still retaining a reference.
68 //
69 // Thie client is expected to be set whenever the WebFrameImpl is attached to
70 // the DOM.
71
72 #include "config.h"
73 #include "WebFrameImpl.h"
74
75 #include <algorithm>
76 #include "AssociatedURLLoader.h"
77 #include "CompositionUnderlineVectorBuilder.h"
78 #include "EventListenerWrapper.h"
79 #include "FindInPageCoordinates.h"
80 #include "HTMLNames.h"
81 #include "PageOverlay.h"
82 #include "SharedWorkerRepositoryClientImpl.h"
83 #include "TextFinder.h"
84 #include "WebConsoleMessage.h"
85 #include "WebDOMEvent.h"
86 #include "WebDOMEventListener.h"
87 #include "WebDataSourceImpl.h"
88 #include "WebDevToolsAgentPrivate.h"
89 #include "WebDocument.h"
90 #include "WebFindOptions.h"
91 #include "WebFormElement.h"
92 #include "WebFrameClient.h"
93 #include "WebHistoryItem.h"
94 #include "WebIconURL.h"
95 #include "WebInputElement.h"
96 #include "WebNode.h"
97 #include "WebPerformance.h"
98 #include "WebPlugin.h"
99 #include "WebPluginContainerImpl.h"
100 #include "WebPrintParams.h"
101 #include "WebRange.h"
102 #include "WebScriptSource.h"
103 #include "WebSecurityOrigin.h"
104 #include "WebSerializedScriptValue.h"
105 #include "WebViewImpl.h"
106 #include "bindings/v8/DOMWrapperWorld.h"
107 #include "bindings/v8/ExceptionState.h"
108 #include "bindings/v8/ExceptionStatePlaceholder.h"
109 #include "bindings/v8/ScriptController.h"
110 #include "bindings/v8/ScriptSourceCode.h"
111 #include "bindings/v8/ScriptValue.h"
112 #include "bindings/v8/V8GCController.h"
113 #include "bindings/v8/V8PerIsolateData.h"
114 #include "core/dom/Document.h"
115 #include "core/dom/DocumentMarker.h"
116 #include "core/dom/DocumentMarkerController.h"
117 #include "core/dom/IconURL.h"
118 #include "core/dom/MessagePort.h"
119 #include "core/dom/Node.h"
120 #include "core/dom/NodeTraversal.h"
121 #include "core/dom/shadow/ShadowRoot.h"
122 #include "core/editing/Editor.h"
123 #include "core/editing/FrameSelection.h"
124 #include "core/editing/InputMethodController.h"
125 #include "core/editing/PlainTextRange.h"
126 #include "core/editing/SpellChecker.h"
127 #include "core/editing/TextAffinity.h"
128 #include "core/editing/TextIterator.h"
129 #include "core/editing/htmlediting.h"
130 #include "core/editing/markup.h"
131 #include "core/frame/Console.h"
132 #include "core/frame/DOMWindow.h"
133 #include "core/frame/FrameView.h"
134 #include "core/html/HTMLCollection.h"
135 #include "core/html/HTMLFormElement.h"
136 #include "core/html/HTMLFrameElementBase.h"
137 #include "core/html/HTMLFrameOwnerElement.h"
138 #include "core/html/HTMLHeadElement.h"
139 #include "core/html/HTMLInputElement.h"
140 #include "core/html/HTMLLinkElement.h"
141 #include "core/html/PluginDocument.h"
142 #include "core/inspector/InspectorController.h"
143 #include "core/inspector/ScriptCallStack.h"
144 #include "core/loader/DocumentLoader.h"
145 #include "core/loader/FrameLoadRequest.h"
146 #include "core/loader/FrameLoader.h"
147 #include "core/loader/HistoryItem.h"
148 #include "core/loader/SubstituteData.h"
149 #include "core/page/Chrome.h"
150 #include "core/page/EventHandler.h"
151 #include "core/page/FocusController.h"
152 #include "core/page/FrameTree.h"
153 #include "core/page/Page.h"
154 #include "core/page/PrintContext.h"
155 #include "core/frame/Settings.h"
156 #include "core/rendering/HitTestResult.h"
157 #include "core/rendering/RenderBox.h"
158 #include "core/rendering/RenderFrame.h"
159 #include "core/rendering/RenderLayer.h"
160 #include "core/rendering/RenderObject.h"
161 #include "core/rendering/RenderTreeAsText.h"
162 #include "core/rendering/RenderView.h"
163 #include "core/rendering/style/StyleInheritedData.h"
164 #include "core/timing/Performance.h"
165 #include "modules/notifications/NotificationController.h"
166 #include "platform/TraceEvent.h"
167 #include "platform/UserGestureIndicator.h"
168 #include "platform/clipboard/ClipboardUtilities.h"
169 #include "platform/fonts/FontCache.h"
170 #include "platform/graphics/GraphicsContext.h"
171 #include "platform/graphics/GraphicsLayerClient.h"
172 #include "platform/graphics/skia/SkiaUtils.h"
173 #include "platform/heap/Handle.h"
174 #include "platform/network/ResourceRequest.h"
175 #include "platform/scroll/ScrollbarTheme.h"
176 #include "platform/scroll/ScrollTypes.h"
177 #include "platform/weborigin/KURL.h"
178 #include "platform/weborigin/SchemeRegistry.h"
179 #include "platform/weborigin/SecurityPolicy.h"
180 #include "public/platform/Platform.h"
181 #include "public/platform/WebFloatPoint.h"
182 #include "public/platform/WebFloatRect.h"
183 #include "public/platform/WebLayer.h"
184 #include "public/platform/WebPoint.h"
185 #include "public/platform/WebRect.h"
186 #include "public/platform/WebSize.h"
187 #include "public/platform/WebURLError.h"
188 #include "public/platform/WebVector.h"
189 #include "wtf/CurrentTime.h"
190 #include "wtf/HashMap.h"
191
192 using namespace WebCore;
193
194 namespace blink {
195
196 static int frameCount = 0;
197
198 // Key for a StatsCounter tracking how many WebFrames are active.
199 static const char webFrameActiveCount[] = "WebFrameActiveCount";
200
201 static void frameContentAsPlainText(size_t maxChars, LocalFrame* frame, StringBu ilder& output)
202 {
203 Document* document = frame->document();
204 if (!document)
205 return;
206
207 if (!frame->view())
208 return;
209
210 // TextIterator iterates over the visual representation of the DOM. As such,
211 // it requires you to do a layout before using it (otherwise it'll crash).
212 document->updateLayout();
213
214 // Select the document body.
215 RefPtrWillBeRawPtr<Range> range(document->createRange());
216 TrackExceptionState exceptionState;
217 range->selectNodeContents(document->body(), exceptionState);
218
219 if (!exceptionState.hadException()) {
220 // The text iterator will walk nodes giving us text. This is similar to
221 // the plainText() function in core/editing/TextIterator.h, but we imple ment the maximum
222 // size and also copy the results directly into a wstring, avoiding the
223 // string conversion.
224 for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
225 it.appendTextToStringBuilder(output, 0, maxChars - output.length());
226 if (output.length() >= maxChars)
227 return; // Filled up the buffer.
228 }
229 }
230
231 // The separator between frames when the frames are converted to plain text.
232 const LChar frameSeparator[] = { '\n', '\n' };
233 const size_t frameSeparatorLength = WTF_ARRAY_LENGTH(frameSeparator);
234
235 // Recursively walk the children.
236 const FrameTree& frameTree = frame->tree();
237 for (LocalFrame* curChild = frameTree.firstChild(); curChild; curChild = cur Child->tree().nextSibling()) {
238 // Ignore the text of non-visible frames.
239 RenderView* contentRenderer = curChild->contentRenderer();
240 RenderPart* ownerRenderer = curChild->ownerRenderer();
241 if (!contentRenderer || !contentRenderer->width() || !contentRenderer->h eight()
242 || (contentRenderer->x() + contentRenderer->width() <= 0) || (conten tRenderer->y() + contentRenderer->height() <= 0)
243 || (ownerRenderer && ownerRenderer->style() && ownerRenderer->style( )->visibility() != VISIBLE)) {
244 continue;
245 }
246
247 // Make sure the frame separator won't fill up the buffer, and give up i f
248 // it will. The danger is if the separator will make the buffer longer t han
249 // maxChars. This will cause the computation above:
250 // maxChars - output->size()
251 // to be a negative number which will crash when the subframe is added.
252 if (output.length() >= maxChars - frameSeparatorLength)
253 return;
254
255 output.append(frameSeparator, frameSeparatorLength);
256 frameContentAsPlainText(maxChars, curChild, output);
257 if (output.length() >= maxChars)
258 return; // Filled up the buffer.
259 }
260 }
261
262 WebPluginContainerImpl* WebFrameImpl::pluginContainerFromFrame(LocalFrame* frame )
263 {
264 if (!frame)
265 return 0;
266 if (!frame->document() || !frame->document()->isPluginDocument())
267 return 0;
268 PluginDocument* pluginDocument = toPluginDocument(frame->document());
269 return toWebPluginContainerImpl(pluginDocument->pluginWidget());
270 }
271
272 WebPluginContainerImpl* WebFrameImpl::pluginContainerFromNode(WebCore::LocalFram e* frame, const WebNode& node)
273 {
274 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame);
275 if (pluginContainer)
276 return pluginContainer;
277 return toWebPluginContainerImpl(node.pluginContainer());
278 }
279
280 // Simple class to override some of PrintContext behavior. Some of the methods
281 // made virtual so that they can be overridden by ChromePluginPrintContext.
282 class ChromePrintContext : public PrintContext {
283 WTF_MAKE_NONCOPYABLE(ChromePrintContext);
284 public:
285 ChromePrintContext(LocalFrame* frame)
286 : PrintContext(frame)
287 , m_printedPageWidth(0)
288 {
289 }
290
291 virtual ~ChromePrintContext() { }
292
293 virtual void begin(float width, float height)
294 {
295 ASSERT(!m_printedPageWidth);
296 m_printedPageWidth = width;
297 PrintContext::begin(m_printedPageWidth, height);
298 }
299
300 virtual void end()
301 {
302 PrintContext::end();
303 }
304
305 virtual float getPageShrink(int pageNumber) const
306 {
307 IntRect pageRect = m_pageRects[pageNumber];
308 return m_printedPageWidth / pageRect.width();
309 }
310
311 // Spools the printed page, a subrect of frame(). Skip the scale step.
312 // NativeTheme doesn't play well with scaling. Scaling is done browser side
313 // instead. Returns the scale to be applied.
314 // On Linux, we don't have the problem with NativeTheme, hence we let WebKit
315 // do the scaling and ignore the return value.
316 virtual float spoolPage(GraphicsContext& context, int pageNumber)
317 {
318 IntRect pageRect = m_pageRects[pageNumber];
319 float scale = m_printedPageWidth / pageRect.width();
320
321 context.save();
322 #if OS(POSIX) && !OS(MACOSX)
323 context.scale(WebCore::FloatSize(scale, scale));
324 #endif
325 context.translate(static_cast<float>(-pageRect.x()), static_cast<float>( -pageRect.y()));
326 context.clip(pageRect);
327 frame()->view()->paintContents(&context, pageRect);
328 if (context.supportsURLFragments())
329 outputLinkedDestinations(context, frame()->document(), pageRect);
330 context.restore();
331 return scale;
332 }
333
334 void spoolAllPagesWithBoundaries(GraphicsContext& graphicsContext, const Flo atSize& pageSizeInPixels)
335 {
336 if (!frame()->document() || !frame()->view() || !frame()->document()->re nderer())
337 return;
338
339 frame()->document()->updateLayout();
340
341 float pageHeight;
342 computePageRects(FloatRect(FloatPoint(0, 0), pageSizeInPixels), 0, 0, 1, pageHeight);
343
344 const float pageWidth = pageSizeInPixels.width();
345 size_t numPages = pageRects().size();
346 int totalHeight = numPages * (pageSizeInPixels.height() + 1) - 1;
347
348 // Fill the whole background by white.
349 graphicsContext.setFillColor(Color::white);
350 graphicsContext.fillRect(FloatRect(0, 0, pageWidth, totalHeight));
351
352 int currentHeight = 0;
353 for (size_t pageIndex = 0; pageIndex < numPages; pageIndex++) {
354 // Draw a line for a page boundary if this isn't the first page.
355 if (pageIndex > 0) {
356 graphicsContext.save();
357 graphicsContext.setStrokeColor(Color(0, 0, 255));
358 graphicsContext.setFillColor(Color(0, 0, 255));
359 graphicsContext.drawLine(IntPoint(0, currentHeight), IntPoint(pa geWidth, currentHeight));
360 graphicsContext.restore();
361 }
362
363 graphicsContext.save();
364
365 graphicsContext.translate(0, currentHeight);
366 #if OS(WIN) || OS(MACOSX)
367 // Account for the disabling of scaling in spoolPage. In the context
368 // of spoolAllPagesWithBoundaries the scale HAS NOT been pre-applied .
369 float scale = getPageShrink(pageIndex);
370 graphicsContext.scale(WebCore::FloatSize(scale, scale));
371 #endif
372 spoolPage(graphicsContext, pageIndex);
373 graphicsContext.restore();
374
375 currentHeight += pageSizeInPixels.height() + 1;
376 }
377 }
378
379 virtual void computePageRects(const FloatRect& printRect, float headerHeight , float footerHeight, float userScaleFactor, float& outPageHeight)
380 {
381 PrintContext::computePageRects(printRect, headerHeight, footerHeight, us erScaleFactor, outPageHeight);
382 }
383
384 virtual int pageCount() const
385 {
386 return PrintContext::pageCount();
387 }
388
389 private:
390 // Set when printing.
391 float m_printedPageWidth;
392 };
393
394 // Simple class to override some of PrintContext behavior. This is used when
395 // the frame hosts a plugin that supports custom printing. In this case, we
396 // want to delegate all printing related calls to the plugin.
397 class ChromePluginPrintContext : public ChromePrintContext {
398 public:
399 ChromePluginPrintContext(LocalFrame* frame, WebPluginContainerImpl* plugin, const WebPrintParams& printParams)
400 : ChromePrintContext(frame), m_plugin(plugin), m_pageCount(0), m_printPa rams(printParams)
401 {
402 }
403
404 virtual ~ChromePluginPrintContext() { }
405
406 virtual void begin(float width, float height)
407 {
408 }
409
410 virtual void end()
411 {
412 m_plugin->printEnd();
413 }
414
415 virtual float getPageShrink(int pageNumber) const
416 {
417 // We don't shrink the page (maybe we should ask the widget ??)
418 return 1.0;
419 }
420
421 virtual void computePageRects(const FloatRect& printRect, float headerHeight , float footerHeight, float userScaleFactor, float& outPageHeight)
422 {
423 m_printParams.printContentArea = IntRect(printRect);
424 m_pageCount = m_plugin->printBegin(m_printParams);
425 }
426
427 virtual int pageCount() const
428 {
429 return m_pageCount;
430 }
431
432 // Spools the printed page, a subrect of frame(). Skip the scale step.
433 // NativeTheme doesn't play well with scaling. Scaling is done browser side
434 // instead. Returns the scale to be applied.
435 virtual float spoolPage(GraphicsContext& context, int pageNumber)
436 {
437 m_plugin->printPage(pageNumber, &context);
438 return 1.0;
439 }
440
441 private:
442 // Set when printing.
443 WebPluginContainerImpl* m_plugin;
444 int m_pageCount;
445 WebPrintParams m_printParams;
446
447 };
448
449 static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader)
450 {
451 return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0;
452 }
453
454 // WebFrame -------------------------------------------------------------------
455
456 int WebFrame::instanceCount()
457 {
458 return frameCount;
459 }
460
461 WebLocalFrame* WebLocalFrame::frameForCurrentContext()
462 {
463 v8::Handle<v8::Context> context = v8::Isolate::GetCurrent()->GetCurrentConte xt();
464 if (context.IsEmpty())
465 return 0;
466 return frameForContext(context);
467 }
468
469 WebLocalFrame* WebLocalFrame::frameForContext(v8::Handle<v8::Context> context)
470 {
471 return WebFrameImpl::fromFrame(toFrameIfNotDetached(context));
472 }
473
474 WebLocalFrame* WebLocalFrame::fromFrameOwnerElement(const WebElement& element)
475 {
476 return WebFrameImpl::fromFrameOwnerElement(PassRefPtr<Element>(element).get( ));
477 }
478
479 void WebFrameImpl::close()
480 {
481 m_client = 0;
482 deref(); // Balances ref() acquired in WebFrame::create
483 }
484
485 WebString WebFrameImpl::uniqueName() const
486 {
487 return frame()->tree().uniqueName();
488 }
489
490 WebString WebFrameImpl::assignedName() const
491 {
492 return frame()->tree().name();
493 }
494
495 void WebFrameImpl::setName(const WebString& name)
496 {
497 frame()->tree().setName(name);
498 }
499
500 WebVector<WebIconURL> WebFrameImpl::iconURLs(int iconTypesMask) const
501 {
502 // The URL to the icon may be in the header. As such, only
503 // ask the loader for the icon if it's finished loading.
504 if (frame()->loader().state() == FrameStateComplete)
505 return frame()->document()->iconURLs(iconTypesMask);
506 return WebVector<WebIconURL>();
507 }
508
509 void WebFrameImpl::setIsRemote(bool isRemote)
510 {
511 m_isRemote = isRemote;
512 if (isRemote)
513 client()->initializeChildFrame(frame()->view()->frameRect(), frame()->vi ew()->visibleContentScaleFactor());
514 }
515
516 void WebFrameImpl::setRemoteWebLayer(WebLayer* webLayer)
517 {
518 if (!frame())
519 return;
520
521 if (frame()->remotePlatformLayer())
522 GraphicsLayer::unregisterContentsLayer(frame()->remotePlatformLayer());
523 if (webLayer)
524 GraphicsLayer::registerContentsLayer(webLayer);
525 frame()->setRemotePlatformLayer(webLayer);
526 frame()->ownerElement()->scheduleLayerUpdate();
527 }
528
529 void WebFrameImpl::setPermissionClient(WebPermissionClient* permissionClient)
530 {
531 m_permissionClient = permissionClient;
532 }
533
534 void WebFrameImpl::setSharedWorkerRepositoryClient(WebSharedWorkerRepositoryClie nt* client)
535 {
536 m_sharedWorkerRepositoryClient = SharedWorkerRepositoryClientImpl::create(cl ient);
537 }
538
539 WebSize WebFrameImpl::scrollOffset() const
540 {
541 FrameView* view = frameView();
542 if (!view)
543 return WebSize();
544 return view->scrollOffset();
545 }
546
547 WebSize WebFrameImpl::minimumScrollOffset() const
548 {
549 FrameView* view = frameView();
550 if (!view)
551 return WebSize();
552 return toIntSize(view->minimumScrollPosition());
553 }
554
555 WebSize WebFrameImpl::maximumScrollOffset() const
556 {
557 FrameView* view = frameView();
558 if (!view)
559 return WebSize();
560 return toIntSize(view->maximumScrollPosition());
561 }
562
563 void WebFrameImpl::setScrollOffset(const WebSize& offset)
564 {
565 if (FrameView* view = frameView())
566 view->setScrollOffset(IntPoint(offset.width, offset.height));
567 }
568
569 WebSize WebFrameImpl::contentsSize() const
570 {
571 return frame()->view()->contentsSize();
572 }
573
574 bool WebFrameImpl::hasVisibleContent() const
575 {
576 return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight () > 0;
577 }
578
579 WebRect WebFrameImpl::visibleContentRect() const
580 {
581 return frame()->view()->visibleContentRect();
582 }
583
584 bool WebFrameImpl::hasHorizontalScrollbar() const
585 {
586 return frame() && frame()->view() && frame()->view()->horizontalScrollbar();
587 }
588
589 bool WebFrameImpl::hasVerticalScrollbar() const
590 {
591 return frame() && frame()->view() && frame()->view()->verticalScrollbar();
592 }
593
594 WebView* WebFrameImpl::view() const
595 {
596 return viewImpl();
597 }
598
599 WebFrame* WebFrameImpl::opener() const
600 {
601 return m_opener;
602 }
603
604 void WebFrameImpl::setOpener(WebFrame* opener)
605 {
606 WebFrameImpl* openerImpl = toWebFrameImpl(opener);
607 if (m_opener && !openerImpl && m_client)
608 m_client->didDisownOpener(this);
609
610 if (m_opener)
611 m_opener->m_openedFrames.remove(this);
612 if (openerImpl)
613 openerImpl->m_openedFrames.add(this);
614 m_opener = openerImpl;
615
616 ASSERT(m_frame);
617 if (m_frame && m_frame->document())
618 m_frame->document()->initSecurityContext();
619 }
620
621 void WebFrameImpl::appendChild(WebFrame* child)
622 {
623 // FIXME: Original code asserts that the frames have the same Page. We
624 // should add an equivalent check... figure out what.
625 WebFrameImpl* childImpl = toWebFrameImpl(child);
626 childImpl->m_parent = this;
627 WebFrameImpl* oldLast = m_lastChild;
628 m_lastChild = childImpl;
629
630 if (oldLast) {
631 childImpl->m_previousSibling = oldLast;
632 oldLast->m_nextSibling = childImpl;
633 } else {
634 m_firstChild = childImpl;
635 }
636 // FIXME: Not sure if this is a legitimate assert.
637 ASSERT(frame());
638 frame()->tree().invalidateScopedChildCount();
639 }
640
641 void WebFrameImpl::removeChild(WebFrame* child)
642 {
643 WebFrameImpl* childImpl = toWebFrameImpl(child);
644 childImpl->m_parent = 0;
645
646 if (m_firstChild == childImpl)
647 m_firstChild = childImpl->m_nextSibling;
648 else
649 childImpl->m_previousSibling->m_nextSibling = childImpl->m_nextSibling;
650
651 if (m_lastChild == childImpl)
652 m_lastChild = childImpl->m_previousSibling;
653 else
654 childImpl->m_nextSibling->m_previousSibling = childImpl->m_previousSibli ng;
655
656 childImpl->m_previousSibling = childImpl->m_nextSibling = 0;
657 // FIXME: Not sure if this is a legitimate assert.
658 ASSERT(frame());
659 frame()->tree().invalidateScopedChildCount();
660 }
661
662 WebFrame* WebFrameImpl::parent() const
663 {
664 return m_parent;
665 }
666
667 WebFrame* WebFrameImpl::top() const
668 {
669 WebFrameImpl* frame = const_cast<WebFrameImpl*>(this);
670 for (WebFrameImpl* parent = frame; parent; parent = parent->m_parent)
671 frame = parent;
672 return frame;
673 }
674
675 WebFrame* WebFrameImpl::previousSibling() const
676 {
677 return m_previousSibling;
678 }
679
680 WebFrame* WebFrameImpl::nextSibling() const
681 {
682 return m_nextSibling;
683 }
684
685 WebFrame* WebFrameImpl::firstChild() const
686 {
687 return m_firstChild;
688 }
689
690 WebFrame* WebFrameImpl::lastChild() const
691 {
692 return m_lastChild;
693 }
694
695 WebFrame* WebFrameImpl::traversePrevious(bool wrap) const
696 {
697 if (!frame())
698 return 0;
699 return fromFrame(frame()->tree().traversePreviousWithWrap(wrap));
700 }
701
702 WebFrame* WebFrameImpl::traverseNext(bool wrap) const
703 {
704 if (!frame())
705 return 0;
706 return fromFrame(frame()->tree().traverseNextWithWrap(wrap));
707 }
708
709 WebFrame* WebFrameImpl::findChildByName(const WebString& name) const
710 {
711 if (!frame())
712 return 0;
713 return fromFrame(frame()->tree().child(name));
714 }
715
716 WebDocument WebFrameImpl::document() const
717 {
718 if (!frame() || !frame()->document())
719 return WebDocument();
720 return WebDocument(frame()->document());
721 }
722
723 WebPerformance WebFrameImpl::performance() const
724 {
725 if (!frame())
726 return WebPerformance();
727 return WebPerformance(&frame()->domWindow()->performance());
728 }
729
730 bool WebFrameImpl::dispatchBeforeUnloadEvent()
731 {
732 if (!frame())
733 return true;
734 return frame()->loader().shouldClose();
735 }
736
737 void WebFrameImpl::dispatchUnloadEvent()
738 {
739 if (!frame())
740 return;
741 frame()->loader().closeURL();
742 }
743
744 NPObject* WebFrameImpl::windowObject() const
745 {
746 if (!frame())
747 return 0;
748 return frame()->script().windowScriptNPObject();
749 }
750
751 void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object)
752 {
753 bindToWindowObject(name, object, 0);
754 }
755
756 void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object, v oid*)
757 {
758 if (!frame() || !frame()->script().canExecuteScripts(NotAboutToExecuteScript ))
759 return;
760 frame()->script().bindToWindowObject(frame(), String(name), object);
761 }
762
763 void WebFrameImpl::executeScript(const WebScriptSource& source)
764 {
765 ASSERT(frame());
766 TextPosition position(OrdinalNumber::fromOneBasedInt(source.startLine), Ordi nalNumber::first());
767 frame()->script().executeScriptInMainWorld(ScriptSourceCode(source.code, sou rce.url, position));
768 }
769
770 void WebFrameImpl::executeScriptInIsolatedWorld(int worldID, const WebScriptSour ce* sourcesIn, unsigned numSources, int extensionGroup)
771 {
772 ASSERT(frame());
773 RELEASE_ASSERT(worldID > 0);
774 RELEASE_ASSERT(worldID < EmbedderWorldIdLimit);
775
776 Vector<ScriptSourceCode> sources;
777 for (unsigned i = 0; i < numSources; ++i) {
778 TextPosition position(OrdinalNumber::fromOneBasedInt(sourcesIn[i].startL ine), OrdinalNumber::first());
779 sources.append(ScriptSourceCode(sourcesIn[i].code, sourcesIn[i].url, pos ition));
780 }
781
782 frame()->script().executeScriptInIsolatedWorld(worldID, sources, extensionGr oup, 0);
783 }
784
785 void WebFrameImpl::setIsolatedWorldSecurityOrigin(int worldID, const WebSecurity Origin& securityOrigin)
786 {
787 ASSERT(frame());
788 DOMWrapperWorld::setIsolatedWorldSecurityOrigin(worldID, securityOrigin.get( ));
789 }
790
791 void WebFrameImpl::setIsolatedWorldContentSecurityPolicy(int worldID, const WebS tring& policy)
792 {
793 ASSERT(frame());
794 DOMWrapperWorld::setIsolatedWorldContentSecurityPolicy(worldID, policy);
795 }
796
797 void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message)
798 {
799 ASSERT(frame());
800
801 MessageLevel webCoreMessageLevel;
802 switch (message.level) {
803 case WebConsoleMessage::LevelDebug:
804 webCoreMessageLevel = DebugMessageLevel;
805 break;
806 case WebConsoleMessage::LevelLog:
807 webCoreMessageLevel = LogMessageLevel;
808 break;
809 case WebConsoleMessage::LevelWarning:
810 webCoreMessageLevel = WarningMessageLevel;
811 break;
812 case WebConsoleMessage::LevelError:
813 webCoreMessageLevel = ErrorMessageLevel;
814 break;
815 default:
816 ASSERT_NOT_REACHED();
817 return;
818 }
819
820 frame()->document()->addConsoleMessage(OtherMessageSource, webCoreMessageLev el, message.text);
821 }
822
823 void WebFrameImpl::collectGarbage()
824 {
825 if (!frame())
826 return;
827 if (!frame()->settings()->scriptEnabled())
828 return;
829 V8GCController::collectGarbage(v8::Isolate::GetCurrent());
830 }
831
832 bool WebFrameImpl::checkIfRunInsecureContent(const WebURL& url) const
833 {
834 ASSERT(frame());
835 return frame()->loader().mixedContentChecker()->canRunInsecureContent(frame( )->document()->securityOrigin(), url);
836 }
837
838 v8::Handle<v8::Value> WebFrameImpl::executeScriptAndReturnValue(const WebScriptS ource& source)
839 {
840 ASSERT(frame());
841
842 // FIXME: This fake user gesture is required to make a bunch of pyauto
843 // tests pass. If this isn't needed in non-test situations, we should
844 // consider removing this code and changing the tests.
845 // http://code.google.com/p/chromium/issues/detail?id=86397
846 UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
847
848 TextPosition position(OrdinalNumber::fromOneBasedInt(source.startLine), Ordi nalNumber::first());
849 return frame()->script().executeScriptInMainWorldAndReturnValue(ScriptSource Code(source.code, source.url, position)).v8Value();
850 }
851
852 void WebFrameImpl::executeScriptInIsolatedWorld(int worldID, const WebScriptSour ce* sourcesIn, unsigned numSources, int extensionGroup, WebVector<v8::Local<v8:: Value> >* results)
853 {
854 ASSERT(frame());
855 RELEASE_ASSERT(worldID > 0);
856 RELEASE_ASSERT(worldID < EmbedderWorldIdLimit);
857
858 Vector<ScriptSourceCode> sources;
859
860 for (unsigned i = 0; i < numSources; ++i) {
861 TextPosition position(OrdinalNumber::fromOneBasedInt(sourcesIn[i].startL ine), OrdinalNumber::first());
862 sources.append(ScriptSourceCode(sourcesIn[i].code, sourcesIn[i].url, pos ition));
863 }
864
865 if (results) {
866 Vector<ScriptValue> scriptResults;
867 frame()->script().executeScriptInIsolatedWorld(worldID, sources, extensi onGroup, &scriptResults);
868 WebVector<v8::Local<v8::Value> > v8Results(scriptResults.size());
869 for (unsigned i = 0; i < scriptResults.size(); i++)
870 v8Results[i] = v8::Local<v8::Value>::New(toIsolate(frame()), scriptR esults[i].v8Value());
871 results->swap(v8Results);
872 } else {
873 frame()->script().executeScriptInIsolatedWorld(worldID, sources, extensi onGroup, 0);
874 }
875 }
876
877 v8::Handle<v8::Value> WebFrameImpl::callFunctionEvenIfScriptDisabled(v8::Handle< v8::Function> function, v8::Handle<v8::Value> receiver, int argc, v8::Handle<v8: :Value> argv[])
878 {
879 ASSERT(frame());
880 return frame()->script().callFunction(function, receiver, argc, argv);
881 }
882
883 v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const
884 {
885 return toV8Context(V8PerIsolateData::mainThreadIsolate(), frame(), DOMWrappe rWorld::mainWorld());
886 }
887
888 void WebFrameImpl::reload(bool ignoreCache)
889 {
890 ASSERT(frame());
891 frame()->loader().reload(ignoreCache ? EndToEndReload : NormalReload);
892 }
893
894 void WebFrameImpl::reloadWithOverrideURL(const WebURL& overrideUrl, bool ignoreC ache)
895 {
896 ASSERT(frame());
897 frame()->loader().reload(ignoreCache ? EndToEndReload : NormalReload, overri deUrl);
898 }
899
900 void WebFrameImpl::loadRequest(const WebURLRequest& request)
901 {
902 ASSERT(frame());
903 ASSERT(!request.isNull());
904 const ResourceRequest& resourceRequest = request.toResourceRequest();
905
906 if (resourceRequest.url().protocolIs("javascript")) {
907 loadJavaScriptURL(resourceRequest.url());
908 return;
909 }
910
911 frame()->loader().load(FrameLoadRequest(0, resourceRequest));
912 }
913
914 void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item, WebHistoryLoadTyp e loadType, WebURLRequest::CachePolicy cachePolicy)
915 {
916 ASSERT(frame());
917 RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item);
918 ASSERT(historyItem);
919 frame()->loader().loadHistoryItem(historyItem.get(), static_cast<HistoryLoad Type>(loadType), static_cast<ResourceRequestCachePolicy>(cachePolicy));
920 }
921
922 void WebFrameImpl::loadData(const WebData& data, const WebString& mimeType, cons t WebString& textEncoding, const WebURL& baseURL, const WebURL& unreachableURL, bool replace)
923 {
924 ASSERT(frame());
925
926 // If we are loading substitute data to replace an existing load, then
927 // inherit all of the properties of that original request. This way,
928 // reload will re-attempt the original request. It is essential that
929 // we only do this when there is an unreachableURL since a non-empty
930 // unreachableURL informs FrameLoader::reload to load unreachableURL
931 // instead of the currently loaded URL.
932 ResourceRequest request;
933 if (replace && !unreachableURL.isEmpty() && frame()->loader().provisionalDoc umentLoader())
934 request = frame()->loader().provisionalDocumentLoader()->originalRequest ();
935 request.setURL(baseURL);
936
937 FrameLoadRequest frameRequest(0, request, SubstituteData(data, mimeType, tex tEncoding, unreachableURL));
938 ASSERT(frameRequest.substituteData().isValid());
939 frameRequest.setLockBackForwardList(replace);
940 frame()->loader().load(frameRequest);
941 }
942
943 void WebFrameImpl::loadHTMLString(const WebData& data, const WebURL& baseURL, co nst WebURL& unreachableURL, bool replace)
944 {
945 ASSERT(frame());
946 loadData(data, WebString::fromUTF8("text/html"), WebString::fromUTF8("UTF-8" ), baseURL, unreachableURL, replace);
947 }
948
949 bool WebFrameImpl::isLoading() const
950 {
951 if (!frame())
952 return false;
953 return frame()->loader().isLoading();
954 }
955
956 void WebFrameImpl::stopLoading()
957 {
958 if (!frame())
959 return;
960 // FIXME: Figure out what we should really do here. It seems like a bug
961 // that FrameLoader::stopLoading doesn't call stopAllLoaders.
962 frame()->loader().stopAllLoaders();
963 }
964
965 WebDataSource* WebFrameImpl::provisionalDataSource() const
966 {
967 ASSERT(frame());
968
969 // We regard the policy document loader as still provisional.
970 DocumentLoader* documentLoader = frame()->loader().provisionalDocumentLoader ();
971 if (!documentLoader)
972 documentLoader = frame()->loader().policyDocumentLoader();
973
974 return DataSourceForDocLoader(documentLoader);
975 }
976
977 WebDataSource* WebFrameImpl::dataSource() const
978 {
979 ASSERT(frame());
980 return DataSourceForDocLoader(frame()->loader().documentLoader());
981 }
982
983 void WebFrameImpl::enableViewSourceMode(bool enable)
984 {
985 if (frame())
986 frame()->setInViewSourceMode(enable);
987 }
988
989 bool WebFrameImpl::isViewSourceModeEnabled() const
990 {
991 if (!frame())
992 return false;
993 return frame()->inViewSourceMode();
994 }
995
996 void WebFrameImpl::setReferrerForRequest(WebURLRequest& request, const WebURL& r eferrerURL)
997 {
998 String referrer = referrerURL.isEmpty() ? frame()->document()->outgoingRefer rer() : String(referrerURL.spec().utf16());
999 referrer = SecurityPolicy::generateReferrerHeader(frame()->document()->refer rerPolicy(), request.url(), referrer);
1000 if (referrer.isEmpty())
1001 return;
1002 request.setHTTPReferrer(referrer, static_cast<WebReferrerPolicy>(frame()->do cument()->referrerPolicy()));
1003 }
1004
1005 void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request)
1006 {
1007 ResourceResponse response;
1008 frame()->loader().client()->dispatchWillSendRequest(0, 0, request.toMutableR esourceRequest(), response);
1009 }
1010
1011 WebURLLoader* WebFrameImpl::createAssociatedURLLoader(const WebURLLoaderOptions& options)
1012 {
1013 return new AssociatedURLLoader(this, options);
1014 }
1015
1016 unsigned WebFrameImpl::unloadListenerCount() const
1017 {
1018 return frame()->domWindow()->pendingUnloadEventListeners();
1019 }
1020
1021 void WebFrameImpl::replaceSelection(const WebString& text)
1022 {
1023 bool selectReplacement = false;
1024 bool smartReplace = true;
1025 frame()->editor().replaceSelectionWithText(text, selectReplacement, smartRep lace);
1026 }
1027
1028 void WebFrameImpl::insertText(const WebString& text)
1029 {
1030 if (frame()->inputMethodController().hasComposition())
1031 frame()->inputMethodController().confirmComposition(text);
1032 else
1033 frame()->editor().insertText(text, 0);
1034 }
1035
1036 void WebFrameImpl::setMarkedText(const WebString& text, unsigned location, unsig ned length)
1037 {
1038 Vector<CompositionUnderline> decorations;
1039 frame()->inputMethodController().setComposition(text, decorations, location, length);
1040 }
1041
1042 void WebFrameImpl::unmarkText()
1043 {
1044 frame()->inputMethodController().cancelComposition();
1045 }
1046
1047 bool WebFrameImpl::hasMarkedText() const
1048 {
1049 return frame()->inputMethodController().hasComposition();
1050 }
1051
1052 WebRange WebFrameImpl::markedRange() const
1053 {
1054 return frame()->inputMethodController().compositionRange();
1055 }
1056
1057 bool WebFrameImpl::firstRectForCharacterRange(unsigned location, unsigned length , WebRect& rect) const
1058 {
1059 if ((location + length < location) && (location + length))
1060 length = 0;
1061
1062 Element* editable = frame()->selection().rootEditableElementOrDocumentElemen t();
1063 ASSERT(editable);
1064 RefPtrWillBeRawPtr<Range> range = PlainTextRange(location, location + length ).createRange(*editable);
1065 if (!range)
1066 return false;
1067 IntRect intRect = frame()->editor().firstRectForRange(range.get());
1068 rect = WebRect(intRect);
1069 rect = frame()->view()->contentsToWindow(rect);
1070 return true;
1071 }
1072
1073 size_t WebFrameImpl::characterIndexForPoint(const WebPoint& webPoint) const
1074 {
1075 if (!frame())
1076 return kNotFound;
1077
1078 IntPoint point = frame()->view()->windowToContents(webPoint);
1079 HitTestResult result = frame()->eventHandler().hitTestResultAtPoint(point, H itTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndO ftenMisusedDisallowShadowContent);
1080 RefPtrWillBeRawPtr<Range> range = frame()->rangeForPoint(result.roundedPoint InInnerNodeFrame());
1081 if (!range)
1082 return kNotFound;
1083 Element* editable = frame()->selection().rootEditableElementOrDocumentElemen t();
1084 ASSERT(editable);
1085 return PlainTextRange::create(*editable, *range.get()).start();
1086 }
1087
1088 bool WebFrameImpl::executeCommand(const WebString& name, const WebNode& node)
1089 {
1090 ASSERT(frame());
1091
1092 if (name.length() <= 2)
1093 return false;
1094
1095 // Since we don't have NSControl, we will convert the format of command
1096 // string and call the function on Editor directly.
1097 String command = name;
1098
1099 // Make sure the first letter is upper case.
1100 command.replace(0, 1, command.substring(0, 1).upper());
1101
1102 // Remove the trailing ':' if existing.
1103 if (command[command.length() - 1] == UChar(':'))
1104 command = command.substring(0, command.length() - 1);
1105
1106 WebPluginContainerImpl* pluginContainer = pluginContainerFromNode(frame(), n ode);
1107 if (pluginContainer && pluginContainer->executeEditCommand(name))
1108 return true;
1109
1110 bool result = true;
1111
1112 // Specially handling commands that Editor::execCommand does not directly
1113 // support.
1114 if (command == "DeleteToEndOfParagraph") {
1115 if (!frame()->editor().deleteWithDirection(DirectionForward, ParagraphBo undary, true, false))
1116 frame()->editor().deleteWithDirection(DirectionForward, CharacterGra nularity, true, false);
1117 } else if (command == "Indent") {
1118 frame()->editor().indent();
1119 } else if (command == "Outdent") {
1120 frame()->editor().outdent();
1121 } else if (command == "DeleteBackward") {
1122 result = frame()->editor().command(AtomicString("BackwardDelete")).execu te();
1123 } else if (command == "DeleteForward") {
1124 result = frame()->editor().command(AtomicString("ForwardDelete")).execut e();
1125 } else if (command == "AdvanceToNextMisspelling") {
1126 // Wee need to pass false here or else the currently selected word will never be skipped.
1127 frame()->spellChecker().advanceToNextMisspelling(false);
1128 } else if (command == "ToggleSpellPanel") {
1129 frame()->spellChecker().showSpellingGuessPanel();
1130 } else {
1131 result = frame()->editor().command(command).execute();
1132 }
1133 return result;
1134 }
1135
1136 bool WebFrameImpl::executeCommand(const WebString& name, const WebString& value, const WebNode& node)
1137 {
1138 ASSERT(frame());
1139 String webName = name;
1140
1141 WebPluginContainerImpl* pluginContainer = pluginContainerFromNode(frame(), n ode);
1142 if (pluginContainer && pluginContainer->executeEditCommand(name, value))
1143 return true;
1144
1145 // moveToBeginningOfDocument and moveToEndfDocument are only handled by WebK it for editable nodes.
1146 if (!frame()->editor().canEdit() && webName == "moveToBeginningOfDocument")
1147 return viewImpl()->bubblingScroll(ScrollUp, ScrollByDocument);
1148
1149 if (!frame()->editor().canEdit() && webName == "moveToEndOfDocument")
1150 return viewImpl()->bubblingScroll(ScrollDown, ScrollByDocument);
1151
1152 if (webName == "showGuessPanel") {
1153 frame()->spellChecker().showSpellingGuessPanel();
1154 return true;
1155 }
1156
1157 return frame()->editor().command(webName).execute(value);
1158 }
1159
1160 bool WebFrameImpl::isCommandEnabled(const WebString& name) const
1161 {
1162 ASSERT(frame());
1163 return frame()->editor().command(name).isEnabled();
1164 }
1165
1166 void WebFrameImpl::enableContinuousSpellChecking(bool enable)
1167 {
1168 if (enable == isContinuousSpellCheckingEnabled())
1169 return;
1170 frame()->spellChecker().toggleContinuousSpellChecking();
1171 }
1172
1173 bool WebFrameImpl::isContinuousSpellCheckingEnabled() const
1174 {
1175 return frame()->spellChecker().isContinuousSpellCheckingEnabled();
1176 }
1177
1178 void WebFrameImpl::requestTextChecking(const WebElement& webElement)
1179 {
1180 if (webElement.isNull())
1181 return;
1182 frame()->spellChecker().requestTextChecking(*webElement.constUnwrap<Element> ());
1183 }
1184
1185 void WebFrameImpl::replaceMisspelledRange(const WebString& text)
1186 {
1187 // If this caret selection has two or more markers, this function replace th e range covered by the first marker with the specified word as Microsoft Word do es.
1188 if (pluginContainerFromFrame(frame()))
1189 return;
1190 RefPtrWillBeRawPtr<Range> caretRange = frame()->selection().toNormalizedRang e();
1191 if (!caretRange)
1192 return;
1193 Vector<DocumentMarker*> markers = frame()->document()->markers().markersInRa nge(caretRange.get(), DocumentMarker::MisspellingMarkers());
1194 if (markers.size() < 1 || markers[0]->startOffset() >= markers[0]->endOffset ())
1195 return;
1196 RefPtrWillBeRawPtr<Range> markerRange = Range::create(caretRange->ownerDocum ent(), caretRange->startContainer(), markers[0]->startOffset(), caretRange->endC ontainer(), markers[0]->endOffset());
1197 if (!markerRange)
1198 return;
1199 frame()->selection().setSelection(VisibleSelection(markerRange.get()), Chara cterGranularity);
1200 frame()->editor().replaceSelectionWithText(text, false, false);
1201 }
1202
1203 void WebFrameImpl::removeSpellingMarkers()
1204 {
1205 frame()->document()->markers().removeMarkers(DocumentMarker::MisspellingMark ers());
1206 }
1207
1208 bool WebFrameImpl::hasSelection() const
1209 {
1210 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1211 if (pluginContainer)
1212 return pluginContainer->plugin()->hasSelection();
1213
1214 // frame()->selection()->isNone() never returns true.
1215 return frame()->selection().start() != frame()->selection().end();
1216 }
1217
1218 WebRange WebFrameImpl::selectionRange() const
1219 {
1220 return frame()->selection().toNormalizedRange();
1221 }
1222
1223 WebString WebFrameImpl::selectionAsText() const
1224 {
1225 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1226 if (pluginContainer)
1227 return pluginContainer->plugin()->selectionAsText();
1228
1229 RefPtrWillBeRawPtr<Range> range = frame()->selection().toNormalizedRange();
1230 if (!range)
1231 return WebString();
1232
1233 String text = range->text();
1234 #if OS(WIN)
1235 replaceNewlinesWithWindowsStyleNewlines(text);
1236 #endif
1237 replaceNBSPWithSpace(text);
1238 return text;
1239 }
1240
1241 WebString WebFrameImpl::selectionAsMarkup() const
1242 {
1243 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1244 if (pluginContainer)
1245 return pluginContainer->plugin()->selectionAsMarkup();
1246
1247 RefPtrWillBeRawPtr<Range> range = frame()->selection().toNormalizedRange();
1248 if (!range)
1249 return WebString();
1250
1251 return createMarkup(range.get(), 0, AnnotateForInterchange, false, ResolveNo nLocalURLs);
1252 }
1253
1254 void WebFrameImpl::selectWordAroundPosition(LocalFrame* frame, VisiblePosition p osition)
1255 {
1256 VisibleSelection selection(position);
1257 selection.expandUsingGranularity(WordGranularity);
1258
1259 TextGranularity granularity = selection.isRange() ? WordGranularity : Charac terGranularity;
1260 frame->selection().setSelection(selection, granularity);
1261 }
1262
1263 bool WebFrameImpl::selectWordAroundCaret()
1264 {
1265 FrameSelection& selection = frame()->selection();
1266 ASSERT(!selection.isNone());
1267 if (selection.isNone() || selection.isRange())
1268 return false;
1269 selectWordAroundPosition(frame(), selection.selection().visibleStart());
1270 return true;
1271 }
1272
1273 void WebFrameImpl::selectRange(const WebPoint& base, const WebPoint& extent)
1274 {
1275 moveRangeSelection(base, extent);
1276 }
1277
1278 void WebFrameImpl::selectRange(const WebRange& webRange)
1279 {
1280 if (RefPtrWillBeRawPtr<Range> range = static_cast<PassRefPtrWillBeRawPtr<Ran ge> >(webRange))
1281 frame()->selection().setSelectedRange(range.get(), WebCore::VP_DEFAULT_A FFINITY, false);
1282 }
1283
1284 void WebFrameImpl::moveRangeSelection(const WebPoint& base, const WebPoint& exte nt)
1285 {
1286 VisiblePosition basePosition = visiblePositionForWindowPoint(base);
1287 VisiblePosition extentPosition = visiblePositionForWindowPoint(extent);
1288 VisibleSelection newSelection = VisibleSelection(basePosition, extentPositio n);
1289 frame()->selection().setSelection(newSelection, CharacterGranularity);
1290 }
1291
1292 void WebFrameImpl::moveCaretSelection(const WebPoint& point)
1293 {
1294 Element* editable = frame()->selection().rootEditableElement();
1295 if (!editable)
1296 return;
1297
1298 VisiblePosition position = visiblePositionForWindowPoint(point);
1299 frame()->selection().moveTo(position, UserTriggered);
1300 }
1301
1302 bool WebFrameImpl::setEditableSelectionOffsets(int start, int end)
1303 {
1304 return frame()->inputMethodController().setEditableSelectionOffsets(PlainTex tRange(start, end));
1305 }
1306
1307 bool WebFrameImpl::setCompositionFromExistingText(int compositionStart, int comp ositionEnd, const WebVector<WebCompositionUnderline>& underlines)
1308 {
1309 if (!frame()->editor().canEdit())
1310 return false;
1311
1312 InputMethodController& inputMethodController = frame()->inputMethodControlle r();
1313 inputMethodController.cancelComposition();
1314
1315 if (compositionStart == compositionEnd)
1316 return true;
1317
1318 inputMethodController.setCompositionFromExistingText(CompositionUnderlineVec torBuilder(underlines), compositionStart, compositionEnd);
1319
1320 return true;
1321 }
1322
1323 void WebFrameImpl::extendSelectionAndDelete(int before, int after)
1324 {
1325 if (WebPlugin* plugin = focusedPluginIfInputMethodSupported()) {
1326 plugin->extendSelectionAndDelete(before, after);
1327 return;
1328 }
1329 frame()->inputMethodController().extendSelectionAndDelete(before, after);
1330 }
1331
1332 void WebFrameImpl::setCaretVisible(bool visible)
1333 {
1334 frame()->selection().setCaretVisible(visible);
1335 }
1336
1337 VisiblePosition WebFrameImpl::visiblePositionForWindowPoint(const WebPoint& poin t)
1338 {
1339 FloatPoint unscaledPoint(point);
1340 unscaledPoint.scale(1 / view()->pageScaleFactor(), 1 / view()->pageScaleFact or());
1341
1342 HitTestRequest request = HitTestRequest::Move | HitTestRequest::ReadOnly | H itTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::Confusi ngAndOftenMisusedDisallowShadowContent;
1343 HitTestResult result(frame()->view()->windowToContents(roundedIntPoint(unsca ledPoint)));
1344 frame()->document()->renderView()->layer()->hitTest(request, result);
1345
1346 if (Node* node = result.targetNode())
1347 return frame()->selection().selection().visiblePositionRespectingEditing Boundary(result.localPoint(), node);
1348 return VisiblePosition();
1349 }
1350
1351 WebPlugin* WebFrameImpl::focusedPluginIfInputMethodSupported()
1352 {
1353 WebPluginContainerImpl* container = WebFrameImpl::pluginContainerFromNode(fr ame(), WebNode(frame()->document()->focusedElement()));
1354 if (container && container->supportsInputMethod())
1355 return container->plugin();
1356 return 0;
1357 }
1358
1359 NotificationPresenterImpl* WebFrameImpl::notificationPresenterImpl()
1360 {
1361 if (!m_notificationPresenter.isInitialized() && m_client)
1362 m_notificationPresenter.initialize(m_client->notificationPresenter());
1363 return &m_notificationPresenter;
1364 }
1365
1366 int WebFrameImpl::printBegin(const WebPrintParams& printParams, const WebNode& c onstrainToNode)
1367 {
1368 ASSERT(!frame()->document()->isFrameSet());
1369 WebPluginContainerImpl* pluginContainer = 0;
1370 if (constrainToNode.isNull()) {
1371 // If this is a plugin document, check if the plugin supports its own
1372 // printing. If it does, we will delegate all printing to that.
1373 pluginContainer = pluginContainerFromFrame(frame());
1374 } else {
1375 // We only support printing plugin nodes for now.
1376 pluginContainer = toWebPluginContainerImpl(constrainToNode.pluginContain er());
1377 }
1378
1379 if (pluginContainer && pluginContainer->supportsPaginatedPrint())
1380 m_printContext = adoptPtr(new ChromePluginPrintContext(frame(), pluginCo ntainer, printParams));
1381 else
1382 m_printContext = adoptPtr(new ChromePrintContext(frame()));
1383
1384 FloatRect rect(0, 0, static_cast<float>(printParams.printContentArea.width), static_cast<float>(printParams.printContentArea.height));
1385 m_printContext->begin(rect.width(), rect.height());
1386 float pageHeight;
1387 // We ignore the overlays calculation for now since they are generated in th e
1388 // browser. pageHeight is actually an output parameter.
1389 m_printContext->computePageRects(rect, 0, 0, 1.0, pageHeight);
1390
1391 return m_printContext->pageCount();
1392 }
1393
1394 float WebFrameImpl::getPrintPageShrink(int page)
1395 {
1396 ASSERT(m_printContext && page >= 0);
1397 return m_printContext->getPageShrink(page);
1398 }
1399
1400 float WebFrameImpl::printPage(int page, WebCanvas* canvas)
1401 {
1402 #if ENABLE(PRINTING)
1403 ASSERT(m_printContext && page >= 0 && frame() && frame()->document());
1404
1405 GraphicsContext graphicsContext(canvas);
1406 graphicsContext.setPrinting(true);
1407 return m_printContext->spoolPage(graphicsContext, page);
1408 #else
1409 return 0;
1410 #endif
1411 }
1412
1413 void WebFrameImpl::printEnd()
1414 {
1415 ASSERT(m_printContext);
1416 m_printContext->end();
1417 m_printContext.clear();
1418 }
1419
1420 bool WebFrameImpl::isPrintScalingDisabledForPlugin(const WebNode& node)
1421 {
1422 WebPluginContainerImpl* pluginContainer = node.isNull() ? pluginContainerFr omFrame(frame()) : toWebPluginContainerImpl(node.pluginContainer());
1423
1424 if (!pluginContainer || !pluginContainer->supportsPaginatedPrint())
1425 return false;
1426
1427 return pluginContainer->isPrintScalingDisabled();
1428 }
1429
1430 bool WebFrameImpl::hasCustomPageSizeStyle(int pageIndex)
1431 {
1432 return frame()->document()->styleForPage(pageIndex)->pageSizeType() != PAGE_ SIZE_AUTO;
1433 }
1434
1435 bool WebFrameImpl::isPageBoxVisible(int pageIndex)
1436 {
1437 return frame()->document()->isPageBoxVisible(pageIndex);
1438 }
1439
1440 void WebFrameImpl::pageSizeAndMarginsInPixels(int pageIndex, WebSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1441 {
1442 IntSize size = pageSize;
1443 frame()->document()->pageSizeAndMarginsInPixels(pageIndex, size, marginTop, marginRight, marginBottom, marginLeft);
1444 pageSize = size;
1445 }
1446
1447 WebString WebFrameImpl::pageProperty(const WebString& propertyName, int pageInde x)
1448 {
1449 ASSERT(m_printContext);
1450 return m_printContext->pageProperty(frame(), propertyName.utf8().data(), pag eIndex);
1451 }
1452
1453 bool WebFrameImpl::find(int identifier, const WebString& searchText, const WebFi ndOptions& options, bool wrapWithinFrame, WebRect* selectionRect)
1454 {
1455 return ensureTextFinder().find(identifier, searchText, options, wrapWithinFr ame, selectionRect);
1456 }
1457
1458 void WebFrameImpl::stopFinding(bool clearSelection)
1459 {
1460 if (m_textFinder) {
1461 if (!clearSelection)
1462 setFindEndstateFocusAndSelection();
1463 m_textFinder->stopFindingAndClearSelection();
1464 }
1465 }
1466
1467 void WebFrameImpl::scopeStringMatches(int identifier, const WebString& searchTex t, const WebFindOptions& options, bool reset)
1468 {
1469 ensureTextFinder().scopeStringMatches(identifier, searchText, options, reset );
1470 }
1471
1472 void WebFrameImpl::cancelPendingScopingEffort()
1473 {
1474 if (m_textFinder)
1475 m_textFinder->cancelPendingScopingEffort();
1476 }
1477
1478 void WebFrameImpl::increaseMatchCount(int count, int identifier)
1479 {
1480 // This function should only be called on the mainframe.
1481 ASSERT(!parent());
1482 ASSERT(m_textFinder);
1483 m_textFinder->increaseMatchCount(identifier, count);
1484 }
1485
1486 void WebFrameImpl::resetMatchCount()
1487 {
1488 ASSERT(m_textFinder);
1489 m_textFinder->resetMatchCount();
1490 }
1491
1492 void WebFrameImpl::sendOrientationChangeEvent(int orientation)
1493 {
1494 if (frame())
1495 frame()->sendOrientationChangeEvent(orientation);
1496 }
1497
1498 void WebFrameImpl::dispatchMessageEventWithOriginCheck(const WebSecurityOrigin& intendedTargetOrigin, const WebDOMEvent& event)
1499 {
1500 ASSERT(!event.isNull());
1501 frame()->domWindow()->dispatchMessageEventWithOriginCheck(intendedTargetOrig in.get(), event, nullptr);
1502 }
1503
1504 int WebFrameImpl::findMatchMarkersVersion() const
1505 {
1506 ASSERT(!parent());
1507
1508 if (m_textFinder)
1509 return m_textFinder->findMatchMarkersVersion();
1510 return 0;
1511 }
1512
1513 int WebFrameImpl::selectNearestFindMatch(const WebFloatPoint& point, WebRect* se lectionRect)
1514 {
1515 ASSERT(!parent());
1516 ASSERT(m_textFinder);
1517 return m_textFinder->selectNearestFindMatch(point, selectionRect);
1518 }
1519
1520 WebFloatRect WebFrameImpl::activeFindMatchRect()
1521 {
1522 ASSERT(!parent());
1523
1524 if (m_textFinder)
1525 return m_textFinder->activeFindMatchRect();
1526 return WebFloatRect();
1527 }
1528
1529 void WebFrameImpl::findMatchRects(WebVector<WebFloatRect>& outputRects)
1530 {
1531 ASSERT(!parent());
1532 ASSERT(m_textFinder);
1533 m_textFinder->findMatchRects(outputRects);
1534 }
1535
1536 void WebFrameImpl::setTickmarks(const WebVector<WebRect>& tickmarks)
1537 {
1538 if (frameView()) {
1539 Vector<IntRect> tickmarksConverted(tickmarks.size());
1540 for (size_t i = 0; i < tickmarks.size(); ++i)
1541 tickmarksConverted[i] = tickmarks[i];
1542 frameView()->setTickmarks(tickmarksConverted);
1543 invalidateScrollbar();
1544 }
1545 }
1546
1547 WebString WebFrameImpl::contentAsText(size_t maxChars) const
1548 {
1549 if (!frame())
1550 return WebString();
1551 StringBuilder text;
1552 frameContentAsPlainText(maxChars, frame(), text);
1553 return text.toString();
1554 }
1555
1556 WebString WebFrameImpl::contentAsMarkup() const
1557 {
1558 if (!frame())
1559 return WebString();
1560 return createFullMarkup(frame()->document());
1561 }
1562
1563 WebString WebFrameImpl::renderTreeAsText(RenderAsTextControls toShow) const
1564 {
1565 RenderAsTextBehavior behavior = RenderAsTextBehaviorNormal;
1566
1567 if (toShow & RenderAsTextDebug)
1568 behavior |= RenderAsTextShowCompositedLayers | RenderAsTextShowAddresses | RenderAsTextShowIDAndClass | RenderAsTextShowLayerNesting;
1569
1570 if (toShow & RenderAsTextPrinting)
1571 behavior |= RenderAsTextPrintingMode;
1572
1573 return externalRepresentation(frame(), behavior);
1574 }
1575
1576 WebString WebFrameImpl::markerTextForListItem(const WebElement& webElement) cons t
1577 {
1578 return WebCore::markerTextForListItem(const_cast<Element*>(webElement.constU nwrap<Element>()));
1579 }
1580
1581 void WebFrameImpl::printPagesWithBoundaries(WebCanvas* canvas, const WebSize& pa geSizeInPixels)
1582 {
1583 ASSERT(m_printContext);
1584
1585 GraphicsContext graphicsContext(canvas);
1586 graphicsContext.setPrinting(true);
1587
1588 m_printContext->spoolAllPagesWithBoundaries(graphicsContext, FloatSize(pageS izeInPixels.width, pageSizeInPixels.height));
1589 }
1590
1591 WebRect WebFrameImpl::selectionBoundsRect() const
1592 {
1593 return hasSelection() ? WebRect(IntRect(frame()->selection().bounds(false))) : WebRect();
1594 }
1595
1596 bool WebFrameImpl::selectionStartHasSpellingMarkerFor(int from, int length) cons t
1597 {
1598 if (!frame())
1599 return false;
1600 return frame()->spellChecker().selectionStartHasMarkerFor(DocumentMarker::Sp elling, from, length);
1601 }
1602
1603 WebString WebFrameImpl::layerTreeAsText(bool showDebugInfo) const
1604 {
1605 if (!frame())
1606 return WebString();
1607
1608 return WebString(frame()->layerTreeAsText(showDebugInfo ? LayerTreeIncludesD ebugInfo : LayerTreeNormal));
1609 }
1610
1611 // WebFrameImpl public ---------------------------------------------------------
1612
1613 WebLocalFrame* WebLocalFrame::create(WebFrameClient* client)
1614 {
1615 return WebFrameImpl::create(client);
1616 }
1617
1618 WebFrameImpl* WebFrameImpl::create(WebFrameClient* client)
1619 {
1620 return adoptRef(new WebFrameImpl(client)).leakRef();
1621 }
1622
1623 WebFrameImpl::WebFrameImpl(WebFrameClient* client)
1624 : m_frameLoaderClientImpl(this)
1625 , m_parent(0)
1626 , m_previousSibling(0)
1627 , m_nextSibling(0)
1628 , m_firstChild(0)
1629 , m_lastChild(0)
1630 , m_opener(0)
1631 , m_client(client)
1632 , m_permissionClient(0)
1633 , m_inputEventsScaleFactorForEmulation(1)
1634 {
1635 blink::Platform::current()->incrementStatsCounter(webFrameActiveCount);
1636 frameCount++;
1637 }
1638
1639 WebFrameImpl::~WebFrameImpl()
1640 {
1641 HashSet<WebFrameImpl*>::iterator end = m_openedFrames.end();
1642 for (HashSet<WebFrameImpl*>::iterator it = m_openedFrames.begin(); it != end ; ++it)
1643 (*it)->m_opener = 0;
1644
1645 blink::Platform::current()->decrementStatsCounter(webFrameActiveCount);
1646 frameCount--;
1647
1648 cancelPendingScopingEffort();
1649 }
1650
1651 void WebFrameImpl::setWebCoreFrame(PassRefPtr<WebCore::LocalFrame> frame)
1652 {
1653 m_frame = frame;
1654
1655 // FIXME: we shouldn't add overhead to every frame by registering these obje cts when they're not used.
1656 if (m_frame)
1657 provideNotification(*m_frame, notificationPresenterImpl());
1658 }
1659
1660 void WebFrameImpl::initializeAsMainFrame(WebCore::Page* page)
1661 {
1662 setWebCoreFrame(LocalFrame::create(&m_frameLoaderClientImpl, &page->frameHos t(), 0));
1663
1664 // We must call init() after m_frame is assigned because it is referenced
1665 // during init().
1666 m_frame->init();
1667 }
1668
1669 PassRefPtr<LocalFrame> WebFrameImpl::createChildFrame(const FrameLoadRequest& re quest, HTMLFrameOwnerElement* ownerElement)
1670 {
1671 ASSERT(m_client);
1672 WebFrameImpl* webframe = toWebFrameImpl(m_client->createChildFrame(this, req uest.frameName()));
1673 if (!webframe)
1674 return nullptr;
1675
1676 RefPtr<LocalFrame> childFrame = LocalFrame::create(&webframe->m_frameLoaderC lientImpl, frame()->host(), ownerElement);
1677 webframe->setWebCoreFrame(childFrame);
1678
1679 // FIXME: Using subResourceAttributeName as fallback is not a perfect
1680 // solution. subResourceAttributeName returns just one attribute name. The
1681 // element might not have the attribute, and there might be other attributes
1682 // which can identify the element.
1683 childFrame->tree().setName(request.frameName(), ownerElement->getAttribute(o wnerElement->subResourceAttributeName()));
1684
1685 // FIXME: This comment is not quite accurate anymore.
1686 // LocalFrame::init() can trigger onload event in the parent frame,
1687 // which may detach this frame and trigger a null-pointer access
1688 // in FrameTree::removeChild. Move init() after appendChild call
1689 // so that webframe->mFrame is in the tree before triggering
1690 // onload event handler.
1691 // Because the event handler may set webframe->mFrame to null,
1692 // it is necessary to check the value after calling init() and
1693 // return without loading URL.
1694 // NOTE: m_client will be null if this frame has been detached.
1695 // (b:791612)
1696 childFrame->init(); // create an empty document
1697 if (!childFrame->tree().parent())
1698 return nullptr;
1699
1700 // If we're moving in the back/forward list, we might want to replace the co ntent
1701 // of this child frame with whatever was there at that point.
1702 RefPtr<HistoryItem> childItem;
1703 if (isBackForwardLoadType(frame()->loader().loadType()) && !frame()->documen t()->loadEventFinished())
1704 childItem = PassRefPtr<HistoryItem>(webframe->client()->historyItemForNe wChildFrame(webframe));
1705
1706 if (childItem)
1707 childFrame->loader().loadHistoryItem(childItem.get());
1708 else
1709 childFrame->loader().load(FrameLoadRequest(0, request.resourceRequest(), "_self"));
1710
1711 // A synchronous navigation (about:blank) would have already processed
1712 // onload, so it is possible for the frame to have already been destroyed by
1713 // script in the page.
1714 // NOTE: m_client will be null if this frame has been detached.
1715 if (!childFrame->tree().parent())
1716 return nullptr;
1717
1718 return childFrame.release();
1719 }
1720
1721 void WebFrameImpl::didChangeContentsSize(const IntSize& size)
1722 {
1723 // This is only possible on the main frame.
1724 if (m_textFinder && m_textFinder->totalMatchCount() > 0) {
1725 ASSERT(!parent());
1726 m_textFinder->increaseMarkerVersion();
1727 }
1728 }
1729
1730 void WebFrameImpl::createFrameView()
1731 {
1732 TRACE_EVENT0("webkit", "WebFrameImpl::createFrameView");
1733
1734 ASSERT(frame()); // If frame() doesn't exist, we probably didn't init proper ly.
1735
1736 WebViewImpl* webView = viewImpl();
1737 bool isMainFrame = webView->mainFrameImpl()->frame() == frame();
1738 if (isMainFrame)
1739 webView->suppressInvalidations(true);
1740
1741 frame()->createView(webView->size(), webView->baseBackgroundColor(), webView ->isTransparent());
1742 if (webView->shouldAutoResize() && isMainFrame)
1743 frame()->view()->enableAutoSizeMode(true, webView->minAutoSize(), webVie w->maxAutoSize());
1744
1745 frame()->view()->setInputEventsTransformForEmulation(m_inputEventsOffsetForE mulation, m_inputEventsScaleFactorForEmulation);
1746
1747 if (isMainFrame)
1748 webView->suppressInvalidations(false);
1749 }
1750
1751 WebFrameImpl* WebFrameImpl::fromFrame(LocalFrame* frame)
1752 {
1753 if (!frame)
1754 return 0;
1755 FrameLoaderClient* client = frame->loader().client();
1756 if (!client || !client->isFrameLoaderClientImpl())
1757 return 0;
1758 return toFrameLoaderClientImpl(client)->webFrame();
1759 }
1760
1761 WebFrameImpl* WebFrameImpl::fromFrameOwnerElement(Element* element)
1762 {
1763 // FIXME: Why do we check specifically for <iframe> and <frame> here? Why ca n't we get the WebFrameImpl from an <object> element, for example.
1764 if (!isHTMLFrameElementBase(element))
1765 return 0;
1766 return fromFrame(toLocalFrame(toHTMLFrameElementBase(element)->contentFrame( )));
1767 }
1768
1769 WebViewImpl* WebFrameImpl::viewImpl() const
1770 {
1771 if (!frame())
1772 return 0;
1773 return WebViewImpl::fromPage(frame()->page());
1774 }
1775
1776 WebDataSourceImpl* WebFrameImpl::dataSourceImpl() const
1777 {
1778 return static_cast<WebDataSourceImpl*>(dataSource());
1779 }
1780
1781 WebDataSourceImpl* WebFrameImpl::provisionalDataSourceImpl() const
1782 {
1783 return static_cast<WebDataSourceImpl*>(provisionalDataSource());
1784 }
1785
1786 void WebFrameImpl::setFindEndstateFocusAndSelection()
1787 {
1788 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1789
1790 if (this != mainFrameImpl->activeMatchFrame())
1791 return;
1792
1793 if (Range* activeMatch = m_textFinder->activeMatch()) {
1794 // If the user has set the selection since the match was found, we
1795 // don't focus anything.
1796 VisibleSelection selection(frame()->selection().selection());
1797 if (!selection.isNone())
1798 return;
1799
1800 // Try to find the first focusable node up the chain, which will, for
1801 // example, focus links if we have found text within the link.
1802 Node* node = activeMatch->firstNode();
1803 if (node && node->isInShadowTree()) {
1804 if (Node* host = node->shadowHost()) {
1805 if (isHTMLInputElement(*host) || isHTMLTextAreaElement(*host))
1806 node = host;
1807 }
1808 }
1809 for (; node; node = node->parentNode()) {
1810 if (!node->isElementNode())
1811 continue;
1812 Element* element = toElement(node);
1813 if (element->isFocusable()) {
1814 // Found a focusable parent node. Set the active match as the
1815 // selection and focus to the focusable node.
1816 frame()->selection().setSelection(VisibleSelection(activeMatch)) ;
1817 frame()->document()->setFocusedElement(element);
1818 return;
1819 }
1820 }
1821
1822 // Iterate over all the nodes in the range until we find a focusable nod e.
1823 // This, for example, sets focus to the first link if you search for
1824 // text and text that is within one or more links.
1825 node = activeMatch->firstNode();
1826 for (; node && node != activeMatch->pastLastNode(); node = NodeTraversal ::next(*node)) {
1827 if (!node->isElementNode())
1828 continue;
1829 Element* element = toElement(node);
1830 if (element->isFocusable()) {
1831 frame()->document()->setFocusedElement(element);
1832 return;
1833 }
1834 }
1835
1836 // No node related to the active match was focusable, so set the
1837 // active match as the selection (so that when you end the Find session,
1838 // you'll have the last thing you found highlighted) and make sure that
1839 // we have nothing focused (otherwise you might have text selected but
1840 // a link focused, which is weird).
1841 frame()->selection().setSelection(VisibleSelection(activeMatch));
1842 frame()->document()->setFocusedElement(nullptr);
1843
1844 // Finally clear the active match, for two reasons:
1845 // We just finished the find 'session' and we don't want future (potenti ally
1846 // unrelated) find 'sessions' operations to start at the same place.
1847 // The WebFrameImpl could get reused and the activeMatch could end up po inting
1848 // to a document that is no longer valid. Keeping an invalid reference a round
1849 // is just asking for trouble.
1850 m_textFinder->resetActiveMatch();
1851 }
1852 }
1853
1854 void WebFrameImpl::didFail(const ResourceError& error, bool wasProvisional)
1855 {
1856 if (!client())
1857 return;
1858 WebURLError webError = error;
1859 if (wasProvisional)
1860 client()->didFailProvisionalLoad(this, webError);
1861 else
1862 client()->didFailLoad(this, webError);
1863 }
1864
1865 void WebFrameImpl::setCanHaveScrollbars(bool canHaveScrollbars)
1866 {
1867 frame()->view()->setCanHaveScrollbars(canHaveScrollbars);
1868 }
1869
1870 void WebFrameImpl::setInputEventsTransformForEmulation(const IntSize& offset, fl oat contentScaleFactor)
1871 {
1872 m_inputEventsOffsetForEmulation = offset;
1873 m_inputEventsScaleFactorForEmulation = contentScaleFactor;
1874 if (frame()->view())
1875 frame()->view()->setInputEventsTransformForEmulation(m_inputEventsOffset ForEmulation, m_inputEventsScaleFactorForEmulation);
1876 }
1877
1878 void WebFrameImpl::loadJavaScriptURL(const KURL& url)
1879 {
1880 // This is copied from ScriptController::executeScriptIfJavaScriptURL.
1881 // Unfortunately, we cannot just use that method since it is private, and
1882 // it also doesn't quite behave as we require it to for bookmarklets. The
1883 // key difference is that we need to suppress loading the string result
1884 // from evaluating the JS URL if executing the JS URL resulted in a
1885 // location change. We also allow a JS URL to be loaded even if scripts on
1886 // the page are otherwise disabled.
1887
1888 if (!frame()->document() || !frame()->page())
1889 return;
1890
1891 RefPtr<Document> ownerDocument(frame()->document());
1892
1893 // Protect privileged pages against bookmarklets and other javascript manipu lations.
1894 if (SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(frame()- >document()->url().protocol()))
1895 return;
1896
1897 String script = decodeURLEscapeSequences(url.string().substring(strlen("java script:")));
1898 UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
1899 ScriptValue result = frame()->script().executeScriptInMainWorldAndReturnValu e(ScriptSourceCode(script));
1900
1901 String scriptResult;
1902 if (!result.toString(scriptResult))
1903 return;
1904
1905 if (!frame()->navigationScheduler().locationChangePending())
1906 frame()->document()->loader()->replaceDocument(scriptResult, ownerDocume nt.get());
1907 }
1908
1909 void WebFrameImpl::willDetachParent()
1910 {
1911 // Do not expect string scoping results from any frames that got detached
1912 // in the middle of the operation.
1913 if (m_textFinder && m_textFinder->scopingInProgress()) {
1914
1915 // There is a possibility that the frame being detached was the only
1916 // pending one. We need to make sure final replies can be sent.
1917 m_textFinder->flushCurrentScoping();
1918
1919 m_textFinder->cancelPendingScopingEffort();
1920 }
1921 }
1922
1923 WebFrameImpl* WebFrameImpl::activeMatchFrame() const
1924 {
1925 ASSERT(!parent());
1926
1927 if (m_textFinder)
1928 return m_textFinder->activeMatchFrame();
1929 return 0;
1930 }
1931
1932 WebCore::Range* WebFrameImpl::activeMatch() const
1933 {
1934 if (m_textFinder)
1935 return m_textFinder->activeMatch();
1936 return 0;
1937 }
1938
1939 TextFinder& WebFrameImpl::ensureTextFinder()
1940 {
1941 if (!m_textFinder)
1942 m_textFinder = TextFinder::create(*this);
1943
1944 return *m_textFinder;
1945 }
1946
1947 void WebFrameImpl::invalidateScrollbar() const
1948 {
1949 ASSERT(frame() && frame()->view());
1950 FrameView* view = frame()->view();
1951 // Invalidate the vertical scroll bar region for the view.
1952 Scrollbar* scrollbar = view->verticalScrollbar();
1953 if (scrollbar)
1954 scrollbar->invalidate();
1955 }
1956
1957 void WebFrameImpl::invalidateAll() const
1958 {
1959 ASSERT(frame() && frame()->view());
1960 FrameView* view = frame()->view();
1961 view->invalidateRect(view->frameRect());
1962 invalidateScrollbar();
1963 }
1964
1965 } // namespace blink
OLDNEW
« no previous file with comments | « Source/web/WebFrameImpl.h ('k') | Source/web/WebHelperPluginImpl.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698