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 "WebAnimationControllerImpl.h"
35#include "WebFrame.h"
36
37#include "Frame.h"
38#include "FrameLoaderClientImpl.h"
39#include "PlatformString.h"
40#include <wtf/OwnPtr.h>
41#include <wtf/RefCounted.h>
42
43namespace WebCore {
44class GraphicsContext;
45class HistoryItem;
46class KURL;
47class Node;
48class Range;
49class SubstituteData;
50struct WindowFeatures;
51}
52
53namespace WebKit {
54class ChromePrintContext;
55class WebDataSourceImpl;
56class WebInputElement;
57class WebFrameClient;
58class WebPasswordAutocompleteListener;
59class WebPerformance;
60class WebPluginContainerImpl;
61class WebView;
62class WebViewImpl;
63
64// Implementation of WebFrame, note that this is a reference counted object.
65class WebFrameImpl : public WebFrame, public RefCounted<WebFrameImpl> {
66public:
67    // WebFrame methods:
68    virtual WebString name() const;
69    virtual void setName(const WebString&);
70    virtual long long identifier() const;
71    virtual WebURL url() const;
72    virtual WebURL favIconURL() const;
73    virtual WebURL openSearchDescriptionURL() const;
74    virtual WebString encoding() const;
75    virtual WebSize scrollOffset() const;
76    virtual void setScrollOffset(const WebSize&);
77    virtual WebSize contentsSize() const;
78    virtual int contentsPreferredWidth() const;
79    virtual int documentElementScrollHeight() const;
80    virtual bool hasVisibleContent() const;
81    virtual WebView* view() const;
82    virtual WebFrame* opener() const;
83    virtual void clearOpener();
84    virtual WebFrame* parent() const;
85    virtual WebFrame* top() const;
86    virtual WebFrame* firstChild() const;
87    virtual WebFrame* lastChild() const;
88    virtual WebFrame* nextSibling() const;
89    virtual WebFrame* previousSibling() const;
90    virtual WebFrame* traverseNext(bool wrap) const;
91    virtual WebFrame* traversePrevious(bool wrap) const;
92    virtual WebFrame* findChildByName(const WebString&) const;
93    virtual WebFrame* findChildByExpression(const WebString&) const;
94    virtual WebDocument document() const;
95    virtual void forms(WebVector<WebFormElement>&) const;
96    virtual WebAnimationController* animationController();
97    virtual WebPerformance performance() const;
98    virtual WebSecurityOrigin securityOrigin() const;
99    virtual void grantUniversalAccess();
100    virtual NPObject* windowObject() const;
101    virtual void bindToWindowObject(const WebString& name, NPObject*);
102    virtual void executeScript(const WebScriptSource&);
103    virtual void executeScriptInIsolatedWorld(
104        int worldId, const WebScriptSource* sources, unsigned numSources,
105        int extensionGroup);
106    virtual void addMessageToConsole(const WebConsoleMessage&);
107    virtual void collectGarbage();
108#if WEBKIT_USING_V8
109    virtual v8::Handle<v8::Value> executeScriptAndReturnValue(
110        const WebScriptSource&);
111    virtual v8::Local<v8::Context> mainWorldScriptContext() const;
112    virtual v8::Handle<v8::Value> createFileSystem(WebFileSystem::Type,
113                                                   const WebString& name,
114                                                   const WebString& path);
115    virtual v8::Handle<v8::Value> createFileEntry(WebFileSystem::Type,
116                                                  const WebString& fileSystemName,
117                                                  const WebString& fileSystemPath,
118                                                  const WebString& filePath,
119                                                  bool isDirectory);
120#endif
121    virtual bool insertStyleText(const WebString& css, const WebString& id);
122    virtual void reload(bool ignoreCache);
123    virtual void loadRequest(const WebURLRequest&);
124    virtual void loadHistoryItem(const WebHistoryItem&);
125    virtual void loadData(
126        const WebData&, const WebString& mimeType, const WebString& textEncoding,
127        const WebURL& baseURL, const WebURL& unreachableURL, bool replace);
128    virtual void loadHTMLString(
129        const WebData& html, const WebURL& baseURL, const WebURL& unreachableURL,
130        bool replace);
131    virtual bool isLoading() const;
132    virtual void stopLoading();
133    virtual WebDataSource* provisionalDataSource() const;
134    virtual WebDataSource* dataSource() const;
135    virtual WebHistoryItem previousHistoryItem() const;
136    virtual WebHistoryItem currentHistoryItem() const;
137    virtual void enableViewSourceMode(bool enable);
138    virtual bool isViewSourceModeEnabled() const;
139    virtual void setReferrerForRequest(WebURLRequest&, const WebURL& referrer);
140    virtual void dispatchWillSendRequest(WebURLRequest&);
141    // FIXME: Remove this overload when clients have been changed to pass options.
142    virtual WebURLLoader* createAssociatedURLLoader();
143    virtual WebURLLoader* createAssociatedURLLoader(const WebURLLoaderOptions&);
144    virtual void commitDocumentData(const char* data, size_t length);
145    virtual unsigned unloadListenerCount() const;
146    virtual bool isProcessingUserGesture() const;
147    virtual bool willSuppressOpenerInNewFrame() const;
148    virtual void replaceSelection(const WebString&);
149    virtual void insertText(const WebString&);
150    virtual void setMarkedText(const WebString&, unsigned location, unsigned length);
151    virtual void unmarkText();
152    virtual bool hasMarkedText() const;
153    virtual WebRange markedRange() const;
154    virtual bool firstRectForCharacterRange(unsigned location, unsigned length, WebRect&) const;
155    virtual bool executeCommand(const WebString&);
156    virtual bool executeCommand(const WebString&, const WebString& value);
157    virtual bool isCommandEnabled(const WebString&) const;
158    virtual void enableContinuousSpellChecking(bool);
159    virtual bool isContinuousSpellCheckingEnabled() const;
160    virtual bool hasSelection() const;
161    virtual WebRange selectionRange() const;
162    virtual WebString selectionAsText() const;
163    virtual WebString selectionAsMarkup() const;
164    virtual bool selectWordAroundCaret();
165    virtual void selectRange(const WebPoint& start, const WebPoint& end);
166    virtual int printBegin(const WebSize& pageSize,
167                           const WebNode& constrainToNode,
168                           int printerDPI,
169                           bool* useBrowserOverlays);
170    virtual float printPage(int pageToPrint, WebCanvas*);
171    virtual float getPrintPageShrink(int page);
172    virtual void printEnd();
173    virtual bool isPageBoxVisible(int pageIndex);
174    virtual void pageSizeAndMarginsInPixels(int pageIndex,
175                                            WebSize& pageSize,
176                                            int& marginTop,
177                                            int& marginRight,
178                                            int& marginBottom,
179                                            int& marginLeft);
180    virtual bool find(
181        int identifier, const WebString& searchText, const WebFindOptions&,
182        bool wrapWithinFrame, WebRect* selectionRect);
183    virtual void stopFinding(bool clearSelection);
184    virtual void scopeStringMatches(
185        int identifier, const WebString& searchText, const WebFindOptions&,
186        bool reset);
187    virtual void cancelPendingScopingEffort();
188    virtual void increaseMatchCount(int count, int identifier);
189    virtual void resetMatchCount();
190    virtual bool registerPasswordListener(
191        WebInputElement, WebPasswordAutocompleteListener*);
192    virtual void notifiyPasswordListenerOfAutocomplete(
193        const WebInputElement&);
194
195    virtual WebString contentAsText(size_t maxChars) const;
196    virtual WebString contentAsMarkup() const;
197    virtual WebString renderTreeAsText(bool showDebugInfo = false) const;
198    virtual WebString counterValueForElementById(const WebString& id) const;
199    virtual WebString markerTextForListItem(const WebElement&) const;
200    virtual int pageNumberForElementById(const WebString& id,
201                                         float pageWidthInPixels,
202                                         float pageHeightInPixels) const;
203    virtual WebRect selectionBoundsRect() const;
204
205    virtual bool selectionStartHasSpellingMarkerFor(int from, int length) const;
206    virtual bool pauseSVGAnimation(const WebString& animationId,
207                                   double time,
208                                   const WebString& elementId);
209    virtual WebString layerTreeAsText(bool showDebugInfo = false) const;
210
211    static PassRefPtr<WebFrameImpl> create(WebFrameClient* client);
212    ~WebFrameImpl();
213
214    // Called by the WebViewImpl to initialize its main frame:
215    void initializeAsMainFrame(WebViewImpl*);
216
217    PassRefPtr<WebCore::Frame> createChildFrame(
218        const WebCore::FrameLoadRequest&, WebCore::HTMLFrameOwnerElement*);
219
220    void layout();
221    void paint(WebCanvas*, const WebRect&);
222    void paintWithContext(WebCore::GraphicsContext&, const WebRect&);
223    void createFrameView();
224
225    static WebFrameImpl* fromFrame(WebCore::Frame* frame);
226    static WebFrameImpl* fromFrameOwnerElement(WebCore::Element* element);
227
228    // If the frame hosts a PluginDocument, this method returns the WebPluginContainerImpl
229    // that hosts the plugin.
230    static WebPluginContainerImpl* pluginContainerFromFrame(WebCore::Frame*);
231
232    WebViewImpl* viewImpl() const;
233
234    WebCore::Frame* frame() const { return m_frame; }
235    WebCore::FrameView* frameView() const { return m_frame ? m_frame->view() : 0; }
236
237    // Getters for the impls corresponding to Get(Provisional)DataSource. They
238    // may return 0 if there is no corresponding data source.
239    WebDataSourceImpl* dataSourceImpl() const;
240    WebDataSourceImpl* provisionalDataSourceImpl() const;
241
242    // Returns which frame has an active match. This function should only be
243    // called on the main frame, as it is the only frame keeping track. Returned
244    // value can be 0 if no frame has an active match.
245    const WebFrameImpl* activeMatchFrame() const { return m_activeMatchFrame; }
246
247    // When a Find operation ends, we want to set the selection to what was active
248    // and set focus to the first focusable node we find (starting with the first
249    // node in the matched range and going up the inheritance chain). If we find
250    // nothing to focus we focus the first focusable node in the range. This
251    // allows us to set focus to a link (when we find text inside a link), which
252    // allows us to navigate by pressing Enter after closing the Find box.
253    void setFindEndstateFocusAndSelection();
254
255    void didFail(const WebCore::ResourceError&, bool wasProvisional);
256
257    // Sets whether the WebFrameImpl allows its document to be scrolled.
258    // If the parameter is true, allow the document to be scrolled.
259    // Otherwise, disallow scrolling.
260    void setCanHaveScrollbars(bool);
261
262    // Returns the password autocomplete listener associated with the passed
263    // user name input element, or 0 if none available.
264    // Note that the returned listener is owner by the WebFrameImpl and should not
265    // be kept around as it is deleted when the page goes away.
266    WebPasswordAutocompleteListener* getPasswordListener(const WebCore::HTMLInputElement*);
267
268    WebFrameClient* client() const { return m_client; }
269    void setClient(WebFrameClient* client) { m_client = client; }
270
271    static void selectWordAroundPosition(WebCore::Frame*, WebCore::VisiblePosition);
272
273private:
274    class DeferredScopeStringMatches;
275    friend class DeferredScopeStringMatches;
276    friend class FrameLoaderClientImpl;
277
278    // A bit mask specifying area of the frame to invalidate.
279    enum AreaToInvalidate {
280      InvalidateNothing,
281      InvalidateContentArea,
282      InvalidateScrollbar,   // Vertical scrollbar only.
283      InvalidateAll          // Both content area and the scrollbar.
284    };
285
286    WebFrameImpl(WebFrameClient*);
287
288    // Informs the WebFrame that the Frame is being closed, called by the
289    // WebFrameLoaderClient
290    void closing();
291
292    // Notifies the delegate about a new selection rect.
293    void reportFindInPageSelection(
294        const WebRect& selectionRect, int activeMatchOrdinal, int identifier);
295
296    // Invalidates a certain area within the frame.
297    void invalidateArea(AreaToInvalidate);
298
299    // Add a WebKit TextMatch-highlight marker to nodes in a range.
300    void addMarker(WebCore::Range*, bool activeMatch);
301
302    // Sets the markers within a range as active or inactive.
303    void setMarkerActive(WebCore::Range*, bool active);
304
305    // Returns the ordinal of the first match in the frame specified. This
306    // function enumerates the frames, starting with the main frame and up to (but
307    // not including) the frame passed in as a parameter and counts how many
308    // matches have been found.
309    int ordinalOfFirstMatchForFrame(WebFrameImpl*) const;
310
311    // Determines whether the scoping effort is required for a particular frame.
312    // It is not necessary if the frame is invisible, for example, or if this
313    // is a repeat search that already returned nothing last time the same prefix
314    // was searched.
315    bool shouldScopeMatches(const WTF::String& searchText);
316
317    // Queue up a deferred call to scopeStringMatches.
318    void scopeStringMatchesSoon(
319        int identifier, const WebString& searchText, const WebFindOptions&,
320        bool reset);
321
322    // Called by a DeferredScopeStringMatches instance.
323    void callScopeStringMatches(
324        DeferredScopeStringMatches*, int identifier, const WebString& searchText,
325        const WebFindOptions&, bool reset);
326
327    // Determines whether to invalidate the content area and scrollbar.
328    void invalidateIfNecessary();
329
330    // Clears the map of password listeners.
331    void clearPasswordListeners();
332
333    void loadJavaScriptURL(const WebCore::KURL&);
334
335    // Returns a hit-tested VisiblePosition for the given point
336    WebCore::VisiblePosition visiblePositionForWindowPoint(const WebPoint&);
337
338    FrameLoaderClientImpl m_frameLoaderClient;
339
340    WebFrameClient* m_client;
341
342    // This is a weak pointer to our corresponding WebCore frame.  A reference to
343    // ourselves is held while frame_ is valid.  See our Closing method.
344    WebCore::Frame* m_frame;
345
346    // A way for the main frame to keep track of which frame has an active
347    // match. Should be 0 for all other frames.
348    WebFrameImpl* m_activeMatchFrame;
349
350    // The range of the active match for the current frame.
351    RefPtr<WebCore::Range> m_activeMatch;
352
353    // The index of the active match.
354    int m_activeMatchIndex;
355
356    // This flag is used by the scoping effort to determine if we need to figure
357    // out which rectangle is the active match. Once we find the active
358    // rectangle we clear this flag.
359    bool m_locatingActiveRect;
360
361    // The scoping effort can time out and we need to keep track of where we
362    // ended our last search so we can continue from where we left of.
363    RefPtr<WebCore::Range> m_resumeScopingFromRange;
364
365    // Keeps track of the last string this frame searched for. This is used for
366    // short-circuiting searches in the following scenarios: When a frame has
367    // been searched and returned 0 results, we don't need to search that frame
368    // again if the user is just adding to the search (making it more specific).
369    WTF::String m_lastSearchString;
370
371    // Keeps track of how many matches this frame has found so far, so that we
372    // don't loose count between scoping efforts, and is also used (in conjunction
373    // with m_lastSearchString and m_scopingComplete) to figure out if we need to
374    // search the frame again.
375    int m_lastMatchCount;
376
377    // This variable keeps a cumulative total of matches found so far for ALL the
378    // frames on the page, and is only incremented by calling IncreaseMatchCount
379    // (on the main frame only). It should be -1 for all other frames.
380    int m_totalMatchCount;
381
382    // This variable keeps a cumulative total of how many frames are currently
383    // scoping, and is incremented/decremented on the main frame only.
384    // It should be -1 for all other frames.
385    int m_framesScopingCount;
386
387    // Keeps track of whether the scoping effort was completed (the user may
388    // interrupt it before it completes by submitting a new search).
389    bool m_scopingComplete;
390
391    // Keeps track of when the scoping effort should next invalidate the scrollbar
392    // and the frame area.
393    int m_nextInvalidateAfter;
394
395    // A list of all of the pending calls to scopeStringMatches.
396    Vector<DeferredScopeStringMatches*> m_deferredScopingWork;
397
398    // Valid between calls to BeginPrint() and EndPrint(). Containts the print
399    // information. Is used by PrintPage().
400    OwnPtr<ChromePrintContext> m_printContext;
401
402    // The input fields that are interested in edit events and their associated
403    // listeners.
404    typedef HashMap<RefPtr<WebCore::HTMLInputElement>,
405                    WebPasswordAutocompleteListener*> PasswordListenerMap;
406    PasswordListenerMap m_passwordListeners;
407
408    // Keeps a reference to the frame's WebAnimationController.
409    WebAnimationControllerImpl m_animationController;
410
411    // The identifier of this frame.
412    long long m_identifier;
413
414    // Ensure we don't overwrite valid history data during same document loads
415    // from HistoryItems
416    bool m_inSameDocumentHistoryLoad;
417};
418
419} // namespace WebKit
420
421#endif
422