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

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

Issue 181013007: Introduce TextFinder class for decoupling WebFrameImpl and text finder. (Closed) Base URL: https://chromium.googlesource.com/chromium/blink.git@introduce-textfinder-class-new
Patch Set: Rebase Created 6 years, 9 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
OLDNEW
1 /* 1 /*
2 * Copyright (C) 2009 Google Inc. All rights reserved. 2 * Copyright (C) 2009 Google Inc. All rights reserved.
3 * 3 *
4 * Redistribution and use in source and binary forms, with or without 4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are 5 * modification, are permitted provided that the following conditions are
6 * met: 6 * met:
7 * 7 *
8 * * Redistributions of source code must retain the above copyright 8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer. 9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above 10 * * Redistributions in binary form must reproduce the above
(...skipping 10 matching lines...) Expand all
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 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. 28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */ 29 */
30 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 31
72 #include "config.h" 32 #include "config.h"
73 #include "TextFinder.h" 33 #include "TextFinder.h"
74 34
75 #include <algorithm>
76 #include "AssociatedURLLoader.h"
77 #include "DOMUtilitiesPrivate.h"
78 #include "EventListenerWrapper.h"
79 #include "FindInPageCoordinates.h" 35 #include "FindInPageCoordinates.h"
80 #include "HTMLNames.h"
81 #include "PageOverlay.h"
82 #include "SharedWorkerRepositoryClientImpl.h"
83 #include "WebConsoleMessage.h"
84 #include "WebDOMEvent.h"
85 #include "WebDOMEventListener.h"
86 #include "WebDataSourceImpl.h"
87 #include "WebDevToolsAgentPrivate.h"
88 #include "WebDocument.h"
89 #include "WebFindOptions.h" 36 #include "WebFindOptions.h"
90 #include "WebFormElement.h"
91 #include "WebFrameClient.h" 37 #include "WebFrameClient.h"
92 #include "WebHistoryItem.h" 38 #include "WebFrameImpl.h"
93 #include "WebIconURL.h" 39 #include "WebViewClient.h"
94 #include "WebInputElement.h"
95 #include "WebNode.h"
96 #include "WebPerformance.h"
97 #include "WebPlugin.h"
98 #include "WebPluginContainerImpl.h"
99 #include "WebPrintParams.h"
100 #include "WebRange.h"
101 #include "WebScriptSource.h"
102 #include "WebSecurityOrigin.h"
103 #include "WebSerializedScriptValue.h"
104 #include "WebViewImpl.h" 40 #include "WebViewImpl.h"
105 #include "bindings/v8/DOMWrapperWorld.h"
106 #include "bindings/v8/ExceptionState.h"
107 #include "bindings/v8/ExceptionStatePlaceholder.h"
108 #include "bindings/v8/ScriptController.h"
109 #include "bindings/v8/ScriptSourceCode.h"
110 #include "bindings/v8/ScriptValue.h"
111 #include "bindings/v8/V8GCController.h"
112 #include "bindings/v8/V8PerIsolateData.h"
113 #include "core/dom/Document.h"
114 #include "core/dom/DocumentMarker.h" 41 #include "core/dom/DocumentMarker.h"
115 #include "core/dom/DocumentMarkerController.h" 42 #include "core/dom/DocumentMarkerController.h"
116 #include "core/dom/IconURL.h" 43 #include "core/dom/Range.h"
117 #include "core/dom/MessagePort.h"
118 #include "core/dom/Node.h"
119 #include "core/dom/NodeTraversal.h"
120 #include "core/dom/shadow/ShadowRoot.h" 44 #include "core/dom/shadow/ShadowRoot.h"
121 #include "core/editing/Editor.h" 45 #include "core/editing/Editor.h"
122 #include "core/editing/FrameSelection.h"
123 #include "core/editing/InputMethodController.h"
124 #include "core/editing/PlainTextRange.h"
125 #include "core/editing/SpellChecker.h"
126 #include "core/editing/TextAffinity.h"
127 #include "core/editing/TextIterator.h" 46 #include "core/editing/TextIterator.h"
128 #include "core/editing/htmlediting.h" 47 #include "core/editing/VisibleSelection.h"
129 #include "core/editing/markup.h"
130 #include "core/frame/Console.h"
131 #include "core/frame/DOMWindow.h"
132 #include "core/frame/FrameView.h" 48 #include "core/frame/FrameView.h"
133 #include "core/html/HTMLCollection.h" 49 #include "platform/Timer.h"
134 #include "core/html/HTMLFormElement.h"
135 #include "core/html/HTMLFrameOwnerElement.h"
136 #include "core/html/HTMLHeadElement.h"
137 #include "core/html/HTMLInputElement.h"
138 #include "core/html/HTMLLinkElement.h"
139 #include "core/html/PluginDocument.h"
140 #include "core/inspector/InspectorController.h"
141 #include "core/inspector/ScriptCallStack.h"
142 #include "core/loader/DocumentLoader.h"
143 #include "core/loader/FormState.h"
144 #include "core/loader/FrameLoadRequest.h"
145 #include "core/loader/FrameLoader.h"
146 #include "core/loader/HistoryItem.h"
147 #include "core/loader/SubstituteData.h"
148 #include "core/page/Chrome.h"
149 #include "core/page/EventHandler.h"
150 #include "core/page/FocusController.h"
151 #include "core/page/FrameTree.h"
152 #include "core/page/Page.h"
153 #include "core/page/PrintContext.h"
154 #include "core/frame/Settings.h"
155 #include "core/rendering/HitTestResult.h"
156 #include "core/rendering/RenderBox.h"
157 #include "core/rendering/RenderFrame.h"
158 #include "core/rendering/RenderLayer.h"
159 #include "core/rendering/RenderObject.h"
160 #include "core/rendering/RenderTreeAsText.h"
161 #include "core/rendering/RenderView.h"
162 #include "core/rendering/style/StyleInheritedData.h"
163 #include "core/timing/Performance.h"
164 #include "core/xml/DocumentXPathEvaluator.h"
165 #include "core/xml/XPathResult.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/network/ResourceRequest.h"
174 #include "platform/scroll/ScrollbarTheme.h"
175 #include "platform/scroll/ScrollTypes.h"
176 #include "platform/weborigin/KURL.h"
177 #include "platform/weborigin/SchemeRegistry.h"
178 #include "platform/weborigin/SecurityPolicy.h"
179 #include "public/platform/Platform.h"
180 #include "public/platform/WebFloatPoint.h"
181 #include "public/platform/WebFloatRect.h"
182 #include "public/platform/WebLayer.h"
183 #include "public/platform/WebPoint.h"
184 #include "public/platform/WebRect.h"
185 #include "public/platform/WebSize.h"
186 #include "public/platform/WebURLError.h"
187 #include "public/platform/WebVector.h" 50 #include "public/platform/WebVector.h"
188 #include "wtf/CurrentTime.h" 51 #include "wtf/CurrentTime.h"
189 #include "wtf/HashMap.h"
190 52
191 using namespace WebCore; 53 using namespace WebCore;
192 54
193 namespace blink { 55 namespace blink {
194 56
195 static int frameCount = 0; 57 TextFinder::FindMatch::FindMatch(PassRefPtr<Range> range, int ordinal)
196
197 // Key for a StatsCounter tracking how many WebFrames are active.
198 static const char webFrameActiveCount[] = "WebFrameActiveCount";
199
200 static void frameContentAsPlainText(size_t maxChars, LocalFrame* frame, StringBu ilder& output)
201 {
202 Document* document = frame->document();
203 if (!document)
204 return;
205
206 if (!frame->view())
207 return;
208
209 // TextIterator iterates over the visual representation of the DOM. As such,
210 // it requires you to do a layout before using it (otherwise it'll crash).
211 document->updateLayout();
212
213 // Select the document body.
214 RefPtr<Range> range(document->createRange());
215 TrackExceptionState exceptionState;
216 range->selectNodeContents(document->body(), exceptionState);
217
218 if (!exceptionState.hadException()) {
219 // The text iterator will walk nodes giving us text. This is similar to
220 // the plainText() function in core/editing/TextIterator.h, but we imple ment the maximum
221 // size and also copy the results directly into a wstring, avoiding the
222 // string conversion.
223 for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
224 it.appendTextToStringBuilder(output, 0, maxChars - output.length());
225 if (output.length() >= maxChars)
226 return; // Filled up the buffer.
227 }
228 }
229
230 // The separator between frames when the frames are converted to plain text.
231 const LChar frameSeparator[] = { '\n', '\n' };
232 const size_t frameSeparatorLength = WTF_ARRAY_LENGTH(frameSeparator);
233
234 // Recursively walk the children.
235 const FrameTree& frameTree = frame->tree();
236 for (LocalFrame* curChild = frameTree.firstChild(); curChild; curChild = cur Child->tree().nextSibling()) {
237 // Ignore the text of non-visible frames.
238 RenderView* contentRenderer = curChild->contentRenderer();
239 RenderPart* ownerRenderer = curChild->ownerRenderer();
240 if (!contentRenderer || !contentRenderer->width() || !contentRenderer->h eight()
241 || (contentRenderer->x() + contentRenderer->width() <= 0) || (conten tRenderer->y() + contentRenderer->height() <= 0)
242 || (ownerRenderer && ownerRenderer->style() && ownerRenderer->style( )->visibility() != VISIBLE)) {
243 continue;
244 }
245
246 // Make sure the frame separator won't fill up the buffer, and give up i f
247 // it will. The danger is if the separator will make the buffer longer t han
248 // maxChars. This will cause the computation above:
249 // maxChars - output->size()
250 // to be a negative number which will crash when the subframe is added.
251 if (output.length() >= maxChars - frameSeparatorLength)
252 return;
253
254 output.append(frameSeparator, frameSeparatorLength);
255 frameContentAsPlainText(maxChars, curChild, output);
256 if (output.length() >= maxChars)
257 return; // Filled up the buffer.
258 }
259 }
260
261 WebPluginContainerImpl* WebFrameImpl::pluginContainerFromFrame(LocalFrame* frame )
262 {
263 if (!frame)
264 return 0;
265 if (!frame->document() || !frame->document()->isPluginDocument())
266 return 0;
267 PluginDocument* pluginDocument = toPluginDocument(frame->document());
268 return toWebPluginContainerImpl(pluginDocument->pluginWidget());
269 }
270
271 WebPluginContainerImpl* WebFrameImpl::pluginContainerFromNode(WebCore::LocalFram e* frame, const WebNode& node)
272 {
273 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame);
274 if (pluginContainer)
275 return pluginContainer;
276 return toWebPluginContainerImpl(node.pluginContainer());
277 }
278
279 // Simple class to override some of PrintContext behavior. Some of the methods
280 // made virtual so that they can be overridden by ChromePluginPrintContext.
281 class ChromePrintContext : public PrintContext {
282 WTF_MAKE_NONCOPYABLE(ChromePrintContext);
283 public:
284 ChromePrintContext(LocalFrame* frame)
285 : PrintContext(frame)
286 , m_printedPageWidth(0)
287 {
288 }
289
290 virtual ~ChromePrintContext() { }
291
292 virtual void begin(float width, float height)
293 {
294 ASSERT(!m_printedPageWidth);
295 m_printedPageWidth = width;
296 PrintContext::begin(m_printedPageWidth, height);
297 }
298
299 virtual void end()
300 {
301 PrintContext::end();
302 }
303
304 virtual float getPageShrink(int pageNumber) const
305 {
306 IntRect pageRect = m_pageRects[pageNumber];
307 return m_printedPageWidth / pageRect.width();
308 }
309
310 // Spools the printed page, a subrect of frame(). Skip the scale step.
311 // NativeTheme doesn't play well with scaling. Scaling is done browser side
312 // instead. Returns the scale to be applied.
313 // On Linux, we don't have the problem with NativeTheme, hence we let WebKit
314 // do the scaling and ignore the return value.
315 virtual float spoolPage(GraphicsContext& context, int pageNumber)
316 {
317 IntRect pageRect = m_pageRects[pageNumber];
318 float scale = m_printedPageWidth / pageRect.width();
319
320 context.save();
321 #if OS(POSIX) && !OS(MACOSX)
322 context.scale(WebCore::FloatSize(scale, scale));
323 #endif
324 context.translate(static_cast<float>(-pageRect.x()), static_cast<float>( -pageRect.y()));
325 context.clip(pageRect);
326 frame()->view()->paintContents(&context, pageRect);
327 if (context.supportsURLFragments())
328 outputLinkedDestinations(context, frame()->document(), pageRect);
329 context.restore();
330 return scale;
331 }
332
333 void spoolAllPagesWithBoundaries(GraphicsContext& graphicsContext, const Flo atSize& pageSizeInPixels)
334 {
335 if (!frame()->document() || !frame()->view() || !frame()->document()->re nderer())
336 return;
337
338 frame()->document()->updateLayout();
339
340 float pageHeight;
341 computePageRects(FloatRect(FloatPoint(0, 0), pageSizeInPixels), 0, 0, 1, pageHeight);
342
343 const float pageWidth = pageSizeInPixels.width();
344 size_t numPages = pageRects().size();
345 int totalHeight = numPages * (pageSizeInPixels.height() + 1) - 1;
346
347 // Fill the whole background by white.
348 graphicsContext.setFillColor(Color::white);
349 graphicsContext.fillRect(FloatRect(0, 0, pageWidth, totalHeight));
350
351 int currentHeight = 0;
352 for (size_t pageIndex = 0; pageIndex < numPages; pageIndex++) {
353 // Draw a line for a page boundary if this isn't the first page.
354 if (pageIndex > 0) {
355 graphicsContext.save();
356 graphicsContext.setStrokeColor(Color(0, 0, 255));
357 graphicsContext.setFillColor(Color(0, 0, 255));
358 graphicsContext.drawLine(IntPoint(0, currentHeight), IntPoint(pa geWidth, currentHeight));
359 graphicsContext.restore();
360 }
361
362 graphicsContext.save();
363
364 graphicsContext.translate(0, currentHeight);
365 #if OS(WIN) || OS(MACOSX)
366 // Account for the disabling of scaling in spoolPage. In the context
367 // of spoolAllPagesWithBoundaries the scale HAS NOT been pre-applied .
368 float scale = getPageShrink(pageIndex);
369 graphicsContext.scale(WebCore::FloatSize(scale, scale));
370 #endif
371 spoolPage(graphicsContext, pageIndex);
372 graphicsContext.restore();
373
374 currentHeight += pageSizeInPixels.height() + 1;
375 }
376 }
377
378 virtual void computePageRects(const FloatRect& printRect, float headerHeight , float footerHeight, float userScaleFactor, float& outPageHeight)
379 {
380 PrintContext::computePageRects(printRect, headerHeight, footerHeight, us erScaleFactor, outPageHeight);
381 }
382
383 virtual int pageCount() const
384 {
385 return PrintContext::pageCount();
386 }
387
388 private:
389 // Set when printing.
390 float m_printedPageWidth;
391 };
392
393 // Simple class to override some of PrintContext behavior. This is used when
394 // the frame hosts a plugin that supports custom printing. In this case, we
395 // want to delegate all printing related calls to the plugin.
396 class ChromePluginPrintContext : public ChromePrintContext {
397 public:
398 ChromePluginPrintContext(LocalFrame* frame, WebPluginContainerImpl* plugin, const WebPrintParams& printParams)
399 : ChromePrintContext(frame), m_plugin(plugin), m_pageCount(0), m_printPa rams(printParams)
400 {
401 }
402
403 virtual ~ChromePluginPrintContext() { }
404
405 virtual void begin(float width, float height)
406 {
407 }
408
409 virtual void end()
410 {
411 m_plugin->printEnd();
412 }
413
414 virtual float getPageShrink(int pageNumber) const
415 {
416 // We don't shrink the page (maybe we should ask the widget ??)
417 return 1.0;
418 }
419
420 virtual void computePageRects(const FloatRect& printRect, float headerHeight , float footerHeight, float userScaleFactor, float& outPageHeight)
421 {
422 m_printParams.printContentArea = IntRect(printRect);
423 m_pageCount = m_plugin->printBegin(m_printParams);
424 }
425
426 virtual int pageCount() const
427 {
428 return m_pageCount;
429 }
430
431 // Spools the printed page, a subrect of frame(). Skip the scale step.
432 // NativeTheme doesn't play well with scaling. Scaling is done browser side
433 // instead. Returns the scale to be applied.
434 virtual float spoolPage(GraphicsContext& context, int pageNumber)
435 {
436 m_plugin->printPage(pageNumber, &context);
437 return 1.0;
438 }
439
440 private:
441 // Set when printing.
442 WebPluginContainerImpl* m_plugin;
443 int m_pageCount;
444 WebPrintParams m_printParams;
445
446 };
447
448 static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader)
449 {
450 return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0;
451 }
452
453 WebFrameImpl::FindMatch::FindMatch(PassRefPtr<Range> range, int ordinal)
454 : m_range(range) 58 : m_range(range)
455 , m_ordinal(ordinal) 59 , m_ordinal(ordinal)
456 { 60 {
457 } 61 }
458 62
459 class WebFrameImpl::DeferredScopeStringMatches { 63 class TextFinder::DeferredScopeStringMatches {
460 public: 64 public:
461 DeferredScopeStringMatches(WebFrameImpl* webFrame, int identifier, const Web String& searchText, const WebFindOptions& options, bool reset) 65 DeferredScopeStringMatches(TextFinder* textFinder, int identifier, const Web String& searchText, const WebFindOptions& options, bool reset)
462 : m_timer(this, &DeferredScopeStringMatches::doTimeout) 66 : m_timer(this, &DeferredScopeStringMatches::doTimeout)
463 , m_webFrame(webFrame) 67 , m_textFinder(textFinder)
464 , m_identifier(identifier) 68 , m_identifier(identifier)
465 , m_searchText(searchText) 69 , m_searchText(searchText)
466 , m_options(options) 70 , m_options(options)
467 , m_reset(reset) 71 , m_reset(reset)
468 { 72 {
469 m_timer.startOneShot(0.0); 73 m_timer.startOneShot(0.0, FROM_HERE);
470 } 74 }
471 75
472 private: 76 private:
473 void doTimeout(Timer<DeferredScopeStringMatches>*) 77 void doTimeout(Timer<DeferredScopeStringMatches>*)
474 { 78 {
475 m_webFrame->callScopeStringMatches(this, m_identifier, m_searchText, m_o ptions, m_reset); 79 m_textFinder->callScopeStringMatches(this, m_identifier, m_searchText, m _options, m_reset);
476 } 80 }
477 81
478 Timer<DeferredScopeStringMatches> m_timer; 82 Timer<DeferredScopeStringMatches> m_timer;
479 RefPtr<WebFrameImpl> m_webFrame; 83 TextFinder* m_textFinder;
480 int m_identifier; 84 const int m_identifier;
481 WebString m_searchText; 85 const WebString m_searchText;
482 WebFindOptions m_options; 86 const WebFindOptions m_options;
483 bool m_reset; 87 const bool m_reset;
484 }; 88 };
485 89
486 // WebFrame ------------------------------------------------------------------- 90 bool TextFinder::find(int identifier, const WebString& searchText, const WebFind Options& options, bool wrapWithinFrame, WebRect* selectionRect)
487
488 int WebFrame::instanceCount()
489 { 91 {
490 return frameCount; 92 if (!m_ownerFrame.frame() || !m_ownerFrame.frame()->page())
491 }
492
493 WebFrame* WebFrame::frameForCurrentContext()
494 {
495 v8::Handle<v8::Context> context = v8::Isolate::GetCurrent()->GetCurrentConte xt();
496 if (context.IsEmpty())
497 return 0;
498 return frameForContext(context);
499 }
500
501 WebFrame* WebFrame::frameForContext(v8::Handle<v8::Context> context)
502 {
503 return WebFrameImpl::fromFrame(toFrameIfNotDetached(context));
504 }
505
506 WebFrame* WebFrame::fromFrameOwnerElement(const WebElement& element)
507 {
508 return WebFrameImpl::fromFrameOwnerElement(PassRefPtr<Element>(element).get( ));
509 }
510
511 void WebFrameImpl::close()
512 {
513 m_client = 0;
514 deref(); // Balances ref() acquired in WebFrame::create
515 }
516
517 WebString WebFrameImpl::uniqueName() const
518 {
519 return frame()->tree().uniqueName();
520 }
521
522 WebString WebFrameImpl::assignedName() const
523 {
524 return frame()->tree().name();
525 }
526
527 void WebFrameImpl::setName(const WebString& name)
528 {
529 frame()->tree().setName(name);
530 }
531
532 WebVector<WebIconURL> WebFrameImpl::iconURLs(int iconTypesMask) const
533 {
534 // The URL to the icon may be in the header. As such, only
535 // ask the loader for the icon if it's finished loading.
536 if (frame()->loader().state() == FrameStateComplete)
537 return frame()->document()->iconURLs(iconTypesMask);
538 return WebVector<WebIconURL>();
539 }
540
541 void WebFrameImpl::setIsRemote(bool isRemote)
542 {
543 m_isRemote = isRemote;
544 if (isRemote)
545 client()->initializeChildFrame(frame()->view()->frameRect(), frame()->vi ew()->visibleContentScaleFactor());
546 }
547
548 void WebFrameImpl::setRemoteWebLayer(WebLayer* webLayer)
549 {
550 if (!frame())
551 return;
552
553 if (frame()->remotePlatformLayer())
554 GraphicsLayer::unregisterContentsLayer(frame()->remotePlatformLayer());
555 if (webLayer)
556 GraphicsLayer::registerContentsLayer(webLayer);
557 frame()->setRemotePlatformLayer(webLayer);
558 frame()->ownerElement()->setNeedsStyleRecalc(WebCore::SubtreeStyleChange, We bCore::StyleChangeFromRenderer);
559 }
560
561 void WebFrameImpl::setPermissionClient(WebPermissionClient* permissionClient)
562 {
563 m_permissionClient = permissionClient;
564 }
565
566 void WebFrameImpl::setSharedWorkerRepositoryClient(WebSharedWorkerRepositoryClie nt* client)
567 {
568 m_sharedWorkerRepositoryClient = SharedWorkerRepositoryClientImpl::create(cl ient);
569 }
570
571 WebSize WebFrameImpl::scrollOffset() const
572 {
573 FrameView* view = frameView();
574 if (!view)
575 return WebSize();
576 return view->scrollOffset();
577 }
578
579 WebSize WebFrameImpl::minimumScrollOffset() const
580 {
581 FrameView* view = frameView();
582 if (!view)
583 return WebSize();
584 return toIntSize(view->minimumScrollPosition());
585 }
586
587 WebSize WebFrameImpl::maximumScrollOffset() const
588 {
589 FrameView* view = frameView();
590 if (!view)
591 return WebSize();
592 return toIntSize(view->maximumScrollPosition());
593 }
594
595 void WebFrameImpl::setScrollOffset(const WebSize& offset)
596 {
597 if (FrameView* view = frameView())
598 view->setScrollOffset(IntPoint(offset.width, offset.height));
599 }
600
601 WebSize WebFrameImpl::contentsSize() const
602 {
603 return frame()->view()->contentsSize();
604 }
605
606 bool WebFrameImpl::hasVisibleContent() const
607 {
608 return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight () > 0;
609 }
610
611 WebRect WebFrameImpl::visibleContentRect() const
612 {
613 return frame()->view()->visibleContentRect();
614 }
615
616 bool WebFrameImpl::hasHorizontalScrollbar() const
617 {
618 return frame() && frame()->view() && frame()->view()->horizontalScrollbar();
619 }
620
621 bool WebFrameImpl::hasVerticalScrollbar() const
622 {
623 return frame() && frame()->view() && frame()->view()->verticalScrollbar();
624 }
625
626 WebView* WebFrameImpl::view() const
627 {
628 return viewImpl();
629 }
630
631 WebFrame* WebFrameImpl::opener() const
632 {
633 return m_opener;
634 }
635
636 void WebFrameImpl::setOpener(WebFrame* opener)
637 {
638 WebFrameImpl* openerImpl = toWebFrameImpl(opener);
639 if (m_opener && !openerImpl && m_client)
640 m_client->didDisownOpener(this);
641
642 if (m_opener)
643 m_opener->m_openedFrames.remove(this);
644 if (openerImpl)
645 openerImpl->m_openedFrames.add(this);
646 m_opener = openerImpl;
647
648 ASSERT(m_frame);
649 if (m_frame && m_frame->document())
650 m_frame->document()->initSecurityContext();
651 }
652
653 void WebFrameImpl::appendChild(WebFrame* child)
654 {
655 // FIXME: Original code asserts that the frames have the same Page. We
656 // should add an equivalent check... figure out what.
657 WebFrameImpl* childImpl = toWebFrameImpl(child);
658 childImpl->m_parent = this;
659 WebFrameImpl* oldLast = m_lastChild;
660 m_lastChild = childImpl;
661
662 if (oldLast) {
663 childImpl->m_previousSibling = oldLast;
664 oldLast->m_nextSibling = childImpl;
665 } else {
666 m_firstChild = childImpl;
667 }
668 // FIXME: Not sure if this is a legitimate assert.
669 ASSERT(frame());
670 frame()->tree().invalidateScopedChildCount();
671 }
672
673 void WebFrameImpl::removeChild(WebFrame* child)
674 {
675 WebFrameImpl* childImpl = toWebFrameImpl(child);
676 childImpl->m_parent = 0;
677
678 if (m_firstChild == childImpl)
679 m_firstChild = childImpl->m_nextSibling;
680 else
681 childImpl->m_previousSibling->m_nextSibling = childImpl->m_nextSibling;
682
683 if (m_lastChild == childImpl)
684 m_lastChild = childImpl->m_previousSibling;
685 else
686 childImpl->m_nextSibling->m_previousSibling = childImpl->m_previousSibli ng;
687
688 childImpl->m_previousSibling = childImpl->m_nextSibling = 0;
689 // FIXME: Not sure if this is a legitimate assert.
690 ASSERT(frame());
691 frame()->tree().invalidateScopedChildCount();
692 }
693
694 WebFrame* WebFrameImpl::parent() const
695 {
696 return m_parent;
697 }
698
699 WebFrame* WebFrameImpl::top() const
700 {
701 WebFrameImpl* frame = const_cast<WebFrameImpl*>(this);
702 for (WebFrameImpl* parent = frame; parent; parent = parent->m_parent)
703 frame = parent;
704 return frame;
705 }
706
707 WebFrame* WebFrameImpl::previousSibling() const
708 {
709 return m_previousSibling;
710 }
711
712 WebFrame* WebFrameImpl::nextSibling() const
713 {
714 return m_nextSibling;
715 }
716
717 WebFrame* WebFrameImpl::firstChild() const
718 {
719 return m_firstChild;
720 }
721
722 WebFrame* WebFrameImpl::lastChild() const
723 {
724 return m_lastChild;
725 }
726
727 WebFrame* WebFrameImpl::traversePrevious(bool wrap) const
728 {
729 if (!frame())
730 return 0;
731 return fromFrame(frame()->tree().traversePreviousWithWrap(wrap));
732 }
733
734 WebFrame* WebFrameImpl::traverseNext(bool wrap) const
735 {
736 if (!frame())
737 return 0;
738 return fromFrame(frame()->tree().traverseNextWithWrap(wrap));
739 }
740
741 WebFrame* WebFrameImpl::findChildByName(const WebString& name) const
742 {
743 if (!frame())
744 return 0;
745 return fromFrame(frame()->tree().child(name));
746 }
747
748 WebFrame* WebFrameImpl::findChildByExpression(const WebString& xpath) const
749 {
750 if (xpath.isEmpty())
751 return 0;
752
753 Document* document = frame()->document();
754 ASSERT(document);
755
756 RefPtrWillBeRawPtr<XPathResult> xpathResult = DocumentXPathEvaluator::evalua te(*document, xpath, document, nullptr, XPathResult::ORDERED_NODE_ITERATOR_TYPE, 0, IGNORE_EXCEPTION);
757 if (!xpathResult)
758 return 0;
759
760 Node* node = xpathResult->iterateNext(IGNORE_EXCEPTION);
761 if (!node || !node->isFrameOwnerElement())
762 return 0;
763 return fromFrame(toHTMLFrameOwnerElement(node)->contentFrame());
764 }
765
766 WebDocument WebFrameImpl::document() const
767 {
768 if (!frame() || !frame()->document())
769 return WebDocument();
770 return WebDocument(frame()->document());
771 }
772
773 WebPerformance WebFrameImpl::performance() const
774 {
775 if (!frame())
776 return WebPerformance();
777 return WebPerformance(&frame()->domWindow()->performance());
778 }
779
780 NPObject* WebFrameImpl::windowObject() const
781 {
782 if (!frame())
783 return 0;
784 return frame()->script().windowScriptNPObject();
785 }
786
787 void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object)
788 {
789 bindToWindowObject(name, object, 0);
790 }
791
792 void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object, v oid*)
793 {
794 if (!frame() || !frame()->script().canExecuteScripts(NotAboutToExecuteScript ))
795 return;
796 frame()->script().bindToWindowObject(frame(), String(name), object);
797 }
798
799 void WebFrameImpl::executeScript(const WebScriptSource& source)
800 {
801 ASSERT(frame());
802 TextPosition position(OrdinalNumber::fromOneBasedInt(source.startLine), Ordi nalNumber::first());
803 frame()->script().executeScriptInMainWorld(ScriptSourceCode(source.code, sou rce.url, position));
804 }
805
806 void WebFrameImpl::executeScriptInIsolatedWorld(int worldID, const WebScriptSour ce* sourcesIn, unsigned numSources, int extensionGroup)
807 {
808 ASSERT(frame());
809 RELEASE_ASSERT(worldID > 0);
810 RELEASE_ASSERT(worldID < EmbedderWorldIdLimit);
811
812 Vector<ScriptSourceCode> sources;
813 for (unsigned i = 0; i < numSources; ++i) {
814 TextPosition position(OrdinalNumber::fromOneBasedInt(sourcesIn[i].startL ine), OrdinalNumber::first());
815 sources.append(ScriptSourceCode(sourcesIn[i].code, sourcesIn[i].url, pos ition));
816 }
817
818 frame()->script().executeScriptInIsolatedWorld(worldID, sources, extensionGr oup, 0);
819 }
820
821 void WebFrameImpl::setIsolatedWorldSecurityOrigin(int worldID, const WebSecurity Origin& securityOrigin)
822 {
823 ASSERT(frame());
824 DOMWrapperWorld::setIsolatedWorldSecurityOrigin(worldID, securityOrigin.get( ));
825 }
826
827 void WebFrameImpl::setIsolatedWorldContentSecurityPolicy(int worldID, const WebS tring& policy)
828 {
829 ASSERT(frame());
830 DOMWrapperWorld::setIsolatedWorldContentSecurityPolicy(worldID, policy);
831 }
832
833 void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message)
834 {
835 ASSERT(frame());
836
837 MessageLevel webCoreMessageLevel;
838 switch (message.level) {
839 case WebConsoleMessage::LevelDebug:
840 webCoreMessageLevel = DebugMessageLevel;
841 break;
842 case WebConsoleMessage::LevelLog:
843 webCoreMessageLevel = LogMessageLevel;
844 break;
845 case WebConsoleMessage::LevelWarning:
846 webCoreMessageLevel = WarningMessageLevel;
847 break;
848 case WebConsoleMessage::LevelError:
849 webCoreMessageLevel = ErrorMessageLevel;
850 break;
851 default:
852 ASSERT_NOT_REACHED();
853 return;
854 }
855
856 frame()->document()->addConsoleMessage(OtherMessageSource, webCoreMessageLev el, message.text);
857 }
858
859 void WebFrameImpl::collectGarbage()
860 {
861 if (!frame())
862 return;
863 if (!frame()->settings()->scriptEnabled())
864 return;
865 V8GCController::collectGarbage(v8::Isolate::GetCurrent());
866 }
867
868 bool WebFrameImpl::checkIfRunInsecureContent(const WebURL& url) const
869 {
870 ASSERT(frame());
871 return frame()->loader().mixedContentChecker()->canRunInsecureContent(frame( )->document()->securityOrigin(), url);
872 }
873
874 v8::Handle<v8::Value> WebFrameImpl::executeScriptAndReturnValue(const WebScriptS ource& source)
875 {
876 ASSERT(frame());
877
878 // FIXME: This fake user gesture is required to make a bunch of pyauto
879 // tests pass. If this isn't needed in non-test situations, we should
880 // consider removing this code and changing the tests.
881 // http://code.google.com/p/chromium/issues/detail?id=86397
882 UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
883
884 TextPosition position(OrdinalNumber::fromOneBasedInt(source.startLine), Ordi nalNumber::first());
885 return frame()->script().executeScriptInMainWorldAndReturnValue(ScriptSource Code(source.code, source.url, position)).v8Value();
886 }
887
888 void WebFrameImpl::executeScriptInIsolatedWorld(int worldID, const WebScriptSour ce* sourcesIn, unsigned numSources, int extensionGroup, WebVector<v8::Local<v8:: Value> >* results)
889 {
890 ASSERT(frame());
891 RELEASE_ASSERT(worldID > 0);
892 RELEASE_ASSERT(worldID < EmbedderWorldIdLimit);
893
894 Vector<ScriptSourceCode> sources;
895
896 for (unsigned i = 0; i < numSources; ++i) {
897 TextPosition position(OrdinalNumber::fromOneBasedInt(sourcesIn[i].startL ine), OrdinalNumber::first());
898 sources.append(ScriptSourceCode(sourcesIn[i].code, sourcesIn[i].url, pos ition));
899 }
900
901 if (results) {
902 Vector<ScriptValue> scriptResults;
903 frame()->script().executeScriptInIsolatedWorld(worldID, sources, extensi onGroup, &scriptResults);
904 WebVector<v8::Local<v8::Value> > v8Results(scriptResults.size());
905 for (unsigned i = 0; i < scriptResults.size(); i++)
906 v8Results[i] = v8::Local<v8::Value>::New(toIsolate(frame()), scriptR esults[i].v8Value());
907 results->swap(v8Results);
908 } else {
909 frame()->script().executeScriptInIsolatedWorld(worldID, sources, extensi onGroup, 0);
910 }
911 }
912
913 v8::Handle<v8::Value> WebFrameImpl::callFunctionEvenIfScriptDisabled(v8::Handle< v8::Function> function, v8::Handle<v8::Value> receiver, int argc, v8::Handle<v8: :Value> argv[])
914 {
915 ASSERT(frame());
916 return frame()->script().callFunction(function, receiver, argc, argv);
917 }
918
919 v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const
920 {
921 return toV8Context(V8PerIsolateData::mainThreadIsolate(), frame(), DOMWrappe rWorld::mainWorld());
922 }
923
924 void WebFrameImpl::reload(bool ignoreCache)
925 {
926 ASSERT(frame());
927 frame()->loader().reload(ignoreCache ? EndToEndReload : NormalReload);
928 }
929
930 void WebFrameImpl::reloadWithOverrideURL(const WebURL& overrideUrl, bool ignoreC ache)
931 {
932 ASSERT(frame());
933 frame()->loader().reload(ignoreCache ? EndToEndReload : NormalReload, overri deUrl);
934 }
935
936 void WebFrameImpl::loadRequest(const WebURLRequest& request)
937 {
938 ASSERT(frame());
939 ASSERT(!request.isNull());
940 const ResourceRequest& resourceRequest = request.toResourceRequest();
941
942 if (resourceRequest.url().protocolIs("javascript")) {
943 loadJavaScriptURL(resourceRequest.url());
944 return;
945 }
946
947 frame()->loader().load(FrameLoadRequest(0, resourceRequest));
948 }
949
950 void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item, WebURLRequest::Ca chePolicy cachePolicy)
951 {
952 ASSERT(frame());
953 RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item);
954 ASSERT(historyItem);
955 frame()->page()->historyController().goToItem(historyItem.get(), static_cast <ResourceRequestCachePolicy>(cachePolicy));
956 }
957
958 void WebFrameImpl::loadData(const WebData& data, const WebString& mimeType, cons t WebString& textEncoding, const WebURL& baseURL, const WebURL& unreachableURL, bool replace)
959 {
960 ASSERT(frame());
961
962 // If we are loading substitute data to replace an existing load, then
963 // inherit all of the properties of that original request. This way,
964 // reload will re-attempt the original request. It is essential that
965 // we only do this when there is an unreachableURL since a non-empty
966 // unreachableURL informs FrameLoader::reload to load unreachableURL
967 // instead of the currently loaded URL.
968 ResourceRequest request;
969 if (replace && !unreachableURL.isEmpty() && frame()->loader().provisionalDoc umentLoader())
970 request = frame()->loader().provisionalDocumentLoader()->originalRequest ();
971 request.setURL(baseURL);
972
973 FrameLoadRequest frameRequest(0, request, SubstituteData(data, mimeType, tex tEncoding, unreachableURL));
974 ASSERT(frameRequest.substituteData().isValid());
975 frameRequest.setLockBackForwardList(replace);
976 frame()->loader().load(frameRequest);
977 }
978
979 void WebFrameImpl::loadHTMLString(const WebData& data, const WebURL& baseURL, co nst WebURL& unreachableURL, bool replace)
980 {
981 ASSERT(frame());
982 loadData(data, WebString::fromUTF8("text/html"), WebString::fromUTF8("UTF-8" ), baseURL, unreachableURL, replace);
983 }
984
985 bool WebFrameImpl::isLoading() const
986 {
987 if (!frame())
988 return false;
989 return frame()->loader().isLoading();
990 }
991
992 void WebFrameImpl::stopLoading()
993 {
994 if (!frame())
995 return;
996 // FIXME: Figure out what we should really do here. It seems like a bug
997 // that FrameLoader::stopLoading doesn't call stopAllLoaders.
998 frame()->loader().stopAllLoaders();
999 }
1000
1001 WebDataSource* WebFrameImpl::provisionalDataSource() const
1002 {
1003 ASSERT(frame());
1004
1005 // We regard the policy document loader as still provisional.
1006 DocumentLoader* documentLoader = frame()->loader().provisionalDocumentLoader ();
1007 if (!documentLoader)
1008 documentLoader = frame()->loader().policyDocumentLoader();
1009
1010 return DataSourceForDocLoader(documentLoader);
1011 }
1012
1013 WebDataSource* WebFrameImpl::dataSource() const
1014 {
1015 ASSERT(frame());
1016 return DataSourceForDocLoader(frame()->loader().documentLoader());
1017 }
1018
1019 WebHistoryItem WebFrameImpl::previousHistoryItem() const
1020 {
1021 ASSERT(frame());
1022 // We use the previous item here because documentState (filled-out forms)
1023 // only get saved to history when it becomes the previous item. The caller
1024 // is expected to query the history item after a navigation occurs, after
1025 // the desired history item has become the previous entry.
1026 return WebHistoryItem(frame()->page()->historyController().previousItemForEx port());
1027 }
1028
1029 WebHistoryItem WebFrameImpl::currentHistoryItem() const
1030 {
1031 ASSERT(frame());
1032
1033 // We're shutting down.
1034 if (!frame()->loader().documentLoader())
1035 return WebHistoryItem();
1036
1037 // Lazily update the document state if it was dirtied. Doing it here
1038 // avoids synchronously serializing forms as they're changing.
1039 frame()->loader().saveDocumentState();
1040
1041 return WebHistoryItem(frame()->page()->historyController().currentItemForExp ort());
1042 }
1043
1044 void WebFrameImpl::enableViewSourceMode(bool enable)
1045 {
1046 if (frame())
1047 frame()->setInViewSourceMode(enable);
1048 }
1049
1050 bool WebFrameImpl::isViewSourceModeEnabled() const
1051 {
1052 if (!frame())
1053 return false;
1054 return frame()->inViewSourceMode();
1055 }
1056
1057 void WebFrameImpl::setReferrerForRequest(WebURLRequest& request, const WebURL& r eferrerURL)
1058 {
1059 String referrer = referrerURL.isEmpty() ? frame()->document()->outgoingRefer rer() : String(referrerURL.spec().utf16());
1060 referrer = SecurityPolicy::generateReferrerHeader(frame()->document()->refer rerPolicy(), request.url(), referrer);
1061 if (referrer.isEmpty())
1062 return;
1063 request.setHTTPReferrer(referrer, static_cast<WebReferrerPolicy>(frame()->do cument()->referrerPolicy()));
1064 }
1065
1066 void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request)
1067 {
1068 ResourceResponse response;
1069 frame()->loader().client()->dispatchWillSendRequest(0, 0, request.toMutableR esourceRequest(), response);
1070 }
1071
1072 WebURLLoader* WebFrameImpl::createAssociatedURLLoader(const WebURLLoaderOptions& options)
1073 {
1074 return new AssociatedURLLoader(this, options);
1075 }
1076
1077 unsigned WebFrameImpl::unloadListenerCount() const
1078 {
1079 return frame()->domWindow()->pendingUnloadEventListeners();
1080 }
1081
1082 void WebFrameImpl::replaceSelection(const WebString& text)
1083 {
1084 bool selectReplacement = false;
1085 bool smartReplace = true;
1086 frame()->editor().replaceSelectionWithText(text, selectReplacement, smartRep lace);
1087 }
1088
1089 void WebFrameImpl::insertText(const WebString& text)
1090 {
1091 if (frame()->inputMethodController().hasComposition())
1092 frame()->inputMethodController().confirmComposition(text);
1093 else
1094 frame()->editor().insertText(text, 0);
1095 }
1096
1097 void WebFrameImpl::setMarkedText(const WebString& text, unsigned location, unsig ned length)
1098 {
1099 Vector<CompositionUnderline> decorations;
1100 frame()->inputMethodController().setComposition(text, decorations, location, length);
1101 }
1102
1103 void WebFrameImpl::unmarkText()
1104 {
1105 frame()->inputMethodController().cancelComposition();
1106 }
1107
1108 bool WebFrameImpl::hasMarkedText() const
1109 {
1110 return frame()->inputMethodController().hasComposition();
1111 }
1112
1113 WebRange WebFrameImpl::markedRange() const
1114 {
1115 return frame()->inputMethodController().compositionRange();
1116 }
1117
1118 bool WebFrameImpl::firstRectForCharacterRange(unsigned location, unsigned length , WebRect& rect) const
1119 {
1120 if ((location + length < location) && (location + length))
1121 length = 0;
1122
1123 Element* editable = frame()->selection().rootEditableElementOrDocumentElemen t();
1124 ASSERT(editable);
1125 RefPtr<Range> range = PlainTextRange(location, location + length).createRang e(*editable);
1126 if (!range)
1127 return false;
1128 IntRect intRect = frame()->editor().firstRectForRange(range.get());
1129 rect = WebRect(intRect);
1130 rect = frame()->view()->contentsToWindow(rect);
1131 return true;
1132 }
1133
1134 size_t WebFrameImpl::characterIndexForPoint(const WebPoint& webPoint) const
1135 {
1136 if (!frame())
1137 return kNotFound;
1138
1139 IntPoint point = frame()->view()->windowToContents(webPoint);
1140 HitTestResult result = frame()->eventHandler().hitTestResultAtPoint(point, H itTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndO ftenMisusedDisallowShadowContent);
1141 RefPtr<Range> range = frame()->rangeForPoint(result.roundedPointInInnerNodeF rame());
1142 if (!range)
1143 return kNotFound;
1144 Element* editable = frame()->selection().rootEditableElementOrDocumentElemen t();
1145 ASSERT(editable);
1146 return PlainTextRange::create(*editable, *range.get()).start();
1147 }
1148
1149 bool WebFrameImpl::executeCommand(const WebString& name, const WebNode& node)
1150 {
1151 ASSERT(frame());
1152
1153 if (name.length() <= 2)
1154 return false; 93 return false;
1155 94
1156 // Since we don't have NSControl, we will convert the format of command 95 WebFrameImpl* mainFrameImpl = m_ownerFrame.viewImpl()->mainFrameImpl();
1157 // string and call the function on Editor directly.
1158 String command = name;
1159
1160 // Make sure the first letter is upper case.
1161 command.replace(0, 1, command.substring(0, 1).upper());
1162
1163 // Remove the trailing ':' if existing.
1164 if (command[command.length() - 1] == UChar(':'))
1165 command = command.substring(0, command.length() - 1);
1166
1167 WebPluginContainerImpl* pluginContainer = pluginContainerFromNode(frame(), n ode);
1168 if (pluginContainer && pluginContainer->executeEditCommand(name))
1169 return true;
1170
1171 bool result = true;
1172
1173 // Specially handling commands that Editor::execCommand does not directly
1174 // support.
1175 if (command == "DeleteToEndOfParagraph") {
1176 if (!frame()->editor().deleteWithDirection(DirectionForward, ParagraphBo undary, true, false))
1177 frame()->editor().deleteWithDirection(DirectionForward, CharacterGra nularity, true, false);
1178 } else if (command == "Indent") {
1179 frame()->editor().indent();
1180 } else if (command == "Outdent") {
1181 frame()->editor().outdent();
1182 } else if (command == "DeleteBackward") {
1183 result = frame()->editor().command(AtomicString("BackwardDelete")).execu te();
1184 } else if (command == "DeleteForward") {
1185 result = frame()->editor().command(AtomicString("ForwardDelete")).execut e();
1186 } else if (command == "AdvanceToNextMisspelling") {
1187 // Wee need to pass false here or else the currently selected word will never be skipped.
1188 frame()->spellChecker().advanceToNextMisspelling(false);
1189 } else if (command == "ToggleSpellPanel") {
1190 frame()->spellChecker().showSpellingGuessPanel();
1191 } else {
1192 result = frame()->editor().command(command).execute();
1193 }
1194 return result;
1195 }
1196
1197 bool WebFrameImpl::executeCommand(const WebString& name, const WebString& value, const WebNode& node)
1198 {
1199 ASSERT(frame());
1200 String webName = name;
1201
1202 WebPluginContainerImpl* pluginContainer = pluginContainerFromNode(frame(), n ode);
1203 if (pluginContainer && pluginContainer->executeEditCommand(name, value))
1204 return true;
1205
1206 // moveToBeginningOfDocument and moveToEndfDocument are only handled by WebK it for editable nodes.
1207 if (!frame()->editor().canEdit() && webName == "moveToBeginningOfDocument")
1208 return viewImpl()->bubblingScroll(ScrollUp, ScrollByDocument);
1209
1210 if (!frame()->editor().canEdit() && webName == "moveToEndOfDocument")
1211 return viewImpl()->bubblingScroll(ScrollDown, ScrollByDocument);
1212
1213 if (webName == "showGuessPanel") {
1214 frame()->spellChecker().showSpellingGuessPanel();
1215 return true;
1216 }
1217
1218 return frame()->editor().command(webName).execute(value);
1219 }
1220
1221 bool WebFrameImpl::isCommandEnabled(const WebString& name) const
1222 {
1223 ASSERT(frame());
1224 return frame()->editor().command(name).isEnabled();
1225 }
1226
1227 void WebFrameImpl::enableContinuousSpellChecking(bool enable)
1228 {
1229 if (enable == isContinuousSpellCheckingEnabled())
1230 return;
1231 frame()->spellChecker().toggleContinuousSpellChecking();
1232 }
1233
1234 bool WebFrameImpl::isContinuousSpellCheckingEnabled() const
1235 {
1236 return frame()->spellChecker().isContinuousSpellCheckingEnabled();
1237 }
1238
1239 void WebFrameImpl::requestTextChecking(const WebElement& webElement)
1240 {
1241 if (webElement.isNull())
1242 return;
1243 frame()->spellChecker().requestTextChecking(*webElement.constUnwrap<Element> ());
1244 }
1245
1246 void WebFrameImpl::replaceMisspelledRange(const WebString& text)
1247 {
1248 // 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.
1249 if (pluginContainerFromFrame(frame()))
1250 return;
1251 RefPtr<Range> caretRange = frame()->selection().toNormalizedRange();
1252 if (!caretRange)
1253 return;
1254 Vector<DocumentMarker*> markers = frame()->document()->markers().markersInRa nge(caretRange.get(), DocumentMarker::MisspellingMarkers());
1255 if (markers.size() < 1 || markers[0]->startOffset() >= markers[0]->endOffset ())
1256 return;
1257 RefPtr<Range> markerRange = Range::create(caretRange->ownerDocument(), caret Range->startContainer(), markers[0]->startOffset(), caretRange->endContainer(), markers[0]->endOffset());
1258 if (!markerRange)
1259 return;
1260 frame()->selection().setSelection(markerRange.get(), CharacterGranularity);
1261 frame()->editor().replaceSelectionWithText(text, false, false);
1262 }
1263
1264 void WebFrameImpl::removeSpellingMarkers()
1265 {
1266 frame()->document()->markers().removeMarkers(DocumentMarker::MisspellingMark ers());
1267 }
1268
1269 bool WebFrameImpl::hasSelection() const
1270 {
1271 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1272 if (pluginContainer)
1273 return pluginContainer->plugin()->hasSelection();
1274
1275 // frame()->selection()->isNone() never returns true.
1276 return frame()->selection().start() != frame()->selection().end();
1277 }
1278
1279 WebRange WebFrameImpl::selectionRange() const
1280 {
1281 return frame()->selection().toNormalizedRange();
1282 }
1283
1284 WebString WebFrameImpl::selectionAsText() const
1285 {
1286 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1287 if (pluginContainer)
1288 return pluginContainer->plugin()->selectionAsText();
1289
1290 RefPtr<Range> range = frame()->selection().toNormalizedRange();
1291 if (!range)
1292 return WebString();
1293
1294 String text = range->text();
1295 #if OS(WIN)
1296 replaceNewlinesWithWindowsStyleNewlines(text);
1297 #endif
1298 replaceNBSPWithSpace(text);
1299 return text;
1300 }
1301
1302 WebString WebFrameImpl::selectionAsMarkup() const
1303 {
1304 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1305 if (pluginContainer)
1306 return pluginContainer->plugin()->selectionAsMarkup();
1307
1308 RefPtr<Range> range = frame()->selection().toNormalizedRange();
1309 if (!range)
1310 return WebString();
1311
1312 return createMarkup(range.get(), 0, AnnotateForInterchange, false, ResolveNo nLocalURLs);
1313 }
1314
1315 void WebFrameImpl::selectWordAroundPosition(LocalFrame* frame, VisiblePosition p osition)
1316 {
1317 VisibleSelection selection(position);
1318 selection.expandUsingGranularity(WordGranularity);
1319
1320 TextGranularity granularity = selection.isRange() ? WordGranularity : Charac terGranularity;
1321 frame->selection().setSelection(selection, granularity);
1322 }
1323
1324 bool WebFrameImpl::selectWordAroundCaret()
1325 {
1326 FrameSelection& selection = frame()->selection();
1327 ASSERT(!selection.isNone());
1328 if (selection.isNone() || selection.isRange())
1329 return false;
1330 selectWordAroundPosition(frame(), selection.selection().visibleStart());
1331 return true;
1332 }
1333
1334 void WebFrameImpl::selectRange(const WebPoint& base, const WebPoint& extent)
1335 {
1336 moveRangeSelection(base, extent);
1337 }
1338
1339 void WebFrameImpl::selectRange(const WebRange& webRange)
1340 {
1341 if (RefPtr<Range> range = static_cast<PassRefPtr<Range> >(webRange))
1342 frame()->selection().setSelectedRange(range.get(), WebCore::VP_DEFAULT_A FFINITY, false);
1343 }
1344
1345 void WebFrameImpl::moveRangeSelection(const WebPoint& base, const WebPoint& exte nt)
1346 {
1347 VisiblePosition basePosition = visiblePositionForWindowPoint(base);
1348 VisiblePosition extentPosition = visiblePositionForWindowPoint(extent);
1349 VisibleSelection newSelection = VisibleSelection(basePosition, extentPositio n);
1350 frame()->selection().setSelection(newSelection, CharacterGranularity);
1351 }
1352
1353 void WebFrameImpl::moveCaretSelection(const WebPoint& point)
1354 {
1355 Element* editable = frame()->selection().rootEditableElement();
1356 if (!editable)
1357 return;
1358
1359 VisiblePosition position = visiblePositionForWindowPoint(point);
1360 frame()->selection().moveTo(position, UserTriggered);
1361 }
1362
1363 void WebFrameImpl::setCaretVisible(bool visible)
1364 {
1365 frame()->selection().setCaretVisible(visible);
1366 }
1367
1368 VisiblePosition WebFrameImpl::visiblePositionForWindowPoint(const WebPoint& poin t)
1369 {
1370 FloatPoint unscaledPoint(point);
1371 unscaledPoint.scale(1 / view()->pageScaleFactor(), 1 / view()->pageScaleFact or());
1372
1373 HitTestRequest request = HitTestRequest::Move | HitTestRequest::ReadOnly | H itTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::Confusi ngAndOftenMisusedDisallowShadowContent;
1374 HitTestResult result(frame()->view()->windowToContents(roundedIntPoint(unsca ledPoint)));
1375 frame()->document()->renderView()->layer()->hitTest(request, result);
1376
1377 if (Node* node = result.targetNode())
1378 return frame()->selection().selection().visiblePositionRespectingEditing Boundary(result.localPoint(), node);
1379 return VisiblePosition();
1380 }
1381
1382 int WebFrameImpl::printBegin(const WebPrintParams& printParams, const WebNode& c onstrainToNode)
1383 {
1384 ASSERT(!frame()->document()->isFrameSet());
1385 WebPluginContainerImpl* pluginContainer = 0;
1386 if (constrainToNode.isNull()) {
1387 // If this is a plugin document, check if the plugin supports its own
1388 // printing. If it does, we will delegate all printing to that.
1389 pluginContainer = pluginContainerFromFrame(frame());
1390 } else {
1391 // We only support printing plugin nodes for now.
1392 pluginContainer = toWebPluginContainerImpl(constrainToNode.pluginContain er());
1393 }
1394
1395 if (pluginContainer && pluginContainer->supportsPaginatedPrint())
1396 m_printContext = adoptPtr(new ChromePluginPrintContext(frame(), pluginCo ntainer, printParams));
1397 else
1398 m_printContext = adoptPtr(new ChromePrintContext(frame()));
1399
1400 FloatRect rect(0, 0, static_cast<float>(printParams.printContentArea.width), static_cast<float>(printParams.printContentArea.height));
1401 m_printContext->begin(rect.width(), rect.height());
1402 float pageHeight;
1403 // We ignore the overlays calculation for now since they are generated in th e
1404 // browser. pageHeight is actually an output parameter.
1405 m_printContext->computePageRects(rect, 0, 0, 1.0, pageHeight);
1406
1407 return m_printContext->pageCount();
1408 }
1409
1410 float WebFrameImpl::getPrintPageShrink(int page)
1411 {
1412 ASSERT(m_printContext && page >= 0);
1413 return m_printContext->getPageShrink(page);
1414 }
1415
1416 float WebFrameImpl::printPage(int page, WebCanvas* canvas)
1417 {
1418 #if ENABLE(PRINTING)
1419 ASSERT(m_printContext && page >= 0 && frame() && frame()->document());
1420
1421 GraphicsContext graphicsContext(canvas);
1422 graphicsContext.setPrinting(true);
1423 return m_printContext->spoolPage(graphicsContext, page);
1424 #else
1425 return 0;
1426 #endif
1427 }
1428
1429 void WebFrameImpl::printEnd()
1430 {
1431 ASSERT(m_printContext);
1432 m_printContext->end();
1433 m_printContext.clear();
1434 }
1435
1436 bool WebFrameImpl::isPrintScalingDisabledForPlugin(const WebNode& node)
1437 {
1438 WebPluginContainerImpl* pluginContainer = node.isNull() ? pluginContainerFr omFrame(frame()) : toWebPluginContainerImpl(node.pluginContainer());
1439
1440 if (!pluginContainer || !pluginContainer->supportsPaginatedPrint())
1441 return false;
1442
1443 return pluginContainer->isPrintScalingDisabled();
1444 }
1445
1446 bool WebFrameImpl::hasCustomPageSizeStyle(int pageIndex)
1447 {
1448 return frame()->document()->styleForPage(pageIndex)->pageSizeType() != PAGE_ SIZE_AUTO;
1449 }
1450
1451 bool WebFrameImpl::isPageBoxVisible(int pageIndex)
1452 {
1453 return frame()->document()->isPageBoxVisible(pageIndex);
1454 }
1455
1456 void WebFrameImpl::pageSizeAndMarginsInPixels(int pageIndex, WebSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1457 {
1458 IntSize size = pageSize;
1459 frame()->document()->pageSizeAndMarginsInPixels(pageIndex, size, marginTop, marginRight, marginBottom, marginLeft);
1460 pageSize = size;
1461 }
1462
1463 WebString WebFrameImpl::pageProperty(const WebString& propertyName, int pageInde x)
1464 {
1465 ASSERT(m_printContext);
1466 return m_printContext->pageProperty(frame(), propertyName.utf8().data(), pag eIndex);
1467 }
1468
1469 bool WebFrameImpl::find(int identifier, const WebString& searchText, const WebFi ndOptions& options, bool wrapWithinFrame, WebRect* selectionRect)
1470 {
1471 if (!frame() || !frame()->page())
1472 return false;
1473
1474 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1475 96
1476 if (!options.findNext) 97 if (!options.findNext)
1477 frame()->page()->unmarkAllTextMatches(); 98 m_ownerFrame.frame()->page()->unmarkAllTextMatches();
1478 else 99 else
1479 setMarkerActive(m_activeMatch.get(), false); 100 setMarkerActive(m_activeMatch.get(), false);
1480 101
1481 if (m_activeMatch && &m_activeMatch->ownerDocument() != frame()->document()) 102 if (m_activeMatch && &m_activeMatch->ownerDocument() != m_ownerFrame.frame() ->document())
1482 m_activeMatch = nullptr; 103 m_activeMatch = nullptr;
1483 104
1484 // If the user has selected something since the last Find operation we want 105 // If the user has selected something since the last Find operation we want
1485 // to start from there. Otherwise, we start searching from where the last Fi nd 106 // to start from there. Otherwise, we start searching from where the last Fi nd
1486 // operation left off (either a Find or a FindNext operation). 107 // operation left off (either a Find or a FindNext operation).
1487 VisibleSelection selection(frame()->selection().selection()); 108 VisibleSelection selection(m_ownerFrame.frame()->selection().selection());
1488 bool activeSelection = !selection.isNone(); 109 bool activeSelection = !selection.isNone();
1489 if (activeSelection) { 110 if (activeSelection) {
1490 m_activeMatch = selection.firstRange().get(); 111 m_activeMatch = selection.firstRange().get();
1491 frame()->selection().clear(); 112 m_ownerFrame.frame()->selection().clear();
1492 } 113 }
1493 114
1494 ASSERT(frame() && frame()->view()); 115 ASSERT(m_ownerFrame.frame() && m_ownerFrame.frame()->view());
1495 const FindOptions findOptions = (options.forward ? 0 : Backwards) 116 const FindOptions findOptions = (options.forward ? 0 : Backwards)
1496 | (options.matchCase ? 0 : CaseInsensitive) 117 | (options.matchCase ? 0 : CaseInsensitive)
1497 | (wrapWithinFrame ? WrapAround : 0) 118 | (wrapWithinFrame ? WrapAround : 0)
1498 | (options.wordStart ? AtWordStarts : 0) 119 | (options.wordStart ? AtWordStarts : 0)
1499 | (options.medialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0) 120 | (options.medialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
1500 | (options.findNext ? 0 : StartInSelection); 121 | (options.findNext ? 0 : StartInSelection);
1501 m_activeMatch = frame()->editor().findStringAndScrollToVisible(searchText, m _activeMatch.get(), findOptions); 122 m_activeMatch = m_ownerFrame.frame()->editor().findStringAndScrollToVisible( searchText, m_activeMatch.get(), findOptions);
1502 123
1503 if (!m_activeMatch) { 124 if (!m_activeMatch) {
1504 // If we're finding next the next active match might not be in the curre nt frame. 125 // If we're finding next the next active match might not be in the curre nt frame.
1505 // In this case we don't want to clear the matches cache. 126 // In this case we don't want to clear the matches cache.
1506 if (!options.findNext) 127 if (!options.findNext)
1507 clearFindMatchesCache(); 128 clearFindMatchesCache();
129
1508 invalidateArea(InvalidateAll); 130 invalidateArea(InvalidateAll);
1509 return false; 131 return false;
1510 } 132 }
1511 133
1512 #if OS(ANDROID) 134 #if OS(ANDROID)
1513 viewImpl()->zoomToFindInPageRect(frameView()->contentsToWindow(enclosingIntR ect(RenderObject::absoluteBoundingBoxRectForRange(m_activeMatch.get())))); 135 m_ownerFrame.viewImpl()->zoomToFindInPageRect(m_ownerFrame.frameView()->cont entsToWindow(enclosingIntRect(RenderObject::absoluteBoundingBoxRectForRange(m_ac tiveMatch.get()))));
1514 #endif 136 #endif
1515 137
1516 setMarkerActive(m_activeMatch.get(), true); 138 setMarkerActive(m_activeMatch.get(), true);
1517 WebFrameImpl* oldActiveFrame = mainFrameImpl->m_currentActiveMatchFrame; 139 WebFrameImpl* oldActiveFrame = mainFrameImpl->getOrCreateTextFinder().m_curr entActiveMatchFrame;
1518 mainFrameImpl->m_currentActiveMatchFrame = this; 140 mainFrameImpl->getOrCreateTextFinder().m_currentActiveMatchFrame = &m_ownerF rame;
1519 141
1520 // Make sure no node is focused. See http://crbug.com/38700. 142 // Make sure no node is focused. See http://crbug.com/38700.
1521 frame()->document()->setFocusedElement(nullptr); 143 m_ownerFrame.frame()->document()->setFocusedElement(nullptr);
1522 144
1523 if (!options.findNext || activeSelection) { 145 if (!options.findNext || activeSelection) {
1524 // This is either a Find operation or a Find-next from a new start point 146 // This is either a Find operation or a Find-next from a new start point
1525 // due to a selection, so we set the flag to ask the scoping effort 147 // due to a selection, so we set the flag to ask the scoping effort
1526 // to find the active rect for us and report it back to the UI. 148 // to find the active rect for us and report it back to the UI.
1527 m_locatingActiveRect = true; 149 m_locatingActiveRect = true;
1528 } else { 150 } else {
1529 if (oldActiveFrame != this) { 151 if (oldActiveFrame != &m_ownerFrame) {
1530 if (options.forward) 152 if (options.forward)
1531 m_activeMatchIndexInCurrentFrame = 0; 153 m_activeMatchIndexInCurrentFrame = 0;
1532 else 154 else
1533 m_activeMatchIndexInCurrentFrame = m_lastMatchCount - 1; 155 m_activeMatchIndexInCurrentFrame = m_lastMatchCount - 1;
1534 } else { 156 } else {
1535 if (options.forward) 157 if (options.forward)
1536 ++m_activeMatchIndexInCurrentFrame; 158 ++m_activeMatchIndexInCurrentFrame;
1537 else 159 else
1538 --m_activeMatchIndexInCurrentFrame; 160 --m_activeMatchIndexInCurrentFrame;
1539 161
1540 if (m_activeMatchIndexInCurrentFrame + 1 > m_lastMatchCount) 162 if (m_activeMatchIndexInCurrentFrame + 1 > m_lastMatchCount)
1541 m_activeMatchIndexInCurrentFrame = 0; 163 m_activeMatchIndexInCurrentFrame = 0;
1542 if (m_activeMatchIndexInCurrentFrame == -1) 164 if (m_activeMatchIndexInCurrentFrame == -1)
1543 m_activeMatchIndexInCurrentFrame = m_lastMatchCount - 1; 165 m_activeMatchIndexInCurrentFrame = m_lastMatchCount - 1;
1544 } 166 }
1545 if (selectionRect) { 167 if (selectionRect) {
1546 *selectionRect = frameView()->contentsToWindow(m_activeMatch->boundi ngBox()); 168 *selectionRect = m_ownerFrame.frameView()->contentsToWindow(m_active Match->boundingBox());
1547 reportFindInPageSelection(*selectionRect, m_activeMatchIndexInCurren tFrame + 1, identifier); 169 reportFindInPageSelection(*selectionRect, m_activeMatchIndexInCurren tFrame + 1, identifier);
1548 } 170 }
1549 } 171 }
1550 172
1551 return true; 173 return true;
1552 } 174 }
1553 175
1554 void WebFrameImpl::stopFinding(bool clearSelection) 176 void TextFinder::stopFindingAndClearSelection()
1555 { 177 {
1556 if (!clearSelection)
1557 setFindEndstateFocusAndSelection();
1558 cancelPendingScopingEffort(); 178 cancelPendingScopingEffort();
1559 179
1560 // Remove all markers for matches found and turn off the highlighting. 180 // Remove all markers for matches found and turn off the highlighting.
1561 frame()->document()->markers().removeMarkers(DocumentMarker::TextMatch); 181 m_ownerFrame.frame()->document()->markers().removeMarkers(DocumentMarker::Te xtMatch);
1562 frame()->editor().setMarkedTextMatchesAreHighlighted(false); 182 m_ownerFrame.frame()->editor().setMarkedTextMatchesAreHighlighted(false);
1563 clearFindMatchesCache(); 183 clearFindMatchesCache();
1564 184
1565 // Let the frame know that we don't want tickmarks or highlighting anymore. 185 // Let the frame know that we don't want tickmarks or highlighting anymore.
1566 invalidateArea(InvalidateAll); 186 invalidateArea(InvalidateAll);
1567 } 187 }
1568 188
1569 void WebFrameImpl::scopeStringMatches(int identifier, const WebString& searchTex t, const WebFindOptions& options, bool reset) 189 void TextFinder::scopeStringMatches(int identifier, const WebString& searchText, const WebFindOptions& options, bool reset)
1570 { 190 {
1571 if (reset) { 191 if (reset) {
1572 // This is a brand new search, so we need to reset everything. 192 // This is a brand new search, so we need to reset everything.
1573 // Scoping is just about to begin. 193 // Scoping is just about to begin.
1574 m_scopingInProgress = true; 194 m_scopingInProgress = true;
1575 195
1576 // Need to keep the current identifier locally in order to finish the 196 // Need to keep the current identifier locally in order to finish the
1577 // request in case the frame is detached during the process. 197 // request in case the frame is detached during the process.
1578 m_findRequestIdentifier = identifier; 198 m_findRequestIdentifier = identifier;
1579 199
1580 // Clear highlighting for this frame. 200 // Clear highlighting for this frame.
1581 if (frame() && frame()->page() && frame()->editor().markedTextMatchesAre Highlighted()) 201 LocalFrame* frame = m_ownerFrame.frame();
1582 frame()->page()->unmarkAllTextMatches(); 202 if (frame && frame->page() && frame->editor().markedTextMatchesAreHighli ghted())
203 frame->page()->unmarkAllTextMatches();
1583 204
1584 // Clear the tickmarks and results cache. 205 // Clear the tickmarks and results cache.
1585 clearFindMatchesCache(); 206 clearFindMatchesCache();
1586 207
1587 // Clear the counters from last operation. 208 // Clear the counters from last operation.
1588 m_lastMatchCount = 0; 209 m_lastMatchCount = 0;
1589 m_nextInvalidateAfter = 0; 210 m_nextInvalidateAfter = 0;
1590
1591 m_resumeScopingFromRange = nullptr; 211 m_resumeScopingFromRange = nullptr;
1592 212
1593 // The view might be null on detached frames. 213 // The view might be null on detached frames.
1594 if (frame() && frame()->page()) 214 if (frame && frame->page())
1595 viewImpl()->mainFrameImpl()->m_framesScopingCount++; 215 m_ownerFrame.viewImpl()->mainFrameImpl()->getOrCreateTextFinder().m_ framesScopingCount++;
1596 216
1597 // Now, defer scoping until later to allow find operation to finish quic kly. 217 // Now, defer scoping until later to allow find operation to finish quic kly.
1598 scopeStringMatchesSoon(identifier, searchText, options, false); // false means just reset, so don't do it again. 218 scopeStringMatchesSoon(identifier, searchText, options, false); // false means just reset, so don't do it again.
1599 return; 219 return;
1600 } 220 }
1601 221
1602 if (!shouldScopeMatches(searchText)) { 222 if (!shouldScopeMatches(searchText)) {
1603 // Note that we want to defer the final update when resetting even if sh ouldScopeMatches returns false. 223 // Note that we want to defer the final update when resetting even if sh ouldScopeMatches returns false.
1604 // This is done in order to prevent sending a final message based only o n the results of the first frame 224 // This is done in order to prevent sending a final message based only o n the results of the first frame
1605 // since m_framesScopingCount would be 0 as other frames have yet to res et. 225 // since m_framesScopingCount would be 0 as other frames have yet to res et.
1606 finishCurrentScopingEffort(identifier); 226 finishCurrentScopingEffort(identifier);
1607 return; 227 return;
1608 } 228 }
1609 229
1610 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl(); 230 WebFrameImpl* mainFrameImpl = m_ownerFrame.viewImpl()->mainFrameImpl();
1611 RefPtr<Range> searchRange(rangeOfContents(frame()->document())); 231 RefPtr<Range> searchRange(rangeOfContents(m_ownerFrame.frame()->document())) ;
1612 232
1613 Node* originalEndContainer = searchRange->endContainer(); 233 Node* originalEndContainer = searchRange->endContainer();
1614 int originalEndOffset = searchRange->endOffset(); 234 int originalEndOffset = searchRange->endOffset();
1615 235
1616 TrackExceptionState exceptionState, exceptionState2; 236 TrackExceptionState exceptionState, exceptionState2;
1617 if (m_resumeScopingFromRange) { 237 if (m_resumeScopingFromRange) {
1618 // This is a continuation of a scoping operation that timed out and didn 't 238 // This is a continuation of a scoping operation that timed out and didn 't
1619 // complete last time around, so we should start from where we left off. 239 // complete last time around, so we should start from where we left off.
1620 searchRange->setStart(m_resumeScopingFromRange->startContainer(), m_resu meScopingFromRange->startOffset(exceptionState2) + 1, exceptionState); 240 searchRange->setStart(m_resumeScopingFromRange->startContainer(), m_resu meScopingFromRange->startOffset(exceptionState2) + 1, exceptionState);
1621 if (exceptionState.hadException() || exceptionState2.hadException()) { 241 if (exceptionState.hadException() || exceptionState2.hadException()) {
1622 if (exceptionState2.hadException()) // A non-zero |exceptionState| h appens when navigating during search. 242 if (exceptionState2.hadException()) // A non-zero |exceptionState| h appens when navigating during search.
1623 ASSERT_NOT_REACHED(); 243 ASSERT_NOT_REACHED();
1624 return; 244 return;
1625 } 245 }
1626 } 246 }
1627 247
1628 // This timeout controls how long we scope before releasing control. This 248 // This timeout controls how long we scope before releasing control. This
1629 // value does not prevent us from running for longer than this, but it is 249 // value does not prevent us from running for longer than this, but it is
1630 // periodically checked to see if we have exceeded our allocated time. 250 // periodically checked to see if we have exceeded our allocated time.
1631 const double maxScopingDuration = 0.1; // seconds 251 const double maxScopingDuration = 0.1; // seconds
1632 252
1633 int matchCount = 0; 253 int matchCount = 0;
1634 bool timedOut = false; 254 bool timedOut = false;
1635 double startTime = currentTime(); 255 double startTime = currentTime();
1636 do { 256 do {
1637 // Find next occurrence of the search string. 257 // Find next occurrence of the search string.
1638 // FIXME: (http://b/1088245) This WebKit operation may run for longer 258 // FIXME: (http://b/1088245) This WebKit operation may run for longer
1639 // than the timeout value, and is not interruptible as it is currently 259 // than the timeout value, and is not interruptible as it is currently
1640 // written. We may need to rewrite it with interruptibility in mind, or 260 // written. We may need to rewrite it with interruptibility in mind, or
1641 // find an alternative. 261 // find an alternative.
1642 RefPtr<Range> resultRange(findPlainText(searchRange.get(), 262 RefPtr<Range> resultRange(findPlainText(
1643 searchText, 263 searchRange.get(), searchText, options.matchCase ? 0 : CaseInsensiti ve));
1644 options.matchCase ? 0 : CaseInse nsitive));
1645 if (resultRange->collapsed(exceptionState)) { 264 if (resultRange->collapsed(exceptionState)) {
1646 if (!resultRange->startContainer()->isInShadowTree()) 265 if (!resultRange->startContainer()->isInShadowTree())
1647 break; 266 break;
1648 267
1649 searchRange->setStartAfter( 268 searchRange->setStartAfter(
1650 resultRange->startContainer()->deprecatedShadowAncestorNode(), e xceptionState); 269 resultRange->startContainer()->deprecatedShadowAncestorNode(), e xceptionState);
1651 searchRange->setEnd(originalEndContainer, originalEndOffset, excepti onState); 270 searchRange->setEnd(originalEndContainer, originalEndOffset, excepti onState);
1652 continue; 271 continue;
1653 } 272 }
1654 273
1655 ++matchCount; 274 ++matchCount;
1656 275
1657 // Catch a special case where Find found something but doesn't know what 276 // Catch a special case where Find found something but doesn't know what
1658 // the bounding box for it is. In this case we set the first match we fi nd 277 // the bounding box for it is. In this case we set the first match we fi nd
1659 // as the active rect. 278 // as the active rect.
1660 IntRect resultBounds = resultRange->boundingBox(); 279 IntRect resultBounds = resultRange->boundingBox();
1661 IntRect activeSelectionRect; 280 IntRect activeSelectionRect;
1662 if (m_locatingActiveRect) { 281 if (m_locatingActiveRect) {
1663 activeSelectionRect = m_activeMatch.get() ? 282 activeSelectionRect = m_activeMatch.get() ?
1664 m_activeMatch->boundingBox() : resultBounds; 283 m_activeMatch->boundingBox() : resultBounds;
1665 } 284 }
1666 285
1667 // If the Find function found a match it will have stored where the 286 // If the Find function found a match it will have stored where the
1668 // match was found in m_activeSelectionRect on the current frame. If we 287 // match was found in m_activeSelectionRect on the current frame. If we
1669 // find this rect during scoping it means we have found the active 288 // find this rect during scoping it means we have found the active
1670 // tickmark. 289 // tickmark.
1671 bool foundActiveMatch = false; 290 bool foundActiveMatch = false;
1672 if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) { 291 if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) {
1673 // We have found the active tickmark frame. 292 // We have found the active tickmark frame.
1674 mainFrameImpl->m_currentActiveMatchFrame = this; 293 mainFrameImpl->getOrCreateTextFinder().m_currentActiveMatchFrame = & m_ownerFrame;
1675 foundActiveMatch = true; 294 foundActiveMatch = true;
1676 // We also know which tickmark is active now. 295 // We also know which tickmark is active now.
1677 m_activeMatchIndexInCurrentFrame = matchCount - 1; 296 m_activeMatchIndexInCurrentFrame = matchCount - 1;
1678 // To stop looking for the active tickmark, we set this flag. 297 // To stop looking for the active tickmark, we set this flag.
1679 m_locatingActiveRect = false; 298 m_locatingActiveRect = false;
1680 299
1681 // Notify browser of new location for the selected rectangle. 300 // Notify browser of new location for the selected rectangle.
1682 reportFindInPageSelection( 301 reportFindInPageSelection(
1683 frameView()->contentsToWindow(resultBounds), 302 m_ownerFrame.frameView()->contentsToWindow(resultBounds),
1684 m_activeMatchIndexInCurrentFrame + 1, 303 m_activeMatchIndexInCurrentFrame + 1,
1685 identifier); 304 identifier);
1686 } 305 }
1687 306
1688 addMarker(resultRange.get(), foundActiveMatch); 307 addMarker(resultRange.get(), foundActiveMatch);
1689 308
1690 m_findMatchesCache.append(FindMatch(resultRange.get(), m_lastMatchCount + matchCount)); 309 m_findMatchesCache.append(FindMatch(resultRange.get(), m_lastMatchCount + matchCount));
1691 310
1692 // Set the new start for the search range to be the end of the previous 311 // Set the new start for the search range to be the end of the previous
1693 // result range. There is no need to use a VisiblePosition here, 312 // result range. There is no need to use a VisiblePosition here,
1694 // since findPlainText will use a TextIterator to go over the visible 313 // since findPlainText will use a TextIterator to go over the visible
1695 // text nodes. 314 // text nodes.
1696 searchRange->setStart(resultRange->endContainer(exceptionState), resultR ange->endOffset(exceptionState), exceptionState); 315 searchRange->setStart(resultRange->endContainer(exceptionState), resultR ange->endOffset(exceptionState), exceptionState);
1697 316
1698 Node* shadowTreeRoot = searchRange->shadowRoot(); 317 Node* shadowTreeRoot = searchRange->shadowRoot();
1699 if (searchRange->collapsed(exceptionState) && shadowTreeRoot) 318 if (searchRange->collapsed(exceptionState) && shadowTreeRoot)
1700 searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->countChildren(), exceptionState); 319 searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->countChildren(), exceptionState);
1701 320
1702 m_resumeScopingFromRange = resultRange; 321 m_resumeScopingFromRange = resultRange;
1703 timedOut = (currentTime() - startTime) >= maxScopingDuration; 322 timedOut = (currentTime() - startTime) >= maxScopingDuration;
1704 } while (!timedOut); 323 } while (!timedOut);
1705 324
1706 // Remember what we search for last time, so we can skip searching if more 325 // Remember what we search for last time, so we can skip searching if more
1707 // letters are added to the search string (and last outcome was 0). 326 // letters are added to the search string (and last outcome was 0).
1708 m_lastSearchString = searchText; 327 m_lastSearchString = searchText;
1709 328
1710 if (matchCount > 0) { 329 if (matchCount > 0) {
1711 frame()->editor().setMarkedTextMatchesAreHighlighted(true); 330 m_ownerFrame.frame()->editor().setMarkedTextMatchesAreHighlighted(true);
1712 331
1713 m_lastMatchCount += matchCount; 332 m_lastMatchCount += matchCount;
1714 333
1715 // Let the mainframe know how much we found during this pass. 334 // Let the mainframe know how much we found during this pass.
1716 mainFrameImpl->increaseMatchCount(matchCount, identifier); 335 mainFrameImpl->increaseMatchCount(matchCount, identifier);
1717 } 336 }
1718 337
1719 if (timedOut) { 338 if (timedOut) {
1720 // If we found anything during this pass, we should redraw. However, we 339 // If we found anything during this pass, we should redraw. However, we
1721 // don't want to spam too much if the page is extremely long, so if we 340 // don't want to spam too much if the page is extremely long, so if we
1722 // reach a certain point we start throttling the redraw requests. 341 // reach a certain point we start throttling the redraw requests.
1723 if (matchCount > 0) 342 if (matchCount > 0)
1724 invalidateIfNecessary(); 343 invalidateIfNecessary();
1725 344
1726 // Scoping effort ran out of time, lets ask for another time-slice. 345 // Scoping effort ran out of time, lets ask for another time-slice.
1727 scopeStringMatchesSoon( 346 scopeStringMatchesSoon(
1728 identifier, 347 identifier,
1729 searchText, 348 searchText,
1730 options, 349 options,
1731 false); // don't reset. 350 false); // don't reset.
1732 return; // Done for now, resume work later. 351 return; // Done for now, resume work later.
1733 } 352 }
1734 353
1735 finishCurrentScopingEffort(identifier); 354 finishCurrentScopingEffort(identifier);
1736 } 355 }
1737 356
1738 void WebFrameImpl::flushCurrentScopingEffort(int identifier) 357 void TextFinder::flushCurrentScopingEffort(int identifier)
1739 { 358 {
1740 if (!frame() || !frame()->page()) 359 if (!m_ownerFrame.frame() || !m_ownerFrame.frame()->page())
1741 return; 360 return;
1742 361
1743 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl(); 362 WebFrameImpl* mainFrameImpl = m_ownerFrame.viewImpl()->mainFrameImpl();
1744 363 mainFrameImpl->getOrCreateTextFinder().decrementFramesScopingCount(identifie r);
1745 // This frame has no further scoping left, so it is done. Other frames might ,
1746 // of course, continue to scope matches.
1747 mainFrameImpl->m_framesScopingCount--;
1748
1749 // If this is the last frame to finish scoping we need to trigger the final
1750 // update to be sent.
1751 if (!mainFrameImpl->m_framesScopingCount)
1752 mainFrameImpl->increaseMatchCount(0, identifier);
1753 } 364 }
1754 365
1755 void WebFrameImpl::finishCurrentScopingEffort(int identifier) 366 void TextFinder::finishCurrentScopingEffort(int identifier)
1756 { 367 {
1757 flushCurrentScopingEffort(identifier); 368 flushCurrentScopingEffort(identifier);
1758 369
1759 m_scopingInProgress = false; 370 m_scopingInProgress = false;
1760 m_lastFindRequestCompletedWithNoMatches = !m_lastMatchCount; 371 m_lastFindRequestCompletedWithNoMatches = !m_lastMatchCount;
1761 372
1762 // This frame is done, so show any scrollbar tickmarks we haven't drawn yet. 373 // This frame is done, so show any scrollbar tickmarks we haven't drawn yet.
1763 invalidateArea(InvalidateScrollbar); 374 invalidateArea(InvalidateScrollbar);
1764 } 375 }
1765 376
1766 void WebFrameImpl::cancelPendingScopingEffort() 377 void TextFinder::cancelPendingScopingEffort()
1767 { 378 {
1768 deleteAllValues(m_deferredScopingWork); 379 deleteAllValues(m_deferredScopingWork);
1769 m_deferredScopingWork.clear(); 380 m_deferredScopingWork.clear();
1770 381
1771 m_activeMatchIndexInCurrentFrame = -1; 382 m_activeMatchIndexInCurrentFrame = -1;
1772 383
1773 // Last request didn't complete. 384 // Last request didn't complete.
1774 if (m_scopingInProgress) 385 if (m_scopingInProgress)
1775 m_lastFindRequestCompletedWithNoMatches = false; 386 m_lastFindRequestCompletedWithNoMatches = false;
1776 387
1777 m_scopingInProgress = false; 388 m_scopingInProgress = false;
1778 } 389 }
1779 390
1780 void WebFrameImpl::increaseMatchCount(int count, int identifier) 391 void TextFinder::increaseMatchCount(int identifier, int count)
1781 { 392 {
1782 // This function should only be called on the mainframe.
1783 ASSERT(!parent());
1784
1785 if (count) 393 if (count)
1786 ++m_findMatchMarkersVersion; 394 ++m_findMatchMarkersVersion;
1787 395
1788 m_totalMatchCount += count; 396 m_totalMatchCount += count;
1789 397
1790 // Update the UI with the latest findings. 398 // Update the UI with the latest findings.
1791 if (client()) 399 if (m_ownerFrame.client())
1792 client()->reportFindInPageMatchCount(identifier, m_totalMatchCount, !m_f ramesScopingCount); 400 m_ownerFrame.client()->reportFindInPageMatchCount(identifier, m_totalMat chCount, !m_framesScopingCount);
1793 } 401 }
1794 402
1795 void WebFrameImpl::reportFindInPageSelection(const WebRect& selectionRect, int a ctiveMatchOrdinal, int identifier) 403 void TextFinder::reportFindInPageSelection(const WebRect& selectionRect, int act iveMatchOrdinal, int identifier)
1796 { 404 {
1797 // Update the UI with the latest selection rect. 405 // Update the UI with the latest selection rect.
1798 if (client()) 406 if (m_ownerFrame.client())
1799 client()->reportFindInPageSelection(identifier, ordinalOfFirstMatchForFr ame(this) + activeMatchOrdinal, selectionRect); 407 m_ownerFrame.client()->reportFindInPageSelection(identifier, ordinalOfFi rstMatch() + activeMatchOrdinal, selectionRect);
1800 } 408 }
1801 409
1802 void WebFrameImpl::resetMatchCount() 410 void TextFinder::resetMatchCount()
1803 { 411 {
1804 if (m_totalMatchCount > 0) 412 if (m_totalMatchCount > 0)
1805 ++m_findMatchMarkersVersion; 413 ++m_findMatchMarkersVersion;
1806 414
1807 m_totalMatchCount = 0; 415 m_totalMatchCount = 0;
1808 m_framesScopingCount = 0; 416 m_framesScopingCount = 0;
1809 } 417 }
1810 418
1811 void WebFrameImpl::sendOrientationChangeEvent(int orientation) 419 void TextFinder::clearFindMatchesCache()
1812 {
1813 if (frame())
1814 frame()->sendOrientationChangeEvent(orientation);
1815 }
1816
1817 void WebFrameImpl::dispatchMessageEventWithOriginCheck(const WebSecurityOrigin& intendedTargetOrigin, const WebDOMEvent& event)
1818 {
1819 ASSERT(!event.isNull());
1820 frame()->domWindow()->dispatchMessageEventWithOriginCheck(intendedTargetOrig in.get(), event, nullptr);
1821 }
1822
1823 int WebFrameImpl::findMatchMarkersVersion() const
1824 {
1825 ASSERT(!parent());
1826 return m_findMatchMarkersVersion;
1827 }
1828
1829 void WebFrameImpl::clearFindMatchesCache()
1830 { 420 {
1831 if (!m_findMatchesCache.isEmpty()) 421 if (!m_findMatchesCache.isEmpty())
1832 viewImpl()->mainFrameImpl()->m_findMatchMarkersVersion++; 422 m_ownerFrame.viewImpl()->mainFrameImpl()->getOrCreateTextFinder().m_find MatchMarkersVersion++;
1833 423
1834 m_findMatchesCache.clear(); 424 m_findMatchesCache.clear();
1835 m_findMatchRectsAreValid = false; 425 m_findMatchRectsAreValid = false;
1836 } 426 }
1837 427
1838 bool WebFrameImpl::isActiveMatchFrameValid() const 428 bool TextFinder::isActiveMatchFrameValid() const
1839 { 429 {
1840 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl(); 430 WebFrameImpl* mainFrameImpl = m_ownerFrame.viewImpl()->mainFrameImpl();
1841 WebFrameImpl* activeMatchFrame = mainFrameImpl->activeMatchFrame(); 431 WebFrameImpl* activeMatchFrame = mainFrameImpl->activeMatchFrame();
1842 return activeMatchFrame && activeMatchFrame->m_activeMatch && activeMatchFra me->frame()->tree().isDescendantOf(mainFrameImpl->frame()); 432 return activeMatchFrame && activeMatchFrame->activeMatch() && activeMatchFra me->frame()->tree().isDescendantOf(mainFrameImpl->frame());
1843 } 433 }
1844 434
1845 void WebFrameImpl::updateFindMatchRects() 435 void TextFinder::updateFindMatchRects()
1846 { 436 {
1847 IntSize currentContentsSize = contentsSize(); 437 IntSize currentContentsSize = m_ownerFrame.contentsSize();
1848 if (m_contentsSizeForCurrentFindMatchRects != currentContentsSize) { 438 if (m_contentsSizeForCurrentFindMatchRects != currentContentsSize) {
1849 m_contentsSizeForCurrentFindMatchRects = currentContentsSize; 439 m_contentsSizeForCurrentFindMatchRects = currentContentsSize;
1850 m_findMatchRectsAreValid = false; 440 m_findMatchRectsAreValid = false;
1851 } 441 }
1852 442
1853 size_t deadMatches = 0; 443 size_t deadMatches = 0;
1854 for (Vector<FindMatch>::iterator it = m_findMatchesCache.begin(); it != m_fi ndMatchesCache.end(); ++it) { 444 for (Vector<FindMatch>::iterator it = m_findMatchesCache.begin(); it != m_fi ndMatchesCache.end(); ++it) {
1855 if (!it->m_range->boundaryPointsValid() || !it->m_range->startContainer( )->inDocument()) 445 if (!it->m_range->boundaryPointsValid() || !it->m_range->startContainer( )->inDocument())
1856 it->m_rect = FloatRect(); 446 it->m_rect = FloatRect();
1857 else if (!m_findMatchRectsAreValid) 447 else if (!m_findMatchRectsAreValid)
1858 it->m_rect = findInPageRectFromRange(it->m_range.get()); 448 it->m_rect = findInPageRectFromRange(it->m_range.get());
1859 449
1860 if (it->m_rect.isEmpty()) 450 if (it->m_rect.isEmpty())
1861 ++deadMatches; 451 ++deadMatches;
1862 } 452 }
1863 453
1864 // Remove any invalid matches from the cache. 454 // Remove any invalid matches from the cache.
1865 if (deadMatches) { 455 if (deadMatches) {
1866 Vector<FindMatch> filteredMatches; 456 Vector<FindMatch> filteredMatches;
1867 filteredMatches.reserveCapacity(m_findMatchesCache.size() - deadMatches) ; 457 filteredMatches.reserveCapacity(m_findMatchesCache.size() - deadMatches) ;
1868 458
1869 for (Vector<FindMatch>::const_iterator it = m_findMatchesCache.begin(); it != m_findMatchesCache.end(); ++it) 459 for (Vector<FindMatch>::const_iterator it = m_findMatchesCache.begin(); it != m_findMatchesCache.end(); ++it) {
1870 if (!it->m_rect.isEmpty()) 460 if (!it->m_rect.isEmpty())
1871 filteredMatches.append(*it); 461 filteredMatches.append(*it);
462 }
1872 463
1873 m_findMatchesCache.swap(filteredMatches); 464 m_findMatchesCache.swap(filteredMatches);
1874 } 465 }
1875 466
1876 // Invalidate the rects in child frames. Will be updated later during traver sal. 467 // Invalidate the rects in child frames. Will be updated later during traver sal.
1877 if (!m_findMatchRectsAreValid) 468 if (!m_findMatchRectsAreValid)
1878 for (WebFrame* child = firstChild(); child; child = child->nextSibling() ) 469 for (WebFrame* child = m_ownerFrame.firstChild(); child; child = child-> nextSibling())
1879 toWebFrameImpl(child)->m_findMatchRectsAreValid = false; 470 toWebFrameImpl(child)->getOrCreateTextFinder().m_findMatchRectsAreVa lid = false;
1880 471
1881 m_findMatchRectsAreValid = true; 472 m_findMatchRectsAreValid = true;
1882 } 473 }
1883 474
1884 WebFloatRect WebFrameImpl::activeFindMatchRect() 475 WebFloatRect TextFinder::activeFindMatchRect()
1885 { 476 {
1886 ASSERT(!parent());
1887
1888 if (!isActiveMatchFrameValid()) 477 if (!isActiveMatchFrameValid())
1889 return WebFloatRect(); 478 return WebFloatRect();
1890 479
1891 return WebFloatRect(findInPageRectFromRange(m_currentActiveMatchFrame->m_act iveMatch.get())); 480 return WebFloatRect(findInPageRectFromRange(m_currentActiveMatchFrame->activ eMatch()));
1892 } 481 }
1893 482
1894 void WebFrameImpl::findMatchRects(WebVector<WebFloatRect>& outputRects) 483 void TextFinder::findMatchRects(WebVector<WebFloatRect>& outputRects)
1895 { 484 {
1896 ASSERT(!parent());
1897
1898 Vector<WebFloatRect> matchRects; 485 Vector<WebFloatRect> matchRects;
1899 for (WebFrameImpl* frame = this; frame; frame = toWebFrameImpl(frame->traver seNext(false))) 486 for (WebFrameImpl* frame = &m_ownerFrame; frame; frame = toWebFrameImpl(fram e->traverseNext(false)))
1900 frame->appendFindMatchRects(matchRects); 487 frame->getOrCreateTextFinder().appendFindMatchRects(matchRects);
1901 488
1902 outputRects = matchRects; 489 outputRects = matchRects;
1903 } 490 }
1904 491
1905 void WebFrameImpl::appendFindMatchRects(Vector<WebFloatRect>& frameRects) 492 void TextFinder::appendFindMatchRects(Vector<WebFloatRect>& frameRects)
1906 { 493 {
1907 updateFindMatchRects(); 494 updateFindMatchRects();
1908 frameRects.reserveCapacity(frameRects.size() + m_findMatchesCache.size()); 495 frameRects.reserveCapacity(frameRects.size() + m_findMatchesCache.size());
1909 for (Vector<FindMatch>::const_iterator it = m_findMatchesCache.begin(); it ! = m_findMatchesCache.end(); ++it) { 496 for (Vector<FindMatch>::const_iterator it = m_findMatchesCache.begin(); it ! = m_findMatchesCache.end(); ++it) {
1910 ASSERT(!it->m_rect.isEmpty()); 497 ASSERT(!it->m_rect.isEmpty());
1911 frameRects.append(it->m_rect); 498 frameRects.append(it->m_rect);
1912 } 499 }
1913 } 500 }
1914 501
1915 int WebFrameImpl::selectNearestFindMatch(const WebFloatPoint& point, WebRect* se lectionRect) 502 int TextFinder::selectNearestFindMatch(const WebFloatPoint& point, WebRect* sele ctionRect)
1916 { 503 {
1917 ASSERT(!parent()); 504 TextFinder* bestFinder = 0;
1918
1919 WebFrameImpl* bestFrame = 0;
1920 int indexInBestFrame = -1; 505 int indexInBestFrame = -1;
1921 float distanceInBestFrame = FLT_MAX; 506 float distanceInBestFrame = FLT_MAX;
1922 507
1923 for (WebFrameImpl* frame = this; frame; frame = toWebFrameImpl(frame->traver seNext(false))) { 508 for (WebFrameImpl* frame = &m_ownerFrame; frame; frame = toWebFrameImpl(fram e->traverseNext(false))) {
1924 float distanceInFrame; 509 float distanceInFrame;
1925 int indexInFrame = frame->nearestFindMatch(point, distanceInFrame); 510 TextFinder& finder = frame->getOrCreateTextFinder();
511 int indexInFrame = finder.nearestFindMatch(point, distanceInFrame);
1926 if (distanceInFrame < distanceInBestFrame) { 512 if (distanceInFrame < distanceInBestFrame) {
1927 bestFrame = frame; 513 bestFinder = &finder;
1928 indexInBestFrame = indexInFrame; 514 indexInBestFrame = indexInFrame;
1929 distanceInBestFrame = distanceInFrame; 515 distanceInBestFrame = distanceInFrame;
1930 } 516 }
1931 } 517 }
1932 518
1933 if (indexInBestFrame != -1) 519 if (indexInBestFrame != -1)
1934 return bestFrame->selectFindMatch(static_cast<unsigned>(indexInBestFrame ), selectionRect); 520 return bestFinder->selectFindMatch(static_cast<unsigned>(indexInBestFram e), selectionRect);
1935 521
1936 return -1; 522 return -1;
1937 } 523 }
1938 524
1939 int WebFrameImpl::nearestFindMatch(const FloatPoint& point, float& distanceSquar ed) 525 int TextFinder::nearestFindMatch(const FloatPoint& point, float& distanceSquared )
1940 { 526 {
1941 updateFindMatchRects(); 527 updateFindMatchRects();
1942 528
1943 int nearest = -1; 529 int nearest = -1;
1944 distanceSquared = FLT_MAX; 530 distanceSquared = FLT_MAX;
1945 for (size_t i = 0; i < m_findMatchesCache.size(); ++i) { 531 for (size_t i = 0; i < m_findMatchesCache.size(); ++i) {
1946 ASSERT(!m_findMatchesCache[i].m_rect.isEmpty()); 532 ASSERT(!m_findMatchesCache[i].m_rect.isEmpty());
1947 FloatSize offset = point - m_findMatchesCache[i].m_rect.center(); 533 FloatSize offset = point - m_findMatchesCache[i].m_rect.center();
1948 float width = offset.width(); 534 float width = offset.width();
1949 float height = offset.height(); 535 float height = offset.height();
1950 float currentDistanceSquared = width * width + height * height; 536 float currentDistanceSquared = width * width + height * height;
1951 if (currentDistanceSquared < distanceSquared) { 537 if (currentDistanceSquared < distanceSquared) {
1952 nearest = i; 538 nearest = i;
1953 distanceSquared = currentDistanceSquared; 539 distanceSquared = currentDistanceSquared;
1954 } 540 }
1955 } 541 }
1956 return nearest; 542 return nearest;
1957 } 543 }
1958 544
1959 int WebFrameImpl::selectFindMatch(unsigned index, WebRect* selectionRect) 545 int TextFinder::selectFindMatch(unsigned index, WebRect* selectionRect)
1960 { 546 {
1961 ASSERT_WITH_SECURITY_IMPLICATION(index < m_findMatchesCache.size()); 547 ASSERT_WITH_SECURITY_IMPLICATION(index < m_findMatchesCache.size());
1962 548
1963 RefPtr<Range> range = m_findMatchesCache[index].m_range; 549 RefPtr<Range> range = m_findMatchesCache[index].m_range;
1964 if (!range->boundaryPointsValid() || !range->startContainer()->inDocument()) 550 if (!range->boundaryPointsValid() || !range->startContainer()->inDocument())
1965 return -1; 551 return -1;
1966 552
1967 // Check if the match is already selected. 553 // Check if the match is already selected.
1968 WebFrameImpl* activeMatchFrame = viewImpl()->mainFrameImpl()->m_currentActiv eMatchFrame; 554 TextFinder& mainFrameTextFinder = m_ownerFrame.viewImpl()->mainFrameImpl()-> getOrCreateTextFinder();
1969 if (this != activeMatchFrame || !m_activeMatch || !areRangesEqual(m_activeMa tch.get(), range.get())) { 555 WebFrameImpl* activeMatchFrame = mainFrameTextFinder.m_currentActiveMatchFra me;
556 if (&m_ownerFrame != activeMatchFrame || !m_activeMatch || !areRangesEqual(m _activeMatch.get(), range.get())) {
1970 if (isActiveMatchFrameValid()) 557 if (isActiveMatchFrameValid())
1971 activeMatchFrame->setMarkerActive(activeMatchFrame->m_activeMatch.ge t(), false); 558 activeMatchFrame->getOrCreateTextFinder().setMatchMarkerActive(false );
1972 559
1973 m_activeMatchIndexInCurrentFrame = m_findMatchesCache[index].m_ordinal - 1; 560 m_activeMatchIndexInCurrentFrame = m_findMatchesCache[index].m_ordinal - 1;
1974 561
1975 // Set this frame as the active frame (the one with the active highlight ). 562 // Set this frame as the active frame (the one with the active highlight ).
1976 viewImpl()->mainFrameImpl()->m_currentActiveMatchFrame = this; 563 mainFrameTextFinder.m_currentActiveMatchFrame = &m_ownerFrame;
1977 viewImpl()->setFocusedFrame(this); 564 m_ownerFrame.viewImpl()->setFocusedFrame(&m_ownerFrame);
1978 565
1979 m_activeMatch = range.release(); 566 m_activeMatch = range.release();
1980 setMarkerActive(m_activeMatch.get(), true); 567 setMarkerActive(m_activeMatch.get(), true);
1981 568
1982 // Clear any user selection, to make sure Find Next continues on from th e match we just activated. 569 // Clear any user selection, to make sure Find Next continues on from th e match we just activated.
1983 frame()->selection().clear(); 570 m_ownerFrame.frame()->selection().clear();
1984 571
1985 // Make sure no node is focused. See http://crbug.com/38700. 572 // Make sure no node is focused. See http://crbug.com/38700.
1986 frame()->document()->setFocusedElement(nullptr); 573 m_ownerFrame.frame()->document()->setFocusedElement(nullptr);
1987 } 574 }
1988 575
1989 IntRect activeMatchRect; 576 IntRect activeMatchRect;
1990 IntRect activeMatchBoundingBox = enclosingIntRect(RenderObject::absoluteBoun dingBoxRectForRange(m_activeMatch.get())); 577 IntRect activeMatchBoundingBox = enclosingIntRect(RenderObject::absoluteBoun dingBoxRectForRange(m_activeMatch.get()));
1991 578
1992 if (!activeMatchBoundingBox.isEmpty()) { 579 if (!activeMatchBoundingBox.isEmpty()) {
1993 if (m_activeMatch->firstNode() && m_activeMatch->firstNode()->renderer() ) 580 if (m_activeMatch->firstNode() && m_activeMatch->firstNode()->renderer() ) {
1994 m_activeMatch->firstNode()->renderer()->scrollRectToVisible(activeMa tchBoundingBox, 581 m_activeMatch->firstNode()->renderer()->scrollRectToVisible(
1995 ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::align CenterIfNeeded); 582 activeMatchBoundingBox, ScrollAlignment::alignCenterIfNeeded, Sc rollAlignment::alignCenterIfNeeded);
583 }
1996 584
1997 // Zoom to the active match. 585 // Zoom to the active match.
1998 activeMatchRect = frameView()->contentsToWindow(activeMatchBoundingBox); 586 activeMatchRect = m_ownerFrame.frameView()->contentsToWindow(activeMatch BoundingBox);
1999 viewImpl()->zoomToFindInPageRect(activeMatchRect); 587 m_ownerFrame.viewImpl()->zoomToFindInPageRect(activeMatchRect);
2000 } 588 }
2001 589
2002 if (selectionRect) 590 if (selectionRect)
2003 *selectionRect = activeMatchRect; 591 *selectionRect = activeMatchRect;
2004 592
2005 return ordinalOfFirstMatchForFrame(this) + m_activeMatchIndexInCurrentFrame + 1; 593 return ordinalOfFirstMatch() + m_activeMatchIndexInCurrentFrame + 1;
2006 } 594 }
2007 595
2008 WebString WebFrameImpl::contentAsText(size_t maxChars) const 596 PassOwnPtr<TextFinder> TextFinder::create(WebFrameImpl& ownerFrame)
2009 { 597 {
2010 if (!frame()) 598 return adoptPtr(new TextFinder(ownerFrame));
2011 return WebString();
2012 StringBuilder text;
2013 frameContentAsPlainText(maxChars, frame(), text);
2014 return text.toString();
2015 } 599 }
2016 600
2017 WebString WebFrameImpl::contentAsMarkup() const 601 TextFinder::TextFinder(WebFrameImpl& ownerFrame)
2018 { 602 : m_ownerFrame(ownerFrame)
2019 if (!frame())
2020 return WebString();
2021 return createFullMarkup(frame()->document());
2022 }
2023
2024 WebString WebFrameImpl::renderTreeAsText(RenderAsTextControls toShow) const
2025 {
2026 RenderAsTextBehavior behavior = RenderAsTextBehaviorNormal;
2027
2028 if (toShow & RenderAsTextDebug)
2029 behavior |= RenderAsTextShowCompositedLayers | RenderAsTextShowAddresses | RenderAsTextShowIDAndClass | RenderAsTextShowLayerNesting;
2030
2031 if (toShow & RenderAsTextPrinting)
2032 behavior |= RenderAsTextPrintingMode;
2033
2034 return externalRepresentation(frame(), behavior);
2035 }
2036
2037 WebString WebFrameImpl::markerTextForListItem(const WebElement& webElement) cons t
2038 {
2039 return WebCore::markerTextForListItem(const_cast<Element*>(webElement.constU nwrap<Element>()));
2040 }
2041
2042 void WebFrameImpl::printPagesWithBoundaries(WebCanvas* canvas, const WebSize& pa geSizeInPixels)
2043 {
2044 ASSERT(m_printContext);
2045
2046 GraphicsContext graphicsContext(canvas);
2047 graphicsContext.setPrinting(true);
2048
2049 m_printContext->spoolAllPagesWithBoundaries(graphicsContext, FloatSize(pageS izeInPixels.width, pageSizeInPixels.height));
2050 }
2051
2052 WebRect WebFrameImpl::selectionBoundsRect() const
2053 {
2054 return hasSelection() ? WebRect(IntRect(frame()->selection().bounds(false))) : WebRect();
2055 }
2056
2057 bool WebFrameImpl::selectionStartHasSpellingMarkerFor(int from, int length) cons t
2058 {
2059 if (!frame())
2060 return false;
2061 return frame()->spellChecker().selectionStartHasMarkerFor(DocumentMarker::Sp elling, from, length);
2062 }
2063
2064 WebString WebFrameImpl::layerTreeAsText(bool showDebugInfo) const
2065 {
2066 if (!frame())
2067 return WebString();
2068
2069 return WebString(frame()->layerTreeAsText(showDebugInfo ? LayerTreeIncludesD ebugInfo : LayerTreeNormal));
2070 }
2071
2072 // WebFrameImpl public ---------------------------------------------------------
2073
2074 WebFrame* WebFrame::create(WebFrameClient* client)
2075 {
2076 return WebFrameImpl::create(client);
2077 }
2078
2079 WebFrameImpl* WebFrameImpl::create(WebFrameClient* client)
2080 {
2081 return adoptRef(new WebFrameImpl(client)).leakRef();
2082 }
2083
2084 WebFrameImpl::WebFrameImpl(WebFrameClient* client)
2085 : m_frameLoaderClientImpl(this)
2086 , m_parent(0)
2087 , m_previousSibling(0)
2088 , m_nextSibling(0)
2089 , m_firstChild(0)
2090 , m_lastChild(0)
2091 , m_opener(0)
2092 , m_client(client)
2093 , m_permissionClient(0)
2094 , m_currentActiveMatchFrame(0) 603 , m_currentActiveMatchFrame(0)
2095 , m_activeMatchIndexInCurrentFrame(-1) 604 , m_activeMatchIndexInCurrentFrame(-1)
2096 , m_locatingActiveRect(false)
2097 , m_resumeScopingFromRange(nullptr) 605 , m_resumeScopingFromRange(nullptr)
2098 , m_lastMatchCount(-1) 606 , m_lastMatchCount(-1)
2099 , m_totalMatchCount(-1) 607 , m_totalMatchCount(-1)
2100 , m_framesScopingCount(-1) 608 , m_framesScopingCount(-1)
2101 , m_findRequestIdentifier(-1) 609 , m_findRequestIdentifier(-1)
610 , m_nextInvalidateAfter(0)
611 , m_findMatchMarkersVersion(0)
612 , m_locatingActiveRect(false)
2102 , m_scopingInProgress(false) 613 , m_scopingInProgress(false)
2103 , m_lastFindRequestCompletedWithNoMatches(false) 614 , m_lastFindRequestCompletedWithNoMatches(false)
2104 , m_nextInvalidateAfter(0)
2105 , m_findMatchMarkersVersion(0)
2106 , m_findMatchRectsAreValid(false) 615 , m_findMatchRectsAreValid(false)
2107 , m_inputEventsScaleFactorForEmulation(1)
2108 { 616 {
2109 blink::Platform::current()->incrementStatsCounter(webFrameActiveCount);
2110 frameCount++;
2111 } 617 }
2112 618
2113 WebFrameImpl::~WebFrameImpl() 619 TextFinder::~TextFinder()
2114 { 620 {
2115 HashSet<WebFrameImpl*>::iterator end = m_openedFrames.end();
2116 for (HashSet<WebFrameImpl*>::iterator it = m_openedFrames.begin(); it != end ; ++it)
2117 (*it)->m_opener = 0;
2118
2119 blink::Platform::current()->decrementStatsCounter(webFrameActiveCount);
2120 frameCount--;
2121
2122 cancelPendingScopingEffort(); 621 cancelPendingScopingEffort();
2123 } 622 }
2124 623
2125 void WebFrameImpl::setWebCoreFrame(PassRefPtr<WebCore::LocalFrame> frame) 624 void TextFinder::invalidateArea(AreaToInvalidate area)
2126 { 625 {
2127 m_frame = frame; 626 ASSERT(m_ownerFrame.frame() && m_ownerFrame.frame()->view());
2128 } 627 FrameView* view = m_ownerFrame.frame()->view();
2129 628
2130 void WebFrameImpl::initializeAsMainFrame(WebCore::Page* page) 629 if ((area & InvalidateAll) == InvalidateAll) {
2131 {
2132 setWebCoreFrame(LocalFrame::create(&m_frameLoaderClientImpl, &page->frameHos t(), 0));
2133
2134 // We must call init() after m_frame is assigned because it is referenced
2135 // during init().
2136 m_frame->init();
2137 }
2138
2139 PassRefPtr<LocalFrame> WebFrameImpl::createChildFrame(const FrameLoadRequest& re quest, HTMLFrameOwnerElement* ownerElement)
2140 {
2141 ASSERT(m_client);
2142 WebFrameImpl* webframe = toWebFrameImpl(m_client->createChildFrame(this, req uest.frameName()));
2143 if (!webframe)
2144 return nullptr;
2145
2146 RefPtr<LocalFrame> childFrame = LocalFrame::create(&webframe->m_frameLoaderC lientImpl, frame()->host(), ownerElement);
2147 webframe->setWebCoreFrame(childFrame);
2148
2149 childFrame->tree().setName(request.frameName());
2150
2151 // FIXME: This comment is not quite accurate anymore.
2152 // LocalFrame::init() can trigger onload event in the parent frame,
2153 // which may detach this frame and trigger a null-pointer access
2154 // in FrameTree::removeChild. Move init() after appendChild call
2155 // so that webframe->mFrame is in the tree before triggering
2156 // onload event handler.
2157 // Because the event handler may set webframe->mFrame to null,
2158 // it is necessary to check the value after calling init() and
2159 // return without loading URL.
2160 // NOTE: m_client will be null if this frame has been detached.
2161 // (b:791612)
2162 childFrame->init(); // create an empty document
2163 if (!childFrame->tree().parent())
2164 return nullptr;
2165
2166 // If we're moving in the back/forward list, we might want to replace the co ntent
2167 // of this child frame with whatever was there at that point.
2168 HistoryItem* childItem = 0;
2169 if (isBackForwardLoadType(frame()->loader().loadType()) && !frame()->documen t()->loadEventFinished())
2170 childItem = frame()->page()->historyController().itemForNewChildFrame(ch ildFrame.get());
2171
2172 if (childItem)
2173 childFrame->loader().loadHistoryItem(childItem);
2174 else
2175 childFrame->loader().load(FrameLoadRequest(0, request.resourceRequest(), "_self"));
2176
2177 // A synchronous navigation (about:blank) would have already processed
2178 // onload, so it is possible for the frame to have already been destroyed by
2179 // script in the page.
2180 // NOTE: m_client will be null if this frame has been detached.
2181 if (!childFrame->tree().parent())
2182 return nullptr;
2183
2184 return childFrame.release();
2185 }
2186
2187 void WebFrameImpl::didChangeContentsSize(const IntSize& size)
2188 {
2189 // This is only possible on the main frame.
2190 if (m_totalMatchCount > 0) {
2191 ASSERT(!parent());
2192 ++m_findMatchMarkersVersion;
2193 }
2194 }
2195
2196 void WebFrameImpl::createFrameView()
2197 {
2198 TRACE_EVENT0("webkit", "WebFrameImpl::createFrameView");
2199
2200 ASSERT(frame()); // If frame() doesn't exist, we probably didn't init proper ly.
2201
2202 WebViewImpl* webView = viewImpl();
2203 bool isMainFrame = webView->mainFrameImpl()->frame() == frame();
2204 if (isMainFrame)
2205 webView->suppressInvalidations(true);
2206
2207 frame()->createView(webView->size(), webView->baseBackgroundColor(), webView ->isTransparent());
2208 if (webView->shouldAutoResize() && isMainFrame)
2209 frame()->view()->enableAutoSizeMode(true, webView->minAutoSize(), webVie w->maxAutoSize());
2210
2211 frame()->view()->setInputEventsTransformForEmulation(m_inputEventsOffsetForE mulation, m_inputEventsScaleFactorForEmulation);
2212
2213 if (isMainFrame)
2214 webView->suppressInvalidations(false);
2215 }
2216
2217 WebFrameImpl* WebFrameImpl::fromFrame(LocalFrame* frame)
2218 {
2219 if (!frame)
2220 return 0;
2221 return toFrameLoaderClientImpl(frame->loader().client())->webFrame();
2222 }
2223
2224 WebFrameImpl* WebFrameImpl::fromFrameOwnerElement(Element* element)
2225 {
2226 // 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.
2227 if (!element || !element->isFrameOwnerElement() || (!element->hasTagName(HTM LNames::iframeTag) && !element->hasTagName(HTMLNames::frameTag)))
2228 return 0;
2229 return fromFrame(toHTMLFrameOwnerElement(element)->contentFrame());
2230 }
2231
2232 WebViewImpl* WebFrameImpl::viewImpl() const
2233 {
2234 if (!frame())
2235 return 0;
2236 return WebViewImpl::fromPage(frame()->page());
2237 }
2238
2239 WebDataSourceImpl* WebFrameImpl::dataSourceImpl() const
2240 {
2241 return static_cast<WebDataSourceImpl*>(dataSource());
2242 }
2243
2244 WebDataSourceImpl* WebFrameImpl::provisionalDataSourceImpl() const
2245 {
2246 return static_cast<WebDataSourceImpl*>(provisionalDataSource());
2247 }
2248
2249 void WebFrameImpl::setFindEndstateFocusAndSelection()
2250 {
2251 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
2252
2253 if (this == mainFrameImpl->activeMatchFrame() && m_activeMatch.get()) {
2254 // If the user has set the selection since the match was found, we
2255 // don't focus anything.
2256 VisibleSelection selection(frame()->selection().selection());
2257 if (!selection.isNone())
2258 return;
2259
2260 // Try to find the first focusable node up the chain, which will, for
2261 // example, focus links if we have found text within the link.
2262 Node* node = m_activeMatch->firstNode();
2263 if (node && node->isInShadowTree()) {
2264 Node* host = node->deprecatedShadowAncestorNode();
2265 if (host->hasTagName(HTMLNames::inputTag) || host->hasTagName(HTMLNa mes::textareaTag))
2266 node = host;
2267 }
2268 for (; node; node = node->parentNode()) {
2269 if (!node->isElementNode())
2270 continue;
2271 Element* element = toElement(node);
2272 if (element->isFocusable()) {
2273 // Found a focusable parent node. Set the active match as the
2274 // selection and focus to the focusable node.
2275 frame()->selection().setSelection(m_activeMatch.get());
2276 frame()->document()->setFocusedElement(element);
2277 return;
2278 }
2279 }
2280
2281 // Iterate over all the nodes in the range until we find a focusable nod e.
2282 // This, for example, sets focus to the first link if you search for
2283 // text and text that is within one or more links.
2284 node = m_activeMatch->firstNode();
2285 for (; node && node != m_activeMatch->pastLastNode(); node = NodeTravers al::next(*node)) {
2286 if (!node->isElementNode())
2287 continue;
2288 Element* element = toElement(node);
2289 if (element->isFocusable()) {
2290 frame()->document()->setFocusedElement(element);
2291 return;
2292 }
2293 }
2294
2295 // No node related to the active match was focusable, so set the
2296 // active match as the selection (so that when you end the Find session,
2297 // you'll have the last thing you found highlighted) and make sure that
2298 // we have nothing focused (otherwise you might have text selected but
2299 // a link focused, which is weird).
2300 frame()->selection().setSelection(m_activeMatch.get());
2301 frame()->document()->setFocusedElement(nullptr);
2302
2303 // Finally clear the active match, for two reasons:
2304 // We just finished the find 'session' and we don't want future (potenti ally
2305 // unrelated) find 'sessions' operations to start at the same place.
2306 // The WebFrameImpl could get reused and the m_activeMatch could end up pointing
2307 // to a document that is no longer valid. Keeping an invalid reference a round
2308 // is just asking for trouble.
2309 m_activeMatch = nullptr;
2310 }
2311 }
2312
2313 void WebFrameImpl::didFail(const ResourceError& error, bool wasProvisional)
2314 {
2315 if (!client())
2316 return;
2317 WebURLError webError = error;
2318 if (wasProvisional)
2319 client()->didFailProvisionalLoad(this, webError);
2320 else
2321 client()->didFailLoad(this, webError);
2322 }
2323
2324 void WebFrameImpl::setCanHaveScrollbars(bool canHaveScrollbars)
2325 {
2326 frame()->view()->setCanHaveScrollbars(canHaveScrollbars);
2327 }
2328
2329 void WebFrameImpl::setInputEventsTransformForEmulation(const IntSize& offset, fl oat contentScaleFactor)
2330 {
2331 m_inputEventsOffsetForEmulation = offset;
2332 m_inputEventsScaleFactorForEmulation = contentScaleFactor;
2333 if (frame()->view())
2334 frame()->view()->setInputEventsTransformForEmulation(m_inputEventsOffset ForEmulation, m_inputEventsScaleFactorForEmulation);
2335 }
2336
2337 void WebFrameImpl::invalidateArea(AreaToInvalidate area)
2338 {
2339 ASSERT(frame() && frame()->view());
2340 FrameView* view = frame()->view();
2341
2342 if ((area & InvalidateAll) == InvalidateAll)
2343 view->invalidateRect(view->frameRect()); 630 view->invalidateRect(view->frameRect());
2344 else { 631 } else {
2345 if ((area & InvalidateContentArea) == InvalidateContentArea) { 632 if ((area & InvalidateContentArea) == InvalidateContentArea) {
2346 IntRect contentArea( 633 IntRect contentArea(
2347 view->x(), view->y(), view->visibleWidth(), view->visibleHeight( )); 634 view->x(), view->y(), view->visibleWidth(), view->visibleHeight( ));
2348 IntRect frameRect = view->frameRect(); 635 IntRect frameRect = view->frameRect();
2349 contentArea.move(-frameRect.x(), -frameRect.y()); 636 contentArea.move(-frameRect.x(), -frameRect.y());
2350 view->invalidateRect(contentArea); 637 view->invalidateRect(contentArea);
2351 } 638 }
2352 } 639 }
2353 640
2354 if ((area & InvalidateScrollbar) == InvalidateScrollbar) { 641 if ((area & InvalidateScrollbar) == InvalidateScrollbar) {
2355 // Invalidate the vertical scroll bar region for the view. 642 // Invalidate the vertical scroll bar region for the view.
2356 Scrollbar* scrollbar = view->verticalScrollbar(); 643 Scrollbar* scrollbar = view->verticalScrollbar();
2357 if (scrollbar) 644 if (scrollbar)
2358 scrollbar->invalidate(); 645 scrollbar->invalidate();
2359 } 646 }
2360 } 647 }
2361 648
2362 void WebFrameImpl::addMarker(Range* range, bool activeMatch) 649 void TextFinder::addMarker(Range* range, bool activeMatch)
2363 { 650 {
2364 frame()->document()->markers().addTextMatchMarker(range, activeMatch); 651 m_ownerFrame.frame()->document()->markers().addTextMatchMarker(range, active Match);
2365 } 652 }
2366 653
2367 void WebFrameImpl::setMarkerActive(Range* range, bool active) 654 void TextFinder::setMarkerActive(Range* range, bool active)
2368 { 655 {
2369 if (!range || range->collapsed(IGNORE_EXCEPTION)) 656 if (!range || range->collapsed(IGNORE_EXCEPTION))
2370 return; 657 return;
2371 frame()->document()->markers().setMarkersActive(range, active); 658 m_ownerFrame.frame()->document()->markers().setMarkersActive(range, active);
2372 } 659 }
2373 660
2374 int WebFrameImpl::ordinalOfFirstMatchForFrame(WebFrameImpl* frame) const 661 int TextFinder::ordinalOfFirstMatchForFrame(WebFrameImpl* frame) const
2375 { 662 {
2376 int ordinal = 0; 663 int ordinal = 0;
2377 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl(); 664 WebFrameImpl* mainFrameImpl = m_ownerFrame.viewImpl()->mainFrameImpl();
2378 // Iterate from the main frame up to (but not including) |frame| and 665 // Iterate from the main frame up to (but not including) |frame| and
2379 // add up the number of matches found so far. 666 // add up the number of matches found so far.
2380 for (WebFrameImpl* it = mainFrameImpl; it != frame; it = toWebFrameImpl(it-> traverseNext(true))) { 667 for (WebFrameImpl* it = mainFrameImpl; it != frame; it = toWebFrameImpl(it-> traverseNext(true))) {
2381 if (it->m_lastMatchCount > 0) 668 TextFinder& finder = it->getOrCreateTextFinder();
2382 ordinal += it->m_lastMatchCount; 669 if (finder.m_lastMatchCount > 0)
670 ordinal += finder.m_lastMatchCount;
2383 } 671 }
2384 return ordinal; 672 return ordinal;
2385 } 673 }
2386 674
2387 bool WebFrameImpl::shouldScopeMatches(const String& searchText) 675 bool TextFinder::shouldScopeMatches(const String& searchText)
2388 { 676 {
2389 // Don't scope if we can't find a frame or a view. 677 // Don't scope if we can't find a frame or a view.
2390 // The user may have closed the tab/application, so abort. 678 // The user may have closed the tab/application, so abort.
2391 // Also ignore detached frames, as many find operations report to the main f rame. 679 // Also ignore detached frames, as many find operations report to the main f rame.
2392 if (!frame() || !frame()->view() || !frame()->page() || !hasVisibleContent() ) 680 LocalFrame* frame = m_ownerFrame.frame();
681 if (!frame || !frame->view() || !frame->page() || !m_ownerFrame.hasVisibleCo ntent())
2393 return false; 682 return false;
2394 683
2395 ASSERT(frame()->document() && frame()->view()); 684 ASSERT(frame->document() && frame->view());
2396 685
2397 // If the frame completed the scoping operation and found 0 matches the last 686 // If the frame completed the scoping operation and found 0 matches the last
2398 // time it was searched, then we don't have to search it again if the user i s 687 // time it was searched, then we don't have to search it again if the user i s
2399 // just adding to the search string or sending the same search string again. 688 // just adding to the search string or sending the same search string again.
2400 if (m_lastFindRequestCompletedWithNoMatches && !m_lastSearchString.isEmpty() ) { 689 if (m_lastFindRequestCompletedWithNoMatches && !m_lastSearchString.isEmpty() ) {
2401 // Check to see if the search string prefixes match. 690 // Check to see if the search string prefixes match.
2402 String previousSearchPrefix = 691 String previousSearchPrefix =
2403 searchText.substring(0, m_lastSearchString.length()); 692 searchText.substring(0, m_lastSearchString.length());
2404 693
2405 if (previousSearchPrefix == m_lastSearchString) 694 if (previousSearchPrefix == m_lastSearchString)
2406 return false; // Don't search this frame, it will be fruitless. 695 return false; // Don't search this frame, it will be fruitless.
2407 } 696 }
2408 697
2409 return true; 698 return true;
2410 } 699 }
2411 700
2412 void WebFrameImpl::scopeStringMatchesSoon(int identifier, const WebString& searc hText, const WebFindOptions& options, bool reset) 701 void TextFinder::scopeStringMatchesSoon(int identifier, const WebString& searchT ext, const WebFindOptions& options, bool reset)
2413 { 702 {
2414 m_deferredScopingWork.append(new DeferredScopeStringMatches(this, identifier , searchText, options, reset)); 703 m_deferredScopingWork.append(new DeferredScopeStringMatches(this, identifier , searchText, options, reset));
2415 } 704 }
2416 705
2417 void WebFrameImpl::callScopeStringMatches(DeferredScopeStringMatches* caller, in t identifier, const WebString& searchText, const WebFindOptions& options, bool r eset) 706 void TextFinder::callScopeStringMatches(DeferredScopeStringMatches* caller, int identifier, const WebString& searchText, const WebFindOptions& options, bool res et)
2418 { 707 {
2419 m_deferredScopingWork.remove(m_deferredScopingWork.find(caller)); 708 m_deferredScopingWork.remove(m_deferredScopingWork.find(caller));
2420 scopeStringMatches(identifier, searchText, options, reset); 709 scopeStringMatches(identifier, searchText, options, reset);
2421 710
2422 // This needs to happen last since searchText is passed by reference. 711 // This needs to happen last since searchText is passed by reference.
2423 delete caller; 712 delete caller;
2424 } 713 }
2425 714
2426 void WebFrameImpl::invalidateIfNecessary() 715 void TextFinder::invalidateIfNecessary()
2427 { 716 {
2428 if (m_lastMatchCount <= m_nextInvalidateAfter) 717 if (m_lastMatchCount <= m_nextInvalidateAfter)
2429 return; 718 return;
2430 719
2431 // FIXME: (http://b/1088165) Optimize the drawing of the tickmarks and 720 // FIXME: (http://b/1088165) Optimize the drawing of the tickmarks and
2432 // remove this. This calculation sets a milestone for when next to 721 // remove this. This calculation sets a milestone for when next to
2433 // invalidate the scrollbar and the content area. We do this so that we 722 // invalidate the scrollbar and the content area. We do this so that we
2434 // don't spend too much time drawing the scrollbar over and over again. 723 // don't spend too much time drawing the scrollbar over and over again.
2435 // Basically, up until the first 500 matches there is no throttle. 724 // Basically, up until the first 500 matches there is no throttle.
2436 // After the first 500 matches, we set set the milestone further and 725 // After the first 500 matches, we set set the milestone further and
2437 // further out (750, 1125, 1688, 2K, 3K). 726 // further out (750, 1125, 1688, 2K, 3K).
2438 static const int startSlowingDownAfter = 500; 727 static const int startSlowingDownAfter = 500;
2439 static const int slowdown = 750; 728 static const int slowdown = 750;
2440 729
2441 int i = m_lastMatchCount / startSlowingDownAfter; 730 int i = m_lastMatchCount / startSlowingDownAfter;
2442 m_nextInvalidateAfter += i * slowdown; 731 m_nextInvalidateAfter += i * slowdown;
2443 invalidateArea(InvalidateScrollbar); 732 invalidateArea(InvalidateScrollbar);
2444 } 733 }
2445 734
2446 void WebFrameImpl::loadJavaScriptURL(const KURL& url) 735 void TextFinder::flushCurrentScoping()
2447 { 736 {
2448 // This is copied from ScriptController::executeScriptIfJavaScriptURL. 737 flushCurrentScopingEffort(m_findRequestIdentifier);
2449 // Unfortunately, we cannot just use that method since it is private, and
2450 // it also doesn't quite behave as we require it to for bookmarklets. The
2451 // key difference is that we need to suppress loading the string result
2452 // from evaluating the JS URL if executing the JS URL resulted in a
2453 // location change. We also allow a JS URL to be loaded even if scripts on
2454 // the page are otherwise disabled.
2455
2456 if (!frame()->document() || !frame()->page())
2457 return;
2458
2459 RefPtr<Document> ownerDocument(frame()->document());
2460
2461 // Protect privileged pages against bookmarklets and other javascript manipu lations.
2462 if (SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(frame()- >document()->url().protocol()))
2463 return;
2464
2465 String script = decodeURLEscapeSequences(url.string().substring(strlen("java script:")));
2466 UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
2467 ScriptValue result = frame()->script().executeScriptInMainWorldAndReturnValu e(ScriptSourceCode(script));
2468
2469 String scriptResult;
2470 if (!result.getString(scriptResult))
2471 return;
2472
2473 if (!frame()->navigationScheduler().locationChangePending())
2474 frame()->document()->loader()->replaceDocument(scriptResult, ownerDocume nt.get());
2475 } 738 }
2476 739
2477 void WebFrameImpl::willDetachParent() 740 void TextFinder::setMatchMarkerActive(bool active)
2478 { 741 {
2479 // Do not expect string scoping results from any frames that got detached 742 setMarkerActive(m_activeMatch.get(), active);
2480 // in the middle of the operation. 743 }
2481 if (m_scopingInProgress) {
2482 744
2483 // There is a possibility that the frame being detached was the only 745 void TextFinder::decrementFramesScopingCount(int identifier)
2484 // pending one. We need to make sure final replies can be sent. 746 {
2485 flushCurrentScopingEffort(m_findRequestIdentifier); 747 // This frame has no further scoping left, so it is done. Other frames might ,
748 // of course, continue to scope matches.
749 --m_framesScopingCount;
2486 750
2487 cancelPendingScopingEffort(); 751 // If this is the last frame to finish scoping we need to trigger the final
2488 } 752 // update to be sent.
753 if (!m_framesScopingCount)
754 m_ownerFrame.increaseMatchCount(0, identifier);
755 }
756
757 int TextFinder::ordinalOfFirstMatch() const
758 {
759 return ordinalOfFirstMatchForFrame(&m_ownerFrame);
2489 } 760 }
2490 761
2491 } // namespace blink 762 } // namespace blink
OLDNEW
« no previous file with comments | « Source/web/TextFinder.h ('k') | Source/web/WebFrameImpl.h » ('j') | Source/web/WebFrameImpl.h » ('J')

Powered by Google App Engine
This is Rietveld 408576698