Add remaining Linux configs for MB.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob052edae4c7a6c79c620b1133491f800d7a9d07bf
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 body_background_color_(SK_ColorWHITE),
516 #endif
517 popup_origin_scale_for_emulation_(0.f),
518 frame_swap_message_queue_(new FrameSwapMessageQueue()),
519 resizing_mode_selector_(new ResizingModeSelector()),
520 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
521 has_host_context_menu_location_(false) {
522 if (!swapped_out)
523 RenderProcess::current()->AddRefProcess();
524 DCHECK(RenderThread::Get());
525 device_color_profile_.push_back('0');
526 #if defined(OS_ANDROID)
527 text_input_info_history_.push_back(blink::WebTextInputInfo());
528 #endif
531 RenderWidget::~RenderWidget() {
532 DCHECK(!webwidget_) << "Leaking our WebWidget!";
534 // If we are swapped out, we have released already.
535 if (!is_swapped_out_ && RenderProcess::current())
536 RenderProcess::current()->ReleaseProcess();
539 // static
540 RenderWidget* RenderWidget::Create(int32 opener_id,
541 CompositorDependencies* compositor_deps,
542 blink::WebPopupType popup_type,
543 const blink::WebScreenInfo& screen_info) {
544 DCHECK(opener_id != MSG_ROUTING_NONE);
545 scoped_refptr<RenderWidget> widget(new RenderWidget(
546 compositor_deps, popup_type, screen_info, false, false, false));
547 if (widget->Init(opener_id)) { // adds reference on success.
548 return widget.get();
550 return NULL;
553 // static
554 RenderWidget* RenderWidget::CreateForFrame(
555 int routing_id,
556 int surface_id,
557 bool hidden,
558 const blink::WebScreenInfo& screen_info,
559 CompositorDependencies* compositor_deps,
560 blink::WebLocalFrame* frame) {
561 CHECK_NE(routing_id, MSG_ROUTING_NONE);
562 scoped_refptr<RenderWidget> widget(
563 new RenderWidget(compositor_deps, blink::WebPopupTypeNone, screen_info,
564 false, hidden, false));
565 widget->routing_id_ = routing_id;
566 widget->surface_id_ = surface_id;
567 widget->for_oopif_ = true;
568 // DoInit increments the reference count on |widget|, keeping it alive after
569 // this function returns.
570 if (widget->DoInit(MSG_ROUTING_NONE,
571 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
572 nullptr)) {
573 widget->CompleteInit();
574 return widget.get();
576 return nullptr;
579 // static
580 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
581 RenderWidget* render_widget,
582 blink::WebLocalFrame* frame) {
583 return blink::WebFrameWidget::create(render_widget, frame);
586 // static
587 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
588 switch (render_widget->popup_type_) {
589 case blink::WebPopupTypeNone: // Nothing to create.
590 break;
591 case blink::WebPopupTypePage:
592 return WebPagePopup::create(render_widget);
593 default:
594 NOTREACHED();
596 return NULL;
599 void RenderWidget::CloseForFrame() {
600 OnClose();
603 bool RenderWidget::Init(int32 opener_id) {
604 return DoInit(opener_id, RenderWidget::CreateWebWidget(this),
605 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
606 &routing_id_, &surface_id_));
609 bool RenderWidget::DoInit(int32 opener_id,
610 WebWidget* web_widget,
611 IPC::SyncMessage* create_widget_message) {
612 DCHECK(!webwidget_);
614 if (opener_id != MSG_ROUTING_NONE)
615 opener_id_ = opener_id;
617 webwidget_ = web_widget;
619 bool result = true;
620 if (create_widget_message)
621 result = RenderThread::Get()->Send(create_widget_message);
623 if (result) {
624 RenderThread::Get()->AddRoute(routing_id_, this);
625 // Take a reference on behalf of the RenderThread. This will be balanced
626 // when we receive ViewMsg_Close.
627 AddRef();
628 if (RenderThreadImpl::current()) {
629 RenderThreadImpl::current()->WidgetCreated();
630 if (is_hidden_)
631 RenderThreadImpl::current()->WidgetHidden();
633 return true;
634 } else {
635 // The above Send can fail when the tab is closing.
636 return false;
640 // This is used to complete pending inits and non-pending inits.
641 void RenderWidget::CompleteInit() {
642 DCHECK(routing_id_ != MSG_ROUTING_NONE);
644 init_complete_ = true;
646 if (compositor_)
647 StartCompositor();
649 Send(new ViewHostMsg_RenderViewReady(routing_id_));
652 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
653 // We should only toggle between states.
654 DCHECK(is_swapped_out_ != is_swapped_out);
655 is_swapped_out_ = is_swapped_out;
657 // If we are swapping out, we will call ReleaseProcess, allowing the process
658 // to exit if all of its RenderViews are swapped out. We wait until the
659 // WasSwappedOut call to do this, to allow the unload handler to finish.
660 // If we are swapping in, we call AddRefProcess to prevent the process from
661 // exiting.
662 if (!is_swapped_out_)
663 RenderProcess::current()->AddRefProcess();
666 void RenderWidget::WasSwappedOut() {
667 // If we have been swapped out and no one else is using this process,
668 // it's safe to exit now.
669 CHECK(is_swapped_out_);
670 RenderProcess::current()->ReleaseProcess();
673 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
674 ScreenMetricsEmulator* emulator) {
675 popup_origin_scale_for_emulation_ = emulator->scale();
676 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
677 popup_screen_origin_for_emulation_ = gfx::Point(
678 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
679 emulator->original_screen_rect().origin().y() + emulator->offset().y());
680 screen_info_ = emulator->original_screen_info();
681 device_scale_factor_ = screen_info_.deviceScaleFactor;
684 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
685 if (screen_metrics_emulator_)
686 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
687 return anchor;
690 void RenderWidget::SetScreenMetricsEmulationParameters(
691 bool enabled,
692 const blink::WebDeviceEmulationParams& params) {
693 // This is only supported in RenderView.
694 NOTREACHED();
697 #if defined(OS_MACOSX) || defined(OS_ANDROID)
698 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
699 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
700 popup->SetOriginScaleAndOffsetForEmulation(
701 emulator->scale(), emulator->offset());
703 #endif
705 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
706 if (screen_metrics_emulator_)
707 screen_metrics_emulator_->OnShowContextMenu(params);
710 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
711 bool handled = true;
712 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
713 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
714 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
715 OnCursorVisibilityChange)
716 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
717 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
718 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
719 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
720 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
721 OnSyntheticGestureCompleted)
722 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
723 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
724 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
725 IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation,
726 OnEnableDeviceEmulation)
727 IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation,
728 OnDisableDeviceEmulation)
729 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
730 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
731 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
732 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
733 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
734 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
735 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
736 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
737 IPC_MESSAGE_HANDLER(ViewMsg_SetSurfaceIdNamespace, OnSetSurfaceIdNamespace)
738 #if defined(OS_ANDROID)
739 IPC_MESSAGE_HANDLER(InputMsg_ImeEventAck, OnImeEventAck)
740 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
741 #endif
742 IPC_MESSAGE_UNHANDLED(handled = false)
743 IPC_END_MESSAGE_MAP()
744 return handled;
747 bool RenderWidget::Send(IPC::Message* message) {
748 // Don't send any messages after the browser has told us to close, and filter
749 // most outgoing messages while swapped out.
750 if ((is_swapped_out_ &&
751 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
752 closing_) {
753 delete message;
754 return false;
757 // If given a messsage without a routing ID, then assign our routing ID.
758 if (message->routing_id() == MSG_ROUTING_NONE)
759 message->set_routing_id(routing_id_);
761 return RenderThread::Get()->Send(message);
764 void RenderWidget::Resize(const gfx::Size& new_size,
765 const gfx::Size& physical_backing_size,
766 bool top_controls_shrink_blink_size,
767 float top_controls_height,
768 const gfx::Size& visible_viewport_size,
769 const gfx::Rect& resizer_rect,
770 bool is_fullscreen_granted,
771 blink::WebDisplayMode display_mode,
772 const ResizeAck resize_ack) {
773 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
774 // A resize ack shouldn't be requested if we have not ACK'd the previous
775 // one.
776 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
777 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
780 // Ignore this during shutdown.
781 if (!webwidget_)
782 return;
784 if (compositor_) {
785 compositor_->setViewportSize(new_size, physical_backing_size);
788 physical_backing_size_ = physical_backing_size;
789 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
790 top_controls_height_ = top_controls_height;
791 visible_viewport_size_ = visible_viewport_size;
792 resizer_rect_ = resizer_rect;
794 // NOTE: We may have entered fullscreen mode without changing our size.
795 bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted;
796 is_fullscreen_granted_ = is_fullscreen_granted;
797 display_mode_ = display_mode;
799 webwidget_->setTopControlsHeight(top_controls_height,
800 top_controls_shrink_blink_size_);
802 if (size_ != new_size) {
803 size_ = new_size;
805 // When resizing, we want to wait to paint before ACK'ing the resize. This
806 // ensures that we only resize as fast as we can paint. We only need to
807 // send an ACK if we are resized to a non-empty rect.
808 webwidget_->resize(new_size);
811 webwidget()->resizePinchViewport(gfx::Size(
812 visible_viewport_size.width(),
813 visible_viewport_size.height()));
815 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
816 // In this case there is no paint/composite and therefore no
817 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
818 // ack through a fake ViewHostMsg_UpdateRect or a different message.
819 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
822 // Send the Resize_ACK flag once we paint again if requested.
823 if (resize_ack == SEND_RESIZE_ACK)
824 set_next_paint_is_resize_ack();
826 if (fullscreen_change)
827 DidToggleFullscreen();
829 // If a resize ack is requested and it isn't set-up, then no more resizes will
830 // come in and in general things will go wrong.
831 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
834 void RenderWidget::SetWindowRectSynchronously(
835 const gfx::Rect& new_window_rect) {
836 Resize(new_window_rect.size(),
837 new_window_rect.size(),
838 top_controls_shrink_blink_size_,
839 top_controls_height_,
840 new_window_rect.size(),
841 gfx::Rect(),
842 is_fullscreen_granted_,
843 display_mode_,
844 NO_RESIZE_ACK);
845 view_screen_rect_ = new_window_rect;
846 window_screen_rect_ = new_window_rect;
847 if (!did_show_)
848 initial_rect_ = new_window_rect;
851 void RenderWidget::OnClose() {
852 DCHECK(content::RenderThread::Get());
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 (for_oopif_) {
867 // Widgets for frames may be created and closed at any time while the frame
868 // is alive. However, the closing process must happen synchronously. Frame
869 // widget and frames hold pointers to each other. If Close() is deferred to
870 // the message loop like in the non-frame widget case, WebWidget::close()
871 // can end up accessing members of an already-deleted frame.
872 Close();
873 } else {
874 // If there is a Send call on the stack, then it could be dangerous to close
875 // now. Post a task that only gets invoked when there are no nested message
876 // loops.
877 base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(
878 FROM_HERE, base::Bind(&RenderWidget::Close, this));
881 // Balances the AddRef taken when we called AddRoute.
882 Release();
885 // Got a response from the browser after the renderer decided to create a new
886 // view.
887 void RenderWidget::OnCreatingNewAck() {
888 DCHECK(routing_id_ != MSG_ROUTING_NONE);
890 CompleteInit();
893 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
894 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
895 return;
897 if (screen_metrics_emulator_) {
898 screen_metrics_emulator_->OnResizeMessage(params);
899 return;
902 bool orientation_changed =
903 screen_info_.orientationAngle != params.screen_info.orientationAngle;
905 screen_info_ = params.screen_info;
906 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
907 Resize(params.new_size,
908 params.physical_backing_size,
909 params.top_controls_shrink_blink_size,
910 params.top_controls_height,
911 params.visible_viewport_size,
912 params.resizer_rect,
913 params.is_fullscreen_granted,
914 params.display_mode,
915 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
917 if (orientation_changed)
918 OnOrientationChange();
921 void RenderWidget::OnEnableDeviceEmulation(
922 const blink::WebDeviceEmulationParams& params) {
923 if (!screen_metrics_emulator_)
924 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
925 else
926 screen_metrics_emulator_->ChangeEmulationParams(params);
929 void RenderWidget::OnDisableDeviceEmulation() {
930 screen_metrics_emulator_.reset();
933 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
934 SetDeviceColorProfile(color_profile);
937 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
938 if (resizer_rect_ == resizer_rect)
939 return;
940 resizer_rect_ = resizer_rect;
941 if (webwidget_)
942 webwidget_->didChangeWindowResizerRect();
945 void RenderWidget::OnWasHidden() {
946 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
947 // Go into a mode where we stop generating paint and scrolling events.
948 SetHidden(true);
949 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
950 WasHidden());
953 void RenderWidget::OnWasShown(bool needs_repainting,
954 const ui::LatencyInfo& latency_info) {
955 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
956 // During shutdown we can just ignore this message.
957 if (!webwidget_)
958 return;
960 // See OnWasHidden
961 SetHidden(false);
962 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
963 WasShown());
965 if (!needs_repainting)
966 return;
968 // Generate a full repaint.
969 if (compositor_) {
970 ui::LatencyInfo swap_latency_info(latency_info);
971 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
972 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
973 compositor_->SetNeedsForcedRedraw();
975 ScheduleComposite();
978 void RenderWidget::OnRequestMoveAck() {
979 DCHECK(pending_window_rect_count_);
980 pending_window_rect_count_--;
983 GURL RenderWidget::GetURLForGraphicsContext3D() {
984 return GURL();
987 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
988 // For widgets that are never visible, we don't start the compositor, so we
989 // never get a request for a cc::OutputSurface.
990 DCHECK(!never_visible_);
992 #if defined(OS_ANDROID)
993 if (SynchronousCompositorFactory* factory =
994 SynchronousCompositorFactory::GetInstance()) {
995 return factory->CreateOutputSurface(routing_id(), surface_id(),
996 frame_swap_message_queue_);
998 #endif
1000 const base::CommandLine& command_line =
1001 *base::CommandLine::ForCurrentProcess();
1002 bool use_software = fallback;
1003 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1004 use_software = true;
1006 scoped_refptr<ContextProviderCommandBuffer> context_provider;
1007 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
1008 if (!use_software) {
1009 context_provider = ContextProviderCommandBuffer::Create(
1010 CreateGraphicsContext3D(true), RENDER_COMPOSITOR_CONTEXT);
1011 if (!context_provider.get()) {
1012 // Cause the compositor to wait and try again.
1013 return scoped_ptr<cc::OutputSurface>();
1016 worker_context_provider = ContextProviderCommandBuffer::Create(
1017 CreateGraphicsContext3D(false), RENDER_WORKER_CONTEXT);
1018 if (!worker_context_provider.get()) {
1019 // Cause the compositor to wait and try again.
1020 return scoped_ptr<cc::OutputSurface>();
1024 uint32 output_surface_id = next_output_surface_id_++;
1025 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1026 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1027 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1028 routing_id(), output_surface_id, context_provider,
1029 worker_context_provider, frame_swap_message_queue_));
1031 if (!context_provider.get()) {
1032 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1033 new cc::SoftwareOutputDevice());
1035 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1036 routing_id(), output_surface_id, nullptr, nullptr,
1037 software_device.Pass(), frame_swap_message_queue_, true));
1040 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1041 // Composite-to-mailbox is currently used for layout tests in order to cause
1042 // them to draw inside in the renderer to do the readback there. This should
1043 // no longer be the case when crbug.com/311404 is fixed.
1044 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1045 cc::ResourceFormat format = cc::RGBA_8888;
1046 if (base::SysInfo::IsLowEndDevice())
1047 format = cc::RGB_565;
1048 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1049 routing_id(), output_surface_id, context_provider,
1050 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1051 frame_swap_message_queue_, format));
1053 bool use_swap_compositor_frame_message = false;
1054 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1055 routing_id(), output_surface_id, context_provider,
1056 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1057 frame_swap_message_queue_, use_swap_compositor_frame_message));
1060 void RenderWidget::OnSwapBuffersAborted() {
1061 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1062 // Schedule another frame so the compositor learns about it.
1063 ScheduleComposite();
1066 void RenderWidget::OnSwapBuffersPosted() {
1067 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1070 void RenderWidget::OnSwapBuffersComplete() {
1071 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1073 // Notify subclasses that composited rendering was flushed to the screen.
1074 DidFlushPaint();
1077 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1078 const ui::LatencyInfo& latency_info,
1079 bool is_keyboard_shortcut) {
1080 if (!input_event)
1081 return;
1082 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1083 true);
1084 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1085 &handling_event_type_, input_event->type);
1087 // Calls into |didOverscroll()| while handling this event will populate
1088 // |event_overscroll|, which in turn will be bundled with the event ack.
1089 scoped_ptr<DidOverscrollParams> event_overscroll;
1090 base::AutoReset<scoped_ptr<DidOverscrollParams>*>
1091 handling_event_overscroll_resetter(&handling_event_overscroll_,
1092 &event_overscroll);
1094 #if defined(OS_ANDROID)
1095 // On Android, when a key is pressed or sent from the Keyboard using IME,
1096 // |AdapterInputConnection| generates input key events to make sure all JS
1097 // listeners that monitor KeyUp and KeyDown events receive the proper key
1098 // code. Since this input key event comes from IME, we need to set the
1099 // IME event guard here to make sure it does not interfere with other IME
1100 // events.
1101 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1102 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1103 const WebKeyboardEvent& key_event =
1104 *static_cast<const WebKeyboardEvent*>(input_event);
1105 // Some keys are special and it's essential that no events get blocked.
1106 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1107 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1108 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1109 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1110 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1111 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1112 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1114 #endif
1116 base::TimeTicks start_time;
1117 if (base::TimeTicks::IsHighResolution())
1118 start_time = base::TimeTicks::Now();
1120 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1121 "event", WebInputEventTraits::GetName(input_event->type));
1122 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1123 TRACE_EVENT_FLOW_STEP0(
1124 "input,benchmark",
1125 "LatencyInfo.Flow",
1126 TRACE_ID_DONT_MANGLE(latency_info.trace_id()),
1127 "HanldeInputEventMain");
1129 // If we don't have a high res timer, these metrics won't be accurate enough
1130 // to be worth collecting. Note that this does introduce some sampling bias.
1131 if (!start_time.is_null())
1132 LogInputEventLatencyUma(*input_event, start_time);
1134 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1135 ui::LatencyInfo swap_latency_info(latency_info);
1136 if (compositor_) {
1137 latency_info_swap_promise_monitor =
1138 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1139 .Pass();
1142 bool prevent_default = false;
1143 if (WebInputEvent::isMouseEventType(input_event->type)) {
1144 const WebMouseEvent& mouse_event =
1145 *static_cast<const WebMouseEvent*>(input_event);
1146 TRACE_EVENT2("renderer", "HandleMouseMove",
1147 "x", mouse_event.x, "y", mouse_event.y);
1148 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1149 prevent_default = WillHandleMouseEvent(mouse_event);
1152 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1153 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1154 #if defined(OS_ANDROID)
1155 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1156 // case it should behave like a select key (i.e. causing a click if a button
1157 // is focused). However, if a text field is focused (2), its intended
1158 // behavior is to just show the IME and don't propagate the key.
1159 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1160 // when clicked on an input text field and cause the form submit if clicked
1161 // when the submit button is focused, but not vice-versa.
1162 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1163 // but at this point we have to swallow the event for the scenario (2).
1164 const WebKeyboardEvent& key_event =
1165 *static_cast<const WebKeyboardEvent*>(input_event);
1166 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1167 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1168 OnShowImeIfNeeded();
1169 prevent_default = true;
1171 #endif
1174 if (WebInputEvent::isGestureEventType(input_event->type)) {
1175 const WebGestureEvent& gesture_event =
1176 *static_cast<const WebGestureEvent*>(input_event);
1177 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1178 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1181 bool processed = prevent_default;
1182 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1183 suppress_next_char_events_ = false;
1184 if (!processed && webwidget_)
1185 processed = webwidget_->handleInputEvent(*input_event);
1188 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1189 // it's not processed by webkit, then we need to suppress the upcoming Char
1190 // events.
1191 if (!processed && is_keyboard_shortcut)
1192 suppress_next_char_events_ = true;
1194 InputEventAckState ack_result = processed ?
1195 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1196 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1197 const WebTouchEvent& touch_event =
1198 *static_cast<const WebTouchEvent*>(input_event);
1199 // Hit-test for all the pressed touch points. If there is a touch-handler
1200 // for any of the touch points, then the renderer should continue to receive
1201 // touch events.
1202 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1203 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1204 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1205 HasTouchEventHandlersAt(
1206 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1207 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1208 break;
1213 // Send mouse wheel events and their disposition to the compositor thread, so
1214 // that they can be used to produce the elastic overscroll effect on Mac.
1215 if (input_event->type == WebInputEvent::MouseWheel) {
1216 ObserveWheelEventAndResult(
1217 static_cast<const WebMouseWheelEvent&>(*input_event),
1218 event_overscroll ? event_overscroll->latest_overscroll_delta
1219 : gfx::Vector2dF(),
1220 processed);
1223 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1225 // If we don't have a fast and accurate Now(), we assume the input handlers
1226 // are heavy and rate limit them.
1227 bool rate_limiting_wanted =
1228 input_event->type == WebInputEvent::MouseMove ||
1229 input_event->type == WebInputEvent::MouseWheel;
1230 if (rate_limiting_wanted && !start_time.is_null()) {
1231 base::TimeTicks end_time = base::TimeTicks::Now();
1232 total_input_handling_time_this_frame_ += (end_time - start_time);
1233 rate_limiting_wanted =
1234 total_input_handling_time_this_frame_.InMicroseconds() >
1235 kInputHandlingTimeThrottlingThresholdMicroseconds;
1238 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1240 // Note that we can't use handling_event_type_ here since it will be overriden
1241 // by reentrant calls for events after the paused one.
1242 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1243 input_event->type == WebInputEvent::MouseMove;
1244 if (WebInputEventTraits::WillReceiveAckFromRenderer(*input_event) &&
1245 !no_ack) {
1246 InputEventAck ack(input_event->type, ack_result, swap_latency_info,
1247 event_overscroll.Pass(),
1248 WebInputEventTraits::GetUniqueTouchEventId(*input_event));
1249 scoped_ptr<IPC::Message> response(
1250 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1251 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1252 // We want to rate limit the input events in this case, so we'll wait for
1253 // painting to finish before ACKing this message.
1254 TRACE_EVENT_INSTANT0("renderer",
1255 "RenderWidget::OnHandleInputEvent ack throttled",
1256 TRACE_EVENT_SCOPE_THREAD);
1257 if (pending_input_event_ack_) {
1258 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1259 pending_input_event_ack_.get());
1260 // As two different kinds of events could cause us to postpone an ack
1261 // we send it now, if we have one pending. The Browser should never
1262 // send us the same kind of event we are delaying the ack for.
1263 Send(pending_input_event_ack_.release());
1265 pending_input_event_ack_ = response.Pass();
1266 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1267 pending_input_event_ack_.get());
1268 if (compositor_)
1269 compositor_->NotifyInputThrottledUntilCommit();
1270 } else {
1271 Send(response.release());
1273 } else {
1274 DCHECK(!event_overscroll) << "Unexpected overscroll for un-acked event";
1276 if (!no_ack && RenderThreadImpl::current()) {
1277 RenderThreadImpl::current()
1278 ->GetRendererScheduler()
1279 ->DidHandleInputEventOnMainThread(*input_event);
1281 if (input_event->type == WebInputEvent::MouseMove)
1282 ignore_ack_for_mouse_move_from_debugger_ = false;
1284 #if defined(OS_ANDROID)
1285 // Allow the IME to be shown when the focus changes as a consequence
1286 // of a processed touch end event.
1287 if (input_event->type == WebInputEvent::TouchEnd && processed)
1288 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1289 #elif defined(USE_AURA)
1290 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1291 // change.
1292 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1293 input_event->type == WebInputEvent::MouseUp)) {
1294 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1296 #endif
1298 if (!prevent_default) {
1299 if (WebInputEvent::isKeyboardEventType(input_event->type))
1300 DidHandleKeyEvent();
1303 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1304 // virtual keyboard.
1305 #if !defined(OS_ANDROID)
1306 // Virtual keyboard is not supported, so react to focus change immediately.
1307 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1308 input_event->type == WebInputEvent::MouseUp)) {
1309 FocusChangeComplete();
1311 #endif
1314 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1315 if (webwidget_)
1316 webwidget_->setCursorVisibilityState(is_visible);
1319 void RenderWidget::OnMouseCaptureLost() {
1320 if (webwidget_)
1321 webwidget_->mouseCaptureLost();
1324 void RenderWidget::OnSetFocus(bool enable) {
1325 has_focus_ = enable;
1326 if (webwidget_)
1327 webwidget_->setFocus(enable);
1330 void RenderWidget::ClearFocus() {
1331 // We may have got the focus from the browser before this gets processed, in
1332 // which case we do not want to unfocus ourself.
1333 if (!has_focus_ && webwidget_)
1334 webwidget_->setFocus(false);
1337 void RenderWidget::FlushPendingInputEventAck() {
1338 if (pending_input_event_ack_) {
1339 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1340 pending_input_event_ack_.get());
1341 Send(pending_input_event_ack_.release());
1343 total_input_handling_time_this_frame_ = base::TimeDelta();
1346 ///////////////////////////////////////////////////////////////////////////////
1347 // WebWidgetClient
1349 void RenderWidget::didAutoResize(const WebSize& new_size) {
1350 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1351 size_ = new_size;
1353 if (resizing_mode_selector_->is_synchronous_mode()) {
1354 WebRect new_pos(rootWindowRect().x,
1355 rootWindowRect().y,
1356 new_size.width,
1357 new_size.height);
1358 view_screen_rect_ = new_pos;
1359 window_screen_rect_ = new_pos;
1362 AutoResizeCompositor();
1364 if (!resizing_mode_selector_->is_synchronous_mode())
1365 need_update_rect_for_auto_resize_ = true;
1369 void RenderWidget::AutoResizeCompositor() {
1370 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1371 device_scale_factor_));
1372 if (compositor_)
1373 compositor_->setViewportSize(size_, physical_backing_size_);
1376 void RenderWidget::initializeLayerTreeView() {
1377 DCHECK(!host_closing_);
1379 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1380 compositor_->setViewportSize(size_, physical_backing_size_);
1381 if (init_complete_)
1382 StartCompositor();
1385 void RenderWidget::WillCloseLayerTreeView() {
1386 if (host_closing_)
1387 return;
1389 // Prevent new compositors or output surfaces from being created.
1390 host_closing_ = true;
1392 // Always send this notification to prevent new layer tree views from
1393 // being created, even if one hasn't been created yet.
1394 if (webwidget_)
1395 webwidget_->willCloseLayerTreeView();
1398 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1399 return compositor_.get();
1402 void RenderWidget::WillBeginCompositorFrame() {
1403 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1405 // The UpdateTextInputState can result in further layout and possibly
1406 // enable GPU acceleration so they need to be called before any painting
1407 // is done.
1408 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1409 UpdateSelectionBounds();
1412 void RenderWidget::DidCommitCompositorFrame() {
1413 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1414 DidCommitCompositorFrame());
1415 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1416 DidCommitCompositorFrame());
1417 #if defined(VIDEO_HOLE)
1418 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1419 DidCommitCompositorFrame());
1420 #endif // defined(VIDEO_HOLE)
1421 FlushPendingInputEventAck();
1424 void RenderWidget::DidCommitAndDrawCompositorFrame() {
1425 // NOTE: Tests may break if this event is renamed or moved. See
1426 // tab_capture_performancetest.cc.
1427 TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame");
1428 // Notify subclasses that we initiated the paint operation.
1429 DidInitiatePaint();
1432 void RenderWidget::DidCompleteSwapBuffers() {
1433 TRACE_EVENT0("renderer", "RenderWidget::DidCompleteSwapBuffers");
1435 // Notify subclasses threaded composited rendering was flushed to the screen.
1436 DidFlushPaint();
1438 if (!next_paint_flags_ &&
1439 !need_update_rect_for_auto_resize_ &&
1440 !plugin_window_moves_.size()) {
1441 return;
1444 ViewHostMsg_UpdateRect_Params params;
1445 params.view_size = size_;
1446 params.plugin_window_moves.swap(plugin_window_moves_);
1447 params.flags = next_paint_flags_;
1449 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1450 next_paint_flags_ = 0;
1451 need_update_rect_for_auto_resize_ = false;
1454 void RenderWidget::ScheduleComposite() {
1455 if (compositor_ &&
1456 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1457 compositor_->setNeedsAnimate();
1461 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
1462 if (compositor_) {
1463 // Regardless of whether threaded compositing is enabled, always
1464 // use this mechanism to force the compositor to redraw. However,
1465 // the invalidation code path below is still needed for the
1466 // non-threaded case.
1467 compositor_->SetNeedsForcedRedraw();
1469 ScheduleComposite();
1472 // static
1473 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1474 IPC::Message* msg,
1475 MessageDeliveryPolicy policy,
1476 FrameSwapMessageQueue* frame_swap_message_queue,
1477 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1478 int source_frame_number) {
1479 bool first_message_for_frame = false;
1480 frame_swap_message_queue->QueueMessageForFrame(policy,
1481 source_frame_number,
1482 make_scoped_ptr(msg),
1483 &first_message_for_frame);
1484 if (first_message_for_frame) {
1485 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1486 sync_message_filter, frame_swap_message_queue, source_frame_number));
1487 return promise;
1489 return nullptr;
1492 void RenderWidget::QueueMessage(IPC::Message* msg,
1493 MessageDeliveryPolicy policy) {
1494 // RenderThreadImpl::current() is NULL in some tests.
1495 if (!compositor_ || !RenderThreadImpl::current()) {
1496 Send(msg);
1497 return;
1500 scoped_ptr<cc::SwapPromise> swap_promise =
1501 QueueMessageImpl(msg,
1502 policy,
1503 frame_swap_message_queue_.get(),
1504 RenderThreadImpl::current()->sync_message_filter(),
1505 compositor_->GetSourceFrameNumber());
1507 if (swap_promise) {
1508 compositor_->QueueSwapPromise(swap_promise.Pass());
1509 // Request a commit. This might either A) request a commit ahead of time
1510 // or B) request a commit which is not needed because there are not
1511 // pending updates. If B) then the commit will be skipped and the swap
1512 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1513 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1514 // can_cancel_commit is not unset.
1515 compositor_->SetNeedsUpdateLayers();
1519 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1520 // TODO(darin): Eliminate this temporary.
1521 WebCursor cursor;
1522 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1523 // Only send a SetCursor message if we need to make a change.
1524 if (!current_cursor_.IsEqual(cursor)) {
1525 current_cursor_ = cursor;
1526 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1530 // We are supposed to get a single call to Show for a newly created RenderWidget
1531 // that was created via RenderWidget::CreateWebView. So, we wait until this
1532 // point to dispatch the ShowWidget message.
1534 // This method provides us with the information about how to display the newly
1535 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1537 void RenderWidget::show(WebNavigationPolicy) {
1538 DCHECK(!did_show_) << "received extraneous Show call";
1539 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1540 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1542 if (did_show_)
1543 return;
1545 did_show_ = true;
1546 // NOTE: initial_rect_ may still have its default values at this point, but
1547 // that's okay. It'll be ignored if as_popup is false, or the browser
1548 // process will impose a default position otherwise.
1549 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1550 SetPendingWindowRect(initial_rect_);
1553 void RenderWidget::didFocus() {
1556 void RenderWidget::didBlur() {
1559 void RenderWidget::DoDeferredClose() {
1560 WillCloseLayerTreeView();
1561 Send(new ViewHostMsg_Close(routing_id_));
1564 void RenderWidget::NotifyOnClose() {
1565 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose());
1568 void RenderWidget::closeWidgetSoon() {
1569 DCHECK(content::RenderThread::Get());
1570 if (is_swapped_out_) {
1571 // This widget is currently swapped out, and the active widget is in a
1572 // different process. Have the browser route the close request to the
1573 // active widget instead, so that the correct unload handlers are run.
1574 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1575 return;
1578 // If a page calls window.close() twice, we'll end up here twice, but that's
1579 // OK. It is safe to send multiple Close messages.
1581 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1582 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1583 // could be closed before the JS finishes executing. So instead, post a
1584 // message back to the message loop, which won't run until the JS is
1585 // complete, and then the Close message can be sent.
1586 base::ThreadTaskRunnerHandle::Get()->PostTask(
1587 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1590 void RenderWidget::QueueSyntheticGesture(
1591 scoped_ptr<SyntheticGestureParams> gesture_params,
1592 const SyntheticGestureCompletionCallback& callback) {
1593 DCHECK(!callback.is_null());
1595 pending_synthetic_gesture_callbacks_.push(callback);
1597 SyntheticGesturePacket gesture_packet;
1598 gesture_packet.set_gesture_params(gesture_params.Pass());
1600 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1603 void RenderWidget::Close() {
1604 screen_metrics_emulator_.reset();
1605 WillCloseLayerTreeView();
1606 compositor_.reset();
1607 if (webwidget_) {
1608 webwidget_->close();
1609 webwidget_ = NULL;
1613 WebRect RenderWidget::windowRect() {
1614 if (pending_window_rect_count_)
1615 return pending_window_rect_;
1617 return view_screen_rect_;
1620 void RenderWidget::setToolTipText(const blink::WebString& text,
1621 WebTextDirection hint) {
1622 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1625 void RenderWidget::setWindowRect(const WebRect& rect) {
1626 WebRect window_rect = rect;
1627 if (popup_origin_scale_for_emulation_) {
1628 float scale = popup_origin_scale_for_emulation_;
1629 window_rect.x = popup_screen_origin_for_emulation_.x() +
1630 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1631 window_rect.y = popup_screen_origin_for_emulation_.y() +
1632 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1635 if (!resizing_mode_selector_->is_synchronous_mode()) {
1636 if (did_show_) {
1637 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1638 SetPendingWindowRect(window_rect);
1639 } else {
1640 initial_rect_ = window_rect;
1642 } else {
1643 SetWindowRectSynchronously(window_rect);
1647 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1648 pending_window_rect_ = rect;
1649 pending_window_rect_count_++;
1652 WebRect RenderWidget::rootWindowRect() {
1653 if (pending_window_rect_count_) {
1654 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1655 // the RootWindowRect is probably going to return wrong results since the
1656 // browser may not have processed the Move yet. There isn't really anything
1657 // good to do in this case, and it shouldn't happen - since this size is
1658 // only really needed for windowToScreen, which is only used for Popups.
1659 return pending_window_rect_;
1662 return window_screen_rect_;
1665 WebRect RenderWidget::windowResizerRect() {
1666 return resizer_rect_;
1669 void RenderWidget::OnImeSetComposition(
1670 const base::string16& text,
1671 const std::vector<WebCompositionUnderline>& underlines,
1672 int selection_start, int selection_end) {
1673 if (!ShouldHandleImeEvent())
1674 return;
1675 ImeEventGuard guard(this);
1676 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1677 true);
1678 if (!webwidget_->setComposition(
1679 text, WebVector<WebCompositionUnderline>(underlines),
1680 selection_start, selection_end)) {
1681 // If we failed to set the composition text, then we need to let the browser
1682 // process to cancel the input method's ongoing composition session, to make
1683 // sure we are in a consistent state.
1684 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1686 UpdateCompositionInfo(true);
1689 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1690 const gfx::Range& replacement_range,
1691 bool keep_selection) {
1692 if (!ShouldHandleImeEvent())
1693 return;
1694 ImeEventGuard guard(this);
1695 handling_input_event_ = true;
1696 if (text.length())
1697 webwidget_->confirmComposition(text);
1698 else if (keep_selection)
1699 webwidget_->confirmComposition(WebWidget::KeepSelection);
1700 else
1701 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1702 handling_input_event_ = false;
1703 UpdateCompositionInfo(true);
1706 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1707 // During shutdown we can just ignore this message.
1708 if (!webwidget_)
1709 return;
1711 // Even if the browser provides an empty damage rect, it's still expecting to
1712 // receive a repaint ack so just damage the entire widget bounds.
1713 if (size_to_paint.IsEmpty()) {
1714 size_to_paint = size_;
1717 set_next_paint_is_repaint_ack();
1718 if (compositor_)
1719 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1722 void RenderWidget::OnSyntheticGestureCompleted() {
1723 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1725 pending_synthetic_gesture_callbacks_.front().Run();
1726 pending_synthetic_gesture_callbacks_.pop();
1729 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1730 if (!webwidget_)
1731 return;
1732 webwidget_->setTextDirection(direction);
1735 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1736 const gfx::Rect& window_screen_rect) {
1737 if (screen_metrics_emulator_) {
1738 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1739 view_screen_rect, window_screen_rect);
1740 } else {
1741 view_screen_rect_ = view_screen_rect;
1742 window_screen_rect_ = window_screen_rect;
1744 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1747 void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) {
1748 if (compositor_)
1749 compositor_->SetSurfaceIdNamespace(surface_id_namespace);
1752 void RenderWidget::showImeIfNeeded() {
1753 OnShowImeIfNeeded();
1756 void RenderWidget::OnShowImeIfNeeded() {
1757 #if defined(OS_ANDROID) || defined(USE_AURA)
1758 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1759 #endif
1761 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1762 // virtual keyboard.
1763 #if !defined(OS_ANDROID)
1764 FocusChangeComplete();
1765 #endif
1768 #if defined(OS_ANDROID)
1769 void RenderWidget::OnImeEventSentForAck(const blink::WebTextInputInfo& info) {
1770 text_input_info_history_.push_back(info);
1773 void RenderWidget::OnImeEventAck() {
1774 DCHECK_GE(text_input_info_history_.size(), 1u);
1775 text_input_info_history_.pop_front();
1777 #endif
1779 bool RenderWidget::ShouldHandleImeEvent() {
1780 #if defined(OS_ANDROID)
1781 if (!webwidget_)
1782 return false;
1784 // We cannot handle IME events if there is any chance that the event we are
1785 // receiving here from the browser is based on the state that is different
1786 // from our current one as indicated by |text_input_info_|.
1787 // The states the browser might be in are:
1788 // text_input_info_history_[0] - current state ack'd by browser
1789 // text_input_info_history_[1...N] - pending state changes
1790 for (size_t i = 0u; i < text_input_info_history_.size() - 1u; ++i) {
1791 if (text_input_info_history_[i] != text_input_info_)
1792 return false;
1794 return true;
1795 #else
1796 return !!webwidget_;
1797 #endif
1800 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1801 if (handling_event_type_ == WebInputEvent::MouseMove) {
1802 // If we pause multiple times during a single mouse move event, we should
1803 // only send ACK once.
1804 if (!ignore_ack_for_mouse_move_from_debugger_) {
1805 InputEventAck ack(handling_event_type_, INPUT_EVENT_ACK_STATE_CONSUMED);
1806 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1807 return true;
1810 return false;
1813 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1814 ignore_ack_for_mouse_move_from_debugger_ = true;
1817 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1818 if (device_scale_factor_ == device_scale_factor)
1819 return;
1821 device_scale_factor_ = device_scale_factor;
1822 ScheduleComposite();
1825 bool RenderWidget::SetDeviceColorProfile(
1826 const std::vector<char>& color_profile) {
1827 if (device_color_profile_ == color_profile)
1828 return false;
1830 device_color_profile_ = color_profile;
1831 return true;
1834 void RenderWidget::ResetDeviceColorProfileForTesting() {
1835 if (!device_color_profile_.empty())
1836 device_color_profile_.clear();
1837 device_color_profile_.push_back('0');
1840 void RenderWidget::OnOrientationChange() {
1843 gfx::Vector2d RenderWidget::GetScrollOffset() {
1844 // Bare RenderWidgets don't support scroll offset.
1845 return gfx::Vector2d();
1848 void RenderWidget::SetHidden(bool hidden) {
1849 if (is_hidden_ == hidden)
1850 return;
1852 // The status has changed. Tell the RenderThread about it and ensure
1853 // throttled acks are released in case frame production ceases.
1854 is_hidden_ = hidden;
1855 FlushPendingInputEventAck();
1857 if (is_hidden_)
1858 RenderThreadImpl::current()->WidgetHidden();
1859 else
1860 RenderThreadImpl::current()->WidgetRestored();
1863 void RenderWidget::DidToggleFullscreen() {
1864 if (!webwidget_)
1865 return;
1867 if (is_fullscreen_granted_) {
1868 webwidget_->didEnterFullScreen();
1869 } else {
1870 webwidget_->didExitFullScreen();
1874 bool RenderWidget::next_paint_is_resize_ack() const {
1875 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1878 void RenderWidget::set_next_paint_is_resize_ack() {
1879 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1882 void RenderWidget::set_next_paint_is_repaint_ack() {
1883 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1886 static bool IsDateTimeInput(ui::TextInputType type) {
1887 return type == ui::TEXT_INPUT_TYPE_DATE ||
1888 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1889 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1890 type == ui::TEXT_INPUT_TYPE_MONTH ||
1891 type == ui::TEXT_INPUT_TYPE_TIME ||
1892 type == ui::TEXT_INPUT_TYPE_WEEK;
1896 void RenderWidget::StartHandlingImeEvent() {
1897 DCHECK(!handling_ime_event_);
1898 handling_ime_event_ = true;
1901 void RenderWidget::FinishHandlingImeEvent() {
1902 DCHECK(handling_ime_event_);
1903 handling_ime_event_ = false;
1904 // While handling an ime event, text input state and selection bounds updates
1905 // are ignored. These must explicitly be updated once finished handling the
1906 // ime event.
1907 UpdateSelectionBounds();
1908 #if defined(OS_ANDROID)
1909 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1910 #endif
1913 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1914 ChangeSource change_source) {
1915 TRACE_EVENT0("renderer", "RenderWidget::UpdateTextInputState");
1916 if (handling_ime_event_)
1917 return;
1918 ui::TextInputType new_type = GetTextInputType();
1919 if (IsDateTimeInput(new_type))
1920 return; // Not considered as a text input field in WebKit/Chromium.
1922 blink::WebTextInputInfo new_info;
1923 if (webwidget_)
1924 new_info = webwidget_->textInputInfo();
1925 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1927 bool new_can_compose_inline = CanComposeInline();
1929 // Only sends text input params if they are changed or if the ime should be
1930 // shown.
1931 if (show_ime == SHOW_IME_IF_NEEDED ||
1932 (text_input_type_ != new_type ||
1933 text_input_mode_ != new_mode ||
1934 text_input_info_ != new_info ||
1935 can_compose_inline_ != new_can_compose_inline)
1936 #if defined(OS_ANDROID)
1937 || text_field_is_dirty_
1938 #endif
1940 ViewHostMsg_TextInputState_Params params;
1941 params.type = new_type;
1942 params.mode = new_mode;
1943 params.flags = new_info.flags;
1944 params.value = new_info.value.utf8();
1945 params.selection_start = new_info.selectionStart;
1946 params.selection_end = new_info.selectionEnd;
1947 params.composition_start = new_info.compositionStart;
1948 params.composition_end = new_info.compositionEnd;
1949 params.can_compose_inline = new_can_compose_inline;
1950 params.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1951 #if defined(USE_AURA)
1952 params.is_non_ime_change = true;
1953 #endif
1954 #if defined(OS_ANDROID)
1955 params.is_non_ime_change = (change_source == FROM_NON_IME) ||
1956 text_field_is_dirty_;
1957 if (params.is_non_ime_change)
1958 OnImeEventSentForAck(new_info);
1959 text_field_is_dirty_ = false;
1960 #endif
1961 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), params));
1963 text_input_info_ = new_info;
1964 text_input_type_ = new_type;
1965 text_input_mode_ = new_mode;
1966 can_compose_inline_ = new_can_compose_inline;
1967 text_input_flags_ = new_info.flags;
1971 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1972 WebRect focus_webrect;
1973 WebRect anchor_webrect;
1974 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1975 *focus = focus_webrect;
1976 *anchor = anchor_webrect;
1979 void RenderWidget::UpdateSelectionBounds() {
1980 TRACE_EVENT0("renderer", "RenderWidget::UpdateSelectionBounds");
1981 if (!webwidget_)
1982 return;
1983 if (handling_ime_event_)
1984 return;
1986 #if defined(USE_AURA)
1987 // TODO(mohsen): For now, always send explicit selection IPC notifications for
1988 // Aura beucause composited selection updates are not working for webview tags
1989 // which regresses IME inside webview. Remove this when composited selection
1990 // updates are fixed for webviews. See, http://crbug.com/510568.
1991 bool send_ipc = true;
1992 #else
1993 // With composited selection updates, the selection bounds will be reported
1994 // directly by the compositor, in which case explicit IPC selection
1995 // notifications should be suppressed.
1996 bool send_ipc =
1997 !blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled();
1998 #endif
1999 if (send_ipc) {
2000 ViewHostMsg_SelectionBounds_Params params;
2001 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2002 if (selection_anchor_rect_ != params.anchor_rect ||
2003 selection_focus_rect_ != params.focus_rect) {
2004 selection_anchor_rect_ = params.anchor_rect;
2005 selection_focus_rect_ = params.focus_rect;
2006 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2007 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2008 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2012 UpdateCompositionInfo(false);
2015 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2016 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2017 static_assert(int(blink::WebTextInputType##a) \
2018 == int(ui::TEXT_INPUT_TYPE_##b), \
2019 "mismatching enums: " #a)
2021 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2022 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2023 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2024 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2025 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2026 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2027 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2028 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2029 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2030 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2031 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2032 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2033 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2034 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2035 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2036 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2037 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2039 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2040 blink::WebTextInputType type) {
2041 // Check the type is in the range representable by ui::TextInputType.
2042 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2043 "blink::WebTextInputType and ui::TextInputType not synchronized";
2044 return static_cast<ui::TextInputType>(type);
2047 ui::TextInputType RenderWidget::GetTextInputType() {
2048 if (webwidget_)
2049 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2050 return ui::TEXT_INPUT_TYPE_NONE;
2053 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2054 #if defined(OS_ANDROID)
2055 // TODO(yukawa): Start sending character bounds when the browser side
2056 // implementation becomes ready (crbug.com/424866).
2057 #else
2058 TRACE_EVENT0("renderer", "RenderWidget::UpdateCompositionInfo");
2059 gfx::Range range = gfx::Range();
2060 if (should_update_range) {
2061 GetCompositionRange(&range);
2062 } else {
2063 range = composition_range_;
2065 std::vector<gfx::Rect> character_bounds;
2066 GetCompositionCharacterBounds(&character_bounds);
2068 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2069 return;
2070 composition_character_bounds_ = character_bounds;
2071 composition_range_ = range;
2072 Send(new InputHostMsg_ImeCompositionRangeChanged(
2073 routing_id(), composition_range_, composition_character_bounds_));
2074 #endif
2077 void RenderWidget::GetCompositionCharacterBounds(
2078 std::vector<gfx::Rect>* bounds) {
2079 DCHECK(bounds);
2080 bounds->clear();
2083 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2084 size_t location, length;
2085 if (webwidget_->compositionRange(&location, &length)) {
2086 range->set_start(location);
2087 range->set_end(location + length);
2088 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2089 range->set_start(location);
2090 range->set_end(location + length);
2091 } else {
2092 *range = gfx::Range::InvalidRange();
2096 bool RenderWidget::ShouldUpdateCompositionInfo(
2097 const gfx::Range& range,
2098 const std::vector<gfx::Rect>& bounds) {
2099 if (composition_range_ != range)
2100 return true;
2101 if (bounds.size() != composition_character_bounds_.size())
2102 return true;
2103 for (size_t i = 0; i < bounds.size(); ++i) {
2104 if (bounds[i] != composition_character_bounds_[i])
2105 return true;
2107 return false;
2110 #if defined(OS_ANDROID)
2111 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2112 // If not initialized, default to white. Note that 0 is different from black
2113 // as black still has alpha 0xFF.
2114 if (!bg_color)
2115 bg_color = SK_ColorWHITE;
2117 if (bg_color != body_background_color_) {
2118 body_background_color_ = bg_color;
2119 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2123 bool RenderWidget::DoesRecordFullLayer() const {
2124 SynchronousCompositorFactory* synchronous_compositor_factory =
2125 SynchronousCompositorFactory::GetInstance();
2127 // We assume that the absence of synchronous_compositor_factory
2128 // means we are in Chrome. In chrome, we want to clip, i.e.
2129 // *not* to record the full layer.
2130 if (!synchronous_compositor_factory)
2131 return false;
2133 return synchronous_compositor_factory->RecordFullLayer();
2135 #endif
2137 bool RenderWidget::CanComposeInline() {
2138 return true;
2141 WebScreenInfo RenderWidget::screenInfo() {
2142 return screen_info_;
2145 float RenderWidget::deviceScaleFactor() {
2146 return device_scale_factor_;
2149 void RenderWidget::resetInputMethod() {
2150 ImeEventGuard guard(this);
2151 // If the last text input type is not None, then we should finish any
2152 // ongoing composition regardless of the new text input type.
2153 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2154 // If a composition text exists, then we need to let the browser process
2155 // to cancel the input method's ongoing composition session.
2156 if (webwidget_->confirmComposition())
2157 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2160 UpdateCompositionInfo(true);
2163 #if defined(OS_ANDROID)
2164 void RenderWidget::showUnhandledTapUIIfNeeded(
2165 const WebPoint& tapped_position,
2166 const WebNode& tapped_node,
2167 bool page_changed) {
2168 DCHECK(handling_input_event_);
2169 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2170 !tapped_node.isContentEditable() &&
2171 !tapped_node.isInsideFocusableElementOrARIAWidget();
2172 if (should_trigger) {
2173 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2174 tapped_position.x, tapped_position.y));
2177 #endif
2179 void RenderWidget::didHandleGestureEvent(
2180 const WebGestureEvent& event,
2181 bool event_cancelled) {
2182 #if defined(OS_ANDROID) || defined(USE_AURA)
2183 if (event_cancelled)
2184 return;
2185 if (event.type == WebInputEvent::GestureTap) {
2186 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2187 } else if (event.type == WebInputEvent::GestureLongPress) {
2188 DCHECK(webwidget_);
2189 if (webwidget_->textInputInfo().value.isEmpty())
2190 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2191 else
2192 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2194 #endif
2197 void RenderWidget::didOverscroll(
2198 const blink::WebFloatSize& unusedDelta,
2199 const blink::WebFloatSize& accumulatedRootOverScroll,
2200 const blink::WebFloatPoint& position,
2201 const blink::WebFloatSize& velocity) {
2202 DidOverscrollParams params;
2203 params.accumulated_overscroll = gfx::Vector2dF(
2204 accumulatedRootOverScroll.width, accumulatedRootOverScroll.height);
2205 params.latest_overscroll_delta =
2206 gfx::Vector2dF(unusedDelta.width, unusedDelta.height);
2207 // TODO(sataya.m): don't negate velocity once http://crbug.com/499743 is
2208 // fixed.
2209 params.current_fling_velocity =
2210 gfx::Vector2dF(-velocity.width, -velocity.height);
2211 params.causal_event_viewport_point = gfx::PointF(position.x, position.y);
2213 // If we're currently handling an event, stash the overscroll data such that
2214 // it can be bundled in the event ack.
2215 if (handling_event_overscroll_) {
2216 handling_event_overscroll_->reset(new DidOverscrollParams(params));
2217 return;
2220 Send(new InputHostMsg_DidOverscroll(routing_id_, params));
2223 void RenderWidget::StartCompositor() {
2224 // For widgets that are never visible, we don't need the compositor to run
2225 // at all.
2226 if (never_visible_)
2227 return;
2228 // In tests without a RenderThreadImpl, don't set ready as this kicks
2229 // off creating output surfaces that the test can't create.
2230 if (!RenderThreadImpl::current())
2231 return;
2232 compositor_->StartCompositor();
2235 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2236 size_t i = 0;
2237 for (; i < plugin_window_moves_.size(); ++i) {
2238 if (plugin_window_moves_[i].window == move.window) {
2239 if (move.rects_valid) {
2240 plugin_window_moves_[i] = move;
2241 } else {
2242 plugin_window_moves_[i].visible = move.visible;
2244 break;
2248 if (i == plugin_window_moves_.size())
2249 plugin_window_moves_.push_back(move);
2252 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2253 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2254 i != plugin_window_moves_.end(); ++i) {
2255 if (i->window == window) {
2256 plugin_window_moves_.erase(i);
2257 break;
2263 RenderWidgetCompositor* RenderWidget::compositor() const {
2264 return compositor_.get();
2267 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2268 return false;
2271 bool RenderWidget::WillHandleGestureEvent(
2272 const blink::WebGestureEvent& event) {
2273 return false;
2276 void RenderWidget::ObserveWheelEventAndResult(
2277 const blink::WebMouseWheelEvent& wheel_event,
2278 const gfx::Vector2dF& wheel_unused_delta,
2279 bool event_processed) {
2280 if (!compositor_deps_->IsElasticOverscrollEnabled())
2281 return;
2283 cc::InputHandlerScrollResult scroll_result;
2284 scroll_result.did_scroll = event_processed;
2285 scroll_result.did_overscroll_root = !wheel_unused_delta.IsZero();
2286 scroll_result.unused_scroll_delta = wheel_unused_delta;
2288 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2289 InputHandlerManager* input_handler_manager =
2290 render_thread ? render_thread->input_handler_manager() : NULL;
2291 if (input_handler_manager) {
2292 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2293 routing_id_, wheel_event, scroll_result);
2297 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2298 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2301 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2302 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2303 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2304 "mismatching enums: " #a)
2306 inline content::TouchAction& operator|=(content::TouchAction& a,
2307 content::TouchAction b) {
2308 a = static_cast<content::TouchAction>(static_cast<int>(a) |
2309 static_cast<int>(b));
2310 return a;
2313 void RenderWidget::setTouchAction(
2314 blink::WebTouchAction web_touch_action) {
2316 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2317 // when blink is emulating touch with mouse).
2318 if (handling_event_type_ != WebInputEvent::TouchStart)
2319 return;
2321 // Verify the same values are used by the types so we can cast between them.
2322 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2323 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2324 STATIC_ASSERT_WTI_ENUM_MATCH(PanLeft, PAN_LEFT);
2325 STATIC_ASSERT_WTI_ENUM_MATCH(PanRight, PAN_RIGHT);
2326 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2327 STATIC_ASSERT_WTI_ENUM_MATCH(PanUp, PAN_UP);
2328 STATIC_ASSERT_WTI_ENUM_MATCH(PanDown, PAN_DOWN);
2329 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2330 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2332 content::TouchAction content_touch_action =
2333 static_cast<content::TouchAction>(web_touch_action);
2334 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2337 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2338 #if defined(OS_ANDROID)
2339 text_field_is_dirty_ = true;
2340 #endif
2343 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2344 return true;
2347 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2348 RenderWidget::CreateGraphicsContext3D(bool compositor) {
2349 if (!webwidget_)
2350 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2351 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2352 switches::kDisableGpuCompositing))
2353 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2354 if (!RenderThreadImpl::current())
2355 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2356 CauseForGpuLaunch cause =
2357 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2358 scoped_refptr<GpuChannelHost> gpu_channel_host(
2359 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2360 if (!gpu_channel_host.get())
2361 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2363 // Explicitly disable antialiasing for the compositor. As of the time of
2364 // this writing, the only platform that supported antialiasing for the
2365 // compositor was Mac OS X, because the on-screen OpenGL context creation
2366 // code paths on Windows and Linux didn't yet have multisampling support.
2367 // Mac OS X essentially always behaves as though it's rendering offscreen.
2368 // Multisampling has a heavy cost especially on devices with relatively low
2369 // fill rate like most notebooks, and the Mac implementation would need to
2370 // be optimized to resolve directly into the IOSurface shared between the
2371 // GPU and browser processes. For these reasons and to avoid platform
2372 // disparities we explicitly disable antialiasing.
2373 blink::WebGraphicsContext3D::Attributes attributes;
2374 attributes.antialias = false;
2375 attributes.shareResources = true;
2376 attributes.noAutomaticFlushes = true;
2377 attributes.depth = false;
2378 attributes.stencil = false;
2379 bool lose_context_when_out_of_memory = true;
2380 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2381 #if defined(OS_ANDROID)
2382 // If we raster too fast we become upload bound, and pending
2383 // uploads consume memory. For maximum upload throughput, we would
2384 // want to allow for upload_throughput * pipeline_time of pending
2385 // uploads, after which we are just wasting memory. Since we don't
2386 // know our upload throughput yet, this just caps our memory usage.
2387 size_t divider = 1;
2388 if (base::SysInfo::IsLowEndDevice())
2389 divider = 6;
2390 // For reference Nexus10 can upload 1MB in about 2.5ms.
2391 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2392 // Deadline to draw a frame to achieve 60 frames per second.
2393 const size_t kMillisecondsPerFrame = 16;
2394 // Assuming a two frame deep pipeline between the CPU and the GPU.
2395 size_t max_transfer_buffer_usage_mb =
2396 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2397 static const size_t kBytesPerMegabyte = 1024 * 1024;
2398 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2399 // to avoid unnecessarily stalling the compositor thread.
2400 limits.mapped_memory_reclaim_limit =
2401 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2402 #endif
2403 if (compositor) {
2404 limits.command_buffer_size = 64 * 1024;
2405 limits.start_transfer_buffer_size = 64 * 1024;
2406 limits.min_transfer_buffer_size = 64 * 1024;
2409 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2410 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2411 GetURLForGraphicsContext3D(),
2412 gpu_channel_host.get(),
2413 attributes,
2414 lose_context_when_out_of_memory,
2415 limits,
2416 NULL));
2417 return context.Pass();
2420 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2421 render_frame_proxies_.AddObserver(proxy);
2424 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2425 render_frame_proxies_.RemoveObserver(proxy);
2428 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2429 render_frames_.AddObserver(frame);
2432 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2433 render_frames_.RemoveObserver(frame);
2436 #if defined(VIDEO_HOLE)
2437 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2438 video_hole_frames_.AddObserver(frame);
2441 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2442 video_hole_frames_.RemoveObserver(frame);
2444 #endif // defined(VIDEO_HOLE)
2446 } // namespace content