Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / content / renderer / render_widget.cc
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 #include "content/renderer/render_widget.h"
6
7 #include "base/auto_reset.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/debug/trace_event_synthetic_delay.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/singleton.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/stl_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/sys_info.h"
20 #include "build/build_config.h"
21 #include "cc/base/switches.h"
22 #include "cc/debug/benchmark_instrumentation.h"
23 #include "cc/output/output_surface.h"
24 #include "cc/trees/layer_tree_host.h"
25 #include "content/child/npapi/webplugin.h"
26 #include "content/common/gpu/client/context_provider_command_buffer.h"
27 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
28 #include "content/common/gpu/gpu_process_launch_causes.h"
29 #include "content/common/input/synthetic_gesture_packet.h"
30 #include "content/common/input/web_input_event_traits.h"
31 #include "content/common/input_messages.h"
32 #include "content/common/swapped_out_messages.h"
33 #include "content/common/view_messages.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/context_menu_params.h"
36 #include "content/renderer/cursor_utils.h"
37 #include "content/renderer/external_popup_menu.h"
38 #include "content/renderer/gpu/compositor_output_surface.h"
39 #include "content/renderer/gpu/compositor_software_output_device.h"
40 #include "content/renderer/gpu/delegated_compositor_output_surface.h"
41 #include "content/renderer/gpu/frame_swap_message_queue.h"
42 #include "content/renderer/gpu/mailbox_output_surface.h"
43 #include "content/renderer/gpu/queue_message_swap_promise.h"
44 #include "content/renderer/gpu/render_widget_compositor.h"
45 #include "content/renderer/ime_event_guard.h"
46 #include "content/renderer/input/input_handler_manager.h"
47 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
48 #include "content/renderer/render_frame_impl.h"
49 #include "content/renderer/render_frame_proxy.h"
50 #include "content/renderer/render_process.h"
51 #include "content/renderer/render_thread_impl.h"
52 #include "content/renderer/renderer_blink_platform_impl.h"
53 #include "content/renderer/resizing_mode_selector.h"
54 #include "ipc/ipc_sync_message.h"
55 #include "skia/ext/platform_canvas.h"
56 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
57 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
58 #include "third_party/WebKit/public/platform/WebRect.h"
59 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
60 #include "third_party/WebKit/public/platform/WebSize.h"
61 #include "third_party/WebKit/public/platform/WebString.h"
62 #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
63 #include "third_party/WebKit/public/web/WebPagePopup.h"
64 #include "third_party/WebKit/public/web/WebPopupMenu.h"
65 #include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
66 #include "third_party/WebKit/public/web/WebRange.h"
67 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
68 #include "third_party/skia/include/core/SkShader.h"
69 #include "ui/base/ui_base_switches.h"
70 #include "ui/gfx/frame_time.h"
71 #include "ui/gfx/point_conversions.h"
72 #include "ui/gfx/rect_conversions.h"
73 #include "ui/gfx/size_conversions.h"
74 #include "ui/gfx/skia_util.h"
75 #include "ui/gl/gl_switches.h"
76 #include "ui/surface/transport_dib.h"
77
78 #if defined(OS_ANDROID)
79 #include <android/keycodes.h>
80 #include "base/android/build_info.h"
81 #include "content/renderer/android/synchronous_compositor_factory.h"
82 #endif
83
84 #if defined(OS_POSIX)
85 #include "ipc/ipc_channel_posix.h"
86 #include "third_party/skia/include/core/SkMallocPixelRef.h"
87 #include "third_party/skia/include/core/SkPixelRef.h"
88 #endif  // defined(OS_POSIX)
89
90 #include "third_party/WebKit/public/web/WebWidget.h"
91
92 using blink::WebCompositionUnderline;
93 using blink::WebCursorInfo;
94 using blink::WebDeviceEmulationParams;
95 using blink::WebGestureEvent;
96 using blink::WebInputEvent;
97 using blink::WebKeyboardEvent;
98 using blink::WebMouseEvent;
99 using blink::WebMouseWheelEvent;
100 using blink::WebNavigationPolicy;
101 using blink::WebPagePopup;
102 using blink::WebPopupMenu;
103 using blink::WebPopupMenuInfo;
104 using blink::WebPopupType;
105 using blink::WebRange;
106 using blink::WebRect;
107 using blink::WebScreenInfo;
108 using blink::WebSize;
109 using blink::WebTextDirection;
110 using blink::WebTouchEvent;
111 using blink::WebTouchPoint;
112 using blink::WebVector;
113 using blink::WebWidget;
114
115 namespace {
116
117 typedef std::map<std::string, ui::TextInputMode> TextInputModeMap;
118
119 class TextInputModeMapSingleton {
120  public:
121   static TextInputModeMapSingleton* GetInstance() {
122     return Singleton<TextInputModeMapSingleton>::get();
123   }
124   TextInputModeMapSingleton() {
125     map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM;
126     map_["latin"] = ui::TEXT_INPUT_MODE_LATIN;
127     map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME;
128     map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE;
129     map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN;
130     map_["kana"] = ui::TEXT_INPUT_MODE_KANA;
131     map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA;
132     map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC;
133     map_["tel"] = ui::TEXT_INPUT_MODE_TEL;
134     map_["email"] = ui::TEXT_INPUT_MODE_EMAIL;
135     map_["url"] = ui::TEXT_INPUT_MODE_URL;
136   }
137   const TextInputModeMap& map() const { return map_; }
138  private:
139   TextInputModeMap map_;
140
141   friend struct DefaultSingletonTraits<TextInputModeMapSingleton>;
142
143   DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton);
144 };
145
146 ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) {
147   static TextInputModeMapSingleton* singleton =
148       TextInputModeMapSingleton::GetInstance();
149   TextInputModeMap::const_iterator it =
150       singleton->map().find(input_mode.utf8());
151   if (it == singleton->map().end())
152     return ui::TEXT_INPUT_MODE_DEFAULT;
153   return it->second;
154 }
155
156 bool IsThreadedCompositingEnabled() {
157   content::RenderThreadImpl* impl = content::RenderThreadImpl::current();
158   return impl && !!impl->compositor_message_loop_proxy().get();
159 }
160
161 // TODO(brianderson): Replace the hard-coded threshold with a fraction of
162 // the BeginMainFrame interval.
163 // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to
164 // be spent in input hanlders before input starts getting throttled.
165 const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166;
166
167 }  // namespace
168
169 namespace content {
170
171 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
172
173 class RenderWidget::ScreenMetricsEmulator {
174  public:
175   ScreenMetricsEmulator(
176       RenderWidget* widget,
177       const WebDeviceEmulationParams& params);
178   virtual ~ScreenMetricsEmulator();
179
180   // Scale and offset used to convert between host coordinates
181   // and webwidget coordinates.
182   float scale() { return scale_; }
183   gfx::Point offset() { return offset_; }
184   gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
185   gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
186   const WebScreenInfo& original_screen_info() { return original_screen_info_; }
187
188   void ChangeEmulationParams(
189       const WebDeviceEmulationParams& params);
190
191   // The following methods alter handlers' behavior for messages related to
192   // widget size and position.
193   void OnResizeMessage(const ViewMsg_Resize_Params& params);
194   void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
195                                   const gfx::Rect& window_screen_rect);
196   void OnShowContextMenu(ContextMenuParams* params);
197   gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
198
199  private:
200   void Reapply();
201   void Apply(float top_controls_layout_height,
202              gfx::Rect resizer_rect,
203              bool is_fullscreen);
204
205   RenderWidget* widget_;
206
207   // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
208   WebDeviceEmulationParams params_;
209
210   // The computed scale and offset used to fit widget into browser window.
211   float scale_;
212   gfx::Point offset_;
213
214   // Widget rect as passed to webwidget.
215   gfx::Rect applied_widget_rect_;
216
217   // Original values to restore back after emulation ends.
218   gfx::Size original_size_;
219   gfx::Size original_physical_backing_size_;
220   gfx::Size original_visible_viewport_size_;
221   blink::WebScreenInfo original_screen_info_;
222   gfx::Rect original_view_screen_rect_;
223   gfx::Rect original_window_screen_rect_;
224 };
225
226 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
227     RenderWidget* widget,
228     const WebDeviceEmulationParams& params)
229     : widget_(widget),
230       params_(params),
231       scale_(1.f) {
232   original_size_ = widget_->size_;
233   original_physical_backing_size_ = widget_->physical_backing_size_;
234   original_visible_viewport_size_ = widget_->visible_viewport_size_;
235   original_screen_info_ = widget_->screen_info_;
236   original_view_screen_rect_ = widget_->view_screen_rect_;
237   original_window_screen_rect_ = widget_->window_screen_rect_;
238   Apply(widget_->top_controls_layout_height_, widget_->resizer_rect_,
239       widget_->is_fullscreen_);
240 }
241
242 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
243   widget_->screen_info_ = original_screen_info_;
244
245   widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
246   widget_->SetScreenMetricsEmulationParameters(0.f, gfx::Point(), 1.f);
247   widget_->view_screen_rect_ = original_view_screen_rect_;
248   widget_->window_screen_rect_ = original_window_screen_rect_;
249   widget_->Resize(original_size_,
250                   original_physical_backing_size_,
251                   widget_->top_controls_layout_height_,
252                   original_visible_viewport_size_,
253                   widget_->resizer_rect_,
254                   widget_->is_fullscreen_,
255                   NO_RESIZE_ACK);
256 }
257
258 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
259     const WebDeviceEmulationParams& params) {
260   params_ = params;
261   Reapply();
262 }
263
264 void RenderWidget::ScreenMetricsEmulator::Reapply() {
265   Apply(widget_->top_controls_layout_height_, widget_->resizer_rect_,
266       widget_->is_fullscreen_);
267 }
268
269 void RenderWidget::ScreenMetricsEmulator::Apply(
270     float top_controls_layout_height,
271     gfx::Rect resizer_rect,
272     bool is_fullscreen) {
273   applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
274   if (!applied_widget_rect_.width())
275     applied_widget_rect_.set_width(original_size_.width());
276   if (!applied_widget_rect_.height())
277     applied_widget_rect_.set_height(original_size_.height());
278
279   if (params_.fitToView && !original_size_.IsEmpty()) {
280     int original_width = std::max(original_size_.width(), 1);
281     int original_height = std::max(original_size_.height(), 1);
282     float width_ratio =
283         static_cast<float>(applied_widget_rect_.width()) / original_width;
284     float height_ratio =
285         static_cast<float>(applied_widget_rect_.height()) / original_height;
286     float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
287     scale_ = 1.f / ratio;
288
289     // Center emulated view inside available view space.
290     offset_.set_x(
291         (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
292     offset_.set_y(
293         (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
294   } else {
295     scale_ = params_.scale;
296     offset_.SetPoint(params_.offset.x, params_.offset.y);
297   }
298
299   if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
300     applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
301     widget_->screen_info_.rect = original_screen_info_.rect;
302     widget_->screen_info_.availableRect = original_screen_info_.availableRect;
303     widget_->window_screen_rect_ = original_window_screen_rect_;
304   } else {
305     applied_widget_rect_.set_origin(gfx::Point(0, 0));
306     widget_->screen_info_.rect = applied_widget_rect_;
307     widget_->screen_info_.availableRect = applied_widget_rect_;
308     widget_->window_screen_rect_ = applied_widget_rect_;
309   }
310
311   float applied_device_scale_factor = params_.deviceScaleFactor ?
312       params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
313   widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
314
315   // Pass three emulation parameters to the blink side:
316   // - we keep the real device scale factor in compositor to produce sharp image
317   //   even when emulating different scale factor;
318   // - in order to fit into view, WebView applies offset and scale to the
319   //   root layer.
320   widget_->SetScreenMetricsEmulationParameters(
321       original_screen_info_.deviceScaleFactor, offset_, scale_);
322
323   widget_->SetDeviceScaleFactor(applied_device_scale_factor);
324   widget_->view_screen_rect_ = applied_widget_rect_;
325
326   gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
327       original_size_, original_screen_info_.deviceScaleFactor));
328   widget_->Resize(applied_widget_rect_.size(), physical_backing_size,
329       top_controls_layout_height, applied_widget_rect_.size(), resizer_rect,
330       is_fullscreen, NO_RESIZE_ACK);
331 }
332
333 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
334     const ViewMsg_Resize_Params& params) {
335   bool need_ack = params.new_size != original_size_ &&
336       !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
337   original_size_ = params.new_size;
338   original_physical_backing_size_ = params.physical_backing_size;
339   original_screen_info_ = params.screen_info;
340   original_visible_viewport_size_ = params.visible_viewport_size;
341   Apply(params.top_controls_layout_height, params.resizer_rect,
342       params.is_fullscreen);
343
344   if (need_ack) {
345     widget_->set_next_paint_is_resize_ack();
346     if (widget_->compositor_)
347       widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
348   }
349 }
350
351 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
352     const gfx::Rect& view_screen_rect,
353     const gfx::Rect& window_screen_rect) {
354   original_view_screen_rect_ = view_screen_rect;
355   original_window_screen_rect_ = window_screen_rect;
356   if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
357     Reapply();
358 }
359
360 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
361     ContextMenuParams* params) {
362   params->x *= scale_;
363   params->x += offset_.x();
364   params->y *= scale_;
365   params->y += offset_.y();
366 }
367
368 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
369     const gfx::Rect& anchor) {
370   gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
371   scaled.set_x(scaled.x() + offset_.x());
372   scaled.set_y(scaled.y() + offset_.y());
373   return scaled;
374 }
375
376 // RenderWidget ---------------------------------------------------------------
377
378 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
379                            const blink::WebScreenInfo& screen_info,
380                            bool swapped_out,
381                            bool hidden,
382                            bool never_visible)
383     : routing_id_(MSG_ROUTING_NONE),
384       surface_id_(0),
385       webwidget_(NULL),
386       opener_id_(MSG_ROUTING_NONE),
387       init_complete_(false),
388       top_controls_layout_height_(0.f),
389       next_paint_flags_(0),
390       auto_resize_mode_(false),
391       need_update_rect_for_auto_resize_(false),
392       did_show_(false),
393       is_hidden_(hidden),
394       never_visible_(never_visible),
395       is_fullscreen_(false),
396       has_focus_(false),
397       handling_input_event_(false),
398       handling_ime_event_(false),
399       handling_event_type_(WebInputEvent::Undefined),
400       ignore_ack_for_mouse_move_from_debugger_(false),
401       closing_(false),
402       host_closing_(false),
403       is_swapped_out_(swapped_out),
404       input_method_is_active_(false),
405       text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
406       text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
407       text_input_flags_(0),
408       can_compose_inline_(true),
409       popup_type_(popup_type),
410       pending_window_rect_count_(0),
411       suppress_next_char_events_(false),
412       screen_info_(screen_info),
413       device_scale_factor_(screen_info_.deviceScaleFactor),
414       current_event_latency_info_(NULL),
415       next_output_surface_id_(0),
416 #if defined(OS_ANDROID)
417       text_field_is_dirty_(false),
418       outstanding_ime_acks_(0),
419       body_background_color_(SK_ColorWHITE),
420 #endif
421       popup_origin_scale_for_emulation_(0.f),
422       frame_swap_message_queue_(new FrameSwapMessageQueue()),
423       resizing_mode_selector_(new ResizingModeSelector()),
424       context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
425       has_host_context_menu_location_(false) {
426   if (!swapped_out)
427     RenderProcess::current()->AddRefProcess();
428   DCHECK(RenderThread::Get());
429   device_color_profile_.push_back('0');
430 }
431
432 RenderWidget::~RenderWidget() {
433   DCHECK(!webwidget_) << "Leaking our WebWidget!";
434
435   // If we are swapped out, we have released already.
436   if (!is_swapped_out_ && RenderProcess::current())
437     RenderProcess::current()->ReleaseProcess();
438 }
439
440 // static
441 RenderWidget* RenderWidget::Create(int32 opener_id,
442                                    blink::WebPopupType popup_type,
443                                    const blink::WebScreenInfo& screen_info) {
444   DCHECK(opener_id != MSG_ROUTING_NONE);
445   scoped_refptr<RenderWidget> widget(
446       new RenderWidget(popup_type, screen_info, false, false, false));
447   if (widget->Init(opener_id)) {  // adds reference on success.
448     return widget.get();
449   }
450   return NULL;
451 }
452
453 // static
454 WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
455   switch (render_widget->popup_type_) {
456     case blink::WebPopupTypeNone:  // Nothing to create.
457       break;
458     case blink::WebPopupTypeSelect:
459     case blink::WebPopupTypeSuggestion:
460       return WebPopupMenu::create(render_widget);
461     case blink::WebPopupTypePage:
462       return WebPagePopup::create(render_widget);
463     default:
464       NOTREACHED();
465   }
466   return NULL;
467 }
468
469 bool RenderWidget::Init(int32 opener_id) {
470   return DoInit(opener_id,
471                 RenderWidget::CreateWebWidget(this),
472                 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
473                                              &routing_id_, &surface_id_));
474 }
475
476 bool RenderWidget::DoInit(int32 opener_id,
477                           WebWidget* web_widget,
478                           IPC::SyncMessage* create_widget_message) {
479   DCHECK(!webwidget_);
480
481   if (opener_id != MSG_ROUTING_NONE)
482     opener_id_ = opener_id;
483
484   webwidget_ = web_widget;
485
486   bool result = RenderThread::Get()->Send(create_widget_message);
487   if (result) {
488     RenderThread::Get()->AddRoute(routing_id_, this);
489     // Take a reference on behalf of the RenderThread.  This will be balanced
490     // when we receive ViewMsg_Close.
491     AddRef();
492     if (RenderThreadImpl::current()) {
493       RenderThreadImpl::current()->WidgetCreated();
494       if (is_hidden_)
495         RenderThreadImpl::current()->WidgetHidden();
496     }
497     return true;
498   } else {
499     // The above Send can fail when the tab is closing.
500     return false;
501   }
502 }
503
504 // This is used to complete pending inits and non-pending inits.
505 void RenderWidget::CompleteInit() {
506   DCHECK(routing_id_ != MSG_ROUTING_NONE);
507
508   init_complete_ = true;
509
510   if (compositor_)
511     StartCompositor();
512
513   Send(new ViewHostMsg_RenderViewReady(routing_id_));
514 }
515
516 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
517   // We should only toggle between states.
518   DCHECK(is_swapped_out_ != is_swapped_out);
519   is_swapped_out_ = is_swapped_out;
520
521   // If we are swapping out, we will call ReleaseProcess, allowing the process
522   // to exit if all of its RenderViews are swapped out.  We wait until the
523   // WasSwappedOut call to do this, to allow the unload handler to finish.
524   // If we are swapping in, we call AddRefProcess to prevent the process from
525   // exiting.
526   if (!is_swapped_out_)
527     RenderProcess::current()->AddRefProcess();
528 }
529
530 void RenderWidget::WasSwappedOut() {
531   // If we have been swapped out and no one else is using this process,
532   // it's safe to exit now.
533   CHECK(is_swapped_out_);
534   RenderProcess::current()->ReleaseProcess();
535 }
536
537 void RenderWidget::EnableScreenMetricsEmulation(
538     const WebDeviceEmulationParams& params) {
539   if (!screen_metrics_emulator_)
540     screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
541   else
542     screen_metrics_emulator_->ChangeEmulationParams(params);
543 }
544
545 void RenderWidget::DisableScreenMetricsEmulation() {
546   screen_metrics_emulator_.reset();
547 }
548
549 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
550     ScreenMetricsEmulator* emulator) {
551   popup_origin_scale_for_emulation_ = emulator->scale();
552   popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
553   popup_screen_origin_for_emulation_ = gfx::Point(
554       emulator->original_screen_rect().origin().x() + emulator->offset().x(),
555       emulator->original_screen_rect().origin().y() + emulator->offset().y());
556   screen_info_ = emulator->original_screen_info();
557   device_scale_factor_ = screen_info_.deviceScaleFactor;
558 }
559
560 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
561   if (screen_metrics_emulator_)
562     return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
563   return anchor;
564 }
565
566 void RenderWidget::SetScreenMetricsEmulationParameters(
567     float device_scale_factor,
568     const gfx::Point& root_layer_offset,
569     float root_layer_scale) {
570   // This is only supported in RenderView.
571   NOTREACHED();
572 }
573
574 #if defined(OS_MACOSX) || defined(OS_ANDROID)
575 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
576     ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
577   popup->SetOriginScaleAndOffsetForEmulation(
578       emulator->scale(), emulator->offset());
579 }
580 #endif
581
582 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
583   if (screen_metrics_emulator_)
584     screen_metrics_emulator_->OnShowContextMenu(params);
585 }
586
587 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
588   if (compositor_) {
589     // Regardless of whether threaded compositing is enabled, always
590     // use this mechanism to force the compositor to redraw. However,
591     // the invalidation code path below is still needed for the
592     // non-threaded case.
593     compositor_->SetNeedsForcedRedraw();
594   }
595   scheduleComposite();
596 }
597
598 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
599   bool handled = true;
600   IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
601     IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
602     IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
603                         OnCursorVisibilityChange)
604     IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
605     IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
606     IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
607     IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
608     IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
609                         OnSyntheticGestureCompleted)
610     IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
611     IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
612     IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
613     IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
614     IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
615     IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
616     IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
617     IPC_MESSAGE_HANDLER(ViewMsg_SetInputMethodActive, OnSetInputMethodActive)
618     IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowShown, OnCandidateWindowShown)
619     IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowUpdated,
620                         OnCandidateWindowUpdated)
621     IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowHidden, OnCandidateWindowHidden)
622     IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
623     IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
624     IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
625     IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
626 #if defined(OS_ANDROID)
627     IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
628     IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
629 #endif
630     IPC_MESSAGE_UNHANDLED(handled = false)
631   IPC_END_MESSAGE_MAP()
632   return handled;
633 }
634
635 bool RenderWidget::Send(IPC::Message* message) {
636   // Don't send any messages after the browser has told us to close, and filter
637   // most outgoing messages while swapped out.
638   if ((is_swapped_out_ &&
639        !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
640       closing_) {
641     delete message;
642     return false;
643   }
644
645   // If given a messsage without a routing ID, then assign our routing ID.
646   if (message->routing_id() == MSG_ROUTING_NONE)
647     message->set_routing_id(routing_id_);
648
649   return RenderThread::Get()->Send(message);
650 }
651
652 void RenderWidget::Resize(const gfx::Size& new_size,
653                           const gfx::Size& physical_backing_size,
654                           float top_controls_layout_height,
655                           const gfx::Size& visible_viewport_size,
656                           const gfx::Rect& resizer_rect,
657                           bool is_fullscreen,
658                           ResizeAck resize_ack) {
659   if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
660     // A resize ack shouldn't be requested if we have not ACK'd the previous
661     // one.
662     DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
663     DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
664   }
665
666   // Ignore this during shutdown.
667   if (!webwidget_)
668     return;
669
670   if (compositor_) {
671     compositor_->setViewportSize(new_size, physical_backing_size);
672     compositor_->SetTopControlsLayoutHeight(top_controls_layout_height);
673   }
674
675   physical_backing_size_ = physical_backing_size;
676   top_controls_layout_height_ = top_controls_layout_height;
677   visible_viewport_size_ = visible_viewport_size;
678   resizer_rect_ = resizer_rect;
679
680   // NOTE: We may have entered fullscreen mode without changing our size.
681   bool fullscreen_change = is_fullscreen_ != is_fullscreen;
682   if (fullscreen_change)
683     WillToggleFullscreen();
684   is_fullscreen_ = is_fullscreen;
685
686   webwidget_->setTopControlsLayoutHeight(top_controls_layout_height);
687
688   if (size_ != new_size) {
689     size_ = new_size;
690
691     // When resizing, we want to wait to paint before ACK'ing the resize.  This
692     // ensures that we only resize as fast as we can paint.  We only need to
693     // send an ACK if we are resized to a non-empty rect.
694     webwidget_->resize(new_size);
695   } else if (!resizing_mode_selector_->is_synchronous_mode()) {
696     resize_ack = NO_RESIZE_ACK;
697   }
698
699   webwidget()->resizePinchViewport(gfx::Size(
700       visible_viewport_size.width(),
701       visible_viewport_size.height()));
702
703   if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
704     // For empty size or empty physical_backing_size, there is no next paint
705     // (along with which to send the ack) until they are set to non-empty.
706     resize_ack = NO_RESIZE_ACK;
707   }
708
709   // Send the Resize_ACK flag once we paint again if requested.
710   if (resize_ack == SEND_RESIZE_ACK)
711     set_next_paint_is_resize_ack();
712
713   if (fullscreen_change)
714     DidToggleFullscreen();
715
716   // If a resize ack is requested and it isn't set-up, then no more resizes will
717   // come in and in general things will go wrong.
718   DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
719 }
720
721 void RenderWidget::ResizeSynchronously(
722     const gfx::Rect& new_position,
723     const gfx::Size& visible_viewport_size) {
724   Resize(new_position.size(),
725          new_position.size(),
726          top_controls_layout_height_,
727          visible_viewport_size,
728          gfx::Rect(),
729          is_fullscreen_,
730          NO_RESIZE_ACK);
731   view_screen_rect_ = new_position;
732   window_screen_rect_ = new_position;
733   if (!did_show_)
734     initial_pos_ = new_position;
735 }
736
737 void RenderWidget::OnClose() {
738   if (closing_)
739     return;
740   closing_ = true;
741
742   // Browser correspondence is no longer needed at this point.
743   if (routing_id_ != MSG_ROUTING_NONE) {
744     if (RenderThreadImpl::current())
745       RenderThreadImpl::current()->WidgetDestroyed();
746     RenderThread::Get()->RemoveRoute(routing_id_);
747     SetHidden(false);
748   }
749
750   // If there is a Send call on the stack, then it could be dangerous to close
751   // now.  Post a task that only gets invoked when there are no nested message
752   // loops.
753   base::MessageLoop::current()->PostNonNestableTask(
754       FROM_HERE, base::Bind(&RenderWidget::Close, this));
755
756   // Balances the AddRef taken when we called AddRoute.
757   Release();
758 }
759
760 // Got a response from the browser after the renderer decided to create a new
761 // view.
762 void RenderWidget::OnCreatingNewAck() {
763   DCHECK(routing_id_ != MSG_ROUTING_NONE);
764
765   CompleteInit();
766 }
767
768 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
769   if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
770     return;
771
772   if (screen_metrics_emulator_) {
773     screen_metrics_emulator_->OnResizeMessage(params);
774     return;
775   }
776
777   bool orientation_changed =
778       screen_info_.orientationAngle != params.screen_info.orientationAngle;
779
780   screen_info_ = params.screen_info;
781   SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
782   Resize(params.new_size, params.physical_backing_size,
783          params.top_controls_layout_height,
784          params.visible_viewport_size, params.resizer_rect,
785          params.is_fullscreen, SEND_RESIZE_ACK);
786
787   if (orientation_changed)
788     OnOrientationChange();
789 }
790
791 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
792   SetDeviceColorProfile(color_profile);
793 }
794
795 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
796   if (resizer_rect_ == resizer_rect)
797     return;
798   resizer_rect_ = resizer_rect;
799   if (webwidget_)
800     webwidget_->didChangeWindowResizerRect();
801 }
802
803 void RenderWidget::OnWasHidden() {
804   TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
805   // Go into a mode where we stop generating paint and scrolling events.
806   SetHidden(true);
807   FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
808                     WasHidden());
809 }
810
811 void RenderWidget::OnWasShown(bool needs_repainting,
812                               const ui::LatencyInfo& latency_info) {
813   TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
814   // During shutdown we can just ignore this message.
815   if (!webwidget_)
816     return;
817
818   // See OnWasHidden
819   SetHidden(false);
820   FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
821                     WasShown());
822
823   if (!needs_repainting)
824     return;
825
826   // Generate a full repaint.
827   if (compositor_) {
828     ui::LatencyInfo swap_latency_info(latency_info);
829     scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
830         compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
831     compositor_->SetNeedsForcedRedraw();
832   }
833   scheduleComposite();
834 }
835
836 void RenderWidget::OnRequestMoveAck() {
837   DCHECK(pending_window_rect_count_);
838   pending_window_rect_count_--;
839 }
840
841 GURL RenderWidget::GetURLForGraphicsContext3D() {
842   return GURL();
843 }
844
845 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
846   // For widgets that are never visible, we don't start the compositor, so we
847   // never get a request for a cc::OutputSurface.
848   DCHECK(!never_visible_);
849
850 #if defined(OS_ANDROID)
851   if (SynchronousCompositorFactory* factory =
852       SynchronousCompositorFactory::GetInstance()) {
853     return factory->CreateOutputSurface(routing_id(),
854                                         frame_swap_message_queue_);
855   }
856 #endif
857
858   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
859   bool use_software = fallback;
860   if (command_line.HasSwitch(switches::kDisableGpuCompositing))
861     use_software = true;
862
863   scoped_refptr<ContextProviderCommandBuffer> context_provider;
864   if (!use_software) {
865     context_provider = ContextProviderCommandBuffer::Create(
866         CreateGraphicsContext3D(), "RenderCompositor");
867     if (!context_provider.get()) {
868       // Cause the compositor to wait and try again.
869       return scoped_ptr<cc::OutputSurface>();
870     }
871   }
872
873   uint32 output_surface_id = next_output_surface_id_++;
874   if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
875     DCHECK(IsThreadedCompositingEnabled());
876     return scoped_ptr<cc::OutputSurface>(
877         new DelegatedCompositorOutputSurface(routing_id(),
878                                              output_surface_id,
879                                              context_provider,
880                                              frame_swap_message_queue_));
881   }
882   if (!context_provider.get()) {
883     scoped_ptr<cc::SoftwareOutputDevice> software_device(
884         new CompositorSoftwareOutputDevice());
885
886     return scoped_ptr<cc::OutputSurface>(
887         new CompositorOutputSurface(routing_id(),
888                                     output_surface_id,
889                                     NULL,
890                                     software_device.Pass(),
891                                     frame_swap_message_queue_,
892                                     true));
893   }
894
895   if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
896     // Composite-to-mailbox is currently used for layout tests in order to cause
897     // them to draw inside in the renderer to do the readback there. This should
898     // no longer be the case when crbug.com/311404 is fixed.
899     DCHECK(IsThreadedCompositingEnabled() ||
900            RenderThreadImpl::current()->layout_test_mode());
901     cc::ResourceFormat format = cc::RGBA_8888;
902     if (base::SysInfo::IsLowEndDevice())
903       format = cc::RGB_565;
904     return scoped_ptr<cc::OutputSurface>(
905         new MailboxOutputSurface(routing_id(),
906                                  output_surface_id,
907                                  context_provider,
908                                  scoped_ptr<cc::SoftwareOutputDevice>(),
909                                  frame_swap_message_queue_,
910                                  format));
911   }
912   bool use_swap_compositor_frame_message = false;
913   return scoped_ptr<cc::OutputSurface>(
914       new CompositorOutputSurface(routing_id(),
915                                   output_surface_id,
916                                   context_provider,
917                                   scoped_ptr<cc::SoftwareOutputDevice>(),
918                                   frame_swap_message_queue_,
919                                   use_swap_compositor_frame_message));
920 }
921
922 void RenderWidget::OnSwapBuffersAborted() {
923   TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
924   // Schedule another frame so the compositor learns about it.
925   scheduleComposite();
926 }
927
928 void RenderWidget::OnSwapBuffersPosted() {
929   TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
930 }
931
932 void RenderWidget::OnSwapBuffersComplete() {
933   TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
934
935   // Notify subclasses that composited rendering was flushed to the screen.
936   DidFlushPaint();
937 }
938
939 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
940                                       const ui::LatencyInfo& latency_info,
941                                       bool is_keyboard_shortcut) {
942   base::AutoReset<bool> handling_input_event_resetter(
943       &handling_input_event_, true);
944   if (!input_event)
945     return;
946   base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
947       &handling_event_type_, input_event->type);
948 #if defined(OS_ANDROID)
949   // On Android, when a key is pressed or sent from the Keyboard using IME,
950   // |AdapterInputConnection| generates input key events to make sure all JS
951   // listeners that monitor KeyUp and KeyDown events receive the proper key
952   // code. Since this input key event comes from IME, we need to set the
953   // IME event guard here to make sure it does not interfere with other IME
954   // events.
955   scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
956   if (WebInputEvent::isKeyboardEventType(input_event->type)) {
957     const WebKeyboardEvent& key_event =
958         *static_cast<const WebKeyboardEvent*>(input_event);
959     // Some keys are special and it's essential that no events get blocked.
960     if (key_event.nativeKeyCode != AKEYCODE_TAB &&
961         key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER)
962       ime_event_guard_maybe.reset(new ImeEventGuard(this));
963   }
964 #endif
965
966   base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
967                                                    &latency_info);
968
969   base::TimeTicks start_time;
970   if (base::TimeTicks::IsHighResNowFastAndReliable())
971     start_time = base::TimeTicks::HighResNow();
972
973   const char* const event_name =
974       WebInputEventTraits::GetName(input_event->type);
975   TRACE_EVENT1("renderer", "RenderWidget::OnHandleInputEvent",
976                "event", event_name);
977   TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
978   TRACE_EVENT_FLOW_STEP0(
979       "input",
980       "LatencyInfo.Flow",
981       TRACE_ID_DONT_MANGLE(latency_info.trace_id),
982       "HanldeInputEventMain");
983
984   scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
985   ui::LatencyInfo swap_latency_info(latency_info);
986   if (compositor_) {
987     latency_info_swap_promise_monitor =
988         compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
989             .Pass();
990   }
991
992   if (base::TimeTicks::IsHighResNowFastAndReliable()) {
993     // If we don't have a high res timer, these metrics won't be accurate enough
994     // to be worth collecting. Note that this does introduce some sampling bias.
995
996     base::TimeDelta now = base::TimeDelta::FromInternalValue(
997         base::TimeTicks::HighResNow().ToInternalValue());
998
999     int64 delta =
1000         static_cast<int64>((now.InSecondsF() - input_event->timeStampSeconds) *
1001                            base::Time::kMicrosecondsPerSecond);
1002
1003     UMA_HISTOGRAM_CUSTOM_COUNTS(
1004         "Event.AggregatedLatency.Renderer2", delta, 1, 10000000, 100);
1005     base::HistogramBase* counter_for_type = base::Histogram::FactoryGet(
1006         base::StringPrintf("Event.Latency.Renderer2.%s", event_name),
1007         1,
1008         10000000,
1009         100,
1010         base::HistogramBase::kUmaTargetedHistogramFlag);
1011     counter_for_type->Add(delta);
1012   }
1013
1014   bool prevent_default = false;
1015   if (WebInputEvent::isMouseEventType(input_event->type)) {
1016     const WebMouseEvent& mouse_event =
1017         *static_cast<const WebMouseEvent*>(input_event);
1018     TRACE_EVENT2("renderer", "HandleMouseMove",
1019                  "x", mouse_event.x, "y", mouse_event.y);
1020     context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1021     prevent_default = WillHandleMouseEvent(mouse_event);
1022   }
1023
1024   if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1025     context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1026 #if defined(OS_ANDROID)
1027     // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1028     // case it should behave like a select key (i.e. causing a click if a button
1029     // is focused). However, if a text field is focused (2), its intended
1030     // behavior is to just show the IME and don't propagate the key.
1031     // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1032     // when clicked on an input text field and cause the form submit if clicked
1033     // when the submit button is focused, but not vice-versa.
1034     // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1035     // but at this point we have to swallow the event for the scenario (2).
1036     const WebKeyboardEvent& key_event =
1037         *static_cast<const WebKeyboardEvent*>(input_event);
1038     if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1039         GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1040       OnShowImeIfNeeded();
1041       prevent_default = true;
1042     }
1043 #endif
1044   }
1045
1046   if (WebInputEvent::isGestureEventType(input_event->type)) {
1047     const WebGestureEvent& gesture_event =
1048         *static_cast<const WebGestureEvent*>(input_event);
1049     context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1050     prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1051   }
1052
1053   bool processed = prevent_default;
1054   if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1055     suppress_next_char_events_ = false;
1056     if (!processed && webwidget_)
1057       processed = webwidget_->handleInputEvent(*input_event);
1058   }
1059
1060   // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1061   // it's not processed by webkit, then we need to suppress the upcoming Char
1062   // events.
1063   if (!processed && is_keyboard_shortcut)
1064     suppress_next_char_events_ = true;
1065
1066   InputEventAckState ack_result = processed ?
1067       INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1068   if (!processed &&  input_event->type == WebInputEvent::TouchStart) {
1069     const WebTouchEvent& touch_event =
1070         *static_cast<const WebTouchEvent*>(input_event);
1071     // Hit-test for all the pressed touch points. If there is a touch-handler
1072     // for any of the touch points, then the renderer should continue to receive
1073     // touch events.
1074     ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1075     for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1076       if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1077           HasTouchEventHandlersAt(
1078               gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1079         ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1080         break;
1081       }
1082     }
1083   }
1084
1085   bool event_type_can_be_rate_limited =
1086       input_event->type == WebInputEvent::MouseMove ||
1087       input_event->type == WebInputEvent::MouseWheel;
1088
1089   bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1090
1091   // If we don't have a fast and accurate HighResNow, we assume the input
1092   // handlers are heavy and rate limit them.
1093   bool rate_limiting_wanted = true;
1094   if (base::TimeTicks::IsHighResNowFastAndReliable()) {
1095       base::TimeTicks end_time = base::TimeTicks::HighResNow();
1096       total_input_handling_time_this_frame_ += (end_time - start_time);
1097       rate_limiting_wanted =
1098           total_input_handling_time_this_frame_.InMicroseconds() >
1099           kInputHandlingTimeThrottlingThresholdMicroseconds;
1100   }
1101
1102   TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1103
1104   // Note that we can't use handling_event_type_ here since it will be overriden
1105   // by reentrant calls for events after the paused one.
1106   bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1107       input_event->type == WebInputEvent::MouseMove;
1108   if (!WebInputEventTraits::IgnoresAckDisposition(*input_event) && !no_ack) {
1109     InputHostMsg_HandleInputEvent_ACK_Params ack;
1110     ack.type = input_event->type;
1111     ack.state = ack_result;
1112     ack.latency = swap_latency_info;
1113     scoped_ptr<IPC::Message> response(
1114         new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1115     if (rate_limiting_wanted && event_type_can_be_rate_limited &&
1116         frame_pending && !is_hidden_) {
1117       // We want to rate limit the input events in this case, so we'll wait for
1118       // painting to finish before ACKing this message.
1119       TRACE_EVENT_INSTANT0("renderer",
1120         "RenderWidget::OnHandleInputEvent ack throttled",
1121         TRACE_EVENT_SCOPE_THREAD);
1122       if (pending_input_event_ack_) {
1123         // As two different kinds of events could cause us to postpone an ack
1124         // we send it now, if we have one pending. The Browser should never
1125         // send us the same kind of event we are delaying the ack for.
1126         Send(pending_input_event_ack_.release());
1127       }
1128       pending_input_event_ack_ = response.Pass();
1129       if (compositor_)
1130         compositor_->NotifyInputThrottledUntilCommit();
1131     } else {
1132       Send(response.release());
1133     }
1134   }
1135   if (input_event->type == WebInputEvent::MouseMove)
1136     ignore_ack_for_mouse_move_from_debugger_ = false;
1137
1138 #if defined(OS_ANDROID)
1139   // Allow the IME to be shown when the focus changes as a consequence
1140   // of a processed touch end event.
1141   if (input_event->type == WebInputEvent::TouchEnd && processed)
1142     UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1143 #elif defined(USE_AURA)
1144   // Show the virtual keyboard if enabled and a user gesture triggers a focus
1145   // change.
1146   if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1147       input_event->type == WebInputEvent::MouseUp))
1148     UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1149 #endif
1150
1151   if (!prevent_default) {
1152     if (WebInputEvent::isKeyboardEventType(input_event->type))
1153       DidHandleKeyEvent();
1154     if (WebInputEvent::isMouseEventType(input_event->type))
1155       DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1156     if (WebInputEvent::isTouchEventType(input_event->type))
1157       DidHandleTouchEvent(*(static_cast<const WebTouchEvent*>(input_event)));
1158   }
1159 }
1160
1161 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1162   if (webwidget_)
1163     webwidget_->setCursorVisibilityState(is_visible);
1164 }
1165
1166 void RenderWidget::OnMouseCaptureLost() {
1167   if (webwidget_)
1168     webwidget_->mouseCaptureLost();
1169 }
1170
1171 void RenderWidget::OnSetFocus(bool enable) {
1172   has_focus_ = enable;
1173   if (webwidget_)
1174     webwidget_->setFocus(enable);
1175 }
1176
1177 void RenderWidget::ClearFocus() {
1178   // We may have got the focus from the browser before this gets processed, in
1179   // which case we do not want to unfocus ourself.
1180   if (!has_focus_ && webwidget_)
1181     webwidget_->setFocus(false);
1182 }
1183
1184 void RenderWidget::FlushPendingInputEventAck() {
1185   if (pending_input_event_ack_)
1186     Send(pending_input_event_ack_.release());
1187   total_input_handling_time_this_frame_ = base::TimeDelta();
1188 }
1189
1190 ///////////////////////////////////////////////////////////////////////////////
1191 // WebWidgetClient
1192
1193 void RenderWidget::didAutoResize(const WebSize& new_size) {
1194   if (size_.width() != new_size.width || size_.height() != new_size.height) {
1195     size_ = new_size;
1196
1197     if (resizing_mode_selector_->is_synchronous_mode()) {
1198       WebRect new_pos(rootWindowRect().x,
1199                       rootWindowRect().y,
1200                       new_size.width,
1201                       new_size.height);
1202       view_screen_rect_ = new_pos;
1203       window_screen_rect_ = new_pos;
1204     }
1205
1206     AutoResizeCompositor();
1207
1208     if (!resizing_mode_selector_->is_synchronous_mode())
1209       need_update_rect_for_auto_resize_ = true;
1210   }
1211 }
1212
1213 void RenderWidget::AutoResizeCompositor()  {
1214   physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1215       device_scale_factor_));
1216   if (compositor_)
1217     compositor_->setViewportSize(size_, physical_backing_size_);
1218 }
1219
1220 void RenderWidget::initializeLayerTreeView() {
1221   DCHECK(!host_closing_);
1222
1223   compositor_ =
1224       RenderWidgetCompositor::Create(this, IsThreadedCompositingEnabled());
1225   compositor_->setViewportSize(size_, physical_backing_size_);
1226   if (init_complete_)
1227     StartCompositor();
1228 }
1229
1230 void RenderWidget::DestroyLayerTreeView() {
1231   // Always send this notification to prevent new layer tree views from
1232   // being created, even if one hasn't been created yet.
1233   if (webwidget_)
1234     webwidget_->willCloseLayerTreeView();
1235   compositor_.reset();
1236 }
1237
1238 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1239   return compositor_.get();
1240 }
1241
1242 void RenderWidget::willBeginCompositorFrame() {
1243   TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1244
1245   // The following two can result in further layout and possibly
1246   // enable GPU acceleration so they need to be called before any painting
1247   // is done.
1248   UpdateTextInputType();
1249 #if defined(OS_ANDROID)
1250   UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1251 #endif
1252   UpdateSelectionBounds();
1253 }
1254
1255 void RenderWidget::didBecomeReadyForAdditionalInput() {
1256   TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1257   FlushPendingInputEventAck();
1258 }
1259
1260 void RenderWidget::DidCommitCompositorFrame() {
1261   FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1262                     DidCommitCompositorFrame());
1263 #if defined(VIDEO_HOLE)
1264   FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1265                     DidCommitCompositorFrame());
1266 #endif  // defined(VIDEO_HOLE)
1267 }
1268
1269 // static
1270 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1271     IPC::Message* msg,
1272     MessageDeliveryPolicy policy,
1273     FrameSwapMessageQueue* frame_swap_message_queue,
1274     scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1275     bool commit_requested,
1276     int source_frame_number) {
1277   if (policy == MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE &&
1278       // No need for lock: this gets changed only on this thread.
1279       !commit_requested &&
1280       // No need for lock: Messages are only enqueued from this thread, if we
1281       // don't have any now, no other thread will add any.
1282       frame_swap_message_queue->Empty()) {
1283     sync_message_filter->Send(msg);
1284     return nullptr;
1285   }
1286
1287   bool first_message_for_frame = false;
1288   frame_swap_message_queue->QueueMessageForFrame(policy,
1289                                                  source_frame_number,
1290                                                  make_scoped_ptr(msg),
1291                                                  &first_message_for_frame);
1292   if (first_message_for_frame) {
1293     scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1294         sync_message_filter, frame_swap_message_queue, source_frame_number));
1295     return promise;
1296   }
1297   return nullptr;
1298 }
1299
1300 void RenderWidget::QueueMessage(IPC::Message* msg,
1301                                 MessageDeliveryPolicy policy) {
1302   // RenderThreadImpl::current() is NULL in some tests.
1303   if (!compositor_ || !RenderThreadImpl::current()) {
1304     Send(msg);
1305     return;
1306   }
1307
1308   scoped_ptr<cc::SwapPromise> swap_promise =
1309       QueueMessageImpl(msg,
1310                        policy,
1311                        frame_swap_message_queue_.get(),
1312                        RenderThreadImpl::current()->sync_message_filter(),
1313                        compositor_->commitRequested(),
1314                        compositor_->GetSourceFrameNumber());
1315
1316   if (swap_promise) {
1317     compositor_->QueueSwapPromise(swap_promise.Pass());
1318     compositor_->SetNeedsCommit();
1319   }
1320 }
1321
1322 void RenderWidget::didCommitAndDrawCompositorFrame() {
1323   // NOTE: Tests may break if this event is renamed or moved. See
1324   // tab_capture_performancetest.cc.
1325   TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1326   // Notify subclasses that we initiated the paint operation.
1327   DidInitiatePaint();
1328 }
1329
1330 void RenderWidget::didCompleteSwapBuffers() {
1331   TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
1332
1333   // Notify subclasses threaded composited rendering was flushed to the screen.
1334   DidFlushPaint();
1335
1336   if (!next_paint_flags_ &&
1337       !need_update_rect_for_auto_resize_ &&
1338       !plugin_window_moves_.size()) {
1339     return;
1340   }
1341
1342   ViewHostMsg_UpdateRect_Params params;
1343   params.view_size = size_;
1344   params.plugin_window_moves.swap(plugin_window_moves_);
1345   params.flags = next_paint_flags_;
1346
1347   Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1348   next_paint_flags_ = 0;
1349   need_update_rect_for_auto_resize_ = false;
1350 }
1351
1352 void RenderWidget::scheduleComposite() {
1353   RenderThreadImpl* render_thread = RenderThreadImpl::current();
1354   // render_thread may be NULL in tests.
1355   if (render_thread && render_thread->compositor_message_loop_proxy().get() &&
1356       compositor_) {
1357     compositor_->setNeedsAnimate();
1358   }
1359 }
1360
1361 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1362   // TODO(darin): Eliminate this temporary.
1363   WebCursor cursor;
1364   InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1365   // Only send a SetCursor message if we need to make a change.
1366   if (!current_cursor_.IsEqual(cursor)) {
1367     current_cursor_ = cursor;
1368     Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1369   }
1370 }
1371
1372 // We are supposed to get a single call to Show for a newly created RenderWidget
1373 // that was created via RenderWidget::CreateWebView.  So, we wait until this
1374 // point to dispatch the ShowWidget message.
1375 //
1376 // This method provides us with the information about how to display the newly
1377 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1378 //
1379 void RenderWidget::show(WebNavigationPolicy) {
1380   DCHECK(!did_show_) << "received extraneous Show call";
1381   DCHECK(routing_id_ != MSG_ROUTING_NONE);
1382   DCHECK(opener_id_ != MSG_ROUTING_NONE);
1383
1384   if (did_show_)
1385     return;
1386
1387   did_show_ = true;
1388   // NOTE: initial_pos_ may still have its default values at this point, but
1389   // that's okay.  It'll be ignored if as_popup is false, or the browser
1390   // process will impose a default position otherwise.
1391   Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_pos_));
1392   SetPendingWindowRect(initial_pos_);
1393 }
1394
1395 void RenderWidget::didFocus() {
1396 }
1397
1398 void RenderWidget::didBlur() {
1399 }
1400
1401 void RenderWidget::DoDeferredClose() {
1402   // No more compositing is possible.  This prevents shutdown races between
1403   // previously posted CreateOutputSurface tasks and the host being unable to
1404   // create them because the close message was handled.
1405   DestroyLayerTreeView();
1406   // Also prevent new compositors from being created.
1407   host_closing_ = true;
1408   Send(new ViewHostMsg_Close(routing_id_));
1409 }
1410
1411 void RenderWidget::closeWidgetSoon() {
1412   if (is_swapped_out_) {
1413     // This widget is currently swapped out, and the active widget is in a
1414     // different process.  Have the browser route the close request to the
1415     // active widget instead, so that the correct unload handlers are run.
1416     Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1417     return;
1418   }
1419
1420   // If a page calls window.close() twice, we'll end up here twice, but that's
1421   // OK.  It is safe to send multiple Close messages.
1422
1423   // Ask the RenderWidgetHost to initiate close.  We could be called from deep
1424   // in Javascript.  If we ask the RendwerWidgetHost to close now, the window
1425   // could be closed before the JS finishes executing.  So instead, post a
1426   // message back to the message loop, which won't run until the JS is
1427   // complete, and then the Close message can be sent.
1428   base::MessageLoop::current()->PostNonNestableTask(
1429       FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1430 }
1431
1432 void RenderWidget::QueueSyntheticGesture(
1433     scoped_ptr<SyntheticGestureParams> gesture_params,
1434     const SyntheticGestureCompletionCallback& callback) {
1435   DCHECK(!callback.is_null());
1436
1437   pending_synthetic_gesture_callbacks_.push(callback);
1438
1439   SyntheticGesturePacket gesture_packet;
1440   gesture_packet.set_gesture_params(gesture_params.Pass());
1441
1442   Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1443 }
1444
1445 void RenderWidget::Close() {
1446   screen_metrics_emulator_.reset();
1447   DestroyLayerTreeView();
1448   if (webwidget_) {
1449     webwidget_->close();
1450     webwidget_ = NULL;
1451   }
1452 }
1453
1454 WebRect RenderWidget::windowRect() {
1455   if (pending_window_rect_count_)
1456     return pending_window_rect_;
1457
1458   return view_screen_rect_;
1459 }
1460
1461 void RenderWidget::setToolTipText(const blink::WebString& text,
1462                                   WebTextDirection hint) {
1463   Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1464 }
1465
1466 void RenderWidget::setWindowRect(const WebRect& rect) {
1467   WebRect pos = rect;
1468   if (popup_origin_scale_for_emulation_) {
1469     float scale = popup_origin_scale_for_emulation_;
1470     pos.x = popup_screen_origin_for_emulation_.x() +
1471         (pos.x - popup_view_origin_for_emulation_.x()) * scale;
1472     pos.y = popup_screen_origin_for_emulation_.y() +
1473         (pos.y - popup_view_origin_for_emulation_.y()) * scale;
1474   }
1475
1476   if (!resizing_mode_selector_->is_synchronous_mode()) {
1477     if (did_show_) {
1478       Send(new ViewHostMsg_RequestMove(routing_id_, pos));
1479       SetPendingWindowRect(pos);
1480     } else {
1481       initial_pos_ = pos;
1482     }
1483   } else {
1484     ResizeSynchronously(pos, visible_viewport_size_);
1485   }
1486 }
1487
1488 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1489   pending_window_rect_ = rect;
1490   pending_window_rect_count_++;
1491 }
1492
1493 WebRect RenderWidget::rootWindowRect() {
1494   if (pending_window_rect_count_) {
1495     // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1496     // the RootWindowRect is probably going to return wrong results since the
1497     // browser may not have processed the Move yet.  There isn't really anything
1498     // good to do in this case, and it shouldn't happen - since this size is
1499     // only really needed for windowToScreen, which is only used for Popups.
1500     return pending_window_rect_;
1501   }
1502
1503   return window_screen_rect_;
1504 }
1505
1506 WebRect RenderWidget::windowResizerRect() {
1507   return resizer_rect_;
1508 }
1509
1510 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1511   // To prevent this renderer process from sending unnecessary IPC messages to
1512   // a browser process, we permit the renderer process to send IPC messages
1513   // only during the input method attached to the browser process is active.
1514   input_method_is_active_ = is_active;
1515 }
1516
1517 void RenderWidget::OnCandidateWindowShown() {
1518   webwidget_->didShowCandidateWindow();
1519 }
1520
1521 void RenderWidget::OnCandidateWindowUpdated() {
1522   webwidget_->didUpdateCandidateWindow();
1523 }
1524
1525 void RenderWidget::OnCandidateWindowHidden() {
1526   webwidget_->didHideCandidateWindow();
1527 }
1528
1529 void RenderWidget::OnImeSetComposition(
1530     const base::string16& text,
1531     const std::vector<WebCompositionUnderline>& underlines,
1532     int selection_start, int selection_end) {
1533   if (!ShouldHandleImeEvent())
1534     return;
1535   ImeEventGuard guard(this);
1536   if (!webwidget_->setComposition(
1537       text, WebVector<WebCompositionUnderline>(underlines),
1538       selection_start, selection_end)) {
1539     // If we failed to set the composition text, then we need to let the browser
1540     // process to cancel the input method's ongoing composition session, to make
1541     // sure we are in a consistent state.
1542     Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1543   }
1544 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
1545   UpdateCompositionInfo(true);
1546 #endif
1547 }
1548
1549 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1550                                            const gfx::Range& replacement_range,
1551                                            bool keep_selection) {
1552   if (!ShouldHandleImeEvent())
1553     return;
1554   ImeEventGuard guard(this);
1555   handling_input_event_ = true;
1556   if (text.length())
1557     webwidget_->confirmComposition(text);
1558   else if (keep_selection)
1559     webwidget_->confirmComposition(WebWidget::KeepSelection);
1560   else
1561     webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1562   handling_input_event_ = false;
1563 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
1564   UpdateCompositionInfo(true);
1565 #endif
1566 }
1567
1568 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1569   // During shutdown we can just ignore this message.
1570   if (!webwidget_)
1571     return;
1572
1573   // Even if the browser provides an empty damage rect, it's still expecting to
1574   // receive a repaint ack so just damage the entire widget bounds.
1575   if (size_to_paint.IsEmpty()) {
1576     size_to_paint = size_;
1577   }
1578
1579   set_next_paint_is_repaint_ack();
1580   if (compositor_)
1581     compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1582 }
1583
1584 void RenderWidget::OnSyntheticGestureCompleted() {
1585   DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1586
1587   pending_synthetic_gesture_callbacks_.front().Run();
1588   pending_synthetic_gesture_callbacks_.pop();
1589 }
1590
1591 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1592   if (!webwidget_)
1593     return;
1594   webwidget_->setTextDirection(direction);
1595 }
1596
1597 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1598                                        const gfx::Rect& window_screen_rect) {
1599   if (screen_metrics_emulator_) {
1600     screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1601         view_screen_rect, window_screen_rect);
1602   } else {
1603     view_screen_rect_ = view_screen_rect;
1604     window_screen_rect_ = window_screen_rect;
1605   }
1606   Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1607 }
1608
1609 void RenderWidget::showImeIfNeeded() {
1610   OnShowImeIfNeeded();
1611 }
1612
1613 void RenderWidget::OnShowImeIfNeeded() {
1614 #if defined(OS_ANDROID) || defined(USE_AURA)
1615   UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1616 #endif
1617 }
1618
1619 #if defined(OS_ANDROID)
1620 void RenderWidget::IncrementOutstandingImeEventAcks() {
1621   ++outstanding_ime_acks_;
1622 }
1623
1624 void RenderWidget::OnImeEventAck() {
1625   --outstanding_ime_acks_;
1626   DCHECK(outstanding_ime_acks_ >= 0);
1627 }
1628 #endif
1629
1630 bool RenderWidget::ShouldHandleImeEvent() {
1631 #if defined(OS_ANDROID)
1632   return !!webwidget_ && outstanding_ime_acks_ == 0;
1633 #else
1634   return !!webwidget_;
1635 #endif
1636 }
1637
1638 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1639   if (handling_event_type_ == WebInputEvent::MouseMove) {
1640     // If we pause multiple times during a single mouse move event, we should
1641     // only send ACK once.
1642     if (!ignore_ack_for_mouse_move_from_debugger_) {
1643       InputHostMsg_HandleInputEvent_ACK_Params ack;
1644       ack.type = handling_event_type_;
1645       ack.state = INPUT_EVENT_ACK_STATE_CONSUMED;
1646       Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1647     }
1648     return true;
1649   }
1650   return false;
1651 }
1652
1653 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1654   ignore_ack_for_mouse_move_from_debugger_ = true;
1655 }
1656
1657 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1658   if (device_scale_factor_ == device_scale_factor)
1659     return;
1660
1661   device_scale_factor_ = device_scale_factor;
1662   scheduleComposite();
1663 }
1664
1665 bool RenderWidget::SetDeviceColorProfile(
1666     const std::vector<char>& color_profile) {
1667   if (device_color_profile_ == color_profile)
1668     return false;
1669
1670   device_color_profile_ = color_profile;
1671   return true;
1672 }
1673
1674 void RenderWidget::ResetDeviceColorProfileForTesting() {
1675   if (!device_color_profile_.empty())
1676     device_color_profile_.clear();
1677   device_color_profile_.push_back('0');
1678 }
1679
1680 void RenderWidget::OnOrientationChange() {
1681 }
1682
1683 gfx::Vector2d RenderWidget::GetScrollOffset() {
1684   // Bare RenderWidgets don't support scroll offset.
1685   return gfx::Vector2d();
1686 }
1687
1688 void RenderWidget::SetHidden(bool hidden) {
1689   if (is_hidden_ == hidden)
1690     return;
1691
1692   // The status has changed.  Tell the RenderThread about it.
1693   is_hidden_ = hidden;
1694   if (is_hidden_)
1695     RenderThreadImpl::current()->WidgetHidden();
1696   else
1697     RenderThreadImpl::current()->WidgetRestored();
1698 }
1699
1700 void RenderWidget::WillToggleFullscreen() {
1701   if (!webwidget_)
1702     return;
1703
1704   if (is_fullscreen_) {
1705     webwidget_->willExitFullScreen();
1706   } else {
1707     webwidget_->willEnterFullScreen();
1708   }
1709 }
1710
1711 void RenderWidget::DidToggleFullscreen() {
1712   if (!webwidget_)
1713     return;
1714
1715   if (is_fullscreen_) {
1716     webwidget_->didEnterFullScreen();
1717   } else {
1718     webwidget_->didExitFullScreen();
1719   }
1720 }
1721
1722 bool RenderWidget::next_paint_is_resize_ack() const {
1723   return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1724 }
1725
1726 void RenderWidget::set_next_paint_is_resize_ack() {
1727   next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1728 }
1729
1730 void RenderWidget::set_next_paint_is_repaint_ack() {
1731   next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1732 }
1733
1734 static bool IsDateTimeInput(ui::TextInputType type) {
1735   return type == ui::TEXT_INPUT_TYPE_DATE ||
1736       type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1737       type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1738       type == ui::TEXT_INPUT_TYPE_MONTH ||
1739       type == ui::TEXT_INPUT_TYPE_TIME ||
1740       type == ui::TEXT_INPUT_TYPE_WEEK;
1741 }
1742
1743
1744 void RenderWidget::StartHandlingImeEvent() {
1745   DCHECK(!handling_ime_event_);
1746   handling_ime_event_ = true;
1747 }
1748
1749 void RenderWidget::FinishHandlingImeEvent() {
1750   DCHECK(handling_ime_event_);
1751   handling_ime_event_ = false;
1752   // While handling an ime event, text input state and selection bounds updates
1753   // are ignored. These must explicitly be updated once finished handling the
1754   // ime event.
1755   UpdateSelectionBounds();
1756 #if defined(OS_ANDROID)
1757   UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1758 #endif
1759 }
1760
1761 void RenderWidget::UpdateTextInputType() {
1762   // On Windows, not only an IME but also an on-screen keyboard relies on the
1763   // latest TextInputType to optimize its layout and functionality. Thus
1764   // |input_method_is_active_| is no longer an appropriate condition to suppress
1765   // TextInputTypeChanged IPC on Windows.
1766   // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
1767   // on other platforms as well as Windows if the overhead is acceptable.
1768 #if !defined(OS_WIN)
1769   if (!input_method_is_active_)
1770     return;
1771 #endif
1772
1773   ui::TextInputType new_type = GetTextInputType();
1774   if (IsDateTimeInput(new_type))
1775     return;  // Not considered as a text input field in WebKit/Chromium.
1776
1777   bool new_can_compose_inline = CanComposeInline();
1778
1779   blink::WebTextInputInfo new_info;
1780   if (webwidget_)
1781     new_info = webwidget_->textInputInfo();
1782   const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1783   int new_flags = new_info.flags;
1784
1785   if (text_input_type_ != new_type
1786       || can_compose_inline_ != new_can_compose_inline
1787       || text_input_mode_ != new_mode
1788       || text_input_flags_ != new_flags) {
1789     Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1790                                               new_type,
1791                                               new_mode,
1792                                               new_can_compose_inline,
1793                                               new_flags));
1794     text_input_type_ = new_type;
1795     can_compose_inline_ = new_can_compose_inline;
1796     text_input_mode_ = new_mode;
1797     text_input_flags_ = new_flags;
1798   }
1799 }
1800
1801 #if defined(OS_ANDROID) || defined(USE_AURA)
1802 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1803                                         ChangeSource change_source) {
1804   if (handling_ime_event_)
1805     return;
1806   if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1807     return;
1808   ui::TextInputType new_type = GetTextInputType();
1809   if (IsDateTimeInput(new_type))
1810     return;  // Not considered as a text input field in WebKit/Chromium.
1811
1812   blink::WebTextInputInfo new_info;
1813   if (webwidget_)
1814     new_info = webwidget_->textInputInfo();
1815
1816   bool new_can_compose_inline = CanComposeInline();
1817
1818   // Only sends text input params if they are changed or if the ime should be
1819   // shown.
1820   if (show_ime == SHOW_IME_IF_NEEDED ||
1821       (text_input_type_ != new_type ||
1822        text_input_info_ != new_info ||
1823        can_compose_inline_ != new_can_compose_inline)
1824 #if defined(OS_ANDROID)
1825       || text_field_is_dirty_
1826 #endif
1827       ) {
1828     ViewHostMsg_TextInputState_Params p;
1829     p.type = new_type;
1830     p.flags = new_info.flags;
1831     p.value = new_info.value.utf8();
1832     p.selection_start = new_info.selectionStart;
1833     p.selection_end = new_info.selectionEnd;
1834     p.composition_start = new_info.compositionStart;
1835     p.composition_end = new_info.compositionEnd;
1836     p.can_compose_inline = new_can_compose_inline;
1837     p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1838 #if defined(USE_AURA)
1839     p.is_non_ime_change = true;
1840 #endif
1841 #if defined(OS_ANDROID)
1842     p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1843                          text_field_is_dirty_;
1844     if (p.is_non_ime_change)
1845       IncrementOutstandingImeEventAcks();
1846     text_field_is_dirty_ = false;
1847 #endif
1848 #if defined(USE_AURA)
1849     Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1850                                               new_type,
1851                                               text_input_mode_,
1852                                               new_can_compose_inline,
1853                                               new_info.flags));
1854 #endif
1855     Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
1856
1857     text_input_info_ = new_info;
1858     text_input_type_ = new_type;
1859     can_compose_inline_ = new_can_compose_inline;
1860     text_input_flags_ = new_info.flags;
1861   }
1862 }
1863 #endif
1864
1865 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1866   WebRect focus_webrect;
1867   WebRect anchor_webrect;
1868   webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1869   *focus = focus_webrect;
1870   *anchor = anchor_webrect;
1871 }
1872
1873 void RenderWidget::UpdateSelectionBounds() {
1874   if (!webwidget_)
1875     return;
1876   if (handling_ime_event_)
1877     return;
1878
1879   // With composited selection updates, the selection bounds will be reported
1880   // directly by the compositor, in which case explicit IPC selection
1881   // notifications should be suppressed.
1882   if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
1883     ViewHostMsg_SelectionBounds_Params params;
1884     GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
1885     if (selection_anchor_rect_ != params.anchor_rect ||
1886         selection_focus_rect_ != params.focus_rect) {
1887       selection_anchor_rect_ = params.anchor_rect;
1888       selection_focus_rect_ = params.focus_rect;
1889       webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
1890       params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
1891       Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
1892     }
1893   }
1894
1895 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
1896   UpdateCompositionInfo(false);
1897 #endif
1898 }
1899
1900 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
1901 COMPILE_ASSERT(int(blink::WebTextInputTypeNone) == \
1902                int(ui::TEXT_INPUT_TYPE_NONE), mismatching_enums);
1903 COMPILE_ASSERT(int(blink::WebTextInputTypeText) == \
1904                int(ui::TEXT_INPUT_TYPE_TEXT), mismatching_enums);
1905 COMPILE_ASSERT(int(blink::WebTextInputTypePassword) == \
1906                int(ui::TEXT_INPUT_TYPE_PASSWORD), mismatching_enums);
1907 COMPILE_ASSERT(int(blink::WebTextInputTypeSearch) == \
1908                int(ui::TEXT_INPUT_TYPE_SEARCH), mismatching_enums);
1909 COMPILE_ASSERT(int(blink::WebTextInputTypeEmail) == \
1910                int(ui::TEXT_INPUT_TYPE_EMAIL), mismatching_enums);
1911 COMPILE_ASSERT(int(blink::WebTextInputTypeNumber) == \
1912                int(ui::TEXT_INPUT_TYPE_NUMBER), mismatching_enums);
1913 COMPILE_ASSERT(int(blink::WebTextInputTypeTelephone) == \
1914                int(ui::TEXT_INPUT_TYPE_TELEPHONE), mismatching_enums);
1915 COMPILE_ASSERT(int(blink::WebTextInputTypeURL) == \
1916                int(ui::TEXT_INPUT_TYPE_URL), mismatching_enums);
1917 COMPILE_ASSERT(int(blink::WebTextInputTypeDate) == \
1918                int(ui::TEXT_INPUT_TYPE_DATE), mismatching_enum);
1919 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTime) == \
1920                int(ui::TEXT_INPUT_TYPE_DATE_TIME), mismatching_enum);
1921 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeLocal) == \
1922                int(ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL), mismatching_enum);
1923 COMPILE_ASSERT(int(blink::WebTextInputTypeMonth) == \
1924                int(ui::TEXT_INPUT_TYPE_MONTH), mismatching_enum);
1925 COMPILE_ASSERT(int(blink::WebTextInputTypeTime) == \
1926                int(ui::TEXT_INPUT_TYPE_TIME), mismatching_enum);
1927 COMPILE_ASSERT(int(blink::WebTextInputTypeWeek) == \
1928                int(ui::TEXT_INPUT_TYPE_WEEK), mismatching_enum);
1929 COMPILE_ASSERT(int(blink::WebTextInputTypeTextArea) == \
1930                int(ui::TEXT_INPUT_TYPE_TEXT_AREA), mismatching_enums);
1931 COMPILE_ASSERT(int(blink::WebTextInputTypeContentEditable) == \
1932                int(ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE), mismatching_enums);
1933 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeField) == \
1934                int(ui::TEXT_INPUT_TYPE_DATE_TIME_FIELD), mismatching_enums);
1935
1936 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
1937     blink::WebTextInputType type) {
1938   // Check the type is in the range representable by ui::TextInputType.
1939   DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
1940     "blink::WebTextInputType and ui::TextInputType not synchronized";
1941   return static_cast<ui::TextInputType>(type);
1942 }
1943
1944 ui::TextInputType RenderWidget::GetTextInputType() {
1945   if (webwidget_)
1946     return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
1947   return ui::TEXT_INPUT_TYPE_NONE;
1948 }
1949
1950 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
1951 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
1952 #if defined(OS_ANDROID)
1953   // Sending composition info makes sense only in Lollipop (API level 21)
1954   // and above due to the API availability.
1955   if (base::android::BuildInfo::GetInstance()->sdk_int() < 21)
1956     return;
1957 #endif
1958
1959   gfx::Range range = gfx::Range();
1960   if (should_update_range) {
1961     GetCompositionRange(&range);
1962   } else {
1963     range = composition_range_;
1964   }
1965   std::vector<gfx::Rect> character_bounds;
1966   GetCompositionCharacterBounds(&character_bounds);
1967
1968   if (!ShouldUpdateCompositionInfo(range, character_bounds))
1969     return;
1970   composition_character_bounds_ = character_bounds;
1971   composition_range_ = range;
1972   Send(new InputHostMsg_ImeCompositionRangeChanged(
1973       routing_id(), composition_range_, composition_character_bounds_));
1974 }
1975
1976 void RenderWidget::GetCompositionCharacterBounds(
1977     std::vector<gfx::Rect>* bounds) {
1978   DCHECK(bounds);
1979   bounds->clear();
1980 }
1981
1982 void RenderWidget::GetCompositionRange(gfx::Range* range) {
1983   size_t location, length;
1984   if (webwidget_->compositionRange(&location, &length)) {
1985     range->set_start(location);
1986     range->set_end(location + length);
1987   } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
1988     range->set_start(location);
1989     range->set_end(location + length);
1990   } else {
1991     *range = gfx::Range::InvalidRange();
1992   }
1993 }
1994
1995 bool RenderWidget::ShouldUpdateCompositionInfo(
1996     const gfx::Range& range,
1997     const std::vector<gfx::Rect>& bounds) {
1998   if (composition_range_ != range)
1999     return true;
2000   if (bounds.size() != composition_character_bounds_.size())
2001     return true;
2002   for (size_t i = 0; i < bounds.size(); ++i) {
2003     if (bounds[i] != composition_character_bounds_[i])
2004       return true;
2005   }
2006   return false;
2007 }
2008 #endif
2009
2010 #if defined(OS_ANDROID)
2011 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2012   // If not initialized, default to white. Note that 0 is different from black
2013   // as black still has alpha 0xFF.
2014   if (!bg_color)
2015     bg_color = SK_ColorWHITE;
2016
2017   if (bg_color != body_background_color_) {
2018     body_background_color_ = bg_color;
2019     Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2020   }
2021 }
2022 #endif
2023
2024 bool RenderWidget::CanComposeInline() {
2025   return true;
2026 }
2027
2028 WebScreenInfo RenderWidget::screenInfo() {
2029   return screen_info_;
2030 }
2031
2032 float RenderWidget::deviceScaleFactor() {
2033   return device_scale_factor_;
2034 }
2035
2036 void RenderWidget::resetInputMethod() {
2037   if (!input_method_is_active_)
2038     return;
2039
2040   ImeEventGuard guard(this);
2041   // If the last text input type is not None, then we should finish any
2042   // ongoing composition regardless of the new text input type.
2043   if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2044     // If a composition text exists, then we need to let the browser process
2045     // to cancel the input method's ongoing composition session.
2046     if (webwidget_->confirmComposition())
2047       Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2048   }
2049
2050 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
2051   UpdateCompositionInfo(true);
2052 #endif
2053 }
2054
2055 void RenderWidget::didHandleGestureEvent(
2056     const WebGestureEvent& event,
2057     bool event_cancelled) {
2058 #if defined(OS_ANDROID) || defined(USE_AURA)
2059   if (event_cancelled)
2060     return;
2061   if (event.type == WebInputEvent::GestureTap) {
2062     UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2063   } else if (event.type == WebInputEvent::GestureLongPress) {
2064     DCHECK(webwidget_);
2065     if (webwidget_->textInputInfo().value.isEmpty())
2066       UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2067     else
2068       UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2069   }
2070 #endif
2071 }
2072
2073 void RenderWidget::StartCompositor() {
2074   // For widgets that are never visible, we don't need the compositor to run
2075   // at all.
2076   if (never_visible_)
2077     return;
2078   compositor_->setSurfaceReady();
2079 }
2080
2081 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2082   size_t i = 0;
2083   for (; i < plugin_window_moves_.size(); ++i) {
2084     if (plugin_window_moves_[i].window == move.window) {
2085       if (move.rects_valid) {
2086         plugin_window_moves_[i] = move;
2087       } else {
2088         plugin_window_moves_[i].visible = move.visible;
2089       }
2090       break;
2091     }
2092   }
2093
2094   if (i == plugin_window_moves_.size())
2095     plugin_window_moves_.push_back(move);
2096 }
2097
2098 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2099   for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2100        i != plugin_window_moves_.end(); ++i) {
2101     if (i->window == window) {
2102       plugin_window_moves_.erase(i);
2103       break;
2104     }
2105   }
2106 }
2107
2108
2109 RenderWidgetCompositor* RenderWidget::compositor() const {
2110   return compositor_.get();
2111 }
2112
2113 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2114   return false;
2115 }
2116
2117 bool RenderWidget::WillHandleGestureEvent(
2118     const blink::WebGestureEvent& event) {
2119   return false;
2120 }
2121
2122 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2123   Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2124 }
2125
2126 void RenderWidget::setTouchAction(
2127     blink::WebTouchAction web_touch_action) {
2128
2129   // Ignore setTouchAction calls that result from synthetic touch events (eg.
2130   // when blink is emulating touch with mouse).
2131   if (handling_event_type_ != WebInputEvent::TouchStart)
2132     return;
2133
2134    // Verify the same values are used by the types so we can cast between them.
2135    COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_AUTO) ==
2136                       blink::WebTouchActionAuto,
2137                   enum_values_must_match_for_touch_action);
2138    COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_NONE) ==
2139                       blink::WebTouchActionNone,
2140                   enum_values_must_match_for_touch_action);
2141    COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_X) ==
2142                       blink::WebTouchActionPanX,
2143                   enum_values_must_match_for_touch_action);
2144    COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_Y) ==
2145                       blink::WebTouchActionPanY,
2146                   enum_values_must_match_for_touch_action);
2147    COMPILE_ASSERT(
2148        static_cast<blink::WebTouchAction>(TOUCH_ACTION_PINCH_ZOOM) ==
2149            blink::WebTouchActionPinchZoom,
2150        enum_values_must_match_for_touch_action);
2151
2152    content::TouchAction content_touch_action =
2153        static_cast<content::TouchAction>(web_touch_action);
2154   Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2155 }
2156
2157 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2158 #if defined(OS_ANDROID)
2159   text_field_is_dirty_ = true;
2160 #endif
2161 }
2162
2163 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2164   return true;
2165 }
2166
2167 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2168 RenderWidget::CreateGraphicsContext3D() {
2169   if (!webwidget_)
2170     return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2171   if (CommandLine::ForCurrentProcess()->HasSwitch(
2172           switches::kDisableGpuCompositing))
2173     return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2174   if (!RenderThreadImpl::current())
2175     return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2176   CauseForGpuLaunch cause =
2177       CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2178   scoped_refptr<GpuChannelHost> gpu_channel_host(
2179       RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2180   if (!gpu_channel_host.get())
2181     return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2182
2183   // Explicitly disable antialiasing for the compositor. As of the time of
2184   // this writing, the only platform that supported antialiasing for the
2185   // compositor was Mac OS X, because the on-screen OpenGL context creation
2186   // code paths on Windows and Linux didn't yet have multisampling support.
2187   // Mac OS X essentially always behaves as though it's rendering offscreen.
2188   // Multisampling has a heavy cost especially on devices with relatively low
2189   // fill rate like most notebooks, and the Mac implementation would need to
2190   // be optimized to resolve directly into the IOSurface shared between the
2191   // GPU and browser processes. For these reasons and to avoid platform
2192   // disparities we explicitly disable antialiasing.
2193   blink::WebGraphicsContext3D::Attributes attributes;
2194   attributes.antialias = false;
2195   attributes.shareResources = true;
2196   attributes.noAutomaticFlushes = true;
2197   attributes.depth = false;
2198   attributes.stencil = false;
2199   bool lose_context_when_out_of_memory = true;
2200   WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2201 #if defined(OS_ANDROID)
2202   // If we raster too fast we become upload bound, and pending
2203   // uploads consume memory. For maximum upload throughput, we would
2204   // want to allow for upload_throughput * pipeline_time of pending
2205   // uploads, after which we are just wasting memory. Since we don't
2206   // know our upload throughput yet, this just caps our memory usage.
2207   size_t divider = 1;
2208   if (base::SysInfo::IsLowEndDevice())
2209     divider = 6;
2210   // For reference Nexus10 can upload 1MB in about 2.5ms.
2211   const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2212   // Deadline to draw a frame to achieve 60 frames per second.
2213   const size_t kMillisecondsPerFrame = 16;
2214   // Assuming a two frame deep pipeline between the CPU and the GPU.
2215   size_t max_transfer_buffer_usage_mb =
2216       static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2217   static const size_t kBytesPerMegabyte = 1024 * 1024;
2218   // We keep the MappedMemoryReclaimLimit the same as the upload limit
2219   // to avoid unnecessarily stalling the compositor thread.
2220   limits.mapped_memory_reclaim_limit =
2221       max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2222 #endif
2223
2224   scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2225       new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2226                                                 GetURLForGraphicsContext3D(),
2227                                                 gpu_channel_host.get(),
2228                                                 attributes,
2229                                                 lose_context_when_out_of_memory,
2230                                                 limits,
2231                                                 NULL));
2232   return context.Pass();
2233 }
2234
2235 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2236   render_frame_proxies_.AddObserver(proxy);
2237 }
2238
2239 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2240   render_frame_proxies_.RemoveObserver(proxy);
2241 }
2242
2243 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2244   render_frames_.AddObserver(frame);
2245 }
2246
2247 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2248   render_frames_.RemoveObserver(frame);
2249 }
2250
2251 #if defined(VIDEO_HOLE)
2252 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2253   video_hole_frames_.AddObserver(frame);
2254 }
2255
2256 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2257   video_hole_frames_.RemoveObserver(frame);
2258 }
2259 #endif  // defined(VIDEO_HOLE)
2260
2261 }  // namespace content