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