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 MediaPlayerAction;
33 struct ViewHostMsg_CreateWindow_Params;
34 struct ViewHostMsg_ShowPopup_Params;
35 struct FrameMsg_Navigate_Params;
36 struct ViewMsg_PostMessage_Params;
48 struct SelectedFileInfo;
53 class MediaWebContentsObserver;
54 class ChildProcessSecurityPolicyImpl;
56 class RenderWidgetHostDelegate;
57 class SessionStorageNamespace;
58 class SessionStorageNamespaceImpl;
59 class TestRenderViewHost;
61 struct FileChooserParams;
63 #if defined(COMPILER_MSVC)
64 // RenderViewHostImpl is the bottom of a diamond-shaped hierarchy,
65 // with RenderWidgetHost at the root. VS warns when methods from the
66 // root are overridden in only one of the base classes and not both
67 // (in this case, RenderWidgetHostImpl provides implementations of
68 // many of the methods). This is a silly warning when dealing with
69 // pure virtual methods that only have a single implementation in the
70 // hierarchy above this class, and is safe to ignore in this case.
72 #pragma warning(disable: 4250)
75 // This implements the RenderViewHost interface that is exposed to
76 // embedders of content, and adds things only visible to content.
78 // The exact API of this object needs to be more thoroughly designed. Right
79 // now it mimics what WebContentsImpl exposed, which is a fairly large API and
80 // may contain things that are not relevant to a common subset of views. See
81 // also the comment in render_view_host_delegate.h about the size and scope of
84 // Right now, the concept of page navigation (both top level and frame) exists
85 // in the WebContentsImpl still, so if you instantiate one of these elsewhere,
86 // you will not be able to traverse pages back and forward. We need to determine
87 // if we want to bring that and other functionality down into this object so it
88 // can be shared by others.
89 class CONTENT_EXPORT RenderViewHostImpl
90 : public RenderViewHost,
91 public RenderWidgetHostImpl {
93 // Keeps track of the state of the RenderViewHostImpl, particularly with
94 // respect to swap out.
95 enum RenderViewHostImplState {
96 // The standard state for a RVH handling the communication with a
99 // The RVH has sent the SwapOut request to the renderer, but has not
100 // received the SwapOutACK yet. The new page has not been committed yet
102 STATE_WAITING_FOR_UNLOAD_ACK,
103 // The RVH received the SwapOutACK from the RenderView, but the new page has
104 // not been committed yet.
105 STATE_WAITING_FOR_COMMIT,
106 // The RVH is waiting for the CloseACK from the RenderView.
107 STATE_WAITING_FOR_CLOSE,
108 // The RVH has not received the SwapOutACK yet, but the new page has
109 // committed in a different RVH. The number of active views of the RVH
110 // SiteInstanceImpl is not zero. Upon reception of the SwapOutACK, the RVH
111 // will be swapped out.
112 STATE_PENDING_SWAP_OUT,
113 // The RVH has not received the SwapOutACK yet, but the new page has
114 // committed in a different RVH. The number of active views of the RVH
115 // SiteInstanceImpl is zero. Upon reception of the SwapOutACK, the RVH will
117 STATE_PENDING_SHUTDOWN,
118 // The RVH is swapped out, and it is being used as a placeholder to allow
119 // for cross-process communication.
122 // Helper function to determine whether the RVH state should contribute to the
123 // number of active views of a SiteInstance or not.
124 static bool IsRVHStateActive(RenderViewHostImplState rvh_state);
126 // Convenience function, just like RenderViewHost::FromID.
127 static RenderViewHostImpl* FromID(int render_process_id, int render_view_id);
129 // |routing_id| could be a valid route id, or it could be MSG_ROUTING_NONE, in
130 // which case RenderWidgetHost will create a new one. |swapped_out| indicates
131 // whether the view should initially be swapped out (e.g., for an opener
132 // frame being rendered by another process). |hidden| indicates whether the
133 // view is initially hidden or visible.
135 // The |session_storage_namespace| parameter allows multiple render views and
136 // WebContentses to share the same session storage (part of the WebStorage
137 // spec) space. This is useful when restoring contentses, but most callers
138 // should pass in NULL which will cause a new SessionStorageNamespace to be
141 SiteInstance* instance,
142 RenderViewHostDelegate* delegate,
143 RenderWidgetHostDelegate* widget_delegate,
145 int main_frame_routing_id,
148 virtual ~RenderViewHostImpl();
150 // RenderViewHost implementation.
151 virtual RenderFrameHost* GetMainFrame() OVERRIDE;
152 virtual void AllowBindings(int binding_flags) OVERRIDE;
153 virtual void ClearFocusedElement() OVERRIDE;
154 virtual bool IsFocusedElementEditable() OVERRIDE;
155 virtual void ClosePage() OVERRIDE;
156 virtual void CopyImageAt(int x, int y) OVERRIDE;
157 virtual void SaveImageAt(int x, int y) OVERRIDE;
158 virtual void DirectoryEnumerationFinished(
160 const std::vector<base::FilePath>& files) OVERRIDE;
161 virtual void DisableScrollbarsForThreshold(const gfx::Size& size) OVERRIDE;
162 virtual void DragSourceEndedAt(
163 int client_x, int client_y, int screen_x, int screen_y,
164 blink::WebDragOperation operation) OVERRIDE;
165 virtual void DragSourceSystemDragEnded() OVERRIDE;
166 virtual void DragTargetDragEnter(
167 const DropData& drop_data,
168 const gfx::Point& client_pt,
169 const gfx::Point& screen_pt,
170 blink::WebDragOperationsMask operations_allowed,
171 int key_modifiers) OVERRIDE;
172 virtual void DragTargetDragOver(
173 const gfx::Point& client_pt,
174 const gfx::Point& screen_pt,
175 blink::WebDragOperationsMask operations_allowed,
176 int key_modifiers) OVERRIDE;
177 virtual void DragTargetDragLeave() OVERRIDE;
178 virtual void DragTargetDrop(const gfx::Point& client_pt,
179 const gfx::Point& screen_pt,
180 int key_modifiers) OVERRIDE;
181 virtual void EnableAutoResize(const gfx::Size& min_size,
182 const gfx::Size& max_size) OVERRIDE;
183 virtual void DisableAutoResize(const gfx::Size& new_size) OVERRIDE;
184 virtual void EnablePreferredSizeMode() OVERRIDE;
185 virtual void ExecuteMediaPlayerActionAtLocation(
186 const gfx::Point& location,
187 const blink::WebMediaPlayerAction& action) OVERRIDE;
188 virtual void ExecutePluginActionAtLocation(
189 const gfx::Point& location,
190 const blink::WebPluginAction& action) OVERRIDE;
191 virtual void ExitFullscreen() OVERRIDE;
192 virtual void FilesSelectedInChooser(
193 const std::vector<ui::SelectedFileInfo>& files,
194 FileChooserParams::Mode permissions) OVERRIDE;
195 virtual RenderViewHostDelegate* GetDelegate() const OVERRIDE;
196 virtual int GetEnabledBindings() const OVERRIDE;
197 virtual SiteInstance* GetSiteInstance() const OVERRIDE;
198 virtual bool IsRenderViewLive() const OVERRIDE;
199 virtual void NotifyMoveOrResizeStarted() OVERRIDE;
200 virtual void SetWebUIProperty(const std::string& name,
201 const std::string& value) OVERRIDE;
202 virtual void Zoom(PageZoom zoom) OVERRIDE;
203 virtual void SyncRendererPrefs() OVERRIDE;
204 virtual WebPreferences GetWebkitPreferences() OVERRIDE;
205 virtual void UpdateWebkitPreferences(
206 const WebPreferences& prefs) OVERRIDE;
207 virtual void OnWebkitPreferencesChanged() OVERRIDE;
208 virtual void GetAudioOutputControllers(
209 const GetAudioOutputControllersCallback& callback) const OVERRIDE;
210 virtual void SelectWordAroundCaret() OVERRIDE;
212 #if defined(OS_ANDROID)
213 virtual void ActivateNearestFindResult(int request_id,
216 virtual void RequestFindMatchRects(int current_version) OVERRIDE;
219 void set_delegate(RenderViewHostDelegate* d) {
220 CHECK(d); // http://crbug.com/82827
224 // Set up the RenderView child process. Virtual because it is overridden by
225 // TestRenderViewHost. If the |frame_name| parameter is non-empty, it is used
226 // as the name of the new top-level frame.
227 // The |opener_route_id| parameter indicates which RenderView created this
228 // (MSG_ROUTING_NONE if none). If |max_page_id| is larger than -1, the
229 // RenderView is told to start issuing page IDs at |max_page_id| + 1.
230 // |window_was_created_with_opener| is true if this top-level frame was
231 // created with an opener. (The opener may have been closed since.)
232 // The |proxy_route_id| is only used when creating a RenderView in swapped out
234 virtual bool CreateRenderView(const base::string16& frame_name,
238 bool window_was_created_with_opener);
240 base::TerminationStatus render_view_termination_status() const {
241 return render_view_termination_status_;
244 // Returns the content specific prefs for this RenderViewHost.
245 WebPreferences ComputeWebkitPrefs(const GURL& url);
247 // Sends the given navigation message. Use this rather than sending it
248 // yourself since this does the internal bookkeeping described below. This
249 // function takes ownership of the provided message pointer.
251 // If a cross-site request is in progress, we may be suspended while waiting
252 // for the onbeforeunload handler, so this function might buffer the message
253 // rather than sending it.
254 // TODO(nasko): Remove this method once all callers are converted to use
255 // RenderFrameHostImpl.
256 void Navigate(const FrameMsg_Navigate_Params& message);
258 // Load the specified URL, this is a shortcut for Navigate().
259 // TODO(nasko): Remove this method once all callers are converted to use
260 // RenderFrameHostImpl.
261 void NavigateToURL(const GURL& url);
263 // Whether this RenderViewHost has been swapped out to be displayed by a
264 // different process.
265 bool IsSwappedOut() const { return rvh_state_ == STATE_SWAPPED_OUT; }
267 // The current state of this RVH.
268 RenderViewHostImplState rvh_state() const { return rvh_state_; }
270 // Tells the renderer that this RenderView will soon be swapped out, and thus
271 // not to create any new modal dialogs until it happens. This must be done
272 // separately so that the PageGroupLoadDeferrers of any current dialogs are no
273 // longer on the stack when we attempt to swap it out.
274 void SuppressDialogsUntilSwapOut();
276 // Called when either the SwapOut request has been acknowledged or has timed
278 void OnSwappedOut(bool timed_out);
280 // Called when the RenderFrameHostManager has swapped in a new
281 // RenderFrameHost. Should |this| RVH switch to the pending shutdown state,
282 // |pending_delete_on_swap_out| will be executed upon reception of the
283 // SwapOutACK, or when the unload timer times out.
284 void WasSwappedOut(const base::Closure& pending_delete_on_swap_out);
286 // Set |this| as pending shutdown. |on_swap_out| will be called
287 // when the SwapOutACK is received, or when the unload timer times out.
288 void SetPendingShutdown(const base::Closure& on_swap_out);
290 // Close the page ignoring whether it has unload events registers.
291 // This is called after the beforeunload and unload events have fired
292 // and the user has agreed to continue with closing the page.
293 void ClosePageIgnoringUnloadEvents();
295 // Tells the renderer view to focus the first (last if reverse is true) node.
296 void SetInitialFocus(bool reverse);
298 // Get html data by serializing all frames of current page with lists
299 // which contain all resource links that have local copy.
300 // The parameter links contain original URLs of all saved links.
301 // The parameter local_paths contain corresponding local file paths of
302 // all saved links, which matched with vector:links one by one.
303 // The parameter local_directory_name is relative path of directory which
304 // contain all saved auxiliary files included all sub frames and resouces.
305 void GetSerializedHtmlDataForCurrentPageWithLocalLinks(
306 const std::vector<GURL>& links,
307 const std::vector<base::FilePath>& local_paths,
308 const base::FilePath& local_directory_name);
310 // Notifies the RenderViewHost that its load state changed.
311 void LoadStateChanged(const GURL& url,
312 const net::LoadStateWithParam& load_state,
313 uint64 upload_position,
316 bool SuddenTerminationAllowed() const;
317 void set_sudden_termination_allowed(bool enabled) {
318 sudden_termination_allowed_ = enabled;
321 // RenderWidgetHost public overrides.
322 virtual void Init() OVERRIDE;
323 virtual void Shutdown() OVERRIDE;
324 virtual bool IsRenderView() const OVERRIDE;
325 virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
326 virtual void GotFocus() OVERRIDE;
327 virtual void LostCapture() OVERRIDE;
328 virtual void LostMouseLock() OVERRIDE;
329 virtual void ForwardMouseEvent(
330 const blink::WebMouseEvent& mouse_event) OVERRIDE;
331 virtual void OnPointerEventActivate() OVERRIDE;
332 virtual void ForwardKeyboardEvent(
333 const NativeWebKeyboardEvent& key_event) OVERRIDE;
334 virtual gfx::Rect GetRootWindowResizerRect() const OVERRIDE;
336 // Creates a new RenderView with the given route id.
337 void CreateNewWindow(
339 int main_frame_route_id,
340 const ViewHostMsg_CreateWindow_Params& params,
341 SessionStorageNamespace* session_storage_namespace);
343 // Creates a new RenderWidget with the given route id. |popup_type| indicates
344 // if this widget is a popup and what kind of popup it is (select, autofill).
345 void CreateNewWidget(int route_id, blink::WebPopupType popup_type);
347 // Creates a full screen RenderWidget.
348 void CreateNewFullscreenWidget(int route_id);
350 #if defined(OS_MACOSX)
351 // Select popup menu related methods (for external popup menus).
352 void DidSelectPopupMenuItem(int selected_index);
353 void DidCancelPopupMenu();
356 #if defined(ENABLE_BROWSER_CDMS)
357 MediaWebContentsObserver* media_web_contents_observer() {
358 return media_web_contents_observer_.get();
362 #if defined(OS_ANDROID)
363 void DidSelectPopupMenuItems(const std::vector<int>& selected_indices);
364 void DidCancelPopupMenu();
367 int main_frame_routing_id() const {
368 return main_frame_routing_id_;
371 // Set the opener to null in the renderer process.
374 bool is_waiting_for_beforeunload_ack() {
375 return is_waiting_for_beforeunload_ack_;
378 // Whether the RVH is waiting for the unload ack from the renderer.
379 bool IsWaitingForUnloadACK() const;
381 void OnTextSurroundingSelectionResponse(const base::string16& content,
385 // Update the FrameTree to use this RenderViewHost's main frame
386 // RenderFrameHost. Called when the RenderViewHost is committed.
388 // TODO(ajwong): Remove once RenderViewHost no longer owns the main frame
390 void AttachToFrameTree();
392 // Increases the refcounting on this RVH. This is done by the FrameTree on
393 // creation of a RenderFrameHost.
394 void increment_ref_count() { ++frames_ref_count_; }
396 // Decreases the refcounting on this RVH. This is done by the FrameTree on
397 // destruction of a RenderFrameHost.
398 void decrement_ref_count() { --frames_ref_count_; }
400 // Returns the refcount on this RVH, that is the number of RenderFrameHosts
401 // currently using it.
402 int ref_count() { return frames_ref_count_; }
404 // NOTE: Do not add functions that just send an IPC message that are called in
405 // one or two places. Have the caller send the IPC message directly (unless
406 // the caller places are in different platforms, in which case it's better
407 // to keep them consistent).
410 // RenderWidgetHost protected overrides.
411 virtual void OnUserGesture() OVERRIDE;
412 virtual void NotifyRendererUnresponsive() OVERRIDE;
413 virtual void NotifyRendererResponsive() OVERRIDE;
414 virtual void OnRenderAutoResized(const gfx::Size& size) OVERRIDE;
415 virtual void RequestToLockMouse(bool user_gesture,
416 bool last_unlocked_by_target) OVERRIDE;
417 virtual bool IsFullscreen() const OVERRIDE;
418 virtual void OnFocus() OVERRIDE;
419 virtual void OnBlur() OVERRIDE;
421 // IPC message handlers.
422 void OnShowView(int route_id,
423 WindowOpenDisposition disposition,
424 const gfx::Rect& initial_pos,
426 void OnShowWidget(int route_id, const gfx::Rect& initial_pos);
427 void OnShowFullscreenWidget(int route_id);
428 void OnRunModal(int opener_id, IPC::Message* reply_msg);
429 void OnRenderViewReady();
430 void OnRenderProcessGone(int status, int error_code);
431 void OnUpdateState(int32 page_id, const PageState& state);
432 void OnUpdateTargetURL(int32 page_id, const GURL& url);
434 void OnRequestMove(const gfx::Rect& pos);
435 void OnDocumentAvailableInMainFrame(bool uses_temporary_zoom_level);
436 void OnToggleFullscreen(bool enter_fullscreen);
437 void OnDidContentsPreferredSizeChange(const gfx::Size& new_size);
438 void OnDidChangeScrollOffset();
439 void OnPasteFromSelectionClipboard();
440 void OnRouteCloseEvent();
441 void OnRouteMessageEvent(const ViewMsg_PostMessage_Params& params);
442 void OnStartDragging(const DropData& drop_data,
443 blink::WebDragOperationsMask operations_allowed,
444 const SkBitmap& bitmap,
445 const gfx::Vector2d& bitmap_offset_in_dip,
446 const DragEventSourceInfo& event_info);
447 void OnUpdateDragCursor(blink::WebDragOperation drag_operation);
448 void OnTargetDropACK();
449 void OnTakeFocus(bool reverse);
450 void OnFocusedNodeChanged(bool is_editable_node);
451 void OnUpdateInspectorSetting(const std::string& key,
452 const std::string& value);
453 void OnClosePageACK();
454 void OnDidZoomURL(double zoom_level, const GURL& url);
455 void OnRunFileChooser(const FileChooserParams& params);
456 void OnFocusedNodeTouched(bool editable);
458 #if defined(OS_MACOSX) || defined(OS_ANDROID)
459 void OnShowPopup(const ViewHostMsg_ShowPopup_Params& params);
464 // TODO(nasko): Temporarily friend RenderFrameHostImpl, so we don't duplicate
465 // utility functions and state needed in both classes, while we move frame
466 // specific code away from this class.
467 friend class RenderFrameHostImpl;
468 friend class TestRenderViewHost;
469 FRIEND_TEST_ALL_PREFIXES(RenderViewHostTest, BasicRenderFrameHost);
470 FRIEND_TEST_ALL_PREFIXES(RenderViewHostTest, RoutingIdSane);
472 // TODO(creis): Move to a private namespace on RenderFrameHostImpl.
473 // Delay to wait on closing the WebContents for a beforeunload/unload handler
475 static const int kUnloadTimeoutMS;
477 // Updates the state of this RenderViewHost and clears any waiting state
478 // that is no longer relevant.
479 void SetState(RenderViewHostImplState rvh_state);
481 bool CanAccessFilesOfPageState(const PageState& state) const;
483 // The number of RenderFrameHosts which have a reference to this RVH.
484 int frames_ref_count_;
486 // Our delegate, which wants to know about changes in the RenderView.
487 RenderViewHostDelegate* delegate_;
489 // The SiteInstance associated with this RenderViewHost. All pages drawn
490 // in this RenderViewHost are part of this SiteInstance. Should not change
492 scoped_refptr<SiteInstanceImpl> instance_;
494 // true if we are currently waiting for a response for drag context
496 bool waiting_for_drag_context_response_;
498 // A bitwise OR of bindings types that have been enabled for this RenderView.
499 // See BindingsPolicy for details.
500 int enabled_bindings_;
503 // The current state of this RVH.
504 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
505 RenderViewHostImplState rvh_state_;
507 // Routing ID for the main frame's RenderFrameHost.
508 int main_frame_routing_id_;
510 // If we were asked to RunModal, then this will hold the reply_msg that we
511 // must return to the renderer to unblock it.
512 IPC::Message* run_modal_reply_msg_;
513 // This will hold the routing id of the RenderView that opened us.
514 int run_modal_opener_id_;
516 // Set to true when there is a pending ViewMsg_ShouldClose message. This
517 // ensures we don't spam the renderer with multiple beforeunload requests.
518 // When either this value or IsWaitingForUnloadACK is true, the value of
519 // unload_ack_is_for_cross_site_transition_ indicates whether this is for a
520 // cross-site transition or a tab close attempt.
521 // TODO(clamy): Remove this boolean and add one more state to the state
523 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
524 bool is_waiting_for_beforeunload_ack_;
526 // Valid only when is_waiting_for_beforeunload_ack_ or
527 // IsWaitingForUnloadACK is true. This tells us if the unload request
528 // is for closing the entire tab ( = false), or only this RenderViewHost in
529 // the case of a cross-site transition ( = true).
530 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
531 bool unload_ack_is_for_cross_site_transition_;
533 // True if the render view can be shut down suddenly.
534 bool sudden_termination_allowed_;
536 // The termination status of the last render view that terminated.
537 base::TerminationStatus render_view_termination_status_;
539 // Set to true if we requested the on screen keyboard to be displayed.
540 bool virtual_keyboard_requested_;
542 #if defined(ENABLE_BROWSER_CDMS)
543 // Manages all the media player and CDM managers and forwards IPCs to them.
544 scoped_ptr<MediaWebContentsObserver> media_web_contents_observer_;
547 // Used to swap out or shutdown this RVH when the unload event is taking too
548 // long to execute, depending on the number of active views in the
550 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
551 scoped_ptr<TimeoutMonitor> unload_event_monitor_timeout_;
553 // Called after receiving the SwapOutACK when the RVH is in state pending
554 // shutdown. Also called if the unload timer times out.
555 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
556 base::Closure pending_shutdown_on_swap_out_;
558 base::WeakPtrFactory<RenderViewHostImpl> weak_factory_;
560 // True if the current focused element is editable.
561 bool is_focused_element_editable_;
563 // This is updated every time UpdateWebkitPreferences is called. That method
564 // is in turn called when any of the settings change that the WebPreferences
566 scoped_ptr<WebPreferences> web_preferences_;
568 bool updating_web_preferences_;
570 DISALLOW_COPY_AND_ASSIGN(RenderViewHostImpl);
573 #if defined(COMPILER_MSVC)
577 } // namespace content
579 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_IMPL_H_