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

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

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

Powered by Google App Engine
This is Rietveld 408576698