Update V8 to version 4.6.61.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob3d83dd8188937346e9ce7698e7f7059b7226f4be
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(CompositorDependencies* compositor_deps,
472 blink::WebPopupType popup_type,
473 const blink::WebScreenInfo& screen_info,
474 bool swapped_out,
475 bool hidden,
476 bool never_visible)
477 : routing_id_(MSG_ROUTING_NONE),
478 surface_id_(0),
479 compositor_deps_(compositor_deps),
480 webwidget_(nullptr),
481 opener_id_(MSG_ROUTING_NONE),
482 init_complete_(false),
483 top_controls_shrink_blink_size_(false),
484 top_controls_height_(0.f),
485 next_paint_flags_(0),
486 auto_resize_mode_(false),
487 need_update_rect_for_auto_resize_(false),
488 did_show_(false),
489 is_hidden_(hidden),
490 never_visible_(never_visible),
491 is_fullscreen_granted_(false),
492 display_mode_(blink::WebDisplayModeUndefined),
493 has_focus_(false),
494 handling_input_event_(false),
495 handling_event_overscroll_(nullptr),
496 handling_ime_event_(false),
497 handling_event_type_(WebInputEvent::Undefined),
498 ignore_ack_for_mouse_move_from_debugger_(false),
499 closing_(false),
500 host_closing_(false),
501 is_swapped_out_(swapped_out),
502 for_oopif_(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 next_output_surface_id_(0),
513 #if defined(OS_ANDROID)
514 text_field_is_dirty_(false),
515 outstanding_ime_acks_(0),
516 body_background_color_(SK_ColorWHITE),
517 #endif
518 popup_origin_scale_for_emulation_(0.f),
519 frame_swap_message_queue_(new FrameSwapMessageQueue()),
520 resizing_mode_selector_(new ResizingModeSelector()),
521 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
522 has_host_context_menu_location_(false) {
523 if (!swapped_out)
524 RenderProcess::current()->AddRefProcess();
525 DCHECK(RenderThread::Get());
526 device_color_profile_.push_back('0');
529 RenderWidget::~RenderWidget() {
530 DCHECK(!webwidget_) << "Leaking our WebWidget!";
532 // If we are swapped out, we have released already.
533 if (!is_swapped_out_ && RenderProcess::current())
534 RenderProcess::current()->ReleaseProcess();
537 // static
538 RenderWidget* RenderWidget::Create(int32 opener_id,
539 CompositorDependencies* compositor_deps,
540 blink::WebPopupType popup_type,
541 const blink::WebScreenInfo& screen_info) {
542 DCHECK(opener_id != MSG_ROUTING_NONE);
543 scoped_refptr<RenderWidget> widget(new RenderWidget(
544 compositor_deps, popup_type, screen_info, false, false, false));
545 if (widget->Init(opener_id)) { // adds reference on success.
546 return widget.get();
548 return NULL;
551 // static
552 RenderWidget* RenderWidget::CreateForFrame(
553 int routing_id,
554 int surface_id,
555 bool hidden,
556 const blink::WebScreenInfo& screen_info,
557 CompositorDependencies* compositor_deps,
558 blink::WebLocalFrame* frame) {
559 CHECK_NE(routing_id, MSG_ROUTING_NONE);
560 scoped_refptr<RenderWidget> widget(
561 new RenderWidget(compositor_deps, blink::WebPopupTypeNone, screen_info,
562 false, hidden, false));
563 widget->routing_id_ = routing_id;
564 widget->surface_id_ = surface_id;
565 widget->for_oopif_ = true;
566 // DoInit increments the reference count on |widget|, keeping it alive after
567 // this function returns.
568 if (widget->DoInit(MSG_ROUTING_NONE,
569 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
570 nullptr)) {
571 widget->CompleteInit();
572 return widget.get();
574 return nullptr;
577 // static
578 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
579 RenderWidget* render_widget,
580 blink::WebLocalFrame* frame) {
581 return blink::WebFrameWidget::create(render_widget, frame);
584 // static
585 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
586 switch (render_widget->popup_type_) {
587 case blink::WebPopupTypeNone: // Nothing to create.
588 break;
589 case blink::WebPopupTypePage:
590 return WebPagePopup::create(render_widget);
591 default:
592 NOTREACHED();
594 return NULL;
597 void RenderWidget::CloseForFrame() {
598 OnClose();
601 bool RenderWidget::Init(int32 opener_id) {
602 return DoInit(opener_id, RenderWidget::CreateWebWidget(this),
603 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
604 &routing_id_, &surface_id_));
607 bool RenderWidget::DoInit(int32 opener_id,
608 WebWidget* web_widget,
609 IPC::SyncMessage* create_widget_message) {
610 DCHECK(!webwidget_);
612 if (opener_id != MSG_ROUTING_NONE)
613 opener_id_ = opener_id;
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_Repaint, OnRepaint)
732 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
733 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
734 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
735 IPC_MESSAGE_HANDLER(ViewMsg_SetSurfaceIdNamespace, OnSetSurfaceIdNamespace)
736 #if defined(OS_ANDROID)
737 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
738 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
739 #endif
740 IPC_MESSAGE_UNHANDLED(handled = false)
741 IPC_END_MESSAGE_MAP()
742 return handled;
745 bool RenderWidget::Send(IPC::Message* message) {
746 // Don't send any messages after the browser has told us to close, and filter
747 // most outgoing messages while swapped out.
748 if ((is_swapped_out_ &&
749 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
750 closing_) {
751 delete message;
752 return false;
755 // If given a messsage without a routing ID, then assign our routing ID.
756 if (message->routing_id() == MSG_ROUTING_NONE)
757 message->set_routing_id(routing_id_);
759 return RenderThread::Get()->Send(message);
762 void RenderWidget::Resize(const gfx::Size& new_size,
763 const gfx::Size& physical_backing_size,
764 bool top_controls_shrink_blink_size,
765 float top_controls_height,
766 const gfx::Size& visible_viewport_size,
767 const gfx::Rect& resizer_rect,
768 bool is_fullscreen_granted,
769 blink::WebDisplayMode display_mode,
770 const ResizeAck resize_ack) {
771 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
772 // A resize ack shouldn't be requested if we have not ACK'd the previous
773 // one.
774 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
775 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
778 // Ignore this during shutdown.
779 if (!webwidget_)
780 return;
782 if (compositor_) {
783 compositor_->setViewportSize(new_size, physical_backing_size);
786 physical_backing_size_ = physical_backing_size;
787 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
788 top_controls_height_ = top_controls_height;
789 visible_viewport_size_ = visible_viewport_size;
790 resizer_rect_ = resizer_rect;
792 // NOTE: We may have entered fullscreen mode without changing our size.
793 bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted;
794 is_fullscreen_granted_ = is_fullscreen_granted;
795 display_mode_ = display_mode;
797 webwidget_->setTopControlsHeight(top_controls_height,
798 top_controls_shrink_blink_size_);
800 if (size_ != new_size) {
801 size_ = new_size;
803 // When resizing, we want to wait to paint before ACK'ing the resize. This
804 // ensures that we only resize as fast as we can paint. We only need to
805 // send an ACK if we are resized to a non-empty rect.
806 webwidget_->resize(new_size);
809 webwidget()->resizePinchViewport(gfx::Size(
810 visible_viewport_size.width(),
811 visible_viewport_size.height()));
813 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
814 // In this case there is no paint/composite and therefore no
815 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
816 // ack through a fake ViewHostMsg_UpdateRect or a different message.
817 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
820 // Send the Resize_ACK flag once we paint again if requested.
821 if (resize_ack == SEND_RESIZE_ACK)
822 set_next_paint_is_resize_ack();
824 if (fullscreen_change)
825 DidToggleFullscreen();
827 // If a resize ack is requested and it isn't set-up, then no more resizes will
828 // come in and in general things will go wrong.
829 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
832 void RenderWidget::SetWindowRectSynchronously(
833 const gfx::Rect& new_window_rect) {
834 Resize(new_window_rect.size(),
835 new_window_rect.size(),
836 top_controls_shrink_blink_size_,
837 top_controls_height_,
838 new_window_rect.size(),
839 gfx::Rect(),
840 is_fullscreen_granted_,
841 display_mode_,
842 NO_RESIZE_ACK);
843 view_screen_rect_ = new_window_rect;
844 window_screen_rect_ = new_window_rect;
845 if (!did_show_)
846 initial_rect_ = new_window_rect;
849 void RenderWidget::OnClose() {
850 DCHECK(content::RenderThread::Get());
851 if (closing_)
852 return;
853 NotifyOnClose();
854 closing_ = true;
856 // Browser correspondence is no longer needed at this point.
857 if (routing_id_ != MSG_ROUTING_NONE) {
858 RenderThread::Get()->RemoveRoute(routing_id_);
859 SetHidden(false);
860 if (RenderThreadImpl::current())
861 RenderThreadImpl::current()->WidgetDestroyed();
864 if (for_oopif_) {
865 // Widgets for frames may be created and closed at any time while the frame
866 // is alive. However, the closing process must happen synchronously. Frame
867 // widget and frames hold pointers to each other. If Close() is deferred to
868 // the message loop like in the non-frame widget case, WebWidget::close()
869 // can end up accessing members of an already-deleted frame.
870 Close();
871 } else {
872 // If there is a Send call on the stack, then it could be dangerous to close
873 // now. Post a task that only gets invoked when there are no nested message
874 // loops.
875 base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(
876 FROM_HERE, base::Bind(&RenderWidget::Close, this));
879 // Balances the AddRef taken when we called AddRoute.
880 Release();
883 // Got a response from the browser after the renderer decided to create a new
884 // view.
885 void RenderWidget::OnCreatingNewAck() {
886 DCHECK(routing_id_ != MSG_ROUTING_NONE);
888 CompleteInit();
891 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
892 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
893 return;
895 if (screen_metrics_emulator_) {
896 screen_metrics_emulator_->OnResizeMessage(params);
897 return;
900 bool orientation_changed =
901 screen_info_.orientationAngle != params.screen_info.orientationAngle;
903 screen_info_ = params.screen_info;
904 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
905 Resize(params.new_size,
906 params.physical_backing_size,
907 params.top_controls_shrink_blink_size,
908 params.top_controls_height,
909 params.visible_viewport_size,
910 params.resizer_rect,
911 params.is_fullscreen_granted,
912 params.display_mode,
913 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
915 if (orientation_changed)
916 OnOrientationChange();
919 void RenderWidget::OnEnableDeviceEmulation(
920 const blink::WebDeviceEmulationParams& params) {
921 if (!screen_metrics_emulator_)
922 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
923 else
924 screen_metrics_emulator_->ChangeEmulationParams(params);
927 void RenderWidget::OnDisableDeviceEmulation() {
928 screen_metrics_emulator_.reset();
931 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
932 SetDeviceColorProfile(color_profile);
935 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
936 if (resizer_rect_ == resizer_rect)
937 return;
938 resizer_rect_ = resizer_rect;
939 if (webwidget_)
940 webwidget_->didChangeWindowResizerRect();
943 void RenderWidget::OnWasHidden() {
944 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
945 // Go into a mode where we stop generating paint and scrolling events.
946 SetHidden(true);
947 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
948 WasHidden());
951 void RenderWidget::OnWasShown(bool needs_repainting,
952 const ui::LatencyInfo& latency_info) {
953 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
954 // During shutdown we can just ignore this message.
955 if (!webwidget_)
956 return;
958 // See OnWasHidden
959 SetHidden(false);
960 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
961 WasShown());
963 if (!needs_repainting)
964 return;
966 // Generate a full repaint.
967 if (compositor_) {
968 ui::LatencyInfo swap_latency_info(latency_info);
969 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
970 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
971 compositor_->SetNeedsForcedRedraw();
973 ScheduleComposite();
976 void RenderWidget::OnRequestMoveAck() {
977 DCHECK(pending_window_rect_count_);
978 pending_window_rect_count_--;
981 GURL RenderWidget::GetURLForGraphicsContext3D() {
982 return GURL();
985 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
986 // For widgets that are never visible, we don't start the compositor, so we
987 // never get a request for a cc::OutputSurface.
988 DCHECK(!never_visible_);
990 #if defined(OS_ANDROID)
991 if (SynchronousCompositorFactory* factory =
992 SynchronousCompositorFactory::GetInstance()) {
993 return factory->CreateOutputSurface(routing_id(), surface_id(),
994 frame_swap_message_queue_);
996 #endif
998 const base::CommandLine& command_line =
999 *base::CommandLine::ForCurrentProcess();
1000 bool use_software = fallback;
1001 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1002 use_software = true;
1004 scoped_refptr<ContextProviderCommandBuffer> context_provider;
1005 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
1006 if (!use_software) {
1007 context_provider = ContextProviderCommandBuffer::Create(
1008 CreateGraphicsContext3D(true), RENDER_COMPOSITOR_CONTEXT);
1009 if (!context_provider.get()) {
1010 // Cause the compositor to wait and try again.
1011 return scoped_ptr<cc::OutputSurface>();
1014 worker_context_provider = ContextProviderCommandBuffer::Create(
1015 CreateGraphicsContext3D(false), RENDER_WORKER_CONTEXT);
1016 if (!worker_context_provider.get()) {
1017 // Cause the compositor to wait and try again.
1018 return scoped_ptr<cc::OutputSurface>();
1022 uint32 output_surface_id = next_output_surface_id_++;
1023 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1024 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1025 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1026 routing_id(), output_surface_id, context_provider,
1027 worker_context_provider, frame_swap_message_queue_));
1029 if (!context_provider.get()) {
1030 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1031 new cc::SoftwareOutputDevice());
1033 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1034 routing_id(), output_surface_id, nullptr, nullptr,
1035 software_device.Pass(), frame_swap_message_queue_, true));
1038 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1039 // Composite-to-mailbox is currently used for layout tests in order to cause
1040 // them to draw inside in the renderer to do the readback there. This should
1041 // no longer be the case when crbug.com/311404 is fixed.
1042 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1043 cc::ResourceFormat format = cc::RGBA_8888;
1044 if (base::SysInfo::IsLowEndDevice())
1045 format = cc::RGB_565;
1046 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1047 routing_id(), output_surface_id, context_provider,
1048 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1049 frame_swap_message_queue_, format));
1051 bool use_swap_compositor_frame_message = false;
1052 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1053 routing_id(), output_surface_id, context_provider,
1054 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1055 frame_swap_message_queue_, use_swap_compositor_frame_message));
1058 void RenderWidget::OnSwapBuffersAborted() {
1059 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1060 // Schedule another frame so the compositor learns about it.
1061 ScheduleComposite();
1064 void RenderWidget::OnSwapBuffersPosted() {
1065 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1068 void RenderWidget::OnSwapBuffersComplete() {
1069 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1071 // Notify subclasses that composited rendering was flushed to the screen.
1072 DidFlushPaint();
1075 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1076 const ui::LatencyInfo& latency_info,
1077 bool is_keyboard_shortcut) {
1078 if (!input_event)
1079 return;
1080 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1081 true);
1082 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1083 &handling_event_type_, input_event->type);
1085 // Calls into |didOverscroll()| while handling this event will populate
1086 // |event_overscroll|, which in turn will be bundled with the event ack.
1087 scoped_ptr<DidOverscrollParams> event_overscroll;
1088 base::AutoReset<scoped_ptr<DidOverscrollParams>*>
1089 handling_event_overscroll_resetter(&handling_event_overscroll_,
1090 &event_overscroll);
1092 #if defined(OS_ANDROID)
1093 // On Android, when a key is pressed or sent from the Keyboard using IME,
1094 // |AdapterInputConnection| generates input key events to make sure all JS
1095 // listeners that monitor KeyUp and KeyDown events receive the proper key
1096 // code. Since this input key event comes from IME, we need to set the
1097 // IME event guard here to make sure it does not interfere with other IME
1098 // events.
1099 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1100 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1101 const WebKeyboardEvent& key_event =
1102 *static_cast<const WebKeyboardEvent*>(input_event);
1103 // Some keys are special and it's essential that no events get blocked.
1104 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1105 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1106 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1107 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1108 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1109 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1110 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1112 #endif
1114 base::TimeTicks start_time;
1115 if (base::TimeTicks::IsHighResolution())
1116 start_time = base::TimeTicks::Now();
1118 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1119 "event", WebInputEventTraits::GetName(input_event->type));
1120 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1121 TRACE_EVENT_FLOW_STEP0(
1122 "input,benchmark",
1123 "LatencyInfo.Flow",
1124 TRACE_ID_DONT_MANGLE(latency_info.trace_id()),
1125 "HanldeInputEventMain");
1127 // If we don't have a high res timer, these metrics won't be accurate enough
1128 // to be worth collecting. Note that this does introduce some sampling bias.
1129 if (!start_time.is_null())
1130 LogInputEventLatencyUma(*input_event, start_time);
1132 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1133 ui::LatencyInfo swap_latency_info(latency_info);
1134 if (compositor_) {
1135 latency_info_swap_promise_monitor =
1136 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1137 .Pass();
1140 bool prevent_default = false;
1141 if (WebInputEvent::isMouseEventType(input_event->type)) {
1142 const WebMouseEvent& mouse_event =
1143 *static_cast<const WebMouseEvent*>(input_event);
1144 TRACE_EVENT2("renderer", "HandleMouseMove",
1145 "x", mouse_event.x, "y", mouse_event.y);
1146 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1147 prevent_default = WillHandleMouseEvent(mouse_event);
1150 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1151 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1152 #if defined(OS_ANDROID)
1153 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1154 // case it should behave like a select key (i.e. causing a click if a button
1155 // is focused). However, if a text field is focused (2), its intended
1156 // behavior is to just show the IME and don't propagate the key.
1157 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1158 // when clicked on an input text field and cause the form submit if clicked
1159 // when the submit button is focused, but not vice-versa.
1160 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1161 // but at this point we have to swallow the event for the scenario (2).
1162 const WebKeyboardEvent& key_event =
1163 *static_cast<const WebKeyboardEvent*>(input_event);
1164 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1165 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1166 OnShowImeIfNeeded();
1167 prevent_default = true;
1169 #endif
1172 if (WebInputEvent::isGestureEventType(input_event->type)) {
1173 const WebGestureEvent& gesture_event =
1174 *static_cast<const WebGestureEvent*>(input_event);
1175 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1176 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1179 bool processed = prevent_default;
1180 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1181 suppress_next_char_events_ = false;
1182 if (!processed && webwidget_)
1183 processed = webwidget_->handleInputEvent(*input_event);
1186 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1187 // it's not processed by webkit, then we need to suppress the upcoming Char
1188 // events.
1189 if (!processed && is_keyboard_shortcut)
1190 suppress_next_char_events_ = true;
1192 InputEventAckState ack_result = processed ?
1193 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1194 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1195 const WebTouchEvent& touch_event =
1196 *static_cast<const WebTouchEvent*>(input_event);
1197 // Hit-test for all the pressed touch points. If there is a touch-handler
1198 // for any of the touch points, then the renderer should continue to receive
1199 // touch events.
1200 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1201 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1202 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1203 HasTouchEventHandlersAt(
1204 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1205 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1206 break;
1211 // Send mouse wheel events and their disposition to the compositor thread, so
1212 // that they can be used to produce the elastic overscroll effect on Mac.
1213 if (input_event->type == WebInputEvent::MouseWheel) {
1214 ObserveWheelEventAndResult(
1215 static_cast<const WebMouseWheelEvent&>(*input_event),
1216 event_overscroll ? event_overscroll->latest_overscroll_delta
1217 : gfx::Vector2dF(),
1218 processed);
1221 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1223 // If we don't have a fast and accurate Now(), we assume the input handlers
1224 // are heavy and rate limit them.
1225 bool rate_limiting_wanted =
1226 input_event->type == WebInputEvent::MouseMove ||
1227 input_event->type == WebInputEvent::MouseWheel;
1228 if (rate_limiting_wanted && !start_time.is_null()) {
1229 base::TimeTicks end_time = base::TimeTicks::Now();
1230 total_input_handling_time_this_frame_ += (end_time - start_time);
1231 rate_limiting_wanted =
1232 total_input_handling_time_this_frame_.InMicroseconds() >
1233 kInputHandlingTimeThrottlingThresholdMicroseconds;
1236 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1238 // Note that we can't use handling_event_type_ here since it will be overriden
1239 // by reentrant calls for events after the paused one.
1240 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1241 input_event->type == WebInputEvent::MouseMove;
1242 if (WebInputEventTraits::WillReceiveAckFromRenderer(*input_event) &&
1243 !no_ack) {
1244 InputEventAck ack(input_event->type, ack_result, swap_latency_info,
1245 event_overscroll.Pass(),
1246 WebInputEventTraits::GetUniqueTouchEventId(*input_event));
1247 scoped_ptr<IPC::Message> response(
1248 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1249 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1250 // We want to rate limit the input events in this case, so we'll wait for
1251 // painting to finish before ACKing this message.
1252 TRACE_EVENT_INSTANT0("renderer",
1253 "RenderWidget::OnHandleInputEvent ack throttled",
1254 TRACE_EVENT_SCOPE_THREAD);
1255 if (pending_input_event_ack_) {
1256 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1257 pending_input_event_ack_.get());
1258 // As two different kinds of events could cause us to postpone an ack
1259 // we send it now, if we have one pending. The Browser should never
1260 // send us the same kind of event we are delaying the ack for.
1261 Send(pending_input_event_ack_.release());
1263 pending_input_event_ack_ = response.Pass();
1264 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1265 pending_input_event_ack_.get());
1266 if (compositor_)
1267 compositor_->NotifyInputThrottledUntilCommit();
1268 } else {
1269 Send(response.release());
1271 } else {
1272 DCHECK(!event_overscroll) << "Unexpected overscroll for un-acked event";
1274 if (!no_ack && RenderThreadImpl::current()) {
1275 RenderThreadImpl::current()
1276 ->GetRendererScheduler()
1277 ->DidHandleInputEventOnMainThread(*input_event);
1279 if (input_event->type == WebInputEvent::MouseMove)
1280 ignore_ack_for_mouse_move_from_debugger_ = false;
1282 #if defined(OS_ANDROID)
1283 // Allow the IME to be shown when the focus changes as a consequence
1284 // of a processed touch end event.
1285 if (input_event->type == WebInputEvent::TouchEnd && processed)
1286 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1287 #elif defined(USE_AURA)
1288 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1289 // change.
1290 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1291 input_event->type == WebInputEvent::MouseUp)) {
1292 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1294 #endif
1296 if (!prevent_default) {
1297 if (WebInputEvent::isKeyboardEventType(input_event->type))
1298 DidHandleKeyEvent();
1301 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1302 // virtual keyboard.
1303 #if !defined(OS_ANDROID)
1304 // Virtual keyboard is not supported, so react to focus change immediately.
1305 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1306 input_event->type == WebInputEvent::MouseUp)) {
1307 FocusChangeComplete();
1309 #endif
1312 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1313 if (webwidget_)
1314 webwidget_->setCursorVisibilityState(is_visible);
1317 void RenderWidget::OnMouseCaptureLost() {
1318 if (webwidget_)
1319 webwidget_->mouseCaptureLost();
1322 void RenderWidget::OnSetFocus(bool enable) {
1323 has_focus_ = enable;
1324 if (webwidget_)
1325 webwidget_->setFocus(enable);
1328 void RenderWidget::ClearFocus() {
1329 // We may have got the focus from the browser before this gets processed, in
1330 // which case we do not want to unfocus ourself.
1331 if (!has_focus_ && webwidget_)
1332 webwidget_->setFocus(false);
1335 void RenderWidget::FlushPendingInputEventAck() {
1336 if (pending_input_event_ack_) {
1337 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1338 pending_input_event_ack_.get());
1339 Send(pending_input_event_ack_.release());
1341 total_input_handling_time_this_frame_ = base::TimeDelta();
1344 ///////////////////////////////////////////////////////////////////////////////
1345 // WebWidgetClient
1347 void RenderWidget::didAutoResize(const WebSize& new_size) {
1348 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1349 size_ = new_size;
1351 if (resizing_mode_selector_->is_synchronous_mode()) {
1352 WebRect new_pos(rootWindowRect().x,
1353 rootWindowRect().y,
1354 new_size.width,
1355 new_size.height);
1356 view_screen_rect_ = new_pos;
1357 window_screen_rect_ = new_pos;
1360 AutoResizeCompositor();
1362 if (!resizing_mode_selector_->is_synchronous_mode())
1363 need_update_rect_for_auto_resize_ = true;
1367 void RenderWidget::AutoResizeCompositor() {
1368 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1369 device_scale_factor_));
1370 if (compositor_)
1371 compositor_->setViewportSize(size_, physical_backing_size_);
1374 void RenderWidget::initializeLayerTreeView() {
1375 DCHECK(!host_closing_);
1377 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1378 compositor_->setViewportSize(size_, physical_backing_size_);
1379 if (init_complete_)
1380 StartCompositor();
1383 void RenderWidget::WillCloseLayerTreeView() {
1384 if (host_closing_)
1385 return;
1387 // Prevent new compositors or output surfaces from being created.
1388 host_closing_ = true;
1390 // Always send this notification to prevent new layer tree views from
1391 // being created, even if one hasn't been created yet.
1392 if (webwidget_)
1393 webwidget_->willCloseLayerTreeView();
1396 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1397 return compositor_.get();
1400 void RenderWidget::WillBeginCompositorFrame() {
1401 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1403 // The UpdateTextInputState can result in further layout and possibly
1404 // enable GPU acceleration so they need to be called before any painting
1405 // is done.
1406 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1407 UpdateSelectionBounds();
1410 void RenderWidget::DidCommitCompositorFrame() {
1411 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1412 DidCommitCompositorFrame());
1413 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1414 DidCommitCompositorFrame());
1415 #if defined(VIDEO_HOLE)
1416 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1417 DidCommitCompositorFrame());
1418 #endif // defined(VIDEO_HOLE)
1419 FlushPendingInputEventAck();
1422 void RenderWidget::DidCommitAndDrawCompositorFrame() {
1423 // NOTE: Tests may break if this event is renamed or moved. See
1424 // tab_capture_performancetest.cc.
1425 TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame");
1426 // Notify subclasses that we initiated the paint operation.
1427 DidInitiatePaint();
1430 void RenderWidget::DidCompleteSwapBuffers() {
1431 TRACE_EVENT0("renderer", "RenderWidget::DidCompleteSwapBuffers");
1433 // Notify subclasses threaded composited rendering was flushed to the screen.
1434 DidFlushPaint();
1436 if (!next_paint_flags_ &&
1437 !need_update_rect_for_auto_resize_ &&
1438 !plugin_window_moves_.size()) {
1439 return;
1442 ViewHostMsg_UpdateRect_Params params;
1443 params.view_size = size_;
1444 params.plugin_window_moves.swap(plugin_window_moves_);
1445 params.flags = next_paint_flags_;
1447 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1448 next_paint_flags_ = 0;
1449 need_update_rect_for_auto_resize_ = false;
1452 void RenderWidget::ScheduleComposite() {
1453 if (compositor_ &&
1454 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1455 compositor_->setNeedsAnimate();
1459 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
1460 if (compositor_) {
1461 // Regardless of whether threaded compositing is enabled, always
1462 // use this mechanism to force the compositor to redraw. However,
1463 // the invalidation code path below is still needed for the
1464 // non-threaded case.
1465 compositor_->SetNeedsForcedRedraw();
1467 ScheduleComposite();
1470 // static
1471 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1472 IPC::Message* msg,
1473 MessageDeliveryPolicy policy,
1474 FrameSwapMessageQueue* frame_swap_message_queue,
1475 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1476 int source_frame_number) {
1477 bool first_message_for_frame = false;
1478 frame_swap_message_queue->QueueMessageForFrame(policy,
1479 source_frame_number,
1480 make_scoped_ptr(msg),
1481 &first_message_for_frame);
1482 if (first_message_for_frame) {
1483 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1484 sync_message_filter, frame_swap_message_queue, source_frame_number));
1485 return promise;
1487 return nullptr;
1490 void RenderWidget::QueueMessage(IPC::Message* msg,
1491 MessageDeliveryPolicy policy) {
1492 // RenderThreadImpl::current() is NULL in some tests.
1493 if (!compositor_ || !RenderThreadImpl::current()) {
1494 Send(msg);
1495 return;
1498 scoped_ptr<cc::SwapPromise> swap_promise =
1499 QueueMessageImpl(msg,
1500 policy,
1501 frame_swap_message_queue_.get(),
1502 RenderThreadImpl::current()->sync_message_filter(),
1503 compositor_->GetSourceFrameNumber());
1505 if (swap_promise) {
1506 compositor_->QueueSwapPromise(swap_promise.Pass());
1507 // Request a commit. This might either A) request a commit ahead of time
1508 // or B) request a commit which is not needed because there are not
1509 // pending updates. If B) then the commit will be skipped and the swap
1510 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1511 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1512 // can_cancel_commit is not unset.
1513 compositor_->SetNeedsUpdateLayers();
1517 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1518 // TODO(darin): Eliminate this temporary.
1519 WebCursor cursor;
1520 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1521 // Only send a SetCursor message if we need to make a change.
1522 if (!current_cursor_.IsEqual(cursor)) {
1523 current_cursor_ = cursor;
1524 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1528 // We are supposed to get a single call to Show for a newly created RenderWidget
1529 // that was created via RenderWidget::CreateWebView. So, we wait until this
1530 // point to dispatch the ShowWidget message.
1532 // This method provides us with the information about how to display the newly
1533 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1535 void RenderWidget::show(WebNavigationPolicy) {
1536 DCHECK(!did_show_) << "received extraneous Show call";
1537 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1538 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1540 if (did_show_)
1541 return;
1543 did_show_ = true;
1544 // NOTE: initial_rect_ may still have its default values at this point, but
1545 // that's okay. It'll be ignored if as_popup is false, or the browser
1546 // process will impose a default position otherwise.
1547 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1548 SetPendingWindowRect(initial_rect_);
1551 void RenderWidget::didFocus() {
1554 void RenderWidget::didBlur() {
1557 void RenderWidget::DoDeferredClose() {
1558 WillCloseLayerTreeView();
1559 Send(new ViewHostMsg_Close(routing_id_));
1562 void RenderWidget::NotifyOnClose() {
1563 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose());
1566 void RenderWidget::closeWidgetSoon() {
1567 DCHECK(content::RenderThread::Get());
1568 if (is_swapped_out_) {
1569 // This widget is currently swapped out, and the active widget is in a
1570 // different process. Have the browser route the close request to the
1571 // active widget instead, so that the correct unload handlers are run.
1572 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1573 return;
1576 // If a page calls window.close() twice, we'll end up here twice, but that's
1577 // OK. It is safe to send multiple Close messages.
1579 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1580 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1581 // could be closed before the JS finishes executing. So instead, post a
1582 // message back to the message loop, which won't run until the JS is
1583 // complete, and then the Close message can be sent.
1584 base::ThreadTaskRunnerHandle::Get()->PostTask(
1585 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1588 void RenderWidget::QueueSyntheticGesture(
1589 scoped_ptr<SyntheticGestureParams> gesture_params,
1590 const SyntheticGestureCompletionCallback& callback) {
1591 DCHECK(!callback.is_null());
1593 pending_synthetic_gesture_callbacks_.push(callback);
1595 SyntheticGesturePacket gesture_packet;
1596 gesture_packet.set_gesture_params(gesture_params.Pass());
1598 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1601 void RenderWidget::Close() {
1602 screen_metrics_emulator_.reset();
1603 WillCloseLayerTreeView();
1604 compositor_.reset();
1605 if (webwidget_) {
1606 webwidget_->close();
1607 webwidget_ = NULL;
1611 WebRect RenderWidget::windowRect() {
1612 if (pending_window_rect_count_)
1613 return pending_window_rect_;
1615 return view_screen_rect_;
1618 void RenderWidget::setToolTipText(const blink::WebString& text,
1619 WebTextDirection hint) {
1620 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1623 void RenderWidget::setWindowRect(const WebRect& rect) {
1624 WebRect window_rect = rect;
1625 if (popup_origin_scale_for_emulation_) {
1626 float scale = popup_origin_scale_for_emulation_;
1627 window_rect.x = popup_screen_origin_for_emulation_.x() +
1628 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1629 window_rect.y = popup_screen_origin_for_emulation_.y() +
1630 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1633 if (!resizing_mode_selector_->is_synchronous_mode()) {
1634 if (did_show_) {
1635 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1636 SetPendingWindowRect(window_rect);
1637 } else {
1638 initial_rect_ = window_rect;
1640 } else {
1641 SetWindowRectSynchronously(window_rect);
1645 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1646 pending_window_rect_ = rect;
1647 pending_window_rect_count_++;
1650 WebRect RenderWidget::rootWindowRect() {
1651 if (pending_window_rect_count_) {
1652 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1653 // the RootWindowRect is probably going to return wrong results since the
1654 // browser may not have processed the Move yet. There isn't really anything
1655 // good to do in this case, and it shouldn't happen - since this size is
1656 // only really needed for windowToScreen, which is only used for Popups.
1657 return pending_window_rect_;
1660 return window_screen_rect_;
1663 WebRect RenderWidget::windowResizerRect() {
1664 return resizer_rect_;
1667 void RenderWidget::OnImeSetComposition(
1668 const base::string16& text,
1669 const std::vector<WebCompositionUnderline>& underlines,
1670 int selection_start, int selection_end) {
1671 if (!ShouldHandleImeEvent())
1672 return;
1673 ImeEventGuard guard(this);
1674 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1675 true);
1676 if (!webwidget_->setComposition(
1677 text, WebVector<WebCompositionUnderline>(underlines),
1678 selection_start, selection_end)) {
1679 // If we failed to set the composition text, then we need to let the browser
1680 // process to cancel the input method's ongoing composition session, to make
1681 // sure we are in a consistent state.
1682 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1684 UpdateCompositionInfo(true);
1687 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1688 const gfx::Range& replacement_range,
1689 bool keep_selection) {
1690 if (!ShouldHandleImeEvent())
1691 return;
1692 ImeEventGuard guard(this);
1693 handling_input_event_ = true;
1694 if (text.length())
1695 webwidget_->confirmComposition(text);
1696 else if (keep_selection)
1697 webwidget_->confirmComposition(WebWidget::KeepSelection);
1698 else
1699 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1700 handling_input_event_ = false;
1701 UpdateCompositionInfo(true);
1704 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1705 // During shutdown we can just ignore this message.
1706 if (!webwidget_)
1707 return;
1709 // Even if the browser provides an empty damage rect, it's still expecting to
1710 // receive a repaint ack so just damage the entire widget bounds.
1711 if (size_to_paint.IsEmpty()) {
1712 size_to_paint = size_;
1715 set_next_paint_is_repaint_ack();
1716 if (compositor_)
1717 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1720 void RenderWidget::OnSyntheticGestureCompleted() {
1721 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1723 pending_synthetic_gesture_callbacks_.front().Run();
1724 pending_synthetic_gesture_callbacks_.pop();
1727 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1728 if (!webwidget_)
1729 return;
1730 webwidget_->setTextDirection(direction);
1733 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1734 const gfx::Rect& window_screen_rect) {
1735 if (screen_metrics_emulator_) {
1736 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1737 view_screen_rect, window_screen_rect);
1738 } else {
1739 view_screen_rect_ = view_screen_rect;
1740 window_screen_rect_ = window_screen_rect;
1742 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1745 void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) {
1746 if (compositor_)
1747 compositor_->SetSurfaceIdNamespace(surface_id_namespace);
1750 void RenderWidget::showImeIfNeeded() {
1751 OnShowImeIfNeeded();
1754 void RenderWidget::OnShowImeIfNeeded() {
1755 #if defined(OS_ANDROID) || defined(USE_AURA)
1756 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1757 #endif
1759 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1760 // virtual keyboard.
1761 #if !defined(OS_ANDROID)
1762 FocusChangeComplete();
1763 #endif
1766 #if defined(OS_ANDROID)
1767 void RenderWidget::IncrementOutstandingImeEventAcks() {
1768 ++outstanding_ime_acks_;
1771 void RenderWidget::OnImeEventAck() {
1772 --outstanding_ime_acks_;
1773 DCHECK(outstanding_ime_acks_ >= 0);
1775 #endif
1777 bool RenderWidget::ShouldHandleImeEvent() {
1778 #if defined(OS_ANDROID)
1779 return !!webwidget_ && outstanding_ime_acks_ == 0;
1780 #else
1781 return !!webwidget_;
1782 #endif
1785 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1786 if (handling_event_type_ == WebInputEvent::MouseMove) {
1787 // If we pause multiple times during a single mouse move event, we should
1788 // only send ACK once.
1789 if (!ignore_ack_for_mouse_move_from_debugger_) {
1790 InputEventAck ack(handling_event_type_, INPUT_EVENT_ACK_STATE_CONSUMED);
1791 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1792 return true;
1795 return false;
1798 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1799 ignore_ack_for_mouse_move_from_debugger_ = true;
1802 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1803 if (device_scale_factor_ == device_scale_factor)
1804 return;
1806 device_scale_factor_ = device_scale_factor;
1807 ScheduleComposite();
1810 bool RenderWidget::SetDeviceColorProfile(
1811 const std::vector<char>& color_profile) {
1812 if (device_color_profile_ == color_profile)
1813 return false;
1815 device_color_profile_ = color_profile;
1816 return true;
1819 void RenderWidget::ResetDeviceColorProfileForTesting() {
1820 if (!device_color_profile_.empty())
1821 device_color_profile_.clear();
1822 device_color_profile_.push_back('0');
1825 void RenderWidget::OnOrientationChange() {
1828 gfx::Vector2d RenderWidget::GetScrollOffset() {
1829 // Bare RenderWidgets don't support scroll offset.
1830 return gfx::Vector2d();
1833 void RenderWidget::SetHidden(bool hidden) {
1834 if (is_hidden_ == hidden)
1835 return;
1837 // The status has changed. Tell the RenderThread about it and ensure
1838 // throttled acks are released in case frame production ceases.
1839 is_hidden_ = hidden;
1840 FlushPendingInputEventAck();
1842 if (is_hidden_)
1843 RenderThreadImpl::current()->WidgetHidden();
1844 else
1845 RenderThreadImpl::current()->WidgetRestored();
1848 void RenderWidget::DidToggleFullscreen() {
1849 if (!webwidget_)
1850 return;
1852 if (is_fullscreen_granted_) {
1853 webwidget_->didEnterFullScreen();
1854 } else {
1855 webwidget_->didExitFullScreen();
1859 bool RenderWidget::next_paint_is_resize_ack() const {
1860 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1863 void RenderWidget::set_next_paint_is_resize_ack() {
1864 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1867 void RenderWidget::set_next_paint_is_repaint_ack() {
1868 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1871 static bool IsDateTimeInput(ui::TextInputType type) {
1872 return type == ui::TEXT_INPUT_TYPE_DATE ||
1873 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1874 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1875 type == ui::TEXT_INPUT_TYPE_MONTH ||
1876 type == ui::TEXT_INPUT_TYPE_TIME ||
1877 type == ui::TEXT_INPUT_TYPE_WEEK;
1881 void RenderWidget::StartHandlingImeEvent() {
1882 DCHECK(!handling_ime_event_);
1883 handling_ime_event_ = true;
1886 void RenderWidget::FinishHandlingImeEvent() {
1887 DCHECK(handling_ime_event_);
1888 handling_ime_event_ = false;
1889 // While handling an ime event, text input state and selection bounds updates
1890 // are ignored. These must explicitly be updated once finished handling the
1891 // ime event.
1892 UpdateSelectionBounds();
1893 #if defined(OS_ANDROID)
1894 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1895 #endif
1898 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1899 ChangeSource change_source) {
1900 TRACE_EVENT0("renderer", "RenderWidget::UpdateTextInputState");
1901 if (handling_ime_event_)
1902 return;
1903 ui::TextInputType new_type = GetTextInputType();
1904 if (IsDateTimeInput(new_type))
1905 return; // Not considered as a text input field in WebKit/Chromium.
1907 blink::WebTextInputInfo new_info;
1908 if (webwidget_)
1909 new_info = webwidget_->textInputInfo();
1910 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1912 bool new_can_compose_inline = CanComposeInline();
1914 // Only sends text input params if they are changed or if the ime should be
1915 // shown.
1916 if (show_ime == SHOW_IME_IF_NEEDED ||
1917 (text_input_type_ != new_type ||
1918 text_input_mode_ != new_mode ||
1919 text_input_info_ != new_info ||
1920 can_compose_inline_ != new_can_compose_inline)
1921 #if defined(OS_ANDROID)
1922 || text_field_is_dirty_
1923 #endif
1925 ViewHostMsg_TextInputState_Params params;
1926 params.type = new_type;
1927 params.mode = new_mode;
1928 params.flags = new_info.flags;
1929 params.value = new_info.value.utf8();
1930 params.selection_start = new_info.selectionStart;
1931 params.selection_end = new_info.selectionEnd;
1932 params.composition_start = new_info.compositionStart;
1933 params.composition_end = new_info.compositionEnd;
1934 params.can_compose_inline = new_can_compose_inline;
1935 params.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1936 #if defined(USE_AURA)
1937 params.is_non_ime_change = true;
1938 #endif
1939 #if defined(OS_ANDROID)
1940 params.is_non_ime_change = (change_source == FROM_NON_IME) ||
1941 text_field_is_dirty_;
1942 if (params.is_non_ime_change)
1943 IncrementOutstandingImeEventAcks();
1944 text_field_is_dirty_ = false;
1945 #endif
1946 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), params));
1948 text_input_info_ = new_info;
1949 text_input_type_ = new_type;
1950 text_input_mode_ = new_mode;
1951 can_compose_inline_ = new_can_compose_inline;
1952 text_input_flags_ = new_info.flags;
1956 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1957 WebRect focus_webrect;
1958 WebRect anchor_webrect;
1959 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1960 *focus = focus_webrect;
1961 *anchor = anchor_webrect;
1964 void RenderWidget::UpdateSelectionBounds() {
1965 TRACE_EVENT0("renderer", "RenderWidget::UpdateSelectionBounds");
1966 if (!webwidget_)
1967 return;
1968 if (handling_ime_event_)
1969 return;
1971 #if defined(USE_AURA)
1972 // TODO(mohsen): For now, always send explicit selection IPC notifications for
1973 // Aura beucause composited selection updates are not working for webview tags
1974 // which regresses IME inside webview. Remove this when composited selection
1975 // updates are fixed for webviews. See, http://crbug.com/510568.
1976 bool send_ipc = true;
1977 #else
1978 // With composited selection updates, the selection bounds will be reported
1979 // directly by the compositor, in which case explicit IPC selection
1980 // notifications should be suppressed.
1981 bool send_ipc =
1982 !blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled();
1983 #endif
1984 if (send_ipc) {
1985 ViewHostMsg_SelectionBounds_Params params;
1986 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
1987 if (selection_anchor_rect_ != params.anchor_rect ||
1988 selection_focus_rect_ != params.focus_rect) {
1989 selection_anchor_rect_ = params.anchor_rect;
1990 selection_focus_rect_ = params.focus_rect;
1991 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
1992 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
1993 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
1997 UpdateCompositionInfo(false);
2000 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2001 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2002 static_assert(int(blink::WebTextInputType##a) \
2003 == int(ui::TEXT_INPUT_TYPE_##b), \
2004 "mismatching enums: " #a)
2006 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2007 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2008 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2009 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2010 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2011 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2012 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2013 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2014 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2015 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2016 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2017 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2018 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2019 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2020 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2021 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2022 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2024 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2025 blink::WebTextInputType type) {
2026 // Check the type is in the range representable by ui::TextInputType.
2027 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2028 "blink::WebTextInputType and ui::TextInputType not synchronized";
2029 return static_cast<ui::TextInputType>(type);
2032 ui::TextInputType RenderWidget::GetTextInputType() {
2033 if (webwidget_)
2034 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2035 return ui::TEXT_INPUT_TYPE_NONE;
2038 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2039 #if defined(OS_ANDROID)
2040 // TODO(yukawa): Start sending character bounds when the browser side
2041 // implementation becomes ready (crbug.com/424866).
2042 #else
2043 TRACE_EVENT0("renderer", "RenderWidget::UpdateCompositionInfo");
2044 gfx::Range range = gfx::Range();
2045 if (should_update_range) {
2046 GetCompositionRange(&range);
2047 } else {
2048 range = composition_range_;
2050 std::vector<gfx::Rect> character_bounds;
2051 GetCompositionCharacterBounds(&character_bounds);
2053 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2054 return;
2055 composition_character_bounds_ = character_bounds;
2056 composition_range_ = range;
2057 Send(new InputHostMsg_ImeCompositionRangeChanged(
2058 routing_id(), composition_range_, composition_character_bounds_));
2059 #endif
2062 void RenderWidget::GetCompositionCharacterBounds(
2063 std::vector<gfx::Rect>* bounds) {
2064 DCHECK(bounds);
2065 bounds->clear();
2068 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2069 size_t location, length;
2070 if (webwidget_->compositionRange(&location, &length)) {
2071 range->set_start(location);
2072 range->set_end(location + length);
2073 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2074 range->set_start(location);
2075 range->set_end(location + length);
2076 } else {
2077 *range = gfx::Range::InvalidRange();
2081 bool RenderWidget::ShouldUpdateCompositionInfo(
2082 const gfx::Range& range,
2083 const std::vector<gfx::Rect>& bounds) {
2084 if (composition_range_ != range)
2085 return true;
2086 if (bounds.size() != composition_character_bounds_.size())
2087 return true;
2088 for (size_t i = 0; i < bounds.size(); ++i) {
2089 if (bounds[i] != composition_character_bounds_[i])
2090 return true;
2092 return false;
2095 #if defined(OS_ANDROID)
2096 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2097 // If not initialized, default to white. Note that 0 is different from black
2098 // as black still has alpha 0xFF.
2099 if (!bg_color)
2100 bg_color = SK_ColorWHITE;
2102 if (bg_color != body_background_color_) {
2103 body_background_color_ = bg_color;
2104 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2108 bool RenderWidget::DoesRecordFullLayer() const {
2109 SynchronousCompositorFactory* synchronous_compositor_factory =
2110 SynchronousCompositorFactory::GetInstance();
2112 // We assume that the absence of synchronous_compositor_factory
2113 // means we are in Chrome. In chrome, we want to clip, i.e.
2114 // *not* to record the full layer.
2115 if (!synchronous_compositor_factory)
2116 return false;
2118 return synchronous_compositor_factory->RecordFullLayer();
2120 #endif
2122 bool RenderWidget::CanComposeInline() {
2123 return true;
2126 WebScreenInfo RenderWidget::screenInfo() {
2127 return screen_info_;
2130 float RenderWidget::deviceScaleFactor() {
2131 return device_scale_factor_;
2134 void RenderWidget::resetInputMethod() {
2135 ImeEventGuard guard(this);
2136 // If the last text input type is not None, then we should finish any
2137 // ongoing composition regardless of the new text input type.
2138 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2139 // If a composition text exists, then we need to let the browser process
2140 // to cancel the input method's ongoing composition session.
2141 if (webwidget_->confirmComposition())
2142 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2145 UpdateCompositionInfo(true);
2148 #if defined(OS_ANDROID)
2149 void RenderWidget::showUnhandledTapUIIfNeeded(
2150 const WebPoint& tapped_position,
2151 const WebNode& tapped_node,
2152 bool page_changed) {
2153 DCHECK(handling_input_event_);
2154 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2155 !tapped_node.isContentEditable() &&
2156 !tapped_node.isInsideFocusableElementOrARIAWidget();
2157 if (should_trigger) {
2158 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2159 tapped_position.x, tapped_position.y));
2162 #endif
2164 void RenderWidget::didHandleGestureEvent(
2165 const WebGestureEvent& event,
2166 bool event_cancelled) {
2167 #if defined(OS_ANDROID) || defined(USE_AURA)
2168 if (event_cancelled)
2169 return;
2170 if (event.type == WebInputEvent::GestureTap) {
2171 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2172 } else if (event.type == WebInputEvent::GestureLongPress) {
2173 DCHECK(webwidget_);
2174 if (webwidget_->textInputInfo().value.isEmpty())
2175 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2176 else
2177 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2179 #endif
2182 void RenderWidget::didOverscroll(
2183 const blink::WebFloatSize& unusedDelta,
2184 const blink::WebFloatSize& accumulatedRootOverScroll,
2185 const blink::WebFloatPoint& position,
2186 const blink::WebFloatSize& velocity) {
2187 DidOverscrollParams params;
2188 params.accumulated_overscroll = gfx::Vector2dF(
2189 accumulatedRootOverScroll.width, accumulatedRootOverScroll.height);
2190 params.latest_overscroll_delta =
2191 gfx::Vector2dF(unusedDelta.width, unusedDelta.height);
2192 // TODO(sataya.m): don't negate velocity once http://crbug.com/499743 is
2193 // fixed.
2194 params.current_fling_velocity =
2195 gfx::Vector2dF(-velocity.width, -velocity.height);
2196 params.causal_event_viewport_point = gfx::PointF(position.x, position.y);
2198 // If we're currently handling an event, stash the overscroll data such that
2199 // it can be bundled in the event ack.
2200 if (handling_event_overscroll_) {
2201 handling_event_overscroll_->reset(new DidOverscrollParams(params));
2202 return;
2205 Send(new InputHostMsg_DidOverscroll(routing_id_, params));
2208 void RenderWidget::StartCompositor() {
2209 // For widgets that are never visible, we don't need the compositor to run
2210 // at all.
2211 if (never_visible_)
2212 return;
2213 // In tests without a RenderThreadImpl, don't set ready as this kicks
2214 // off creating output surfaces that the test can't create.
2215 if (!RenderThreadImpl::current())
2216 return;
2217 compositor_->StartCompositor();
2220 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2221 size_t i = 0;
2222 for (; i < plugin_window_moves_.size(); ++i) {
2223 if (plugin_window_moves_[i].window == move.window) {
2224 if (move.rects_valid) {
2225 plugin_window_moves_[i] = move;
2226 } else {
2227 plugin_window_moves_[i].visible = move.visible;
2229 break;
2233 if (i == plugin_window_moves_.size())
2234 plugin_window_moves_.push_back(move);
2237 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2238 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2239 i != plugin_window_moves_.end(); ++i) {
2240 if (i->window == window) {
2241 plugin_window_moves_.erase(i);
2242 break;
2248 RenderWidgetCompositor* RenderWidget::compositor() const {
2249 return compositor_.get();
2252 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2253 return false;
2256 bool RenderWidget::WillHandleGestureEvent(
2257 const blink::WebGestureEvent& event) {
2258 return false;
2261 void RenderWidget::ObserveWheelEventAndResult(
2262 const blink::WebMouseWheelEvent& wheel_event,
2263 const gfx::Vector2dF& wheel_unused_delta,
2264 bool event_processed) {
2265 if (!compositor_deps_->IsElasticOverscrollEnabled())
2266 return;
2268 cc::InputHandlerScrollResult scroll_result;
2269 scroll_result.did_scroll = event_processed;
2270 scroll_result.did_overscroll_root = !wheel_unused_delta.IsZero();
2271 scroll_result.unused_scroll_delta = wheel_unused_delta;
2273 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2274 InputHandlerManager* input_handler_manager =
2275 render_thread ? render_thread->input_handler_manager() : NULL;
2276 if (input_handler_manager) {
2277 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2278 routing_id_, wheel_event, scroll_result);
2282 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2283 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2286 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2287 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2288 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2289 "mismatching enums: " #a)
2291 inline content::TouchAction& operator|=(content::TouchAction& a,
2292 content::TouchAction b) {
2293 a = static_cast<content::TouchAction>(static_cast<int>(a) |
2294 static_cast<int>(b));
2295 return a;
2298 void RenderWidget::setTouchAction(
2299 blink::WebTouchAction web_touch_action) {
2301 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2302 // when blink is emulating touch with mouse).
2303 if (handling_event_type_ != WebInputEvent::TouchStart)
2304 return;
2306 // Verify the same values are used by the types so we can cast between them.
2307 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2308 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2309 STATIC_ASSERT_WTI_ENUM_MATCH(PanLeft, PAN_LEFT);
2310 STATIC_ASSERT_WTI_ENUM_MATCH(PanRight, PAN_RIGHT);
2311 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2312 STATIC_ASSERT_WTI_ENUM_MATCH(PanUp, PAN_UP);
2313 STATIC_ASSERT_WTI_ENUM_MATCH(PanDown, PAN_DOWN);
2314 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2315 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2317 content::TouchAction content_touch_action =
2318 static_cast<content::TouchAction>(web_touch_action);
2319 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2322 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2323 #if defined(OS_ANDROID)
2324 text_field_is_dirty_ = true;
2325 #endif
2328 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2329 return true;
2332 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2333 RenderWidget::CreateGraphicsContext3D(bool compositor) {
2334 if (!webwidget_)
2335 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2336 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2337 switches::kDisableGpuCompositing))
2338 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2339 if (!RenderThreadImpl::current())
2340 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2341 CauseForGpuLaunch cause =
2342 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2343 scoped_refptr<GpuChannelHost> gpu_channel_host(
2344 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2345 if (!gpu_channel_host.get())
2346 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2348 // Explicitly disable antialiasing for the compositor. As of the time of
2349 // this writing, the only platform that supported antialiasing for the
2350 // compositor was Mac OS X, because the on-screen OpenGL context creation
2351 // code paths on Windows and Linux didn't yet have multisampling support.
2352 // Mac OS X essentially always behaves as though it's rendering offscreen.
2353 // Multisampling has a heavy cost especially on devices with relatively low
2354 // fill rate like most notebooks, and the Mac implementation would need to
2355 // be optimized to resolve directly into the IOSurface shared between the
2356 // GPU and browser processes. For these reasons and to avoid platform
2357 // disparities we explicitly disable antialiasing.
2358 blink::WebGraphicsContext3D::Attributes attributes;
2359 attributes.antialias = false;
2360 attributes.shareResources = true;
2361 attributes.noAutomaticFlushes = true;
2362 attributes.depth = false;
2363 attributes.stencil = false;
2364 bool lose_context_when_out_of_memory = true;
2365 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2366 #if defined(OS_ANDROID)
2367 // If we raster too fast we become upload bound, and pending
2368 // uploads consume memory. For maximum upload throughput, we would
2369 // want to allow for upload_throughput * pipeline_time of pending
2370 // uploads, after which we are just wasting memory. Since we don't
2371 // know our upload throughput yet, this just caps our memory usage.
2372 size_t divider = 1;
2373 if (base::SysInfo::IsLowEndDevice())
2374 divider = 6;
2375 // For reference Nexus10 can upload 1MB in about 2.5ms.
2376 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2377 // Deadline to draw a frame to achieve 60 frames per second.
2378 const size_t kMillisecondsPerFrame = 16;
2379 // Assuming a two frame deep pipeline between the CPU and the GPU.
2380 size_t max_transfer_buffer_usage_mb =
2381 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2382 static const size_t kBytesPerMegabyte = 1024 * 1024;
2383 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2384 // to avoid unnecessarily stalling the compositor thread.
2385 limits.mapped_memory_reclaim_limit =
2386 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2387 #endif
2388 if (compositor)
2389 limits.command_buffer_size = 64 * 1024;
2391 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2392 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2393 GetURLForGraphicsContext3D(),
2394 gpu_channel_host.get(),
2395 attributes,
2396 lose_context_when_out_of_memory,
2397 limits,
2398 NULL));
2399 return context.Pass();
2402 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2403 render_frame_proxies_.AddObserver(proxy);
2406 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2407 render_frame_proxies_.RemoveObserver(proxy);
2410 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2411 render_frames_.AddObserver(frame);
2414 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2415 render_frames_.RemoveObserver(frame);
2418 #if defined(VIDEO_HOLE)
2419 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2420 video_hole_frames_.AddObserver(frame);
2423 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2424 video_hole_frames_.RemoveObserver(frame);
2426 #endif // defined(VIDEO_HOLE)
2428 } // namespace content