Fix a couple bugs in the settings_page_header wrt breadcrumbs.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob2b2dbf58db115e6027dc6d35f5a34418c8917e8c
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/WebPopupMenu.h"
69 #include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
70 #include "third_party/WebKit/public/web/WebRange.h"
71 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
72 #include "third_party/WebKit/public/web/WebView.h"
73 #include "third_party/skia/include/core/SkShader.h"
74 #include "ui/base/ui_base_switches.h"
75 #include "ui/gfx/geometry/point_conversions.h"
76 #include "ui/gfx/geometry/rect_conversions.h"
77 #include "ui/gfx/geometry/size_conversions.h"
78 #include "ui/gfx/skia_util.h"
79 #include "ui/gl/gl_switches.h"
80 #include "ui/surface/transport_dib.h"
82 #if defined(OS_ANDROID)
83 #include <android/keycodes.h>
84 #include "content/renderer/android/synchronous_compositor_factory.h"
85 #endif
87 #if defined(OS_POSIX)
88 #include "ipc/ipc_channel_posix.h"
89 #include "third_party/skia/include/core/SkMallocPixelRef.h"
90 #include "third_party/skia/include/core/SkPixelRef.h"
91 #endif // defined(OS_POSIX)
93 #include "third_party/WebKit/public/web/WebWidget.h"
95 using blink::WebCompositionUnderline;
96 using blink::WebCursorInfo;
97 using blink::WebDeviceEmulationParams;
98 using blink::WebGestureEvent;
99 using blink::WebInputEvent;
100 using blink::WebKeyboardEvent;
101 using blink::WebMouseEvent;
102 using blink::WebMouseWheelEvent;
103 using blink::WebNavigationPolicy;
104 using blink::WebNode;
105 using blink::WebPagePopup;
106 using blink::WebPoint;
107 using blink::WebPopupMenu;
108 using blink::WebPopupMenuInfo;
109 using blink::WebPopupType;
110 using blink::WebRange;
111 using blink::WebRect;
112 using blink::WebScreenInfo;
113 using blink::WebSize;
114 using blink::WebTextDirection;
115 using blink::WebTouchEvent;
116 using blink::WebTouchPoint;
117 using blink::WebVector;
118 using blink::WebWidget;
120 namespace {
122 typedef std::map<std::string, ui::TextInputMode> TextInputModeMap;
124 class TextInputModeMapSingleton {
125 public:
126 static TextInputModeMapSingleton* GetInstance() {
127 return Singleton<TextInputModeMapSingleton>::get();
129 TextInputModeMapSingleton() {
130 map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM;
131 map_["latin"] = ui::TEXT_INPUT_MODE_LATIN;
132 map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME;
133 map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE;
134 map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN;
135 map_["kana"] = ui::TEXT_INPUT_MODE_KANA;
136 map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA;
137 map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC;
138 map_["tel"] = ui::TEXT_INPUT_MODE_TEL;
139 map_["email"] = ui::TEXT_INPUT_MODE_EMAIL;
140 map_["url"] = ui::TEXT_INPUT_MODE_URL;
142 const TextInputModeMap& map() const { return map_; }
143 private:
144 TextInputModeMap map_;
146 friend struct DefaultSingletonTraits<TextInputModeMapSingleton>;
148 DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton);
151 ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) {
152 static TextInputModeMapSingleton* singleton =
153 TextInputModeMapSingleton::GetInstance();
154 TextInputModeMap::const_iterator it =
155 singleton->map().find(input_mode.utf8());
156 if (it == singleton->map().end())
157 return ui::TEXT_INPUT_MODE_DEFAULT;
158 return it->second;
161 // TODO(brianderson): Replace the hard-coded threshold with a fraction of
162 // the BeginMainFrame interval.
163 // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to
164 // be spent in input hanlders before input starts getting throttled.
165 const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166;
167 int64 GetEventLatencyMicros(const WebInputEvent& event, base::TimeTicks now) {
168 return (now - base::TimeDelta::FromSecondsD(event.timeStampSeconds))
169 .ToInternalValue();
172 void LogInputEventLatencyUma(const WebInputEvent& event, base::TimeTicks now) {
173 UMA_HISTOGRAM_CUSTOM_COUNTS(
174 "Event.AggregatedLatency.Renderer2",
175 GetEventLatencyMicros(event, now),
177 10000000,
178 100);
180 #define CASE_TYPE(t) \
181 case WebInputEvent::t: \
182 UMA_HISTOGRAM_CUSTOM_COUNTS( \
183 "Event.Latency.Renderer2." #t, \
184 GetEventLatencyMicros(event, now), \
185 1, \
186 10000000, \
187 100); \
188 break;
190 switch(event.type) {
191 CASE_TYPE(Undefined);
192 CASE_TYPE(MouseDown);
193 CASE_TYPE(MouseUp);
194 CASE_TYPE(MouseMove);
195 CASE_TYPE(MouseEnter);
196 CASE_TYPE(MouseLeave);
197 CASE_TYPE(ContextMenu);
198 CASE_TYPE(MouseWheel);
199 CASE_TYPE(RawKeyDown);
200 CASE_TYPE(KeyDown);
201 CASE_TYPE(KeyUp);
202 CASE_TYPE(Char);
203 CASE_TYPE(GestureScrollBegin);
204 CASE_TYPE(GestureScrollEnd);
205 CASE_TYPE(GestureScrollUpdate);
206 CASE_TYPE(GestureFlingStart);
207 CASE_TYPE(GestureFlingCancel);
208 CASE_TYPE(GestureShowPress);
209 CASE_TYPE(GestureTap);
210 CASE_TYPE(GestureTapUnconfirmed);
211 CASE_TYPE(GestureTapDown);
212 CASE_TYPE(GestureTapCancel);
213 CASE_TYPE(GestureDoubleTap);
214 CASE_TYPE(GestureTwoFingerTap);
215 CASE_TYPE(GestureLongPress);
216 CASE_TYPE(GestureLongTap);
217 CASE_TYPE(GesturePinchBegin);
218 CASE_TYPE(GesturePinchEnd);
219 CASE_TYPE(GesturePinchUpdate);
220 CASE_TYPE(TouchStart);
221 CASE_TYPE(TouchMove);
222 CASE_TYPE(TouchEnd);
223 CASE_TYPE(TouchCancel);
224 default:
225 // Must include default to let blink::WebInputEvent add new event types
226 // before they're added here.
227 DLOG(WARNING) << "Unhandled WebInputEvent type: " << event.type;
228 break;
231 #undef CASE_TYPE
234 } // namespace
236 namespace content {
238 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
240 class RenderWidget::ScreenMetricsEmulator {
241 public:
242 ScreenMetricsEmulator(
243 RenderWidget* widget,
244 const WebDeviceEmulationParams& params);
245 virtual ~ScreenMetricsEmulator();
247 // Scale and offset used to convert between host coordinates
248 // and webwidget coordinates.
249 float scale() { return scale_; }
250 gfx::PointF offset() { return offset_; }
251 gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
252 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
253 const WebScreenInfo& original_screen_info() { return original_screen_info_; }
255 void ChangeEmulationParams(
256 const WebDeviceEmulationParams& params);
258 // The following methods alter handlers' behavior for messages related to
259 // widget size and position.
260 void OnResizeMessage(const ViewMsg_Resize_Params& params);
261 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
262 const gfx::Rect& window_screen_rect);
263 void OnShowContextMenu(ContextMenuParams* params);
264 gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
266 private:
267 void Reapply();
268 void Apply(bool top_controls_shrink_blink_size,
269 float top_controls_height,
270 gfx::Rect resizer_rect,
271 bool is_fullscreen_granted,
272 blink::WebDisplayMode display_mode);
274 RenderWidget* widget_;
276 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
277 WebDeviceEmulationParams params_;
279 // The computed scale and offset used to fit widget into browser window.
280 float scale_;
281 gfx::PointF offset_;
283 // Widget rect as passed to webwidget.
284 gfx::Rect applied_widget_rect_;
286 // Original values to restore back after emulation ends.
287 gfx::Size original_size_;
288 gfx::Size original_physical_backing_size_;
289 gfx::Size original_visible_viewport_size_;
290 blink::WebScreenInfo original_screen_info_;
291 gfx::Rect original_view_screen_rect_;
292 gfx::Rect original_window_screen_rect_;
295 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
296 RenderWidget* widget,
297 const WebDeviceEmulationParams& params)
298 : widget_(widget),
299 params_(params),
300 scale_(1.f) {
301 original_size_ = widget_->size_;
302 original_physical_backing_size_ = widget_->physical_backing_size_;
303 original_visible_viewport_size_ = widget_->visible_viewport_size_;
304 original_screen_info_ = widget_->screen_info_;
305 original_view_screen_rect_ = widget_->view_screen_rect_;
306 original_window_screen_rect_ = widget_->window_screen_rect_;
307 Apply(widget_->top_controls_shrink_blink_size_,
308 widget_->top_controls_height_,
309 widget_->resizer_rect_,
310 widget_->is_fullscreen_granted_,
311 widget_->display_mode_);
314 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
315 widget_->screen_info_ = original_screen_info_;
317 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
318 widget_->SetScreenMetricsEmulationParameters(false, params_);
319 widget_->view_screen_rect_ = original_view_screen_rect_;
320 widget_->window_screen_rect_ = original_window_screen_rect_;
321 widget_->Resize(original_size_,
322 original_physical_backing_size_,
323 widget_->top_controls_shrink_blink_size_,
324 widget_->top_controls_height_,
325 original_visible_viewport_size_,
326 widget_->resizer_rect_,
327 widget_->is_fullscreen_granted_,
328 widget_->display_mode_,
329 NO_RESIZE_ACK);
332 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
333 const WebDeviceEmulationParams& params) {
334 params_ = params;
335 Reapply();
338 void RenderWidget::ScreenMetricsEmulator::Reapply() {
339 Apply(widget_->top_controls_shrink_blink_size_,
340 widget_->top_controls_height_,
341 widget_->resizer_rect_,
342 widget_->is_fullscreen_granted_,
343 widget_->display_mode_);
346 void RenderWidget::ScreenMetricsEmulator::Apply(
347 bool top_controls_shrink_blink_size,
348 float top_controls_height,
349 gfx::Rect resizer_rect,
350 bool is_fullscreen_granted,
351 blink::WebDisplayMode display_mode) {
352 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
353 if (!applied_widget_rect_.width())
354 applied_widget_rect_.set_width(original_size_.width());
355 if (!applied_widget_rect_.height())
356 applied_widget_rect_.set_height(original_size_.height());
358 if (params_.fitToView && !original_size_.IsEmpty()) {
359 int original_width = std::max(original_size_.width(), 1);
360 int original_height = std::max(original_size_.height(), 1);
361 float width_ratio =
362 static_cast<float>(applied_widget_rect_.width()) / original_width;
363 float height_ratio =
364 static_cast<float>(applied_widget_rect_.height()) / original_height;
365 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
366 scale_ = 1.f / ratio;
368 // Center emulated view inside available view space.
369 offset_.set_x(
370 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
371 offset_.set_y(
372 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
373 } else {
374 scale_ = params_.scale;
375 offset_.SetPoint(params_.offset.x, params_.offset.y);
378 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
379 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
380 widget_->screen_info_.rect = original_screen_info_.rect;
381 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
382 widget_->window_screen_rect_ = original_window_screen_rect_;
383 } else {
384 applied_widget_rect_.set_origin(gfx::Point(0, 0));
385 widget_->screen_info_.rect = applied_widget_rect_;
386 widget_->screen_info_.availableRect = applied_widget_rect_;
387 widget_->window_screen_rect_ = applied_widget_rect_;
390 float applied_device_scale_factor = params_.deviceScaleFactor ?
391 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
392 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
394 // Pass three emulation parameters to the blink side:
395 // - we keep the real device scale factor in compositor to produce sharp image
396 // even when emulating different scale factor;
397 // - in order to fit into view, WebView applies offset and scale to the
398 // root layer.
399 blink::WebDeviceEmulationParams modified_params = params_;
400 modified_params.deviceScaleFactor = original_screen_info_.deviceScaleFactor;
401 modified_params.offset = blink::WebFloatPoint(offset_.x(), offset_.y());
402 modified_params.scale = scale_;
403 widget_->SetScreenMetricsEmulationParameters(true, modified_params);
405 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
406 widget_->view_screen_rect_ = applied_widget_rect_;
408 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
409 original_size_, original_screen_info_.deviceScaleFactor));
410 widget_->Resize(applied_widget_rect_.size(),
411 physical_backing_size,
412 top_controls_shrink_blink_size,
413 top_controls_height,
414 applied_widget_rect_.size(),
415 resizer_rect,
416 is_fullscreen_granted,
417 display_mode,
418 NO_RESIZE_ACK);
421 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
422 const ViewMsg_Resize_Params& params) {
423 bool need_ack = params.new_size != original_size_ &&
424 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
425 original_size_ = params.new_size;
426 original_physical_backing_size_ = params.physical_backing_size;
427 original_screen_info_ = params.screen_info;
428 original_visible_viewport_size_ = params.visible_viewport_size;
429 Apply(params.top_controls_shrink_blink_size,
430 params.top_controls_height,
431 params.resizer_rect,
432 params.is_fullscreen_granted,
433 params.display_mode);
435 if (need_ack) {
436 widget_->set_next_paint_is_resize_ack();
437 if (widget_->compositor_)
438 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
442 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
443 const gfx::Rect& view_screen_rect,
444 const gfx::Rect& window_screen_rect) {
445 original_view_screen_rect_ = view_screen_rect;
446 original_window_screen_rect_ = window_screen_rect;
447 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
448 Reapply();
451 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
452 ContextMenuParams* params) {
453 params->x *= scale_;
454 params->x += offset_.x();
455 params->y *= scale_;
456 params->y += offset_.y();
459 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
460 const gfx::Rect& anchor) {
461 gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
462 scaled.set_x(scaled.x() + offset_.x());
463 scaled.set_y(scaled.y() + offset_.y());
464 return scaled;
467 // RenderWidget ---------------------------------------------------------------
469 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
470 const blink::WebScreenInfo& screen_info,
471 bool swapped_out,
472 bool hidden,
473 bool never_visible)
474 : routing_id_(MSG_ROUTING_NONE),
475 surface_id_(0),
476 compositor_deps_(nullptr),
477 webwidget_(nullptr),
478 opener_id_(MSG_ROUTING_NONE),
479 init_complete_(false),
480 top_controls_shrink_blink_size_(false),
481 top_controls_height_(0.f),
482 next_paint_flags_(0),
483 auto_resize_mode_(false),
484 need_update_rect_for_auto_resize_(false),
485 did_show_(false),
486 is_hidden_(hidden),
487 never_visible_(never_visible),
488 is_fullscreen_granted_(false),
489 display_mode_(blink::WebDisplayModeUndefined),
490 has_focus_(false),
491 handling_input_event_(false),
492 handling_ime_event_(false),
493 handling_event_type_(WebInputEvent::Undefined),
494 ignore_ack_for_mouse_move_from_debugger_(false),
495 closing_(false),
496 host_closing_(false),
497 is_swapped_out_(swapped_out),
498 for_oopif_(false),
499 input_method_is_active_(false),
500 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
501 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
502 text_input_flags_(0),
503 can_compose_inline_(true),
504 popup_type_(popup_type),
505 pending_window_rect_count_(0),
506 suppress_next_char_events_(false),
507 screen_info_(screen_info),
508 device_scale_factor_(screen_info_.deviceScaleFactor),
509 current_event_latency_info_(NULL),
510 next_output_surface_id_(0),
511 #if defined(OS_ANDROID)
512 text_field_is_dirty_(false),
513 outstanding_ime_acks_(0),
514 body_background_color_(SK_ColorWHITE),
515 #endif
516 popup_origin_scale_for_emulation_(0.f),
517 frame_swap_message_queue_(new FrameSwapMessageQueue()),
518 resizing_mode_selector_(new ResizingModeSelector()),
519 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
520 has_host_context_menu_location_(false) {
521 if (!swapped_out)
522 RenderProcess::current()->AddRefProcess();
523 DCHECK(RenderThread::Get());
524 device_color_profile_.push_back('0');
527 RenderWidget::~RenderWidget() {
528 DCHECK(!webwidget_) << "Leaking our WebWidget!";
530 // If we are swapped out, we have released already.
531 if (!is_swapped_out_ && RenderProcess::current())
532 RenderProcess::current()->ReleaseProcess();
535 // static
536 RenderWidget* RenderWidget::Create(int32 opener_id,
537 CompositorDependencies* compositor_deps,
538 blink::WebPopupType popup_type,
539 const blink::WebScreenInfo& screen_info) {
540 DCHECK(opener_id != MSG_ROUTING_NONE);
541 scoped_refptr<RenderWidget> widget(
542 new RenderWidget(popup_type, screen_info, false, false, false));
543 if (widget->Init(opener_id, compositor_deps)) { // adds reference on success.
544 return widget.get();
546 return NULL;
549 // static
550 RenderWidget* RenderWidget::CreateForFrame(
551 int routing_id,
552 int surface_id,
553 bool hidden,
554 const blink::WebScreenInfo& screen_info,
555 CompositorDependencies* compositor_deps,
556 blink::WebLocalFrame* frame) {
557 CHECK_NE(routing_id, MSG_ROUTING_NONE);
558 scoped_refptr<RenderWidget> widget(new RenderWidget(
559 blink::WebPopupTypeNone, screen_info, false, hidden, false));
560 widget->routing_id_ = routing_id;
561 widget->surface_id_ = surface_id;
562 widget->compositor_deps_ = compositor_deps;
563 widget->for_oopif_ = true;
564 // DoInit increments the reference count on |widget|, keeping it alive after
565 // this function returns.
566 if (widget->DoInit(MSG_ROUTING_NONE, compositor_deps,
567 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
568 nullptr)) {
569 widget->CompleteInit();
570 return widget.get();
572 return nullptr;
575 // static
576 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
577 switch (render_widget->popup_type_) {
578 case blink::WebPopupTypeNone: // Nothing to create.
579 break;
580 case blink::WebPopupTypeSelect:
581 case blink::WebPopupTypeSuggestion:
582 return WebPopupMenu::create(render_widget);
583 case blink::WebPopupTypePage:
584 return WebPagePopup::create(render_widget);
585 default:
586 NOTREACHED();
588 return NULL;
591 // static
592 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
593 RenderWidget* render_widget,
594 blink::WebLocalFrame* frame) {
595 return blink::WebFrameWidget::create(render_widget, frame);
598 bool RenderWidget::Init(int32 opener_id,
599 CompositorDependencies* compositor_deps) {
600 return DoInit(opener_id, compositor_deps, RenderWidget::CreateWebWidget(this),
601 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
602 &routing_id_, &surface_id_));
605 bool RenderWidget::DoInit(int32 opener_id,
606 CompositorDependencies* compositor_deps,
607 WebWidget* web_widget,
608 IPC::SyncMessage* create_widget_message) {
609 DCHECK(!webwidget_);
611 if (opener_id != MSG_ROUTING_NONE)
612 opener_id_ = opener_id;
614 compositor_deps_ = compositor_deps;
615 webwidget_ = web_widget;
617 bool result = true;
618 if (create_widget_message)
619 result = RenderThread::Get()->Send(create_widget_message);
621 if (result) {
622 RenderThread::Get()->AddRoute(routing_id_, this);
623 // Take a reference on behalf of the RenderThread. This will be balanced
624 // when we receive ViewMsg_Close.
625 AddRef();
626 if (RenderThreadImpl::current()) {
627 RenderThreadImpl::current()->WidgetCreated();
628 if (is_hidden_)
629 RenderThreadImpl::current()->WidgetHidden();
631 return true;
632 } else {
633 // The above Send can fail when the tab is closing.
634 return false;
638 // This is used to complete pending inits and non-pending inits.
639 void RenderWidget::CompleteInit() {
640 DCHECK(routing_id_ != MSG_ROUTING_NONE);
642 init_complete_ = true;
644 if (compositor_)
645 StartCompositor();
647 Send(new ViewHostMsg_RenderViewReady(routing_id_));
650 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
651 // We should only toggle between states.
652 DCHECK(is_swapped_out_ != is_swapped_out);
653 is_swapped_out_ = is_swapped_out;
655 // If we are swapping out, we will call ReleaseProcess, allowing the process
656 // to exit if all of its RenderViews are swapped out. We wait until the
657 // WasSwappedOut call to do this, to allow the unload handler to finish.
658 // If we are swapping in, we call AddRefProcess to prevent the process from
659 // exiting.
660 if (!is_swapped_out_)
661 RenderProcess::current()->AddRefProcess();
664 void RenderWidget::WasSwappedOut() {
665 // If we have been swapped out and no one else is using this process,
666 // it's safe to exit now.
667 CHECK(is_swapped_out_);
668 RenderProcess::current()->ReleaseProcess();
671 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
672 ScreenMetricsEmulator* emulator) {
673 popup_origin_scale_for_emulation_ = emulator->scale();
674 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
675 popup_screen_origin_for_emulation_ = gfx::Point(
676 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
677 emulator->original_screen_rect().origin().y() + emulator->offset().y());
678 screen_info_ = emulator->original_screen_info();
679 device_scale_factor_ = screen_info_.deviceScaleFactor;
682 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
683 if (screen_metrics_emulator_)
684 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
685 return anchor;
688 void RenderWidget::SetScreenMetricsEmulationParameters(
689 bool enabled,
690 const blink::WebDeviceEmulationParams& params) {
691 // This is only supported in RenderView.
692 NOTREACHED();
695 #if defined(OS_MACOSX) || defined(OS_ANDROID)
696 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
697 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
698 popup->SetOriginScaleAndOffsetForEmulation(
699 emulator->scale(), emulator->offset());
701 #endif
703 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
704 if (screen_metrics_emulator_)
705 screen_metrics_emulator_->OnShowContextMenu(params);
708 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
709 if (compositor_) {
710 // Regardless of whether threaded compositing is enabled, always
711 // use this mechanism to force the compositor to redraw. However,
712 // the invalidation code path below is still needed for the
713 // non-threaded case.
714 compositor_->SetNeedsForcedRedraw();
716 scheduleComposite();
719 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
720 bool handled = true;
721 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
722 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
723 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
724 OnCursorVisibilityChange)
725 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
726 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
727 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
728 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
729 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
730 OnSyntheticGestureCompleted)
731 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
732 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
733 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
734 IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation,
735 OnEnableDeviceEmulation)
736 IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation,
737 OnDisableDeviceEmulation)
738 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
739 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
740 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
741 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
742 IPC_MESSAGE_HANDLER(ViewMsg_SetInputMethodActive, OnSetInputMethodActive)
743 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
744 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
745 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
746 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
747 IPC_MESSAGE_HANDLER(ViewMsg_SetSurfaceIdNamespace, OnSetSurfaceIdNamespace)
748 #if defined(OS_ANDROID)
749 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
750 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
751 #endif
752 IPC_MESSAGE_UNHANDLED(handled = false)
753 IPC_END_MESSAGE_MAP()
754 return handled;
757 bool RenderWidget::Send(IPC::Message* message) {
758 // Don't send any messages after the browser has told us to close, and filter
759 // most outgoing messages while swapped out.
760 if ((is_swapped_out_ &&
761 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
762 closing_) {
763 delete message;
764 return false;
767 // If given a messsage without a routing ID, then assign our routing ID.
768 if (message->routing_id() == MSG_ROUTING_NONE)
769 message->set_routing_id(routing_id_);
771 return RenderThread::Get()->Send(message);
774 void RenderWidget::Resize(const gfx::Size& new_size,
775 const gfx::Size& physical_backing_size,
776 bool top_controls_shrink_blink_size,
777 float top_controls_height,
778 const gfx::Size& visible_viewport_size,
779 const gfx::Rect& resizer_rect,
780 bool is_fullscreen_granted,
781 blink::WebDisplayMode display_mode,
782 const ResizeAck resize_ack) {
783 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
784 // A resize ack shouldn't be requested if we have not ACK'd the previous
785 // one.
786 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
787 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
790 // Ignore this during shutdown.
791 if (!webwidget_)
792 return;
794 if (compositor_) {
795 compositor_->setViewportSize(new_size, physical_backing_size);
798 physical_backing_size_ = physical_backing_size;
799 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
800 top_controls_height_ = top_controls_height;
801 visible_viewport_size_ = visible_viewport_size;
802 resizer_rect_ = resizer_rect;
804 // NOTE: We may have entered fullscreen mode without changing our size.
805 bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted;
806 if (fullscreen_change)
807 WillToggleFullscreen();
808 is_fullscreen_granted_ = is_fullscreen_granted;
809 display_mode_ = display_mode;
811 webwidget_->setTopControlsHeight(top_controls_height,
812 top_controls_shrink_blink_size_);
814 if (size_ != new_size) {
815 size_ = new_size;
817 // When resizing, we want to wait to paint before ACK'ing the resize. This
818 // ensures that we only resize as fast as we can paint. We only need to
819 // send an ACK if we are resized to a non-empty rect.
820 webwidget_->resize(new_size);
823 webwidget()->resizePinchViewport(gfx::Size(
824 visible_viewport_size.width(),
825 visible_viewport_size.height()));
827 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
828 // In this case there is no paint/composite and therefore no
829 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
830 // ack through a fake ViewHostMsg_UpdateRect or a different message.
831 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
834 // Send the Resize_ACK flag once we paint again if requested.
835 if (resize_ack == SEND_RESIZE_ACK)
836 set_next_paint_is_resize_ack();
838 if (fullscreen_change)
839 DidToggleFullscreen();
841 // If a resize ack is requested and it isn't set-up, then no more resizes will
842 // come in and in general things will go wrong.
843 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
846 void RenderWidget::SetWindowRectSynchronously(
847 const gfx::Rect& new_window_rect) {
848 Resize(new_window_rect.size(),
849 new_window_rect.size(),
850 top_controls_shrink_blink_size_,
851 top_controls_height_,
852 new_window_rect.size(),
853 gfx::Rect(),
854 is_fullscreen_granted_,
855 display_mode_,
856 NO_RESIZE_ACK);
857 view_screen_rect_ = new_window_rect;
858 window_screen_rect_ = new_window_rect;
859 if (!did_show_)
860 initial_rect_ = new_window_rect;
863 void RenderWidget::OnClose() {
864 if (closing_)
865 return;
866 NotifyOnClose();
867 closing_ = true;
869 // Browser correspondence is no longer needed at this point.
870 if (routing_id_ != MSG_ROUTING_NONE) {
871 RenderThread::Get()->RemoveRoute(routing_id_);
872 SetHidden(false);
873 if (RenderThreadImpl::current())
874 RenderThreadImpl::current()->WidgetDestroyed();
877 // If there is a Send call on the stack, then it could be dangerous to close
878 // now. Post a task that only gets invoked when there are no nested message
879 // loops.
880 RenderThread::Get()->GetTaskRunner()->PostNonNestableTask(
881 FROM_HERE, base::Bind(&RenderWidget::Close, this));
883 // Balances the AddRef taken when we called AddRoute.
884 Release();
887 // Got a response from the browser after the renderer decided to create a new
888 // view.
889 void RenderWidget::OnCreatingNewAck() {
890 DCHECK(routing_id_ != MSG_ROUTING_NONE);
892 CompleteInit();
895 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
896 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
897 return;
899 if (screen_metrics_emulator_) {
900 screen_metrics_emulator_->OnResizeMessage(params);
901 return;
904 bool orientation_changed =
905 screen_info_.orientationAngle != params.screen_info.orientationAngle;
907 screen_info_ = params.screen_info;
908 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
909 Resize(params.new_size,
910 params.physical_backing_size,
911 params.top_controls_shrink_blink_size,
912 params.top_controls_height,
913 params.visible_viewport_size,
914 params.resizer_rect,
915 params.is_fullscreen_granted,
916 params.display_mode,
917 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
919 if (orientation_changed)
920 OnOrientationChange();
923 void RenderWidget::OnEnableDeviceEmulation(
924 const blink::WebDeviceEmulationParams& params) {
925 if (!screen_metrics_emulator_)
926 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
927 else
928 screen_metrics_emulator_->ChangeEmulationParams(params);
931 void RenderWidget::OnDisableDeviceEmulation() {
932 screen_metrics_emulator_.reset();
935 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
936 SetDeviceColorProfile(color_profile);
939 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
940 if (resizer_rect_ == resizer_rect)
941 return;
942 resizer_rect_ = resizer_rect;
943 if (webwidget_)
944 webwidget_->didChangeWindowResizerRect();
947 void RenderWidget::OnWasHidden() {
948 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
949 // Go into a mode where we stop generating paint and scrolling events.
950 SetHidden(true);
951 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
952 WasHidden());
955 void RenderWidget::OnWasShown(bool needs_repainting,
956 const ui::LatencyInfo& latency_info) {
957 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
958 // During shutdown we can just ignore this message.
959 if (!webwidget_)
960 return;
962 // See OnWasHidden
963 SetHidden(false);
964 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
965 WasShown());
967 if (!needs_repainting)
968 return;
970 // Generate a full repaint.
971 if (compositor_) {
972 ui::LatencyInfo swap_latency_info(latency_info);
973 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
974 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
975 compositor_->SetNeedsForcedRedraw();
977 scheduleComposite();
980 void RenderWidget::OnRequestMoveAck() {
981 DCHECK(pending_window_rect_count_);
982 pending_window_rect_count_--;
985 GURL RenderWidget::GetURLForGraphicsContext3D() {
986 return GURL();
989 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
990 // For widgets that are never visible, we don't start the compositor, so we
991 // never get a request for a cc::OutputSurface.
992 DCHECK(!never_visible_);
994 #if defined(OS_ANDROID)
995 if (SynchronousCompositorFactory* factory =
996 SynchronousCompositorFactory::GetInstance()) {
997 return factory->CreateOutputSurface(routing_id(),
998 frame_swap_message_queue_);
1000 #endif
1002 const base::CommandLine& command_line =
1003 *base::CommandLine::ForCurrentProcess();
1004 bool use_software = fallback;
1005 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1006 use_software = true;
1008 scoped_refptr<ContextProviderCommandBuffer> context_provider;
1009 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
1010 if (!use_software) {
1011 context_provider = ContextProviderCommandBuffer::Create(
1012 CreateGraphicsContext3D(), RENDER_COMPOSITOR_CONTEXT);
1013 if (!context_provider.get()) {
1014 // Cause the compositor to wait and try again.
1015 return scoped_ptr<cc::OutputSurface>();
1018 worker_context_provider = ContextProviderCommandBuffer::Create(
1019 CreateGraphicsContext3D(), RENDER_WORKER_CONTEXT);
1020 if (!worker_context_provider.get()) {
1021 // Cause the compositor to wait and try again.
1022 return scoped_ptr<cc::OutputSurface>();
1026 uint32 output_surface_id = next_output_surface_id_++;
1027 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1028 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1029 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1030 routing_id(), output_surface_id, context_provider,
1031 worker_context_provider, frame_swap_message_queue_));
1033 if (!context_provider.get()) {
1034 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1035 new cc::SoftwareOutputDevice());
1037 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1038 routing_id(), output_surface_id, nullptr, nullptr,
1039 software_device.Pass(), frame_swap_message_queue_, true));
1042 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1043 // Composite-to-mailbox is currently used for layout tests in order to cause
1044 // them to draw inside in the renderer to do the readback there. This should
1045 // no longer be the case when crbug.com/311404 is fixed.
1046 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1047 cc::ResourceFormat format = cc::RGBA_8888;
1048 if (base::SysInfo::IsLowEndDevice())
1049 format = cc::RGB_565;
1050 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1051 routing_id(), output_surface_id, context_provider,
1052 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1053 frame_swap_message_queue_, format));
1055 bool use_swap_compositor_frame_message = false;
1056 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1057 routing_id(), output_surface_id, context_provider,
1058 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1059 frame_swap_message_queue_, use_swap_compositor_frame_message));
1062 void RenderWidget::OnSwapBuffersAborted() {
1063 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1064 // Schedule another frame so the compositor learns about it.
1065 scheduleComposite();
1068 void RenderWidget::OnSwapBuffersPosted() {
1069 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1072 void RenderWidget::OnSwapBuffersComplete() {
1073 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1075 // Notify subclasses that composited rendering was flushed to the screen.
1076 DidFlushPaint();
1079 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1080 const ui::LatencyInfo& latency_info,
1081 bool is_keyboard_shortcut) {
1082 base::AutoReset<bool> handling_input_event_resetter(
1083 &handling_input_event_, true);
1084 if (!input_event)
1085 return;
1086 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1087 &handling_event_type_, input_event->type);
1088 #if defined(OS_ANDROID)
1089 // On Android, when a key is pressed or sent from the Keyboard using IME,
1090 // |AdapterInputConnection| generates input key events to make sure all JS
1091 // listeners that monitor KeyUp and KeyDown events receive the proper key
1092 // code. Since this input key event comes from IME, we need to set the
1093 // IME event guard here to make sure it does not interfere with other IME
1094 // events.
1095 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1096 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1097 const WebKeyboardEvent& key_event =
1098 *static_cast<const WebKeyboardEvent*>(input_event);
1099 // Some keys are special and it's essential that no events get blocked.
1100 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1101 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1102 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1103 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1104 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1105 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1106 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1108 #endif
1110 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
1111 &latency_info);
1113 base::TimeTicks start_time;
1114 if (base::TimeTicks::IsHighResolution())
1115 start_time = base::TimeTicks::Now();
1117 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1118 "event", WebInputEventTraits::GetName(input_event->type));
1119 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1120 TRACE_EVENT_FLOW_STEP0(
1121 "input,benchmark",
1122 "LatencyInfo.Flow",
1123 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
1124 "HanldeInputEventMain");
1126 // If we don't have a high res timer, these metrics won't be accurate enough
1127 // to be worth collecting. Note that this does introduce some sampling bias.
1128 if (!start_time.is_null())
1129 LogInputEventLatencyUma(*input_event, start_time);
1131 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1132 ui::LatencyInfo swap_latency_info(latency_info);
1133 if (compositor_) {
1134 latency_info_swap_promise_monitor =
1135 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1136 .Pass();
1139 bool prevent_default = false;
1140 if (WebInputEvent::isMouseEventType(input_event->type)) {
1141 const WebMouseEvent& mouse_event =
1142 *static_cast<const WebMouseEvent*>(input_event);
1143 TRACE_EVENT2("renderer", "HandleMouseMove",
1144 "x", mouse_event.x, "y", mouse_event.y);
1145 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1146 prevent_default = WillHandleMouseEvent(mouse_event);
1149 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1150 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1151 #if defined(OS_ANDROID)
1152 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1153 // case it should behave like a select key (i.e. causing a click if a button
1154 // is focused). However, if a text field is focused (2), its intended
1155 // behavior is to just show the IME and don't propagate the key.
1156 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1157 // when clicked on an input text field and cause the form submit if clicked
1158 // when the submit button is focused, but not vice-versa.
1159 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1160 // but at this point we have to swallow the event for the scenario (2).
1161 const WebKeyboardEvent& key_event =
1162 *static_cast<const WebKeyboardEvent*>(input_event);
1163 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1164 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1165 OnShowImeIfNeeded();
1166 prevent_default = true;
1168 #endif
1171 if (WebInputEvent::isGestureEventType(input_event->type)) {
1172 const WebGestureEvent& gesture_event =
1173 *static_cast<const WebGestureEvent*>(input_event);
1174 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1175 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1178 bool processed = prevent_default;
1179 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1180 suppress_next_char_events_ = false;
1181 if (!processed && webwidget_)
1182 processed = webwidget_->handleInputEvent(*input_event);
1185 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1186 // it's not processed by webkit, then we need to suppress the upcoming Char
1187 // events.
1188 if (!processed && is_keyboard_shortcut)
1189 suppress_next_char_events_ = true;
1191 InputEventAckState ack_result = processed ?
1192 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1193 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1194 const WebTouchEvent& touch_event =
1195 *static_cast<const WebTouchEvent*>(input_event);
1196 // Hit-test for all the pressed touch points. If there is a touch-handler
1197 // for any of the touch points, then the renderer should continue to receive
1198 // touch events.
1199 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1200 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1201 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1202 HasTouchEventHandlersAt(
1203 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1204 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1205 break;
1210 // Send mouse wheel events and their disposition to the compositor thread, so
1211 // that they can be used to produce the elastic overscroll effect on Mac.
1212 if (input_event->type == WebInputEvent::MouseWheel) {
1213 ObserveWheelEventAndResult(
1214 static_cast<const WebMouseWheelEvent&>(*input_event), processed);
1217 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1219 // If we don't have a fast and accurate Now(), we assume the input handlers
1220 // are heavy and rate limit them.
1221 bool rate_limiting_wanted =
1222 input_event->type == WebInputEvent::MouseMove ||
1223 input_event->type == WebInputEvent::MouseWheel;
1224 if (rate_limiting_wanted && !start_time.is_null()) {
1225 base::TimeTicks end_time = base::TimeTicks::Now();
1226 total_input_handling_time_this_frame_ += (end_time - start_time);
1227 rate_limiting_wanted =
1228 total_input_handling_time_this_frame_.InMicroseconds() >
1229 kInputHandlingTimeThrottlingThresholdMicroseconds;
1232 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1234 // Note that we can't use handling_event_type_ here since it will be overriden
1235 // by reentrant calls for events after the paused one.
1236 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1237 input_event->type == WebInputEvent::MouseMove;
1238 if (WebInputEventTraits::WillReceiveAckFromRenderer(*input_event) &&
1239 !no_ack) {
1240 InputEventAck ack(input_event->type, ack_result, swap_latency_info,
1241 WebInputEventTraits::GetUniqueTouchEventId(*input_event));
1242 scoped_ptr<IPC::Message> response(
1243 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1244 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1245 // We want to rate limit the input events in this case, so we'll wait for
1246 // painting to finish before ACKing this message.
1247 TRACE_EVENT_INSTANT0("renderer",
1248 "RenderWidget::OnHandleInputEvent ack throttled",
1249 TRACE_EVENT_SCOPE_THREAD);
1250 if (pending_input_event_ack_) {
1251 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1252 pending_input_event_ack_.get());
1253 // As two different kinds of events could cause us to postpone an ack
1254 // we send it now, if we have one pending. The Browser should never
1255 // send us the same kind of event we are delaying the ack for.
1256 Send(pending_input_event_ack_.release());
1258 pending_input_event_ack_ = response.Pass();
1259 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1260 pending_input_event_ack_.get());
1261 if (compositor_)
1262 compositor_->NotifyInputThrottledUntilCommit();
1263 } else {
1264 Send(response.release());
1267 if (!no_ack && RenderThreadImpl::current()) {
1268 RenderThreadImpl::current()
1269 ->GetRendererScheduler()
1270 ->DidHandleInputEventOnMainThread(*input_event);
1272 if (input_event->type == WebInputEvent::MouseMove)
1273 ignore_ack_for_mouse_move_from_debugger_ = false;
1275 #if defined(OS_ANDROID)
1276 // Allow the IME to be shown when the focus changes as a consequence
1277 // of a processed touch end event.
1278 if (input_event->type == WebInputEvent::TouchEnd && processed)
1279 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1280 #elif defined(USE_AURA)
1281 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1282 // change.
1283 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1284 input_event->type == WebInputEvent::MouseUp)) {
1285 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1287 #endif
1289 if (!prevent_default) {
1290 if (WebInputEvent::isKeyboardEventType(input_event->type))
1291 DidHandleKeyEvent();
1292 if (WebInputEvent::isMouseEventType(input_event->type))
1293 DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1296 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1297 // virtual keyboard.
1298 #if !defined(OS_ANDROID)
1299 // Virtual keyboard is not supported, so react to focus change immediately.
1300 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1301 input_event->type == WebInputEvent::MouseUp)) {
1302 FocusChangeComplete();
1304 #endif
1307 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1308 if (webwidget_)
1309 webwidget_->setCursorVisibilityState(is_visible);
1312 void RenderWidget::OnMouseCaptureLost() {
1313 if (webwidget_)
1314 webwidget_->mouseCaptureLost();
1317 void RenderWidget::OnSetFocus(bool enable) {
1318 has_focus_ = enable;
1319 if (webwidget_)
1320 webwidget_->setFocus(enable);
1323 void RenderWidget::ClearFocus() {
1324 // We may have got the focus from the browser before this gets processed, in
1325 // which case we do not want to unfocus ourself.
1326 if (!has_focus_ && webwidget_)
1327 webwidget_->setFocus(false);
1330 void RenderWidget::FlushPendingInputEventAck() {
1331 if (pending_input_event_ack_) {
1332 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1333 pending_input_event_ack_.get());
1334 Send(pending_input_event_ack_.release());
1336 total_input_handling_time_this_frame_ = base::TimeDelta();
1339 ///////////////////////////////////////////////////////////////////////////////
1340 // WebWidgetClient
1342 void RenderWidget::didAutoResize(const WebSize& new_size) {
1343 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1344 size_ = new_size;
1346 if (resizing_mode_selector_->is_synchronous_mode()) {
1347 WebRect new_pos(rootWindowRect().x,
1348 rootWindowRect().y,
1349 new_size.width,
1350 new_size.height);
1351 view_screen_rect_ = new_pos;
1352 window_screen_rect_ = new_pos;
1355 AutoResizeCompositor();
1357 if (!resizing_mode_selector_->is_synchronous_mode())
1358 need_update_rect_for_auto_resize_ = true;
1362 void RenderWidget::AutoResizeCompositor() {
1363 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1364 device_scale_factor_));
1365 if (compositor_)
1366 compositor_->setViewportSize(size_, physical_backing_size_);
1369 void RenderWidget::initializeLayerTreeView() {
1370 DCHECK(!host_closing_);
1372 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1373 compositor_->setViewportSize(size_, physical_backing_size_);
1374 if (init_complete_)
1375 StartCompositor();
1378 void RenderWidget::WillCloseLayerTreeView() {
1379 if (host_closing_)
1380 return;
1382 // Prevent new compositors or output surfaces from being created.
1383 host_closing_ = true;
1385 // Always send this notification to prevent new layer tree views from
1386 // being created, even if one hasn't been created yet.
1387 if (webwidget_)
1388 webwidget_->willCloseLayerTreeView();
1391 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1392 return compositor_.get();
1395 void RenderWidget::willBeginCompositorFrame() {
1396 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1398 // The following two can result in further layout and possibly
1399 // enable GPU acceleration so they need to be called before any painting
1400 // is done.
1401 UpdateTextInputType();
1402 #if defined(OS_ANDROID)
1403 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1404 #endif
1405 UpdateSelectionBounds();
1408 void RenderWidget::didBecomeReadyForAdditionalInput() {
1409 TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1410 FlushPendingInputEventAck();
1413 void RenderWidget::DidCommitCompositorFrame() {
1414 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1415 DidCommitCompositorFrame());
1416 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1417 DidCommitCompositorFrame());
1418 #if defined(VIDEO_HOLE)
1419 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1420 DidCommitCompositorFrame());
1421 #endif // defined(VIDEO_HOLE)
1424 // static
1425 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1426 IPC::Message* msg,
1427 MessageDeliveryPolicy policy,
1428 FrameSwapMessageQueue* frame_swap_message_queue,
1429 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1430 int source_frame_number) {
1431 bool first_message_for_frame = false;
1432 frame_swap_message_queue->QueueMessageForFrame(policy,
1433 source_frame_number,
1434 make_scoped_ptr(msg),
1435 &first_message_for_frame);
1436 if (first_message_for_frame) {
1437 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1438 sync_message_filter, frame_swap_message_queue, source_frame_number));
1439 return promise;
1441 return nullptr;
1444 void RenderWidget::QueueMessage(IPC::Message* msg,
1445 MessageDeliveryPolicy policy) {
1446 // RenderThreadImpl::current() is NULL in some tests.
1447 if (!compositor_ || !RenderThreadImpl::current()) {
1448 Send(msg);
1449 return;
1452 scoped_ptr<cc::SwapPromise> swap_promise =
1453 QueueMessageImpl(msg,
1454 policy,
1455 frame_swap_message_queue_.get(),
1456 RenderThreadImpl::current()->sync_message_filter(),
1457 compositor_->GetSourceFrameNumber());
1459 if (swap_promise) {
1460 compositor_->QueueSwapPromise(swap_promise.Pass());
1461 // Request a commit. This might either A) request a commit ahead of time
1462 // or B) request a commit which is not needed because there are not
1463 // pending updates. If B) then the commit will be skipped and the swap
1464 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1465 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1466 // can_cancel_commit is not unset.
1467 compositor_->SetNeedsUpdateLayers();
1471 void RenderWidget::didCommitAndDrawCompositorFrame() {
1472 // NOTE: Tests may break if this event is renamed or moved. See
1473 // tab_capture_performancetest.cc.
1474 TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1475 // Notify subclasses that we initiated the paint operation.
1476 DidInitiatePaint();
1479 void RenderWidget::didCompleteSwapBuffers() {
1480 TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
1482 // Notify subclasses threaded composited rendering was flushed to the screen.
1483 DidFlushPaint();
1485 if (!next_paint_flags_ &&
1486 !need_update_rect_for_auto_resize_ &&
1487 !plugin_window_moves_.size()) {
1488 return;
1491 ViewHostMsg_UpdateRect_Params params;
1492 params.view_size = size_;
1493 params.plugin_window_moves.swap(plugin_window_moves_);
1494 params.flags = next_paint_flags_;
1496 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1497 next_paint_flags_ = 0;
1498 need_update_rect_for_auto_resize_ = false;
1501 void RenderWidget::scheduleComposite() {
1502 if (compositor_ &&
1503 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1504 compositor_->setNeedsAnimate();
1508 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1509 // TODO(darin): Eliminate this temporary.
1510 WebCursor cursor;
1511 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1512 // Only send a SetCursor message if we need to make a change.
1513 if (!current_cursor_.IsEqual(cursor)) {
1514 current_cursor_ = cursor;
1515 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1519 // We are supposed to get a single call to Show for a newly created RenderWidget
1520 // that was created via RenderWidget::CreateWebView. So, we wait until this
1521 // point to dispatch the ShowWidget message.
1523 // This method provides us with the information about how to display the newly
1524 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1526 void RenderWidget::show(WebNavigationPolicy) {
1527 DCHECK(!did_show_) << "received extraneous Show call";
1528 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1529 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1531 if (did_show_)
1532 return;
1534 did_show_ = true;
1535 // NOTE: initial_rect_ may still have its default values at this point, but
1536 // that's okay. It'll be ignored if as_popup is false, or the browser
1537 // process will impose a default position otherwise.
1538 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1539 SetPendingWindowRect(initial_rect_);
1542 void RenderWidget::didFocus() {
1545 void RenderWidget::didBlur() {
1548 void RenderWidget::DoDeferredClose() {
1549 WillCloseLayerTreeView();
1550 Send(new ViewHostMsg_Close(routing_id_));
1553 void RenderWidget::NotifyOnClose() {
1554 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose());
1557 void RenderWidget::closeWidgetSoon() {
1558 if (is_swapped_out_) {
1559 // This widget is currently swapped out, and the active widget is in a
1560 // different process. Have the browser route the close request to the
1561 // active widget instead, so that the correct unload handlers are run.
1562 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1563 return;
1566 // If a page calls window.close() twice, we'll end up here twice, but that's
1567 // OK. It is safe to send multiple Close messages.
1569 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1570 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1571 // could be closed before the JS finishes executing. So instead, post a
1572 // message back to the message loop, which won't run until the JS is
1573 // complete, and then the Close message can be sent.
1574 RenderThread::Get()->GetTaskRunner()->PostTask(
1575 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1578 void RenderWidget::QueueSyntheticGesture(
1579 scoped_ptr<SyntheticGestureParams> gesture_params,
1580 const SyntheticGestureCompletionCallback& callback) {
1581 DCHECK(!callback.is_null());
1583 pending_synthetic_gesture_callbacks_.push(callback);
1585 SyntheticGesturePacket gesture_packet;
1586 gesture_packet.set_gesture_params(gesture_params.Pass());
1588 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1591 void RenderWidget::Close() {
1592 screen_metrics_emulator_.reset();
1593 WillCloseLayerTreeView();
1594 compositor_.reset();
1595 if (webwidget_) {
1596 webwidget_->close();
1597 webwidget_ = NULL;
1601 WebRect RenderWidget::windowRect() {
1602 if (pending_window_rect_count_)
1603 return pending_window_rect_;
1605 return view_screen_rect_;
1608 void RenderWidget::setToolTipText(const blink::WebString& text,
1609 WebTextDirection hint) {
1610 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1613 void RenderWidget::setWindowRect(const WebRect& rect) {
1614 WebRect window_rect = rect;
1615 if (popup_origin_scale_for_emulation_) {
1616 float scale = popup_origin_scale_for_emulation_;
1617 window_rect.x = popup_screen_origin_for_emulation_.x() +
1618 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1619 window_rect.y = popup_screen_origin_for_emulation_.y() +
1620 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1623 if (!resizing_mode_selector_->is_synchronous_mode()) {
1624 if (did_show_) {
1625 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1626 SetPendingWindowRect(window_rect);
1627 } else {
1628 initial_rect_ = window_rect;
1630 } else {
1631 SetWindowRectSynchronously(window_rect);
1635 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1636 pending_window_rect_ = rect;
1637 pending_window_rect_count_++;
1640 WebRect RenderWidget::rootWindowRect() {
1641 if (pending_window_rect_count_) {
1642 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1643 // the RootWindowRect is probably going to return wrong results since the
1644 // browser may not have processed the Move yet. There isn't really anything
1645 // good to do in this case, and it shouldn't happen - since this size is
1646 // only really needed for windowToScreen, which is only used for Popups.
1647 return pending_window_rect_;
1650 return window_screen_rect_;
1653 WebRect RenderWidget::windowResizerRect() {
1654 return resizer_rect_;
1657 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1658 // To prevent this renderer process from sending unnecessary IPC messages to
1659 // a browser process, we permit the renderer process to send IPC messages
1660 // only during the input method attached to the browser process is active.
1661 input_method_is_active_ = is_active;
1664 void RenderWidget::OnImeSetComposition(
1665 const base::string16& text,
1666 const std::vector<WebCompositionUnderline>& underlines,
1667 int selection_start, int selection_end) {
1668 if (!ShouldHandleImeEvent())
1669 return;
1670 ImeEventGuard guard(this);
1671 if (!webwidget_->setComposition(
1672 text, WebVector<WebCompositionUnderline>(underlines),
1673 selection_start, selection_end)) {
1674 // If we failed to set the composition text, then we need to let the browser
1675 // process to cancel the input method's ongoing composition session, to make
1676 // sure we are in a consistent state.
1677 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1679 UpdateCompositionInfo(true);
1682 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1683 const gfx::Range& replacement_range,
1684 bool keep_selection) {
1685 if (!ShouldHandleImeEvent())
1686 return;
1687 ImeEventGuard guard(this);
1688 handling_input_event_ = true;
1689 if (text.length())
1690 webwidget_->confirmComposition(text);
1691 else if (keep_selection)
1692 webwidget_->confirmComposition(WebWidget::KeepSelection);
1693 else
1694 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1695 handling_input_event_ = false;
1696 UpdateCompositionInfo(true);
1699 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1700 // During shutdown we can just ignore this message.
1701 if (!webwidget_)
1702 return;
1704 // Even if the browser provides an empty damage rect, it's still expecting to
1705 // receive a repaint ack so just damage the entire widget bounds.
1706 if (size_to_paint.IsEmpty()) {
1707 size_to_paint = size_;
1710 set_next_paint_is_repaint_ack();
1711 if (compositor_)
1712 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1715 void RenderWidget::OnSyntheticGestureCompleted() {
1716 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1718 pending_synthetic_gesture_callbacks_.front().Run();
1719 pending_synthetic_gesture_callbacks_.pop();
1722 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1723 if (!webwidget_)
1724 return;
1725 webwidget_->setTextDirection(direction);
1728 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1729 const gfx::Rect& window_screen_rect) {
1730 if (screen_metrics_emulator_) {
1731 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1732 view_screen_rect, window_screen_rect);
1733 } else {
1734 view_screen_rect_ = view_screen_rect;
1735 window_screen_rect_ = window_screen_rect;
1737 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1740 void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) {
1741 if (compositor_)
1742 compositor_->SetSurfaceIdNamespace(surface_id_namespace);
1745 void RenderWidget::showImeIfNeeded() {
1746 OnShowImeIfNeeded();
1749 void RenderWidget::OnShowImeIfNeeded() {
1750 #if defined(OS_ANDROID) || defined(USE_AURA)
1751 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1752 #endif
1754 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1755 // virtual keyboard.
1756 #if !defined(OS_ANDROID)
1757 FocusChangeComplete();
1758 #endif
1761 #if defined(OS_ANDROID)
1762 void RenderWidget::IncrementOutstandingImeEventAcks() {
1763 ++outstanding_ime_acks_;
1766 void RenderWidget::OnImeEventAck() {
1767 --outstanding_ime_acks_;
1768 DCHECK(outstanding_ime_acks_ >= 0);
1770 #endif
1772 bool RenderWidget::ShouldHandleImeEvent() {
1773 #if defined(OS_ANDROID)
1774 return !!webwidget_ && outstanding_ime_acks_ == 0;
1775 #else
1776 return !!webwidget_;
1777 #endif
1780 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1781 if (handling_event_type_ == WebInputEvent::MouseMove) {
1782 // If we pause multiple times during a single mouse move event, we should
1783 // only send ACK once.
1784 if (!ignore_ack_for_mouse_move_from_debugger_) {
1785 InputEventAck ack(handling_event_type_, INPUT_EVENT_ACK_STATE_CONSUMED);
1786 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1787 return true;
1790 return false;
1793 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1794 ignore_ack_for_mouse_move_from_debugger_ = true;
1797 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1798 if (device_scale_factor_ == device_scale_factor)
1799 return;
1801 device_scale_factor_ = device_scale_factor;
1802 scheduleComposite();
1805 bool RenderWidget::SetDeviceColorProfile(
1806 const std::vector<char>& color_profile) {
1807 if (device_color_profile_ == color_profile)
1808 return false;
1810 device_color_profile_ = color_profile;
1811 return true;
1814 void RenderWidget::ResetDeviceColorProfileForTesting() {
1815 if (!device_color_profile_.empty())
1816 device_color_profile_.clear();
1817 device_color_profile_.push_back('0');
1820 void RenderWidget::OnOrientationChange() {
1823 gfx::Vector2d RenderWidget::GetScrollOffset() {
1824 // Bare RenderWidgets don't support scroll offset.
1825 return gfx::Vector2d();
1828 void RenderWidget::SetHidden(bool hidden) {
1829 if (is_hidden_ == hidden)
1830 return;
1832 // The status has changed. Tell the RenderThread about it and ensure
1833 // throttled acks are released in case frame production ceases.
1834 is_hidden_ = hidden;
1835 FlushPendingInputEventAck();
1837 if (is_hidden_)
1838 RenderThreadImpl::current()->WidgetHidden();
1839 else
1840 RenderThreadImpl::current()->WidgetRestored();
1843 void RenderWidget::WillToggleFullscreen() {
1844 if (!webwidget_)
1845 return;
1847 if (is_fullscreen_granted_) {
1848 webwidget_->willExitFullScreen();
1849 } else {
1850 webwidget_->willEnterFullScreen();
1854 void RenderWidget::DidToggleFullscreen() {
1855 if (!webwidget_)
1856 return;
1858 if (is_fullscreen_granted_) {
1859 webwidget_->didEnterFullScreen();
1860 } else {
1861 webwidget_->didExitFullScreen();
1865 bool RenderWidget::next_paint_is_resize_ack() const {
1866 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1869 void RenderWidget::set_next_paint_is_resize_ack() {
1870 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1873 void RenderWidget::set_next_paint_is_repaint_ack() {
1874 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1877 static bool IsDateTimeInput(ui::TextInputType type) {
1878 return type == ui::TEXT_INPUT_TYPE_DATE ||
1879 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1880 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1881 type == ui::TEXT_INPUT_TYPE_MONTH ||
1882 type == ui::TEXT_INPUT_TYPE_TIME ||
1883 type == ui::TEXT_INPUT_TYPE_WEEK;
1887 void RenderWidget::StartHandlingImeEvent() {
1888 DCHECK(!handling_ime_event_);
1889 handling_ime_event_ = true;
1892 void RenderWidget::FinishHandlingImeEvent() {
1893 DCHECK(handling_ime_event_);
1894 handling_ime_event_ = false;
1895 // While handling an ime event, text input state and selection bounds updates
1896 // are ignored. These must explicitly be updated once finished handling the
1897 // ime event.
1898 UpdateSelectionBounds();
1899 #if defined(OS_ANDROID)
1900 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1901 #endif
1904 void RenderWidget::UpdateTextInputType() {
1905 // On Windows, not only an IME but also an on-screen keyboard relies on the
1906 // latest TextInputType to optimize its layout and functionality. Thus
1907 // |input_method_is_active_| is no longer an appropriate condition to suppress
1908 // TextInputTypeChanged IPC on Windows.
1909 // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
1910 // on other platforms as well as Windows if the overhead is acceptable.
1911 #if !defined(OS_WIN)
1912 if (!input_method_is_active_)
1913 return;
1914 #endif
1916 ui::TextInputType new_type = GetTextInputType();
1917 if (IsDateTimeInput(new_type))
1918 return; // Not considered as a text input field in WebKit/Chromium.
1920 bool new_can_compose_inline = CanComposeInline();
1922 blink::WebTextInputInfo new_info;
1923 if (webwidget_)
1924 new_info = webwidget_->textInputInfo();
1925 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1926 int new_flags = new_info.flags;
1928 if (text_input_type_ != new_type
1929 || can_compose_inline_ != new_can_compose_inline
1930 || text_input_mode_ != new_mode
1931 || text_input_flags_ != new_flags) {
1932 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1933 new_type,
1934 new_mode,
1935 new_can_compose_inline,
1936 new_flags));
1937 text_input_type_ = new_type;
1938 can_compose_inline_ = new_can_compose_inline;
1939 text_input_mode_ = new_mode;
1940 text_input_flags_ = new_flags;
1944 #if defined(OS_ANDROID) || defined(USE_AURA)
1945 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1946 ChangeSource change_source) {
1947 if (handling_ime_event_)
1948 return;
1949 if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1950 return;
1951 ui::TextInputType new_type = GetTextInputType();
1952 if (IsDateTimeInput(new_type))
1953 return; // Not considered as a text input field in WebKit/Chromium.
1955 blink::WebTextInputInfo new_info;
1956 if (webwidget_)
1957 new_info = webwidget_->textInputInfo();
1959 bool new_can_compose_inline = CanComposeInline();
1961 // Only sends text input params if they are changed or if the ime should be
1962 // shown.
1963 if (show_ime == SHOW_IME_IF_NEEDED ||
1964 (text_input_type_ != new_type ||
1965 text_input_info_ != new_info ||
1966 can_compose_inline_ != new_can_compose_inline)
1967 #if defined(OS_ANDROID)
1968 || text_field_is_dirty_
1969 #endif
1971 ViewHostMsg_TextInputState_Params p;
1972 p.type = new_type;
1973 p.flags = new_info.flags;
1974 p.value = new_info.value.utf8();
1975 p.selection_start = new_info.selectionStart;
1976 p.selection_end = new_info.selectionEnd;
1977 p.composition_start = new_info.compositionStart;
1978 p.composition_end = new_info.compositionEnd;
1979 p.can_compose_inline = new_can_compose_inline;
1980 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1981 #if defined(USE_AURA)
1982 p.is_non_ime_change = true;
1983 #endif
1984 #if defined(OS_ANDROID)
1985 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1986 text_field_is_dirty_;
1987 if (p.is_non_ime_change)
1988 IncrementOutstandingImeEventAcks();
1989 text_field_is_dirty_ = false;
1990 #endif
1991 #if defined(USE_AURA)
1992 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1993 new_type,
1994 text_input_mode_,
1995 new_can_compose_inline,
1996 new_info.flags));
1997 #endif
1998 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
2000 text_input_info_ = new_info;
2001 text_input_type_ = new_type;
2002 can_compose_inline_ = new_can_compose_inline;
2003 text_input_flags_ = new_info.flags;
2006 #endif
2008 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
2009 WebRect focus_webrect;
2010 WebRect anchor_webrect;
2011 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
2012 *focus = focus_webrect;
2013 *anchor = anchor_webrect;
2016 void RenderWidget::UpdateSelectionBounds() {
2017 if (!webwidget_)
2018 return;
2019 if (handling_ime_event_)
2020 return;
2022 // With composited selection updates, the selection bounds will be reported
2023 // directly by the compositor, in which case explicit IPC selection
2024 // notifications should be suppressed.
2025 if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
2026 ViewHostMsg_SelectionBounds_Params params;
2027 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2028 if (selection_anchor_rect_ != params.anchor_rect ||
2029 selection_focus_rect_ != params.focus_rect) {
2030 selection_anchor_rect_ = params.anchor_rect;
2031 selection_focus_rect_ = params.focus_rect;
2032 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2033 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2034 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2038 UpdateCompositionInfo(false);
2041 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2042 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2043 static_assert(int(blink::WebTextInputType##a) \
2044 == int(ui::TEXT_INPUT_TYPE_##b), \
2045 "mismatching enums: " #a)
2047 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2048 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2049 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2050 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2051 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2052 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2053 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2054 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2055 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2056 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2057 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2058 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2059 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2060 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2061 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2062 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2063 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2065 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2066 blink::WebTextInputType type) {
2067 // Check the type is in the range representable by ui::TextInputType.
2068 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2069 "blink::WebTextInputType and ui::TextInputType not synchronized";
2070 return static_cast<ui::TextInputType>(type);
2073 ui::TextInputType RenderWidget::GetTextInputType() {
2074 if (webwidget_)
2075 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2076 return ui::TEXT_INPUT_TYPE_NONE;
2079 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2080 #if defined(OS_ANDROID)
2081 // TODO(yukawa): Start sending character bounds when the browser side
2082 // implementation becomes ready (crbug.com/424866).
2083 #else
2084 gfx::Range range = gfx::Range();
2085 if (should_update_range) {
2086 GetCompositionRange(&range);
2087 } else {
2088 range = composition_range_;
2090 std::vector<gfx::Rect> character_bounds;
2091 GetCompositionCharacterBounds(&character_bounds);
2093 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2094 return;
2095 composition_character_bounds_ = character_bounds;
2096 composition_range_ = range;
2097 Send(new InputHostMsg_ImeCompositionRangeChanged(
2098 routing_id(), composition_range_, composition_character_bounds_));
2099 #endif
2102 void RenderWidget::GetCompositionCharacterBounds(
2103 std::vector<gfx::Rect>* bounds) {
2104 DCHECK(bounds);
2105 bounds->clear();
2108 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2109 size_t location, length;
2110 if (webwidget_->compositionRange(&location, &length)) {
2111 range->set_start(location);
2112 range->set_end(location + length);
2113 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2114 range->set_start(location);
2115 range->set_end(location + length);
2116 } else {
2117 *range = gfx::Range::InvalidRange();
2121 bool RenderWidget::ShouldUpdateCompositionInfo(
2122 const gfx::Range& range,
2123 const std::vector<gfx::Rect>& bounds) {
2124 if (composition_range_ != range)
2125 return true;
2126 if (bounds.size() != composition_character_bounds_.size())
2127 return true;
2128 for (size_t i = 0; i < bounds.size(); ++i) {
2129 if (bounds[i] != composition_character_bounds_[i])
2130 return true;
2132 return false;
2135 #if defined(OS_ANDROID)
2136 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2137 // If not initialized, default to white. Note that 0 is different from black
2138 // as black still has alpha 0xFF.
2139 if (!bg_color)
2140 bg_color = SK_ColorWHITE;
2142 if (bg_color != body_background_color_) {
2143 body_background_color_ = bg_color;
2144 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2148 bool RenderWidget::DoesRecordFullLayer() const {
2149 SynchronousCompositorFactory* synchronous_compositor_factory =
2150 SynchronousCompositorFactory::GetInstance();
2152 // We assume that the absence of synchronous_compositor_factory
2153 // means we are in Chrome. In chrome, we want to clip, i.e.
2154 // *not* to record the full layer.
2155 if (!synchronous_compositor_factory)
2156 return false;
2158 return synchronous_compositor_factory->RecordFullLayer();
2160 #endif
2162 bool RenderWidget::CanComposeInline() {
2163 return true;
2166 WebScreenInfo RenderWidget::screenInfo() {
2167 return screen_info_;
2170 float RenderWidget::deviceScaleFactor() {
2171 return device_scale_factor_;
2174 void RenderWidget::resetInputMethod() {
2175 if (!input_method_is_active_)
2176 return;
2178 ImeEventGuard guard(this);
2179 // If the last text input type is not None, then we should finish any
2180 // ongoing composition regardless of the new text input type.
2181 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2182 // If a composition text exists, then we need to let the browser process
2183 // to cancel the input method's ongoing composition session.
2184 if (webwidget_->confirmComposition())
2185 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2188 UpdateCompositionInfo(true);
2191 #if defined(OS_ANDROID)
2192 void RenderWidget::showUnhandledTapUIIfNeeded(
2193 const WebPoint& tapped_position,
2194 const WebNode& tapped_node,
2195 bool page_changed) {
2196 DCHECK(handling_input_event_);
2197 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2198 !tapped_node.isContentEditable() &&
2199 !tapped_node.isInsideFocusableElementOrARIAWidget();
2200 if (should_trigger) {
2201 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2202 tapped_position.x, tapped_position.y));
2205 #endif
2207 void RenderWidget::didHandleGestureEvent(
2208 const WebGestureEvent& event,
2209 bool event_cancelled) {
2210 #if defined(OS_ANDROID) || defined(USE_AURA)
2211 if (event_cancelled)
2212 return;
2213 if (event.type == WebInputEvent::GestureTap) {
2214 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2215 } else if (event.type == WebInputEvent::GestureLongPress) {
2216 DCHECK(webwidget_);
2217 if (webwidget_->textInputInfo().value.isEmpty())
2218 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2219 else
2220 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2222 #endif
2225 void RenderWidget::StartCompositor() {
2226 // For widgets that are never visible, we don't need the compositor to run
2227 // at all.
2228 if (never_visible_)
2229 return;
2230 // In tests without a RenderThreadImpl, don't set ready as this kicks
2231 // off creating output surfaces that the test can't create.
2232 if (!RenderThreadImpl::current())
2233 return;
2234 compositor_->StartCompositor();
2237 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2238 size_t i = 0;
2239 for (; i < plugin_window_moves_.size(); ++i) {
2240 if (plugin_window_moves_[i].window == move.window) {
2241 if (move.rects_valid) {
2242 plugin_window_moves_[i] = move;
2243 } else {
2244 plugin_window_moves_[i].visible = move.visible;
2246 break;
2250 if (i == plugin_window_moves_.size())
2251 plugin_window_moves_.push_back(move);
2254 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2255 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2256 i != plugin_window_moves_.end(); ++i) {
2257 if (i->window == window) {
2258 plugin_window_moves_.erase(i);
2259 break;
2265 RenderWidgetCompositor* RenderWidget::compositor() const {
2266 return compositor_.get();
2269 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2270 return false;
2273 bool RenderWidget::WillHandleGestureEvent(
2274 const blink::WebGestureEvent& event) {
2275 return false;
2278 void RenderWidget::ObserveWheelEventAndResult(
2279 const blink::WebMouseWheelEvent& wheel_event,
2280 bool event_processed) {
2281 if (!compositor_deps_->IsElasticOverscrollEnabled())
2282 return;
2284 // Blink does not accurately compute scroll bubbling or overscroll. For now,
2285 // assume that an unprocessed event was entirely an overscroll, and that a
2286 // processed event was entirely scroll.
2287 // TODO(ccameron): Retrieve an accurate scroll result from Blink.
2288 // http://crbug.com/442859
2289 cc::InputHandlerScrollResult scroll_result;
2290 if (event_processed) {
2291 scroll_result.did_scroll = true;
2292 } else {
2293 scroll_result.did_overscroll_root = true;
2294 scroll_result.unused_scroll_delta =
2295 gfx::Vector2dF(-wheel_event.deltaX, -wheel_event.deltaY);
2298 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2299 InputHandlerManager* input_handler_manager =
2300 render_thread ? render_thread->input_handler_manager() : NULL;
2301 if (input_handler_manager) {
2302 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2303 routing_id_, wheel_event, scroll_result);
2307 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2308 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2311 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2312 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2313 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2314 "mismatching enums: " #a)
2316 inline content::TouchAction& operator|=(content::TouchAction& a,
2317 content::TouchAction b) {
2318 a = static_cast<content::TouchAction>(static_cast<int>(a) |
2319 static_cast<int>(b));
2320 return a;
2323 void RenderWidget::setTouchAction(
2324 blink::WebTouchAction web_touch_action) {
2326 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2327 // when blink is emulating touch with mouse).
2328 if (handling_event_type_ != WebInputEvent::TouchStart)
2329 return;
2331 // Verify the same values are used by the types so we can cast between them.
2332 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2333 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2334 STATIC_ASSERT_WTI_ENUM_MATCH(PanLeft, PAN_LEFT);
2335 STATIC_ASSERT_WTI_ENUM_MATCH(PanRight, PAN_RIGHT);
2336 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2337 STATIC_ASSERT_WTI_ENUM_MATCH(PanUp, PAN_UP);
2338 STATIC_ASSERT_WTI_ENUM_MATCH(PanDown, PAN_DOWN);
2339 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2340 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2342 content::TouchAction content_touch_action =
2343 static_cast<content::TouchAction>(web_touch_action);
2344 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2347 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2348 #if defined(OS_ANDROID)
2349 text_field_is_dirty_ = true;
2350 #endif
2353 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2354 return true;
2357 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2358 RenderWidget::CreateGraphicsContext3D() {
2359 if (!webwidget_)
2360 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2361 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2362 switches::kDisableGpuCompositing))
2363 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2364 if (!RenderThreadImpl::current())
2365 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2366 CauseForGpuLaunch cause =
2367 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2368 scoped_refptr<GpuChannelHost> gpu_channel_host(
2369 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2370 if (!gpu_channel_host.get())
2371 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2373 // Explicitly disable antialiasing for the compositor. As of the time of
2374 // this writing, the only platform that supported antialiasing for the
2375 // compositor was Mac OS X, because the on-screen OpenGL context creation
2376 // code paths on Windows and Linux didn't yet have multisampling support.
2377 // Mac OS X essentially always behaves as though it's rendering offscreen.
2378 // Multisampling has a heavy cost especially on devices with relatively low
2379 // fill rate like most notebooks, and the Mac implementation would need to
2380 // be optimized to resolve directly into the IOSurface shared between the
2381 // GPU and browser processes. For these reasons and to avoid platform
2382 // disparities we explicitly disable antialiasing.
2383 blink::WebGraphicsContext3D::Attributes attributes;
2384 attributes.antialias = false;
2385 attributes.shareResources = true;
2386 attributes.noAutomaticFlushes = true;
2387 attributes.depth = false;
2388 attributes.stencil = false;
2389 bool lose_context_when_out_of_memory = true;
2390 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2391 #if defined(OS_ANDROID)
2392 // If we raster too fast we become upload bound, and pending
2393 // uploads consume memory. For maximum upload throughput, we would
2394 // want to allow for upload_throughput * pipeline_time of pending
2395 // uploads, after which we are just wasting memory. Since we don't
2396 // know our upload throughput yet, this just caps our memory usage.
2397 size_t divider = 1;
2398 if (base::SysInfo::IsLowEndDevice())
2399 divider = 6;
2400 // For reference Nexus10 can upload 1MB in about 2.5ms.
2401 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2402 // Deadline to draw a frame to achieve 60 frames per second.
2403 const size_t kMillisecondsPerFrame = 16;
2404 // Assuming a two frame deep pipeline between the CPU and the GPU.
2405 size_t max_transfer_buffer_usage_mb =
2406 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2407 static const size_t kBytesPerMegabyte = 1024 * 1024;
2408 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2409 // to avoid unnecessarily stalling the compositor thread.
2410 limits.mapped_memory_reclaim_limit =
2411 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2412 #endif
2414 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2415 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2416 GetURLForGraphicsContext3D(),
2417 gpu_channel_host.get(),
2418 attributes,
2419 lose_context_when_out_of_memory,
2420 limits,
2421 NULL));
2422 return context.Pass();
2425 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2426 render_frame_proxies_.AddObserver(proxy);
2429 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2430 render_frame_proxies_.RemoveObserver(proxy);
2433 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2434 render_frames_.AddObserver(frame);
2437 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2438 render_frames_.RemoveObserver(frame);
2441 #if defined(VIDEO_HOLE)
2442 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2443 video_hole_frames_.AddObserver(frame);
2446 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2447 video_hole_frames_.RemoveObserver(frame);
2449 #endif // defined(VIDEO_HOLE)
2451 } // namespace content