• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "cc/resources/shared_bitmap.h"
27 #include "content/browser/renderer_host/event_with_latency_info.h"
28 #include "content/browser/renderer_host/input/input_ack_handler.h"
29 #include "content/browser/renderer_host/input/input_router_client.h"
30 #include "content/browser/renderer_host/input/synthetic_gesture.h"
31 #include "content/browser/renderer_host/input/touch_emulator_client.h"
32 #include "content/common/input/input_event_ack_state.h"
33 #include "content/common/input/synthetic_gesture_packet.h"
34 #include "content/common/view_message_enums.h"
35 #include "content/public/browser/render_widget_host.h"
36 #include "content/public/common/page_zoom.h"
37 #include "ipc/ipc_listener.h"
38 #include "ui/base/ime/text_input_mode.h"
39 #include "ui/base/ime/text_input_type.h"
40 #include "ui/events/latency_info.h"
41 #include "ui/gfx/native_widget_types.h"
42 
43 struct AcceleratedSurfaceMsg_BufferPresented_Params;
44 struct ViewHostMsg_BeginSmoothScroll_Params;
45 struct ViewHostMsg_SelectionBounds_Params;
46 struct ViewHostMsg_TextInputState_Params;
47 struct ViewHostMsg_UpdateRect_Params;
48 struct ViewMsg_Resize_Params;
49 
50 namespace base {
51 class TimeTicks;
52 }
53 
54 namespace cc {
55 class CompositorFrame;
56 class CompositorFrameAck;
57 }
58 
59 namespace gfx {
60 class Range;
61 }
62 
63 namespace ui {
64 class KeyEvent;
65 }
66 
67 namespace blink {
68 class WebInputEvent;
69 class WebMouseEvent;
70 struct WebCompositionUnderline;
71 struct WebScreenInfo;
72 }
73 
74 #if defined(OS_ANDROID)
75 namespace blink {
76 class WebLayer;
77 }
78 #endif
79 
80 namespace content {
81 class BrowserAccessibilityManager;
82 class InputRouter;
83 class MockRenderWidgetHost;
84 class RenderWidgetHostDelegate;
85 class RenderWidgetHostViewBase;
86 class SyntheticGestureController;
87 class TimeoutMonitor;
88 class TouchEmulator;
89 class WebCursor;
90 struct EditCommand;
91 
92 // This implements the RenderWidgetHost interface that is exposed to
93 // embedders of content, and adds things only visible to content.
94 class CONTENT_EXPORT RenderWidgetHostImpl
95     : virtual public RenderWidgetHost,
96       public InputRouterClient,
97       public InputAckHandler,
98       public TouchEmulatorClient,
99       public IPC::Listener {
100  public:
101   // routing_id can be MSG_ROUTING_NONE, in which case the next available
102   // routing id is taken from the RenderProcessHost.
103   // If this object outlives |delegate|, DetachDelegate() must be called when
104   // |delegate| goes away.
105   RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
106                        RenderProcessHost* process,
107                        int routing_id,
108                        bool hidden);
109   virtual ~RenderWidgetHostImpl();
110 
111   // Similar to RenderWidgetHost::FromID, but returning the Impl object.
112   static RenderWidgetHostImpl* FromID(int32 process_id, int32 routing_id);
113 
114   // Returns all RenderWidgetHosts including swapped out ones for
115   // internal use. The public interface
116   // RendgerWidgetHost::GetRenderWidgetHosts only returns active ones.
117   static scoped_ptr<RenderWidgetHostIterator> GetAllRenderWidgetHosts();
118 
119   // Use RenderWidgetHostImpl::From(rwh) to downcast a
120   // RenderWidgetHost to a RenderWidgetHostImpl.  Internally, this
121   // uses RenderWidgetHost::AsRenderWidgetHostImpl().
122   static RenderWidgetHostImpl* From(RenderWidgetHost* rwh);
123 
set_hung_renderer_delay_ms(const base::TimeDelta & timeout)124   void set_hung_renderer_delay_ms(const base::TimeDelta& timeout) {
125     hung_renderer_delay_ms_ = timeout.InMilliseconds();
126   }
127 
128   // RenderWidgetHost implementation.
129   virtual void UpdateTextDirection(blink::WebTextDirection direction) OVERRIDE;
130   virtual void NotifyTextDirection() OVERRIDE;
131   virtual void Focus() OVERRIDE;
132   virtual void Blur() OVERRIDE;
133   virtual void SetActive(bool active) OVERRIDE;
134   virtual void CopyFromBackingStore(
135       const gfx::Rect& src_rect,
136       const gfx::Size& accelerated_dst_size,
137       const base::Callback<void(bool, const SkBitmap&)>& callback,
138       const SkColorType color_type) OVERRIDE;
139   virtual bool CanCopyFromBackingStore() OVERRIDE;
140 #if defined(OS_ANDROID)
141   virtual void LockBackingStore() OVERRIDE;
142   virtual void UnlockBackingStore() OVERRIDE;
143 #endif
144   virtual void ForwardMouseEvent(
145       const blink::WebMouseEvent& mouse_event) OVERRIDE;
146   virtual void ForwardWheelEvent(
147       const blink::WebMouseWheelEvent& wheel_event) OVERRIDE;
148   virtual void ForwardKeyboardEvent(
149       const NativeWebKeyboardEvent& key_event) OVERRIDE;
150   virtual RenderProcessHost* GetProcess() const OVERRIDE;
151   virtual int GetRoutingID() const OVERRIDE;
152   virtual RenderWidgetHostView* GetView() const OVERRIDE;
153   virtual bool IsLoading() const OVERRIDE;
154   virtual bool IsRenderView() const OVERRIDE;
155   virtual void ResizeRectChanged(const gfx::Rect& new_rect) OVERRIDE;
156   virtual void RestartHangMonitorTimeout() OVERRIDE;
157   virtual void SetIgnoreInputEvents(bool ignore_input_events) OVERRIDE;
158   virtual void WasResized() OVERRIDE;
159   virtual void AddKeyPressEventCallback(
160       const KeyPressEventCallback& callback) OVERRIDE;
161   virtual void RemoveKeyPressEventCallback(
162       const KeyPressEventCallback& callback) OVERRIDE;
163   virtual void AddMouseEventCallback(
164       const MouseEventCallback& callback) OVERRIDE;
165   virtual void RemoveMouseEventCallback(
166       const MouseEventCallback& callback) OVERRIDE;
167   virtual void GetWebScreenInfo(blink::WebScreenInfo* result) OVERRIDE;
168 
169   virtual SkColorType PreferredReadbackFormat() OVERRIDE;
170 
171   // Forces redraw in the renderer and when the update reaches the browser
172   // grabs snapshot from the compositor. Returns PNG-encoded snapshot.
173   void GetSnapshotFromBrowser(
174       const base::Callback<void(const unsigned char*,size_t)> callback);
175 
176   const NativeWebKeyboardEvent* GetLastKeyboardEvent() const;
177 
178   // Notification that the screen info has changed.
179   void NotifyScreenInfoChanged();
180 
181   // Invalidates the cached screen info so that next resize request
182   // will carry the up to date screen info. Unlike
183   // |NotifyScreenInfoChanged|, this doesn't send a message to the renderer.
184   void InvalidateScreenInfo();
185 
186   // Sets the View of this RenderWidgetHost.
187   void SetView(RenderWidgetHostViewBase* view);
188 
surface_id()189   int surface_id() const { return surface_id_; }
190 
empty()191   bool empty() const { return current_size_.IsEmpty(); }
192 
193   // Called when a renderer object already been created for this host, and we
194   // just need to be attached to it. Used for window.open, <select> dropdown
195   // menus, and other times when the renderer initiates creating an object.
196   virtual void Init();
197 
198   // Tells the renderer to die and then calls Destroy().
199   virtual void Shutdown();
200 
201   // IPC::Listener
202   virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
203 
204   // Sends a message to the corresponding object in the renderer.
205   virtual bool Send(IPC::Message* msg) OVERRIDE;
206 
207   // Indicates if the page has finished loading.
208   virtual void SetIsLoading(bool is_loading);
209 
210   // Called to notify the RenderWidget that it has been hidden or restored from
211   // having been hidden.
212   virtual void WasHidden();
213   virtual void WasShown(const ui::LatencyInfo& latency_info);
214 
215   // Returns true if the RenderWidget is hidden.
is_hidden()216   bool is_hidden() const { return is_hidden_; }
217 
218   // Called to notify the RenderWidget that its associated native window
219   // got/lost focused.
220   virtual void GotFocus();
221   virtual void LostCapture();
222 
223   // Called to notify the RenderWidget that it has lost the mouse lock.
224   virtual void LostMouseLock();
225 
226   // Noifies the RenderWidget of the current mouse cursor visibility state.
227   void SendCursorVisibilityState(bool is_visible);
228 
229   // Notifies the RenderWidgetHost that the View was destroyed.
230   void ViewDestroyed();
231 
232 #if defined(OS_MACOSX)
233   // Pause for a moment to wait for pending repaint or resize messages sent to
234   // the renderer to arrive. If pending resize messages are for an old window
235   // size, then also pump through a new resize message if there is time.
236   void PauseForPendingResizeOrRepaints();
237 
238   // Whether pausing may be useful.
239   bool CanPauseForPendingResizeOrRepaints();
240 
241   // Wait for a surface matching the size of the widget's view, possibly
242   // blocking until the renderer sends a new frame.
243   void WaitForSurface();
244 #endif
245 
resize_ack_pending_for_testing()246   bool resize_ack_pending_for_testing() { return resize_ack_pending_; }
247 
248   // GPU accelerated version of GetBackingStore function. This will
249   // trigger a re-composite to the view. It may fail if a resize is pending, or
250   // if a composite has already been requested and not acked yet.
251   bool ScheduleComposite();
252 
253   // Starts a hang monitor timeout. If there's already a hang monitor timeout
254   // the new one will only fire if it has a shorter delay than the time
255   // left on the existing timeouts.
256   void StartHangMonitorTimeout(base::TimeDelta delay);
257 
258   // Stops all existing hang monitor timeouts and assumes the renderer is
259   // responsive.
260   void StopHangMonitorTimeout();
261 
262   // Forwards the given message to the renderer. These are called by the view
263   // when it has received a message.
264   void ForwardGestureEventWithLatencyInfo(
265       const blink::WebGestureEvent& gesture_event,
266       const ui::LatencyInfo& ui_latency);
267   void ForwardTouchEventWithLatencyInfo(
268       const blink::WebTouchEvent& touch_event,
269       const ui::LatencyInfo& ui_latency);
270   void ForwardMouseEventWithLatencyInfo(
271       const blink::WebMouseEvent& mouse_event,
272       const ui::LatencyInfo& ui_latency);
273   void ForwardWheelEventWithLatencyInfo(
274       const blink::WebMouseWheelEvent& wheel_event,
275       const ui::LatencyInfo& ui_latency);
276 
277   // Enables/disables touch emulation using mouse event. See TouchEmulator.
278   void SetTouchEventEmulationEnabled(bool enabled);
279 
280   // TouchEmulatorClient implementation.
281   virtual void ForwardGestureEvent(
282       const blink::WebGestureEvent& gesture_event) OVERRIDE;
283   virtual void ForwardEmulatedTouchEvent(
284       const blink::WebTouchEvent& touch_event) OVERRIDE;
285   virtual void SetCursor(const WebCursor& cursor) OVERRIDE;
286   virtual void ShowContextMenuAtPoint(const gfx::Point& point) OVERRIDE;
287 
288   // Queues a synthetic gesture for testing purposes.  Invokes the on_complete
289   // callback when the gesture is finished running.
290   void QueueSyntheticGesture(
291       scoped_ptr<SyntheticGesture> synthetic_gesture,
292       const base::Callback<void(SyntheticGesture::Result)>& on_complete);
293 
294   void CancelUpdateTextDirection();
295 
296   // Called when a mouse click/gesture tap activates the renderer.
297   virtual void OnPointerEventActivate();
298 
299   // Notifies the renderer whether or not the input method attached to this
300   // process is activated.
301   // When the input method is activated, a renderer process sends IPC messages
302   // to notify the status of its composition node. (This message is mainly used
303   // for notifying the position of the input cursor so that the browser can
304   // display input method windows under the cursor.)
305   void SetInputMethodActive(bool activate);
306 
307   // Notifies the renderer changes of IME candidate window state.
308   void CandidateWindowShown();
309   void CandidateWindowUpdated();
310   void CandidateWindowHidden();
311 
312   // Update the composition node of the renderer (or WebKit).
313   // WebKit has a special node (a composition node) for input method to change
314   // its text without affecting any other DOM nodes. When the input method
315   // (attached to the browser) updates its text, the browser sends IPC messages
316   // to update the composition node of the renderer.
317   // (Read the comments of each function for its detail.)
318 
319   // Sets the text of the composition node.
320   // This function can also update the cursor position and mark the specified
321   // range in the composition node.
322   // A browser should call this function:
323   // * when it receives a WM_IME_COMPOSITION message with a GCS_COMPSTR flag
324   //   (on Windows);
325   // * when it receives a "preedit_changed" signal of GtkIMContext (on Linux);
326   // * when markedText of NSTextInput is called (on Mac).
327   void ImeSetComposition(
328       const base::string16& text,
329       const std::vector<blink::WebCompositionUnderline>& underlines,
330       int selection_start,
331       int selection_end);
332 
333   // Finishes an ongoing composition with the specified text.
334   // A browser should call this function:
335   // * when it receives a WM_IME_COMPOSITION message with a GCS_RESULTSTR flag
336   //   (on Windows);
337   // * when it receives a "commit" signal of GtkIMContext (on Linux);
338   // * when insertText of NSTextInput is called (on Mac).
339   void ImeConfirmComposition(const base::string16& text,
340                              const gfx::Range& replacement_range,
341                              bool keep_selection);
342 
343   // Cancels an ongoing composition.
344   void ImeCancelComposition();
345 
346   // This is for derived classes to give us access to the resizer rect.
347   // And to also expose it to the RenderWidgetHostView.
348   virtual gfx::Rect GetRootWindowResizerRect() const;
349 
ignore_input_events()350   bool ignore_input_events() const {
351     return ignore_input_events_;
352   }
353 
input_method_active()354   bool input_method_active() const {
355     return input_method_active_;
356   }
357 
358   // Whether forwarded WebInputEvents should be ignored.  True if either
359   // |ignore_input_events_| or |process_->IgnoreInputEvents()| is true.
360   bool IgnoreInputEvents() const;
361 
362   // Event queries delegated to the |input_router_|.
363   bool ShouldForwardTouchEvent() const;
364 
has_touch_handler()365   bool has_touch_handler() const { return has_touch_handler_; }
366 
367   // Notification that the user has made some kind of input that could
368   // perform an action. See OnUserGesture for more details.
369   void StartUserGesture();
370 
371   // Set the RenderView background transparency.
372   void SetBackgroundOpaque(bool opaque);
373 
374   // Notifies the renderer that the next key event is bound to one or more
375   // pre-defined edit commands
376   void SetEditCommandsForNextKeyEvent(
377       const std::vector<EditCommand>& commands);
378 
379   // Executes the edit command on the RenderView.
380   void ExecuteEditCommand(const std::string& command,
381                           const std::string& value);
382 
383   // Tells the renderer to scroll the currently focused node into rect only if
384   // the currently focused node is a Text node (textfield, text area or content
385   // editable divs).
386   void ScrollFocusedEditableNodeIntoRect(const gfx::Rect& rect);
387 
388   // Requests the renderer to move the caret selection towards the point.
389   void MoveCaret(const gfx::Point& point);
390 
391   // Called when the reponse to a pending mouse lock request has arrived.
392   // Returns true if |allowed| is true and the mouse has been successfully
393   // locked.
394   bool GotResponseToLockMouseRequest(bool allowed);
395 
396   // Tells the RenderWidget about the latest vsync parameters.
397   // Note: Make sure the timebase was obtained using
398   // base::TimeTicks::HighResNow. Using the non-high res timer will result in
399   // incorrect synchronization across processes.
400   virtual void UpdateVSyncParameters(base::TimeTicks timebase,
401                                      base::TimeDelta interval);
402 
403   // Called by the view in response to AcceleratedSurfaceBuffersSwapped or
404   // AcceleratedSurfacePostSubBuffer.
405   static void AcknowledgeBufferPresent(
406       int32 route_id,
407       int gpu_host_id,
408       const AcceleratedSurfaceMsg_BufferPresented_Params& params);
409 
410   // Called by the view in response to OnSwapCompositorFrame.
411   static void SendSwapCompositorFrameAck(
412       int32 route_id,
413       uint32 output_surface_id,
414       int renderer_host_id,
415       const cc::CompositorFrameAck& ack);
416 
417   // Called by the view to return resources to the compositor.
418   static void SendReclaimCompositorResources(int32 route_id,
419                                              uint32 output_surface_id,
420                                              int renderer_host_id,
421                                              const cc::CompositorFrameAck& ack);
422 
set_allow_privileged_mouse_lock(bool allow)423   void set_allow_privileged_mouse_lock(bool allow) {
424     allow_privileged_mouse_lock_ = allow;
425   }
426 
427   // Resets state variables related to tracking pending size and painting.
428   //
429   // We need to reset these flags when we want to repaint the contents of
430   // browser plugin in this RWH. Resetting these flags will ensure we ignore
431   // any previous pending acks that are not relevant upon repaint.
432   void ResetSizeAndRepaintPendingFlags();
433 
434   void DetachDelegate();
435 
436   // Update the renderer's cache of the screen rect of the view and window.
437   void SendScreenRects();
438 
439   // Suppreses future char events until a keydown. See
440   // suppress_next_char_events_.
441   void SuppressNextCharEvents();
442 
443   // Called by RenderWidgetHostView in response to OnSetNeedsFlushInput.
444   void FlushInput();
445 
446   // InputRouterClient
447   virtual void SetNeedsFlush() OVERRIDE;
448 
449   // Indicates whether the renderer drives the RenderWidgetHosts's size or the
450   // other way around.
auto_resize_enabled()451   bool auto_resize_enabled() { return auto_resize_enabled_; }
452 
453   // The minimum size of this renderer when auto-resize is enabled.
min_size_for_auto_resize()454   const gfx::Size& min_size_for_auto_resize() const {
455     return min_size_for_auto_resize_;
456   }
457 
458   // The maximum size of this renderer when auto-resize is enabled.
max_size_for_auto_resize()459   const gfx::Size& max_size_for_auto_resize() const {
460     return max_size_for_auto_resize_;
461   }
462 
463   void ComputeTouchLatency(const ui::LatencyInfo& latency_info);
464   void FrameSwapped(const ui::LatencyInfo& latency_info);
465   void DidReceiveRendererFrame();
466 
467   // Returns the ID that uniquely describes this component to the latency
468   // subsystem.
469   int64 GetLatencyComponentId();
470 
471   static void CompositorFrameDrawn(
472       const std::vector<ui::LatencyInfo>& latency_info);
473 
474   // Don't check whether we expected a resize ack during layout tests.
475   static void DisableResizeAckCheckForTesting();
476 
477   void WindowSnapshotAsyncCallback(
478       int routing_id,
479       int snapshot_id,
480       gfx::Size snapshot_size,
481       scoped_refptr<base::RefCountedBytes> png_data);
482 
483   // LatencyComponents generated in the renderer must have component IDs
484   // provided to them by the browser process. This function adds the correct
485   // component ID where necessary.
486   void AddLatencyInfoComponentIds(ui::LatencyInfo* latency_info);
487 
input_router()488   InputRouter* input_router() { return input_router_.get(); }
489 
490   // Get the BrowserAccessibilityManager for the root of the frame tree,
491   BrowserAccessibilityManager* GetRootBrowserAccessibilityManager();
492 
493   // Get the BrowserAccessibilityManager for the root of the frame tree,
494   // or create it if it doesn't already exist.
495   BrowserAccessibilityManager* GetOrCreateRootBrowserAccessibilityManager();
496 
497 #if defined(OS_WIN)
498   gfx::NativeViewAccessible GetParentNativeViewAccessible();
499 #endif
500 
501  protected:
502   virtual RenderWidgetHostImpl* AsRenderWidgetHostImpl() OVERRIDE;
503 
504   // Create a LatencyInfo struct with INPUT_EVENT_LATENCY_RWH_COMPONENT
505   // component if it is not already in |original|. And if |original| is
506   // not NULL, it is also merged into the resulting LatencyInfo.
507   ui::LatencyInfo CreateRWHLatencyInfoIfNotExist(
508       const ui::LatencyInfo* original,
509       blink::WebInputEvent::Type type,
510       const ui::LatencyInfo::InputCoordinate* logical_coordinates,
511       size_t logical_coordinates_size);
512 
513   // Called when we receive a notification indicating that the renderer
514   // process has gone. This will reset our state so that our state will be
515   // consistent if a new renderer is created.
516   void RendererExited(base::TerminationStatus status, int exit_code);
517 
518   // Retrieves an id the renderer can use to refer to its view.
519   // This is used for various IPC messages, including plugins.
520   gfx::NativeViewId GetNativeViewId() const;
521 
522   // Retrieves an id for the surface that the renderer can draw to
523   // when accelerated compositing is enabled.
524   gfx::GLSurfaceHandle GetCompositingSurface();
525 
526   // ---------------------------------------------------------------------------
527   // The following methods are overridden by RenderViewHost to send upwards to
528   // its delegate.
529 
530   // Called when a mousewheel event was not processed by the renderer.
UnhandledWheelEvent(const blink::WebMouseWheelEvent & event)531   virtual void UnhandledWheelEvent(const blink::WebMouseWheelEvent& event) {}
532 
533   // Notification that the user has made some kind of input that could
534   // perform an action. The gestures that count are 1) any mouse down
535   // event and 2) enter or space key presses.
OnUserGesture()536   virtual void OnUserGesture() {}
537 
538   // Callbacks for notification when the renderer becomes unresponsive to user
539   // input events, and subsequently responsive again.
NotifyRendererUnresponsive()540   virtual void NotifyRendererUnresponsive() {}
NotifyRendererResponsive()541   virtual void NotifyRendererResponsive() {}
542 
543   // Called when auto-resize resulted in the renderer size changing.
OnRenderAutoResized(const gfx::Size & new_size)544   virtual void OnRenderAutoResized(const gfx::Size& new_size) {}
545 
546   // ---------------------------------------------------------------------------
547 
548   // RenderViewHost overrides this method to impose further restrictions on when
549   // to allow mouse lock.
550   // Once the request is approved or rejected, GotResponseToLockMouseRequest()
551   // will be called.
552   virtual void RequestToLockMouse(bool user_gesture,
553                                   bool last_unlocked_by_target);
554 
555   void RejectMouseLockOrUnlockIfNecessary();
556   bool IsMouseLocked() const;
557 
558   // RenderViewHost overrides this method to report when in fullscreen mode.
559   virtual bool IsFullscreen() const;
560 
561   // Indicates if the render widget host should track the render widget's size
562   // as opposed to visa versa.
563   void SetAutoResize(bool enable,
564                      const gfx::Size& min_size,
565                      const gfx::Size& max_size);
566 
567   // Fills in the |resize_params| struct.
568   void GetResizeParams(ViewMsg_Resize_Params* resize_params);
569 
570   // Sets the |resize_params| that were sent to the renderer bundled with the
571   // request to create a new RenderWidget.
572   void SetInitialRenderSizeParams(const ViewMsg_Resize_Params& resize_params);
573 
574   // Expose increment/decrement of the in-flight event count, so
575   // RenderViewHostImpl can account for in-flight beforeunload/unload events.
increment_in_flight_event_count()576   int increment_in_flight_event_count() { return ++in_flight_event_count_; }
decrement_in_flight_event_count()577   int decrement_in_flight_event_count() { return --in_flight_event_count_; }
578 
579   // The View associated with the RenderViewHost. The lifetime of this object
580   // is associated with the lifetime of the Render process. If the Renderer
581   // crashes, its View is destroyed and this pointer becomes NULL, even though
582   // render_view_host_ lives on to load another URL (creating a new View while
583   // doing so).
584   RenderWidgetHostViewBase* view_;
585 
586   // A weak pointer to the view. The above pointer should be weak, but changing
587   // that to be weak causes crashes on Android.
588   // TODO(ccameron): Fix this.
589   // http://crbug.com/404828
590   base::WeakPtr<RenderWidgetHostViewBase> view_weak_;
591 
592   // true if a renderer has once been valid. We use this flag to display a sad
593   // tab only when we lose our renderer and not if a paint occurs during
594   // initialization.
595   bool renderer_initialized_;
596 
597   // This value indicates how long to wait before we consider a renderer hung.
598   int hung_renderer_delay_ms_;
599 
600  private:
601   friend class MockRenderWidgetHost;
602 
603   // Tell this object to destroy itself.
604   void Destroy();
605 
606   // Called by |hang_timeout_monitor_| on delayed response from the renderer.
607   void RendererIsUnresponsive();
608 
609   // Called if we know the renderer is responsive. When we currently think the
610   // renderer is unresponsive, this will clear that state and call
611   // NotifyRendererResponsive.
612   void RendererIsResponsive();
613 
614   // IPC message handlers
615   void OnRenderViewReady();
616   void OnRenderProcessGone(int status, int error_code);
617   void OnClose();
618   void OnUpdateScreenRectsAck();
619   void OnRequestMove(const gfx::Rect& pos);
620   void OnSetTooltipText(const base::string16& tooltip_text,
621                         blink::WebTextDirection text_direction_hint);
622   bool OnSwapCompositorFrame(const IPC::Message& message);
623   void OnFlingingStopped();
624   void OnUpdateRect(const ViewHostMsg_UpdateRect_Params& params);
625   void OnQueueSyntheticGesture(const SyntheticGesturePacket& gesture_packet);
626   virtual void OnFocus();
627   virtual void OnBlur();
628   void OnSetCursor(const WebCursor& cursor);
629   void OnTextInputTypeChanged(ui::TextInputType type,
630                               ui::TextInputMode input_mode,
631                               bool can_compose_inline);
632 
633 #if defined(OS_MACOSX) || defined(USE_AURA)
634   void OnImeCompositionRangeChanged(
635       const gfx::Range& range,
636       const std::vector<gfx::Rect>& character_bounds);
637 #endif
638   void OnImeCancelComposition();
639   void OnLockMouse(bool user_gesture,
640                    bool last_unlocked_by_target,
641                    bool privileged);
642   void OnUnlockMouse();
643   void OnShowDisambiguationPopup(const gfx::Rect& rect_pixels,
644                                  const gfx::Size& size,
645                                  const cc::SharedBitmapId& id);
646 #if defined(OS_WIN)
647   void OnWindowlessPluginDummyWindowCreated(
648       gfx::NativeViewId dummy_activation_window);
649   void OnWindowlessPluginDummyWindowDestroyed(
650       gfx::NativeViewId dummy_activation_window);
651 #endif
652   void OnSelectionChanged(const base::string16& text,
653                           size_t offset,
654                           const gfx::Range& range);
655   void OnSelectionBoundsChanged(
656       const ViewHostMsg_SelectionBounds_Params& params);
657   void OnSnapshot(bool success, const SkBitmap& bitmap);
658 
659   // Called (either immediately or asynchronously) after we're done with our
660   // BackingStore and can send an ACK to the renderer so it can paint onto it
661   // again.
662   void DidUpdateBackingStore(const ViewHostMsg_UpdateRect_Params& params,
663                              const base::TimeTicks& paint_start);
664 
665   // Give key press listeners a chance to handle this key press. This allow
666   // widgets that don't have focus to still handle key presses.
667   bool KeyPressListenersHandleEvent(const NativeWebKeyboardEvent& event);
668 
669   // InputRouterClient
670   virtual InputEventAckState FilterInputEvent(
671       const blink::WebInputEvent& event,
672       const ui::LatencyInfo& latency_info) OVERRIDE;
673   virtual void IncrementInFlightEventCount() OVERRIDE;
674   virtual void DecrementInFlightEventCount() OVERRIDE;
675   virtual void OnHasTouchEventHandlers(bool has_handlers) OVERRIDE;
676   virtual void DidFlush() OVERRIDE;
677   virtual void DidOverscroll(const DidOverscrollParams& params) OVERRIDE;
678 
679   // InputAckHandler
680   virtual void OnKeyboardEventAck(const NativeWebKeyboardEvent& event,
681                                   InputEventAckState ack_result) OVERRIDE;
682   virtual void OnWheelEventAck(const MouseWheelEventWithLatencyInfo& event,
683                                InputEventAckState ack_result) OVERRIDE;
684   virtual void OnTouchEventAck(const TouchEventWithLatencyInfo& event,
685                                InputEventAckState ack_result) OVERRIDE;
686   virtual void OnGestureEventAck(const GestureEventWithLatencyInfo& event,
687                                  InputEventAckState ack_result) OVERRIDE;
688   virtual void OnUnexpectedEventAck(UnexpectedEventAckType type) OVERRIDE;
689 
690   void OnSyntheticGestureCompleted(SyntheticGesture::Result result);
691 
692   // Called when there is a new auto resize (using a post to avoid a stack
693   // which may get in recursive loops).
694   void DelayedAutoResized();
695 
696   void WindowOldSnapshotReachedScreen(int snapshot_id);
697 
698   void WindowSnapshotReachedScreen(int snapshot_id);
699 
700   void OnSnapshotDataReceived(int snapshot_id,
701                               const unsigned char* png,
702                               size_t size);
703 
704   void OnSnapshotDataReceivedAsync(
705       int snapshot_id,
706       scoped_refptr<base::RefCountedBytes> png_data);
707 
708   // Our delegate, which wants to know mainly about keyboard events.
709   // It will remain non-NULL until DetachDelegate() is called.
710   RenderWidgetHostDelegate* delegate_;
711 
712   // Created during construction but initialized during Init*(). Therefore, it
713   // is guaranteed never to be NULL, but its channel may be NULL if the
714   // renderer crashed, so you must always check that.
715   RenderProcessHost* process_;
716 
717   // The ID of the corresponding object in the Renderer Instance.
718   int routing_id_;
719 
720   // The ID of the surface corresponding to this render widget.
721   int surface_id_;
722 
723   // Indicates whether a page is loading or not.
724   bool is_loading_;
725 
726   // Indicates whether a page is hidden or not. It has to stay in sync with the
727   // most recent call to process_->WidgetRestored() / WidgetHidden().
728   bool is_hidden_;
729 
730   // Set if we are waiting for a repaint ack for the view.
731   bool repaint_ack_pending_;
732 
733   // True when waiting for RESIZE_ACK.
734   bool resize_ack_pending_;
735 
736   // Cached copy of the screen info so that it doesn't need to be updated every
737   // time the window is resized.
738   scoped_ptr<blink::WebScreenInfo> screen_info_;
739 
740   // Set if screen_info_ may have changed and should be recomputed and force a
741   // resize message.
742   bool screen_info_out_of_date_;
743 
744   // The current size of the RenderWidget.
745   gfx::Size current_size_;
746 
747   // Resize information that was previously sent to the renderer.
748   scoped_ptr<ViewMsg_Resize_Params> old_resize_params_;
749 
750   // The next auto resize to send.
751   gfx::Size new_auto_size_;
752 
753   // True if the render widget host should track the render widget's size as
754   // opposed to visa versa.
755   bool auto_resize_enabled_;
756 
757   // The minimum size for the render widget if auto-resize is enabled.
758   gfx::Size min_size_for_auto_resize_;
759 
760   // The maximum size for the render widget if auto-resize is enabled.
761   gfx::Size max_size_for_auto_resize_;
762 
763   bool waiting_for_screen_rects_ack_;
764   gfx::Rect last_view_screen_rect_;
765   gfx::Rect last_window_screen_rect_;
766 
767   // Keyboard event listeners.
768   std::vector<KeyPressEventCallback> key_press_event_callbacks_;
769 
770   // Mouse event callbacks.
771   std::vector<MouseEventCallback> mouse_event_callbacks_;
772 
773   // If true, then we should repaint when restoring even if we have a
774   // backingstore.  This flag is set to true if we receive a paint message
775   // while is_hidden_ to true.  Even though we tell the render widget to hide
776   // itself, a paint message could already be in flight at that point.
777   bool needs_repainting_on_restore_;
778 
779   // This is true if the renderer is currently unresponsive.
780   bool is_unresponsive_;
781 
782   // The following value indicates a time in the future when we would consider
783   // the renderer hung if it does not generate an appropriate response message.
784   base::Time time_when_considered_hung_;
785 
786   // This value denotes the number of input events yet to be acknowledged
787   // by the renderer.
788   int in_flight_event_count_;
789 
790   // This timer runs to check if time_when_considered_hung_ has past.
791   base::OneShotTimer<RenderWidgetHostImpl> hung_renderer_timer_;
792 
793   // Flag to detect recursive calls to GetBackingStore().
794   bool in_get_backing_store_;
795 
796   // Used for UMA histogram logging to measure the time for a repaint view
797   // operation to finish.
798   base::TimeTicks repaint_start_time_;
799 
800   // Set to true if we shouldn't send input events from the render widget.
801   bool ignore_input_events_;
802 
803   // Indicates whether IME is active.
804   bool input_method_active_;
805 
806   // Set when we update the text direction of the selected input element.
807   bool text_direction_updated_;
808   blink::WebTextDirection text_direction_;
809 
810   // Set when we cancel updating the text direction.
811   // This flag also ignores succeeding update requests until we call
812   // NotifyTextDirection().
813   bool text_direction_canceled_;
814 
815   // Indicates if the next sequence of Char events should be suppressed or not.
816   // System may translate a RawKeyDown event into zero or more Char events,
817   // usually we send them to the renderer directly in sequence. However, If a
818   // RawKeyDown event was not handled by the renderer but was handled by
819   // our UnhandledKeyboardEvent() method, e.g. as an accelerator key, then we
820   // shall not send the following sequence of Char events, which was generated
821   // by this RawKeyDown event, to the renderer. Otherwise the renderer may
822   // handle the Char events and cause unexpected behavior.
823   // For example, pressing alt-2 may let the browser switch to the second tab,
824   // but the Char event generated by alt-2 may also activate a HTML element
825   // if its accesskey happens to be "2", then the user may get confused when
826   // switching back to the original tab, because the content may already be
827   // changed.
828   bool suppress_next_char_events_;
829 
830   bool pending_mouse_lock_request_;
831   bool allow_privileged_mouse_lock_;
832 
833   // Keeps track of whether the webpage has any touch event handler. If it does,
834   // then touch events are sent to the renderer. Otherwise, the touch events are
835   // not sent to the renderer.
836   bool has_touch_handler_;
837 
838   scoped_ptr<SyntheticGestureController> synthetic_gesture_controller_;
839 
840   scoped_ptr<TouchEmulator> touch_emulator_;
841 
842   // Receives and handles all input events.
843   scoped_ptr<InputRouter> input_router_;
844 
845   scoped_ptr<TimeoutMonitor> hang_monitor_timeout_;
846 
847 #if defined(OS_WIN)
848   std::list<HWND> dummy_windows_for_activation_;
849 #endif
850 
851   int64 last_input_number_;
852 
853   int next_browser_snapshot_id_;
854   typedef std::map<int,
855       base::Callback<void(const unsigned char*, size_t)> > PendingSnapshotMap;
856   PendingSnapshotMap pending_browser_snapshots_;
857 
858   base::WeakPtrFactory<RenderWidgetHostImpl> weak_factory_;
859 
860   DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostImpl);
861 };
862 
863 }  // namespace content
864 
865 #endif  // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_IMPL_H_
866