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