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