1 /*
2 * Copyright (C) 2009 Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #ifndef WebFrameImpl_h
32 #define WebFrameImpl_h
33
34 #include "WebFrame.h"
35
36 #include "FrameLoaderClientImpl.h"
37 #include "core/frame/Frame.h"
38 #include "core/frame/FrameDestructionObserver.h"
39 #include "platform/geometry/FloatRect.h"
40 #include "public/platform/WebFileSystemType.h"
41 #include "wtf/Compiler.h"
42 #include "wtf/OwnPtr.h"
43 #include "wtf/RefCounted.h"
44 #include "wtf/text/WTFString.h"
45
46 namespace WebCore {
47 class GraphicsContext;
48 class HTMLInputElement;
49 class HistoryItem;
50 class IntSize;
51 class KURL;
52 class Node;
53 class Range;
54 class SubstituteData;
55 struct FrameLoadRequest;
56 struct WindowFeatures;
57 }
58
59 namespace blink {
60 class ChromePrintContext;
61 class WebDataSourceImpl;
62 class WebInputElement;
63 class WebFrameClient;
64 class WebPerformance;
65 class WebPluginContainerImpl;
66 class WebView;
67 class WebViewImpl;
68 struct WebPrintParams;
69
70 template <typename T> class WebVector;
71
72 // Implementation of WebFrame, note that this is a reference counted object.
73 class WebFrameImpl
74 : public WebFrame
75 , public RefCounted<WebFrameImpl>
76 , public WebCore::FrameDestructionObserver {
77 public:
78 // WebFrame methods:
79 virtual void close();
80 virtual WebString uniqueName() const;
81 virtual WebString assignedName() const;
82 virtual void setName(const WebString&);
83 virtual long long embedderIdentifier() const;
84 virtual WebVector<WebIconURL> iconURLs(int iconTypesMask) const;
85 virtual void setRemoteWebLayer(WebLayer*);
86 virtual void setPermissionClient(WebPermissionClient*);
87 virtual WebSize scrollOffset() const;
88 virtual void setScrollOffset(const WebSize&);
89 virtual WebSize minimumScrollOffset() const;
90 virtual WebSize maximumScrollOffset() const;
91 virtual WebSize contentsSize() const;
92 virtual bool hasVisibleContent() const;
93 virtual WebRect visibleContentRect() const;
94 virtual bool hasHorizontalScrollbar() const;
95 virtual bool hasVerticalScrollbar() const;
96 virtual WebView* view() const;
97 virtual WebFrame* opener() const;
98 virtual void setOpener(const WebFrame*);
99 virtual WebFrame* parent() const;
100 virtual WebFrame* top() const;
101 virtual WebFrame* firstChild() const;
102 virtual WebFrame* lastChild() const;
103 virtual WebFrame* nextSibling() const;
104 virtual WebFrame* previousSibling() const;
105 virtual WebFrame* traverseNext(bool wrap) const;
106 virtual WebFrame* traversePrevious(bool wrap) const;
107 virtual WebFrame* findChildByName(const WebString&) const;
108 virtual WebFrame* findChildByExpression(const WebString&) const;
109 virtual WebDocument document() const;
110 virtual WebPerformance performance() const;
111 virtual NPObject* windowObject() const;
112 virtual void bindToWindowObject(const WebString& name, NPObject*);
113 virtual void bindToWindowObject(const WebString& name, NPObject*, void*);
114 virtual void executeScript(const WebScriptSource&);
115 virtual void executeScriptInIsolatedWorld(
116 int worldID, const WebScriptSource* sources, unsigned numSources,
117 int extensionGroup);
118 virtual void setIsolatedWorldSecurityOrigin(int worldID, const WebSecurityOrigin&);
119 virtual void setIsolatedWorldContentSecurityPolicy(int worldID, const WebString&);
120 virtual void addMessageToConsole(const WebConsoleMessage&);
121 virtual void collectGarbage();
122 virtual bool checkIfRunInsecureContent(const WebURL&) const;
123 virtual v8::Handle<v8::Value> executeScriptAndReturnValue(
124 const WebScriptSource&);
125 virtual void executeScriptInIsolatedWorld(
126 int worldID, const WebScriptSource* sourcesIn, unsigned numSources,
127 int extensionGroup, WebVector<v8::Local<v8::Value> >* results);
128 virtual v8::Handle<v8::Value> callFunctionEvenIfScriptDisabled(
129 v8::Handle<v8::Function>,
130 v8::Handle<v8::Object>,
131 int argc,
132 v8::Handle<v8::Value> argv[]);
133 virtual v8::Local<v8::Context> mainWorldScriptContext() const;
134 virtual v8::Handle<v8::Value> createFileSystem(WebFileSystemType,
135 const WebString& name,
136 const WebString& path);
137 virtual v8::Handle<v8::Value> createSerializableFileSystem(WebFileSystemType,
138 const WebString& name,
139 const WebString& path);
140 virtual v8::Handle<v8::Value> createFileEntry(WebFileSystemType,
141 const WebString& fileSystemName,
142 const WebString& fileSystemPath,
143 const WebString& filePath,
144 bool isDirectory);
145 virtual void reload(bool ignoreCache);
146 virtual void reloadWithOverrideURL(const WebURL& overrideUrl, bool ignoreCache);
147 virtual void loadRequest(const WebURLRequest&);
148 virtual void loadHistoryItem(const WebHistoryItem&);
149 virtual void loadData(
150 const WebData&, const WebString& mimeType, const WebString& textEncoding,
151 const WebURL& baseURL, const WebURL& unreachableURL, bool replace);
152 virtual void loadHTMLString(
153 const WebData& html, const WebURL& baseURL, const WebURL& unreachableURL,
154 bool replace);
155 virtual bool isLoading() const;
156 virtual void stopLoading();
157 virtual WebDataSource* provisionalDataSource() const;
158 virtual WebDataSource* dataSource() const;
159 virtual WebHistoryItem previousHistoryItem() const;
160 virtual WebHistoryItem currentHistoryItem() const;
161 virtual void enableViewSourceMode(bool enable);
162 virtual bool isViewSourceModeEnabled() const;
163 virtual void setReferrerForRequest(WebURLRequest&, const WebURL& referrer);
164 virtual void dispatchWillSendRequest(WebURLRequest&);
165 virtual WebURLLoader* createAssociatedURLLoader(const WebURLLoaderOptions&);
166 virtual unsigned unloadListenerCount() const;
167 virtual void replaceSelection(const WebString&);
168 virtual void insertText(const WebString&);
169 virtual void setMarkedText(const WebString&, unsigned location, unsigned length);
170 virtual void unmarkText();
171 virtual bool hasMarkedText() const;
172 virtual WebRange markedRange() const;
173 virtual bool firstRectForCharacterRange(unsigned location, unsigned length, WebRect&) const;
174 virtual size_t characterIndexForPoint(const WebPoint&) const;
175 virtual bool executeCommand(const WebString&, const WebNode& = WebNode());
176 virtual bool executeCommand(const WebString&, const WebString& value, const WebNode& = WebNode());
177 virtual bool isCommandEnabled(const WebString&) const;
178 virtual void enableContinuousSpellChecking(bool);
179 virtual bool isContinuousSpellCheckingEnabled() const;
180 virtual void requestTextChecking(const WebElement&);
181 virtual void replaceMisspelledRange(const WebString&);
182 virtual void removeSpellingMarkers();
183 virtual bool hasSelection() const;
184 virtual WebRange selectionRange() const;
185 virtual WebString selectionAsText() const;
186 virtual WebString selectionAsMarkup() const;
187 virtual bool selectWordAroundCaret();
188 virtual void selectRange(const WebPoint& base, const WebPoint& extent);
189 virtual void selectRange(const WebRange&);
190 virtual void moveRangeSelection(const WebPoint& base, const WebPoint& extent);
191 virtual void moveCaretSelection(const WebPoint&);
192 virtual void setCaretVisible(bool);
193 virtual int printBegin(const WebPrintParams&, const WebNode& constrainToNode);
194 virtual float printPage(int pageToPrint, WebCanvas*);
195 virtual float getPrintPageShrink(int page);
196 virtual void printEnd();
197 virtual bool isPrintScalingDisabledForPlugin(const WebNode&);
198 virtual bool hasCustomPageSizeStyle(int pageIndex);
199 virtual bool isPageBoxVisible(int pageIndex);
200 virtual void pageSizeAndMarginsInPixels(int pageIndex,
201 WebSize& pageSize,
202 int& marginTop,
203 int& marginRight,
204 int& marginBottom,
205 int& marginLeft);
206 virtual WebString pageProperty(const WebString& propertyName, int pageIndex);
207 virtual void printPagesWithBoundaries(WebCanvas*, const WebSize&);
208 virtual bool find(
209 int identifier, const WebString& searchText, const WebFindOptions&,
210 bool wrapWithinFrame, WebRect* selectionRect);
211 virtual void stopFinding(bool clearSelection);
212 virtual void scopeStringMatches(
213 int identifier, const WebString& searchText, const WebFindOptions&,
214 bool reset);
215 virtual void cancelPendingScopingEffort();
216 virtual void increaseMatchCount(int count, int identifier);
217 virtual void resetMatchCount();
218 virtual int findMatchMarkersVersion() const;
219 virtual WebFloatRect activeFindMatchRect();
220 virtual void findMatchRects(WebVector<WebFloatRect>&);
221 virtual int selectNearestFindMatch(const WebFloatPoint&, WebRect* selectionRect);
222
223 virtual void sendOrientationChangeEvent(int orientation);
224
225 virtual void dispatchMessageEventWithOriginCheck(
226 const WebSecurityOrigin& intendedTargetOrigin,
227 const WebDOMEvent&);
228
229 virtual WebString contentAsText(size_t maxChars) const;
230 virtual WebString contentAsMarkup() const;
231 virtual WebString renderTreeAsText(RenderAsTextControls toShow = RenderAsTextNormal) const;
232 virtual WebString markerTextForListItem(const WebElement&) const;
233 virtual WebRect selectionBoundsRect() const;
234
235 virtual bool selectionStartHasSpellingMarkerFor(int from, int length) const;
236 virtual WebString layerTreeAsText(bool showDebugInfo = false) const;
237
238 // WebCore::FrameDestructionObserver methods.
239 virtual void willDetachPage();
240
241 static WebFrameImpl* create(WebFrameClient*);
242 // FIXME: Move the embedderIdentifier concept fully to the embedder and
243 // remove this factory method.
244 static WebFrameImpl* create(WebFrameClient*, long long embedderIdentifier);
245 virtual ~WebFrameImpl();
246
247 // Called by the WebViewImpl to initialize the main frame for the page.
248 void initializeAsMainFrame(WebCore::Page*);
249
250 PassRefPtr<WebCore::Frame> createChildFrame(
251 const WebCore::FrameLoadRequest&, WebCore::HTMLFrameOwnerElement*);
252
253 void didChangeContentsSize(const WebCore::IntSize&);
254
255 void createFrameView();
256
257 static WebFrameImpl* fromFrame(WebCore::Frame* frame);
258 static WebFrameImpl* fromFrameOwnerElement(WebCore::Element* element);
259
260 // If the frame hosts a PluginDocument, this method returns the WebPluginContainerImpl
261 // that hosts the plugin.
262 static WebPluginContainerImpl* pluginContainerFromFrame(WebCore::Frame*);
263
264 // If the frame hosts a PluginDocument, this method returns the WebPluginContainerImpl
265 // that hosts the plugin. If the provided node is a plugin, then it runs its
266 // WebPluginContainerImpl.
267 static WebPluginContainerImpl* pluginContainerFromNode(WebCore::Frame*, const WebNode&);
268
269 WebViewImpl* viewImpl() const;
270
frameView()271 WebCore::FrameView* frameView() const { return frame() ? frame()->view() : 0; }
272
273 // Getters for the impls corresponding to Get(Provisional)DataSource. They
274 // may return 0 if there is no corresponding data source.
275 WebDataSourceImpl* dataSourceImpl() const;
276 WebDataSourceImpl* provisionalDataSourceImpl() const;
277
278 // Returns which frame has an active match. This function should only be
279 // called on the main frame, as it is the only frame keeping track. Returned
280 // value can be 0 if no frame has an active match.
activeMatchFrame()281 WebFrameImpl* activeMatchFrame() const { return m_currentActiveMatchFrame; }
282
283 // Returns the active match in the current frame. Could be a null range if
284 // the local frame has no active match.
activeMatch()285 WebCore::Range* activeMatch() const { return m_activeMatch.get(); }
286
287 // When a Find operation ends, we want to set the selection to what was active
288 // and set focus to the first focusable node we find (starting with the first
289 // node in the matched range and going up the inheritance chain). If we find
290 // nothing to focus we focus the first focusable node in the range. This
291 // allows us to set focus to a link (when we find text inside a link), which
292 // allows us to navigate by pressing Enter after closing the Find box.
293 void setFindEndstateFocusAndSelection();
294
295 void didFail(const WebCore::ResourceError&, bool wasProvisional);
296
297 // Sets whether the WebFrameImpl allows its document to be scrolled.
298 // If the parameter is true, allow the document to be scrolled.
299 // Otherwise, disallow scrolling.
300 void setCanHaveScrollbars(bool);
301
client()302 WebFrameClient* client() const { return m_client; }
setClient(WebFrameClient * client)303 void setClient(WebFrameClient* client) { m_client = client; }
304
permissionClient()305 WebPermissionClient* permissionClient() { return m_permissionClient; }
306
307 void setInputEventsTransformForEmulation(const WebCore::IntSize&, float);
308
309 static void selectWordAroundPosition(WebCore::Frame*, WebCore::VisiblePosition);
310
311 private:
312 class DeferredScopeStringMatches;
313 friend class DeferredScopeStringMatches;
314 friend class FrameLoaderClientImpl;
315
316 struct FindMatch {
317 RefPtr<WebCore::Range> m_range;
318
319 // 1-based index within this frame.
320 int m_ordinal;
321
322 // In find-in-page coordinates.
323 // Lazily calculated by updateFindMatchRects.
324 WebCore::FloatRect m_rect;
325
326 FindMatch(PassRefPtr<WebCore::Range>, int ordinal);
327 };
328
329 // A bit mask specifying area of the frame to invalidate.
330 enum AreaToInvalidate {
331 InvalidateNothing,
332 InvalidateContentArea,
333 InvalidateScrollbar, // Vertical scrollbar only.
334 InvalidateAll // Both content area and the scrollbar.
335 };
336
337 WebFrameImpl(WebFrameClient*, long long frame_identifier);
338
339 // Sets the local WebCore frame and registers destruction observers.
340 void setWebCoreFrame(WebCore::Frame*);
341
342 // Notifies the delegate about a new selection rect.
343 void reportFindInPageSelection(
344 const WebRect& selectionRect, int activeMatchOrdinal, int identifier);
345
346 // Clear the find-in-page matches cache forcing rects to be fully
347 // calculated again next time updateFindMatchRects is called.
348 void clearFindMatchesCache();
349
350 // Check if the activeMatchFrame still exists in the frame tree.
351 bool isActiveMatchFrameValid() const;
352
353 // Return the index in the find-in-page cache of the match closest to the
354 // provided point in find-in-page coordinates, or -1 in case of error.
355 // The squared distance to the closest match is returned in the distanceSquared parameter.
356 int nearestFindMatch(const WebCore::FloatPoint&, float& distanceSquared);
357
358 // Select a find-in-page match marker in the current frame using a cache
359 // match index returned by nearestFindMatch. Returns the ordinal of the new
360 // selected match or -1 in case of error. Also provides the bounding box of
361 // the marker in window coordinates if selectionRect is not null.
362 int selectFindMatch(unsigned index, WebRect* selectionRect);
363
364 // Compute and cache the rects for FindMatches if required.
365 // Rects are automatically invalidated in case of content size changes,
366 // propagating the invalidation to child frames.
367 void updateFindMatchRects();
368
369 // Append the find-in-page match rects of the current frame to the provided vector.
370 void appendFindMatchRects(Vector<WebFloatRect>& frameRects);
371
372 // Invalidates a certain area within the frame.
373 void invalidateArea(AreaToInvalidate);
374
375 // Add a WebKit TextMatch-highlight marker to nodes in a range.
376 void addMarker(WebCore::Range*, bool activeMatch);
377
378 // Sets the markers within a range as active or inactive.
379 void setMarkerActive(WebCore::Range*, bool active);
380
381 // Returns the ordinal of the first match in the frame specified. This
382 // function enumerates the frames, starting with the main frame and up to (but
383 // not including) the frame passed in as a parameter and counts how many
384 // matches have been found.
385 int ordinalOfFirstMatchForFrame(WebFrameImpl*) const;
386
387 // Determines whether the scoping effort is required for a particular frame.
388 // It is not necessary if the frame is invisible, for example, or if this
389 // is a repeat search that already returned nothing last time the same prefix
390 // was searched.
391 bool shouldScopeMatches(const WTF::String& searchText);
392
393 // Removes the current frame from the global scoping effort and triggers any
394 // updates if appropriate. This method does not mark the scoping operation
395 // as finished.
396 void flushCurrentScopingEffort(int identifier);
397
398 // Finishes the current scoping effort and triggers any updates if appropriate.
399 void finishCurrentScopingEffort(int identifier);
400
401 // Queue up a deferred call to scopeStringMatches.
402 void scopeStringMatchesSoon(
403 int identifier, const WebString& searchText, const WebFindOptions&,
404 bool reset);
405
406 // Called by a DeferredScopeStringMatches instance.
407 void callScopeStringMatches(
408 DeferredScopeStringMatches*, int identifier, const WebString& searchText,
409 const WebFindOptions&, bool reset);
410
411 // Determines whether to invalidate the content area and scrollbar.
412 void invalidateIfNecessary();
413
414 void loadJavaScriptURL(const WebCore::KURL&);
415
416 // Returns a hit-tested VisiblePosition for the given point
417 WebCore::VisiblePosition visiblePositionForWindowPoint(const WebPoint&);
418
419 class WebFrameInit : public WebCore::FrameInit {
420 public:
create(WebFrameImpl * webFrameImpl,int64_t frameID)421 static PassRefPtr<WebFrameInit> create(WebFrameImpl* webFrameImpl, int64_t frameID)
422 {
423 return adoptRef(new WebFrameInit(webFrameImpl, frameID));
424 }
425
426 private:
WebFrameInit(WebFrameImpl * webFrameImpl,int64_t frameID)427 WebFrameInit(WebFrameImpl* webFrameImpl, int64_t frameID)
428 : WebCore::FrameInit(frameID)
429 , m_frameLoaderClientImpl(webFrameImpl)
430 {
431 setFrameLoaderClient(&m_frameLoaderClientImpl);
432 }
433
434 FrameLoaderClientImpl m_frameLoaderClientImpl;
435 };
436 RefPtr<WebFrameInit> m_frameInit;
437
438 WebFrameClient* m_client;
439 WebPermissionClient* m_permissionClient;
440
441 // A way for the main frame to keep track of which frame has an active
442 // match. Should be 0 for all other frames.
443 WebFrameImpl* m_currentActiveMatchFrame;
444
445 // The range of the active match for the current frame.
446 RefPtr<WebCore::Range> m_activeMatch;
447
448 // The index of the active match for the current frame.
449 int m_activeMatchIndexInCurrentFrame;
450
451 // This flag is used by the scoping effort to determine if we need to figure
452 // out which rectangle is the active match. Once we find the active
453 // rectangle we clear this flag.
454 bool m_locatingActiveRect;
455
456 // The scoping effort can time out and we need to keep track of where we
457 // ended our last search so we can continue from where we left of.
458 RefPtr<WebCore::Range> m_resumeScopingFromRange;
459
460 // Keeps track of the last string this frame searched for. This is used for
461 // short-circuiting searches in the following scenarios: When a frame has
462 // been searched and returned 0 results, we don't need to search that frame
463 // again if the user is just adding to the search (making it more specific).
464 WTF::String m_lastSearchString;
465
466 // Keeps track of how many matches this frame has found so far, so that we
467 // don't loose count between scoping efforts, and is also used (in conjunction
468 // with m_lastSearchString) to figure out if we need to search the frame again.
469 int m_lastMatchCount;
470
471 // This variable keeps a cumulative total of matches found so far for ALL the
472 // frames on the page, and is only incremented by calling IncreaseMatchCount
473 // (on the main frame only). It should be -1 for all other frames.
474 int m_totalMatchCount;
475
476 // This variable keeps a cumulative total of how many frames are currently
477 // scoping, and is incremented/decremented on the main frame only.
478 // It should be -1 for all other frames.
479 int m_framesScopingCount;
480
481 // Identifier of the latest find-in-page request. Required to be stored in
482 // the frame in order to reply if required in case the frame is detached.
483 int m_findRequestIdentifier;
484
485 // Keeps track of whether there is an scoping effort ongoing in the frame.
486 bool m_scopingInProgress;
487
488 // Keeps track of whether the last find request completed its scoping effort
489 // without finding any matches in this frame.
490 bool m_lastFindRequestCompletedWithNoMatches;
491
492 // Keeps track of when the scoping effort should next invalidate the scrollbar
493 // and the frame area.
494 int m_nextInvalidateAfter;
495
496 // A list of all of the pending calls to scopeStringMatches.
497 Vector<DeferredScopeStringMatches*> m_deferredScopingWork;
498
499 // Version number incremented on the main frame only whenever the document
500 // find-in-page match markers change. It should be 0 for all other frames.
501 int m_findMatchMarkersVersion;
502
503 // Local cache of the find match markers currently displayed for this frame.
504 Vector<FindMatch> m_findMatchesCache;
505
506 // Determines if the rects in the find-in-page matches cache of this frame
507 // are invalid and should be recomputed.
508 bool m_findMatchRectsAreValid;
509
510 // Contents size when find-in-page match rects were last computed for this
511 // frame's cache.
512 WebCore::IntSize m_contentsSizeForCurrentFindMatchRects;
513
514 // Valid between calls to BeginPrint() and EndPrint(). Containts the print
515 // information. Is used by PrintPage().
516 OwnPtr<ChromePrintContext> m_printContext;
517
518 // Stores the additional input events offset and scale when device metrics emulation is enabled.
519 WebCore::IntSize m_inputEventsOffsetForEmulation;
520 float m_inputEventsScaleFactorForEmulation;
521 };
522
toWebFrameImpl(WebFrame * webFrame)523 inline WebFrameImpl* toWebFrameImpl(WebFrame* webFrame)
524 {
525 return static_cast<WebFrameImpl*>(webFrame);
526 }
527
toWebFrameImpl(const WebFrame * webFrame)528 inline const WebFrameImpl* toWebFrameImpl(const WebFrame* webFrame)
529 {
530 return static_cast<const WebFrameImpl*>(webFrame);
531 }
532
533 // This will catch anyone doing an unnecessary cast.
534 void toWebFrameImpl(const WebFrameImpl*);
535
536 } // namespace blink
537
538 #endif
539