- add sources.
[platform/framework/web/crosswalk.git] / src / content / browser / renderer_host / render_widget_host_impl.h
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_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_IMPL_H_
6 #define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_IMPL_H_
7
8 #include <deque>
9 #include <list>
10 #include <map>
11 #include <queue>
12 #include <string>
13 #include <utility>
14 #include <vector>
15
16 #include "base/callback.h"
17 #include "base/gtest_prod_util.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/observer_list.h"
21 #include "base/process/kill.h"
22 #include "base/strings/string16.h"
23 #include "base/time/time.h"
24 #include "base/timer/timer.h"
25 #include "build/build_config.h"
26 #include "content/browser/renderer_host/input/input_ack_handler.h"
27 #include "content/browser/renderer_host/input/input_router_client.h"
28 #include "content/browser/renderer_host/synthetic_gesture_controller.h"
29 #include "content/common/browser_rendering_stats.h"
30 #include "content/common/view_message_enums.h"
31 #include "content/port/browser/event_with_latency_info.h"
32 #include "content/port/common/input_event_ack_state.h"
33 #include "content/public/browser/render_widget_host.h"
34 #include "content/public/common/page_zoom.h"
35 #include "ipc/ipc_listener.h"
36 #include "ui/base/ime/text_input_mode.h"
37 #include "ui/base/ime/text_input_type.h"
38 #include "ui/events/latency_info.h"
39 #include "ui/gfx/native_widget_types.h"
40
41 class WebCursor;
42 struct AcceleratedSurfaceMsg_BufferPresented_Params;
43 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
44 struct ViewHostMsg_UpdateRect_Params;
45 struct ViewHostMsg_TextInputState_Params;
46 struct ViewHostMsg_BeginSmoothScroll_Params;
47
48 namespace base {
49 class TimeTicks;
50 }
51
52 namespace cc {
53 class CompositorFrame;
54 class CompositorFrameAck;
55 }
56
57 namespace gfx {
58 class Range;
59 }
60
61 namespace ui {
62 class KeyEvent;
63 }
64
65 namespace WebKit {
66 class WebInputEvent;
67 class WebMouseEvent;
68 struct WebCompositionUnderline;
69 struct WebScreenInfo;
70 }
71
72 #if defined(OS_ANDROID)
73 namespace WebKit {
74 class WebLayer;
75 }
76 #endif
77
78 namespace content {
79 class BackingStore;
80 class InputRouter;
81 class MockRenderWidgetHost;
82 class OverscrollController;
83 class RenderWidgetHostDelegate;
84 class RenderWidgetHostViewPort;
85 class SyntheticGestureController;
86 struct EditCommand;
87
88 // This implements the RenderWidgetHost interface that is exposed to
89 // embedders of content, and adds things only visible to content.
90 class CONTENT_EXPORT RenderWidgetHostImpl : virtual public RenderWidgetHost,
91                                             public InputRouterClient,
92                                             public InputAckHandler,
93                                             public IPC::Listener {
94  public:
95   // routing_id can be MSG_ROUTING_NONE, in which case the next available
96   // routing id is taken from the RenderProcessHost.
97   // If this object outlives |delegate|, DetachDelegate() must be called when
98   // |delegate| goes away.
99   RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
100                        RenderProcessHost* process,
101                        int routing_id,
102                        bool hidden);
103   virtual ~RenderWidgetHostImpl();
104
105   // Similar to RenderWidgetHost::FromID, but returning the Impl object.
106   static RenderWidgetHostImpl* FromID(int32 process_id, int32 routing_id);
107
108   // Returns all RenderWidgetHosts including swapped out ones for
109   // internal use. The public interface
110   // RendgerWidgetHost::GetRenderWidgetHosts only returns active ones.
111   static scoped_ptr<RenderWidgetHostIterator> GetAllRenderWidgetHosts();
112
113   // Use RenderWidgetHostImpl::From(rwh) to downcast a
114   // RenderWidgetHost to a RenderWidgetHostImpl.  Internally, this
115   // uses RenderWidgetHost::AsRenderWidgetHostImpl().
116   static RenderWidgetHostImpl* From(RenderWidgetHost* rwh);
117
118   void set_hung_renderer_delay_ms(const base::TimeDelta& timeout) {
119     hung_renderer_delay_ms_ = timeout.InMilliseconds();
120   }
121
122   // RenderWidgetHost implementation.
123   virtual void Undo() OVERRIDE;
124   virtual void Redo() OVERRIDE;
125   virtual void Cut() OVERRIDE;
126   virtual void Copy() OVERRIDE;
127   virtual void CopyToFindPboard() OVERRIDE;
128   virtual void Paste() OVERRIDE;
129   virtual void PasteAndMatchStyle() OVERRIDE;
130   virtual void Delete() OVERRIDE;
131   virtual void SelectAll() OVERRIDE;
132   virtual void Unselect() OVERRIDE;
133   virtual void UpdateTextDirection(WebKit::WebTextDirection direction) OVERRIDE;
134   virtual void NotifyTextDirection() OVERRIDE;
135   virtual void Focus() OVERRIDE;
136   virtual void Blur() OVERRIDE;
137   virtual void SetActive(bool active) OVERRIDE;
138   virtual void CopyFromBackingStore(
139       const gfx::Rect& src_rect,
140       const gfx::Size& accelerated_dst_size,
141       const base::Callback<void(bool, const SkBitmap&)>& callback) OVERRIDE;
142 #if defined(TOOLKIT_GTK)
143   virtual bool CopyFromBackingStoreToGtkWindow(const gfx::Rect& dest_rect,
144                                                GdkWindow* target) OVERRIDE;
145 #elif defined(OS_MACOSX)
146   virtual gfx::Size GetBackingStoreSize() OVERRIDE;
147   virtual bool CopyFromBackingStoreToCGContext(const CGRect& dest_rect,
148                                                CGContextRef target) OVERRIDE;
149 #endif
150   virtual void EnableFullAccessibilityMode() OVERRIDE;
151   virtual void ForwardMouseEvent(
152       const WebKit::WebMouseEvent& mouse_event) OVERRIDE;
153   virtual void ForwardWheelEvent(
154       const WebKit::WebMouseWheelEvent& wheel_event) OVERRIDE;
155   virtual void ForwardKeyboardEvent(
156       const NativeWebKeyboardEvent& key_event) OVERRIDE;
157   virtual const gfx::Vector2d& GetLastScrollOffset() const OVERRIDE;
158   virtual RenderProcessHost* GetProcess() const OVERRIDE;
159   virtual int GetRoutingID() const OVERRIDE;
160   virtual RenderWidgetHostView* GetView() const OVERRIDE;
161   virtual bool IsLoading() const OVERRIDE;
162   virtual bool IsRenderView() const OVERRIDE;
163   virtual void PaintAtSize(TransportDIB::Handle dib_handle,
164                            int tag,
165                            const gfx::Size& page_size,
166                            const gfx::Size& desired_size) OVERRIDE;
167   virtual void Replace(const string16& word) OVERRIDE;
168   virtual void ReplaceMisspelling(const string16& word) OVERRIDE;
169   virtual void ResizeRectChanged(const gfx::Rect& new_rect) OVERRIDE;
170   virtual void RestartHangMonitorTimeout() OVERRIDE;
171   virtual void SetIgnoreInputEvents(bool ignore_input_events) OVERRIDE;
172   virtual void Stop() OVERRIDE;
173   virtual void WasResized() OVERRIDE;
174   virtual void AddKeyPressEventCallback(
175       const KeyPressEventCallback& callback) OVERRIDE;
176   virtual void RemoveKeyPressEventCallback(
177       const KeyPressEventCallback& callback) OVERRIDE;
178   virtual void AddMouseEventCallback(
179       const MouseEventCallback& callback) OVERRIDE;
180   virtual void RemoveMouseEventCallback(
181       const MouseEventCallback& callback) OVERRIDE;
182   virtual void GetWebScreenInfo(WebKit::WebScreenInfo* result) OVERRIDE;
183   virtual void GetSnapshotFromRenderer(
184       const gfx::Rect& src_subrect,
185       const base::Callback<void(bool, const SkBitmap&)>& callback) OVERRIDE;
186
187   const NativeWebKeyboardEvent* GetLastKeyboardEvent() const;
188
189   // Notification that the screen info has changed.
190   void NotifyScreenInfoChanged();
191
192   // Invalidates the cached screen info so that next resize request
193   // will carry the up to date screen info. Unlike
194   // |NotifyScreenInfoChanged|, this doesn't send a message to the renderer.
195   void InvalidateScreenInfo();
196
197   // Sets the View of this RenderWidgetHost.
198   void SetView(RenderWidgetHostView* view);
199
200   int surface_id() const { return surface_id_; }
201
202   bool empty() const { return current_size_.IsEmpty(); }
203
204   // Called when a renderer object already been created for this host, and we
205   // just need to be attached to it. Used for window.open, <select> dropdown
206   // menus, and other times when the renderer initiates creating an object.
207   virtual void Init();
208
209   // Tells the renderer to die and then calls Destroy().
210   virtual void Shutdown();
211
212   // IPC::Listener
213   virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
214
215   // Sends a message to the corresponding object in the renderer.
216   virtual bool Send(IPC::Message* msg) OVERRIDE;
217
218   // Called to notify the RenderWidget that it has been hidden or restored from
219   // having been hidden.
220   void WasHidden();
221   void WasShown();
222
223   // Returns true if the RenderWidget is hidden.
224   bool is_hidden() const { return is_hidden_; }
225
226   // Called to notify the RenderWidget that its associated native window
227   // got/lost focused.
228   virtual void GotFocus();
229   virtual void LostCapture();
230
231   // Called to notify the RenderWidget that it has lost the mouse lock.
232   virtual void LostMouseLock();
233
234   // Noifies the RenderWidget of the current mouse cursor visibility state.
235   void SendCursorVisibilityState(bool is_visible);
236
237   // Tells us whether the page is rendered directly via the GPU process.
238   bool is_accelerated_compositing_active() {
239     return is_accelerated_compositing_active_;
240   }
241
242   // Notifies the RenderWidgetHost that the View was destroyed.
243   void ViewDestroyed();
244
245   // Indicates if the page has finished loading.
246   void SetIsLoading(bool is_loading);
247
248   // Check for the existance of a BackingStore of the given |desired_size| and
249   // return it if it exists. If the BackingStore is GPU, true is returned and
250   // |*backing_store| is set to NULL.
251   bool TryGetBackingStore(const gfx::Size& desired_size,
252                           BackingStore** backing_store);
253
254   // Get access to the widget's backing store matching the size of the widget's
255   // view. If you pass |force_create| as true, then GetBackingStore may block
256   // for the renderer to send a new frame. Otherwise, NULL will be returned if
257   // the backing store doesn't already exist. It will also return NULL if the
258   // backing store could not be created.
259   //
260   // Mac only: NULL may also be returned if the last frame was GPU accelerated.
261   // Call GetView()->HasAcceleratedSurface to determine if the last frame was
262   // accelerated.
263   BackingStore* GetBackingStore(bool force_create);
264
265   // Allocate a new backing store of the given size. Returns NULL on failure
266   // (for example, if we don't currently have a RenderWidgetHostView.)
267   BackingStore* AllocBackingStore(const gfx::Size& size);
268
269   // When a backing store does asynchronous painting, it will call this function
270   // when it is done with the DIB. We will then forward a message to the
271   // renderer to send another paint.
272   void DonePaintingToBackingStore();
273
274   // GPU accelerated version of GetBackingStore function. This will
275   // trigger a re-composite to the view. It may fail if a resize is pending, or
276   // if a composite has already been requested and not acked yet.
277   bool ScheduleComposite();
278
279   // Starts a hang monitor timeout. If there's already a hang monitor timeout
280   // the new one will only fire if it has a shorter delay than the time
281   // left on the existing timeouts.
282   void StartHangMonitorTimeout(base::TimeDelta delay);
283
284   // Stops all existing hang monitor timeouts and assumes the renderer is
285   // responsive.
286   void StopHangMonitorTimeout();
287
288   // Forwards the given message to the renderer. These are called by the view
289   // when it has received a message.
290   void ForwardGestureEvent(const WebKit::WebGestureEvent& gesture_event);
291   void ForwardGestureEventWithLatencyInfo(
292       const WebKit::WebGestureEvent& gesture_event,
293       const ui::LatencyInfo& ui_latency);
294   void ForwardTouchEventWithLatencyInfo(
295       const WebKit::WebTouchEvent& touch_event,
296       const ui::LatencyInfo& ui_latency);
297   void ForwardMouseEventWithLatencyInfo(
298       const MouseEventWithLatencyInfo& mouse_event);
299   void ForwardWheelEventWithLatencyInfo(
300       const MouseWheelEventWithLatencyInfo& wheel_event);
301
302   void CancelUpdateTextDirection();
303
304   // Called when a mouse click/gesture tap activates the renderer.
305   virtual void OnPointerEventActivate();
306
307   // Notifies the renderer whether or not the input method attached to this
308   // process is activated.
309   // When the input method is activated, a renderer process sends IPC messages
310   // to notify the status of its composition node. (This message is mainly used
311   // for notifying the position of the input cursor so that the browser can
312   // display input method windows under the cursor.)
313   void SetInputMethodActive(bool activate);
314
315   // Update the composition node of the renderer (or WebKit).
316   // WebKit has a special node (a composition node) for input method to change
317   // its text without affecting any other DOM nodes. When the input method
318   // (attached to the browser) updates its text, the browser sends IPC messages
319   // to update the composition node of the renderer.
320   // (Read the comments of each function for its detail.)
321
322   // Sets the text of the composition node.
323   // This function can also update the cursor position and mark the specified
324   // range in the composition node.
325   // A browser should call this function:
326   // * when it receives a WM_IME_COMPOSITION message with a GCS_COMPSTR flag
327   //   (on Windows);
328   // * when it receives a "preedit_changed" signal of GtkIMContext (on Linux);
329   // * when markedText of NSTextInput is called (on Mac).
330   void ImeSetComposition(
331       const string16& text,
332       const std::vector<WebKit::WebCompositionUnderline>& underlines,
333       int selection_start,
334       int selection_end);
335
336   // Finishes an ongoing composition with the specified text.
337   // A browser should call this function:
338   // * when it receives a WM_IME_COMPOSITION message with a GCS_RESULTSTR flag
339   //   (on Windows);
340   // * when it receives a "commit" signal of GtkIMContext (on Linux);
341   // * when insertText of NSTextInput is called (on Mac).
342   void ImeConfirmComposition(const string16& text,
343                              const gfx::Range& replacement_range,
344                              bool keep_selection);
345
346   // Cancels an ongoing composition.
347   void ImeCancelComposition();
348
349   // Deletes the current selection plus the specified number of characters
350   // before and after the selection or caret.
351   void ExtendSelectionAndDelete(size_t before, size_t after);
352
353   // This is for derived classes to give us access to the resizer rect.
354   // And to also expose it to the RenderWidgetHostView.
355   virtual gfx::Rect GetRootWindowResizerRect() const;
356
357   bool ignore_input_events() const {
358     return ignore_input_events_;
359   }
360
361   bool input_method_active() const {
362     return input_method_active_;
363   }
364
365   // Whether forwarded WebInputEvents should be ignored.  True if either
366   // |ignore_input_events_| or |process_->IgnoreInputEvents()| is true.
367   bool IgnoreInputEvents() const;
368
369   // Event queries delegated to the |input_router_|.
370   bool ShouldForwardTouchEvent() const;
371
372   bool has_touch_handler() const { return has_touch_handler_; }
373
374   // Notification that the user has made some kind of input that could
375   // perform an action. See OnUserGesture for more details.
376   void StartUserGesture();
377
378   // Set the RenderView background.
379   void SetBackground(const SkBitmap& background);
380
381   // Notifies the renderer that the next key event is bound to one or more
382   // pre-defined edit commands
383   void SetEditCommandsForNextKeyEvent(
384       const std::vector<EditCommand>& commands);
385
386   // Gets the accessibility mode.
387   AccessibilityMode accessibility_mode() const {
388     return accessibility_mode_;
389   }
390
391   // Send a message to the renderer process to change the accessibility mode.
392   void SetAccessibilityMode(AccessibilityMode mode);
393
394   // Relay a request from assistive technology to perform the default action
395   // on a given node.
396   void AccessibilityDoDefaultAction(int object_id);
397
398   // Relay a request from assistive technology to set focus to a given node.
399   void AccessibilitySetFocus(int object_id);
400
401   // Relay a request from assistive technology to make a given object
402   // visible by scrolling as many scrollable containers as necessary.
403   // In addition, if it's not possible to make the entire object visible,
404   // scroll so that the |subfocus| rect is visible at least. The subfocus
405   // rect is in local coordinates of the object itself.
406   void AccessibilityScrollToMakeVisible(
407       int acc_obj_id, gfx::Rect subfocus);
408
409   // Relay a request from assistive technology to move a given object
410   // to a specific location, in the WebContents area coordinate space, i.e.
411   // (0, 0) is the top-left corner of the WebContents.
412   void AccessibilityScrollToPoint(int acc_obj_id, gfx::Point point);
413
414   // Relay a request from assistive technology to set text selection.
415   void AccessibilitySetTextSelection(
416       int acc_obj_id, int start_offset, int end_offset);
417
418   // Kill the renderer because we got a fatal accessibility error.
419   void FatalAccessibilityTreeError();
420
421 #if defined(OS_WIN) && defined(USE_AURA)
422   void SetParentNativeViewAccessible(
423       gfx::NativeViewAccessible accessible_parent);
424   gfx::NativeViewAccessible GetParentNativeViewAccessible() const;
425 #endif
426
427   // Executes the edit command on the RenderView.
428   void ExecuteEditCommand(const std::string& command,
429                           const std::string& value);
430
431   // Tells the renderer to scroll the currently focused node into rect only if
432   // the currently focused node is a Text node (textfield, text area or content
433   // editable divs).
434   void ScrollFocusedEditableNodeIntoRect(const gfx::Rect& rect);
435
436   // Requests the renderer to select the region between two points.
437   void SelectRange(const gfx::Point& start, const gfx::Point& end);
438
439   // Requests the renderer to move the caret selection towards the point.
440   void MoveCaret(const gfx::Point& point);
441
442   // Called when the reponse to a pending mouse lock request has arrived.
443   // Returns true if |allowed| is true and the mouse has been successfully
444   // locked.
445   bool GotResponseToLockMouseRequest(bool allowed);
446
447   // Tells the RenderWidget about the latest vsync parameters.
448   // Note: Make sure the timebase was obtained using
449   // base::TimeTicks::HighResNow. Using the non-high res timer will result in
450   // incorrect synchronization across processes.
451   virtual void UpdateVSyncParameters(base::TimeTicks timebase,
452                                      base::TimeDelta interval);
453
454   // Called by the view in response to AcceleratedSurfaceBuffersSwapped or
455   // AcceleratedSurfacePostSubBuffer.
456   static void AcknowledgeBufferPresent(
457       int32 route_id,
458       int gpu_host_id,
459       const AcceleratedSurfaceMsg_BufferPresented_Params& params);
460
461   // Called by the view in response to OnSwapCompositorFrame.
462   static void SendSwapCompositorFrameAck(
463       int32 route_id,
464       uint32 output_surface_id,
465       int renderer_host_id,
466       const cc::CompositorFrameAck& ack);
467
468   // Called by the view to return resources to the compositor.
469   static void SendReclaimCompositorResources(int32 route_id,
470                                              uint32 output_surface_id,
471                                              int renderer_host_id,
472                                              const cc::CompositorFrameAck& ack);
473
474   // Called by the view in response to AcceleratedSurfaceBuffersSwapped for
475   // platforms that support deferred GPU process descheduling. This does
476   // nothing if the compositor thread is enabled.
477   // TODO(jbates) Once the compositor thread is always on, this can be removed.
478   void AcknowledgeSwapBuffersToRenderer();
479
480   bool is_threaded_compositing_enabled() const {
481     return is_threaded_compositing_enabled_;
482   }
483
484 #if defined(USE_AURA)
485   // Called by the view when the parent changes. If a parent isn't available,
486   // NULL is used.
487   void ParentChanged(gfx::NativeViewId new_parent);
488 #endif
489
490   // Signals that the compositing surface was updated, e.g. after a lost context
491   // event.
492   void CompositingSurfaceUpdated();
493
494   void set_allow_privileged_mouse_lock(bool allow) {
495     allow_privileged_mouse_lock_ = allow;
496   }
497
498   // Resets state variables related to tracking pending size and painting.
499   //
500   // We need to reset these flags when we want to repaint the contents of
501   // browser plugin in this RWH. Resetting these flags will ensure we ignore
502   // any previous pending acks that are not relevant upon repaint.
503   void ResetSizeAndRepaintPendingFlags();
504
505   void DetachDelegate();
506
507   // Update the renderer's cache of the screen rect of the view and window.
508   void SendScreenRects();
509
510   OverscrollController* overscroll_controller() const {
511     return overscroll_controller_.get();
512   }
513
514   base::TimeDelta GetSyntheticGestureMessageInterval() const;
515
516   // Sets whether the overscroll controller should be enabled for this page.
517   void SetOverscrollControllerEnabled(bool enabled);
518
519   // Suppreses future char events until a keydown. See
520   // suppress_next_char_events_.
521   void SuppressNextCharEvents();
522
523   // Called by RenderWidgetHostView in response to OnSetNeedsFlushInput.
524   void FlushInput();
525
526   // Indicates whether the renderer drives the RenderWidgetHosts's size or the
527   // other way around.
528   bool should_auto_resize() { return should_auto_resize_; }
529
530   void ComputeTouchLatency(const ui::LatencyInfo& latency_info);
531   void FrameSwapped(const ui::LatencyInfo& latency_info);
532   void DidReceiveRendererFrame();
533
534   // Returns the ID that uniquely describes this component to the latency
535   // subsystem.
536   int64 GetLatencyComponentId();
537
538   static void CompositorFrameDrawn(const ui::LatencyInfo& latency_info);
539
540   // Don't check whether we expected a resize ack during layout tests.
541   static void DisableResizeAckCheckForTesting();
542
543  protected:
544   virtual RenderWidgetHostImpl* AsRenderWidgetHostImpl() OVERRIDE;
545
546   // Create a LatencyInfo struct with INPUT_EVENT_LATENCY_RWH_COMPONENT
547   // component if it is not already in |original|. And if |original| is
548   // not NULL, it is also merged into the resulting LatencyInfo.
549   ui::LatencyInfo CreateRWHLatencyInfoIfNotExist(
550       const ui::LatencyInfo* original);
551
552   // Called when we receive a notification indicating that the renderer
553   // process has gone. This will reset our state so that our state will be
554   // consistent if a new renderer is created.
555   void RendererExited(base::TerminationStatus status, int exit_code);
556
557   // Retrieves an id the renderer can use to refer to its view.
558   // This is used for various IPC messages, including plugins.
559   gfx::NativeViewId GetNativeViewId() const;
560
561   // Retrieves an id for the surface that the renderer can draw to
562   // when accelerated compositing is enabled.
563   gfx::GLSurfaceHandle GetCompositingSurface();
564
565   // ---------------------------------------------------------------------------
566   // The following methods are overridden by RenderViewHost to send upwards to
567   // its delegate.
568
569   // Called when a mousewheel event was not processed by the renderer.
570   virtual void UnhandledWheelEvent(const WebKit::WebMouseWheelEvent& event) {}
571
572   // Notification that the user has made some kind of input that could
573   // perform an action. The gestures that count are 1) any mouse down
574   // event and 2) enter or space key presses.
575   virtual void OnUserGesture() {}
576
577   // Callbacks for notification when the renderer becomes unresponsive to user
578   // input events, and subsequently responsive again.
579   virtual void NotifyRendererUnresponsive() {}
580   virtual void NotifyRendererResponsive() {}
581
582   // Called when auto-resize resulted in the renderer size changing.
583   virtual void OnRenderAutoResized(const gfx::Size& new_size) {}
584
585   // ---------------------------------------------------------------------------
586
587   // RenderViewHost overrides this method to impose further restrictions on when
588   // to allow mouse lock.
589   // Once the request is approved or rejected, GotResponseToLockMouseRequest()
590   // will be called.
591   virtual void RequestToLockMouse(bool user_gesture,
592                                   bool last_unlocked_by_target);
593
594   void RejectMouseLockOrUnlockIfNecessary();
595   bool IsMouseLocked() const;
596
597   // RenderViewHost overrides this method to report when in fullscreen mode.
598   virtual bool IsFullscreen() const;
599
600   // Indicates if the render widget host should track the render widget's size
601   // as opposed to visa versa.
602   void SetShouldAutoResize(bool enable);
603
604   // Expose increment/decrement of the in-flight event count, so
605   // RenderViewHostImpl can account for in-flight beforeunload/unload events.
606   int increment_in_flight_event_count() { return ++in_flight_event_count_; }
607   int decrement_in_flight_event_count() { return --in_flight_event_count_; }
608
609   // Returns whether an overscroll gesture is in progress.
610   bool IsInOverscrollGesture() const;
611
612   // The View associated with the RenderViewHost. The lifetime of this object
613   // is associated with the lifetime of the Render process. If the Renderer
614   // crashes, its View is destroyed and this pointer becomes NULL, even though
615   // render_view_host_ lives on to load another URL (creating a new View while
616   // doing so).
617   RenderWidgetHostViewPort* view_;
618
619   // true if a renderer has once been valid. We use this flag to display a sad
620   // tab only when we lose our renderer and not if a paint occurs during
621   // initialization.
622   bool renderer_initialized_;
623
624   // This value indicates how long to wait before we consider a renderer hung.
625   int hung_renderer_delay_ms_;
626
627  private:
628   friend class MockRenderWidgetHost;
629
630   // Tell this object to destroy itself.
631   void Destroy();
632
633   // Checks whether the renderer is hung and calls NotifyRendererUnresponsive
634   // if it is.
635   void CheckRendererIsUnresponsive();
636
637   // Called if we know the renderer is responsive. When we currently think the
638   // renderer is unresponsive, this will clear that state and call
639   // NotifyRendererResponsive.
640   void RendererIsResponsive();
641
642   // IPC message handlers
643   void OnRenderViewReady();
644   void OnRenderProcessGone(int status, int error_code);
645   void OnClose();
646   void OnUpdateScreenRectsAck();
647   void OnRequestMove(const gfx::Rect& pos);
648   void OnSetTooltipText(const string16& tooltip_text,
649                         WebKit::WebTextDirection text_direction_hint);
650   void OnPaintAtSizeAck(int tag, const gfx::Size& size);
651 #if defined(OS_MACOSX)
652   void OnCompositorSurfaceBuffersSwapped(
653       const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
654 #endif
655   bool OnSwapCompositorFrame(const IPC::Message& message);
656   void OnOverscrolled(gfx::Vector2dF accumulated_overscroll,
657                       gfx::Vector2dF current_fling_velocity);
658   void OnUpdateRect(const ViewHostMsg_UpdateRect_Params& params);
659   void OnUpdateIsDelayed();
660   void OnBeginSmoothScroll(
661       const ViewHostMsg_BeginSmoothScroll_Params& params);
662   void OnBeginPinch(
663       const ViewHostMsg_BeginPinch_Params& params);
664   virtual void OnFocus();
665   virtual void OnBlur();
666   void OnSetCursor(const WebCursor& cursor);
667   void OnTextInputTypeChanged(ui::TextInputType type,
668                               ui::TextInputMode input_mode,
669                               bool can_compose_inline);
670 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
671   void OnImeCompositionRangeChanged(
672       const gfx::Range& range,
673       const std::vector<gfx::Rect>& character_bounds);
674 #endif
675   void OnImeCancelComposition();
676   void OnDidActivateAcceleratedCompositing(bool activated);
677   void OnLockMouse(bool user_gesture,
678                    bool last_unlocked_by_target,
679                    bool privileged);
680   void OnUnlockMouse();
681   void OnShowDisambiguationPopup(const gfx::Rect& rect,
682                                  const gfx::Size& size,
683                                  const TransportDIB::Id& id);
684 #if defined(OS_WIN)
685   void OnWindowlessPluginDummyWindowCreated(
686       gfx::NativeViewId dummy_activation_window);
687   void OnWindowlessPluginDummyWindowDestroyed(
688       gfx::NativeViewId dummy_activation_window);
689 #endif
690   void OnSnapshot(bool success, const SkBitmap& bitmap);
691
692   // Called (either immediately or asynchronously) after we're done with our
693   // BackingStore and can send an ACK to the renderer so it can paint onto it
694   // again.
695   void DidUpdateBackingStore(const ViewHostMsg_UpdateRect_Params& params,
696                              const base::TimeTicks& paint_start);
697
698   // Paints the given bitmap to the current backing store at the given
699   // location.  Returns true if the passed callback was asynchronously
700   // scheduled in the future (and thus the caller must manually synchronously
701   // call the callback function).
702   bool PaintBackingStoreRect(TransportDIB::Id bitmap,
703                              const gfx::Rect& bitmap_rect,
704                              const std::vector<gfx::Rect>& copy_rects,
705                              const gfx::Size& view_size,
706                              float scale_factor,
707                              const base::Closure& completion_callback);
708
709   // Scrolls the given |clip_rect| in the backing by the given dx/dy amount. The
710   // |dib| and its corresponding location |bitmap_rect| in the backing store
711   // is the newly painted pixels by the renderer.
712   void ScrollBackingStoreRect(const gfx::Vector2d& delta,
713                               const gfx::Rect& clip_rect,
714                               const gfx::Size& view_size);
715
716   // Give key press listeners a chance to handle this key press. This allow
717   // widgets that don't have focus to still handle key presses.
718   bool KeyPressListenersHandleEvent(const NativeWebKeyboardEvent& event);
719
720   // InputRouterClient
721   virtual InputEventAckState FilterInputEvent(
722       const WebKit::WebInputEvent& event,
723       const ui::LatencyInfo& latency_info) OVERRIDE;
724   virtual void IncrementInFlightEventCount() OVERRIDE;
725   virtual void DecrementInFlightEventCount() OVERRIDE;
726   virtual void OnHasTouchEventHandlers(bool has_handlers) OVERRIDE;
727   virtual OverscrollController* GetOverscrollController() const OVERRIDE;
728   virtual void SetNeedsFlush() OVERRIDE;
729   virtual void DidFlush() OVERRIDE;
730
731   // InputAckHandler
732   virtual void OnKeyboardEventAck(const NativeWebKeyboardEvent& event,
733                                   InputEventAckState ack_result) OVERRIDE;
734   virtual void OnWheelEventAck(const MouseWheelEventWithLatencyInfo& event,
735                                InputEventAckState ack_result) OVERRIDE;
736   virtual void OnTouchEventAck(const TouchEventWithLatencyInfo& event,
737                                InputEventAckState ack_result) OVERRIDE;
738   virtual void OnGestureEventAck(const GestureEventWithLatencyInfo& event,
739                                  InputEventAckState ack_result) OVERRIDE;
740   virtual void OnUnexpectedEventAck(UnexpectedEventAckType type) OVERRIDE;
741
742   // Called when there is a new auto resize (using a post to avoid a stack
743   // which may get in recursive loops).
744   void DelayedAutoResized();
745
746   void WindowSnapshotReachedScreen(int snapshot_id);
747
748   // Our delegate, which wants to know mainly about keyboard events.
749   // It will remain non-NULL until DetachDelegate() is called.
750   RenderWidgetHostDelegate* delegate_;
751
752   // Created during construction but initialized during Init*(). Therefore, it
753   // is guaranteed never to be NULL, but its channel may be NULL if the
754   // renderer crashed, so you must always check that.
755   RenderProcessHost* process_;
756
757   // The ID of the corresponding object in the Renderer Instance.
758   int routing_id_;
759
760   // The ID of the surface corresponding to this render widget.
761   int surface_id_;
762
763   // Indicates whether a page is loading or not.
764   bool is_loading_;
765
766   // Indicates whether a page is hidden or not.
767   bool is_hidden_;
768
769   // Indicates whether a page is fullscreen or not.
770   bool is_fullscreen_;
771
772   // True when a page is rendered directly via the GPU process.
773   bool is_accelerated_compositing_active_;
774
775   // True if threaded compositing is enabled on this view.
776   bool is_threaded_compositing_enabled_;
777
778   // Set if we are waiting for a repaint ack for the view.
779   bool repaint_ack_pending_;
780
781   // True when waiting for RESIZE_ACK.
782   bool resize_ack_pending_;
783
784   // Cached copy of the screen info so that it doesn't need to be updated every
785   // time the window is resized.
786   scoped_ptr<WebKit::WebScreenInfo> screen_info_;
787
788   // Set if screen_info_ may have changed and should be recomputed and force a
789   // resize message.
790   bool screen_info_out_of_date_;
791
792   // The current size of the RenderWidget.
793   gfx::Size current_size_;
794
795   // The size of the view's backing surface in non-DPI-adjusted pixels.
796   gfx::Size physical_backing_size_;
797
798   // The height of the physical backing surface that is overdrawn opaquely in
799   // the browser, for example by an on-screen-keyboard (in DPI-adjusted pixels).
800   float overdraw_bottom_height_;
801
802   // The size we last sent as requested size to the renderer. |current_size_|
803   // is only updated once the resize message has been ack'd. This on the other
804   // hand is updated when the resize message is sent. This is very similar to
805   // |resize_ack_pending_|, but the latter is not set if the new size has width
806   // or height zero, which is why we need this too.
807   gfx::Size last_requested_size_;
808
809   // The next auto resize to send.
810   gfx::Size new_auto_size_;
811
812   // True if the render widget host should track the render widget's size as
813   // opposed to visa versa.
814   bool should_auto_resize_;
815
816   bool waiting_for_screen_rects_ack_;
817   gfx::Rect last_view_screen_rect_;
818   gfx::Rect last_window_screen_rect_;
819
820   AccessibilityMode accessibility_mode_;
821
822   // Keyboard event listeners.
823   std::vector<KeyPressEventCallback> key_press_event_callbacks_;
824
825   // Mouse event callbacks.
826   std::vector<MouseEventCallback> mouse_event_callbacks_;
827
828   // If true, then we should repaint when restoring even if we have a
829   // backingstore.  This flag is set to true if we receive a paint message
830   // while is_hidden_ to true.  Even though we tell the render widget to hide
831   // itself, a paint message could already be in flight at that point.
832   bool needs_repainting_on_restore_;
833
834   // This is true if the renderer is currently unresponsive.
835   bool is_unresponsive_;
836
837   // The following value indicates a time in the future when we would consider
838   // the renderer hung if it does not generate an appropriate response message.
839   base::Time time_when_considered_hung_;
840
841   // This value denotes the number of input events yet to be acknowledged
842   // by the renderer.
843   int in_flight_event_count_;
844
845   // This timer runs to check if time_when_considered_hung_ has past.
846   base::OneShotTimer<RenderWidgetHostImpl> hung_renderer_timer_;
847
848   // Flag to detect recursive calls to GetBackingStore().
849   bool in_get_backing_store_;
850
851   // Flag to trigger the GetBackingStore method to abort early.
852   bool abort_get_backing_store_;
853
854   // Set when we call DidPaintRect/DidScrollRect on the view.
855   bool view_being_painted_;
856
857   // Used for UMA histogram logging to measure the time for a repaint view
858   // operation to finish.
859   base::TimeTicks repaint_start_time_;
860
861   // Set to true if we shouldn't send input events from the render widget.
862   bool ignore_input_events_;
863
864   // Indicates whether IME is active.
865   bool input_method_active_;
866
867   // Set when we update the text direction of the selected input element.
868   bool text_direction_updated_;
869   WebKit::WebTextDirection text_direction_;
870
871   // Set when we cancel updating the text direction.
872   // This flag also ignores succeeding update requests until we call
873   // NotifyTextDirection().
874   bool text_direction_canceled_;
875
876   // Indicates if the next sequence of Char events should be suppressed or not.
877   // System may translate a RawKeyDown event into zero or more Char events,
878   // usually we send them to the renderer directly in sequence. However, If a
879   // RawKeyDown event was not handled by the renderer but was handled by
880   // our UnhandledKeyboardEvent() method, e.g. as an accelerator key, then we
881   // shall not send the following sequence of Char events, which was generated
882   // by this RawKeyDown event, to the renderer. Otherwise the renderer may
883   // handle the Char events and cause unexpected behavior.
884   // For example, pressing alt-2 may let the browser switch to the second tab,
885   // but the Char event generated by alt-2 may also activate a HTML element
886   // if its accesskey happens to be "2", then the user may get confused when
887   // switching back to the original tab, because the content may already be
888   // changed.
889   bool suppress_next_char_events_;
890
891   // The last scroll offset of the render widget.
892   gfx::Vector2d last_scroll_offset_;
893
894   bool pending_mouse_lock_request_;
895   bool allow_privileged_mouse_lock_;
896
897   // Keeps track of whether the webpage has any touch event handler. If it does,
898   // then touch events are sent to the renderer. Otherwise, the touch events are
899   // not sent to the renderer.
900   bool has_touch_handler_;
901
902   base::WeakPtrFactory<RenderWidgetHostImpl> weak_factory_;
903
904   SyntheticGestureController synthetic_gesture_controller_;
905
906   // Receives and handles all input events.
907   scoped_ptr<InputRouter> input_router_;
908
909   scoped_ptr<OverscrollController> overscroll_controller_;
910
911 #if defined(OS_WIN)
912   std::list<HWND> dummy_windows_for_activation_;
913 #endif
914
915   // List of callbacks for pending snapshot requests to the renderer.
916   std::queue<base::Callback<void(bool, const SkBitmap&)> > pending_snapshots_;
917
918   int64 last_input_number_;
919
920   BrowserRenderingStats rendering_stats_;
921
922   DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostImpl);
923 };
924
925 }  // namespace content
926
927 #endif  // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_IMPL_H_