65fa860df34c83ce8756c018e0a420fcf8e352fb
[platform/framework/web/crosswalk.git] / src / content / browser / renderer_host / render_widget_host_impl.h
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_IMPL_H_
6 #define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_IMPL_H_
7
8 #include <deque>
9 #include <list>
10 #include <map>
11 #include <queue>
12 #include <string>
13 #include <utility>
14 #include <vector>
15
16 #include "base/callback.h"
17 #include "base/gtest_prod_util.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/observer_list.h"
21 #include "base/process/kill.h"
22 #include "base/strings/string16.h"
23 #include "base/time/time.h"
24 #include "base/timer/timer.h"
25 #include "build/build_config.h"
26 #include "cc/resources/shared_bitmap.h"
27 #include "content/browser/accessibility/browser_accessibility_manager.h"
28 #include "content/browser/renderer_host/event_with_latency_info.h"
29 #include "content/browser/renderer_host/input/input_ack_handler.h"
30 #include "content/browser/renderer_host/input/input_router_client.h"
31 #include "content/browser/renderer_host/input/synthetic_gesture.h"
32 #include "content/browser/renderer_host/input/touch_emulator_client.h"
33 #include "content/common/input/input_event_ack_state.h"
34 #include "content/common/input/synthetic_gesture_packet.h"
35 #include "content/common/view_message_enums.h"
36 #include "content/public/browser/render_widget_host.h"
37 #include "content/public/common/page_zoom.h"
38 #include "ipc/ipc_listener.h"
39 #include "ui/base/ime/text_input_mode.h"
40 #include "ui/base/ime/text_input_type.h"
41 #include "ui/events/latency_info.h"
42 #include "ui/gfx/native_widget_types.h"
43
44 struct AcceleratedSurfaceMsg_BufferPresented_Params;
45 struct ViewHostMsg_BeginSmoothScroll_Params;
46 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
47 struct ViewHostMsg_SelectionBounds_Params;
48 struct ViewHostMsg_TextInputState_Params;
49 struct ViewHostMsg_UpdateRect_Params;
50
51 namespace base {
52 class TimeTicks;
53 }
54
55 namespace cc {
56 class CompositorFrame;
57 class CompositorFrameAck;
58 }
59
60 namespace gfx {
61 class Range;
62 }
63
64 namespace ui {
65 class KeyEvent;
66 }
67
68 namespace blink {
69 class WebInputEvent;
70 class WebMouseEvent;
71 struct WebCompositionUnderline;
72 struct WebScreenInfo;
73 }
74
75 #if defined(OS_ANDROID)
76 namespace blink {
77 class WebLayer;
78 }
79 #endif
80
81 namespace content {
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 BrowserAccessibilityDelegate {
101  public:
102   // routing_id can be MSG_ROUTING_NONE, in which case the next available
103   // routing id is taken from the RenderProcessHost.
104   // If this object outlives |delegate|, DetachDelegate() must be called when
105   // |delegate| goes away.
106   RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
107                        RenderProcessHost* process,
108                        int routing_id,
109                        bool hidden);
110   virtual ~RenderWidgetHostImpl();
111
112   // Similar to RenderWidgetHost::FromID, but returning the Impl object.
113   static RenderWidgetHostImpl* FromID(int32 process_id, int32 routing_id);
114
115   // Returns all RenderWidgetHosts including swapped out ones for
116   // internal use. The public interface
117   // RendgerWidgetHost::GetRenderWidgetHosts only returns active ones.
118   static scoped_ptr<RenderWidgetHostIterator> GetAllRenderWidgetHosts();
119
120   // Use RenderWidgetHostImpl::From(rwh) to downcast a
121   // RenderWidgetHost to a RenderWidgetHostImpl.  Internally, this
122   // uses RenderWidgetHost::AsRenderWidgetHostImpl().
123   static RenderWidgetHostImpl* From(RenderWidgetHost* rwh);
124
125   void set_hung_renderer_delay_ms(const base::TimeDelta& timeout) {
126     hung_renderer_delay_ms_ = timeout.InMilliseconds();
127   }
128
129   // RenderWidgetHost implementation.
130   virtual void UpdateTextDirection(blink::WebTextDirection direction) OVERRIDE;
131   virtual void NotifyTextDirection() OVERRIDE;
132   virtual void Focus() OVERRIDE;
133   virtual void Blur() OVERRIDE;
134   virtual void SetActive(bool active) OVERRIDE;
135   virtual void CopyFromBackingStore(
136       const gfx::Rect& src_rect,
137       const gfx::Size& accelerated_dst_size,
138       const base::Callback<void(bool, const SkBitmap&)>& callback,
139       const SkBitmap::Config& bitmap_config) OVERRIDE;
140   virtual bool CanCopyFromBackingStore() OVERRIDE;
141 #if defined(OS_ANDROID)
142   virtual void LockBackingStore() OVERRIDE;
143   virtual void UnlockBackingStore() OVERRIDE;
144 #endif
145   virtual void EnableFullAccessibilityMode() OVERRIDE;
146   virtual bool IsFullAccessibilityModeForTesting() OVERRIDE;
147   virtual void EnableTreeOnlyAccessibilityMode() OVERRIDE;
148   virtual bool IsTreeOnlyAccessibilityModeForTesting() OVERRIDE;
149   virtual void ForwardMouseEvent(
150       const blink::WebMouseEvent& mouse_event) OVERRIDE;
151   virtual void ForwardWheelEvent(
152       const blink::WebMouseWheelEvent& wheel_event) OVERRIDE;
153   virtual void ForwardKeyboardEvent(
154       const NativeWebKeyboardEvent& key_event) OVERRIDE;
155   virtual const gfx::Vector2d& GetLastScrollOffset() const OVERRIDE;
156   virtual RenderProcessHost* GetProcess() const OVERRIDE;
157   virtual int GetRoutingID() const OVERRIDE;
158   virtual RenderWidgetHostView* GetView() const OVERRIDE;
159   virtual bool IsLoading() const OVERRIDE;
160   virtual bool IsRenderView() const OVERRIDE;
161   virtual void ResizeRectChanged(const gfx::Rect& new_rect) OVERRIDE;
162   virtual void RestartHangMonitorTimeout() OVERRIDE;
163   virtual void SetIgnoreInputEvents(bool ignore_input_events) OVERRIDE;
164   virtual void Stop() OVERRIDE;
165   virtual void WasResized() OVERRIDE;
166   virtual void AddKeyPressEventCallback(
167       const KeyPressEventCallback& callback) OVERRIDE;
168   virtual void RemoveKeyPressEventCallback(
169       const KeyPressEventCallback& callback) OVERRIDE;
170   virtual void AddMouseEventCallback(
171       const MouseEventCallback& callback) OVERRIDE;
172   virtual void RemoveMouseEventCallback(
173       const MouseEventCallback& callback) OVERRIDE;
174   virtual void GetWebScreenInfo(blink::WebScreenInfo* result) OVERRIDE;
175
176   virtual SkBitmap::Config PreferredReadbackFormat() OVERRIDE;
177
178   // BrowserAccessibilityDelegate
179   virtual void AccessibilitySetFocus(int acc_obj_id) OVERRIDE;
180   virtual void AccessibilityDoDefaultAction(int acc_obj_id) OVERRIDE;
181   virtual void AccessibilityShowMenu(int acc_obj_id) OVERRIDE;
182   virtual void AccessibilityScrollToMakeVisible(
183       int acc_obj_id, gfx::Rect subfocus) OVERRIDE;
184   virtual void AccessibilityScrollToPoint(
185       int acc_obj_id, gfx::Point point) OVERRIDE;
186   virtual void AccessibilitySetTextSelection(
187       int acc_obj_id, int start_offset, int end_offset) OVERRIDE;
188   virtual bool AccessibilityViewHasFocus() const OVERRIDE;
189   virtual gfx::Rect AccessibilityGetViewBounds() const OVERRIDE;
190   virtual gfx::Point AccessibilityOriginInScreen(const gfx::Rect& bounds)
191       const OVERRIDE;
192   virtual void AccessibilityHitTest(const gfx::Point& point) OVERRIDE;
193   virtual void AccessibilityFatalError() OVERRIDE;
194
195   const NativeWebKeyboardEvent* GetLastKeyboardEvent() const;
196
197   // Notification that the screen info has changed.
198   void NotifyScreenInfoChanged();
199
200   // Invalidates the cached screen info so that next resize request
201   // will carry the up to date screen info. Unlike
202   // |NotifyScreenInfoChanged|, this doesn't send a message to the renderer.
203   void InvalidateScreenInfo();
204
205   // Sets the View of this RenderWidgetHost.
206   void SetView(RenderWidgetHostViewBase* view);
207
208   int surface_id() const { return surface_id_; }
209
210   bool empty() const { return current_size_.IsEmpty(); }
211
212   // Called when a renderer object already been created for this host, and we
213   // just need to be attached to it. Used for window.open, <select> dropdown
214   // menus, and other times when the renderer initiates creating an object.
215   virtual void Init();
216
217   // Tells the renderer to die and then calls Destroy().
218   virtual void Shutdown();
219
220   // IPC::Listener
221   virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
222
223   // Sends a message to the corresponding object in the renderer.
224   virtual bool Send(IPC::Message* msg) OVERRIDE;
225
226   // Called to notify the RenderWidget that it has been hidden or restored from
227   // having been hidden.
228   void WasHidden();
229   void WasShown();
230
231   // Returns true if the RenderWidget is hidden.
232   bool is_hidden() const { return is_hidden_; }
233
234   // Called to notify the RenderWidget that its associated native window
235   // got/lost focused.
236   virtual void GotFocus();
237   virtual void LostCapture();
238
239   // Called to notify the RenderWidget that it has lost the mouse lock.
240   virtual void LostMouseLock();
241
242   // Noifies the RenderWidget of the current mouse cursor visibility state.
243   void SendCursorVisibilityState(bool is_visible);
244
245   // Notifies the RenderWidgetHost that the View was destroyed.
246   void ViewDestroyed();
247
248   // Indicates if the page has finished loading.
249   void SetIsLoading(bool is_loading);
250
251   // Pause for a moment to wait for pending repaint or resize messages sent to
252   // the renderer to arrive. If pending resize messages are for an old window
253   // size, then also pump through a new resize message if there is time.
254   void PauseForPendingResizeOrRepaints();
255
256   // Whether pausing may be useful.
257   bool CanPauseForPendingResizeOrRepaints();
258
259   // Wait for a surface matching the size of the widget's view, possibly
260   // blocking until the renderer sends a new frame.
261   void WaitForSurface();
262
263   // GPU accelerated version of GetBackingStore function. This will
264   // trigger a re-composite to the view. It may fail if a resize is pending, or
265   // if a composite has already been requested and not acked yet.
266   bool ScheduleComposite();
267
268   // Starts a hang monitor timeout. If there's already a hang monitor timeout
269   // the new one will only fire if it has a shorter delay than the time
270   // left on the existing timeouts.
271   void StartHangMonitorTimeout(base::TimeDelta delay);
272
273   // Stops all existing hang monitor timeouts and assumes the renderer is
274   // responsive.
275   void StopHangMonitorTimeout();
276
277   // Forwards the given message to the renderer. These are called by the view
278   // when it has received a message.
279   void ForwardGestureEventWithLatencyInfo(
280       const blink::WebGestureEvent& gesture_event,
281       const ui::LatencyInfo& ui_latency);
282   void ForwardTouchEventWithLatencyInfo(
283       const blink::WebTouchEvent& touch_event,
284       const ui::LatencyInfo& ui_latency);
285   void ForwardMouseEventWithLatencyInfo(
286       const blink::WebMouseEvent& mouse_event,
287       const ui::LatencyInfo& ui_latency);
288   void ForwardWheelEventWithLatencyInfo(
289       const blink::WebMouseWheelEvent& wheel_event,
290       const ui::LatencyInfo& ui_latency);
291
292   // TouchEmulatorClient overrides.
293   virtual void ForwardGestureEvent(
294       const blink::WebGestureEvent& gesture_event) OVERRIDE;
295   virtual void ForwardTouchEvent(
296       const blink::WebTouchEvent& touch_event) OVERRIDE;
297   virtual void SetCursor(const WebCursor& cursor) OVERRIDE;
298
299   // Queues a synthetic gesture for testing purposes.  Invokes the on_complete
300   // callback when the gesture is finished running.
301   void QueueSyntheticGesture(
302       scoped_ptr<SyntheticGesture> synthetic_gesture,
303       const base::Callback<void(SyntheticGesture::Result)>& on_complete);
304
305   void CancelUpdateTextDirection();
306
307   // Called when a mouse click/gesture tap activates the renderer.
308   virtual void OnPointerEventActivate();
309
310   // Notifies the renderer whether or not the input method attached to this
311   // process is activated.
312   // When the input method is activated, a renderer process sends IPC messages
313   // to notify the status of its composition node. (This message is mainly used
314   // for notifying the position of the input cursor so that the browser can
315   // display input method windows under the cursor.)
316   void SetInputMethodActive(bool activate);
317
318   // Notifies the renderer changes of IME candidate window state.
319   void CandidateWindowShown();
320   void CandidateWindowUpdated();
321   void CandidateWindowHidden();
322
323   // Update the composition node of the renderer (or WebKit).
324   // WebKit has a special node (a composition node) for input method to change
325   // its text without affecting any other DOM nodes. When the input method
326   // (attached to the browser) updates its text, the browser sends IPC messages
327   // to update the composition node of the renderer.
328   // (Read the comments of each function for its detail.)
329
330   // Sets the text of the composition node.
331   // This function can also update the cursor position and mark the specified
332   // range in the composition node.
333   // A browser should call this function:
334   // * when it receives a WM_IME_COMPOSITION message with a GCS_COMPSTR flag
335   //   (on Windows);
336   // * when it receives a "preedit_changed" signal of GtkIMContext (on Linux);
337   // * when markedText of NSTextInput is called (on Mac).
338   void ImeSetComposition(
339       const base::string16& text,
340       const std::vector<blink::WebCompositionUnderline>& underlines,
341       int selection_start,
342       int selection_end);
343
344   // Finishes an ongoing composition with the specified text.
345   // A browser should call this function:
346   // * when it receives a WM_IME_COMPOSITION message with a GCS_RESULTSTR flag
347   //   (on Windows);
348   // * when it receives a "commit" signal of GtkIMContext (on Linux);
349   // * when insertText of NSTextInput is called (on Mac).
350   void ImeConfirmComposition(const base::string16& text,
351                              const gfx::Range& replacement_range,
352                              bool keep_selection);
353
354   // Cancels an ongoing composition.
355   void ImeCancelComposition();
356
357   // This is for derived classes to give us access to the resizer rect.
358   // And to also expose it to the RenderWidgetHostView.
359   virtual gfx::Rect GetRootWindowResizerRect() const;
360
361   bool ignore_input_events() const {
362     return ignore_input_events_;
363   }
364
365   bool input_method_active() const {
366     return input_method_active_;
367   }
368
369   // Whether forwarded WebInputEvents should be ignored.  True if either
370   // |ignore_input_events_| or |process_->IgnoreInputEvents()| is true.
371   bool IgnoreInputEvents() const;
372
373   // Event queries delegated to the |input_router_|.
374   bool ShouldForwardTouchEvent() const;
375
376   bool has_touch_handler() const { return has_touch_handler_; }
377
378   // Notification that the user has made some kind of input that could
379   // perform an action. See OnUserGesture for more details.
380   void StartUserGesture();
381
382   // Set the RenderView background transparency.
383   void SetBackgroundOpaque(bool opaque);
384
385   // Notifies the renderer that the next key event is bound to one or more
386   // pre-defined edit commands
387   void SetEditCommandsForNextKeyEvent(
388       const std::vector<EditCommand>& commands);
389
390   // Gets the accessibility mode.
391   AccessibilityMode accessibility_mode() const {
392     return accessibility_mode_;
393   }
394
395   // Adds the given accessibility mode to the current accessibility mode bitmap.
396   void AddAccessibilityMode(AccessibilityMode mode);
397
398   // Removes the given accessibility mode from the current accessibility mode
399   // bitmap, managing the bits that are shared with other modes such that a
400   // bit will only be turned off when all modes that depend on it have been
401   // removed.
402   void RemoveAccessibilityMode(AccessibilityMode mode);
403
404   // Resets the accessibility mode to the default setting in
405   // BrowserStateAccessibilityImpl.
406   void ResetAccessibilityMode();
407
408 #if defined(OS_WIN)
409   void SetParentNativeViewAccessible(
410       gfx::NativeViewAccessible accessible_parent);
411   gfx::NativeViewAccessible GetParentNativeViewAccessible() const;
412 #endif
413
414   // Executes the edit command on the RenderView.
415   void ExecuteEditCommand(const std::string& command,
416                           const std::string& value);
417
418   // Tells the renderer to scroll the currently focused node into rect only if
419   // the currently focused node is a Text node (textfield, text area or content
420   // editable divs).
421   void ScrollFocusedEditableNodeIntoRect(const gfx::Rect& rect);
422
423   // Requests the renderer to move the caret selection towards the point.
424   void MoveCaret(const gfx::Point& point);
425
426   // Called when the reponse to a pending mouse lock request has arrived.
427   // Returns true if |allowed| is true and the mouse has been successfully
428   // locked.
429   bool GotResponseToLockMouseRequest(bool allowed);
430
431   // Tells the RenderWidget about the latest vsync parameters.
432   // Note: Make sure the timebase was obtained using
433   // base::TimeTicks::HighResNow. Using the non-high res timer will result in
434   // incorrect synchronization across processes.
435   virtual void UpdateVSyncParameters(base::TimeTicks timebase,
436                                      base::TimeDelta interval);
437
438   // Called by the view in response to AcceleratedSurfaceBuffersSwapped or
439   // AcceleratedSurfacePostSubBuffer.
440   static void AcknowledgeBufferPresent(
441       int32 route_id,
442       int gpu_host_id,
443       const AcceleratedSurfaceMsg_BufferPresented_Params& params);
444
445   // Called by the view in response to OnSwapCompositorFrame.
446   static void SendSwapCompositorFrameAck(
447       int32 route_id,
448       uint32 output_surface_id,
449       int renderer_host_id,
450       const cc::CompositorFrameAck& ack);
451
452   // Called by the view to return resources to the compositor.
453   static void SendReclaimCompositorResources(int32 route_id,
454                                              uint32 output_surface_id,
455                                              int renderer_host_id,
456                                              const cc::CompositorFrameAck& ack);
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   // Suppreses future char events until a keydown. See
475   // suppress_next_char_events_.
476   void SuppressNextCharEvents();
477
478   // Called by RenderWidgetHostView in response to OnSetNeedsFlushInput.
479   void FlushInput();
480
481   // InputRouterClient
482   virtual void SetNeedsFlush() OVERRIDE;
483
484   // Indicates whether the renderer drives the RenderWidgetHosts's size or the
485   // other way around.
486   bool should_auto_resize() { return should_auto_resize_; }
487
488   void ComputeTouchLatency(const ui::LatencyInfo& latency_info);
489   void FrameSwapped(const ui::LatencyInfo& latency_info);
490   void DidReceiveRendererFrame();
491
492   // Returns the ID that uniquely describes this component to the latency
493   // subsystem.
494   int64 GetLatencyComponentId();
495
496   static void CompositorFrameDrawn(
497       const std::vector<ui::LatencyInfo>& latency_info);
498
499   // Don't check whether we expected a resize ack during layout tests.
500   static void DisableResizeAckCheckForTesting();
501
502   void WindowSnapshotAsyncCallback(
503       int routing_id,
504       int snapshot_id,
505       gfx::Size snapshot_size,
506       scoped_refptr<base::RefCountedBytes> png_data);
507
508   // LatencyComponents generated in the renderer must have component IDs
509   // provided to them by the browser process. This function adds the correct
510   // component ID where necessary.
511   void AddLatencyInfoComponentIds(ui::LatencyInfo* latency_info);
512
513   InputRouter* input_router() { return input_router_.get(); }
514
515  protected:
516   virtual RenderWidgetHostImpl* AsRenderWidgetHostImpl() OVERRIDE;
517
518   // Create a LatencyInfo struct with INPUT_EVENT_LATENCY_RWH_COMPONENT
519   // component if it is not already in |original|. And if |original| is
520   // not NULL, it is also merged into the resulting LatencyInfo.
521   ui::LatencyInfo CreateRWHLatencyInfoIfNotExist(
522       const ui::LatencyInfo* original, blink::WebInputEvent::Type type);
523
524   // Called when we receive a notification indicating that the renderer
525   // process has gone. This will reset our state so that our state will be
526   // consistent if a new renderer is created.
527   void RendererExited(base::TerminationStatus status, int exit_code);
528
529   // Retrieves an id the renderer can use to refer to its view.
530   // This is used for various IPC messages, including plugins.
531   gfx::NativeViewId GetNativeViewId() const;
532
533   // Retrieves an id for the surface that the renderer can draw to
534   // when accelerated compositing is enabled.
535   gfx::GLSurfaceHandle GetCompositingSurface();
536
537   // ---------------------------------------------------------------------------
538   // The following methods are overridden by RenderViewHost to send upwards to
539   // its delegate.
540
541   // Called when a mousewheel event was not processed by the renderer.
542   virtual void UnhandledWheelEvent(const blink::WebMouseWheelEvent& event) {}
543
544   // Notification that the user has made some kind of input that could
545   // perform an action. The gestures that count are 1) any mouse down
546   // event and 2) enter or space key presses.
547   virtual void OnUserGesture() {}
548
549   // Callbacks for notification when the renderer becomes unresponsive to user
550   // input events, and subsequently responsive again.
551   virtual void NotifyRendererUnresponsive() {}
552   virtual void NotifyRendererResponsive() {}
553
554   // Called when auto-resize resulted in the renderer size changing.
555   virtual void OnRenderAutoResized(const gfx::Size& new_size) {}
556
557   // ---------------------------------------------------------------------------
558
559   // RenderViewHost overrides this method to impose further restrictions on when
560   // to allow mouse lock.
561   // Once the request is approved or rejected, GotResponseToLockMouseRequest()
562   // will be called.
563   virtual void RequestToLockMouse(bool user_gesture,
564                                   bool last_unlocked_by_target);
565
566   void RejectMouseLockOrUnlockIfNecessary();
567   bool IsMouseLocked() const;
568
569   // RenderViewHost overrides this method to report when in fullscreen mode.
570   virtual bool IsFullscreen() const;
571
572   // Indicates if the render widget host should track the render widget's size
573   // as opposed to visa versa.
574   void SetShouldAutoResize(bool enable);
575
576   // Expose increment/decrement of the in-flight event count, so
577   // RenderViewHostImpl can account for in-flight beforeunload/unload events.
578   int increment_in_flight_event_count() { return ++in_flight_event_count_; }
579   int decrement_in_flight_event_count() { return --in_flight_event_count_; }
580
581   // The View associated with the RenderViewHost. The lifetime of this object
582   // is associated with the lifetime of the Render process. If the Renderer
583   // crashes, its View is destroyed and this pointer becomes NULL, even though
584   // render_view_host_ lives on to load another URL (creating a new View while
585   // doing so).
586   RenderWidgetHostViewBase* view_;
587
588   // true if a renderer has once been valid. We use this flag to display a sad
589   // tab only when we lose our renderer and not if a paint occurs during
590   // initialization.
591   bool renderer_initialized_;
592
593   // This value indicates how long to wait before we consider a renderer hung.
594   int hung_renderer_delay_ms_;
595
596  private:
597   friend class MockRenderWidgetHost;
598
599   // Tell this object to destroy itself.
600   void Destroy();
601
602   // Called by |hang_timeout_monitor_| on delayed response from the renderer.
603   void RendererIsUnresponsive();
604
605   // Called if we know the renderer is responsive. When we currently think the
606   // renderer is unresponsive, this will clear that state and call
607   // NotifyRendererResponsive.
608   void RendererIsResponsive();
609
610   // IPC message handlers
611   void OnRenderViewReady();
612   void OnRenderProcessGone(int status, int error_code);
613   void OnClose();
614   void OnUpdateScreenRectsAck();
615   void OnRequestMove(const gfx::Rect& pos);
616   void OnSetTooltipText(const base::string16& tooltip_text,
617                         blink::WebTextDirection text_direction_hint);
618 #if defined(OS_MACOSX)
619   void OnCompositorSurfaceBuffersSwapped(
620       const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
621 #endif
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 OnSetTouchEventEmulationEnabled(bool enabled, bool allow_pinch);
630   void OnTextInputStateChanged(
631       const ViewHostMsg_TextInputState_Params& params);
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,
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 WindowSnapshotReachedScreen(int snapshot_id);
697
698   // Send a message to the renderer process to change the accessibility mode.
699   void SetAccessibilityMode(AccessibilityMode AccessibilityMode);
700
701   // Our delegate, which wants to know mainly about keyboard events.
702   // It will remain non-NULL until DetachDelegate() is called.
703   RenderWidgetHostDelegate* delegate_;
704
705   // Created during construction but initialized during Init*(). Therefore, it
706   // is guaranteed never to be NULL, but its channel may be NULL if the
707   // renderer crashed, so you must always check that.
708   RenderProcessHost* process_;
709
710   // The ID of the corresponding object in the Renderer Instance.
711   int routing_id_;
712
713   // The ID of the surface corresponding to this render widget.
714   int surface_id_;
715
716   // Indicates whether a page is loading or not.
717   bool is_loading_;
718
719   // Indicates whether a page is hidden or not.
720   bool is_hidden_;
721
722   // Indicates whether a page is fullscreen or not.
723   bool is_fullscreen_;
724
725   // Set if we are waiting for a repaint ack for the view.
726   bool repaint_ack_pending_;
727
728   // True when waiting for RESIZE_ACK.
729   bool resize_ack_pending_;
730
731   // Cached copy of the screen info so that it doesn't need to be updated every
732   // time the window is resized.
733   scoped_ptr<blink::WebScreenInfo> screen_info_;
734
735   // Set if screen_info_ may have changed and should be recomputed and force a
736   // resize message.
737   bool screen_info_out_of_date_;
738
739   // The current size of the RenderWidget.
740   gfx::Size current_size_;
741
742   // The size of the view's backing surface in non-DPI-adjusted pixels.
743   gfx::Size physical_backing_size_;
744
745   // The height of the physical backing surface that is overdrawn opaquely in
746   // the browser, for example by an on-screen-keyboard (in DPI-adjusted pixels).
747   float overdraw_bottom_height_;
748
749   // The size of the visible viewport, which may be smaller than the view if the
750   // view is partially occluded (e.g. by a virtual keyboard).  The size is in
751   // DPI-adjusted pixels.
752   gfx::Size visible_viewport_size_;
753
754   // The size we last sent as requested size to the renderer. |current_size_|
755   // is only updated once the resize message has been ack'd. This on the other
756   // hand is updated when the resize message is sent. This is very similar to
757   // |resize_ack_pending_|, but the latter is not set if the new size has width
758   // or height zero, which is why we need this too.
759   gfx::Size last_requested_size_;
760
761   // The next auto resize to send.
762   gfx::Size new_auto_size_;
763
764   // True if the render widget host should track the render widget's size as
765   // opposed to visa versa.
766   bool should_auto_resize_;
767
768   bool waiting_for_screen_rects_ack_;
769   gfx::Rect last_view_screen_rect_;
770   gfx::Rect last_window_screen_rect_;
771
772   AccessibilityMode accessibility_mode_;
773
774   // Keyboard event listeners.
775   std::vector<KeyPressEventCallback> key_press_event_callbacks_;
776
777   // Mouse event callbacks.
778   std::vector<MouseEventCallback> mouse_event_callbacks_;
779
780   // If true, then we should repaint when restoring even if we have a
781   // backingstore.  This flag is set to true if we receive a paint message
782   // while is_hidden_ to true.  Even though we tell the render widget to hide
783   // itself, a paint message could already be in flight at that point.
784   bool needs_repainting_on_restore_;
785
786   // This is true if the renderer is currently unresponsive.
787   bool is_unresponsive_;
788
789   // The following value indicates a time in the future when we would consider
790   // the renderer hung if it does not generate an appropriate response message.
791   base::Time time_when_considered_hung_;
792
793   // This value denotes the number of input events yet to be acknowledged
794   // by the renderer.
795   int in_flight_event_count_;
796
797   // This timer runs to check if time_when_considered_hung_ has past.
798   base::OneShotTimer<RenderWidgetHostImpl> hung_renderer_timer_;
799
800   // Flag to detect recursive calls to GetBackingStore().
801   bool in_get_backing_store_;
802
803   // Used for UMA histogram logging to measure the time for a repaint view
804   // operation to finish.
805   base::TimeTicks repaint_start_time_;
806
807   // Set to true if we shouldn't send input events from the render widget.
808   bool ignore_input_events_;
809
810   // Indicates whether IME is active.
811   bool input_method_active_;
812
813   // Set when we update the text direction of the selected input element.
814   bool text_direction_updated_;
815   blink::WebTextDirection text_direction_;
816
817   // Set when we cancel updating the text direction.
818   // This flag also ignores succeeding update requests until we call
819   // NotifyTextDirection().
820   bool text_direction_canceled_;
821
822   // Indicates if the next sequence of Char events should be suppressed or not.
823   // System may translate a RawKeyDown event into zero or more Char events,
824   // usually we send them to the renderer directly in sequence. However, If a
825   // RawKeyDown event was not handled by the renderer but was handled by
826   // our UnhandledKeyboardEvent() method, e.g. as an accelerator key, then we
827   // shall not send the following sequence of Char events, which was generated
828   // by this RawKeyDown event, to the renderer. Otherwise the renderer may
829   // handle the Char events and cause unexpected behavior.
830   // For example, pressing alt-2 may let the browser switch to the second tab,
831   // but the Char event generated by alt-2 may also activate a HTML element
832   // if its accesskey happens to be "2", then the user may get confused when
833   // switching back to the original tab, because the content may already be
834   // changed.
835   bool suppress_next_char_events_;
836
837   // The last scroll offset of the render widget.
838   gfx::Vector2d last_scroll_offset_;
839
840   bool pending_mouse_lock_request_;
841   bool allow_privileged_mouse_lock_;
842
843   // Keeps track of whether the webpage has any touch event handler. If it does,
844   // then touch events are sent to the renderer. Otherwise, the touch events are
845   // not sent to the renderer.
846   bool has_touch_handler_;
847
848   base::WeakPtrFactory<RenderWidgetHostImpl> weak_factory_;
849
850   scoped_ptr<SyntheticGestureController> synthetic_gesture_controller_;
851
852   scoped_ptr<TouchEmulator> touch_emulator_;
853
854   // Receives and handles all input events.
855   scoped_ptr<InputRouter> input_router_;
856
857   scoped_ptr<TimeoutMonitor> hang_monitor_timeout_;
858
859 #if defined(OS_WIN)
860   std::list<HWND> dummy_windows_for_activation_;
861 #endif
862
863   int64 last_input_number_;
864
865   DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostImpl);
866 };
867
868 }  // namespace content
869
870 #endif  // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_IMPL_H_