[Android] Implement 3-way sensor fallback for Device Orientation.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
bloba071d1477ad0e8e6c6e6962b95285a313368c79f
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/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/singleton.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/stl_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/sys_info.h"
18 #include "base/trace_event/trace_event.h"
19 #include "base/trace_event/trace_event_synthetic_delay.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 "components/scheduler/renderer/renderer_scheduler.h"
26 #include "content/child/npapi/webplugin.h"
27 #include "content/common/gpu/client/context_provider_command_buffer.h"
28 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
29 #include "content/common/gpu/gpu_process_launch_causes.h"
30 #include "content/common/input/synthetic_gesture_packet.h"
31 #include "content/common/input/web_input_event_traits.h"
32 #include "content/common/input_messages.h"
33 #include "content/common/swapped_out_messages.h"
34 #include "content/common/view_messages.h"
35 #include "content/public/common/content_switches.h"
36 #include "content/public/common/context_menu_params.h"
37 #include "content/renderer/cursor_utils.h"
38 #include "content/renderer/external_popup_menu.h"
39 #include "content/renderer/gpu/compositor_output_surface.h"
40 #include "content/renderer/gpu/delegated_compositor_output_surface.h"
41 #include "content/renderer/gpu/frame_swap_message_queue.h"
42 #include "content/renderer/gpu/mailbox_output_surface.h"
43 #include "content/renderer/gpu/queue_message_swap_promise.h"
44 #include "content/renderer/gpu/render_widget_compositor.h"
45 #include "content/renderer/ime_event_guard.h"
46 #include "content/renderer/input/input_handler_manager.h"
47 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
48 #include "content/renderer/render_frame_impl.h"
49 #include "content/renderer/render_frame_proxy.h"
50 #include "content/renderer/render_process.h"
51 #include "content/renderer/render_thread_impl.h"
52 #include "content/renderer/renderer_blink_platform_impl.h"
53 #include "content/renderer/resizing_mode_selector.h"
54 #include "ipc/ipc_sync_message.h"
55 #include "skia/ext/platform_canvas.h"
56 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
57 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
58 #include "third_party/WebKit/public/platform/WebPoint.h"
59 #include "third_party/WebKit/public/platform/WebRect.h"
60 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
61 #include "third_party/WebKit/public/platform/WebSize.h"
62 #include "third_party/WebKit/public/platform/WebString.h"
63 #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
64 #include "third_party/WebKit/public/web/WebFrameWidget.h"
65 #include "third_party/WebKit/public/web/WebLocalFrame.h"
66 #include "third_party/WebKit/public/web/WebNode.h"
67 #include "third_party/WebKit/public/web/WebPagePopup.h"
68 #include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
69 #include "third_party/WebKit/public/web/WebRange.h"
70 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
71 #include "third_party/WebKit/public/web/WebView.h"
72 #include "third_party/skia/include/core/SkShader.h"
73 #include "ui/base/ui_base_switches.h"
74 #include "ui/gfx/geometry/point_conversions.h"
75 #include "ui/gfx/geometry/rect_conversions.h"
76 #include "ui/gfx/geometry/size_conversions.h"
77 #include "ui/gfx/skia_util.h"
78 #include "ui/gl/gl_switches.h"
79 #include "ui/surface/transport_dib.h"
81 #if defined(OS_ANDROID)
82 #include <android/keycodes.h>
83 #include "content/renderer/android/synchronous_compositor_factory.h"
84 #endif
86 #if defined(OS_POSIX)
87 #include "ipc/ipc_channel_posix.h"
88 #include "third_party/skia/include/core/SkMallocPixelRef.h"
89 #include "third_party/skia/include/core/SkPixelRef.h"
90 #endif // defined(OS_POSIX)
92 #include "third_party/WebKit/public/web/WebWidget.h"
94 using blink::WebCompositionUnderline;
95 using blink::WebCursorInfo;
96 using blink::WebDeviceEmulationParams;
97 using blink::WebGestureEvent;
98 using blink::WebInputEvent;
99 using blink::WebKeyboardEvent;
100 using blink::WebMouseEvent;
101 using blink::WebMouseWheelEvent;
102 using blink::WebNavigationPolicy;
103 using blink::WebNode;
104 using blink::WebPagePopup;
105 using blink::WebPoint;
106 using blink::WebPopupType;
107 using blink::WebRange;
108 using blink::WebRect;
109 using blink::WebScreenInfo;
110 using blink::WebSize;
111 using blink::WebTextDirection;
112 using blink::WebTouchEvent;
113 using blink::WebTouchPoint;
114 using blink::WebVector;
115 using blink::WebWidget;
117 namespace {
119 typedef std::map<std::string, ui::TextInputMode> TextInputModeMap;
121 class TextInputModeMapSingleton {
122 public:
123 static TextInputModeMapSingleton* GetInstance() {
124 return Singleton<TextInputModeMapSingleton>::get();
126 TextInputModeMapSingleton() {
127 map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM;
128 map_["latin"] = ui::TEXT_INPUT_MODE_LATIN;
129 map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME;
130 map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE;
131 map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN;
132 map_["kana"] = ui::TEXT_INPUT_MODE_KANA;
133 map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA;
134 map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC;
135 map_["tel"] = ui::TEXT_INPUT_MODE_TEL;
136 map_["email"] = ui::TEXT_INPUT_MODE_EMAIL;
137 map_["url"] = ui::TEXT_INPUT_MODE_URL;
139 const TextInputModeMap& map() const { return map_; }
140 private:
141 TextInputModeMap map_;
143 friend struct DefaultSingletonTraits<TextInputModeMapSingleton>;
145 DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton);
148 ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) {
149 static TextInputModeMapSingleton* singleton =
150 TextInputModeMapSingleton::GetInstance();
151 TextInputModeMap::const_iterator it =
152 singleton->map().find(input_mode.utf8());
153 if (it == singleton->map().end())
154 return ui::TEXT_INPUT_MODE_DEFAULT;
155 return it->second;
158 // TODO(brianderson): Replace the hard-coded threshold with a fraction of
159 // the BeginMainFrame interval.
160 // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to
161 // be spent in input hanlders before input starts getting throttled.
162 const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166;
164 int64 GetEventLatencyMicros(double event_timestamp, base::TimeTicks now) {
165 return (now - base::TimeDelta::FromSecondsD(event_timestamp))
166 .ToInternalValue();
169 void LogInputEventLatencyUmaImpl(WebInputEvent::Type event_type,
170 double event_timestamp,
171 base::TimeTicks now) {
172 UMA_HISTOGRAM_CUSTOM_COUNTS("Event.AggregatedLatency.Renderer2",
173 GetEventLatencyMicros(event_timestamp, now), 1,
174 10000000, 100);
176 #define CASE_TYPE(t) \
177 case WebInputEvent::t: \
178 UMA_HISTOGRAM_CUSTOM_COUNTS("Event.Latency.Renderer2." #t, \
179 GetEventLatencyMicros(event_timestamp, now), \
180 1, 10000000, 100); \
181 break;
183 switch (event_type) {
184 CASE_TYPE(Undefined);
185 CASE_TYPE(MouseDown);
186 CASE_TYPE(MouseUp);
187 CASE_TYPE(MouseMove);
188 CASE_TYPE(MouseEnter);
189 CASE_TYPE(MouseLeave);
190 CASE_TYPE(ContextMenu);
191 CASE_TYPE(MouseWheel);
192 CASE_TYPE(RawKeyDown);
193 CASE_TYPE(KeyDown);
194 CASE_TYPE(KeyUp);
195 CASE_TYPE(Char);
196 CASE_TYPE(GestureScrollBegin);
197 CASE_TYPE(GestureScrollEnd);
198 CASE_TYPE(GestureScrollUpdate);
199 CASE_TYPE(GestureFlingStart);
200 CASE_TYPE(GestureFlingCancel);
201 CASE_TYPE(GestureShowPress);
202 CASE_TYPE(GestureTap);
203 CASE_TYPE(GestureTapUnconfirmed);
204 CASE_TYPE(GestureTapDown);
205 CASE_TYPE(GestureTapCancel);
206 CASE_TYPE(GestureDoubleTap);
207 CASE_TYPE(GestureTwoFingerTap);
208 CASE_TYPE(GestureLongPress);
209 CASE_TYPE(GestureLongTap);
210 CASE_TYPE(GesturePinchBegin);
211 CASE_TYPE(GesturePinchEnd);
212 CASE_TYPE(GesturePinchUpdate);
213 CASE_TYPE(TouchStart);
214 CASE_TYPE(TouchMove);
215 CASE_TYPE(TouchEnd);
216 CASE_TYPE(TouchCancel);
217 default:
218 // Must include default to let blink::WebInputEvent add new event types
219 // before they're added here.
220 DLOG(WARNING) << "Unhandled WebInputEvent type: " << event_type;
221 break;
224 #undef CASE_TYPE
227 void LogInputEventLatencyUma(const WebInputEvent& event, base::TimeTicks now,
228 const ui::LatencyInfo& latency_info) {
229 LogInputEventLatencyUmaImpl(event.type, event.timeStampSeconds, now);
230 for (size_t i = 0; i < latency_info.coalesced_events_size(); i++) {
231 LogInputEventLatencyUmaImpl(
232 event.type,
233 latency_info.timestamps_of_coalesced_events()[i],
234 now);
238 } // namespace
240 namespace content {
242 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
244 class RenderWidget::ScreenMetricsEmulator {
245 public:
246 ScreenMetricsEmulator(
247 RenderWidget* widget,
248 const WebDeviceEmulationParams& params);
249 virtual ~ScreenMetricsEmulator();
251 // Scale and offset used to convert between host coordinates
252 // and webwidget coordinates.
253 float scale() { return scale_; }
254 gfx::PointF offset() { return offset_; }
255 gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
256 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
257 const WebScreenInfo& original_screen_info() { return original_screen_info_; }
259 void ChangeEmulationParams(
260 const WebDeviceEmulationParams& params);
262 // The following methods alter handlers' behavior for messages related to
263 // widget size and position.
264 void OnResizeMessage(const ViewMsg_Resize_Params& params);
265 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
266 const gfx::Rect& window_screen_rect);
267 void OnShowContextMenu(ContextMenuParams* params);
268 gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
270 private:
271 void Reapply();
272 void Apply(bool top_controls_shrink_blink_size,
273 float top_controls_height,
274 gfx::Rect resizer_rect,
275 bool is_fullscreen_granted,
276 blink::WebDisplayMode display_mode);
278 RenderWidget* widget_;
280 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
281 WebDeviceEmulationParams params_;
283 // The computed scale and offset used to fit widget into browser window.
284 float scale_;
285 gfx::PointF offset_;
287 // Widget rect as passed to webwidget.
288 gfx::Rect applied_widget_rect_;
290 // Original values to restore back after emulation ends.
291 gfx::Size original_size_;
292 gfx::Size original_physical_backing_size_;
293 gfx::Size original_visible_viewport_size_;
294 blink::WebScreenInfo original_screen_info_;
295 gfx::Rect original_view_screen_rect_;
296 gfx::Rect original_window_screen_rect_;
299 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
300 RenderWidget* widget,
301 const WebDeviceEmulationParams& params)
302 : widget_(widget),
303 params_(params),
304 scale_(1.f) {
305 original_size_ = widget_->size_;
306 original_physical_backing_size_ = widget_->physical_backing_size_;
307 original_visible_viewport_size_ = widget_->visible_viewport_size_;
308 original_screen_info_ = widget_->screen_info_;
309 original_view_screen_rect_ = widget_->view_screen_rect_;
310 original_window_screen_rect_ = widget_->window_screen_rect_;
311 Apply(widget_->top_controls_shrink_blink_size_,
312 widget_->top_controls_height_,
313 widget_->resizer_rect_,
314 widget_->is_fullscreen_granted_,
315 widget_->display_mode_);
318 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
319 widget_->screen_info_ = original_screen_info_;
321 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
322 widget_->SetScreenMetricsEmulationParameters(false, params_);
323 widget_->view_screen_rect_ = original_view_screen_rect_;
324 widget_->window_screen_rect_ = original_window_screen_rect_;
325 widget_->Resize(original_size_,
326 original_physical_backing_size_,
327 widget_->top_controls_shrink_blink_size_,
328 widget_->top_controls_height_,
329 original_visible_viewport_size_,
330 widget_->resizer_rect_,
331 widget_->is_fullscreen_granted_,
332 widget_->display_mode_,
333 NO_RESIZE_ACK);
336 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
337 const WebDeviceEmulationParams& params) {
338 params_ = params;
339 Reapply();
342 void RenderWidget::ScreenMetricsEmulator::Reapply() {
343 Apply(widget_->top_controls_shrink_blink_size_,
344 widget_->top_controls_height_,
345 widget_->resizer_rect_,
346 widget_->is_fullscreen_granted_,
347 widget_->display_mode_);
350 void RenderWidget::ScreenMetricsEmulator::Apply(
351 bool top_controls_shrink_blink_size,
352 float top_controls_height,
353 gfx::Rect resizer_rect,
354 bool is_fullscreen_granted,
355 blink::WebDisplayMode display_mode) {
356 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
357 if (!applied_widget_rect_.width())
358 applied_widget_rect_.set_width(original_size_.width());
359 if (!applied_widget_rect_.height())
360 applied_widget_rect_.set_height(original_size_.height());
362 if (params_.fitToView && !original_size_.IsEmpty()) {
363 int original_width = std::max(original_size_.width(), 1);
364 int original_height = std::max(original_size_.height(), 1);
365 float width_ratio =
366 static_cast<float>(applied_widget_rect_.width()) / original_width;
367 float height_ratio =
368 static_cast<float>(applied_widget_rect_.height()) / original_height;
369 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
370 scale_ = 1.f / ratio;
372 // Center emulated view inside available view space.
373 offset_.set_x(
374 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
375 offset_.set_y(
376 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
377 } else {
378 scale_ = params_.scale;
379 offset_.SetPoint(params_.offset.x, params_.offset.y);
382 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
383 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
384 widget_->screen_info_.rect = original_screen_info_.rect;
385 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
386 widget_->window_screen_rect_ = original_window_screen_rect_;
387 } else {
388 applied_widget_rect_.set_origin(params_.viewPosition);
389 gfx::Rect screen_rect = applied_widget_rect_;
390 if (!params_.screenSize.isEmpty()) {
391 screen_rect =
392 gfx::Rect(0, 0, params_.screenSize.width, params_.screenSize.height);
394 widget_->screen_info_.rect = screen_rect;
395 widget_->screen_info_.availableRect = screen_rect;
396 widget_->window_screen_rect_ = applied_widget_rect_;
399 float applied_device_scale_factor = params_.deviceScaleFactor ?
400 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
401 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
403 // Pass three emulation parameters to the blink side:
404 // - we keep the real device scale factor in compositor to produce sharp image
405 // even when emulating different scale factor;
406 // - in order to fit into view, WebView applies offset and scale to the
407 // root layer.
408 blink::WebDeviceEmulationParams modified_params = params_;
409 modified_params.deviceScaleFactor = original_screen_info_.deviceScaleFactor;
410 modified_params.offset = blink::WebFloatPoint(offset_.x(), offset_.y());
411 modified_params.scale = scale_;
412 widget_->SetScreenMetricsEmulationParameters(true, modified_params);
414 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
415 widget_->view_screen_rect_ = applied_widget_rect_;
417 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
418 original_size_, original_screen_info_.deviceScaleFactor));
419 widget_->Resize(applied_widget_rect_.size(),
420 physical_backing_size,
421 top_controls_shrink_blink_size,
422 top_controls_height,
423 applied_widget_rect_.size(),
424 resizer_rect,
425 is_fullscreen_granted,
426 display_mode,
427 NO_RESIZE_ACK);
430 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
431 const ViewMsg_Resize_Params& params) {
432 bool need_ack = params.new_size != original_size_ &&
433 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
434 original_size_ = params.new_size;
435 original_physical_backing_size_ = params.physical_backing_size;
436 original_screen_info_ = params.screen_info;
437 original_visible_viewport_size_ = params.visible_viewport_size;
438 Apply(params.top_controls_shrink_blink_size,
439 params.top_controls_height,
440 params.resizer_rect,
441 params.is_fullscreen_granted,
442 params.display_mode);
444 if (need_ack) {
445 widget_->set_next_paint_is_resize_ack();
446 if (widget_->compositor_)
447 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
451 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
452 const gfx::Rect& view_screen_rect,
453 const gfx::Rect& window_screen_rect) {
454 original_view_screen_rect_ = view_screen_rect;
455 original_window_screen_rect_ = window_screen_rect;
456 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
457 Reapply();
460 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
461 ContextMenuParams* params) {
462 params->x *= scale_;
463 params->x += offset_.x();
464 params->y *= scale_;
465 params->y += offset_.y();
468 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
469 const gfx::Rect& anchor) {
470 gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
471 scaled.set_x(scaled.x() + offset_.x());
472 scaled.set_y(scaled.y() + offset_.y());
473 return scaled;
476 // RenderWidget ---------------------------------------------------------------
478 RenderWidget::RenderWidget(CompositorDependencies* compositor_deps,
479 blink::WebPopupType popup_type,
480 const blink::WebScreenInfo& screen_info,
481 bool swapped_out,
482 bool hidden,
483 bool never_visible)
484 : routing_id_(MSG_ROUTING_NONE),
485 surface_id_(0),
486 compositor_deps_(compositor_deps),
487 webwidget_(nullptr),
488 opener_id_(MSG_ROUTING_NONE),
489 init_complete_(false),
490 top_controls_shrink_blink_size_(false),
491 top_controls_height_(0.f),
492 next_paint_flags_(0),
493 auto_resize_mode_(false),
494 need_update_rect_for_auto_resize_(false),
495 did_show_(false),
496 is_hidden_(hidden),
497 never_visible_(never_visible),
498 is_fullscreen_granted_(false),
499 display_mode_(blink::WebDisplayModeUndefined),
500 has_focus_(false),
501 handling_input_event_(false),
502 handling_event_overscroll_(nullptr),
503 handling_ime_event_(false),
504 handling_event_type_(WebInputEvent::Undefined),
505 ignore_ack_for_mouse_move_from_debugger_(false),
506 closing_(false),
507 host_closing_(false),
508 is_swapped_out_(swapped_out),
509 for_oopif_(false),
510 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
511 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
512 text_input_flags_(0),
513 can_compose_inline_(true),
514 popup_type_(popup_type),
515 pending_window_rect_count_(0),
516 suppress_next_char_events_(false),
517 screen_info_(screen_info),
518 device_scale_factor_(screen_info_.deviceScaleFactor),
519 next_output_surface_id_(0),
520 #if defined(OS_ANDROID)
521 text_field_is_dirty_(false),
522 body_background_color_(SK_ColorWHITE),
523 #endif
524 popup_origin_scale_for_emulation_(0.f),
525 frame_swap_message_queue_(new FrameSwapMessageQueue()),
526 resizing_mode_selector_(new ResizingModeSelector()),
527 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
528 has_host_context_menu_location_(false) {
529 if (!swapped_out)
530 RenderProcess::current()->AddRefProcess();
531 DCHECK(RenderThread::Get());
532 device_color_profile_.push_back('0');
533 #if defined(OS_ANDROID)
534 text_input_info_history_.push_back(blink::WebTextInputInfo());
535 #endif
538 RenderWidget::~RenderWidget() {
539 DCHECK(!webwidget_) << "Leaking our WebWidget!";
541 // If we are swapped out, we have released already.
542 if (!is_swapped_out_ && RenderProcess::current())
543 RenderProcess::current()->ReleaseProcess();
546 // static
547 RenderWidget* RenderWidget::Create(int32 opener_id,
548 CompositorDependencies* compositor_deps,
549 blink::WebPopupType popup_type,
550 const blink::WebScreenInfo& screen_info) {
551 DCHECK(opener_id != MSG_ROUTING_NONE);
552 scoped_refptr<RenderWidget> widget(new RenderWidget(
553 compositor_deps, popup_type, screen_info, false, false, false));
554 if (widget->Init(opener_id)) { // adds reference on success.
555 return widget.get();
557 return NULL;
560 // static
561 RenderWidget* RenderWidget::CreateForFrame(
562 int routing_id,
563 int surface_id,
564 bool hidden,
565 const blink::WebScreenInfo& screen_info,
566 CompositorDependencies* compositor_deps,
567 blink::WebLocalFrame* frame) {
568 CHECK_NE(routing_id, MSG_ROUTING_NONE);
569 scoped_refptr<RenderWidget> widget(
570 new RenderWidget(compositor_deps, blink::WebPopupTypeNone, screen_info,
571 false, hidden, false));
572 widget->routing_id_ = routing_id;
573 widget->surface_id_ = surface_id;
574 widget->for_oopif_ = true;
575 // DoInit increments the reference count on |widget|, keeping it alive after
576 // this function returns.
577 if (widget->DoInit(MSG_ROUTING_NONE,
578 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
579 nullptr)) {
580 widget->CompleteInit();
581 return widget.get();
583 return nullptr;
586 // static
587 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
588 RenderWidget* render_widget,
589 blink::WebLocalFrame* frame) {
590 return blink::WebFrameWidget::create(render_widget, frame);
593 // static
594 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
595 switch (render_widget->popup_type_) {
596 case blink::WebPopupTypeNone: // Nothing to create.
597 break;
598 case blink::WebPopupTypePage:
599 return WebPagePopup::create(render_widget);
600 default:
601 NOTREACHED();
603 return NULL;
606 void RenderWidget::CloseForFrame() {
607 OnClose();
610 bool RenderWidget::Init(int32 opener_id) {
611 return DoInit(opener_id, RenderWidget::CreateWebWidget(this),
612 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
613 &routing_id_, &surface_id_));
616 bool RenderWidget::DoInit(int32 opener_id,
617 WebWidget* web_widget,
618 IPC::SyncMessage* create_widget_message) {
619 DCHECK(!webwidget_);
621 if (opener_id != MSG_ROUTING_NONE)
622 opener_id_ = opener_id;
624 webwidget_ = web_widget;
626 bool result = true;
627 if (create_widget_message)
628 result = RenderThread::Get()->Send(create_widget_message);
630 if (result) {
631 RenderThread::Get()->AddRoute(routing_id_, this);
632 // Take a reference on behalf of the RenderThread. This will be balanced
633 // when we receive ViewMsg_Close.
634 AddRef();
635 if (RenderThreadImpl::current()) {
636 RenderThreadImpl::current()->WidgetCreated();
637 if (is_hidden_)
638 RenderThreadImpl::current()->WidgetHidden();
640 return true;
641 } else {
642 // The above Send can fail when the tab is closing.
643 return false;
647 // This is used to complete pending inits and non-pending inits.
648 void RenderWidget::CompleteInit() {
649 DCHECK(routing_id_ != MSG_ROUTING_NONE);
651 init_complete_ = true;
653 if (compositor_)
654 StartCompositor();
656 Send(new ViewHostMsg_RenderViewReady(routing_id_));
659 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
660 // We should only toggle between states.
661 DCHECK(is_swapped_out_ != is_swapped_out);
662 is_swapped_out_ = is_swapped_out;
664 // If we are swapping out, we will call ReleaseProcess, allowing the process
665 // to exit if all of its RenderViews are swapped out. We wait until the
666 // WasSwappedOut call to do this, to allow the unload handler to finish.
667 // If we are swapping in, we call AddRefProcess to prevent the process from
668 // exiting.
669 if (!is_swapped_out_)
670 RenderProcess::current()->AddRefProcess();
673 void RenderWidget::WasSwappedOut() {
674 // If we have been swapped out and no one else is using this process,
675 // it's safe to exit now.
676 CHECK(is_swapped_out_);
677 RenderProcess::current()->ReleaseProcess();
680 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
681 ScreenMetricsEmulator* emulator) {
682 popup_origin_scale_for_emulation_ = emulator->scale();
683 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
684 popup_screen_origin_for_emulation_ = gfx::Point(
685 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
686 emulator->original_screen_rect().origin().y() + emulator->offset().y());
687 screen_info_ = emulator->original_screen_info();
688 device_scale_factor_ = screen_info_.deviceScaleFactor;
691 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
692 if (screen_metrics_emulator_)
693 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
694 return anchor;
697 void RenderWidget::SetScreenMetricsEmulationParameters(
698 bool enabled,
699 const blink::WebDeviceEmulationParams& params) {
700 // This is only supported in RenderView.
701 NOTREACHED();
704 #if defined(OS_MACOSX) || defined(OS_ANDROID)
705 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
706 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
707 popup->SetOriginScaleAndOffsetForEmulation(
708 emulator->scale(), emulator->offset());
710 #endif
712 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
713 if (screen_metrics_emulator_)
714 screen_metrics_emulator_->OnShowContextMenu(params);
717 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
718 bool handled = true;
719 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
720 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
721 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
722 OnCursorVisibilityChange)
723 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
724 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
725 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
726 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
727 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
728 OnSyntheticGestureCompleted)
729 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
730 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
731 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
732 IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation,
733 OnEnableDeviceEmulation)
734 IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation,
735 OnDisableDeviceEmulation)
736 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
737 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
738 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
739 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
740 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
741 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
742 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
743 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
744 IPC_MESSAGE_HANDLER(ViewMsg_SetSurfaceIdNamespace, OnSetSurfaceIdNamespace)
745 #if defined(OS_ANDROID)
746 IPC_MESSAGE_HANDLER(InputMsg_ImeEventAck, OnImeEventAck)
747 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
748 #endif
749 IPC_MESSAGE_UNHANDLED(handled = false)
750 IPC_END_MESSAGE_MAP()
751 return handled;
754 bool RenderWidget::Send(IPC::Message* message) {
755 // Don't send any messages after the browser has told us to close, and filter
756 // most outgoing messages while swapped out.
757 if ((is_swapped_out_ &&
758 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
759 closing_) {
760 delete message;
761 return false;
764 // If given a messsage without a routing ID, then assign our routing ID.
765 if (message->routing_id() == MSG_ROUTING_NONE)
766 message->set_routing_id(routing_id_);
768 return RenderThread::Get()->Send(message);
771 void RenderWidget::Resize(const gfx::Size& new_size,
772 const gfx::Size& physical_backing_size,
773 bool top_controls_shrink_blink_size,
774 float top_controls_height,
775 const gfx::Size& visible_viewport_size,
776 const gfx::Rect& resizer_rect,
777 bool is_fullscreen_granted,
778 blink::WebDisplayMode display_mode,
779 const ResizeAck resize_ack) {
780 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
781 // A resize ack shouldn't be requested if we have not ACK'd the previous
782 // one.
783 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
784 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
787 // Ignore this during shutdown.
788 if (!webwidget_)
789 return;
791 if (compositor_) {
792 compositor_->setViewportSize(new_size, physical_backing_size);
795 physical_backing_size_ = physical_backing_size;
796 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
797 top_controls_height_ = top_controls_height;
798 visible_viewport_size_ = visible_viewport_size;
799 resizer_rect_ = resizer_rect;
801 // NOTE: We may have entered fullscreen mode without changing our size.
802 bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted;
803 is_fullscreen_granted_ = is_fullscreen_granted;
804 display_mode_ = display_mode;
806 webwidget_->setTopControlsHeight(top_controls_height,
807 top_controls_shrink_blink_size_);
809 if (size_ != new_size) {
810 size_ = new_size;
812 // When resizing, we want to wait to paint before ACK'ing the resize. This
813 // ensures that we only resize as fast as we can paint. We only need to
814 // send an ACK if we are resized to a non-empty rect.
815 webwidget_->resize(new_size);
818 webwidget()->resizePinchViewport(gfx::Size(
819 visible_viewport_size.width(),
820 visible_viewport_size.height()));
822 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
823 // In this case there is no paint/composite and therefore no
824 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
825 // ack through a fake ViewHostMsg_UpdateRect or a different message.
826 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
829 // Send the Resize_ACK flag once we paint again if requested.
830 if (resize_ack == SEND_RESIZE_ACK)
831 set_next_paint_is_resize_ack();
833 if (fullscreen_change)
834 DidToggleFullscreen();
836 // If a resize ack is requested and it isn't set-up, then no more resizes will
837 // come in and in general things will go wrong.
838 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
841 void RenderWidget::SetWindowRectSynchronously(
842 const gfx::Rect& new_window_rect) {
843 Resize(new_window_rect.size(),
844 new_window_rect.size(),
845 top_controls_shrink_blink_size_,
846 top_controls_height_,
847 new_window_rect.size(),
848 gfx::Rect(),
849 is_fullscreen_granted_,
850 display_mode_,
851 NO_RESIZE_ACK);
852 view_screen_rect_ = new_window_rect;
853 window_screen_rect_ = new_window_rect;
854 if (!did_show_)
855 initial_rect_ = new_window_rect;
858 void RenderWidget::OnClose() {
859 DCHECK(content::RenderThread::Get());
860 if (closing_)
861 return;
862 NotifyOnClose();
863 closing_ = true;
865 // Browser correspondence is no longer needed at this point.
866 if (routing_id_ != MSG_ROUTING_NONE) {
867 RenderThread::Get()->RemoveRoute(routing_id_);
868 SetHidden(false);
869 if (RenderThreadImpl::current())
870 RenderThreadImpl::current()->WidgetDestroyed();
873 if (for_oopif_) {
874 // Widgets for frames may be created and closed at any time while the frame
875 // is alive. However, the closing process must happen synchronously. Frame
876 // widget and frames hold pointers to each other. If Close() is deferred to
877 // the message loop like in the non-frame widget case, WebWidget::close()
878 // can end up accessing members of an already-deleted frame.
879 Close();
880 } else {
881 // If there is a Send call on the stack, then it could be dangerous to close
882 // now. Post a task that only gets invoked when there are no nested message
883 // loops.
884 base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(
885 FROM_HERE, base::Bind(&RenderWidget::Close, this));
888 // Balances the AddRef taken when we called AddRoute.
889 Release();
892 // Got a response from the browser after the renderer decided to create a new
893 // view.
894 void RenderWidget::OnCreatingNewAck() {
895 DCHECK(routing_id_ != MSG_ROUTING_NONE);
897 CompleteInit();
900 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
901 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
902 return;
904 if (screen_metrics_emulator_) {
905 screen_metrics_emulator_->OnResizeMessage(params);
906 return;
909 bool orientation_changed =
910 screen_info_.orientationAngle != params.screen_info.orientationAngle;
912 screen_info_ = params.screen_info;
913 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
914 Resize(params.new_size,
915 params.physical_backing_size,
916 params.top_controls_shrink_blink_size,
917 params.top_controls_height,
918 params.visible_viewport_size,
919 params.resizer_rect,
920 params.is_fullscreen_granted,
921 params.display_mode,
922 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
924 if (orientation_changed)
925 OnOrientationChange();
928 void RenderWidget::OnEnableDeviceEmulation(
929 const blink::WebDeviceEmulationParams& params) {
930 if (!screen_metrics_emulator_)
931 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
932 else
933 screen_metrics_emulator_->ChangeEmulationParams(params);
936 void RenderWidget::OnDisableDeviceEmulation() {
937 screen_metrics_emulator_.reset();
940 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
941 SetDeviceColorProfile(color_profile);
944 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
945 if (resizer_rect_ == resizer_rect)
946 return;
947 resizer_rect_ = resizer_rect;
948 if (webwidget_)
949 webwidget_->didChangeWindowResizerRect();
952 void RenderWidget::OnWasHidden() {
953 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
954 // Go into a mode where we stop generating paint and scrolling events.
955 SetHidden(true);
956 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
957 WasHidden());
960 void RenderWidget::OnWasShown(bool needs_repainting,
961 const ui::LatencyInfo& latency_info) {
962 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
963 // During shutdown we can just ignore this message.
964 if (!webwidget_)
965 return;
967 // See OnWasHidden
968 SetHidden(false);
969 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
970 WasShown());
972 if (!needs_repainting)
973 return;
975 // Generate a full repaint.
976 if (compositor_) {
977 ui::LatencyInfo swap_latency_info(latency_info);
978 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
979 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
980 compositor_->SetNeedsForcedRedraw();
982 ScheduleComposite();
985 void RenderWidget::OnRequestMoveAck() {
986 DCHECK(pending_window_rect_count_);
987 pending_window_rect_count_--;
990 GURL RenderWidget::GetURLForGraphicsContext3D() {
991 return GURL();
994 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
995 // For widgets that are never visible, we don't start the compositor, so we
996 // never get a request for a cc::OutputSurface.
997 DCHECK(!never_visible_);
999 #if defined(OS_ANDROID)
1000 if (SynchronousCompositorFactory* factory =
1001 SynchronousCompositorFactory::GetInstance()) {
1002 return factory->CreateOutputSurface(routing_id(), surface_id(),
1003 frame_swap_message_queue_);
1005 #endif
1007 const base::CommandLine& command_line =
1008 *base::CommandLine::ForCurrentProcess();
1009 bool use_software = fallback;
1010 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1011 use_software = true;
1013 scoped_refptr<ContextProviderCommandBuffer> context_provider;
1014 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
1015 if (!use_software) {
1016 context_provider = ContextProviderCommandBuffer::Create(
1017 CreateGraphicsContext3D(true), RENDER_COMPOSITOR_CONTEXT);
1018 if (!context_provider.get()) {
1019 // Cause the compositor to wait and try again.
1020 return scoped_ptr<cc::OutputSurface>();
1023 worker_context_provider = ContextProviderCommandBuffer::Create(
1024 CreateGraphicsContext3D(false), RENDER_WORKER_CONTEXT);
1025 if (!worker_context_provider.get()) {
1026 // Cause the compositor to wait and try again.
1027 return scoped_ptr<cc::OutputSurface>();
1031 uint32 output_surface_id = next_output_surface_id_++;
1032 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1033 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1034 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1035 routing_id(), output_surface_id, context_provider,
1036 worker_context_provider, frame_swap_message_queue_));
1038 if (!context_provider.get()) {
1039 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1040 new cc::SoftwareOutputDevice());
1042 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1043 routing_id(), output_surface_id, nullptr, nullptr,
1044 software_device.Pass(), frame_swap_message_queue_, true));
1047 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1048 // Composite-to-mailbox is currently used for layout tests in order to cause
1049 // them to draw inside in the renderer to do the readback there. This should
1050 // no longer be the case when crbug.com/311404 is fixed.
1051 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1052 cc::ResourceFormat format = cc::RGBA_8888;
1053 if (base::SysInfo::IsLowEndDevice())
1054 format = cc::RGB_565;
1055 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1056 routing_id(), output_surface_id, context_provider,
1057 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1058 frame_swap_message_queue_, format));
1060 bool use_swap_compositor_frame_message = false;
1061 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1062 routing_id(), output_surface_id, context_provider,
1063 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1064 frame_swap_message_queue_, use_swap_compositor_frame_message));
1067 void RenderWidget::OnSwapBuffersAborted() {
1068 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1069 // Schedule another frame so the compositor learns about it.
1070 ScheduleComposite();
1073 void RenderWidget::OnSwapBuffersPosted() {
1074 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1077 void RenderWidget::OnSwapBuffersComplete() {
1078 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1080 // Notify subclasses that composited rendering was flushed to the screen.
1081 DidFlushPaint();
1084 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1085 const ui::LatencyInfo& latency_info,
1086 bool is_keyboard_shortcut) {
1087 if (!input_event)
1088 return;
1089 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1090 true);
1091 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1092 &handling_event_type_, input_event->type);
1094 // Calls into |didOverscroll()| while handling this event will populate
1095 // |event_overscroll|, which in turn will be bundled with the event ack.
1096 scoped_ptr<DidOverscrollParams> event_overscroll;
1097 base::AutoReset<scoped_ptr<DidOverscrollParams>*>
1098 handling_event_overscroll_resetter(&handling_event_overscroll_,
1099 &event_overscroll);
1101 #if defined(OS_ANDROID)
1102 // On Android, when a key is pressed or sent from the Keyboard using IME,
1103 // |AdapterInputConnection| generates input key events to make sure all JS
1104 // listeners that monitor KeyUp and KeyDown events receive the proper key
1105 // code. Since this input key event comes from IME, we need to set the
1106 // IME event guard here to make sure it does not interfere with other IME
1107 // events.
1108 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1109 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1110 const WebKeyboardEvent& key_event =
1111 *static_cast<const WebKeyboardEvent*>(input_event);
1112 // Some keys are special and it's essential that no events get blocked.
1113 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1114 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1115 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1116 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1117 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1118 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1119 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1121 #endif
1123 base::TimeTicks start_time;
1124 if (base::TimeTicks::IsHighResolution())
1125 start_time = base::TimeTicks::Now();
1127 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1128 "event", WebInputEventTraits::GetName(input_event->type));
1129 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1130 TRACE_EVENT_WITH_FLOW1("input,benchmark",
1131 "LatencyInfo.Flow",
1132 TRACE_ID_DONT_MANGLE(latency_info.trace_id()),
1133 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
1134 "step", "HandleInputEventMain");
1136 // If we don't have a high res timer, these metrics won't be accurate enough
1137 // to be worth collecting. Note that this does introduce some sampling bias.
1138 if (!start_time.is_null())
1139 LogInputEventLatencyUma(*input_event, start_time, latency_info);
1141 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1142 ui::LatencyInfo swap_latency_info(latency_info);
1143 if (compositor_) {
1144 latency_info_swap_promise_monitor =
1145 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1146 .Pass();
1149 bool prevent_default = false;
1150 if (WebInputEvent::isMouseEventType(input_event->type)) {
1151 const WebMouseEvent& mouse_event =
1152 *static_cast<const WebMouseEvent*>(input_event);
1153 TRACE_EVENT2("renderer", "HandleMouseMove",
1154 "x", mouse_event.x, "y", mouse_event.y);
1155 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1156 prevent_default = WillHandleMouseEvent(mouse_event);
1159 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1160 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1161 #if defined(OS_ANDROID)
1162 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1163 // case it should behave like a select key (i.e. causing a click if a button
1164 // is focused). However, if a text field is focused (2), its intended
1165 // behavior is to just show the IME and don't propagate the key.
1166 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1167 // when clicked on an input text field and cause the form submit if clicked
1168 // when the submit button is focused, but not vice-versa.
1169 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1170 // but at this point we have to swallow the event for the scenario (2).
1171 const WebKeyboardEvent& key_event =
1172 *static_cast<const WebKeyboardEvent*>(input_event);
1173 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1174 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1175 OnShowImeIfNeeded();
1176 prevent_default = true;
1178 #endif
1181 if (WebInputEvent::isGestureEventType(input_event->type)) {
1182 const WebGestureEvent& gesture_event =
1183 *static_cast<const WebGestureEvent*>(input_event);
1184 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1185 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1188 bool processed = prevent_default;
1189 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1190 suppress_next_char_events_ = false;
1191 if (!processed && webwidget_)
1192 processed = webwidget_->handleInputEvent(*input_event);
1195 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1196 // it's not processed by webkit, then we need to suppress the upcoming Char
1197 // events.
1198 if (!processed && is_keyboard_shortcut)
1199 suppress_next_char_events_ = true;
1201 InputEventAckState ack_result = processed ?
1202 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1203 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1204 const WebTouchEvent& touch_event =
1205 *static_cast<const WebTouchEvent*>(input_event);
1206 // Hit-test for all the pressed touch points. If there is a touch-handler
1207 // for any of the touch points, then the renderer should continue to receive
1208 // touch events.
1209 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1210 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1211 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1212 HasTouchEventHandlersAt(
1213 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1214 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1215 break;
1220 // Send mouse wheel events and their disposition to the compositor thread, so
1221 // that they can be used to produce the elastic overscroll effect on Mac.
1222 if (input_event->type == WebInputEvent::MouseWheel) {
1223 ObserveWheelEventAndResult(
1224 static_cast<const WebMouseWheelEvent&>(*input_event),
1225 event_overscroll ? event_overscroll->latest_overscroll_delta
1226 : gfx::Vector2dF(),
1227 processed);
1230 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1232 // If we don't have a fast and accurate Now(), we assume the input handlers
1233 // are heavy and rate limit them.
1234 bool rate_limiting_wanted =
1235 input_event->type == WebInputEvent::MouseMove ||
1236 input_event->type == WebInputEvent::MouseWheel;
1237 if (rate_limiting_wanted && !start_time.is_null()) {
1238 base::TimeTicks end_time = base::TimeTicks::Now();
1239 total_input_handling_time_this_frame_ += (end_time - start_time);
1240 rate_limiting_wanted =
1241 total_input_handling_time_this_frame_.InMicroseconds() >
1242 kInputHandlingTimeThrottlingThresholdMicroseconds;
1245 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1247 // Note that we can't use handling_event_type_ here since it will be overriden
1248 // by reentrant calls for events after the paused one.
1249 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1250 input_event->type == WebInputEvent::MouseMove;
1251 if (WebInputEventTraits::WillReceiveAckFromRenderer(*input_event) &&
1252 !no_ack) {
1253 InputEventAck ack(input_event->type, ack_result, swap_latency_info,
1254 event_overscroll.Pass(),
1255 WebInputEventTraits::GetUniqueTouchEventId(*input_event));
1256 scoped_ptr<IPC::Message> response(
1257 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1258 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1259 // We want to rate limit the input events in this case, so we'll wait for
1260 // painting to finish before ACKing this message.
1261 TRACE_EVENT_INSTANT0("renderer",
1262 "RenderWidget::OnHandleInputEvent ack throttled",
1263 TRACE_EVENT_SCOPE_THREAD);
1264 if (pending_input_event_ack_) {
1265 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1266 pending_input_event_ack_.get());
1267 // As two different kinds of events could cause us to postpone an ack
1268 // we send it now, if we have one pending. The Browser should never
1269 // send us the same kind of event we are delaying the ack for.
1270 Send(pending_input_event_ack_.release());
1272 pending_input_event_ack_ = response.Pass();
1273 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1274 pending_input_event_ack_.get());
1275 if (compositor_)
1276 compositor_->NotifyInputThrottledUntilCommit();
1277 } else {
1278 Send(response.release());
1280 } else {
1281 DCHECK(!event_overscroll) << "Unexpected overscroll for un-acked event";
1283 if (!no_ack && RenderThreadImpl::current()) {
1284 RenderThreadImpl::current()
1285 ->GetRendererScheduler()
1286 ->DidHandleInputEventOnMainThread(*input_event);
1288 if (input_event->type == WebInputEvent::MouseMove)
1289 ignore_ack_for_mouse_move_from_debugger_ = false;
1291 #if defined(OS_ANDROID)
1292 // Allow the IME to be shown when the focus changes as a consequence
1293 // of a processed touch end event.
1294 if (input_event->type == WebInputEvent::TouchEnd && processed)
1295 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1296 #elif defined(USE_AURA)
1297 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1298 // change.
1299 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1300 input_event->type == WebInputEvent::MouseUp)) {
1301 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1303 #endif
1305 if (!prevent_default) {
1306 if (WebInputEvent::isKeyboardEventType(input_event->type))
1307 DidHandleKeyEvent();
1310 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1311 // virtual keyboard.
1312 #if !defined(OS_ANDROID)
1313 // Virtual keyboard is not supported, so react to focus change immediately.
1314 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1315 input_event->type == WebInputEvent::MouseUp)) {
1316 FocusChangeComplete();
1318 #endif
1321 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1322 if (webwidget_)
1323 webwidget_->setCursorVisibilityState(is_visible);
1326 void RenderWidget::OnMouseCaptureLost() {
1327 if (webwidget_)
1328 webwidget_->mouseCaptureLost();
1331 void RenderWidget::OnSetFocus(bool enable) {
1332 has_focus_ = enable;
1333 if (webwidget_)
1334 webwidget_->setFocus(enable);
1337 void RenderWidget::ClearFocus() {
1338 // We may have got the focus from the browser before this gets processed, in
1339 // which case we do not want to unfocus ourself.
1340 if (!has_focus_ && webwidget_)
1341 webwidget_->setFocus(false);
1344 void RenderWidget::FlushPendingInputEventAck() {
1345 if (pending_input_event_ack_) {
1346 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1347 pending_input_event_ack_.get());
1348 Send(pending_input_event_ack_.release());
1350 total_input_handling_time_this_frame_ = base::TimeDelta();
1353 ///////////////////////////////////////////////////////////////////////////////
1354 // WebWidgetClient
1356 void RenderWidget::didAutoResize(const WebSize& new_size) {
1357 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1358 size_ = new_size;
1360 if (resizing_mode_selector_->is_synchronous_mode()) {
1361 WebRect new_pos(rootWindowRect().x,
1362 rootWindowRect().y,
1363 new_size.width,
1364 new_size.height);
1365 view_screen_rect_ = new_pos;
1366 window_screen_rect_ = new_pos;
1369 AutoResizeCompositor();
1371 if (!resizing_mode_selector_->is_synchronous_mode())
1372 need_update_rect_for_auto_resize_ = true;
1376 void RenderWidget::AutoResizeCompositor() {
1377 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1378 device_scale_factor_));
1379 if (compositor_)
1380 compositor_->setViewportSize(size_, physical_backing_size_);
1383 void RenderWidget::initializeLayerTreeView() {
1384 DCHECK(!host_closing_);
1386 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1387 compositor_->setViewportSize(size_, physical_backing_size_);
1388 if (init_complete_)
1389 StartCompositor();
1392 void RenderWidget::WillCloseLayerTreeView() {
1393 if (host_closing_)
1394 return;
1396 // Prevent new compositors or output surfaces from being created.
1397 host_closing_ = true;
1399 // Always send this notification to prevent new layer tree views from
1400 // being created, even if one hasn't been created yet.
1401 if (webwidget_)
1402 webwidget_->willCloseLayerTreeView();
1405 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1406 return compositor_.get();
1409 void RenderWidget::WillBeginCompositorFrame() {
1410 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1412 // The UpdateTextInputState can result in further layout and possibly
1413 // enable GPU acceleration so they need to be called before any painting
1414 // is done.
1415 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1416 UpdateSelectionBounds();
1419 void RenderWidget::DidCommitCompositorFrame() {
1420 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1421 DidCommitCompositorFrame());
1422 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1423 DidCommitCompositorFrame());
1424 #if defined(VIDEO_HOLE)
1425 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1426 DidCommitCompositorFrame());
1427 #endif // defined(VIDEO_HOLE)
1428 FlushPendingInputEventAck();
1431 void RenderWidget::DidCommitAndDrawCompositorFrame() {
1432 // NOTE: Tests may break if this event is renamed or moved. See
1433 // tab_capture_performancetest.cc.
1434 TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame");
1435 // Notify subclasses that we initiated the paint operation.
1436 DidInitiatePaint();
1439 void RenderWidget::DidCompleteSwapBuffers() {
1440 TRACE_EVENT0("renderer", "RenderWidget::DidCompleteSwapBuffers");
1442 // Notify subclasses threaded composited rendering was flushed to the screen.
1443 DidFlushPaint();
1445 if (!next_paint_flags_ &&
1446 !need_update_rect_for_auto_resize_ &&
1447 !plugin_window_moves_.size()) {
1448 return;
1451 ViewHostMsg_UpdateRect_Params params;
1452 params.view_size = size_;
1453 params.plugin_window_moves.swap(plugin_window_moves_);
1454 params.flags = next_paint_flags_;
1456 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1457 next_paint_flags_ = 0;
1458 need_update_rect_for_auto_resize_ = false;
1461 void RenderWidget::ScheduleComposite() {
1462 if (compositor_ &&
1463 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1464 compositor_->setNeedsAnimate();
1468 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
1469 if (compositor_) {
1470 // Regardless of whether threaded compositing is enabled, always
1471 // use this mechanism to force the compositor to redraw. However,
1472 // the invalidation code path below is still needed for the
1473 // non-threaded case.
1474 compositor_->SetNeedsForcedRedraw();
1476 ScheduleComposite();
1479 // static
1480 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1481 IPC::Message* msg,
1482 MessageDeliveryPolicy policy,
1483 FrameSwapMessageQueue* frame_swap_message_queue,
1484 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1485 int source_frame_number) {
1486 bool first_message_for_frame = false;
1487 frame_swap_message_queue->QueueMessageForFrame(policy,
1488 source_frame_number,
1489 make_scoped_ptr(msg),
1490 &first_message_for_frame);
1491 if (first_message_for_frame) {
1492 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1493 sync_message_filter, frame_swap_message_queue, source_frame_number));
1494 return promise;
1496 return nullptr;
1499 void RenderWidget::QueueMessage(IPC::Message* msg,
1500 MessageDeliveryPolicy policy) {
1501 // RenderThreadImpl::current() is NULL in some tests.
1502 if (!compositor_ || !RenderThreadImpl::current()) {
1503 Send(msg);
1504 return;
1507 scoped_ptr<cc::SwapPromise> swap_promise =
1508 QueueMessageImpl(msg,
1509 policy,
1510 frame_swap_message_queue_.get(),
1511 RenderThreadImpl::current()->sync_message_filter(),
1512 compositor_->GetSourceFrameNumber());
1514 if (swap_promise) {
1515 compositor_->QueueSwapPromise(swap_promise.Pass());
1516 // Request a commit. This might either A) request a commit ahead of time
1517 // or B) request a commit which is not needed because there are not
1518 // pending updates. If B) then the commit will be skipped and the swap
1519 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1520 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1521 // can_cancel_commit is not unset.
1522 compositor_->SetNeedsUpdateLayers();
1526 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1527 // TODO(darin): Eliminate this temporary.
1528 WebCursor cursor;
1529 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1530 // Only send a SetCursor message if we need to make a change.
1531 if (!current_cursor_.IsEqual(cursor)) {
1532 current_cursor_ = cursor;
1533 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1537 // We are supposed to get a single call to Show for a newly created RenderWidget
1538 // that was created via RenderWidget::CreateWebView. So, we wait until this
1539 // point to dispatch the ShowWidget message.
1541 // This method provides us with the information about how to display the newly
1542 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1544 void RenderWidget::show(WebNavigationPolicy) {
1545 DCHECK(!did_show_) << "received extraneous Show call";
1546 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1547 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1549 if (did_show_)
1550 return;
1552 did_show_ = true;
1553 // NOTE: initial_rect_ may still have its default values at this point, but
1554 // that's okay. It'll be ignored if as_popup is false, or the browser
1555 // process will impose a default position otherwise.
1556 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1557 SetPendingWindowRect(initial_rect_);
1560 void RenderWidget::didFocus() {
1563 void RenderWidget::didBlur() {
1566 void RenderWidget::DoDeferredClose() {
1567 WillCloseLayerTreeView();
1568 Send(new ViewHostMsg_Close(routing_id_));
1571 void RenderWidget::NotifyOnClose() {
1572 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose());
1575 void RenderWidget::closeWidgetSoon() {
1576 DCHECK(content::RenderThread::Get());
1577 if (is_swapped_out_) {
1578 // This widget is currently swapped out, and the active widget is in a
1579 // different process. Have the browser route the close request to the
1580 // active widget instead, so that the correct unload handlers are run.
1581 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1582 return;
1585 // If a page calls window.close() twice, we'll end up here twice, but that's
1586 // OK. It is safe to send multiple Close messages.
1588 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1589 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1590 // could be closed before the JS finishes executing. So instead, post a
1591 // message back to the message loop, which won't run until the JS is
1592 // complete, and then the Close message can be sent.
1593 base::ThreadTaskRunnerHandle::Get()->PostTask(
1594 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1597 void RenderWidget::QueueSyntheticGesture(
1598 scoped_ptr<SyntheticGestureParams> gesture_params,
1599 const SyntheticGestureCompletionCallback& callback) {
1600 DCHECK(!callback.is_null());
1602 pending_synthetic_gesture_callbacks_.push(callback);
1604 SyntheticGesturePacket gesture_packet;
1605 gesture_packet.set_gesture_params(gesture_params.Pass());
1607 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1610 void RenderWidget::Close() {
1611 screen_metrics_emulator_.reset();
1612 WillCloseLayerTreeView();
1613 compositor_.reset();
1614 if (webwidget_) {
1615 webwidget_->close();
1616 webwidget_ = NULL;
1620 WebRect RenderWidget::windowRect() {
1621 if (pending_window_rect_count_)
1622 return pending_window_rect_;
1624 return view_screen_rect_;
1627 void RenderWidget::setToolTipText(const blink::WebString& text,
1628 WebTextDirection hint) {
1629 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1632 void RenderWidget::setWindowRect(const WebRect& rect) {
1633 WebRect window_rect = rect;
1634 if (popup_origin_scale_for_emulation_) {
1635 float scale = popup_origin_scale_for_emulation_;
1636 window_rect.x = popup_screen_origin_for_emulation_.x() +
1637 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1638 window_rect.y = popup_screen_origin_for_emulation_.y() +
1639 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1642 if (!resizing_mode_selector_->is_synchronous_mode()) {
1643 if (did_show_) {
1644 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1645 SetPendingWindowRect(window_rect);
1646 } else {
1647 initial_rect_ = window_rect;
1649 } else {
1650 SetWindowRectSynchronously(window_rect);
1654 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1655 pending_window_rect_ = rect;
1656 pending_window_rect_count_++;
1659 WebRect RenderWidget::rootWindowRect() {
1660 if (pending_window_rect_count_) {
1661 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1662 // the RootWindowRect is probably going to return wrong results since the
1663 // browser may not have processed the Move yet. There isn't really anything
1664 // good to do in this case, and it shouldn't happen - since this size is
1665 // only really needed for windowToScreen, which is only used for Popups.
1666 return pending_window_rect_;
1669 return window_screen_rect_;
1672 WebRect RenderWidget::windowResizerRect() {
1673 return resizer_rect_;
1676 void RenderWidget::OnImeSetComposition(
1677 const base::string16& text,
1678 const std::vector<WebCompositionUnderline>& underlines,
1679 int selection_start, int selection_end) {
1680 if (!ShouldHandleImeEvent())
1681 return;
1682 ImeEventGuard guard(this);
1683 if (!webwidget_->setComposition(
1684 text, WebVector<WebCompositionUnderline>(underlines),
1685 selection_start, selection_end)) {
1686 // If we failed to set the composition text, then we need to let the browser
1687 // process to cancel the input method's ongoing composition session, to make
1688 // sure we are in a consistent state.
1689 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1691 UpdateCompositionInfo(true);
1694 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1695 const gfx::Range& replacement_range,
1696 bool keep_selection) {
1697 if (!ShouldHandleImeEvent())
1698 return;
1699 ImeEventGuard guard(this);
1700 handling_input_event_ = true;
1701 if (text.length())
1702 webwidget_->confirmComposition(text);
1703 else if (keep_selection)
1704 webwidget_->confirmComposition(WebWidget::KeepSelection);
1705 else
1706 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1707 handling_input_event_ = false;
1708 UpdateCompositionInfo(true);
1711 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1712 // During shutdown we can just ignore this message.
1713 if (!webwidget_)
1714 return;
1716 // Even if the browser provides an empty damage rect, it's still expecting to
1717 // receive a repaint ack so just damage the entire widget bounds.
1718 if (size_to_paint.IsEmpty()) {
1719 size_to_paint = size_;
1722 set_next_paint_is_repaint_ack();
1723 if (compositor_)
1724 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1727 void RenderWidget::OnSyntheticGestureCompleted() {
1728 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1730 pending_synthetic_gesture_callbacks_.front().Run();
1731 pending_synthetic_gesture_callbacks_.pop();
1734 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1735 if (!webwidget_)
1736 return;
1737 webwidget_->setTextDirection(direction);
1740 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1741 const gfx::Rect& window_screen_rect) {
1742 if (screen_metrics_emulator_) {
1743 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1744 view_screen_rect, window_screen_rect);
1745 } else {
1746 view_screen_rect_ = view_screen_rect;
1747 window_screen_rect_ = window_screen_rect;
1749 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1752 void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) {
1753 if (compositor_)
1754 compositor_->SetSurfaceIdNamespace(surface_id_namespace);
1757 void RenderWidget::showImeIfNeeded() {
1758 OnShowImeIfNeeded();
1761 void RenderWidget::OnShowImeIfNeeded() {
1762 #if defined(OS_ANDROID) || defined(USE_AURA)
1763 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1764 #endif
1766 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1767 // virtual keyboard.
1768 #if !defined(OS_ANDROID)
1769 FocusChangeComplete();
1770 #endif
1773 #if defined(OS_ANDROID)
1774 void RenderWidget::OnImeEventSentForAck(const blink::WebTextInputInfo& info) {
1775 text_input_info_history_.push_back(info);
1778 void RenderWidget::OnImeEventAck() {
1779 DCHECK_GE(text_input_info_history_.size(), 1u);
1780 text_input_info_history_.pop_front();
1782 #endif
1784 bool RenderWidget::ShouldHandleImeEvent() {
1785 #if defined(OS_ANDROID)
1786 if (!webwidget_)
1787 return false;
1789 // We cannot handle IME events if there is any chance that the event we are
1790 // receiving here from the browser is based on the state that is different
1791 // from our current one as indicated by |text_input_info_|.
1792 // The states the browser might be in are:
1793 // text_input_info_history_[0] - current state ack'd by browser
1794 // text_input_info_history_[1...N] - pending state changes
1795 for (size_t i = 0u; i < text_input_info_history_.size() - 1u; ++i) {
1796 if (text_input_info_history_[i] != text_input_info_)
1797 return false;
1799 return true;
1800 #else
1801 return !!webwidget_;
1802 #endif
1805 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1806 if (handling_event_type_ == WebInputEvent::MouseMove) {
1807 // If we pause multiple times during a single mouse move event, we should
1808 // only send ACK once.
1809 if (!ignore_ack_for_mouse_move_from_debugger_) {
1810 InputEventAck ack(handling_event_type_, INPUT_EVENT_ACK_STATE_CONSUMED);
1811 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1812 return true;
1815 return false;
1818 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1819 ignore_ack_for_mouse_move_from_debugger_ = true;
1822 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1823 if (device_scale_factor_ == device_scale_factor)
1824 return;
1826 device_scale_factor_ = device_scale_factor;
1827 ScheduleComposite();
1830 bool RenderWidget::SetDeviceColorProfile(
1831 const std::vector<char>& color_profile) {
1832 if (device_color_profile_ == color_profile)
1833 return false;
1835 device_color_profile_ = color_profile;
1836 return true;
1839 void RenderWidget::ResetDeviceColorProfileForTesting() {
1840 if (!device_color_profile_.empty())
1841 device_color_profile_.clear();
1842 device_color_profile_.push_back('0');
1845 void RenderWidget::OnOrientationChange() {
1848 gfx::Vector2d RenderWidget::GetScrollOffset() {
1849 // Bare RenderWidgets don't support scroll offset.
1850 return gfx::Vector2d();
1853 void RenderWidget::SetHidden(bool hidden) {
1854 if (is_hidden_ == hidden)
1855 return;
1857 // The status has changed. Tell the RenderThread about it and ensure
1858 // throttled acks are released in case frame production ceases.
1859 is_hidden_ = hidden;
1860 FlushPendingInputEventAck();
1862 if (is_hidden_)
1863 RenderThreadImpl::current()->WidgetHidden();
1864 else
1865 RenderThreadImpl::current()->WidgetRestored();
1868 void RenderWidget::DidToggleFullscreen() {
1869 if (!webwidget_)
1870 return;
1872 if (is_fullscreen_granted_) {
1873 webwidget_->didEnterFullScreen();
1874 } else {
1875 webwidget_->didExitFullScreen();
1879 bool RenderWidget::next_paint_is_resize_ack() const {
1880 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1883 void RenderWidget::set_next_paint_is_resize_ack() {
1884 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1887 void RenderWidget::set_next_paint_is_repaint_ack() {
1888 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1891 static bool IsDateTimeInput(ui::TextInputType type) {
1892 return type == ui::TEXT_INPUT_TYPE_DATE ||
1893 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1894 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1895 type == ui::TEXT_INPUT_TYPE_MONTH ||
1896 type == ui::TEXT_INPUT_TYPE_TIME ||
1897 type == ui::TEXT_INPUT_TYPE_WEEK;
1901 void RenderWidget::StartHandlingImeEvent() {
1902 DCHECK(!handling_ime_event_);
1903 handling_ime_event_ = true;
1906 void RenderWidget::FinishHandlingImeEvent() {
1907 DCHECK(handling_ime_event_);
1908 handling_ime_event_ = false;
1909 // While handling an ime event, text input state and selection bounds updates
1910 // are ignored. These must explicitly be updated once finished handling the
1911 // ime event.
1912 UpdateSelectionBounds();
1913 #if defined(OS_ANDROID)
1914 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1915 #endif
1918 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1919 ChangeSource change_source) {
1920 TRACE_EVENT0("renderer", "RenderWidget::UpdateTextInputState");
1921 if (handling_ime_event_)
1922 return;
1923 ui::TextInputType new_type = GetTextInputType();
1924 if (IsDateTimeInput(new_type))
1925 return; // Not considered as a text input field in WebKit/Chromium.
1927 blink::WebTextInputInfo new_info;
1928 if (webwidget_)
1929 new_info = webwidget_->textInputInfo();
1930 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1932 bool new_can_compose_inline = CanComposeInline();
1934 // Only sends text input params if they are changed or if the ime should be
1935 // shown.
1936 if (show_ime == SHOW_IME_IF_NEEDED ||
1937 (text_input_type_ != new_type ||
1938 text_input_mode_ != new_mode ||
1939 text_input_info_ != new_info ||
1940 can_compose_inline_ != new_can_compose_inline)
1941 #if defined(OS_ANDROID)
1942 || text_field_is_dirty_
1943 #endif
1945 ViewHostMsg_TextInputState_Params params;
1946 params.type = new_type;
1947 params.mode = new_mode;
1948 params.flags = new_info.flags;
1949 params.value = new_info.value.utf8();
1950 params.selection_start = new_info.selectionStart;
1951 params.selection_end = new_info.selectionEnd;
1952 params.composition_start = new_info.compositionStart;
1953 params.composition_end = new_info.compositionEnd;
1954 params.can_compose_inline = new_can_compose_inline;
1955 params.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1956 #if defined(USE_AURA)
1957 params.is_non_ime_change = true;
1958 #endif
1959 #if defined(OS_ANDROID)
1960 params.is_non_ime_change = (change_source == FROM_NON_IME) ||
1961 text_field_is_dirty_;
1962 if (params.is_non_ime_change)
1963 OnImeEventSentForAck(new_info);
1964 text_field_is_dirty_ = false;
1965 #endif
1966 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), params));
1968 text_input_info_ = new_info;
1969 text_input_type_ = new_type;
1970 text_input_mode_ = new_mode;
1971 can_compose_inline_ = new_can_compose_inline;
1972 text_input_flags_ = new_info.flags;
1976 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1977 WebRect focus_webrect;
1978 WebRect anchor_webrect;
1979 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1980 *focus = focus_webrect;
1981 *anchor = anchor_webrect;
1984 void RenderWidget::UpdateSelectionBounds() {
1985 TRACE_EVENT0("renderer", "RenderWidget::UpdateSelectionBounds");
1986 if (!webwidget_)
1987 return;
1988 if (handling_ime_event_)
1989 return;
1991 #if defined(USE_AURA)
1992 // TODO(mohsen): For now, always send explicit selection IPC notifications for
1993 // Aura beucause composited selection updates are not working for webview tags
1994 // which regresses IME inside webview. Remove this when composited selection
1995 // updates are fixed for webviews. See, http://crbug.com/510568.
1996 bool send_ipc = true;
1997 #else
1998 // With composited selection updates, the selection bounds will be reported
1999 // directly by the compositor, in which case explicit IPC selection
2000 // notifications should be suppressed.
2001 bool send_ipc =
2002 !blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled();
2003 #endif
2004 if (send_ipc) {
2005 ViewHostMsg_SelectionBounds_Params params;
2006 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2007 if (selection_anchor_rect_ != params.anchor_rect ||
2008 selection_focus_rect_ != params.focus_rect) {
2009 selection_anchor_rect_ = params.anchor_rect;
2010 selection_focus_rect_ = params.focus_rect;
2011 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2012 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2013 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2017 UpdateCompositionInfo(false);
2020 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2021 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2022 static_assert(int(blink::WebTextInputType##a) \
2023 == int(ui::TEXT_INPUT_TYPE_##b), \
2024 "mismatching enums: " #a)
2026 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2027 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2028 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2029 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2030 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2031 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2032 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2033 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2034 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2035 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2036 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2037 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2038 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2039 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2040 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2041 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2042 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2044 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2045 blink::WebTextInputType type) {
2046 // Check the type is in the range representable by ui::TextInputType.
2047 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2048 "blink::WebTextInputType and ui::TextInputType not synchronized";
2049 return static_cast<ui::TextInputType>(type);
2052 ui::TextInputType RenderWidget::GetTextInputType() {
2053 if (webwidget_)
2054 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2055 return ui::TEXT_INPUT_TYPE_NONE;
2058 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2059 #if defined(OS_ANDROID)
2060 // TODO(yukawa): Start sending character bounds when the browser side
2061 // implementation becomes ready (crbug.com/424866).
2062 #else
2063 TRACE_EVENT0("renderer", "RenderWidget::UpdateCompositionInfo");
2064 gfx::Range range = gfx::Range();
2065 if (should_update_range) {
2066 GetCompositionRange(&range);
2067 } else {
2068 range = composition_range_;
2070 std::vector<gfx::Rect> character_bounds;
2071 GetCompositionCharacterBounds(&character_bounds);
2073 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2074 return;
2075 composition_character_bounds_ = character_bounds;
2076 composition_range_ = range;
2077 Send(new InputHostMsg_ImeCompositionRangeChanged(
2078 routing_id(), composition_range_, composition_character_bounds_));
2079 #endif
2082 void RenderWidget::GetCompositionCharacterBounds(
2083 std::vector<gfx::Rect>* bounds) {
2084 DCHECK(bounds);
2085 bounds->clear();
2088 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2089 size_t location, length;
2090 if (webwidget_->compositionRange(&location, &length)) {
2091 range->set_start(location);
2092 range->set_end(location + length);
2093 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2094 range->set_start(location);
2095 range->set_end(location + length);
2096 } else {
2097 *range = gfx::Range::InvalidRange();
2101 bool RenderWidget::ShouldUpdateCompositionInfo(
2102 const gfx::Range& range,
2103 const std::vector<gfx::Rect>& bounds) {
2104 if (composition_range_ != range)
2105 return true;
2106 if (bounds.size() != composition_character_bounds_.size())
2107 return true;
2108 for (size_t i = 0; i < bounds.size(); ++i) {
2109 if (bounds[i] != composition_character_bounds_[i])
2110 return true;
2112 return false;
2115 #if defined(OS_ANDROID)
2116 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2117 // If not initialized, default to white. Note that 0 is different from black
2118 // as black still has alpha 0xFF.
2119 if (!bg_color)
2120 bg_color = SK_ColorWHITE;
2122 if (bg_color != body_background_color_) {
2123 body_background_color_ = bg_color;
2124 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2128 bool RenderWidget::DoesRecordFullLayer() const {
2129 SynchronousCompositorFactory* synchronous_compositor_factory =
2130 SynchronousCompositorFactory::GetInstance();
2132 // We assume that the absence of synchronous_compositor_factory
2133 // means we are in Chrome. In chrome, we want to clip, i.e.
2134 // *not* to record the full layer.
2135 if (!synchronous_compositor_factory)
2136 return false;
2138 return synchronous_compositor_factory->RecordFullLayer();
2140 #endif
2142 bool RenderWidget::CanComposeInline() {
2143 return true;
2146 WebScreenInfo RenderWidget::screenInfo() {
2147 return screen_info_;
2150 float RenderWidget::deviceScaleFactor() {
2151 return device_scale_factor_;
2154 void RenderWidget::resetInputMethod() {
2155 ImeEventGuard guard(this);
2156 // If the last text input type is not None, then we should finish any
2157 // ongoing composition regardless of the new text input type.
2158 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2159 // If a composition text exists, then we need to let the browser process
2160 // to cancel the input method's ongoing composition session.
2161 if (webwidget_->confirmComposition())
2162 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2165 UpdateCompositionInfo(true);
2168 #if defined(OS_ANDROID)
2169 void RenderWidget::showUnhandledTapUIIfNeeded(
2170 const WebPoint& tapped_position,
2171 const WebNode& tapped_node,
2172 bool page_changed) {
2173 DCHECK(handling_input_event_);
2174 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2175 !tapped_node.isContentEditable() &&
2176 !tapped_node.isInsideFocusableElementOrARIAWidget();
2177 if (should_trigger) {
2178 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2179 tapped_position.x, tapped_position.y));
2182 #endif
2184 void RenderWidget::didHandleGestureEvent(
2185 const WebGestureEvent& event,
2186 bool event_cancelled) {
2187 #if defined(OS_ANDROID) || defined(USE_AURA)
2188 if (event_cancelled)
2189 return;
2190 if (event.type == WebInputEvent::GestureTap) {
2191 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2192 } else if (event.type == WebInputEvent::GestureLongPress) {
2193 DCHECK(webwidget_);
2194 if (webwidget_->textInputInfo().value.isEmpty())
2195 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2196 else
2197 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2199 #endif
2202 void RenderWidget::didOverscroll(
2203 const blink::WebFloatSize& unusedDelta,
2204 const blink::WebFloatSize& accumulatedRootOverScroll,
2205 const blink::WebFloatPoint& position,
2206 const blink::WebFloatSize& velocity) {
2207 DidOverscrollParams params;
2208 params.accumulated_overscroll = gfx::Vector2dF(
2209 accumulatedRootOverScroll.width, accumulatedRootOverScroll.height);
2210 params.latest_overscroll_delta =
2211 gfx::Vector2dF(unusedDelta.width, unusedDelta.height);
2212 // TODO(sataya.m): don't negate velocity once http://crbug.com/499743 is
2213 // fixed.
2214 params.current_fling_velocity =
2215 gfx::Vector2dF(-velocity.width, -velocity.height);
2216 params.causal_event_viewport_point = gfx::PointF(position.x, position.y);
2218 // If we're currently handling an event, stash the overscroll data such that
2219 // it can be bundled in the event ack.
2220 if (handling_event_overscroll_) {
2221 handling_event_overscroll_->reset(new DidOverscrollParams(params));
2222 return;
2225 Send(new InputHostMsg_DidOverscroll(routing_id_, params));
2228 void RenderWidget::StartCompositor() {
2229 // For widgets that are never visible, we don't need the compositor to run
2230 // at all.
2231 if (never_visible_)
2232 return;
2233 // In tests without a RenderThreadImpl, don't set ready as this kicks
2234 // off creating output surfaces that the test can't create.
2235 if (!RenderThreadImpl::current())
2236 return;
2237 compositor_->StartCompositor();
2240 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2241 size_t i = 0;
2242 for (; i < plugin_window_moves_.size(); ++i) {
2243 if (plugin_window_moves_[i].window == move.window) {
2244 if (move.rects_valid) {
2245 plugin_window_moves_[i] = move;
2246 } else {
2247 plugin_window_moves_[i].visible = move.visible;
2249 break;
2253 if (i == plugin_window_moves_.size())
2254 plugin_window_moves_.push_back(move);
2257 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2258 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2259 i != plugin_window_moves_.end(); ++i) {
2260 if (i->window == window) {
2261 plugin_window_moves_.erase(i);
2262 break;
2268 RenderWidgetCompositor* RenderWidget::compositor() const {
2269 return compositor_.get();
2272 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2273 return false;
2276 bool RenderWidget::WillHandleGestureEvent(
2277 const blink::WebGestureEvent& event) {
2278 return false;
2281 void RenderWidget::ObserveWheelEventAndResult(
2282 const blink::WebMouseWheelEvent& wheel_event,
2283 const gfx::Vector2dF& wheel_unused_delta,
2284 bool event_processed) {
2285 if (!compositor_deps_->IsElasticOverscrollEnabled())
2286 return;
2288 cc::InputHandlerScrollResult scroll_result;
2289 scroll_result.did_scroll = event_processed;
2290 scroll_result.did_overscroll_root = !wheel_unused_delta.IsZero();
2291 scroll_result.unused_scroll_delta = wheel_unused_delta;
2293 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2294 InputHandlerManager* input_handler_manager =
2295 render_thread ? render_thread->input_handler_manager() : NULL;
2296 if (input_handler_manager) {
2297 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2298 routing_id_, wheel_event, scroll_result);
2302 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2303 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2306 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2307 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2308 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2309 "mismatching enums: " #a)
2311 inline content::TouchAction& operator|=(content::TouchAction& a,
2312 content::TouchAction b) {
2313 a = static_cast<content::TouchAction>(static_cast<int>(a) |
2314 static_cast<int>(b));
2315 return a;
2318 void RenderWidget::setTouchAction(
2319 blink::WebTouchAction web_touch_action) {
2321 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2322 // when blink is emulating touch with mouse).
2323 if (handling_event_type_ != WebInputEvent::TouchStart)
2324 return;
2326 // Verify the same values are used by the types so we can cast between them.
2327 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2328 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2329 STATIC_ASSERT_WTI_ENUM_MATCH(PanLeft, PAN_LEFT);
2330 STATIC_ASSERT_WTI_ENUM_MATCH(PanRight, PAN_RIGHT);
2331 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2332 STATIC_ASSERT_WTI_ENUM_MATCH(PanUp, PAN_UP);
2333 STATIC_ASSERT_WTI_ENUM_MATCH(PanDown, PAN_DOWN);
2334 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2335 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2337 content::TouchAction content_touch_action =
2338 static_cast<content::TouchAction>(web_touch_action);
2339 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2342 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2343 #if defined(OS_ANDROID)
2344 text_field_is_dirty_ = true;
2345 #endif
2348 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2349 return true;
2352 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2353 RenderWidget::CreateGraphicsContext3D(bool compositor) {
2354 if (!webwidget_)
2355 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2356 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2357 switches::kDisableGpuCompositing))
2358 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2359 if (!RenderThreadImpl::current())
2360 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2361 CauseForGpuLaunch cause =
2362 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2363 scoped_refptr<GpuChannelHost> gpu_channel_host(
2364 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2365 if (!gpu_channel_host.get())
2366 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2368 // Explicitly disable antialiasing for the compositor. As of the time of
2369 // this writing, the only platform that supported antialiasing for the
2370 // compositor was Mac OS X, because the on-screen OpenGL context creation
2371 // code paths on Windows and Linux didn't yet have multisampling support.
2372 // Mac OS X essentially always behaves as though it's rendering offscreen.
2373 // Multisampling has a heavy cost especially on devices with relatively low
2374 // fill rate like most notebooks, and the Mac implementation would need to
2375 // be optimized to resolve directly into the IOSurface shared between the
2376 // GPU and browser processes. For these reasons and to avoid platform
2377 // disparities we explicitly disable antialiasing.
2378 blink::WebGraphicsContext3D::Attributes attributes;
2379 attributes.antialias = false;
2380 attributes.shareResources = true;
2381 attributes.noAutomaticFlushes = true;
2382 attributes.depth = false;
2383 attributes.stencil = false;
2384 bool lose_context_when_out_of_memory = true;
2385 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2386 #if defined(OS_ANDROID)
2387 // If we raster too fast we become upload bound, and pending
2388 // uploads consume memory. For maximum upload throughput, we would
2389 // want to allow for upload_throughput * pipeline_time of pending
2390 // uploads, after which we are just wasting memory. Since we don't
2391 // know our upload throughput yet, this just caps our memory usage.
2392 size_t divider = 1;
2393 if (base::SysInfo::IsLowEndDevice())
2394 divider = 6;
2395 // For reference Nexus10 can upload 1MB in about 2.5ms.
2396 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2397 // Deadline to draw a frame to achieve 60 frames per second.
2398 const size_t kMillisecondsPerFrame = 16;
2399 // Assuming a two frame deep pipeline between the CPU and the GPU.
2400 size_t max_transfer_buffer_usage_mb =
2401 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2402 static const size_t kBytesPerMegabyte = 1024 * 1024;
2403 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2404 // to avoid unnecessarily stalling the compositor thread.
2405 limits.mapped_memory_reclaim_limit =
2406 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2407 #endif
2408 if (compositor) {
2409 limits.command_buffer_size = 64 * 1024;
2410 limits.start_transfer_buffer_size = 64 * 1024;
2411 limits.min_transfer_buffer_size = 64 * 1024;
2414 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2415 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2416 GetURLForGraphicsContext3D(),
2417 gpu_channel_host.get(),
2418 attributes,
2419 lose_context_when_out_of_memory,
2420 limits,
2421 NULL));
2422 return context.Pass();
2425 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2426 render_frame_proxies_.AddObserver(proxy);
2429 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2430 render_frame_proxies_.RemoveObserver(proxy);
2433 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2434 render_frames_.AddObserver(frame);
2437 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2438 render_frames_.RemoveObserver(frame);
2441 #if defined(VIDEO_HOLE)
2442 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2443 video_hole_frames_.AddObserver(frame);
2446 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2447 video_hole_frames_.RemoveObserver(frame);
2449 #endif // defined(VIDEO_HOLE)
2451 } // namespace content