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