Battery Status API: add UMA logging for Linux.
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.h
blob133d3309c8edb1273ff8d03657112a987667ff53
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_
8 #include <map>
9 #include <string>
10 #include <vector>
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"
30 class SkBitmap;
31 class FrameMsg_Navigate;
32 struct FrameMsg_Navigate_Params;
33 struct MediaPlayerAction;
34 struct ViewHostMsg_CreateWindow_Params;
35 struct ViewMsg_PostMessage_Params;
37 namespace base {
38 class ListValue;
41 namespace gfx {
42 class Range;
45 namespace ui {
46 class AXTree;
47 struct SelectedFileInfo;
50 namespace content {
52 class MediaWebContentsObserver;
53 class ChildProcessSecurityPolicyImpl;
54 class PageState;
55 class RenderWidgetHostDelegate;
56 class SessionStorageNamespace;
57 class SessionStorageNamespaceImpl;
58 class TestRenderViewHost;
59 class TimeoutMonitor;
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.
70 #pragma warning(push)
71 #pragma warning(disable: 4250)
72 #endif
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
81 // the delegate API.
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 {
91 public:
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
96 // RenderView.
97 STATE_DEFAULT = 0,
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
108 // be shutdown.
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.
112 STATE_SWAPPED_OUT,
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
131 // created.
132 RenderViewHostImpl(
133 SiteInstance* instance,
134 RenderViewHostDelegate* delegate,
135 RenderWidgetHostDelegate* widget_delegate,
136 int routing_id,
137 int main_frame_routing_id,
138 bool swapped_out,
139 bool hidden);
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(
151 int request_id,
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,
206 float x,
207 float y) OVERRIDE;
208 virtual void RequestFindMatchRects(int current_version) OVERRIDE;
209 #endif
211 void set_delegate(RenderViewHostDelegate* d) {
212 CHECK(d); // http://crbug.com/82827
213 delegate_ = d;
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
225 // state.
226 virtual bool CreateRenderView(const base::string16& frame_name,
227 int opener_route_id,
228 int proxy_route_id,
229 int32 max_page_id,
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
269 // out.
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,
300 uint64 upload_size);
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 ForwardMouseEvent(
318 const blink::WebMouseEvent& mouse_event) OVERRIDE;
319 virtual void OnPointerEventActivate() OVERRIDE;
320 virtual void ForwardKeyboardEvent(
321 const NativeWebKeyboardEvent& key_event) OVERRIDE;
322 virtual gfx::Rect GetRootWindowResizerRect() const OVERRIDE;
324 // Creates a new RenderView with the given route id.
325 void CreateNewWindow(
326 int route_id,
327 int main_frame_route_id,
328 const ViewHostMsg_CreateWindow_Params& params,
329 SessionStorageNamespace* session_storage_namespace);
331 // Creates a new RenderWidget with the given route id. |popup_type| indicates
332 // if this widget is a popup and what kind of popup it is (select, autofill).
333 void CreateNewWidget(int route_id, blink::WebPopupType popup_type);
335 // Creates a full screen RenderWidget.
336 void CreateNewFullscreenWidget(int route_id);
338 #if defined(ENABLE_BROWSER_CDMS)
339 MediaWebContentsObserver* media_web_contents_observer() {
340 return media_web_contents_observer_.get();
342 #endif
344 int main_frame_routing_id() const {
345 return main_frame_routing_id_;
348 bool is_waiting_for_beforeunload_ack() {
349 return is_waiting_for_beforeunload_ack_;
352 // Whether the RVH is waiting for the unload ack from the renderer.
353 bool IsWaitingForUnloadACK() const;
355 void OnTextSurroundingSelectionResponse(const base::string16& content,
356 size_t start_offset,
357 size_t end_offset);
359 // Update the FrameTree to use this RenderViewHost's main frame
360 // RenderFrameHost. Called when the RenderViewHost is committed.
362 // TODO(ajwong): Remove once RenderViewHost no longer owns the main frame
363 // RenderFrameHost.
364 void AttachToFrameTree();
366 // Increases the refcounting on this RVH. This is done by the FrameTree on
367 // creation of a RenderFrameHost.
368 void increment_ref_count() { ++frames_ref_count_; }
370 // Decreases the refcounting on this RVH. This is done by the FrameTree on
371 // destruction of a RenderFrameHost.
372 void decrement_ref_count() { --frames_ref_count_; }
374 // Returns the refcount on this RVH, that is the number of RenderFrameHosts
375 // currently using it.
376 int ref_count() { return frames_ref_count_; }
378 // NOTE: Do not add functions that just send an IPC message that are called in
379 // one or two places. Have the caller send the IPC message directly (unless
380 // the caller places are in different platforms, in which case it's better
381 // to keep them consistent).
383 protected:
384 // RenderWidgetHost protected overrides.
385 virtual void OnUserGesture() OVERRIDE;
386 virtual void NotifyRendererUnresponsive() OVERRIDE;
387 virtual void NotifyRendererResponsive() OVERRIDE;
388 virtual void OnRenderAutoResized(const gfx::Size& size) OVERRIDE;
389 virtual void RequestToLockMouse(bool user_gesture,
390 bool last_unlocked_by_target) OVERRIDE;
391 virtual bool IsFullscreen() const OVERRIDE;
392 virtual void OnFocus() OVERRIDE;
393 virtual void OnBlur() OVERRIDE;
395 // IPC message handlers.
396 void OnShowView(int route_id,
397 WindowOpenDisposition disposition,
398 const gfx::Rect& initial_pos,
399 bool user_gesture);
400 void OnShowWidget(int route_id, const gfx::Rect& initial_pos);
401 void OnShowFullscreenWidget(int route_id);
402 void OnRunModal(int opener_id, IPC::Message* reply_msg);
403 void OnRenderViewReady();
404 void OnRenderProcessGone(int status, int error_code);
405 void OnUpdateState(int32 page_id, const PageState& state);
406 void OnUpdateTargetURL(int32 page_id, const GURL& url);
407 void OnClose();
408 void OnRequestMove(const gfx::Rect& pos);
409 void OnDocumentAvailableInMainFrame(bool uses_temporary_zoom_level);
410 void OnToggleFullscreen(bool enter_fullscreen);
411 void OnDidContentsPreferredSizeChange(const gfx::Size& new_size);
412 void OnPasteFromSelectionClipboard();
413 void OnRouteCloseEvent();
414 void OnRouteMessageEvent(const ViewMsg_PostMessage_Params& params);
415 void OnStartDragging(const DropData& drop_data,
416 blink::WebDragOperationsMask operations_allowed,
417 const SkBitmap& bitmap,
418 const gfx::Vector2d& bitmap_offset_in_dip,
419 const DragEventSourceInfo& event_info);
420 void OnUpdateDragCursor(blink::WebDragOperation drag_operation);
421 void OnTargetDropACK();
422 void OnTakeFocus(bool reverse);
423 void OnFocusedNodeChanged(bool is_editable_node);
424 void OnClosePageACK();
425 void OnDidZoomURL(double zoom_level, const GURL& url);
426 void OnRunFileChooser(const FileChooserParams& params);
427 void OnFocusedNodeTouched(bool editable);
429 private:
430 // TODO(nasko): Temporarily friend RenderFrameHostImpl, so we don't duplicate
431 // utility functions and state needed in both classes, while we move frame
432 // specific code away from this class.
433 friend class RenderFrameHostImpl;
434 friend class TestRenderViewHost;
435 FRIEND_TEST_ALL_PREFIXES(RenderViewHostTest, BasicRenderFrameHost);
436 FRIEND_TEST_ALL_PREFIXES(RenderViewHostTest, RoutingIdSane);
438 // TODO(creis): Move to a private namespace on RenderFrameHostImpl.
439 // Delay to wait on closing the WebContents for a beforeunload/unload handler
440 // to fire.
441 static const int kUnloadTimeoutMS;
443 // Updates the state of this RenderViewHost and clears any waiting state
444 // that is no longer relevant.
445 void SetState(RenderViewHostImplState rvh_state);
447 bool CanAccessFilesOfPageState(const PageState& state) const;
449 // The number of RenderFrameHosts which have a reference to this RVH.
450 int frames_ref_count_;
452 // Our delegate, which wants to know about changes in the RenderView.
453 RenderViewHostDelegate* delegate_;
455 // The SiteInstance associated with this RenderViewHost. All pages drawn
456 // in this RenderViewHost are part of this SiteInstance. Should not change
457 // over time.
458 scoped_refptr<SiteInstanceImpl> instance_;
460 // true if we are currently waiting for a response for drag context
461 // information.
462 bool waiting_for_drag_context_response_;
464 // A bitwise OR of bindings types that have been enabled for this RenderView.
465 // See BindingsPolicy for details.
466 int enabled_bindings_;
469 // The current state of this RVH.
470 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
471 RenderViewHostImplState rvh_state_;
473 // Routing ID for the main frame's RenderFrameHost.
474 int main_frame_routing_id_;
476 // If we were asked to RunModal, then this will hold the reply_msg that we
477 // must return to the renderer to unblock it.
478 IPC::Message* run_modal_reply_msg_;
479 // This will hold the routing id of the RenderView that opened us.
480 int run_modal_opener_id_;
482 // Set to true when there is a pending ViewMsg_ShouldClose message. This
483 // ensures we don't spam the renderer with multiple beforeunload requests.
484 // When either this value or IsWaitingForUnloadACK is true, the value of
485 // unload_ack_is_for_cross_site_transition_ indicates whether this is for a
486 // cross-site transition or a tab close attempt.
487 // TODO(clamy): Remove this boolean and add one more state to the state
488 // machine.
489 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
490 bool is_waiting_for_beforeunload_ack_;
492 // Valid only when is_waiting_for_beforeunload_ack_ or
493 // IsWaitingForUnloadACK is true. This tells us if the unload request
494 // is for closing the entire tab ( = false), or only this RenderViewHost in
495 // the case of a cross-site transition ( = true).
496 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
497 bool unload_ack_is_for_cross_site_transition_;
499 // True if the render view can be shut down suddenly.
500 bool sudden_termination_allowed_;
502 // The termination status of the last render view that terminated.
503 base::TerminationStatus render_view_termination_status_;
505 // Set to true if we requested the on screen keyboard to be displayed.
506 bool virtual_keyboard_requested_;
508 #if defined(ENABLE_BROWSER_CDMS)
509 // Manages all the media player and CDM managers and forwards IPCs to them.
510 scoped_ptr<MediaWebContentsObserver> media_web_contents_observer_;
511 #endif
513 // Used to swap out or shutdown this RVH when the unload event is taking too
514 // long to execute, depending on the number of active views in the
515 // SiteInstance.
516 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
517 scoped_ptr<TimeoutMonitor> unload_event_monitor_timeout_;
519 // Called after receiving the SwapOutACK when the RVH is in state pending
520 // shutdown. Also called if the unload timer times out.
521 // TODO(nasko): Move to RenderFrameHost, as this is per-frame state.
522 base::Closure pending_shutdown_on_swap_out_;
524 base::WeakPtrFactory<RenderViewHostImpl> weak_factory_;
526 // True if the current focused element is editable.
527 bool is_focused_element_editable_;
529 // This is updated every time UpdateWebkitPreferences is called. That method
530 // is in turn called when any of the settings change that the WebPreferences
531 // values depend on.
532 scoped_ptr<WebPreferences> web_preferences_;
534 bool updating_web_preferences_;
536 DISALLOW_COPY_AND_ASSIGN(RenderViewHostImpl);
539 #if defined(COMPILER_MSVC)
540 #pragma warning(pop)
541 #endif
543 } // namespace content
545 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_IMPL_H_