Roll src/third_party/WebKit d10c917:a1123a1 (svn 198729:198730)
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blobd0a6ca3df3f0ba043ec98ea153ae6b26af675688
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(const WebInputEvent& event, base::TimeTicks now) {
165 return (now - base::TimeDelta::FromSecondsD(event.timeStampSeconds))
166 .ToInternalValue();
169 void LogInputEventLatencyUma(const WebInputEvent& event, base::TimeTicks now) {
170 UMA_HISTOGRAM_CUSTOM_COUNTS(
171 "Event.AggregatedLatency.Renderer2",
172 GetEventLatencyMicros(event, now),
174 10000000,
175 100);
177 #define CASE_TYPE(t) \
178 case WebInputEvent::t: \
179 UMA_HISTOGRAM_CUSTOM_COUNTS( \
180 "Event.Latency.Renderer2." #t, \
181 GetEventLatencyMicros(event, now), \
182 1, \
183 10000000, \
184 100); \
185 break;
187 switch(event.type) {
188 CASE_TYPE(Undefined);
189 CASE_TYPE(MouseDown);
190 CASE_TYPE(MouseUp);
191 CASE_TYPE(MouseMove);
192 CASE_TYPE(MouseEnter);
193 CASE_TYPE(MouseLeave);
194 CASE_TYPE(ContextMenu);
195 CASE_TYPE(MouseWheel);
196 CASE_TYPE(RawKeyDown);
197 CASE_TYPE(KeyDown);
198 CASE_TYPE(KeyUp);
199 CASE_TYPE(Char);
200 CASE_TYPE(GestureScrollBegin);
201 CASE_TYPE(GestureScrollEnd);
202 CASE_TYPE(GestureScrollUpdate);
203 CASE_TYPE(GestureFlingStart);
204 CASE_TYPE(GestureFlingCancel);
205 CASE_TYPE(GestureShowPress);
206 CASE_TYPE(GestureTap);
207 CASE_TYPE(GestureTapUnconfirmed);
208 CASE_TYPE(GestureTapDown);
209 CASE_TYPE(GestureTapCancel);
210 CASE_TYPE(GestureDoubleTap);
211 CASE_TYPE(GestureTwoFingerTap);
212 CASE_TYPE(GestureLongPress);
213 CASE_TYPE(GestureLongTap);
214 CASE_TYPE(GesturePinchBegin);
215 CASE_TYPE(GesturePinchEnd);
216 CASE_TYPE(GesturePinchUpdate);
217 CASE_TYPE(TouchStart);
218 CASE_TYPE(TouchMove);
219 CASE_TYPE(TouchEnd);
220 CASE_TYPE(TouchCancel);
221 default:
222 // Must include default to let blink::WebInputEvent add new event types
223 // before they're added here.
224 DLOG(WARNING) << "Unhandled WebInputEvent type: " << event.type;
225 break;
228 #undef CASE_TYPE
231 } // namespace
233 namespace content {
235 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
237 class RenderWidget::ScreenMetricsEmulator {
238 public:
239 ScreenMetricsEmulator(
240 RenderWidget* widget,
241 const WebDeviceEmulationParams& params);
242 virtual ~ScreenMetricsEmulator();
244 // Scale and offset used to convert between host coordinates
245 // and webwidget coordinates.
246 float scale() { return scale_; }
247 gfx::PointF offset() { return offset_; }
248 gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
249 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
250 const WebScreenInfo& original_screen_info() { return original_screen_info_; }
252 void ChangeEmulationParams(
253 const WebDeviceEmulationParams& params);
255 // The following methods alter handlers' behavior for messages related to
256 // widget size and position.
257 void OnResizeMessage(const ViewMsg_Resize_Params& params);
258 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
259 const gfx::Rect& window_screen_rect);
260 void OnShowContextMenu(ContextMenuParams* params);
261 gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
263 private:
264 void Reapply();
265 void Apply(bool top_controls_shrink_blink_size,
266 float top_controls_height,
267 gfx::Rect resizer_rect,
268 bool is_fullscreen_granted,
269 blink::WebDisplayMode display_mode);
271 RenderWidget* widget_;
273 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
274 WebDeviceEmulationParams params_;
276 // The computed scale and offset used to fit widget into browser window.
277 float scale_;
278 gfx::PointF offset_;
280 // Widget rect as passed to webwidget.
281 gfx::Rect applied_widget_rect_;
283 // Original values to restore back after emulation ends.
284 gfx::Size original_size_;
285 gfx::Size original_physical_backing_size_;
286 gfx::Size original_visible_viewport_size_;
287 blink::WebScreenInfo original_screen_info_;
288 gfx::Rect original_view_screen_rect_;
289 gfx::Rect original_window_screen_rect_;
292 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
293 RenderWidget* widget,
294 const WebDeviceEmulationParams& params)
295 : widget_(widget),
296 params_(params),
297 scale_(1.f) {
298 original_size_ = widget_->size_;
299 original_physical_backing_size_ = widget_->physical_backing_size_;
300 original_visible_viewport_size_ = widget_->visible_viewport_size_;
301 original_screen_info_ = widget_->screen_info_;
302 original_view_screen_rect_ = widget_->view_screen_rect_;
303 original_window_screen_rect_ = widget_->window_screen_rect_;
304 Apply(widget_->top_controls_shrink_blink_size_,
305 widget_->top_controls_height_,
306 widget_->resizer_rect_,
307 widget_->is_fullscreen_granted_,
308 widget_->display_mode_);
311 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
312 widget_->screen_info_ = original_screen_info_;
314 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
315 widget_->SetScreenMetricsEmulationParameters(false, params_);
316 widget_->view_screen_rect_ = original_view_screen_rect_;
317 widget_->window_screen_rect_ = original_window_screen_rect_;
318 widget_->Resize(original_size_,
319 original_physical_backing_size_,
320 widget_->top_controls_shrink_blink_size_,
321 widget_->top_controls_height_,
322 original_visible_viewport_size_,
323 widget_->resizer_rect_,
324 widget_->is_fullscreen_granted_,
325 widget_->display_mode_,
326 NO_RESIZE_ACK);
329 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
330 const WebDeviceEmulationParams& params) {
331 params_ = params;
332 Reapply();
335 void RenderWidget::ScreenMetricsEmulator::Reapply() {
336 Apply(widget_->top_controls_shrink_blink_size_,
337 widget_->top_controls_height_,
338 widget_->resizer_rect_,
339 widget_->is_fullscreen_granted_,
340 widget_->display_mode_);
343 void RenderWidget::ScreenMetricsEmulator::Apply(
344 bool top_controls_shrink_blink_size,
345 float top_controls_height,
346 gfx::Rect resizer_rect,
347 bool is_fullscreen_granted,
348 blink::WebDisplayMode display_mode) {
349 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
350 if (!applied_widget_rect_.width())
351 applied_widget_rect_.set_width(original_size_.width());
352 if (!applied_widget_rect_.height())
353 applied_widget_rect_.set_height(original_size_.height());
355 if (params_.fitToView && !original_size_.IsEmpty()) {
356 int original_width = std::max(original_size_.width(), 1);
357 int original_height = std::max(original_size_.height(), 1);
358 float width_ratio =
359 static_cast<float>(applied_widget_rect_.width()) / original_width;
360 float height_ratio =
361 static_cast<float>(applied_widget_rect_.height()) / original_height;
362 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
363 scale_ = 1.f / ratio;
365 // Center emulated view inside available view space.
366 offset_.set_x(
367 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
368 offset_.set_y(
369 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
370 } else {
371 scale_ = params_.scale;
372 offset_.SetPoint(params_.offset.x, params_.offset.y);
375 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
376 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
377 widget_->screen_info_.rect = original_screen_info_.rect;
378 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
379 widget_->window_screen_rect_ = original_window_screen_rect_;
380 } else {
381 applied_widget_rect_.set_origin(params_.viewPosition);
382 gfx::Rect screen_rect = applied_widget_rect_;
383 if (!params_.screenSize.isEmpty()) {
384 screen_rect =
385 gfx::Rect(0, 0, params_.screenSize.width, params_.screenSize.height);
387 widget_->screen_info_.rect = screen_rect;
388 widget_->screen_info_.availableRect = screen_rect;
389 widget_->window_screen_rect_ = applied_widget_rect_;
392 float applied_device_scale_factor = params_.deviceScaleFactor ?
393 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
394 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
396 // Pass three emulation parameters to the blink side:
397 // - we keep the real device scale factor in compositor to produce sharp image
398 // even when emulating different scale factor;
399 // - in order to fit into view, WebView applies offset and scale to the
400 // root layer.
401 blink::WebDeviceEmulationParams modified_params = params_;
402 modified_params.deviceScaleFactor = original_screen_info_.deviceScaleFactor;
403 modified_params.offset = blink::WebFloatPoint(offset_.x(), offset_.y());
404 modified_params.scale = scale_;
405 widget_->SetScreenMetricsEmulationParameters(true, modified_params);
407 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
408 widget_->view_screen_rect_ = applied_widget_rect_;
410 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
411 original_size_, original_screen_info_.deviceScaleFactor));
412 widget_->Resize(applied_widget_rect_.size(),
413 physical_backing_size,
414 top_controls_shrink_blink_size,
415 top_controls_height,
416 applied_widget_rect_.size(),
417 resizer_rect,
418 is_fullscreen_granted,
419 display_mode,
420 NO_RESIZE_ACK);
423 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
424 const ViewMsg_Resize_Params& params) {
425 bool need_ack = params.new_size != original_size_ &&
426 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
427 original_size_ = params.new_size;
428 original_physical_backing_size_ = params.physical_backing_size;
429 original_screen_info_ = params.screen_info;
430 original_visible_viewport_size_ = params.visible_viewport_size;
431 Apply(params.top_controls_shrink_blink_size,
432 params.top_controls_height,
433 params.resizer_rect,
434 params.is_fullscreen_granted,
435 params.display_mode);
437 if (need_ack) {
438 widget_->set_next_paint_is_resize_ack();
439 if (widget_->compositor_)
440 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
444 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
445 const gfx::Rect& view_screen_rect,
446 const gfx::Rect& window_screen_rect) {
447 original_view_screen_rect_ = view_screen_rect;
448 original_window_screen_rect_ = window_screen_rect;
449 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
450 Reapply();
453 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
454 ContextMenuParams* params) {
455 params->x *= scale_;
456 params->x += offset_.x();
457 params->y *= scale_;
458 params->y += offset_.y();
461 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
462 const gfx::Rect& anchor) {
463 gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
464 scaled.set_x(scaled.x() + offset_.x());
465 scaled.set_y(scaled.y() + offset_.y());
466 return scaled;
469 // RenderWidget ---------------------------------------------------------------
471 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
472 const blink::WebScreenInfo& screen_info,
473 bool swapped_out,
474 bool hidden,
475 bool never_visible)
476 : routing_id_(MSG_ROUTING_NONE),
477 surface_id_(0),
478 compositor_deps_(nullptr),
479 webwidget_(nullptr),
480 opener_id_(MSG_ROUTING_NONE),
481 init_complete_(false),
482 top_controls_shrink_blink_size_(false),
483 top_controls_height_(0.f),
484 next_paint_flags_(0),
485 auto_resize_mode_(false),
486 need_update_rect_for_auto_resize_(false),
487 did_show_(false),
488 is_hidden_(hidden),
489 never_visible_(never_visible),
490 is_fullscreen_granted_(false),
491 display_mode_(blink::WebDisplayModeUndefined),
492 has_focus_(false),
493 handling_input_event_(false),
494 handling_event_overscroll_(nullptr),
495 handling_ime_event_(false),
496 handling_event_type_(WebInputEvent::Undefined),
497 ignore_ack_for_mouse_move_from_debugger_(false),
498 closing_(false),
499 host_closing_(false),
500 is_swapped_out_(swapped_out),
501 for_oopif_(false),
502 input_method_is_active_(false),
503 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
504 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
505 text_input_flags_(0),
506 can_compose_inline_(true),
507 popup_type_(popup_type),
508 pending_window_rect_count_(0),
509 suppress_next_char_events_(false),
510 screen_info_(screen_info),
511 device_scale_factor_(screen_info_.deviceScaleFactor),
512 current_event_latency_info_(NULL),
513 next_output_surface_id_(0),
514 #if defined(OS_ANDROID)
515 text_field_is_dirty_(false),
516 outstanding_ime_acks_(0),
517 body_background_color_(SK_ColorWHITE),
518 #endif
519 popup_origin_scale_for_emulation_(0.f),
520 frame_swap_message_queue_(new FrameSwapMessageQueue()),
521 resizing_mode_selector_(new ResizingModeSelector()),
522 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
523 has_host_context_menu_location_(false) {
524 if (!swapped_out)
525 RenderProcess::current()->AddRefProcess();
526 DCHECK(RenderThread::Get());
527 device_color_profile_.push_back('0');
530 RenderWidget::~RenderWidget() {
531 DCHECK(!webwidget_) << "Leaking our WebWidget!";
533 // If we are swapped out, we have released already.
534 if (!is_swapped_out_ && RenderProcess::current())
535 RenderProcess::current()->ReleaseProcess();
538 // static
539 RenderWidget* RenderWidget::Create(int32 opener_id,
540 CompositorDependencies* compositor_deps,
541 blink::WebPopupType popup_type,
542 const blink::WebScreenInfo& screen_info) {
543 DCHECK(opener_id != MSG_ROUTING_NONE);
544 scoped_refptr<RenderWidget> widget(
545 new RenderWidget(popup_type, screen_info, false, false, false));
546 if (widget->Init(opener_id, compositor_deps)) { // adds reference on success.
547 return widget.get();
549 return NULL;
552 // static
553 RenderWidget* RenderWidget::CreateForFrame(
554 int routing_id,
555 int surface_id,
556 bool hidden,
557 const blink::WebScreenInfo& screen_info,
558 CompositorDependencies* compositor_deps,
559 blink::WebLocalFrame* frame) {
560 CHECK_NE(routing_id, MSG_ROUTING_NONE);
561 scoped_refptr<RenderWidget> widget(new RenderWidget(
562 blink::WebPopupTypeNone, screen_info, false, hidden, false));
563 widget->routing_id_ = routing_id;
564 widget->surface_id_ = surface_id;
565 widget->compositor_deps_ = compositor_deps;
566 widget->for_oopif_ = true;
567 // DoInit increments the reference count on |widget|, keeping it alive after
568 // this function returns.
569 if (widget->DoInit(MSG_ROUTING_NONE, compositor_deps,
570 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
571 nullptr)) {
572 widget->CompleteInit();
573 return widget.get();
575 return nullptr;
578 // static
579 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
580 switch (render_widget->popup_type_) {
581 case blink::WebPopupTypeNone: // Nothing to create.
582 break;
583 case blink::WebPopupTypePage:
584 return WebPagePopup::create(render_widget);
585 default:
586 NOTREACHED();
588 return NULL;
591 // static
592 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
593 RenderWidget* render_widget,
594 blink::WebLocalFrame* frame) {
595 return blink::WebFrameWidget::create(render_widget, frame);
598 bool RenderWidget::Init(int32 opener_id,
599 CompositorDependencies* compositor_deps) {
600 return DoInit(opener_id, compositor_deps, RenderWidget::CreateWebWidget(this),
601 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
602 &routing_id_, &surface_id_));
605 bool RenderWidget::DoInit(int32 opener_id,
606 CompositorDependencies* compositor_deps,
607 WebWidget* web_widget,
608 IPC::SyncMessage* create_widget_message) {
609 DCHECK(!webwidget_);
611 if (opener_id != MSG_ROUTING_NONE)
612 opener_id_ = opener_id;
614 compositor_deps_ = compositor_deps;
615 webwidget_ = web_widget;
617 bool result = true;
618 if (create_widget_message)
619 result = RenderThread::Get()->Send(create_widget_message);
621 if (result) {
622 RenderThread::Get()->AddRoute(routing_id_, this);
623 // Take a reference on behalf of the RenderThread. This will be balanced
624 // when we receive ViewMsg_Close.
625 AddRef();
626 if (RenderThreadImpl::current()) {
627 RenderThreadImpl::current()->WidgetCreated();
628 if (is_hidden_)
629 RenderThreadImpl::current()->WidgetHidden();
631 return true;
632 } else {
633 // The above Send can fail when the tab is closing.
634 return false;
638 // This is used to complete pending inits and non-pending inits.
639 void RenderWidget::CompleteInit() {
640 DCHECK(routing_id_ != MSG_ROUTING_NONE);
642 init_complete_ = true;
644 if (compositor_)
645 StartCompositor();
647 Send(new ViewHostMsg_RenderViewReady(routing_id_));
650 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
651 // We should only toggle between states.
652 DCHECK(is_swapped_out_ != is_swapped_out);
653 is_swapped_out_ = is_swapped_out;
655 // If we are swapping out, we will call ReleaseProcess, allowing the process
656 // to exit if all of its RenderViews are swapped out. We wait until the
657 // WasSwappedOut call to do this, to allow the unload handler to finish.
658 // If we are swapping in, we call AddRefProcess to prevent the process from
659 // exiting.
660 if (!is_swapped_out_)
661 RenderProcess::current()->AddRefProcess();
664 void RenderWidget::WasSwappedOut() {
665 // If we have been swapped out and no one else is using this process,
666 // it's safe to exit now.
667 CHECK(is_swapped_out_);
668 RenderProcess::current()->ReleaseProcess();
671 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
672 ScreenMetricsEmulator* emulator) {
673 popup_origin_scale_for_emulation_ = emulator->scale();
674 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
675 popup_screen_origin_for_emulation_ = gfx::Point(
676 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
677 emulator->original_screen_rect().origin().y() + emulator->offset().y());
678 screen_info_ = emulator->original_screen_info();
679 device_scale_factor_ = screen_info_.deviceScaleFactor;
682 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
683 if (screen_metrics_emulator_)
684 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
685 return anchor;
688 void RenderWidget::SetScreenMetricsEmulationParameters(
689 bool enabled,
690 const blink::WebDeviceEmulationParams& params) {
691 // This is only supported in RenderView.
692 NOTREACHED();
695 #if defined(OS_MACOSX) || defined(OS_ANDROID)
696 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
697 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
698 popup->SetOriginScaleAndOffsetForEmulation(
699 emulator->scale(), emulator->offset());
701 #endif
703 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
704 if (screen_metrics_emulator_)
705 screen_metrics_emulator_->OnShowContextMenu(params);
708 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
709 bool handled = true;
710 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
711 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
712 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
713 OnCursorVisibilityChange)
714 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
715 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
716 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
717 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
718 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
719 OnSyntheticGestureCompleted)
720 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
721 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
722 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
723 IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation,
724 OnEnableDeviceEmulation)
725 IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation,
726 OnDisableDeviceEmulation)
727 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
728 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
729 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
730 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
731 IPC_MESSAGE_HANDLER(ViewMsg_SetInputMethodActive, OnSetInputMethodActive)
732 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
733 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
734 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
735 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
736 IPC_MESSAGE_HANDLER(ViewMsg_SetSurfaceIdNamespace, OnSetSurfaceIdNamespace)
737 #if defined(OS_ANDROID)
738 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
739 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
740 #endif
741 IPC_MESSAGE_UNHANDLED(handled = false)
742 IPC_END_MESSAGE_MAP()
743 return handled;
746 bool RenderWidget::Send(IPC::Message* message) {
747 // Don't send any messages after the browser has told us to close, and filter
748 // most outgoing messages while swapped out.
749 if ((is_swapped_out_ &&
750 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
751 closing_) {
752 delete message;
753 return false;
756 // If given a messsage without a routing ID, then assign our routing ID.
757 if (message->routing_id() == MSG_ROUTING_NONE)
758 message->set_routing_id(routing_id_);
760 return RenderThread::Get()->Send(message);
763 void RenderWidget::Resize(const gfx::Size& new_size,
764 const gfx::Size& physical_backing_size,
765 bool top_controls_shrink_blink_size,
766 float top_controls_height,
767 const gfx::Size& visible_viewport_size,
768 const gfx::Rect& resizer_rect,
769 bool is_fullscreen_granted,
770 blink::WebDisplayMode display_mode,
771 const ResizeAck resize_ack) {
772 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
773 // A resize ack shouldn't be requested if we have not ACK'd the previous
774 // one.
775 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
776 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
779 // Ignore this during shutdown.
780 if (!webwidget_)
781 return;
783 if (compositor_) {
784 compositor_->setViewportSize(new_size, physical_backing_size);
787 physical_backing_size_ = physical_backing_size;
788 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
789 top_controls_height_ = top_controls_height;
790 visible_viewport_size_ = visible_viewport_size;
791 resizer_rect_ = resizer_rect;
793 // NOTE: We may have entered fullscreen mode without changing our size.
794 bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted;
795 if (fullscreen_change)
796 WillToggleFullscreen();
797 is_fullscreen_granted_ = is_fullscreen_granted;
798 display_mode_ = display_mode;
800 webwidget_->setTopControlsHeight(top_controls_height,
801 top_controls_shrink_blink_size_);
803 if (size_ != new_size) {
804 size_ = new_size;
806 // When resizing, we want to wait to paint before ACK'ing the resize. This
807 // ensures that we only resize as fast as we can paint. We only need to
808 // send an ACK if we are resized to a non-empty rect.
809 webwidget_->resize(new_size);
812 webwidget()->resizePinchViewport(gfx::Size(
813 visible_viewport_size.width(),
814 visible_viewport_size.height()));
816 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
817 // In this case there is no paint/composite and therefore no
818 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
819 // ack through a fake ViewHostMsg_UpdateRect or a different message.
820 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
823 // Send the Resize_ACK flag once we paint again if requested.
824 if (resize_ack == SEND_RESIZE_ACK)
825 set_next_paint_is_resize_ack();
827 if (fullscreen_change)
828 DidToggleFullscreen();
830 // If a resize ack is requested and it isn't set-up, then no more resizes will
831 // come in and in general things will go wrong.
832 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
835 void RenderWidget::SetWindowRectSynchronously(
836 const gfx::Rect& new_window_rect) {
837 Resize(new_window_rect.size(),
838 new_window_rect.size(),
839 top_controls_shrink_blink_size_,
840 top_controls_height_,
841 new_window_rect.size(),
842 gfx::Rect(),
843 is_fullscreen_granted_,
844 display_mode_,
845 NO_RESIZE_ACK);
846 view_screen_rect_ = new_window_rect;
847 window_screen_rect_ = new_window_rect;
848 if (!did_show_)
849 initial_rect_ = new_window_rect;
852 void RenderWidget::OnClose() {
853 if (closing_)
854 return;
855 NotifyOnClose();
856 closing_ = true;
858 // Browser correspondence is no longer needed at this point.
859 if (routing_id_ != MSG_ROUTING_NONE) {
860 RenderThread::Get()->RemoveRoute(routing_id_);
861 SetHidden(false);
862 if (RenderThreadImpl::current())
863 RenderThreadImpl::current()->WidgetDestroyed();
866 // If there is a Send call on the stack, then it could be dangerous to close
867 // now. Post a task that only gets invoked when there are no nested message
868 // loops.
869 RenderThread::Get()->GetTaskRunner()->PostNonNestableTask(
870 FROM_HERE, base::Bind(&RenderWidget::Close, this));
872 // Balances the AddRef taken when we called AddRoute.
873 Release();
876 // Got a response from the browser after the renderer decided to create a new
877 // view.
878 void RenderWidget::OnCreatingNewAck() {
879 DCHECK(routing_id_ != MSG_ROUTING_NONE);
881 CompleteInit();
884 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
885 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
886 return;
888 if (screen_metrics_emulator_) {
889 screen_metrics_emulator_->OnResizeMessage(params);
890 return;
893 bool orientation_changed =
894 screen_info_.orientationAngle != params.screen_info.orientationAngle;
896 screen_info_ = params.screen_info;
897 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
898 Resize(params.new_size,
899 params.physical_backing_size,
900 params.top_controls_shrink_blink_size,
901 params.top_controls_height,
902 params.visible_viewport_size,
903 params.resizer_rect,
904 params.is_fullscreen_granted,
905 params.display_mode,
906 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
908 if (orientation_changed)
909 OnOrientationChange();
912 void RenderWidget::OnEnableDeviceEmulation(
913 const blink::WebDeviceEmulationParams& params) {
914 if (!screen_metrics_emulator_)
915 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
916 else
917 screen_metrics_emulator_->ChangeEmulationParams(params);
920 void RenderWidget::OnDisableDeviceEmulation() {
921 screen_metrics_emulator_.reset();
924 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
925 SetDeviceColorProfile(color_profile);
928 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
929 if (resizer_rect_ == resizer_rect)
930 return;
931 resizer_rect_ = resizer_rect;
932 if (webwidget_)
933 webwidget_->didChangeWindowResizerRect();
936 void RenderWidget::OnWasHidden() {
937 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
938 // Go into a mode where we stop generating paint and scrolling events.
939 SetHidden(true);
940 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
941 WasHidden());
944 void RenderWidget::OnWasShown(bool needs_repainting,
945 const ui::LatencyInfo& latency_info) {
946 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
947 // During shutdown we can just ignore this message.
948 if (!webwidget_)
949 return;
951 // See OnWasHidden
952 SetHidden(false);
953 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
954 WasShown());
956 if (!needs_repainting)
957 return;
959 // Generate a full repaint.
960 if (compositor_) {
961 ui::LatencyInfo swap_latency_info(latency_info);
962 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
963 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
964 compositor_->SetNeedsForcedRedraw();
966 ScheduleComposite();
969 void RenderWidget::OnRequestMoveAck() {
970 DCHECK(pending_window_rect_count_);
971 pending_window_rect_count_--;
974 GURL RenderWidget::GetURLForGraphicsContext3D() {
975 return GURL();
978 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
979 // For widgets that are never visible, we don't start the compositor, so we
980 // never get a request for a cc::OutputSurface.
981 DCHECK(!never_visible_);
983 #if defined(OS_ANDROID)
984 if (SynchronousCompositorFactory* factory =
985 SynchronousCompositorFactory::GetInstance()) {
986 return factory->CreateOutputSurface(routing_id(),
987 frame_swap_message_queue_);
989 #endif
991 const base::CommandLine& command_line =
992 *base::CommandLine::ForCurrentProcess();
993 bool use_software = fallback;
994 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
995 use_software = true;
997 scoped_refptr<ContextProviderCommandBuffer> context_provider;
998 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
999 if (!use_software) {
1000 context_provider = ContextProviderCommandBuffer::Create(
1001 CreateGraphicsContext3D(), RENDER_COMPOSITOR_CONTEXT);
1002 if (!context_provider.get()) {
1003 // Cause the compositor to wait and try again.
1004 return scoped_ptr<cc::OutputSurface>();
1007 worker_context_provider = ContextProviderCommandBuffer::Create(
1008 CreateGraphicsContext3D(), RENDER_WORKER_CONTEXT);
1009 if (!worker_context_provider.get()) {
1010 // Cause the compositor to wait and try again.
1011 return scoped_ptr<cc::OutputSurface>();
1015 uint32 output_surface_id = next_output_surface_id_++;
1016 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1017 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1018 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1019 routing_id(), output_surface_id, context_provider,
1020 worker_context_provider, frame_swap_message_queue_));
1022 if (!context_provider.get()) {
1023 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1024 new cc::SoftwareOutputDevice());
1026 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1027 routing_id(), output_surface_id, nullptr, nullptr,
1028 software_device.Pass(), frame_swap_message_queue_, true));
1031 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1032 // Composite-to-mailbox is currently used for layout tests in order to cause
1033 // them to draw inside in the renderer to do the readback there. This should
1034 // no longer be the case when crbug.com/311404 is fixed.
1035 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1036 cc::ResourceFormat format = cc::RGBA_8888;
1037 if (base::SysInfo::IsLowEndDevice())
1038 format = cc::RGB_565;
1039 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1040 routing_id(), output_surface_id, context_provider,
1041 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1042 frame_swap_message_queue_, format));
1044 bool use_swap_compositor_frame_message = false;
1045 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1046 routing_id(), output_surface_id, context_provider,
1047 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1048 frame_swap_message_queue_, use_swap_compositor_frame_message));
1051 void RenderWidget::OnSwapBuffersAborted() {
1052 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1053 // Schedule another frame so the compositor learns about it.
1054 ScheduleComposite();
1057 void RenderWidget::OnSwapBuffersPosted() {
1058 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1061 void RenderWidget::OnSwapBuffersComplete() {
1062 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1064 // Notify subclasses that composited rendering was flushed to the screen.
1065 DidFlushPaint();
1068 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1069 const ui::LatencyInfo& latency_info,
1070 bool is_keyboard_shortcut) {
1071 if (!input_event)
1072 return;
1073 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1074 true);
1075 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1076 &handling_event_type_, input_event->type);
1078 // Calls into |didOverscroll()| while handling this event will populate
1079 // |event_overscroll|, which in turn will be bundled with the event ack.
1080 scoped_ptr<DidOverscrollParams> event_overscroll;
1081 base::AutoReset<scoped_ptr<DidOverscrollParams>*>
1082 handling_event_overscroll_resetter(&handling_event_overscroll_,
1083 &event_overscroll);
1085 #if defined(OS_ANDROID)
1086 // On Android, when a key is pressed or sent from the Keyboard using IME,
1087 // |AdapterInputConnection| generates input key events to make sure all JS
1088 // listeners that monitor KeyUp and KeyDown events receive the proper key
1089 // code. Since this input key event comes from IME, we need to set the
1090 // IME event guard here to make sure it does not interfere with other IME
1091 // events.
1092 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1093 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1094 const WebKeyboardEvent& key_event =
1095 *static_cast<const WebKeyboardEvent*>(input_event);
1096 // Some keys are special and it's essential that no events get blocked.
1097 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1098 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1099 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1100 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1101 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1102 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1103 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1105 #endif
1107 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
1108 &latency_info);
1110 base::TimeTicks start_time;
1111 if (base::TimeTicks::IsHighResolution())
1112 start_time = base::TimeTicks::Now();
1114 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1115 "event", WebInputEventTraits::GetName(input_event->type));
1116 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1117 TRACE_EVENT_FLOW_STEP0(
1118 "input,benchmark",
1119 "LatencyInfo.Flow",
1120 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
1121 "HanldeInputEventMain");
1123 // If we don't have a high res timer, these metrics won't be accurate enough
1124 // to be worth collecting. Note that this does introduce some sampling bias.
1125 if (!start_time.is_null())
1126 LogInputEventLatencyUma(*input_event, start_time);
1128 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1129 ui::LatencyInfo swap_latency_info(latency_info);
1130 if (compositor_) {
1131 latency_info_swap_promise_monitor =
1132 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1133 .Pass();
1136 bool prevent_default = false;
1137 if (WebInputEvent::isMouseEventType(input_event->type)) {
1138 const WebMouseEvent& mouse_event =
1139 *static_cast<const WebMouseEvent*>(input_event);
1140 TRACE_EVENT2("renderer", "HandleMouseMove",
1141 "x", mouse_event.x, "y", mouse_event.y);
1142 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1143 prevent_default = WillHandleMouseEvent(mouse_event);
1146 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1147 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1148 #if defined(OS_ANDROID)
1149 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1150 // case it should behave like a select key (i.e. causing a click if a button
1151 // is focused). However, if a text field is focused (2), its intended
1152 // behavior is to just show the IME and don't propagate the key.
1153 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1154 // when clicked on an input text field and cause the form submit if clicked
1155 // when the submit button is focused, but not vice-versa.
1156 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1157 // but at this point we have to swallow the event for the scenario (2).
1158 const WebKeyboardEvent& key_event =
1159 *static_cast<const WebKeyboardEvent*>(input_event);
1160 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1161 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1162 OnShowImeIfNeeded();
1163 prevent_default = true;
1165 #endif
1168 if (WebInputEvent::isGestureEventType(input_event->type)) {
1169 const WebGestureEvent& gesture_event =
1170 *static_cast<const WebGestureEvent*>(input_event);
1171 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1172 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1175 bool processed = prevent_default;
1176 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1177 suppress_next_char_events_ = false;
1178 if (!processed && webwidget_)
1179 processed = webwidget_->handleInputEvent(*input_event);
1182 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1183 // it's not processed by webkit, then we need to suppress the upcoming Char
1184 // events.
1185 if (!processed && is_keyboard_shortcut)
1186 suppress_next_char_events_ = true;
1188 InputEventAckState ack_result = processed ?
1189 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1190 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1191 const WebTouchEvent& touch_event =
1192 *static_cast<const WebTouchEvent*>(input_event);
1193 // Hit-test for all the pressed touch points. If there is a touch-handler
1194 // for any of the touch points, then the renderer should continue to receive
1195 // touch events.
1196 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1197 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1198 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1199 HasTouchEventHandlersAt(
1200 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1201 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1202 break;
1207 // Send mouse wheel events and their disposition to the compositor thread, so
1208 // that they can be used to produce the elastic overscroll effect on Mac.
1209 if (input_event->type == WebInputEvent::MouseWheel) {
1210 ObserveWheelEventAndResult(
1211 static_cast<const WebMouseWheelEvent&>(*input_event),
1212 event_overscroll ? event_overscroll->latest_overscroll_delta
1213 : gfx::Vector2dF(),
1214 processed);
1217 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1219 // If we don't have a fast and accurate Now(), we assume the input handlers
1220 // are heavy and rate limit them.
1221 bool rate_limiting_wanted =
1222 input_event->type == WebInputEvent::MouseMove ||
1223 input_event->type == WebInputEvent::MouseWheel;
1224 if (rate_limiting_wanted && !start_time.is_null()) {
1225 base::TimeTicks end_time = base::TimeTicks::Now();
1226 total_input_handling_time_this_frame_ += (end_time - start_time);
1227 rate_limiting_wanted =
1228 total_input_handling_time_this_frame_.InMicroseconds() >
1229 kInputHandlingTimeThrottlingThresholdMicroseconds;
1232 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1234 // Note that we can't use handling_event_type_ here since it will be overriden
1235 // by reentrant calls for events after the paused one.
1236 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1237 input_event->type == WebInputEvent::MouseMove;
1238 if (WebInputEventTraits::WillReceiveAckFromRenderer(*input_event) &&
1239 !no_ack) {
1240 InputEventAck ack(input_event->type, ack_result, swap_latency_info,
1241 event_overscroll.Pass(),
1242 WebInputEventTraits::GetUniqueTouchEventId(*input_event));
1243 scoped_ptr<IPC::Message> response(
1244 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1245 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1246 // We want to rate limit the input events in this case, so we'll wait for
1247 // painting to finish before ACKing this message.
1248 TRACE_EVENT_INSTANT0("renderer",
1249 "RenderWidget::OnHandleInputEvent ack throttled",
1250 TRACE_EVENT_SCOPE_THREAD);
1251 if (pending_input_event_ack_) {
1252 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1253 pending_input_event_ack_.get());
1254 // As two different kinds of events could cause us to postpone an ack
1255 // we send it now, if we have one pending. The Browser should never
1256 // send us the same kind of event we are delaying the ack for.
1257 Send(pending_input_event_ack_.release());
1259 pending_input_event_ack_ = response.Pass();
1260 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1261 pending_input_event_ack_.get());
1262 if (compositor_)
1263 compositor_->NotifyInputThrottledUntilCommit();
1264 } else {
1265 Send(response.release());
1267 } else {
1268 DCHECK(!event_overscroll) << "Unexpected overscroll for un-acked event";
1270 if (!no_ack && RenderThreadImpl::current()) {
1271 RenderThreadImpl::current()
1272 ->GetRendererScheduler()
1273 ->DidHandleInputEventOnMainThread(*input_event);
1275 if (input_event->type == WebInputEvent::MouseMove)
1276 ignore_ack_for_mouse_move_from_debugger_ = false;
1278 #if defined(OS_ANDROID)
1279 // Allow the IME to be shown when the focus changes as a consequence
1280 // of a processed touch end event.
1281 if (input_event->type == WebInputEvent::TouchEnd && processed)
1282 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1283 #elif defined(USE_AURA)
1284 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1285 // change.
1286 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1287 input_event->type == WebInputEvent::MouseUp)) {
1288 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1290 #endif
1292 if (!prevent_default) {
1293 if (WebInputEvent::isKeyboardEventType(input_event->type))
1294 DidHandleKeyEvent();
1297 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1298 // virtual keyboard.
1299 #if !defined(OS_ANDROID)
1300 // Virtual keyboard is not supported, so react to focus change immediately.
1301 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1302 input_event->type == WebInputEvent::MouseUp)) {
1303 FocusChangeComplete();
1305 #endif
1308 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1309 if (webwidget_)
1310 webwidget_->setCursorVisibilityState(is_visible);
1313 void RenderWidget::OnMouseCaptureLost() {
1314 if (webwidget_)
1315 webwidget_->mouseCaptureLost();
1318 void RenderWidget::OnSetFocus(bool enable) {
1319 has_focus_ = enable;
1320 if (webwidget_)
1321 webwidget_->setFocus(enable);
1324 void RenderWidget::ClearFocus() {
1325 // We may have got the focus from the browser before this gets processed, in
1326 // which case we do not want to unfocus ourself.
1327 if (!has_focus_ && webwidget_)
1328 webwidget_->setFocus(false);
1331 void RenderWidget::FlushPendingInputEventAck() {
1332 if (pending_input_event_ack_) {
1333 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1334 pending_input_event_ack_.get());
1335 Send(pending_input_event_ack_.release());
1337 total_input_handling_time_this_frame_ = base::TimeDelta();
1340 ///////////////////////////////////////////////////////////////////////////////
1341 // WebWidgetClient
1343 void RenderWidget::didAutoResize(const WebSize& new_size) {
1344 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1345 size_ = new_size;
1347 if (resizing_mode_selector_->is_synchronous_mode()) {
1348 WebRect new_pos(rootWindowRect().x,
1349 rootWindowRect().y,
1350 new_size.width,
1351 new_size.height);
1352 view_screen_rect_ = new_pos;
1353 window_screen_rect_ = new_pos;
1356 AutoResizeCompositor();
1358 if (!resizing_mode_selector_->is_synchronous_mode())
1359 need_update_rect_for_auto_resize_ = true;
1363 void RenderWidget::AutoResizeCompositor() {
1364 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1365 device_scale_factor_));
1366 if (compositor_)
1367 compositor_->setViewportSize(size_, physical_backing_size_);
1370 void RenderWidget::initializeLayerTreeView() {
1371 DCHECK(!host_closing_);
1373 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1374 compositor_->setViewportSize(size_, physical_backing_size_);
1375 if (init_complete_)
1376 StartCompositor();
1379 void RenderWidget::WillCloseLayerTreeView() {
1380 if (host_closing_)
1381 return;
1383 // Prevent new compositors or output surfaces from being created.
1384 host_closing_ = true;
1386 // Always send this notification to prevent new layer tree views from
1387 // being created, even if one hasn't been created yet.
1388 if (webwidget_)
1389 webwidget_->willCloseLayerTreeView();
1392 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1393 return compositor_.get();
1396 void RenderWidget::WillBeginCompositorFrame() {
1397 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1399 // The following two can result in further layout and possibly
1400 // enable GPU acceleration so they need to be called before any painting
1401 // is done.
1402 UpdateTextInputType();
1403 #if defined(OS_ANDROID)
1404 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1405 #endif
1406 UpdateSelectionBounds();
1409 void RenderWidget::DidCommitCompositorFrame() {
1410 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1411 DidCommitCompositorFrame());
1412 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1413 DidCommitCompositorFrame());
1414 #if defined(VIDEO_HOLE)
1415 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1416 DidCommitCompositorFrame());
1417 #endif // defined(VIDEO_HOLE)
1418 FlushPendingInputEventAck();
1421 void RenderWidget::DidCommitAndDrawCompositorFrame() {
1422 // NOTE: Tests may break if this event is renamed or moved. See
1423 // tab_capture_performancetest.cc.
1424 TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame");
1425 // Notify subclasses that we initiated the paint operation.
1426 DidInitiatePaint();
1429 void RenderWidget::DidCompleteSwapBuffers() {
1430 TRACE_EVENT0("renderer", "RenderWidget::DidCompleteSwapBuffers");
1432 // Notify subclasses threaded composited rendering was flushed to the screen.
1433 DidFlushPaint();
1435 if (!next_paint_flags_ &&
1436 !need_update_rect_for_auto_resize_ &&
1437 !plugin_window_moves_.size()) {
1438 return;
1441 ViewHostMsg_UpdateRect_Params params;
1442 params.view_size = size_;
1443 params.plugin_window_moves.swap(plugin_window_moves_);
1444 params.flags = next_paint_flags_;
1446 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1447 next_paint_flags_ = 0;
1448 need_update_rect_for_auto_resize_ = false;
1451 void RenderWidget::ScheduleComposite() {
1452 if (compositor_ &&
1453 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1454 compositor_->setNeedsAnimate();
1458 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
1459 if (compositor_) {
1460 // Regardless of whether threaded compositing is enabled, always
1461 // use this mechanism to force the compositor to redraw. However,
1462 // the invalidation code path below is still needed for the
1463 // non-threaded case.
1464 compositor_->SetNeedsForcedRedraw();
1466 ScheduleComposite();
1469 // static
1470 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1471 IPC::Message* msg,
1472 MessageDeliveryPolicy policy,
1473 FrameSwapMessageQueue* frame_swap_message_queue,
1474 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1475 int source_frame_number) {
1476 bool first_message_for_frame = false;
1477 frame_swap_message_queue->QueueMessageForFrame(policy,
1478 source_frame_number,
1479 make_scoped_ptr(msg),
1480 &first_message_for_frame);
1481 if (first_message_for_frame) {
1482 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1483 sync_message_filter, frame_swap_message_queue, source_frame_number));
1484 return promise;
1486 return nullptr;
1489 void RenderWidget::QueueMessage(IPC::Message* msg,
1490 MessageDeliveryPolicy policy) {
1491 // RenderThreadImpl::current() is NULL in some tests.
1492 if (!compositor_ || !RenderThreadImpl::current()) {
1493 Send(msg);
1494 return;
1497 scoped_ptr<cc::SwapPromise> swap_promise =
1498 QueueMessageImpl(msg,
1499 policy,
1500 frame_swap_message_queue_.get(),
1501 RenderThreadImpl::current()->sync_message_filter(),
1502 compositor_->GetSourceFrameNumber());
1504 if (swap_promise) {
1505 compositor_->QueueSwapPromise(swap_promise.Pass());
1506 // Request a commit. This might either A) request a commit ahead of time
1507 // or B) request a commit which is not needed because there are not
1508 // pending updates. If B) then the commit will be skipped and the swap
1509 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1510 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1511 // can_cancel_commit is not unset.
1512 compositor_->SetNeedsUpdateLayers();
1516 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1517 // TODO(darin): Eliminate this temporary.
1518 WebCursor cursor;
1519 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1520 // Only send a SetCursor message if we need to make a change.
1521 if (!current_cursor_.IsEqual(cursor)) {
1522 current_cursor_ = cursor;
1523 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1527 // We are supposed to get a single call to Show for a newly created RenderWidget
1528 // that was created via RenderWidget::CreateWebView. So, we wait until this
1529 // point to dispatch the ShowWidget message.
1531 // This method provides us with the information about how to display the newly
1532 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1534 void RenderWidget::show(WebNavigationPolicy) {
1535 DCHECK(!did_show_) << "received extraneous Show call";
1536 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1537 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1539 if (did_show_)
1540 return;
1542 did_show_ = true;
1543 // NOTE: initial_rect_ may still have its default values at this point, but
1544 // that's okay. It'll be ignored if as_popup is false, or the browser
1545 // process will impose a default position otherwise.
1546 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1547 SetPendingWindowRect(initial_rect_);
1550 void RenderWidget::didFocus() {
1553 void RenderWidget::didBlur() {
1556 void RenderWidget::DoDeferredClose() {
1557 WillCloseLayerTreeView();
1558 Send(new ViewHostMsg_Close(routing_id_));
1561 void RenderWidget::NotifyOnClose() {
1562 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose());
1565 void RenderWidget::closeWidgetSoon() {
1566 if (is_swapped_out_) {
1567 // This widget is currently swapped out, and the active widget is in a
1568 // different process. Have the browser route the close request to the
1569 // active widget instead, so that the correct unload handlers are run.
1570 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1571 return;
1574 // If a page calls window.close() twice, we'll end up here twice, but that's
1575 // OK. It is safe to send multiple Close messages.
1577 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1578 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1579 // could be closed before the JS finishes executing. So instead, post a
1580 // message back to the message loop, which won't run until the JS is
1581 // complete, and then the Close message can be sent.
1582 RenderThread::Get()->GetTaskRunner()->PostTask(
1583 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1586 void RenderWidget::QueueSyntheticGesture(
1587 scoped_ptr<SyntheticGestureParams> gesture_params,
1588 const SyntheticGestureCompletionCallback& callback) {
1589 DCHECK(!callback.is_null());
1591 pending_synthetic_gesture_callbacks_.push(callback);
1593 SyntheticGesturePacket gesture_packet;
1594 gesture_packet.set_gesture_params(gesture_params.Pass());
1596 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1599 void RenderWidget::Close() {
1600 screen_metrics_emulator_.reset();
1601 WillCloseLayerTreeView();
1602 compositor_.reset();
1603 if (webwidget_) {
1604 webwidget_->close();
1605 webwidget_ = NULL;
1609 WebRect RenderWidget::windowRect() {
1610 if (pending_window_rect_count_)
1611 return pending_window_rect_;
1613 return view_screen_rect_;
1616 void RenderWidget::setToolTipText(const blink::WebString& text,
1617 WebTextDirection hint) {
1618 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1621 void RenderWidget::setWindowRect(const WebRect& rect) {
1622 WebRect window_rect = rect;
1623 if (popup_origin_scale_for_emulation_) {
1624 float scale = popup_origin_scale_for_emulation_;
1625 window_rect.x = popup_screen_origin_for_emulation_.x() +
1626 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1627 window_rect.y = popup_screen_origin_for_emulation_.y() +
1628 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1631 if (!resizing_mode_selector_->is_synchronous_mode()) {
1632 if (did_show_) {
1633 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1634 SetPendingWindowRect(window_rect);
1635 } else {
1636 initial_rect_ = window_rect;
1638 } else {
1639 SetWindowRectSynchronously(window_rect);
1643 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1644 pending_window_rect_ = rect;
1645 pending_window_rect_count_++;
1648 WebRect RenderWidget::rootWindowRect() {
1649 if (pending_window_rect_count_) {
1650 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1651 // the RootWindowRect is probably going to return wrong results since the
1652 // browser may not have processed the Move yet. There isn't really anything
1653 // good to do in this case, and it shouldn't happen - since this size is
1654 // only really needed for windowToScreen, which is only used for Popups.
1655 return pending_window_rect_;
1658 return window_screen_rect_;
1661 WebRect RenderWidget::windowResizerRect() {
1662 return resizer_rect_;
1665 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1666 // To prevent this renderer process from sending unnecessary IPC messages to
1667 // a browser process, we permit the renderer process to send IPC messages
1668 // only during the input method attached to the browser process is active.
1669 input_method_is_active_ = is_active;
1672 void RenderWidget::OnImeSetComposition(
1673 const base::string16& text,
1674 const std::vector<WebCompositionUnderline>& underlines,
1675 int selection_start, int selection_end) {
1676 if (!ShouldHandleImeEvent())
1677 return;
1678 ImeEventGuard guard(this);
1679 if (!webwidget_->setComposition(
1680 text, WebVector<WebCompositionUnderline>(underlines),
1681 selection_start, selection_end)) {
1682 // If we failed to set the composition text, then we need to let the browser
1683 // process to cancel the input method's ongoing composition session, to make
1684 // sure we are in a consistent state.
1685 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1687 UpdateCompositionInfo(true);
1690 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1691 const gfx::Range& replacement_range,
1692 bool keep_selection) {
1693 if (!ShouldHandleImeEvent())
1694 return;
1695 ImeEventGuard guard(this);
1696 handling_input_event_ = true;
1697 if (text.length())
1698 webwidget_->confirmComposition(text);
1699 else if (keep_selection)
1700 webwidget_->confirmComposition(WebWidget::KeepSelection);
1701 else
1702 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1703 handling_input_event_ = false;
1704 UpdateCompositionInfo(true);
1707 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1708 // During shutdown we can just ignore this message.
1709 if (!webwidget_)
1710 return;
1712 // Even if the browser provides an empty damage rect, it's still expecting to
1713 // receive a repaint ack so just damage the entire widget bounds.
1714 if (size_to_paint.IsEmpty()) {
1715 size_to_paint = size_;
1718 set_next_paint_is_repaint_ack();
1719 if (compositor_)
1720 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1723 void RenderWidget::OnSyntheticGestureCompleted() {
1724 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1726 pending_synthetic_gesture_callbacks_.front().Run();
1727 pending_synthetic_gesture_callbacks_.pop();
1730 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1731 if (!webwidget_)
1732 return;
1733 webwidget_->setTextDirection(direction);
1736 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1737 const gfx::Rect& window_screen_rect) {
1738 if (screen_metrics_emulator_) {
1739 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1740 view_screen_rect, window_screen_rect);
1741 } else {
1742 view_screen_rect_ = view_screen_rect;
1743 window_screen_rect_ = window_screen_rect;
1745 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1748 void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) {
1749 if (compositor_)
1750 compositor_->SetSurfaceIdNamespace(surface_id_namespace);
1753 void RenderWidget::showImeIfNeeded() {
1754 OnShowImeIfNeeded();
1757 void RenderWidget::OnShowImeIfNeeded() {
1758 #if defined(OS_ANDROID) || defined(USE_AURA)
1759 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1760 #endif
1762 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1763 // virtual keyboard.
1764 #if !defined(OS_ANDROID)
1765 FocusChangeComplete();
1766 #endif
1769 #if defined(OS_ANDROID)
1770 void RenderWidget::IncrementOutstandingImeEventAcks() {
1771 ++outstanding_ime_acks_;
1774 void RenderWidget::OnImeEventAck() {
1775 --outstanding_ime_acks_;
1776 DCHECK(outstanding_ime_acks_ >= 0);
1778 #endif
1780 bool RenderWidget::ShouldHandleImeEvent() {
1781 #if defined(OS_ANDROID)
1782 return !!webwidget_ && outstanding_ime_acks_ == 0;
1783 #else
1784 return !!webwidget_;
1785 #endif
1788 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1789 if (handling_event_type_ == WebInputEvent::MouseMove) {
1790 // If we pause multiple times during a single mouse move event, we should
1791 // only send ACK once.
1792 if (!ignore_ack_for_mouse_move_from_debugger_) {
1793 InputEventAck ack(handling_event_type_, INPUT_EVENT_ACK_STATE_CONSUMED);
1794 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1795 return true;
1798 return false;
1801 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1802 ignore_ack_for_mouse_move_from_debugger_ = true;
1805 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1806 if (device_scale_factor_ == device_scale_factor)
1807 return;
1809 device_scale_factor_ = device_scale_factor;
1810 ScheduleComposite();
1813 bool RenderWidget::SetDeviceColorProfile(
1814 const std::vector<char>& color_profile) {
1815 if (device_color_profile_ == color_profile)
1816 return false;
1818 device_color_profile_ = color_profile;
1819 return true;
1822 void RenderWidget::ResetDeviceColorProfileForTesting() {
1823 if (!device_color_profile_.empty())
1824 device_color_profile_.clear();
1825 device_color_profile_.push_back('0');
1828 void RenderWidget::OnOrientationChange() {
1831 gfx::Vector2d RenderWidget::GetScrollOffset() {
1832 // Bare RenderWidgets don't support scroll offset.
1833 return gfx::Vector2d();
1836 void RenderWidget::SetHidden(bool hidden) {
1837 if (is_hidden_ == hidden)
1838 return;
1840 // The status has changed. Tell the RenderThread about it and ensure
1841 // throttled acks are released in case frame production ceases.
1842 is_hidden_ = hidden;
1843 FlushPendingInputEventAck();
1845 if (is_hidden_)
1846 RenderThreadImpl::current()->WidgetHidden();
1847 else
1848 RenderThreadImpl::current()->WidgetRestored();
1851 void RenderWidget::WillToggleFullscreen() {
1852 if (!webwidget_)
1853 return;
1855 if (is_fullscreen_granted_) {
1856 webwidget_->willExitFullScreen();
1857 } else {
1858 webwidget_->willEnterFullScreen();
1862 void RenderWidget::DidToggleFullscreen() {
1863 if (!webwidget_)
1864 return;
1866 if (is_fullscreen_granted_) {
1867 webwidget_->didEnterFullScreen();
1868 } else {
1869 webwidget_->didExitFullScreen();
1873 bool RenderWidget::next_paint_is_resize_ack() const {
1874 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1877 void RenderWidget::set_next_paint_is_resize_ack() {
1878 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1881 void RenderWidget::set_next_paint_is_repaint_ack() {
1882 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1885 static bool IsDateTimeInput(ui::TextInputType type) {
1886 return type == ui::TEXT_INPUT_TYPE_DATE ||
1887 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1888 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1889 type == ui::TEXT_INPUT_TYPE_MONTH ||
1890 type == ui::TEXT_INPUT_TYPE_TIME ||
1891 type == ui::TEXT_INPUT_TYPE_WEEK;
1895 void RenderWidget::StartHandlingImeEvent() {
1896 DCHECK(!handling_ime_event_);
1897 handling_ime_event_ = true;
1900 void RenderWidget::FinishHandlingImeEvent() {
1901 DCHECK(handling_ime_event_);
1902 handling_ime_event_ = false;
1903 // While handling an ime event, text input state and selection bounds updates
1904 // are ignored. These must explicitly be updated once finished handling the
1905 // ime event.
1906 UpdateSelectionBounds();
1907 #if defined(OS_ANDROID)
1908 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1909 #endif
1912 void RenderWidget::UpdateTextInputType() {
1913 // On Windows, not only an IME but also an on-screen keyboard relies on the
1914 // latest TextInputType to optimize its layout and functionality. Thus
1915 // |input_method_is_active_| is no longer an appropriate condition to suppress
1916 // TextInputTypeChanged IPC on Windows.
1917 // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
1918 // on other platforms as well as Windows if the overhead is acceptable.
1919 #if !defined(OS_WIN)
1920 if (!input_method_is_active_)
1921 return;
1922 #endif
1924 ui::TextInputType new_type = GetTextInputType();
1925 if (IsDateTimeInput(new_type))
1926 return; // Not considered as a text input field in WebKit/Chromium.
1928 bool new_can_compose_inline = CanComposeInline();
1930 blink::WebTextInputInfo new_info;
1931 if (webwidget_)
1932 new_info = webwidget_->textInputInfo();
1933 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1934 int new_flags = new_info.flags;
1936 if (text_input_type_ != new_type
1937 || can_compose_inline_ != new_can_compose_inline
1938 || text_input_mode_ != new_mode
1939 || text_input_flags_ != new_flags) {
1940 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1941 new_type,
1942 new_mode,
1943 new_can_compose_inline,
1944 new_flags));
1945 text_input_type_ = new_type;
1946 can_compose_inline_ = new_can_compose_inline;
1947 text_input_mode_ = new_mode;
1948 text_input_flags_ = new_flags;
1952 #if defined(OS_ANDROID) || defined(USE_AURA)
1953 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1954 ChangeSource change_source) {
1955 if (handling_ime_event_)
1956 return;
1957 if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1958 return;
1959 ui::TextInputType new_type = GetTextInputType();
1960 if (IsDateTimeInput(new_type))
1961 return; // Not considered as a text input field in WebKit/Chromium.
1963 blink::WebTextInputInfo new_info;
1964 if (webwidget_)
1965 new_info = webwidget_->textInputInfo();
1967 bool new_can_compose_inline = CanComposeInline();
1969 // Only sends text input params if they are changed or if the ime should be
1970 // shown.
1971 if (show_ime == SHOW_IME_IF_NEEDED ||
1972 (text_input_type_ != new_type ||
1973 text_input_info_ != new_info ||
1974 can_compose_inline_ != new_can_compose_inline)
1975 #if defined(OS_ANDROID)
1976 || text_field_is_dirty_
1977 #endif
1979 ViewHostMsg_TextInputState_Params p;
1980 p.type = new_type;
1981 p.flags = new_info.flags;
1982 p.value = new_info.value.utf8();
1983 p.selection_start = new_info.selectionStart;
1984 p.selection_end = new_info.selectionEnd;
1985 p.composition_start = new_info.compositionStart;
1986 p.composition_end = new_info.compositionEnd;
1987 p.can_compose_inline = new_can_compose_inline;
1988 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1989 #if defined(USE_AURA)
1990 p.is_non_ime_change = true;
1991 #endif
1992 #if defined(OS_ANDROID)
1993 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1994 text_field_is_dirty_;
1995 if (p.is_non_ime_change)
1996 IncrementOutstandingImeEventAcks();
1997 text_field_is_dirty_ = false;
1998 #endif
1999 #if defined(USE_AURA)
2000 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
2001 new_type,
2002 text_input_mode_,
2003 new_can_compose_inline,
2004 new_info.flags));
2005 #endif
2006 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
2008 text_input_info_ = new_info;
2009 text_input_type_ = new_type;
2010 can_compose_inline_ = new_can_compose_inline;
2011 text_input_flags_ = new_info.flags;
2014 #endif
2016 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
2017 WebRect focus_webrect;
2018 WebRect anchor_webrect;
2019 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
2020 *focus = focus_webrect;
2021 *anchor = anchor_webrect;
2024 void RenderWidget::UpdateSelectionBounds() {
2025 if (!webwidget_)
2026 return;
2027 if (handling_ime_event_)
2028 return;
2030 // With composited selection updates, the selection bounds will be reported
2031 // directly by the compositor, in which case explicit IPC selection
2032 // notifications should be suppressed.
2033 if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
2034 ViewHostMsg_SelectionBounds_Params params;
2035 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2036 if (selection_anchor_rect_ != params.anchor_rect ||
2037 selection_focus_rect_ != params.focus_rect) {
2038 selection_anchor_rect_ = params.anchor_rect;
2039 selection_focus_rect_ = params.focus_rect;
2040 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2041 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2042 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2046 UpdateCompositionInfo(false);
2049 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2050 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2051 static_assert(int(blink::WebTextInputType##a) \
2052 == int(ui::TEXT_INPUT_TYPE_##b), \
2053 "mismatching enums: " #a)
2055 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2056 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2057 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2058 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2059 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2060 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2061 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2062 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2063 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2064 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2065 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2066 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2067 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2068 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2069 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2070 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2071 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2073 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2074 blink::WebTextInputType type) {
2075 // Check the type is in the range representable by ui::TextInputType.
2076 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2077 "blink::WebTextInputType and ui::TextInputType not synchronized";
2078 return static_cast<ui::TextInputType>(type);
2081 ui::TextInputType RenderWidget::GetTextInputType() {
2082 if (webwidget_)
2083 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2084 return ui::TEXT_INPUT_TYPE_NONE;
2087 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2088 #if defined(OS_ANDROID)
2089 // TODO(yukawa): Start sending character bounds when the browser side
2090 // implementation becomes ready (crbug.com/424866).
2091 #else
2092 gfx::Range range = gfx::Range();
2093 if (should_update_range) {
2094 GetCompositionRange(&range);
2095 } else {
2096 range = composition_range_;
2098 std::vector<gfx::Rect> character_bounds;
2099 GetCompositionCharacterBounds(&character_bounds);
2101 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2102 return;
2103 composition_character_bounds_ = character_bounds;
2104 composition_range_ = range;
2105 Send(new InputHostMsg_ImeCompositionRangeChanged(
2106 routing_id(), composition_range_, composition_character_bounds_));
2107 #endif
2110 void RenderWidget::GetCompositionCharacterBounds(
2111 std::vector<gfx::Rect>* bounds) {
2112 DCHECK(bounds);
2113 bounds->clear();
2116 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2117 size_t location, length;
2118 if (webwidget_->compositionRange(&location, &length)) {
2119 range->set_start(location);
2120 range->set_end(location + length);
2121 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2122 range->set_start(location);
2123 range->set_end(location + length);
2124 } else {
2125 *range = gfx::Range::InvalidRange();
2129 bool RenderWidget::ShouldUpdateCompositionInfo(
2130 const gfx::Range& range,
2131 const std::vector<gfx::Rect>& bounds) {
2132 if (composition_range_ != range)
2133 return true;
2134 if (bounds.size() != composition_character_bounds_.size())
2135 return true;
2136 for (size_t i = 0; i < bounds.size(); ++i) {
2137 if (bounds[i] != composition_character_bounds_[i])
2138 return true;
2140 return false;
2143 #if defined(OS_ANDROID)
2144 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2145 // If not initialized, default to white. Note that 0 is different from black
2146 // as black still has alpha 0xFF.
2147 if (!bg_color)
2148 bg_color = SK_ColorWHITE;
2150 if (bg_color != body_background_color_) {
2151 body_background_color_ = bg_color;
2152 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2156 bool RenderWidget::DoesRecordFullLayer() const {
2157 SynchronousCompositorFactory* synchronous_compositor_factory =
2158 SynchronousCompositorFactory::GetInstance();
2160 // We assume that the absence of synchronous_compositor_factory
2161 // means we are in Chrome. In chrome, we want to clip, i.e.
2162 // *not* to record the full layer.
2163 if (!synchronous_compositor_factory)
2164 return false;
2166 return synchronous_compositor_factory->RecordFullLayer();
2168 #endif
2170 bool RenderWidget::CanComposeInline() {
2171 return true;
2174 WebScreenInfo RenderWidget::screenInfo() {
2175 return screen_info_;
2178 float RenderWidget::deviceScaleFactor() {
2179 return device_scale_factor_;
2182 void RenderWidget::resetInputMethod() {
2183 if (!input_method_is_active_)
2184 return;
2186 ImeEventGuard guard(this);
2187 // If the last text input type is not None, then we should finish any
2188 // ongoing composition regardless of the new text input type.
2189 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2190 // If a composition text exists, then we need to let the browser process
2191 // to cancel the input method's ongoing composition session.
2192 if (webwidget_->confirmComposition())
2193 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2196 UpdateCompositionInfo(true);
2199 #if defined(OS_ANDROID)
2200 void RenderWidget::showUnhandledTapUIIfNeeded(
2201 const WebPoint& tapped_position,
2202 const WebNode& tapped_node,
2203 bool page_changed) {
2204 DCHECK(handling_input_event_);
2205 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2206 !tapped_node.isContentEditable() &&
2207 !tapped_node.isInsideFocusableElementOrARIAWidget();
2208 if (should_trigger) {
2209 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2210 tapped_position.x, tapped_position.y));
2213 #endif
2215 void RenderWidget::didHandleGestureEvent(
2216 const WebGestureEvent& event,
2217 bool event_cancelled) {
2218 #if defined(OS_ANDROID) || defined(USE_AURA)
2219 if (event_cancelled)
2220 return;
2221 if (event.type == WebInputEvent::GestureTap) {
2222 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2223 } else if (event.type == WebInputEvent::GestureLongPress) {
2224 DCHECK(webwidget_);
2225 if (webwidget_->textInputInfo().value.isEmpty())
2226 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2227 else
2228 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2230 #endif
2233 void RenderWidget::didOverscroll(
2234 const blink::WebFloatSize& unusedDelta,
2235 const blink::WebFloatSize& accumulatedRootOverScroll,
2236 const blink::WebFloatPoint& position,
2237 const blink::WebFloatSize& velocity) {
2238 DidOverscrollParams params;
2239 params.accumulated_overscroll = gfx::Vector2dF(
2240 accumulatedRootOverScroll.width, accumulatedRootOverScroll.height);
2241 params.latest_overscroll_delta =
2242 gfx::Vector2dF(unusedDelta.width, unusedDelta.height);
2243 // TODO(sataya.m): don't negate velocity once http://crbug.com/499743 is
2244 // fixed.
2245 params.current_fling_velocity =
2246 gfx::Vector2dF(-velocity.width, -velocity.height);
2247 params.causal_event_viewport_point = gfx::PointF(position.x, position.y);
2249 // If we're currently handling an event, stash the overscroll data such that
2250 // it can be bundled in the event ack.
2251 if (handling_event_overscroll_) {
2252 handling_event_overscroll_->reset(new DidOverscrollParams(params));
2253 return;
2256 Send(new InputHostMsg_DidOverscroll(routing_id_, params));
2259 void RenderWidget::StartCompositor() {
2260 // For widgets that are never visible, we don't need the compositor to run
2261 // at all.
2262 if (never_visible_)
2263 return;
2264 // In tests without a RenderThreadImpl, don't set ready as this kicks
2265 // off creating output surfaces that the test can't create.
2266 if (!RenderThreadImpl::current())
2267 return;
2268 compositor_->StartCompositor();
2271 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2272 size_t i = 0;
2273 for (; i < plugin_window_moves_.size(); ++i) {
2274 if (plugin_window_moves_[i].window == move.window) {
2275 if (move.rects_valid) {
2276 plugin_window_moves_[i] = move;
2277 } else {
2278 plugin_window_moves_[i].visible = move.visible;
2280 break;
2284 if (i == plugin_window_moves_.size())
2285 plugin_window_moves_.push_back(move);
2288 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2289 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2290 i != plugin_window_moves_.end(); ++i) {
2291 if (i->window == window) {
2292 plugin_window_moves_.erase(i);
2293 break;
2299 RenderWidgetCompositor* RenderWidget::compositor() const {
2300 return compositor_.get();
2303 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2304 return false;
2307 bool RenderWidget::WillHandleGestureEvent(
2308 const blink::WebGestureEvent& event) {
2309 return false;
2312 void RenderWidget::ObserveWheelEventAndResult(
2313 const blink::WebMouseWheelEvent& wheel_event,
2314 const gfx::Vector2dF& wheel_unused_delta,
2315 bool event_processed) {
2316 if (!compositor_deps_->IsElasticOverscrollEnabled())
2317 return;
2319 cc::InputHandlerScrollResult scroll_result;
2320 scroll_result.did_scroll = event_processed;
2321 scroll_result.did_overscroll_root = !wheel_unused_delta.IsZero();
2322 scroll_result.unused_scroll_delta = wheel_unused_delta;
2324 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2325 InputHandlerManager* input_handler_manager =
2326 render_thread ? render_thread->input_handler_manager() : NULL;
2327 if (input_handler_manager) {
2328 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2329 routing_id_, wheel_event, scroll_result);
2333 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2334 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2337 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2338 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2339 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2340 "mismatching enums: " #a)
2342 inline content::TouchAction& operator|=(content::TouchAction& a,
2343 content::TouchAction b) {
2344 a = static_cast<content::TouchAction>(static_cast<int>(a) |
2345 static_cast<int>(b));
2346 return a;
2349 void RenderWidget::setTouchAction(
2350 blink::WebTouchAction web_touch_action) {
2352 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2353 // when blink is emulating touch with mouse).
2354 if (handling_event_type_ != WebInputEvent::TouchStart)
2355 return;
2357 // Verify the same values are used by the types so we can cast between them.
2358 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2359 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2360 STATIC_ASSERT_WTI_ENUM_MATCH(PanLeft, PAN_LEFT);
2361 STATIC_ASSERT_WTI_ENUM_MATCH(PanRight, PAN_RIGHT);
2362 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2363 STATIC_ASSERT_WTI_ENUM_MATCH(PanUp, PAN_UP);
2364 STATIC_ASSERT_WTI_ENUM_MATCH(PanDown, PAN_DOWN);
2365 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2366 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2368 content::TouchAction content_touch_action =
2369 static_cast<content::TouchAction>(web_touch_action);
2370 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2373 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2374 #if defined(OS_ANDROID)
2375 text_field_is_dirty_ = true;
2376 #endif
2379 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2380 return true;
2383 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2384 RenderWidget::CreateGraphicsContext3D() {
2385 if (!webwidget_)
2386 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2387 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2388 switches::kDisableGpuCompositing))
2389 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2390 if (!RenderThreadImpl::current())
2391 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2392 CauseForGpuLaunch cause =
2393 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2394 scoped_refptr<GpuChannelHost> gpu_channel_host(
2395 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2396 if (!gpu_channel_host.get())
2397 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2399 // Explicitly disable antialiasing for the compositor. As of the time of
2400 // this writing, the only platform that supported antialiasing for the
2401 // compositor was Mac OS X, because the on-screen OpenGL context creation
2402 // code paths on Windows and Linux didn't yet have multisampling support.
2403 // Mac OS X essentially always behaves as though it's rendering offscreen.
2404 // Multisampling has a heavy cost especially on devices with relatively low
2405 // fill rate like most notebooks, and the Mac implementation would need to
2406 // be optimized to resolve directly into the IOSurface shared between the
2407 // GPU and browser processes. For these reasons and to avoid platform
2408 // disparities we explicitly disable antialiasing.
2409 blink::WebGraphicsContext3D::Attributes attributes;
2410 attributes.antialias = false;
2411 attributes.shareResources = true;
2412 attributes.noAutomaticFlushes = true;
2413 attributes.depth = false;
2414 attributes.stencil = false;
2415 bool lose_context_when_out_of_memory = true;
2416 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2417 #if defined(OS_ANDROID)
2418 // If we raster too fast we become upload bound, and pending
2419 // uploads consume memory. For maximum upload throughput, we would
2420 // want to allow for upload_throughput * pipeline_time of pending
2421 // uploads, after which we are just wasting memory. Since we don't
2422 // know our upload throughput yet, this just caps our memory usage.
2423 size_t divider = 1;
2424 if (base::SysInfo::IsLowEndDevice())
2425 divider = 6;
2426 // For reference Nexus10 can upload 1MB in about 2.5ms.
2427 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2428 // Deadline to draw a frame to achieve 60 frames per second.
2429 const size_t kMillisecondsPerFrame = 16;
2430 // Assuming a two frame deep pipeline between the CPU and the GPU.
2431 size_t max_transfer_buffer_usage_mb =
2432 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2433 static const size_t kBytesPerMegabyte = 1024 * 1024;
2434 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2435 // to avoid unnecessarily stalling the compositor thread.
2436 limits.mapped_memory_reclaim_limit =
2437 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2438 #endif
2440 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2441 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2442 GetURLForGraphicsContext3D(),
2443 gpu_channel_host.get(),
2444 attributes,
2445 lose_context_when_out_of_memory,
2446 limits,
2447 NULL));
2448 return context.Pass();
2451 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2452 render_frame_proxies_.AddObserver(proxy);
2455 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2456 render_frame_proxies_.RemoveObserver(proxy);
2459 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2460 render_frames_.AddObserver(frame);
2463 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2464 render_frames_.RemoveObserver(frame);
2467 #if defined(VIDEO_HOLE)
2468 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2469 video_hole_frames_.AddObserver(frame);
2472 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2473 video_hole_frames_.RemoveObserver(frame);
2475 #endif // defined(VIDEO_HOLE)
2477 } // namespace content