render_view_impl.h revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CONTENT_RENDERER_RENDER_VIEW_IMPL_H_
6#define CONTENT_RENDERER_RENDER_VIEW_IMPL_H_
7
8#include <deque>
9#include <map>
10#include <set>
11#include <string>
12#include <vector>
13
14#include "base/basictypes.h"
15#include "base/gtest_prod_util.h"
16#include "base/id_map.h"
17#include "base/memory/linked_ptr.h"
18#include "base/memory/weak_ptr.h"
19#include "base/observer_list.h"
20#include "base/process/process.h"
21#include "base/strings/string16.h"
22#include "base/timer/timer.h"
23#include "build/build_config.h"
24#include "cc/input/top_controls_state.h"
25#include "content/common/content_export.h"
26#include "content/common/drag_event_source_info.h"
27#include "content/common/edit_command.h"
28#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
29#include "content/common/navigation_gesture.h"
30#include "content/common/view_message_enums.h"
31#include "content/public/common/javascript_message_type.h"
32#include "content/public/common/page_zoom.h"
33#include "content/public/common/referrer.h"
34#include "content/public/common/renderer_preferences.h"
35#include "content/public/common/stop_find_action.h"
36#include "content/public/common/top_controls_state.h"
37#include "content/public/renderer/render_view.h"
38#include "content/renderer/media/webmediaplayer_delegate.h"
39#include "content/renderer/mouse_lock_dispatcher.h"
40#include "content/renderer/render_frame_impl.h"
41#include "content/renderer/render_widget.h"
42#include "content/renderer/renderer_webcookiejar_impl.h"
43#include "content/renderer/stats_collection_observer.h"
44#include "ipc/ipc_platform_file.h"
45#include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
46#include "third_party/WebKit/public/web/WebAXObject.h"
47#include "third_party/WebKit/public/web/WebConsoleMessage.h"
48#include "third_party/WebKit/public/web/WebDataSource.h"
49#include "third_party/WebKit/public/web/WebFrameClient.h"
50#include "third_party/WebKit/public/web/WebHistoryItem.h"
51#include "third_party/WebKit/public/web/WebIconURL.h"
52#include "third_party/WebKit/public/web/WebInputEvent.h"
53#include "third_party/WebKit/public/web/WebNavigationType.h"
54#include "third_party/WebKit/public/web/WebNode.h"
55#include "third_party/WebKit/public/web/WebPageSerializerClient.h"
56#include "third_party/WebKit/public/web/WebPageVisibilityState.h"
57#include "third_party/WebKit/public/web/WebSecurityOrigin.h"
58#include "third_party/WebKit/public/web/WebViewClient.h"
59#include "ui/base/ui_base_types.h"
60#include "ui/surface/transport_dib.h"
61#include "webkit/common/webpreferences.h"
62
63#if defined(OS_ANDROID)
64#include "content/renderer/android/content_detector.h"
65#include "third_party/WebKit/public/web/WebContentDetectionResult.h"
66#endif
67
68#if defined(COMPILER_MSVC)
69// RenderViewImpl is a diamond-shaped hierarchy, with WebWidgetClient at the
70// root. VS warns when we inherit the WebWidgetClient method implementations
71// from RenderWidget.  It's safe to ignore that warning.
72#pragma warning(disable: 4250)
73#endif
74
75class CommandLine;
76class PepperDeviceTest;
77class SkBitmap;
78struct PP_NetAddress_Private;
79struct ViewMsg_Navigate_Params;
80struct ViewMsg_PostMessage_Params;
81struct ViewMsg_StopFinding_Params;
82
83namespace ui {
84struct SelectedFileInfo;
85}  // namespace ui
86
87namespace WebKit {
88class WebApplicationCacheHost;
89class WebApplicationCacheHostClient;
90class WebDOMMessageEvent;
91class WebDataSource;
92class WebDateTimeChooserCompletion;
93class WebDragData;
94class WebGeolocationClient;
95class WebGestureEvent;
96class WebIconURL;
97class WebImage;
98class WebPeerConnection00Handler;
99class WebPeerConnection00HandlerClient;
100class WebMediaPlayer;
101class WebMediaPlayerClient;
102class WebMouseEvent;
103class WebPeerConnectionHandler;
104class WebPeerConnectionHandlerClient;
105class WebSocketStreamHandle;
106class WebSpeechInputController;
107class WebSpeechInputListener;
108class WebSpeechRecognizer;
109class WebStorageNamespace;
110class WebTouchEvent;
111class WebURLRequest;
112class WebUserMediaClient;
113struct WebActiveWheelFlingParameters;
114struct WebCursorInfo;
115struct WebDateTimeChooserParams;
116struct WebFileChooserParams;
117struct WebFindOptions;
118struct WebMediaPlayerAction;
119struct WebPluginAction;
120struct WebPoint;
121struct WebWindowFeatures;
122
123#if defined(OS_ANDROID)
124class WebHitTestResult;
125#endif
126}
127
128namespace webkit_glue {
129class WebURLResponseExtraDataImpl;
130}
131
132namespace content {
133class BrowserPluginManager;
134class DeviceOrientationDispatcher;
135class DevToolsAgent;
136class DocumentState;
137class DomAutomationController;
138class ExternalPopupMenu;
139class FaviconHelper;
140class GeolocationDispatcher;
141class ImageResourceFetcher;
142class InputTagSpeechDispatcher;
143class JavaBridgeDispatcher;
144class LoadProgressTracker;
145class MIDIDispatcher;
146class MediaStreamClient;
147class MediaStreamDispatcher;
148class MouseLockDispatcher;
149class NavigationState;
150class NotificationProvider;
151class PepperPluginInstanceImpl;
152class RenderViewObserver;
153class RenderViewTest;
154class RendererAccessibility;
155class RendererDateTimePicker;
156class RendererPpapiHost;
157class RendererWebColorChooserImpl;
158class RenderWidgetFullscreenPepper;
159class SpeechRecognitionDispatcher;
160class StatsCollectionController;
161class WebPluginDelegateProxy;
162struct CustomContextMenuContext;
163struct DropData;
164struct FaviconURL;
165struct FileChooserParams;
166struct RenderViewImplParams;
167
168#if defined(OS_ANDROID)
169class RendererMediaPlayerManager;
170class WebMediaPlayerProxyAndroid;
171#endif
172
173//
174// RenderView is an object that manages a WebView object, and provides a
175// communication interface with an embedding application process
176//
177class CONTENT_EXPORT RenderViewImpl
178    : public RenderWidget,
179      NON_EXPORTED_BASE(public WebKit::WebViewClient),
180      NON_EXPORTED_BASE(public WebKit::WebFrameClient),
181      NON_EXPORTED_BASE(public WebKit::WebPageSerializerClient),
182      public RenderView,
183      NON_EXPORTED_BASE(public WebMediaPlayerDelegate),
184      public base::SupportsWeakPtr<RenderViewImpl> {
185 public:
186  // Creates a new RenderView. |opener_id| is the routing ID of the RenderView
187  // responsible for creating this RenderView.
188  static RenderViewImpl* Create(
189      int32 opener_id,
190      const RendererPreferences& renderer_prefs,
191      const WebPreferences& webkit_prefs,
192      int32 routing_id,
193      int32 main_frame_routing_id,
194      int32 surface_id,
195      int64 session_storage_namespace_id,
196      const string16& frame_name,
197      bool is_renderer_created,
198      bool swapped_out,
199      bool hidden,
200      int32 next_page_id,
201      const WebKit::WebScreenInfo& screen_info,
202      AccessibilityMode accessibility_mode,
203      bool allow_partial_swap);
204
205  // Used by content_layouttest_support to hook into the creation of
206  // RenderViewImpls.
207  static void InstallCreateHook(
208      RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*));
209
210  // Returns the RenderViewImpl containing the given WebView.
211  static RenderViewImpl* FromWebView(WebKit::WebView* webview);
212
213  // Returns the RenderViewImpl for the given routing ID.
214  static RenderViewImpl* FromRoutingID(int routing_id);
215
216  // May return NULL when the view is closing.
217  WebKit::WebView* webview() const;
218
219  int history_list_offset() const { return history_list_offset_; }
220
221  const WebPreferences& webkit_preferences() const {
222    return webkit_preferences_;
223  }
224
225  void set_send_content_state_immediately(bool value) {
226    send_content_state_immediately_ = value;
227  }
228
229  MediaStreamDispatcher* media_stream_dispatcher() {
230    return media_stream_dispatcher_;
231  }
232
233  MouseLockDispatcher* mouse_lock_dispatcher() {
234    return mouse_lock_dispatcher_;
235  }
236
237  RendererWebCookieJarImpl* cookie_jar() { return &cookie_jar_; }
238
239#if defined(OS_ANDROID)
240  RendererMediaPlayerManager* media_player_manager() {
241    return media_player_manager_.get();
242  }
243#endif
244
245  // Lazily initialize this view's BrowserPluginManager and return it.
246  BrowserPluginManager* GetBrowserPluginManager();
247
248  // Functions to add and remove observers for this object.
249  void AddObserver(RenderViewObserver* observer);
250  void RemoveObserver(RenderViewObserver* observer);
251
252  // Returns the StatsCollectionObserver associated with this view, or NULL
253  // if one wasn't created;
254  StatsCollectionObserver* GetStatsCollectionObserver() {
255    return stats_collection_observer_.get();
256  }
257
258  // Adds the given file chooser request to the file_chooser_completion_ queue
259  // (see that var for more) and requests the chooser be displayed if there are
260  // no other waiting items in the queue.
261  //
262  // Returns true if the chooser was successfully scheduled. False means we
263  // didn't schedule anything.
264  bool ScheduleFileChooser(const FileChooserParams& params,
265                           WebKit::WebFileChooserCompletion* completion);
266
267  void LoadNavigationErrorPage(
268      WebKit::WebFrame* frame,
269      const WebKit::WebURLRequest& failed_request,
270      const WebKit::WebURLError& error,
271      const std::string& html,
272      bool replace);
273
274  // Plugin-related functions --------------------------------------------------
275
276#if defined(ENABLE_PLUGINS)
277  // Indicates that the given instance has been created.
278  void PepperInstanceCreated(PepperPluginInstanceImpl* instance);
279
280  // Indicates that the given instance is being destroyed. This is called from
281  // the destructor, so it's important that the instance is not dereferenced
282  // from this call.
283  void PepperInstanceDeleted(PepperPluginInstanceImpl* instance);
284
285  // Notifies that |instance| has changed the cursor.
286  // This will update the cursor appearance if it is currently over the plugin
287  // instance.
288  void PepperDidChangeCursor(PepperPluginInstanceImpl* instance,
289                             const WebKit::WebCursorInfo& cursor);
290
291  // Notifies that |instance| has received a mouse event.
292  void PepperDidReceiveMouseEvent(PepperPluginInstanceImpl* instance);
293
294  // Notification that the given plugin is focused or unfocused.
295  void PepperFocusChanged(PepperPluginInstanceImpl* instance, bool focused);
296
297  // Informs the render view that a PPAPI plugin has changed text input status.
298  void PepperTextInputTypeChanged(PepperPluginInstanceImpl* instance);
299  void PepperCaretPositionChanged(PepperPluginInstanceImpl* instance);
300
301  // Cancels current composition.
302  void PepperCancelComposition(PepperPluginInstanceImpl* instance);
303
304  // Informs the render view that a PPAPI plugin has changed selection.
305  void PepperSelectionChanged(PepperPluginInstanceImpl* instance);
306
307  // Creates a fullscreen container for a pepper plugin instance.
308  RenderWidgetFullscreenPepper* CreatePepperFullscreenContainer(
309      PepperPluginInstanceImpl* plugin);
310
311  // Notification that a PPAPI plugin has been created.
312  void PepperPluginCreated(RendererPpapiHost* host);
313
314  // Retrieves the current caret position if a PPAPI plugin has focus.
315  bool GetPepperCaretBounds(gfx::Rect* rect);
316
317  bool IsPepperAcceptingCompositionEvents() const;
318
319  // Notification that the given plugin has crashed.
320  void PluginCrashed(const base::FilePath& plugin_path,
321                     base::ProcessId plugin_pid);
322
323  // Simulates IME events for testing purpose.
324  void SimulateImeSetComposition(
325      const string16& text,
326      const std::vector<WebKit::WebCompositionUnderline>& underlines,
327      int selection_start,
328      int selection_end);
329  void SimulateImeConfirmComposition(const string16& text,
330                                     const gfx::Range& replacement_range);
331
332#if defined(OS_MACOSX) || defined(OS_WIN)
333  // Informs the render view that the given plugin has gained or lost focus.
334  void PluginFocusChanged(bool focused, int plugin_id);
335#endif
336
337#if defined(OS_MACOSX)
338  // Starts plugin IME.
339  void StartPluginIme();
340#endif
341
342  void RegisterPluginDelegate(WebPluginDelegateProxy* delegate);
343  void UnregisterPluginDelegate(WebPluginDelegateProxy* delegate);
344
345  // Helper function to retrieve information about a plugin for a URL and mime
346  // type. Returns false if no plugin was found.
347  // |actual_mime_type| is the actual mime type supported by the
348  // plugin found that match the URL given (one for each item in
349  // |info|).
350  bool GetPluginInfo(const GURL& url,
351                     const GURL& page_url,
352                     const std::string& mime_type,
353                     WebPluginInfo* plugin_info,
354                     std::string* actual_mime_type);
355
356#endif  // ENABLE_PLUGINS
357
358  void TransferActiveWheelFlingAnimation(
359      const WebKit::WebActiveWheelFlingParameters& params);
360
361  // Returns true if the focused element is editable text from the perspective
362  // of IME support (also used for on-screen keyboard). Works correctly inside
363  // supported PPAPI plug-ins.
364  bool HasIMETextFocus();
365
366  // Callback for use with GetWindowSnapshot.
367  typedef base::Callback<void(
368      const gfx::Size&, const std::vector<unsigned char>&)>
369      WindowSnapshotCallback;
370
371  void GetWindowSnapshot(const WindowSnapshotCallback& callback);
372
373  // Dispatches the current navigation state to the browser. Called on a
374  // periodic timer so we don't send too many messages.
375  void SyncNavigationState();
376
377  // Returns the length of the session history of this RenderView. Note that
378  // this only coincides with the actual length of the session history if this
379  // RenderView is the currently active RenderView of a WebContents.
380  unsigned GetLocalSessionHistoryLengthForTesting() const;
381
382  // Invokes OnSetFocus and marks the widget as active depending on the value
383  // of |enable|. This is used for layout tests that need to control the focus
384  // synchronously from the renderer.
385  void SetFocusAndActivateForTesting(bool enable);
386
387  // Change the device scale factor and force the compositor to resize.
388  void SetDeviceScaleFactorForTesting(float factor);
389
390  // Control autoresize mode.
391  void EnableAutoResizeForTesting(const gfx::Size& min_size,
392                                  const gfx::Size& max_size);
393  void DisableAutoResizeForTesting(const gfx::Size& new_size);
394
395  // Overrides the MediaStreamClient used when creating MediaStream players.
396  // Must be called before any players are created.
397  void SetMediaStreamClientForTesting(MediaStreamClient* media_stream_client);
398
399  // IPC::Listener implementation ----------------------------------------------
400
401  virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
402
403  // WebKit::WebWidgetClient implementation ------------------------------------
404
405  // Most methods are handled by RenderWidget.
406  virtual void didFocus();
407  virtual void didBlur();
408  virtual void show(WebKit::WebNavigationPolicy policy);
409  virtual void runModal();
410  virtual bool enterFullScreen();
411  virtual void exitFullScreen();
412  virtual bool requestPointerLock();
413  virtual void requestPointerUnlock();
414  virtual bool isPointerLocked();
415  virtual void didActivateCompositor(int input_handler_identifier);
416  virtual void didHandleGestureEvent(const WebKit::WebGestureEvent& event,
417                                     bool event_cancelled) OVERRIDE;
418  virtual void initializeLayerTreeView() OVERRIDE;
419
420  // WebKit::WebViewClient implementation --------------------------------------
421
422  virtual WebKit::WebView* createView(
423      WebKit::WebFrame* creator,
424      const WebKit::WebURLRequest& request,
425      const WebKit::WebWindowFeatures& features,
426      const WebKit::WebString& frame_name,
427      WebKit::WebNavigationPolicy policy);
428  virtual WebKit::WebWidget* createPopupMenu(WebKit::WebPopupType popup_type);
429  virtual WebKit::WebExternalPopupMenu* createExternalPopupMenu(
430      const WebKit::WebPopupMenuInfo& popup_menu_info,
431      WebKit::WebExternalPopupMenuClient* popup_menu_client);
432  virtual WebKit::WebStorageNamespace* createSessionStorageNamespace();
433  virtual bool shouldReportDetailedMessageForSource(
434      const WebKit::WebString& source);
435  virtual void didAddMessageToConsole(
436      const WebKit::WebConsoleMessage& message,
437      const WebKit::WebString& source_name,
438      unsigned source_line,
439      const WebKit::WebString& stack_trace);
440  virtual void printPage(WebKit::WebFrame* frame);
441  virtual WebKit::WebNotificationPresenter* notificationPresenter();
442  virtual bool enumerateChosenDirectory(
443      const WebKit::WebString& path,
444      WebKit::WebFileChooserCompletion* chooser_completion);
445  virtual void initializeHelperPluginWebFrame(WebKit::WebHelperPlugin*);
446  virtual void didStartLoading();
447  virtual void didStopLoading();
448  virtual void didChangeLoadProgress(WebKit::WebFrame* frame,
449                                     double load_progress);
450  virtual void didCancelCompositionOnSelectionChange();
451  virtual void didChangeSelection(bool is_selection_empty);
452  virtual void didExecuteCommand(const WebKit::WebString& command_name);
453  virtual bool handleCurrentKeyboardEvent();
454  virtual WebKit::WebColorChooser* createColorChooser(
455      WebKit::WebColorChooserClient*, const WebKit::WebColor& initial_color);
456  virtual bool runFileChooser(
457      const WebKit::WebFileChooserParams& params,
458      WebKit::WebFileChooserCompletion* chooser_completion);
459  virtual void runModalAlertDialog(WebKit::WebFrame* frame,
460                                   const WebKit::WebString& message);
461  virtual bool runModalConfirmDialog(WebKit::WebFrame* frame,
462                                     const WebKit::WebString& message);
463  virtual bool runModalPromptDialog(WebKit::WebFrame* frame,
464                                    const WebKit::WebString& message,
465                                    const WebKit::WebString& default_value,
466                                    WebKit::WebString* actual_value);
467  virtual bool runModalBeforeUnloadDialog(WebKit::WebFrame* frame,
468                                          bool is_reload,
469                                          const WebKit::WebString& message);
470  // DEPRECATED
471  virtual bool runModalBeforeUnloadDialog(WebKit::WebFrame* frame,
472                                          const WebKit::WebString& message);
473  virtual void showContextMenu(WebKit::WebFrame* frame,
474                               const WebKit::WebContextMenuData& data);
475  virtual void clearContextMenu();
476  virtual void setStatusText(const WebKit::WebString& text);
477  virtual void setMouseOverURL(const WebKit::WebURL& url);
478  virtual void setKeyboardFocusURL(const WebKit::WebURL& url);
479  virtual void startDragging(WebKit::WebFrame* frame,
480                             const WebKit::WebDragData& data,
481                             WebKit::WebDragOperationsMask mask,
482                             const WebKit::WebImage& image,
483                             const WebKit::WebPoint& imageOffset);
484  virtual bool acceptsLoadDrops();
485  virtual void focusNext();
486  virtual void focusPrevious();
487  virtual void focusedNodeChanged(const WebKit::WebNode& node);
488  virtual void numberOfWheelEventHandlersChanged(unsigned num_handlers);
489  virtual void didUpdateLayout();
490#if defined(OS_ANDROID)
491  virtual bool didTapMultipleTargets(
492      const WebKit::WebGestureEvent& event,
493      const WebKit::WebVector<WebKit::WebRect>& target_rects);
494#endif
495  virtual void navigateBackForwardSoon(int offset);
496  virtual int historyBackListCount();
497  virtual int historyForwardListCount();
498  virtual void postAccessibilityEvent(
499      const WebKit::WebAXObject& obj, WebKit::WebAXEvent event);
500  virtual void didUpdateInspectorSetting(const WebKit::WebString& key,
501                                         const WebKit::WebString& value);
502  virtual WebKit::WebGeolocationClient* geolocationClient();
503  virtual WebKit::WebSpeechInputController* speechInputController(
504      WebKit::WebSpeechInputListener* listener);
505  virtual WebKit::WebSpeechRecognizer* speechRecognizer();
506  virtual WebKit::WebDeviceOrientationClient* deviceOrientationClient();
507  virtual void zoomLimitsChanged(double minimum_level, double maximum_level);
508  virtual void zoomLevelChanged();
509  virtual double zoomLevelToZoomFactor(double zoom_level) const;
510  virtual double zoomFactorToZoomLevel(double factor) const;
511  virtual void registerProtocolHandler(const WebKit::WebString& scheme,
512                                       const WebKit::WebString& base_url,
513                                       const WebKit::WebString& url,
514                                       const WebKit::WebString& title);
515  virtual WebKit::WebPageVisibilityState visibilityState() const;
516  virtual WebKit::WebUserMediaClient* userMediaClient();
517  virtual WebKit::WebMIDIClient* webMIDIClient();
518  virtual void draggableRegionsChanged();
519
520#if defined(OS_ANDROID)
521  virtual void scheduleContentIntent(const WebKit::WebURL& intent);
522  virtual void cancelScheduledContentIntents();
523  virtual WebKit::WebContentDetectionResult detectContentAround(
524      const WebKit::WebHitTestResult& touch_hit);
525
526  // Only used on Android since all other platforms implement
527  // date and time input fields using MULTIPLE_FIELDS_UI
528  virtual bool openDateTimeChooser(const WebKit::WebDateTimeChooserParams&,
529                                   WebKit::WebDateTimeChooserCompletion*);
530  virtual void didScrollWithKeyboard(const WebKit::WebSize& delta);
531#endif
532
533  // WebKit::WebFrameClient implementation -------------------------------------
534
535  virtual WebKit::WebMediaPlayer* createMediaPlayer(
536      WebKit::WebFrame* frame,
537      const WebKit::WebURL& url,
538      WebKit::WebMediaPlayerClient* client);
539  virtual WebKit::WebCookieJar* cookieJar(WebKit::WebFrame* frame);
540  virtual void didAccessInitialDocument(WebKit::WebFrame* frame);
541  virtual void didDisownOpener(WebKit::WebFrame* frame);
542  virtual void frameDetached(WebKit::WebFrame* frame);
543  virtual void willClose(WebKit::WebFrame* frame);
544
545  // The WebDataSource::ExtraData* is assumed to be a DocumentState* subclass.
546  virtual WebKit::WebNavigationPolicy decidePolicyForNavigation(
547      WebKit::WebFrame* frame,
548      WebKit::WebDataSource::ExtraData* extraData,
549      const WebKit::WebURLRequest& request,
550      WebKit::WebNavigationType type,
551      WebKit::WebNavigationPolicy default_policy,
552      bool is_redirect);
553  // DEPRECATED.
554  virtual WebKit::WebNavigationPolicy decidePolicyForNavigation(
555      WebKit::WebFrame* frame,
556      const WebKit::WebURLRequest& request,
557      WebKit::WebNavigationType type,
558      WebKit::WebNavigationPolicy default_policy,
559      bool is_redirect);
560  virtual void willSendSubmitEvent(WebKit::WebFrame* frame,
561                                   const WebKit::WebFormElement& form);
562  virtual void willSubmitForm(WebKit::WebFrame* frame,
563                              const WebKit::WebFormElement& form);
564  virtual void didCreateDataSource(WebKit::WebFrame* frame,
565                                   WebKit::WebDataSource* datasource);
566  virtual void didStartProvisionalLoad(WebKit::WebFrame* frame);
567  virtual void didReceiveServerRedirectForProvisionalLoad(
568      WebKit::WebFrame* frame);
569  virtual void didFailProvisionalLoad(WebKit::WebFrame* frame,
570                                      const WebKit::WebURLError& error);
571  virtual void didCommitProvisionalLoad(WebKit::WebFrame* frame,
572                                        bool is_new_navigation);
573  virtual void didClearWindowObject(WebKit::WebFrame* frame);
574  virtual void didCreateDocumentElement(WebKit::WebFrame* frame);
575  virtual void didReceiveTitle(WebKit::WebFrame* frame,
576                               const WebKit::WebString& title,
577                               WebKit::WebTextDirection direction);
578  virtual void didChangeIcon(WebKit::WebFrame*,
579                             WebKit::WebIconURL::Type);
580  virtual void didFinishDocumentLoad(WebKit::WebFrame* frame);
581  virtual void didHandleOnloadEvents(WebKit::WebFrame* frame);
582  virtual void didFailLoad(WebKit::WebFrame* frame,
583                           const WebKit::WebURLError& error);
584  virtual void didFinishLoad(WebKit::WebFrame* frame);
585  virtual void didNavigateWithinPage(WebKit::WebFrame* frame,
586                                     bool is_new_navigation);
587  virtual void didUpdateCurrentHistoryItem(WebKit::WebFrame* frame);
588  virtual void willSendRequest(WebKit::WebFrame* frame,
589                               unsigned identifier,
590                               WebKit::WebURLRequest& request,
591                               const WebKit::WebURLResponse& redirect_response);
592  virtual void didReceiveResponse(WebKit::WebFrame* frame,
593                                  unsigned identifier,
594                                  const WebKit::WebURLResponse& response);
595  virtual void didFinishResourceLoad(WebKit::WebFrame* frame,
596                                     unsigned identifier);
597  virtual void didLoadResourceFromMemoryCache(
598      WebKit::WebFrame* frame,
599      const WebKit::WebURLRequest& request,
600      const WebKit::WebURLResponse&);
601  virtual void didDisplayInsecureContent(WebKit::WebFrame* frame);
602  virtual void didRunInsecureContent(
603      WebKit::WebFrame* frame,
604      const WebKit::WebSecurityOrigin& origin,
605      const WebKit::WebURL& target);
606  virtual void didExhaustMemoryAvailableForScript(WebKit::WebFrame* frame);
607  virtual void didCreateScriptContext(WebKit::WebFrame* frame,
608                                      v8::Handle<v8::Context>,
609                                      int extension_group,
610                                      int world_id);
611  virtual void willReleaseScriptContext(WebKit::WebFrame* frame,
612                                        v8::Handle<v8::Context>,
613                                        int world_id);
614  virtual void didChangeScrollOffset(WebKit::WebFrame* frame);
615  virtual void willInsertBody(WebKit::WebFrame* frame);
616  virtual void didFirstVisuallyNonEmptyLayout(WebKit::WebFrame*);
617  virtual void didChangeContentsSize(WebKit::WebFrame* frame,
618                                     const WebKit::WebSize& size);
619  virtual void reportFindInPageMatchCount(int request_id,
620                                          int count,
621                                          bool final_update);
622  virtual void reportFindInPageSelection(int request_id,
623                                         int active_match_ordinal,
624                                         const WebKit::WebRect& sel);
625  virtual void requestStorageQuota(
626      WebKit::WebFrame* frame,
627      WebKit::WebStorageQuotaType type,
628      unsigned long long requested_size,
629      WebKit::WebStorageQuotaCallbacks* callbacks);
630  virtual void willOpenSocketStream(
631      WebKit::WebSocketStreamHandle* handle);
632  virtual void willStartUsingPeerConnectionHandler(WebKit::WebFrame* frame,
633      WebKit::WebRTCPeerConnectionHandler* handler);
634  virtual bool willCheckAndDispatchMessageEvent(
635      WebKit::WebFrame* sourceFrame,
636      WebKit::WebFrame* targetFrame,
637      WebKit::WebSecurityOrigin targetOrigin,
638      WebKit::WebDOMMessageEvent event);
639  virtual WebKit::WebString acceptLanguages();
640  virtual WebKit::WebString userAgentOverride(
641      WebKit::WebFrame* frame,
642      const WebKit::WebURL& url);
643  virtual WebKit::WebString doNotTrackValue(WebKit::WebFrame* frame);
644  virtual bool allowWebGL(WebKit::WebFrame* frame, bool default_value);
645  virtual void didLoseWebGLContext(
646      WebKit::WebFrame* frame,
647      int arb_robustness_status_code);
648
649  // WebKit::WebPageSerializerClient implementation ----------------------------
650
651  virtual void didSerializeDataForFrame(
652      const WebKit::WebURL& frame_url,
653      const WebKit::WebCString& data,
654      PageSerializationStatus status) OVERRIDE;
655
656  // RenderView implementation -------------------------------------------------
657
658  virtual bool Send(IPC::Message* message) OVERRIDE;
659  virtual int GetRoutingID() const OVERRIDE;
660  virtual int GetPageId() const OVERRIDE;
661  virtual gfx::Size GetSize() const OVERRIDE;
662  virtual WebPreferences& GetWebkitPreferences() OVERRIDE;
663  virtual void SetWebkitPreferences(const WebPreferences& preferences) OVERRIDE;
664  virtual WebKit::WebView* GetWebView() OVERRIDE;
665  virtual WebKit::WebNode GetFocusedNode() const OVERRIDE;
666  virtual WebKit::WebNode GetContextMenuNode() const OVERRIDE;
667  virtual bool IsEditableNode(const WebKit::WebNode& node) const OVERRIDE;
668  virtual WebKit::WebPlugin* CreatePlugin(
669      WebKit::WebFrame* frame,
670      const WebPluginInfo& info,
671      const WebKit::WebPluginParams& params) OVERRIDE;
672  virtual void EvaluateScript(const string16& frame_xpath,
673                              const string16& jscript,
674                              int id,
675                              bool notify_result) OVERRIDE;
676  virtual bool ShouldDisplayScrollbars(int width, int height) const OVERRIDE;
677  virtual int GetEnabledBindings() const OVERRIDE;
678  virtual bool GetContentStateImmediately() const OVERRIDE;
679  virtual float GetFilteredTimePerFrame() const OVERRIDE;
680  virtual int ShowContextMenu(ContextMenuClient* client,
681                              const ContextMenuParams& params) OVERRIDE;
682  virtual void CancelContextMenu(int request_id) OVERRIDE;
683  virtual WebKit::WebPageVisibilityState GetVisibilityState() const OVERRIDE;
684  virtual void RunModalAlertDialog(WebKit::WebFrame* frame,
685                                   const WebKit::WebString& message) OVERRIDE;
686  virtual void LoadURLExternally(
687      WebKit::WebFrame* frame,
688      const WebKit::WebURLRequest& request,
689      WebKit::WebNavigationPolicy policy) OVERRIDE;
690  virtual void DidStartLoading() OVERRIDE;
691  virtual void DidStopLoading() OVERRIDE;
692  virtual void Repaint(const gfx::Size& size) OVERRIDE;
693  virtual void SetEditCommandForNextKeyEvent(const std::string& name,
694                                             const std::string& value) OVERRIDE;
695  virtual void ClearEditCommands() OVERRIDE;
696  virtual SSLStatus GetSSLStatusOfFrame(WebKit::WebFrame* frame) const OVERRIDE;
697#if defined(OS_ANDROID)
698  virtual void UpdateTopControlsState(TopControlsState constraints,
699                                      TopControlsState current,
700                                      bool animate) OVERRIDE;
701#endif
702
703  // WebMediaPlayerDelegate implementation -----------------------
704
705  virtual void DidPlay(WebKit::WebMediaPlayer* player) OVERRIDE;
706  virtual void DidPause(WebKit::WebMediaPlayer* player) OVERRIDE;
707  virtual void PlayerGone(WebKit::WebMediaPlayer* player) OVERRIDE;
708
709  // Please do not add your stuff randomly to the end here. If there is an
710  // appropriate section, add it there. If not, there are some random functions
711  // nearer to the top you can add it to.
712
713  // Cannot use std::set unfortunately since linked_ptr<> does not support
714  // operator<.
715  typedef std::vector<linked_ptr<ImageResourceFetcher> >
716      ImageResourceFetcherList;
717
718 protected:
719  // RenderWidget overrides:
720  virtual void Close() OVERRIDE;
721  virtual void OnResize(const ViewMsg_Resize_Params& params) OVERRIDE;
722  virtual void WillInitiatePaint() OVERRIDE;
723  virtual void DidInitiatePaint() OVERRIDE;
724  virtual void DidFlushPaint() OVERRIDE;
725  virtual PepperPluginInstanceImpl* GetBitmapForOptimizedPluginPaint(
726      const gfx::Rect& paint_bounds,
727      TransportDIB** dib,
728      gfx::Rect* location,
729      gfx::Rect* clip,
730      float* scale_factor) OVERRIDE;
731  virtual gfx::Vector2d GetScrollOffset() OVERRIDE;
732  virtual void DidHandleKeyEvent() OVERRIDE;
733  virtual bool WillHandleMouseEvent(
734      const WebKit::WebMouseEvent& event) OVERRIDE;
735  virtual bool WillHandleKeyEvent(
736      const WebKit::WebKeyboardEvent& event) OVERRIDE;
737  virtual bool WillHandleGestureEvent(
738      const WebKit::WebGestureEvent& event) OVERRIDE;
739  virtual void DidHandleMouseEvent(const WebKit::WebMouseEvent& event) OVERRIDE;
740  virtual void DidHandleTouchEvent(const WebKit::WebTouchEvent& event) OVERRIDE;
741  virtual bool HasTouchEventHandlersAt(const gfx::Point& point) const OVERRIDE;
742  virtual void OnSetFocus(bool enable) OVERRIDE;
743  virtual void OnWasHidden() OVERRIDE;
744  virtual void OnWasShown(bool needs_repainting) OVERRIDE;
745  virtual GURL GetURLForGraphicsContext3D() OVERRIDE;
746  virtual bool ForceCompositingModeEnabled() OVERRIDE;
747  virtual void OnImeSetComposition(
748      const string16& text,
749      const std::vector<WebKit::WebCompositionUnderline>& underlines,
750      int selection_start,
751      int selection_end) OVERRIDE;
752  virtual void OnImeConfirmComposition(const string16& text,
753                                       const gfx::Range& replacement_range,
754                                       bool keep_selection) OVERRIDE;
755  virtual void SetDeviceScaleFactor(float device_scale_factor) OVERRIDE;
756  virtual ui::TextInputType GetTextInputType() OVERRIDE;
757  virtual void GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) OVERRIDE;
758#if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
759  virtual void GetCompositionCharacterBounds(
760      std::vector<gfx::Rect>* character_bounds) OVERRIDE;
761  virtual void GetCompositionRange(gfx::Range* range) OVERRIDE;
762#endif
763  virtual bool CanComposeInline() OVERRIDE;
764  virtual void DidCommitCompositorFrame() OVERRIDE;
765  virtual void InstrumentWillBeginFrame() OVERRIDE;
766  virtual void InstrumentDidBeginFrame() OVERRIDE;
767  virtual void InstrumentDidCancelFrame() OVERRIDE;
768  virtual void InstrumentWillComposite() OVERRIDE;
769  virtual bool AllowPartialSwap() const OVERRIDE;
770
771 protected:
772  explicit RenderViewImpl(RenderViewImplParams* params);
773
774  void Initialize(RenderViewImplParams* params);
775
776  // Do not delete directly.  This class is reference counted.
777  virtual ~RenderViewImpl();
778
779 private:
780  // For unit tests.
781  friend class ExternalPopupMenuTest;
782  friend class PepperDeviceTest;
783  friend class RendererAccessibilityTest;
784  friend class RenderViewTest;
785
786  // TODO(nasko): Temporarily friend RenderFrameImpl, so we don't duplicate
787  // utility functions needed in both classes, while we move frame specific
788  // code away from this class.
789  friend class RenderFrameImpl;
790
791  FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuRemoveTest, RemoveOnChange);
792  FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuTest, NormalCase);
793  FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuTest, ShowPopupThenNavigate);
794  FRIEND_TEST_ALL_PREFIXES(RendererAccessibilityTest,
795                           AccessibilityMessagesQueueWhileSwappedOut);
796  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, DecideNavigationPolicyForWebUI);
797  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
798                           DidFailProvisionalLoadWithErrorForError);
799  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
800                           DidFailProvisionalLoadWithErrorForCancellation);
801  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
802                           DontIgnoreBackAfterNavEntryLimit);
803  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, ImeComposition);
804  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, InsertCharacters);
805  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, JSBlockSentAfterPageLoad);
806  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, LastCommittedUpdateState);
807  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnExtendSelectionAndDelete);
808  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnHandleKeyboardEvent);
809  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnImeTypeChanged);
810  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnNavStateChanged);
811  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnSetTextDirection);
812  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnUpdateWebPreferences);
813  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, SendSwapOutACK);
814  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, ReloadWhileSwappedOut);
815  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
816                           SetEditableSelectionAndComposition);
817  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, StaleNavigationsIgnored);
818  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, UpdateTargetURLWithInvalidURL);
819  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
820                           GetCompositionCharacterBoundsTest);
821  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnNavigationHttpPost);
822#if defined(OS_MACOSX)
823  FRIEND_TEST_ALL_PREFIXES(RenderViewTest, MacTestCmdUp);
824#endif
825  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, SetHistoryLengthAndPrune);
826  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, ZoomLimit);
827  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, NavigateFrame);
828  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest,
829                           ShouldUpdateSelectionTextFromContextMenuParams);
830  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, BasicRenderFrame);
831  FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, TextInputTypeWithPepper);
832
833  typedef std::map<GURL, double> HostZoomLevels;
834
835  enum ErrorPageType {
836    DNS_ERROR,
837    HTTP_404,
838    CONNECTION_ERROR,
839  };
840
841  static WebKit::WebReferrerPolicy GetReferrerPolicyFromRequest(
842      WebKit::WebFrame* frame,
843      const WebKit::WebURLRequest& request);
844
845  static Referrer GetReferrerFromRequest(
846      WebKit::WebFrame* frame,
847      const WebKit::WebURLRequest& request);
848
849  static webkit_glue::WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
850      const WebKit::WebURLResponse& response);
851
852  void UpdateURL(WebKit::WebFrame* frame);
853  void UpdateTitle(WebKit::WebFrame* frame, const string16& title,
854                   WebKit::WebTextDirection title_direction);
855  void UpdateSessionHistory(WebKit::WebFrame* frame);
856  void SendUpdateState(const WebKit::WebHistoryItem& item);
857
858  // Update current main frame's encoding and send it to browser window.
859  // Since we want to let users see the right encoding info from menu
860  // before finishing loading, we call the UpdateEncoding in
861  // a) function:DidCommitLoadForFrame. When this function is called,
862  // that means we have got first data. In here we try to get encoding
863  // of page if it has been specified in http header.
864  // b) function:DidReceiveTitle. When this function is called,
865  // that means we have got specified title. Because in most of webpages,
866  // title tags will follow meta tags. In here we try to get encoding of
867  // page if it has been specified in meta tag.
868  // c) function:DidFinishDocumentLoadForFrame. When this function is
869  // called, that means we have got whole html page. In here we should
870  // finally get right encoding of page.
871  void UpdateEncoding(WebKit::WebFrame* frame,
872                      const std::string& encoding_name);
873
874  void OpenURL(WebKit::WebFrame* frame,
875               const GURL& url,
876               const Referrer& referrer,
877               WebKit::WebNavigationPolicy policy);
878
879  bool RunJavaScriptMessage(JavaScriptMessageType type,
880                            const string16& message,
881                            const string16& default_value,
882                            const GURL& frame_url,
883                            string16* result);
884
885  // Sends a message and runs a nested message loop.
886  bool SendAndRunNestedMessageLoop(IPC::SyncMessage* message);
887
888  // Called when the "pinned to left/right edge" state needs to be updated.
889  void UpdateScrollState(WebKit::WebFrame* frame);
890
891  // IPC message handlers ------------------------------------------------------
892  //
893  // The documentation for these functions should be in
894  // content/common/*_messages.h for the message that the function is handling.
895
896  void OnCopy();
897  void OnCut();
898  void OnDelete();
899  void OnExecuteEditCommand(const std::string& name, const std::string& value);
900  void OnMoveCaret(const gfx::Point& point);
901  void OnPaste();
902  void OnPasteAndMatchStyle();
903  void OnRedo();
904  void OnReplace(const string16& text);
905  void OnReplaceMisspelling(const string16& text);
906  void OnScrollFocusedEditableNodeIntoRect(const gfx::Rect& rect);
907  void OnSelectAll();
908  void OnSelectRange(const gfx::Point& start, const gfx::Point& end);
909  void OnSetEditCommandsForNextKeyEvent(const EditCommands& edit_commands);
910  void OnUndo();
911  void OnUnselect();
912
913  void OnAllowBindings(int enabled_bindings_flags);
914  void OnAllowScriptToClose(bool script_can_close);
915  void OnCancelDownload(int32 download_id);
916  void OnClearFocusedNode();
917  void OnClosePage();
918  void OnContextMenuClosed(const CustomContextMenuContext& custom_context);
919  void OnShowContextMenu(const gfx::Point& location);
920  void OnCopyImageAt(int x, int y);
921  void OnCSSInsertRequest(const string16& frame_xpath,
922                          const std::string& css);
923  void OnCustomContextMenuAction(const CustomContextMenuContext& custom_context,
924      unsigned action);
925  void OnSetName(const std::string& name);
926  void OnDeterminePageLanguage();
927  void OnDisableScrollbarsForSmallWindows(
928      const gfx::Size& disable_scrollbars_size_limit);
929  void OnDragSourceEndedOrMoved(const gfx::Point& client_point,
930                                const gfx::Point& screen_point,
931                                bool ended,
932                                WebKit::WebDragOperation drag_operation);
933  void OnDragSourceSystemDragEnded();
934  void OnDragTargetDrop(const gfx::Point& client_pt,
935                        const gfx::Point& screen_pt,
936                        int key_modifiers);
937  void OnDragTargetDragEnter(const DropData& drop_data,
938                             const gfx::Point& client_pt,
939                             const gfx::Point& screen_pt,
940                             WebKit::WebDragOperationsMask operations_allowed,
941                             int key_modifiers);
942  void OnDragTargetDragLeave();
943  void OnDragTargetDragOver(const gfx::Point& client_pt,
944                            const gfx::Point& screen_pt,
945                            WebKit::WebDragOperationsMask operations_allowed,
946                            int key_modifiers);
947  void OnEnablePreferredSizeChangedMode();
948  void OnEnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size);
949  void OnDisableAutoResize(const gfx::Size& new_size);
950  void OnEnumerateDirectoryResponse(int id,
951                                    const std::vector<base::FilePath>& paths);
952  void OnExtendSelectionAndDelete(int before, int after);
953  void OnFileChooserResponse(
954      const std::vector<ui::SelectedFileInfo>& files);
955  void OnFind(int request_id, const string16&, const WebKit::WebFindOptions&);
956  void OnGetAllSavableResourceLinksForCurrentPage(const GURL& page_url);
957  void OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
958      const std::vector<GURL>& links,
959      const std::vector<base::FilePath>& local_paths,
960      const base::FilePath& local_directory_name);
961  void OnMediaPlayerActionAt(const gfx::Point& location,
962                             const WebKit::WebMediaPlayerAction& action);
963
964  // Screen has rotated. 0 = default (portrait), 90 = one turn right, and so on.
965  void OnOrientationChangeEvent(int orientation);
966
967  void OnPluginActionAt(const gfx::Point& location,
968                        const WebKit::WebPluginAction& action);
969  void OnMoveOrResizeStarted();
970  void OnNavigate(const ViewMsg_Navigate_Params& params);
971  void OnPostMessageEvent(const ViewMsg_PostMessage_Params& params);
972  void OnReleaseDisambiguationPopupDIB(TransportDIB::Handle dib_handle);
973  void OnReloadFrame();
974  void OnResetPageEncodingToDefault();
975  void OnScriptEvalRequest(const string16& frame_xpath,
976                           const string16& jscript,
977                           int id,
978                           bool notify_result);
979  void OnSetAccessibilityMode(AccessibilityMode new_mode);
980  void OnSetActive(bool active);
981  void OnSetAltErrorPageURL(const GURL& gurl);
982  void OnSetBackground(const SkBitmap& background);
983  void OnSetCompositionFromExistingText(
984      int start, int end,
985      const std::vector<WebKit::WebCompositionUnderline>& underlines);
986  void OnExitFullscreen();
987  void OnSetEditableSelectionOffsets(int start, int end);
988  void OnSetHistoryLengthAndPrune(int history_length, int32 minimum_page_id);
989  void OnSetInitialFocus(bool reverse);
990  void OnSetPageEncoding(const std::string& encoding_name);
991  void OnSetRendererPrefs(const RendererPreferences& renderer_prefs);
992  void OnSetWebUIProperty(const std::string& name, const std::string& value);
993  void OnSetZoomLevel(double zoom_level);
994  void OnSetZoomLevelForLoadingURL(const GURL& url, double zoom_level);
995  void OnShouldClose();
996  void OnStop();
997  void OnStopFinding(StopFindAction action);
998  void OnSwapOut();
999  void OnThemeChanged();
1000  void OnUpdateTargetURLAck();
1001  void OnUpdateTimezone();
1002  void OnUpdateWebPreferences(const WebPreferences& prefs);
1003
1004  void OnZoom(PageZoom zoom);
1005  void OnZoomFactor(PageZoom zoom, int zoom_center_x, int zoom_center_y);
1006
1007  void OnEnableViewSourceMode();
1008
1009  void OnJavaBridgeInit();
1010
1011  void OnDisownOpener();
1012
1013#if defined(OS_ANDROID)
1014  void OnActivateNearestFindResult(int request_id, float x, float y);
1015  void OnFindMatchRects(int current_version);
1016  void OnSelectPopupMenuItems(bool canceled,
1017                              const std::vector<int>& selected_indices);
1018  void OnUndoScrollFocusedEditableNodeIntoRect();
1019  void OnUpdateTopControlsState(bool enable_hiding,
1020                                bool enable_showing,
1021                                bool animate);
1022#elif defined(OS_MACOSX)
1023  void OnCopyToFindPboard();
1024  void OnPluginImeCompositionCompleted(const string16& text, int plugin_id);
1025  void OnSelectPopupMenuItem(int selected_index);
1026  void OnSetInLiveResize(bool in_live_resize);
1027  void OnSetWindowVisibility(bool visible);
1028  void OnWindowFrameChanged(const gfx::Rect& window_frame,
1029                            const gfx::Rect& view_frame);
1030#endif
1031
1032  void OnWindowSnapshotCompleted(const int snapshot_id,
1033      const gfx::Size& size, const std::vector<unsigned char>& png);
1034
1035
1036  // Adding a new message handler? Please add it in alphabetical order above
1037  // and put it in the same position in the .cc file.
1038
1039  // Misc private functions ----------------------------------------------------
1040  void ZoomFactorHelper(PageZoom zoom, int zoom_center_x, int zoom_center_y,
1041                        float scaling_increment);
1042
1043  void AltErrorPageFinished(WebKit::WebFrame* frame,
1044                            const WebKit::WebURLRequest& original_request,
1045                            const WebKit::WebURLError& original_error,
1046                            const std::string& html);
1047
1048  // Check whether the preferred size has changed.
1049  void CheckPreferredSize();
1050
1051  // Initializes |media_stream_client_|, returning true if successful. Returns
1052  // false if it wasn't possible to create a MediaStreamClient (e.g., WebRTC is
1053  // disabled) in which case |media_stream_client_| is NULL.
1054  bool InitializeMediaStreamClient();
1055
1056  // This callback is triggered when DownloadFavicon completes, either
1057  // succesfully or with a failure. See DownloadFavicon for more
1058  // details.
1059  void DidDownloadFavicon(ImageResourceFetcher* fetcher,
1060                          const SkBitmap& image);
1061
1062  // Requests to download a favicon image. When done, the RenderView is notified
1063  // by way of DidDownloadFavicon. Returns true if the request was successfully
1064  // started, false otherwise. id is used to uniquely identify the request and
1065  // passed back to the DidDownloadFavicon method. If the image has multiple
1066  // frames, the frame whose size is image_size is returned. If the image
1067  // doesn't have a frame at the specified size, the first is returned.
1068  bool DownloadFavicon(int id, const GURL& image_url, int image_size);
1069
1070  GURL GetAlternateErrorPageURL(const GURL& failed_url,
1071                                ErrorPageType error_type);
1072
1073  // Locates a sub frame with given xpath
1074  WebKit::WebFrame* GetChildFrame(const string16& frame_xpath) const;
1075
1076  // Returns the URL being loaded by the given frame's request.
1077  GURL GetLoadingUrl(WebKit::WebFrame* frame) const;
1078
1079  // Should only be called if this object wraps a PluginDocument.
1080  WebKit::WebPlugin* GetWebPluginFromPluginDocument();
1081
1082  // Returns true if the |params| navigation is to an entry that has been
1083  // cropped due to a recent navigation the browser did not know about.
1084  bool IsBackForwardToStaleEntry(const ViewMsg_Navigate_Params& params,
1085                                 bool is_reload);
1086
1087  bool MaybeLoadAlternateErrorPage(WebKit::WebFrame* frame,
1088                                   const WebKit::WebURLError& error,
1089                                   bool replace);
1090
1091  // Make this RenderView show an empty, unscriptable page.
1092  void NavigateToSwappedOutURL(WebKit::WebFrame* frame);
1093
1094  // If we initiated a navigation, this function will populate |document_state|
1095  // with the navigation information saved in OnNavigate().
1096  void PopulateDocumentStateFromPending(DocumentState* document_state);
1097
1098  // Returns a new NavigationState populated with the navigation information
1099  // saved in OnNavigate().
1100  NavigationState* CreateNavigationStateFromPending();
1101
1102  // Processes the command-line flags --enable-viewport,
1103  // --enable-fixed-layout[=w,h] and --enable-pinch.
1104  void ProcessViewLayoutFlags(const CommandLine& command_line);
1105
1106#if defined(OS_ANDROID)
1107  // Launch an Android content intent with the given URL.
1108  void LaunchAndroidContentIntent(const GURL& intent_url, size_t request_id);
1109#endif
1110
1111  // Sends a reply to the current find operation handling if it was a
1112  // synchronous find request.
1113  void SendFindReply(int request_id,
1114                     int match_count,
1115                     int ordinal,
1116                     const WebKit::WebRect& selection_rect,
1117                     bool final_status_update);
1118
1119  // Returns whether |params.selection_text| should be synchronized to the
1120  // browser before bringing up the context menu. Static for testing.
1121  static bool ShouldUpdateSelectionTextFromContextMenuParams(
1122      const string16& selection_text,
1123      size_t selection_text_offset,
1124      const gfx::Range& selection_range,
1125      const ContextMenuParams& params);
1126
1127  // Starts nav_state_sync_timer_ if it isn't already running.
1128  void StartNavStateSyncTimerIfNecessary();
1129
1130  // Dispatches the current state of selection on the webpage to the browser if
1131  // it has changed.
1132  // TODO(varunjain): delete this method once we figure out how to keep
1133  // selection handles in sync with the webpage.
1134  void SyncSelectionIfRequired();
1135
1136#if defined(OS_POSIX) && !defined(OS_MACOSX)
1137  void UpdateFontRenderingFromRendererPrefs();
1138#else
1139  void UpdateFontRenderingFromRendererPrefs() {}
1140#endif
1141
1142  // Update the target url and tell the browser that the target URL has changed.
1143  // If |url| is empty, show |fallback_url|.
1144  void UpdateTargetURL(const GURL& url, const GURL& fallback_url);
1145
1146  // Tells the browser what the new list of favicons for the webpage is.
1147  void SendUpdateFaviconURL(const std::vector<FaviconURL>& urls);
1148
1149  // Invoked from DidStopLoading(). Sends the current list of loaded favicons to
1150  // the browser.
1151  void DidStopLoadingIcons();
1152
1153  // Coordinate conversion -----------------------------------------------------
1154
1155  gfx::RectF ClientRectToPhysicalWindowRect(const gfx::RectF& rect) const;
1156
1157  // ---------------------------------------------------------------------------
1158  // ADDING NEW FUNCTIONS? Please keep private functions alphabetized and put
1159  // it in the same order in the .cc file as it was in the header.
1160  // ---------------------------------------------------------------------------
1161
1162  // Settings ------------------------------------------------------------------
1163
1164  WebPreferences webkit_preferences_;
1165  RendererPreferences renderer_preferences_;
1166
1167  HostZoomLevels host_zoom_levels_;
1168
1169  // Whether content state (such as form state, scroll position and page
1170  // contents) should be sent to the browser immediately. This is normally
1171  // false, but set to true by some tests.
1172  bool send_content_state_immediately_;
1173
1174  // Bitwise-ORed set of extra bindings that have been enabled.  See
1175  // BindingsPolicy for details.
1176  int enabled_bindings_;
1177
1178  // The alternate error page URL, if one exists.
1179  GURL alternate_error_page_url_;
1180
1181  // If true, we send IPC messages when |preferred_size_| changes.
1182  bool send_preferred_size_changes_;
1183
1184  // If non-empty, and |send_preferred_size_changes_| is true, disable drawing
1185  // scroll bars on windows smaller than this size.  Used for windows that the
1186  // browser resizes to the size of the content, such as browser action popups.
1187  // If a render view is set to the minimum size of its content, webkit may add
1188  // scroll bars.  This makes sense for fixed sized windows, but it does not
1189  // make sense when the size of the view was chosen to fit the content.
1190  // This setting ensures that no scroll bars are drawn.  The size limit exists
1191  // because if the view grows beyond a size known to the browser, scroll bars
1192  // should be drawn.
1193  gfx::Size disable_scrollbars_size_limit_;
1194
1195  // Loading state -------------------------------------------------------------
1196
1197  // True if the top level frame is currently being loaded.
1198  bool is_loading_;
1199
1200  // The gesture that initiated the current navigation.
1201  NavigationGesture navigation_gesture_;
1202
1203  // Used for popups.
1204  bool opened_by_user_gesture_;
1205
1206  // Whether this RenderView was created by a frame that was suppressing its
1207  // opener. If so, we may want to load pages in a separate process.  See
1208  // decidePolicyForNavigation for details.
1209  bool opener_suppressed_;
1210
1211  // Holds state pertaining to a navigation that we initiated.  This is held by
1212  // the WebDataSource::ExtraData attribute.  We use pending_navigation_state_
1213  // as a temporary holder for the state until the WebDataSource corresponding
1214  // to the new navigation is created.  See DidCreateDataSource.
1215  scoped_ptr<ViewMsg_Navigate_Params> pending_navigation_params_;
1216
1217  // Timer used to delay the updating of nav state (see SyncNavigationState).
1218  base::OneShotTimer<RenderViewImpl> nav_state_sync_timer_;
1219
1220  // Page IDs ------------------------------------------------------------------
1221  // See documentation in RenderView.
1222  int32 page_id_;
1223
1224  // Indicates the ID of the last page that we sent a FrameNavigate to the
1225  // browser for. This is used to determine if the most recent transition
1226  // generated a history entry (less than page_id_), or not (equal to or
1227  // greater than). Note that this will be greater than page_id_ if the user
1228  // goes back.
1229  int32 last_page_id_sent_to_browser_;
1230
1231  // The next available page ID to use for this RenderView.  These IDs are
1232  // specific to a given RenderView and the frames within it.
1233  int32 next_page_id_;
1234
1235  // The offset of the current item in the history list.
1236  int history_list_offset_;
1237
1238  // The RenderView's current impression of the history length.  This includes
1239  // any items that have committed in this process, but because of cross-process
1240  // navigations, the history may have some entries that were committed in other
1241  // processes.  We won't know about them until the next navigation in this
1242  // process.
1243  int history_list_length_;
1244
1245  // The list of page IDs for each history item this RenderView knows about.
1246  // Some entries may be -1 if they were rendered by other processes or were
1247  // restored from a previous session.  This lets us detect attempts to
1248  // navigate to stale entries that have been cropped from our history.
1249  std::vector<int32> history_page_ids_;
1250
1251  // Page info -----------------------------------------------------------------
1252
1253  // The last gotten main frame's encoding.
1254  std::string last_encoding_name_;
1255
1256  // UI state ------------------------------------------------------------------
1257
1258  // The state of our target_url transmissions. When we receive a request to
1259  // send a URL to the browser, we set this to TARGET_INFLIGHT until an ACK
1260  // comes back - if a new request comes in before the ACK, we store the new
1261  // URL in pending_target_url_ and set the status to TARGET_PENDING. If an
1262  // ACK comes back and we are in TARGET_PENDING, we send the stored URL and
1263  // revert to TARGET_INFLIGHT.
1264  //
1265  // We don't need a queue of URLs to send, as only the latest is useful.
1266  enum {
1267    TARGET_NONE,
1268    TARGET_INFLIGHT,  // We have a request in-flight, waiting for an ACK
1269    TARGET_PENDING    // INFLIGHT + we have a URL waiting to be sent
1270  } target_url_status_;
1271
1272  // The URL we show the user in the status bar. We use this to determine if we
1273  // want to send a new one (we do not need to send duplicates). It will be
1274  // equal to either |mouse_over_url_| or |focus_url_|, depending on which was
1275  // updated last.
1276  GURL target_url_;
1277
1278  // The URL the user's mouse is hovering over.
1279  GURL mouse_over_url_;
1280
1281  // The URL that has keyboard focus.
1282  GURL focus_url_;
1283
1284  // The next target URL we want to send to the browser.
1285  GURL pending_target_url_;
1286
1287  // The text selection the last time DidChangeSelection got called. May contain
1288  // additional characters before and after the selected text, for IMEs. The
1289  // portion of this string that is the actual selected text starts at index
1290  // |selection_range_.GetMin() - selection_text_offset_| and has length
1291  // |selection_range_.length()|.
1292  string16 selection_text_;
1293  // The offset corresponding to the start of |selection_text_| in the document.
1294  size_t selection_text_offset_;
1295  // Range over the document corresponding to the actual selected text (which
1296  // could correspond to a substring of |selection_text_|; see above).
1297  gfx::Range selection_range_;
1298
1299  // External context menu requests we're waiting for. "Internal"
1300  // (WebKit-originated) context menu events will have an ID of 0 and will not
1301  // be in this map.
1302  //
1303  // We don't want to add internal ones since some of the "special" page
1304  // handlers in the browser process just ignore the context menu requests so
1305  // avoid showing context menus, and so this will cause right clicks to leak
1306  // entries in this map. Most users of the custom context menu (e.g. Pepper
1307  // plugins) are normally only on "regular" pages and the regular pages will
1308  // always respond properly to the request, so we don't have to worry so
1309  // much about leaks.
1310  IDMap<ContextMenuClient, IDMapExternalPointer> pending_context_menus_;
1311
1312#if defined(OS_ANDROID)
1313  // Cache the old top controls state constraints. Used when updating
1314  // current value only without altering the constraints.
1315  cc::TopControlsState top_controls_constraints_;
1316#endif
1317
1318  // View ----------------------------------------------------------------------
1319
1320  // Cache the preferred size of the page in order to prevent sending the IPC
1321  // when layout() recomputes but doesn't actually change sizes.
1322  gfx::Size preferred_size_;
1323
1324  // Used to delay determining the preferred size (to avoid intermediate
1325  // states for the sizes).
1326  base::OneShotTimer<RenderViewImpl> check_preferred_size_timer_;
1327
1328  // These store the "is main frame is scrolled all the way to the left
1329  // or right" state that was last sent to the browser.
1330  bool cached_is_main_frame_pinned_to_left_;
1331  bool cached_is_main_frame_pinned_to_right_;
1332
1333  // These store the "has scrollbars" state last sent to the browser.
1334  bool cached_has_main_frame_horizontal_scrollbar_;
1335  bool cached_has_main_frame_vertical_scrollbar_;
1336
1337  // Helper objects ------------------------------------------------------------
1338
1339  scoped_ptr<RenderFrameImpl> main_render_frame_;
1340
1341  RendererWebCookieJarImpl cookie_jar_;
1342
1343  // The next group of objects all implement RenderViewObserver, so are deleted
1344  // along with the RenderView automatically.  This is why we just store
1345  // weak references.
1346
1347  // Holds a reference to the service which provides desktop notifications.
1348  NotificationProvider* notification_provider_;
1349
1350  // The geolocation dispatcher attached to this view, lazily initialized.
1351  GeolocationDispatcher* geolocation_dispatcher_;
1352
1353  // The speech dispatcher attached to this view, lazily initialized.
1354  InputTagSpeechDispatcher* input_tag_speech_dispatcher_;
1355
1356  // The speech recognition dispatcher attached to this view, lazily
1357  // initialized.
1358  SpeechRecognitionDispatcher* speech_recognition_dispatcher_;
1359
1360  // Device orientation dispatcher attached to this view; lazily initialized.
1361  DeviceOrientationDispatcher* device_orientation_dispatcher_;
1362
1363  // MediaStream dispatcher attached to this view; lazily initialized.
1364  MediaStreamDispatcher* media_stream_dispatcher_;
1365
1366  // BrowserPluginManager attached to this view; lazily initialized.
1367  scoped_refptr<BrowserPluginManager> browser_plugin_manager_;
1368
1369  // MediaStreamClient attached to this view; lazily initialized.
1370  MediaStreamClient* media_stream_client_;
1371  WebKit::WebUserMediaClient* web_user_media_client_;
1372
1373  // MIDIClient attached to this view; lazily initialized.
1374  MIDIDispatcher* midi_dispatcher_;
1375
1376  DevToolsAgent* devtools_agent_;
1377
1378  // The current accessibility mode.
1379  AccessibilityMode accessibility_mode_;
1380
1381  // Only valid if |accessibility_mode_| is anything other than
1382  // AccessibilityModeOff.
1383  RendererAccessibility* renderer_accessibility_;
1384
1385  // Java Bridge dispatcher attached to this view; lazily initialized.
1386  JavaBridgeDispatcher* java_bridge_dispatcher_;
1387
1388  // Mouse Lock dispatcher attached to this view.
1389  MouseLockDispatcher* mouse_lock_dispatcher_;
1390
1391#if defined(OS_ANDROID)
1392  // Android Specific ---------------------------------------------------------
1393
1394  // The background color of the document body element. This is used as the
1395  // default background color for filling the screen areas for which we don't
1396  // have the actual content.
1397  SkColor body_background_color_;
1398
1399  // Expected id of the next content intent launched. Used to prevent scheduled
1400  // intents to be launched if aborted.
1401  size_t expected_content_intent_id_;
1402
1403  // List of click-based content detectors.
1404  typedef std::vector< linked_ptr<ContentDetector> > ContentDetectorList;
1405  ContentDetectorList content_detectors_;
1406
1407  // Proxy class for WebMediaPlayer to communicate with the real media player
1408  // objects in browser process.
1409  WebMediaPlayerProxyAndroid* media_player_proxy_;
1410
1411  // The media player manager for managing all the media players on this view.
1412  scoped_ptr<RendererMediaPlayerManager> media_player_manager_;
1413
1414  // A date/time picker object for date and time related input elements.
1415  scoped_ptr<RendererDateTimePicker> date_time_picker_client_;
1416#endif
1417
1418  // Plugins -------------------------------------------------------------------
1419
1420  // All the currently active plugin delegates for this RenderView; kept so
1421  // that we can enumerate them to send updates about things like window
1422  // location or tab focus and visibily. These are non-owning references.
1423  std::set<WebPluginDelegateProxy*> plugin_delegates_;
1424
1425#if defined(OS_WIN)
1426  // The ID of the focused NPAPI plug-in.
1427  int focused_plugin_id_;
1428#endif
1429
1430#if defined(ENABLE_PLUGINS)
1431  typedef std::set<PepperPluginInstanceImpl*> PepperPluginSet;
1432  PepperPluginSet active_pepper_instances_;
1433
1434  // Whether or not the focus is on a PPAPI plugin
1435  PepperPluginInstanceImpl* focused_pepper_plugin_;
1436
1437  // Current text input composition text. Empty if no composition is in
1438  // progress.
1439  string16 pepper_composition_text_;
1440
1441  // The plugin instance that received the last mouse event. It is set to NULL
1442  // if the last mouse event went to elements other than Pepper plugins.
1443  // |pepper_last_mouse_event_target_| is not owned by this class. We can know
1444  // about when it is destroyed via InstanceDeleted().
1445  PepperPluginInstanceImpl* pepper_last_mouse_event_target_;
1446#endif
1447
1448  // Misc ----------------------------------------------------------------------
1449
1450  // The current and pending file chooser completion objects. If the queue is
1451  // nonempty, the first item represents the currently running file chooser
1452  // callback, and the remaining elements are the other file chooser completion
1453  // still waiting to be run (in order).
1454  struct PendingFileChooser;
1455  std::deque< linked_ptr<PendingFileChooser> > file_chooser_completions_;
1456
1457  // The current directory enumeration callback
1458  std::map<int, WebKit::WebFileChooserCompletion*> enumeration_completions_;
1459  int enumeration_completion_id_;
1460
1461  // Reports load progress to the browser.
1462  scoped_ptr<LoadProgressTracker> load_progress_tracker_;
1463
1464  // The SessionStorage namespace that we're assigned to has an ID, and that ID
1465  // is passed to us upon creation.  WebKit asks for this ID upon first use and
1466  // uses it whenever asking the browser process to allocate new storage areas.
1467  int64 session_storage_namespace_id_;
1468
1469  // Stores edit commands associated to the next key event.
1470  // Shall be cleared as soon as the next key event is processed.
1471  EditCommands edit_commands_;
1472
1473  // The external popup for the currently showing select popup.
1474  scoped_ptr<ExternalPopupMenu> external_popup_menu_;
1475
1476  // The node that the context menu was pressed over.
1477  WebKit::WebNode context_menu_node_;
1478
1479  // All the registered observers.  We expect this list to be small, so vector
1480  // is fine.
1481  ObserverList<RenderViewObserver> observers_;
1482
1483  // Used to inform didChangeSelection() when it is called in the context
1484  // of handling a InputMsg_SelectRange IPC.
1485  bool handling_select_range_;
1486
1487  // Wraps the |webwidget_| as a MouseLockDispatcher::LockTarget interface.
1488  scoped_ptr<MouseLockDispatcher::LockTarget> webwidget_mouse_lock_target_;
1489
1490  // State associated with the GetWindowSnapshot function.
1491  int next_snapshot_id_;
1492  typedef std::map<int, WindowSnapshotCallback> PendingSnapshotMap;
1493  PendingSnapshotMap pending_snapshots_;
1494
1495  // Allows to selectively disable partial buffer swap for this renderer's
1496  // compositor.
1497  bool allow_partial_swap_;
1498
1499  // Allows JS to access DOM automation. The JS object is only exposed when the
1500  // DOM automation bindings are enabled.
1501  scoped_ptr<DomAutomationController> dom_automation_controller_;
1502
1503  // Allows JS to read out a variety of internal various metrics. The JS object
1504  // is only exposed when the stats collection bindings are enabled.
1505  scoped_ptr<StatsCollectionController> stats_collection_controller_;
1506
1507  // This field stores drag/drop related info for the event that is currently
1508  // being handled. If the current event results in starting a drag/drop
1509  // session, this info is sent to the browser along with other drag/drop info.
1510  DragEventSourceInfo possible_drag_event_info_;
1511
1512  // NOTE: stats_collection_observer_ should be the last members because their
1513  // constructors call the AddObservers method of RenderViewImpl.
1514  scoped_ptr<StatsCollectionObserver> stats_collection_observer_;
1515
1516  ui::MenuSourceType context_menu_source_type_;
1517  gfx::Point touch_editing_context_menu_location_;
1518
1519  // ---------------------------------------------------------------------------
1520  // ADDING NEW DATA? Please see if it fits appropriately in one of the above
1521  // sections rather than throwing it randomly at the end. If you're adding a
1522  // bunch of stuff, you should probably create a helper class and put your
1523  // data and methods on that to avoid bloating RenderView more.  You can
1524  // use the Observer interface to filter IPC messages and receive frame change
1525  // notifications.
1526  // ---------------------------------------------------------------------------
1527
1528  DISALLOW_COPY_AND_ASSIGN(RenderViewImpl);
1529};
1530
1531}  // namespace content
1532
1533#endif  // CONTENT_RENDERER_RENDER_VIEW_IMPL_H_
1534