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.
5 #ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_IMPL_H_
6 #define CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_IMPL_H_
12 #include "base/callback.h"
13 #include "base/compiler_specific.h"
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/process/kill.h"
17 #include "content/browser/renderer_host/render_widget_host_impl.h"
18 #include "content/browser/site_instance_impl.h"
19 #include "content/common/drag_event_source_info.h"
20 #include "content/public/browser/notification_observer.h"
21 #include "content/public/browser/render_view_host.h"
22 #include "content/public/common/window_container_type.h"
23 #include "net/base/load_states.h"
24 #include "third_party/WebKit/public/web/WebAXEnums.h"
25 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
26 #include "third_party/WebKit/public/web/WebPopupType.h"
27 #include "third_party/skia/include/core/SkColor.h"
28 #include "ui/base/window_open_disposition.h"
31 class FrameMsg_Navigate
;
32 struct FrameMsg_Navigate_Params
;
33 struct MediaPlayerAction
;
34 struct ViewHostMsg_CreateWindow_Params
;
35 struct ViewMsg_PostMessage_Params
;
47 struct SelectedFileInfo
;
52 class MediaWebContentsObserver
;
53 class ChildProcessSecurityPolicyImpl
;
55 class RenderWidgetHostDelegate
;
56 class SessionStorageNamespace
;
57 class SessionStorageNamespaceImpl
;
58 class TestRenderViewHost
;
60 struct FileChooserParams
;
62 #if defined(COMPILER_MSVC)
63 // RenderViewHostImpl is the bottom of a diamond-shaped hierarchy,
64 // with RenderWidgetHost at the root. VS warns when methods from the
65 // root are overridden in only one of the base classes and not both
66 // (in this case, RenderWidgetHostImpl provides implementations of
67 // many of the methods). This is a silly warning when dealing with
68 // pure virtual methods that only have a single implementation in the
69 // hierarchy above this class, and is safe to ignore in this case.
71 #pragma warning(disable: 4250)
74 // This implements the RenderViewHost interface that is exposed to
75 // embedders of content, and adds things only visible to content.
77 // The exact API of this object needs to be more thoroughly designed. Right
78 // now it mimics what WebContentsImpl exposed, which is a fairly large API and
79 // may contain things that are not relevant to a common subset of views. See
80 // also the comment in render_view_host_delegate.h about the size and scope of
83 // Right now, the concept of page navigation (both top level and frame) exists
84 // in the WebContentsImpl still, so if you instantiate one of these elsewhere,
85 // you will not be able to traverse pages back and forward. We need to determine
86 // if we want to bring that and other functionality down into this object so it
87 // can be shared by others.
88 class CONTENT_EXPORT RenderViewHostImpl
89 : public RenderViewHost
,
90 public RenderWidgetHostImpl
{
92 // Keeps track of the state of the RenderViewHostImpl, particularly with
93 // respect to swap out.
94 enum RenderViewHostImplState
{
95 // The standard state for a RVH handling the communication with a
98 // The RVH is waiting for the CloseACK from the RenderView.
99 STATE_WAITING_FOR_CLOSE
,
100 // The RVH has not received the SwapOutACK yet, but the new page has
101 // committed in a different RVH. The number of active views of the RVH
102 // SiteInstanceImpl is not zero. Upon reception of the SwapOutACK, the RVH
103 // will be swapped out.
104 STATE_PENDING_SWAP_OUT
,
105 // The RVH has not received the SwapOutACK yet, but the new page has
106 // committed in a different RVH. The number of active views of the RVH
107 // SiteInstanceImpl is zero. Upon reception of the SwapOutACK, the RVH will
109 STATE_PENDING_SHUTDOWN
,
110 // The RVH is swapped out, and it is being used as a placeholder to allow
111 // for cross-process communication.
114 // Helper function to determine whether the RVH state should contribute to the
115 // number of active views of a SiteInstance or not.
116 static bool IsRVHStateActive(RenderViewHostImplState rvh_state
);
118 // Convenience function, just like RenderViewHost::FromID.
119 static RenderViewHostImpl
* FromID(int render_process_id
, int render_view_id
);
121 // |routing_id| could be a valid route id, or it could be MSG_ROUTING_NONE, in
122 // which case RenderWidgetHost will create a new one. |swapped_out| indicates
123 // whether the view should initially be swapped out (e.g., for an opener
124 // frame being rendered by another process). |hidden| indicates whether the
125 // view is initially hidden or visible.
127 // The |session_storage_namespace| parameter allows multiple render views and
128 // WebContentses to share the same session storage (part of the WebStorage
129 // spec) space. This is useful when restoring contentses, but most callers
130 // should pass in NULL which will cause a new SessionStorageNamespace to be
133 SiteInstance
* instance
,
134 RenderViewHostDelegate
* delegate
,
135 RenderWidgetHostDelegate
* widget_delegate
,
137 int main_frame_routing_id
,
140 virtual ~RenderViewHostImpl();
142 // RenderViewHost implementation.
143 virtual RenderFrameHost
* GetMainFrame() OVERRIDE
;
144 virtual void AllowBindings(int binding_flags
) OVERRIDE
;
145 virtual void ClearFocusedElement() OVERRIDE
;
146 virtual bool IsFocusedElementEditable() OVERRIDE
;
147 virtual void ClosePage() OVERRIDE
;
148 virtual void CopyImageAt(int x
, int y
) OVERRIDE
;
149 virtual void SaveImageAt(int x
, int y
) OVERRIDE
;
150 virtual void DirectoryEnumerationFinished(
152 const std::vector
<base::FilePath
>& files
) OVERRIDE
;
153 virtual void DisableScrollbarsForThreshold(const gfx::Size
& size
) OVERRIDE
;
154 virtual void DragSourceEndedAt(
155 int client_x
, int client_y
, int screen_x
, int screen_y
,
156 blink::WebDragOperation operation
) OVERRIDE
;
157 virtual void DragSourceSystemDragEnded() OVERRIDE
;
158 virtual void DragTargetDragEnter(
159 const DropData
& drop_data
,
160 const gfx::Point
& client_pt
,
161 const gfx::Point
& screen_pt
,
162 blink::WebDragOperationsMask operations_allowed
,
163 int key_modifiers
) OVERRIDE
;
164 virtual void DragTargetDragOver(
165 const gfx::Point
& client_pt
,
166 const gfx::Point
& screen_pt
,
167 blink::WebDragOperationsMask operations_allowed
,
168 int key_modifiers
) OVERRIDE
;
169 virtual void DragTargetDragLeave() OVERRIDE
;
170 virtual void DragTargetDrop(const gfx::Point
& client_pt
,
171 const gfx::Point
& screen_pt
,
172 int key_modifiers
) OVERRIDE
;
173 virtual void EnableAutoResize(const gfx::Size
& min_size
,
174 const gfx::Size
& max_size
) OVERRIDE
;
175 virtual void DisableAutoResize(const gfx::Size
& new_size
) OVERRIDE
;
176 virtual void EnablePreferredSizeMode() OVERRIDE
;
177 virtual void ExecuteMediaPlayerActionAtLocation(
178 const gfx::Point
& location
,
179 const blink::WebMediaPlayerAction
& action
) OVERRIDE
;
180 virtual void ExecutePluginActionAtLocation(
181 const gfx::Point
& location
,
182 const blink::WebPluginAction
& action
) OVERRIDE
;
183 virtual void ExitFullscreen() OVERRIDE
;
184 virtual void FilesSelectedInChooser(
185 const std::vector
<ui::SelectedFileInfo
>& files
,
186 FileChooserParams::Mode permissions
) OVERRIDE
;
187 virtual RenderViewHostDelegate
* GetDelegate() const OVERRIDE
;
188 virtual int GetEnabledBindings() const OVERRIDE
;
189 virtual SiteInstance
* GetSiteInstance() const OVERRIDE
;
190 virtual bool IsRenderViewLive() const OVERRIDE
;
191 virtual void NotifyMoveOrResizeStarted() OVERRIDE
;
192 virtual void SetWebUIProperty(const std::string
& name
,
193 const std::string
& value
) OVERRIDE
;
194 virtual void Zoom(PageZoom zoom
) OVERRIDE
;
195 virtual void SyncRendererPrefs() OVERRIDE
;
196 virtual WebPreferences
GetWebkitPreferences() OVERRIDE
;
197 virtual void UpdateWebkitPreferences(
198 const WebPreferences
& prefs
) OVERRIDE
;
199 virtual void OnWebkitPreferencesChanged() OVERRIDE
;
200 virtual void GetAudioOutputControllers(
201 const GetAudioOutputControllersCallback
& callback
) const OVERRIDE
;
202 virtual void SelectWordAroundCaret() OVERRIDE
;
204 #if defined(OS_ANDROID)
205 virtual void ActivateNearestFindResult(int request_id
,
208 virtual void RequestFindMatchRects(int current_version
) OVERRIDE
;
211 void set_delegate(RenderViewHostDelegate
* d
) {
212 CHECK(d
); // http://crbug.com/82827
216 // Set up the RenderView child process. Virtual because it is overridden by
217 // TestRenderViewHost. If the |frame_name| parameter is non-empty, it is used
218 // as the name of the new top-level frame.
219 // The |opener_route_id| parameter indicates which RenderView created this
220 // (MSG_ROUTING_NONE if none). If |max_page_id| is larger than -1, the
221 // RenderView is told to start issuing page IDs at |max_page_id| + 1.
222 // |window_was_created_with_opener| is true if this top-level frame was
223 // created with an opener. (The opener may have been closed since.)
224 // The |proxy_route_id| is only used when creating a RenderView in swapped out
226 virtual bool CreateRenderView(const base::string16
& frame_name
,
230 bool window_was_created_with_opener
);
232 base::TerminationStatus
render_view_termination_status() const {
233 return render_view_termination_status_
;
236 // Returns the content specific prefs for this RenderViewHost.
237 WebPreferences
ComputeWebkitPrefs(const GURL
& url
);
239 // Sends the given navigation message. Use this rather than sending it
240 // yourself since this does the internal bookkeeping described below. This
241 // function takes ownership of the provided message pointer.
243 // If a cross-site request is in progress, we may be suspended while waiting
244 // for the onbeforeunload handler, so this function might buffer the message
245 // rather than sending it.
246 // TODO(nasko): Remove this method once all callers are converted to use
247 // RenderFrameHostImpl.
248 void Navigate(const FrameMsg_Navigate_Params
& message
);
250 // Load the specified URL, this is a shortcut for Navigate().
251 // TODO(nasko): Remove this method once all callers are converted to use
252 // RenderFrameHostImpl.
253 void NavigateToURL(const GURL
& url
);
255 // Whether this RenderViewHost has been swapped out to be displayed by a
256 // different process.
257 bool IsSwappedOut() const { return rvh_state_
== STATE_SWAPPED_OUT
; }
259 // The current state of this RVH.
260 RenderViewHostImplState
rvh_state() const { return rvh_state_
; }
262 // Tells the renderer that this RenderView will soon be swapped out, and thus
263 // not to create any new modal dialogs until it happens. This must be done
264 // separately so that the PageGroupLoadDeferrers of any current dialogs are no
265 // longer on the stack when we attempt to swap it out.
266 void SuppressDialogsUntilSwapOut();
268 // Called when either the SwapOut request has been acknowledged or has timed
270 void OnSwappedOut(bool timed_out
);
272 // Set |this| as pending shutdown. |on_swap_out| will be called
273 // when the SwapOutACK is received, or when the unload timer times out.
274 void SetPendingShutdown(const base::Closure
& on_swap_out
);
276 // Close the page ignoring whether it has unload events registers.
277 // This is called after the beforeunload and unload events have fired
278 // and the user has agreed to continue with closing the page.
279 void ClosePageIgnoringUnloadEvents();
281 // Tells the renderer view to focus the first (last if reverse is true) node.
282 void SetInitialFocus(bool reverse
);
284 // Get html data by serializing all frames of current page with lists
285 // which contain all resource links that have local copy.
286 // The parameter links contain original URLs of all saved links.
287 // The parameter local_paths contain corresponding local file paths of
288 // all saved links, which matched with vector:links one by one.
289 // The parameter local_directory_name is relative path of directory which
290 // contain all saved auxiliary files included all sub frames and resouces.
291 void GetSerializedHtmlDataForCurrentPageWithLocalLinks(
292 const std::vector
<GURL
>& links
,
293 const std::vector
<base::FilePath
>& local_paths
,
294 const base::FilePath
& local_directory_name
);
296 // Notifies the RenderViewHost that its load state changed.
297 void LoadStateChanged(const GURL
& url
,
298 const net::LoadStateWithParam
& load_state
,
299 uint64 upload_position
,
302 bool SuddenTerminationAllowed() const;
303 void set_sudden_termination_allowed(bool enabled
) {
304 sudden_termination_allowed_
= enabled
;
307 // RenderWidgetHost public overrides.
308 virtual void Init() OVERRIDE
;
309 virtual void Shutdown() OVERRIDE
;
310 virtual void WasHidden() OVERRIDE
;
311 virtual void WasShown(const ui::LatencyInfo
& latency_info
) OVERRIDE
;
312 virtual bool IsRenderView() const OVERRIDE
;
313 virtual bool OnMessageReceived(const IPC::Message
& msg
) OVERRIDE
;
314 virtual void GotFocus() OVERRIDE
;
315 virtual void LostCapture() OVERRIDE
;
316 virtual void LostMouseLock() OVERRIDE
;
317 virtual void SetIsLoading(bool is_loading
) OVERRIDE
;
318 virtual void ForwardMouseEvent(
319 const blink::WebMouseEvent
& mouse_event
) OVERRIDE
;
320 virtual void OnPointerEventActivate() OVERRIDE
;
321 virtual void ForwardKeyboardEvent(
322 const NativeWebKeyboardEvent
& key_event
) OVERRIDE
;
323 virtual gfx::Rect
GetRootWindowResizerRect() const OVERRIDE
;
325 // Creates a new RenderView with the given route id.
326 void CreateNewWindow(
328 int main_frame_route_id
,
329 const ViewHostMsg_CreateWindow_Params
& params
,
330 SessionStorageNamespace
* session_storage_namespace
);
332 // Creates a new RenderWidget with the given route id. |popup_type| indicates
333 // if this widget is a popup and what kind of popup it is (select, autofill).
334 void CreateNewWidget(int route_id
, blink::WebPopupType popup_type
);
336 // Creates a full screen RenderWidget.
337 void CreateNewFullscreenWidget(int route_id
);
339 #if defined(ENABLE_BROWSER_CDMS)
340 MediaWebContentsObserver
* media_web_contents_observer() {
341 return media_web_contents_observer_
.get();
345 int main_frame_routing_id() const {
346 return main_frame_routing_id_
;
349 bool is_waiting_for_beforeunload_ack() {
350 return is_waiting_for_beforeunload_ack_
;
353 // Whether the RVH is waiting for the unload ack from the renderer.
354 bool IsWaitingForUnloadACK() const;
356 void OnTextSurroundingSelectionResponse(const base::string16
& content
,
360 // Update the FrameTree to use this RenderViewHost's main frame
361 // RenderFrameHost. Called when the RenderViewHost is committed.
363 // TODO(ajwong): Remove once RenderViewHost no longer owns the main frame
365 void AttachToFrameTree();
367 // Increases the refcounting on this RVH. This is done by the FrameTree on
368 // creation of a RenderFrameHost.
369 void increment_ref_count() { ++frames_ref_count_
; }
371 // Decreases the refcounting on this RVH. This is done by the FrameTree on
372 // destruction of a RenderFrameHost.
373 void decrement_ref_count() { --frames_ref_count_
; }
375 // Returns the refcount on this RVH, that is the number of RenderFrameHosts
376 // currently using it.
377 int ref_count() { return frames_ref_count_
; }
379 // NOTE: Do not add functions that just send an IPC message that are called in
380 // one or two places. Have the caller send the IPC message directly (unless
381 // the caller places are in different platforms, in which case it's better
382 // to keep them consistent).
385 // RenderWidgetHost protected overrides.
386 virtual void OnUserGesture() OVERRIDE
;
387 virtual void NotifyRendererUnresponsive() OVERRIDE
;
388 virtual void NotifyRendererResponsive() OVERRIDE
;
389 virtual void OnRenderAutoResized(const gfx::Size
& size
) OVERRIDE
;
390 virtual void RequestToLockMouse(bool user_gesture
,
391 bool last_unlocked_by_target
) OVERRIDE
;
392 virtual bool IsFullscreen() const OVERRIDE
;
393 virtual void OnFocus() OVERRIDE
;
394 virtual void OnBlur() OVERRIDE
;
396 // IPC message handlers.
397 void OnShowView(int route_id
,
398 WindowOpenDisposition disposition
,
399 const gfx::Rect
& initial_pos
,
401 void OnShowWidget(int route_id
, const gfx::Rect
& initial_pos
);
402 void OnShowFullscreenWidget(int route_id
);
403 void OnRunModal(int opener_id
, IPC::Message
* reply_msg
);
404 void OnRenderViewReady();
405 void OnRenderProcessGone(int status
, int error_code
);
406 void OnUpdateState(int32 page_id
, const PageState
& state
);
407 void OnUpdateTargetURL(int32 page_id
, const GURL
& url
);
409 void OnRequestMove(const gfx::Rect
& pos
);
410 void OnDocumentAvailableInMainFrame(bool uses_temporary_zoom_level
);
411 void OnToggleFullscreen(bool enter_fullscreen
);
412 void OnDidContentsPreferredSizeChange(const gfx::Size
& new_size
);
413 void OnPasteFromSelectionClipboard();
414 void OnRouteCloseEvent();
415 void OnRouteMessageEvent(const ViewMsg_PostMessage_Params
& params
);
416 void OnStartDragging(const DropData
& drop_data
,
417 blink::WebDragOperationsMask operations_allowed
,
418 const SkBitmap
& bitmap
,
419 const gfx::Vector2d
& bitmap_offset_in_dip
,
420 const DragEventSourceInfo
& event_info
);
421 void OnUpdateDragCursor(blink::WebDragOperation drag_operation
);
422 void OnTargetDropACK();
423 void OnTakeFocus(bool reverse
);
424 void OnFocusedNodeChanged(bool is_editable_node
);
425 void OnClosePageACK();
426 void OnDidZoomURL(double zoom_level
, const GURL
& url
);
427 void OnRunFileChooser(const FileChooserParams
& params
);
428 void OnFocusedNodeTouched(bool editable
);
431 // TODO(nasko): Temporarily friend RenderFrameHostImpl, so we don't duplicate
432 // utility functions and state needed in both classes, while we move frame
433 // specific code away from this class.
434 friend class RenderFrameHostImpl
;
435 friend class TestRenderViewHost
;
436 FRIEND_TEST_ALL_PREFIXES(RenderViewHostTest
, BasicRenderFrameHost
);
437 FRIEND_TEST_ALL_PREFIXES(RenderViewHostTest
, RoutingIdSane
);
439 // TODO(creis): Move to a private namespace on RenderFrameHostImpl.
440 // Delay to wait on closing the WebContents for a beforeunload/unload handler
442 static const int kUnloadTimeoutMS
;
444 // Updates the state of this RenderViewHost and clears any waiting state
445 // that is no longer relevant.
446 void SetState(RenderViewHostImplState rvh_state
);
448 bool CanAccessFilesOfPageState(const PageState
& state
) const;
450 // The number of RenderFrameHosts which have a reference to this RVH.
451 int frames_ref_count_
;
453 // Our delegate, which wants to know about changes in the RenderView.
454 RenderViewHostDelegate
* delegate_
;
456 // The SiteInstance associated with this RenderViewHost. All pages drawn
457 // in this RenderViewHost are part of this SiteInstance. Should not change
459 scoped_refptr
<SiteInstanceImpl
> instance_
;
461 // true if we are currently waiting for a response for drag context
463 bool waiting_for_drag_context_response_
;
465 // A bitwise OR of bindings types that have been enabled for this RenderView.
466 // See BindingsPolicy for details.
467 int enabled_bindings_
;
469 // The most recent page ID we've heard from the renderer process. This is
470 // used as context when other session history related IPCs arrive.
471 // TODO(creis): Allocate this in WebContents/NavigationController instead.
474 // The current state of this RVH.
475 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
476 RenderViewHostImplState rvh_state_
;
478 // Routing ID for the main frame's RenderFrameHost.
479 int main_frame_routing_id_
;
481 // If we were asked to RunModal, then this will hold the reply_msg that we
482 // must return to the renderer to unblock it.
483 IPC::Message
* run_modal_reply_msg_
;
484 // This will hold the routing id of the RenderView that opened us.
485 int run_modal_opener_id_
;
487 // Set to true when there is a pending ViewMsg_ShouldClose message. This
488 // ensures we don't spam the renderer with multiple beforeunload requests.
489 // When either this value or IsWaitingForUnloadACK is true, the value of
490 // unload_ack_is_for_cross_site_transition_ indicates whether this is for a
491 // cross-site transition or a tab close attempt.
492 // TODO(clamy): Remove this boolean and add one more state to the state
494 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
495 bool is_waiting_for_beforeunload_ack_
;
497 // Valid only when is_waiting_for_beforeunload_ack_ or
498 // IsWaitingForUnloadACK is true. This tells us if the unload request
499 // is for closing the entire tab ( = false), or only this RenderViewHost in
500 // the case of a cross-site transition ( = true).
501 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
502 bool unload_ack_is_for_cross_site_transition_
;
504 // True if the render view can be shut down suddenly.
505 bool sudden_termination_allowed_
;
507 // The termination status of the last render view that terminated.
508 base::TerminationStatus render_view_termination_status_
;
510 // Set to true if we requested the on screen keyboard to be displayed.
511 bool virtual_keyboard_requested_
;
513 #if defined(ENABLE_BROWSER_CDMS)
514 // Manages all the media player and CDM managers and forwards IPCs to them.
515 scoped_ptr
<MediaWebContentsObserver
> media_web_contents_observer_
;
518 // Used to swap out or shutdown this RVH when the unload event is taking too
519 // long to execute, depending on the number of active views in the
521 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
522 scoped_ptr
<TimeoutMonitor
> unload_event_monitor_timeout_
;
524 // Called after receiving the SwapOutACK when the RVH is in state pending
525 // shutdown. Also called if the unload timer times out.
526 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
527 base::Closure pending_shutdown_on_swap_out_
;
529 base::WeakPtrFactory
<RenderViewHostImpl
> weak_factory_
;
531 // True if the current focused element is editable.
532 bool is_focused_element_editable_
;
534 // This is updated every time UpdateWebkitPreferences is called. That method
535 // is in turn called when any of the settings change that the WebPreferences
537 scoped_ptr
<WebPreferences
> web_preferences_
;
539 bool updating_web_preferences_
;
541 DISALLOW_COPY_AND_ASSIGN(RenderViewHostImpl
);
544 #if defined(COMPILER_MSVC)
548 } // namespace content
550 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_IMPL_H_