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