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