Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob1db3f45c4b73eda17e326ea8769c4d46aaf16024
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 current_event_latency_info_(NULL),
513 next_output_surface_id_(0),
514 #if defined(OS_ANDROID)
515 text_field_is_dirty_(false),
516 outstanding_ime_acks_(0),
517 body_background_color_(SK_ColorWHITE),
518 #endif
519 popup_origin_scale_for_emulation_(0.f),
520 frame_swap_message_queue_(new FrameSwapMessageQueue()),
521 resizing_mode_selector_(new ResizingModeSelector()),
522 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
523 has_host_context_menu_location_(false) {
524 if (!swapped_out)
525 RenderProcess::current()->AddRefProcess();
526 DCHECK(RenderThread::Get());
527 device_color_profile_.push_back('0');
530 RenderWidget::~RenderWidget() {
531 DCHECK(!webwidget_) << "Leaking our WebWidget!";
533 // If we are swapped out, we have released already.
534 if (!is_swapped_out_ && RenderProcess::current())
535 RenderProcess::current()->ReleaseProcess();
538 // static
539 RenderWidget* RenderWidget::Create(int32 opener_id,
540 CompositorDependencies* compositor_deps,
541 blink::WebPopupType popup_type,
542 const blink::WebScreenInfo& screen_info) {
543 DCHECK(opener_id != MSG_ROUTING_NONE);
544 scoped_refptr<RenderWidget> widget(new RenderWidget(
545 compositor_deps, popup_type, screen_info, false, false, false));
546 if (widget->Init(opener_id)) { // adds reference on success.
547 return widget.get();
549 return NULL;
552 // static
553 RenderWidget* RenderWidget::CreateForFrame(
554 int routing_id,
555 int surface_id,
556 bool hidden,
557 const blink::WebScreenInfo& screen_info,
558 CompositorDependencies* compositor_deps,
559 blink::WebLocalFrame* frame) {
560 CHECK_NE(routing_id, MSG_ROUTING_NONE);
561 scoped_refptr<RenderWidget> widget(
562 new RenderWidget(compositor_deps, blink::WebPopupTypeNone, screen_info,
563 false, hidden, false));
564 widget->routing_id_ = routing_id;
565 widget->surface_id_ = surface_id;
566 widget->for_oopif_ = true;
567 // DoInit increments the reference count on |widget|, keeping it alive after
568 // this function returns.
569 if (widget->DoInit(MSG_ROUTING_NONE,
570 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
571 nullptr)) {
572 widget->CompleteInit();
573 return widget.get();
575 return nullptr;
578 // static
579 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
580 RenderWidget* render_widget,
581 blink::WebLocalFrame* frame) {
582 return blink::WebFrameWidget::create(render_widget, frame);
585 // static
586 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
587 switch (render_widget->popup_type_) {
588 case blink::WebPopupTypeNone: // Nothing to create.
589 break;
590 case blink::WebPopupTypePage:
591 return WebPagePopup::create(render_widget);
592 default:
593 NOTREACHED();
595 return NULL;
598 void RenderWidget::CloseForFrame() {
599 OnClose();
602 bool RenderWidget::Init(int32 opener_id) {
603 return DoInit(opener_id, RenderWidget::CreateWebWidget(this),
604 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
605 &routing_id_, &surface_id_));
608 bool RenderWidget::DoInit(int32 opener_id,
609 WebWidget* web_widget,
610 IPC::SyncMessage* create_widget_message) {
611 DCHECK(!webwidget_);
613 if (opener_id != MSG_ROUTING_NONE)
614 opener_id_ = opener_id;
616 webwidget_ = web_widget;
618 bool result = true;
619 if (create_widget_message)
620 result = RenderThread::Get()->Send(create_widget_message);
622 if (result) {
623 RenderThread::Get()->AddRoute(routing_id_, this);
624 // Take a reference on behalf of the RenderThread. This will be balanced
625 // when we receive ViewMsg_Close.
626 AddRef();
627 if (RenderThreadImpl::current()) {
628 RenderThreadImpl::current()->WidgetCreated();
629 if (is_hidden_)
630 RenderThreadImpl::current()->WidgetHidden();
632 return true;
633 } else {
634 // The above Send can fail when the tab is closing.
635 return false;
639 // This is used to complete pending inits and non-pending inits.
640 void RenderWidget::CompleteInit() {
641 DCHECK(routing_id_ != MSG_ROUTING_NONE);
643 init_complete_ = true;
645 if (compositor_)
646 StartCompositor();
648 Send(new ViewHostMsg_RenderViewReady(routing_id_));
651 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
652 // We should only toggle between states.
653 DCHECK(is_swapped_out_ != is_swapped_out);
654 is_swapped_out_ = is_swapped_out;
656 // If we are swapping out, we will call ReleaseProcess, allowing the process
657 // to exit if all of its RenderViews are swapped out. We wait until the
658 // WasSwappedOut call to do this, to allow the unload handler to finish.
659 // If we are swapping in, we call AddRefProcess to prevent the process from
660 // exiting.
661 if (!is_swapped_out_)
662 RenderProcess::current()->AddRefProcess();
665 void RenderWidget::WasSwappedOut() {
666 // If we have been swapped out and no one else is using this process,
667 // it's safe to exit now.
668 CHECK(is_swapped_out_);
669 RenderProcess::current()->ReleaseProcess();
672 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
673 ScreenMetricsEmulator* emulator) {
674 popup_origin_scale_for_emulation_ = emulator->scale();
675 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
676 popup_screen_origin_for_emulation_ = gfx::Point(
677 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
678 emulator->original_screen_rect().origin().y() + emulator->offset().y());
679 screen_info_ = emulator->original_screen_info();
680 device_scale_factor_ = screen_info_.deviceScaleFactor;
683 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
684 if (screen_metrics_emulator_)
685 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
686 return anchor;
689 void RenderWidget::SetScreenMetricsEmulationParameters(
690 bool enabled,
691 const blink::WebDeviceEmulationParams& params) {
692 // This is only supported in RenderView.
693 NOTREACHED();
696 #if defined(OS_MACOSX) || defined(OS_ANDROID)
697 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
698 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
699 popup->SetOriginScaleAndOffsetForEmulation(
700 emulator->scale(), emulator->offset());
702 #endif
704 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
705 if (screen_metrics_emulator_)
706 screen_metrics_emulator_->OnShowContextMenu(params);
709 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
710 bool handled = true;
711 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
712 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
713 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
714 OnCursorVisibilityChange)
715 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
716 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
717 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
718 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
719 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
720 OnSyntheticGestureCompleted)
721 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
722 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
723 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
724 IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation,
725 OnEnableDeviceEmulation)
726 IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation,
727 OnDisableDeviceEmulation)
728 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
729 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
730 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
731 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
732 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
733 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
734 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
735 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
736 IPC_MESSAGE_HANDLER(ViewMsg_SetSurfaceIdNamespace, OnSetSurfaceIdNamespace)
737 #if defined(OS_ANDROID)
738 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
739 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
740 #endif
741 IPC_MESSAGE_UNHANDLED(handled = false)
742 IPC_END_MESSAGE_MAP()
743 return handled;
746 bool RenderWidget::Send(IPC::Message* message) {
747 // Don't send any messages after the browser has told us to close, and filter
748 // most outgoing messages while swapped out.
749 if ((is_swapped_out_ &&
750 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
751 closing_) {
752 delete message;
753 return false;
756 // If given a messsage without a routing ID, then assign our routing ID.
757 if (message->routing_id() == MSG_ROUTING_NONE)
758 message->set_routing_id(routing_id_);
760 return RenderThread::Get()->Send(message);
763 void RenderWidget::Resize(const gfx::Size& new_size,
764 const gfx::Size& physical_backing_size,
765 bool top_controls_shrink_blink_size,
766 float top_controls_height,
767 const gfx::Size& visible_viewport_size,
768 const gfx::Rect& resizer_rect,
769 bool is_fullscreen_granted,
770 blink::WebDisplayMode display_mode,
771 const ResizeAck resize_ack) {
772 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
773 // A resize ack shouldn't be requested if we have not ACK'd the previous
774 // one.
775 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
776 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
779 // Ignore this during shutdown.
780 if (!webwidget_)
781 return;
783 if (compositor_) {
784 compositor_->setViewportSize(new_size, physical_backing_size);
787 physical_backing_size_ = physical_backing_size;
788 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
789 top_controls_height_ = top_controls_height;
790 visible_viewport_size_ = visible_viewport_size;
791 resizer_rect_ = resizer_rect;
793 // NOTE: We may have entered fullscreen mode without changing our size.
794 bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted;
795 is_fullscreen_granted_ = is_fullscreen_granted;
796 display_mode_ = display_mode;
798 webwidget_->setTopControlsHeight(top_controls_height,
799 top_controls_shrink_blink_size_);
801 if (size_ != new_size) {
802 size_ = new_size;
804 // When resizing, we want to wait to paint before ACK'ing the resize. This
805 // ensures that we only resize as fast as we can paint. We only need to
806 // send an ACK if we are resized to a non-empty rect.
807 webwidget_->resize(new_size);
810 webwidget()->resizePinchViewport(gfx::Size(
811 visible_viewport_size.width(),
812 visible_viewport_size.height()));
814 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
815 // In this case there is no paint/composite and therefore no
816 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
817 // ack through a fake ViewHostMsg_UpdateRect or a different message.
818 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
821 // Send the Resize_ACK flag once we paint again if requested.
822 if (resize_ack == SEND_RESIZE_ACK)
823 set_next_paint_is_resize_ack();
825 if (fullscreen_change)
826 DidToggleFullscreen();
828 // If a resize ack is requested and it isn't set-up, then no more resizes will
829 // come in and in general things will go wrong.
830 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
833 void RenderWidget::SetWindowRectSynchronously(
834 const gfx::Rect& new_window_rect) {
835 Resize(new_window_rect.size(),
836 new_window_rect.size(),
837 top_controls_shrink_blink_size_,
838 top_controls_height_,
839 new_window_rect.size(),
840 gfx::Rect(),
841 is_fullscreen_granted_,
842 display_mode_,
843 NO_RESIZE_ACK);
844 view_screen_rect_ = new_window_rect;
845 window_screen_rect_ = new_window_rect;
846 if (!did_show_)
847 initial_rect_ = new_window_rect;
850 void RenderWidget::OnClose() {
851 DCHECK(content::RenderThread::Get());
852 if (closing_)
853 return;
854 NotifyOnClose();
855 closing_ = true;
857 // Browser correspondence is no longer needed at this point.
858 if (routing_id_ != MSG_ROUTING_NONE) {
859 RenderThread::Get()->RemoveRoute(routing_id_);
860 SetHidden(false);
861 if (RenderThreadImpl::current())
862 RenderThreadImpl::current()->WidgetDestroyed();
865 if (for_oopif_) {
866 // Widgets for frames may be created and closed at any time while the frame
867 // is alive. However, the closing process must happen synchronously. Frame
868 // widget and frames hold pointers to each other. If Close() is deferred to
869 // the message loop like in the non-frame widget case, WebWidget::close()
870 // can end up accessing members of an already-deleted frame.
871 Close();
872 } else {
873 // If there is a Send call on the stack, then it could be dangerous to close
874 // now. Post a task that only gets invoked when there are no nested message
875 // loops.
876 base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(
877 FROM_HERE, base::Bind(&RenderWidget::Close, this));
880 // Balances the AddRef taken when we called AddRoute.
881 Release();
884 // Got a response from the browser after the renderer decided to create a new
885 // view.
886 void RenderWidget::OnCreatingNewAck() {
887 DCHECK(routing_id_ != MSG_ROUTING_NONE);
889 CompleteInit();
892 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
893 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
894 return;
896 if (screen_metrics_emulator_) {
897 screen_metrics_emulator_->OnResizeMessage(params);
898 return;
901 bool orientation_changed =
902 screen_info_.orientationAngle != params.screen_info.orientationAngle;
904 screen_info_ = params.screen_info;
905 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
906 Resize(params.new_size,
907 params.physical_backing_size,
908 params.top_controls_shrink_blink_size,
909 params.top_controls_height,
910 params.visible_viewport_size,
911 params.resizer_rect,
912 params.is_fullscreen_granted,
913 params.display_mode,
914 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
916 if (orientation_changed)
917 OnOrientationChange();
920 void RenderWidget::OnEnableDeviceEmulation(
921 const blink::WebDeviceEmulationParams& params) {
922 if (!screen_metrics_emulator_)
923 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
924 else
925 screen_metrics_emulator_->ChangeEmulationParams(params);
928 void RenderWidget::OnDisableDeviceEmulation() {
929 screen_metrics_emulator_.reset();
932 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
933 SetDeviceColorProfile(color_profile);
936 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
937 if (resizer_rect_ == resizer_rect)
938 return;
939 resizer_rect_ = resizer_rect;
940 if (webwidget_)
941 webwidget_->didChangeWindowResizerRect();
944 void RenderWidget::OnWasHidden() {
945 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
946 // Go into a mode where we stop generating paint and scrolling events.
947 SetHidden(true);
948 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
949 WasHidden());
952 void RenderWidget::OnWasShown(bool needs_repainting,
953 const ui::LatencyInfo& latency_info) {
954 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
955 // During shutdown we can just ignore this message.
956 if (!webwidget_)
957 return;
959 // See OnWasHidden
960 SetHidden(false);
961 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
962 WasShown());
964 if (!needs_repainting)
965 return;
967 // Generate a full repaint.
968 if (compositor_) {
969 ui::LatencyInfo swap_latency_info(latency_info);
970 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
971 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
972 compositor_->SetNeedsForcedRedraw();
974 ScheduleComposite();
977 void RenderWidget::OnRequestMoveAck() {
978 DCHECK(pending_window_rect_count_);
979 pending_window_rect_count_--;
982 GURL RenderWidget::GetURLForGraphicsContext3D() {
983 return GURL();
986 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
987 // For widgets that are never visible, we don't start the compositor, so we
988 // never get a request for a cc::OutputSurface.
989 DCHECK(!never_visible_);
991 #if defined(OS_ANDROID)
992 if (SynchronousCompositorFactory* factory =
993 SynchronousCompositorFactory::GetInstance()) {
994 return factory->CreateOutputSurface(routing_id(),
995 frame_swap_message_queue_);
997 #endif
999 const base::CommandLine& command_line =
1000 *base::CommandLine::ForCurrentProcess();
1001 bool use_software = fallback;
1002 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1003 use_software = true;
1005 scoped_refptr<ContextProviderCommandBuffer> context_provider;
1006 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
1007 if (!use_software) {
1008 context_provider = ContextProviderCommandBuffer::Create(
1009 CreateGraphicsContext3D(), RENDER_COMPOSITOR_CONTEXT);
1010 if (!context_provider.get()) {
1011 // Cause the compositor to wait and try again.
1012 return scoped_ptr<cc::OutputSurface>();
1015 worker_context_provider = ContextProviderCommandBuffer::Create(
1016 CreateGraphicsContext3D(), RENDER_WORKER_CONTEXT);
1017 if (!worker_context_provider.get()) {
1018 // Cause the compositor to wait and try again.
1019 return scoped_ptr<cc::OutputSurface>();
1023 uint32 output_surface_id = next_output_surface_id_++;
1024 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1025 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1026 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1027 routing_id(), output_surface_id, context_provider,
1028 worker_context_provider, frame_swap_message_queue_));
1030 if (!context_provider.get()) {
1031 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1032 new cc::SoftwareOutputDevice());
1034 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1035 routing_id(), output_surface_id, nullptr, nullptr,
1036 software_device.Pass(), frame_swap_message_queue_, true));
1039 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1040 // Composite-to-mailbox is currently used for layout tests in order to cause
1041 // them to draw inside in the renderer to do the readback there. This should
1042 // no longer be the case when crbug.com/311404 is fixed.
1043 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1044 cc::ResourceFormat format = cc::RGBA_8888;
1045 if (base::SysInfo::IsLowEndDevice())
1046 format = cc::RGB_565;
1047 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1048 routing_id(), output_surface_id, context_provider,
1049 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1050 frame_swap_message_queue_, format));
1052 bool use_swap_compositor_frame_message = false;
1053 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1054 routing_id(), output_surface_id, context_provider,
1055 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1056 frame_swap_message_queue_, use_swap_compositor_frame_message));
1059 void RenderWidget::OnSwapBuffersAborted() {
1060 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1061 // Schedule another frame so the compositor learns about it.
1062 ScheduleComposite();
1065 void RenderWidget::OnSwapBuffersPosted() {
1066 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1069 void RenderWidget::OnSwapBuffersComplete() {
1070 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1072 // Notify subclasses that composited rendering was flushed to the screen.
1073 DidFlushPaint();
1076 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1077 const ui::LatencyInfo& latency_info,
1078 bool is_keyboard_shortcut) {
1079 if (!input_event)
1080 return;
1081 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1082 true);
1083 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1084 &handling_event_type_, input_event->type);
1086 // Calls into |didOverscroll()| while handling this event will populate
1087 // |event_overscroll|, which in turn will be bundled with the event ack.
1088 scoped_ptr<DidOverscrollParams> event_overscroll;
1089 base::AutoReset<scoped_ptr<DidOverscrollParams>*>
1090 handling_event_overscroll_resetter(&handling_event_overscroll_,
1091 &event_overscroll);
1093 #if defined(OS_ANDROID)
1094 // On Android, when a key is pressed or sent from the Keyboard using IME,
1095 // |AdapterInputConnection| generates input key events to make sure all JS
1096 // listeners that monitor KeyUp and KeyDown events receive the proper key
1097 // code. Since this input key event comes from IME, we need to set the
1098 // IME event guard here to make sure it does not interfere with other IME
1099 // events.
1100 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1101 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1102 const WebKeyboardEvent& key_event =
1103 *static_cast<const WebKeyboardEvent*>(input_event);
1104 // Some keys are special and it's essential that no events get blocked.
1105 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1106 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1107 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1108 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1109 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1110 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1111 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1113 #endif
1115 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
1116 &latency_info);
1118 base::TimeTicks start_time;
1119 if (base::TimeTicks::IsHighResolution())
1120 start_time = base::TimeTicks::Now();
1122 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1123 "event", WebInputEventTraits::GetName(input_event->type));
1124 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1125 TRACE_EVENT_FLOW_STEP0(
1126 "input,benchmark",
1127 "LatencyInfo.Flow",
1128 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
1129 "HanldeInputEventMain");
1131 // If we don't have a high res timer, these metrics won't be accurate enough
1132 // to be worth collecting. Note that this does introduce some sampling bias.
1133 if (!start_time.is_null())
1134 LogInputEventLatencyUma(*input_event, start_time);
1136 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1137 ui::LatencyInfo swap_latency_info(latency_info);
1138 if (compositor_) {
1139 latency_info_swap_promise_monitor =
1140 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1141 .Pass();
1144 bool prevent_default = false;
1145 if (WebInputEvent::isMouseEventType(input_event->type)) {
1146 const WebMouseEvent& mouse_event =
1147 *static_cast<const WebMouseEvent*>(input_event);
1148 TRACE_EVENT2("renderer", "HandleMouseMove",
1149 "x", mouse_event.x, "y", mouse_event.y);
1150 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1151 prevent_default = WillHandleMouseEvent(mouse_event);
1154 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1155 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1156 #if defined(OS_ANDROID)
1157 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1158 // case it should behave like a select key (i.e. causing a click if a button
1159 // is focused). However, if a text field is focused (2), its intended
1160 // behavior is to just show the IME and don't propagate the key.
1161 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1162 // when clicked on an input text field and cause the form submit if clicked
1163 // when the submit button is focused, but not vice-versa.
1164 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1165 // but at this point we have to swallow the event for the scenario (2).
1166 const WebKeyboardEvent& key_event =
1167 *static_cast<const WebKeyboardEvent*>(input_event);
1168 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1169 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1170 OnShowImeIfNeeded();
1171 prevent_default = true;
1173 #endif
1176 if (WebInputEvent::isGestureEventType(input_event->type)) {
1177 const WebGestureEvent& gesture_event =
1178 *static_cast<const WebGestureEvent*>(input_event);
1179 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1180 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1183 bool processed = prevent_default;
1184 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1185 suppress_next_char_events_ = false;
1186 if (!processed && webwidget_)
1187 processed = webwidget_->handleInputEvent(*input_event);
1190 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1191 // it's not processed by webkit, then we need to suppress the upcoming Char
1192 // events.
1193 if (!processed && is_keyboard_shortcut)
1194 suppress_next_char_events_ = true;
1196 InputEventAckState ack_result = processed ?
1197 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1198 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1199 const WebTouchEvent& touch_event =
1200 *static_cast<const WebTouchEvent*>(input_event);
1201 // Hit-test for all the pressed touch points. If there is a touch-handler
1202 // for any of the touch points, then the renderer should continue to receive
1203 // touch events.
1204 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1205 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1206 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1207 HasTouchEventHandlersAt(
1208 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1209 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1210 break;
1215 // Send mouse wheel events and their disposition to the compositor thread, so
1216 // that they can be used to produce the elastic overscroll effect on Mac.
1217 if (input_event->type == WebInputEvent::MouseWheel) {
1218 ObserveWheelEventAndResult(
1219 static_cast<const WebMouseWheelEvent&>(*input_event),
1220 event_overscroll ? event_overscroll->latest_overscroll_delta
1221 : gfx::Vector2dF(),
1222 processed);
1225 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1227 // If we don't have a fast and accurate Now(), we assume the input handlers
1228 // are heavy and rate limit them.
1229 bool rate_limiting_wanted =
1230 input_event->type == WebInputEvent::MouseMove ||
1231 input_event->type == WebInputEvent::MouseWheel;
1232 if (rate_limiting_wanted && !start_time.is_null()) {
1233 base::TimeTicks end_time = base::TimeTicks::Now();
1234 total_input_handling_time_this_frame_ += (end_time - start_time);
1235 rate_limiting_wanted =
1236 total_input_handling_time_this_frame_.InMicroseconds() >
1237 kInputHandlingTimeThrottlingThresholdMicroseconds;
1240 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1242 // Note that we can't use handling_event_type_ here since it will be overriden
1243 // by reentrant calls for events after the paused one.
1244 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1245 input_event->type == WebInputEvent::MouseMove;
1246 if (WebInputEventTraits::WillReceiveAckFromRenderer(*input_event) &&
1247 !no_ack) {
1248 InputEventAck ack(input_event->type, ack_result, swap_latency_info,
1249 event_overscroll.Pass(),
1250 WebInputEventTraits::GetUniqueTouchEventId(*input_event));
1251 scoped_ptr<IPC::Message> response(
1252 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1253 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1254 // We want to rate limit the input events in this case, so we'll wait for
1255 // painting to finish before ACKing this message.
1256 TRACE_EVENT_INSTANT0("renderer",
1257 "RenderWidget::OnHandleInputEvent ack throttled",
1258 TRACE_EVENT_SCOPE_THREAD);
1259 if (pending_input_event_ack_) {
1260 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1261 pending_input_event_ack_.get());
1262 // As two different kinds of events could cause us to postpone an ack
1263 // we send it now, if we have one pending. The Browser should never
1264 // send us the same kind of event we are delaying the ack for.
1265 Send(pending_input_event_ack_.release());
1267 pending_input_event_ack_ = response.Pass();
1268 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1269 pending_input_event_ack_.get());
1270 if (compositor_)
1271 compositor_->NotifyInputThrottledUntilCommit();
1272 } else {
1273 Send(response.release());
1275 } else {
1276 DCHECK(!event_overscroll) << "Unexpected overscroll for un-acked event";
1278 if (!no_ack && RenderThreadImpl::current()) {
1279 RenderThreadImpl::current()
1280 ->GetRendererScheduler()
1281 ->DidHandleInputEventOnMainThread(*input_event);
1283 if (input_event->type == WebInputEvent::MouseMove)
1284 ignore_ack_for_mouse_move_from_debugger_ = false;
1286 #if defined(OS_ANDROID)
1287 // Allow the IME to be shown when the focus changes as a consequence
1288 // of a processed touch end event.
1289 if (input_event->type == WebInputEvent::TouchEnd && processed)
1290 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1291 #elif defined(USE_AURA)
1292 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1293 // change.
1294 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1295 input_event->type == WebInputEvent::MouseUp)) {
1296 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1298 #endif
1300 if (!prevent_default) {
1301 if (WebInputEvent::isKeyboardEventType(input_event->type))
1302 DidHandleKeyEvent();
1305 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1306 // virtual keyboard.
1307 #if !defined(OS_ANDROID)
1308 // Virtual keyboard is not supported, so react to focus change immediately.
1309 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1310 input_event->type == WebInputEvent::MouseUp)) {
1311 FocusChangeComplete();
1313 #endif
1316 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1317 if (webwidget_)
1318 webwidget_->setCursorVisibilityState(is_visible);
1321 void RenderWidget::OnMouseCaptureLost() {
1322 if (webwidget_)
1323 webwidget_->mouseCaptureLost();
1326 void RenderWidget::OnSetFocus(bool enable) {
1327 has_focus_ = enable;
1328 if (webwidget_)
1329 webwidget_->setFocus(enable);
1332 void RenderWidget::ClearFocus() {
1333 // We may have got the focus from the browser before this gets processed, in
1334 // which case we do not want to unfocus ourself.
1335 if (!has_focus_ && webwidget_)
1336 webwidget_->setFocus(false);
1339 void RenderWidget::FlushPendingInputEventAck() {
1340 if (pending_input_event_ack_) {
1341 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1342 pending_input_event_ack_.get());
1343 Send(pending_input_event_ack_.release());
1345 total_input_handling_time_this_frame_ = base::TimeDelta();
1348 ///////////////////////////////////////////////////////////////////////////////
1349 // WebWidgetClient
1351 void RenderWidget::didAutoResize(const WebSize& new_size) {
1352 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1353 size_ = new_size;
1355 if (resizing_mode_selector_->is_synchronous_mode()) {
1356 WebRect new_pos(rootWindowRect().x,
1357 rootWindowRect().y,
1358 new_size.width,
1359 new_size.height);
1360 view_screen_rect_ = new_pos;
1361 window_screen_rect_ = new_pos;
1364 AutoResizeCompositor();
1366 if (!resizing_mode_selector_->is_synchronous_mode())
1367 need_update_rect_for_auto_resize_ = true;
1371 void RenderWidget::AutoResizeCompositor() {
1372 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1373 device_scale_factor_));
1374 if (compositor_)
1375 compositor_->setViewportSize(size_, physical_backing_size_);
1378 void RenderWidget::initializeLayerTreeView() {
1379 DCHECK(!host_closing_);
1381 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1382 compositor_->setViewportSize(size_, physical_backing_size_);
1383 if (init_complete_)
1384 StartCompositor();
1387 void RenderWidget::WillCloseLayerTreeView() {
1388 if (host_closing_)
1389 return;
1391 // Prevent new compositors or output surfaces from being created.
1392 host_closing_ = true;
1394 // Always send this notification to prevent new layer tree views from
1395 // being created, even if one hasn't been created yet.
1396 if (webwidget_)
1397 webwidget_->willCloseLayerTreeView();
1400 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1401 return compositor_.get();
1404 void RenderWidget::WillBeginCompositorFrame() {
1405 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1407 // The following two can result in further layout and possibly
1408 // enable GPU acceleration so they need to be called before any painting
1409 // is done.
1410 UpdateTextInputType();
1411 #if defined(OS_ANDROID)
1412 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1413 #endif
1414 UpdateSelectionBounds();
1417 void RenderWidget::DidCommitCompositorFrame() {
1418 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1419 DidCommitCompositorFrame());
1420 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1421 DidCommitCompositorFrame());
1422 #if defined(VIDEO_HOLE)
1423 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1424 DidCommitCompositorFrame());
1425 #endif // defined(VIDEO_HOLE)
1426 FlushPendingInputEventAck();
1429 void RenderWidget::DidCommitAndDrawCompositorFrame() {
1430 // NOTE: Tests may break if this event is renamed or moved. See
1431 // tab_capture_performancetest.cc.
1432 TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame");
1433 // Notify subclasses that we initiated the paint operation.
1434 DidInitiatePaint();
1437 void RenderWidget::DidCompleteSwapBuffers() {
1438 TRACE_EVENT0("renderer", "RenderWidget::DidCompleteSwapBuffers");
1440 // Notify subclasses threaded composited rendering was flushed to the screen.
1441 DidFlushPaint();
1443 if (!next_paint_flags_ &&
1444 !need_update_rect_for_auto_resize_ &&
1445 !plugin_window_moves_.size()) {
1446 return;
1449 ViewHostMsg_UpdateRect_Params params;
1450 params.view_size = size_;
1451 params.plugin_window_moves.swap(plugin_window_moves_);
1452 params.flags = next_paint_flags_;
1454 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1455 next_paint_flags_ = 0;
1456 need_update_rect_for_auto_resize_ = false;
1459 void RenderWidget::ScheduleComposite() {
1460 if (compositor_ &&
1461 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1462 compositor_->setNeedsAnimate();
1466 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
1467 if (compositor_) {
1468 // Regardless of whether threaded compositing is enabled, always
1469 // use this mechanism to force the compositor to redraw. However,
1470 // the invalidation code path below is still needed for the
1471 // non-threaded case.
1472 compositor_->SetNeedsForcedRedraw();
1474 ScheduleComposite();
1477 // static
1478 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1479 IPC::Message* msg,
1480 MessageDeliveryPolicy policy,
1481 FrameSwapMessageQueue* frame_swap_message_queue,
1482 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1483 int source_frame_number) {
1484 bool first_message_for_frame = false;
1485 frame_swap_message_queue->QueueMessageForFrame(policy,
1486 source_frame_number,
1487 make_scoped_ptr(msg),
1488 &first_message_for_frame);
1489 if (first_message_for_frame) {
1490 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1491 sync_message_filter, frame_swap_message_queue, source_frame_number));
1492 return promise;
1494 return nullptr;
1497 void RenderWidget::QueueMessage(IPC::Message* msg,
1498 MessageDeliveryPolicy policy) {
1499 // RenderThreadImpl::current() is NULL in some tests.
1500 if (!compositor_ || !RenderThreadImpl::current()) {
1501 Send(msg);
1502 return;
1505 scoped_ptr<cc::SwapPromise> swap_promise =
1506 QueueMessageImpl(msg,
1507 policy,
1508 frame_swap_message_queue_.get(),
1509 RenderThreadImpl::current()->sync_message_filter(),
1510 compositor_->GetSourceFrameNumber());
1512 if (swap_promise) {
1513 compositor_->QueueSwapPromise(swap_promise.Pass());
1514 // Request a commit. This might either A) request a commit ahead of time
1515 // or B) request a commit which is not needed because there are not
1516 // pending updates. If B) then the commit will be skipped and the swap
1517 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1518 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1519 // can_cancel_commit is not unset.
1520 compositor_->SetNeedsUpdateLayers();
1524 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1525 // TODO(darin): Eliminate this temporary.
1526 WebCursor cursor;
1527 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1528 // Only send a SetCursor message if we need to make a change.
1529 if (!current_cursor_.IsEqual(cursor)) {
1530 current_cursor_ = cursor;
1531 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1535 // We are supposed to get a single call to Show for a newly created RenderWidget
1536 // that was created via RenderWidget::CreateWebView. So, we wait until this
1537 // point to dispatch the ShowWidget message.
1539 // This method provides us with the information about how to display the newly
1540 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1542 void RenderWidget::show(WebNavigationPolicy) {
1543 DCHECK(!did_show_) << "received extraneous Show call";
1544 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1545 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1547 if (did_show_)
1548 return;
1550 did_show_ = true;
1551 // NOTE: initial_rect_ may still have its default values at this point, but
1552 // that's okay. It'll be ignored if as_popup is false, or the browser
1553 // process will impose a default position otherwise.
1554 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1555 SetPendingWindowRect(initial_rect_);
1558 void RenderWidget::didFocus() {
1561 void RenderWidget::didBlur() {
1564 void RenderWidget::DoDeferredClose() {
1565 WillCloseLayerTreeView();
1566 Send(new ViewHostMsg_Close(routing_id_));
1569 void RenderWidget::NotifyOnClose() {
1570 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose());
1573 void RenderWidget::closeWidgetSoon() {
1574 DCHECK(content::RenderThread::Get());
1575 if (is_swapped_out_) {
1576 // This widget is currently swapped out, and the active widget is in a
1577 // different process. Have the browser route the close request to the
1578 // active widget instead, so that the correct unload handlers are run.
1579 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1580 return;
1583 // If a page calls window.close() twice, we'll end up here twice, but that's
1584 // OK. It is safe to send multiple Close messages.
1586 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1587 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1588 // could be closed before the JS finishes executing. So instead, post a
1589 // message back to the message loop, which won't run until the JS is
1590 // complete, and then the Close message can be sent.
1591 base::ThreadTaskRunnerHandle::Get()->PostTask(
1592 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1595 void RenderWidget::QueueSyntheticGesture(
1596 scoped_ptr<SyntheticGestureParams> gesture_params,
1597 const SyntheticGestureCompletionCallback& callback) {
1598 DCHECK(!callback.is_null());
1600 pending_synthetic_gesture_callbacks_.push(callback);
1602 SyntheticGesturePacket gesture_packet;
1603 gesture_packet.set_gesture_params(gesture_params.Pass());
1605 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1608 void RenderWidget::Close() {
1609 screen_metrics_emulator_.reset();
1610 WillCloseLayerTreeView();
1611 compositor_.reset();
1612 if (webwidget_) {
1613 webwidget_->close();
1614 webwidget_ = NULL;
1618 WebRect RenderWidget::windowRect() {
1619 if (pending_window_rect_count_)
1620 return pending_window_rect_;
1622 return view_screen_rect_;
1625 void RenderWidget::setToolTipText(const blink::WebString& text,
1626 WebTextDirection hint) {
1627 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1630 void RenderWidget::setWindowRect(const WebRect& rect) {
1631 WebRect window_rect = rect;
1632 if (popup_origin_scale_for_emulation_) {
1633 float scale = popup_origin_scale_for_emulation_;
1634 window_rect.x = popup_screen_origin_for_emulation_.x() +
1635 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1636 window_rect.y = popup_screen_origin_for_emulation_.y() +
1637 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1640 if (!resizing_mode_selector_->is_synchronous_mode()) {
1641 if (did_show_) {
1642 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1643 SetPendingWindowRect(window_rect);
1644 } else {
1645 initial_rect_ = window_rect;
1647 } else {
1648 SetWindowRectSynchronously(window_rect);
1652 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1653 pending_window_rect_ = rect;
1654 pending_window_rect_count_++;
1657 WebRect RenderWidget::rootWindowRect() {
1658 if (pending_window_rect_count_) {
1659 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1660 // the RootWindowRect is probably going to return wrong results since the
1661 // browser may not have processed the Move yet. There isn't really anything
1662 // good to do in this case, and it shouldn't happen - since this size is
1663 // only really needed for windowToScreen, which is only used for Popups.
1664 return pending_window_rect_;
1667 return window_screen_rect_;
1670 WebRect RenderWidget::windowResizerRect() {
1671 return resizer_rect_;
1674 void RenderWidget::OnImeSetComposition(
1675 const base::string16& text,
1676 const std::vector<WebCompositionUnderline>& underlines,
1677 int selection_start, int selection_end) {
1678 if (!ShouldHandleImeEvent())
1679 return;
1680 ImeEventGuard guard(this);
1681 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1682 true);
1683 if (!webwidget_->setComposition(
1684 text, WebVector<WebCompositionUnderline>(underlines),
1685 selection_start, selection_end)) {
1686 // If we failed to set the composition text, then we need to let the browser
1687 // process to cancel the input method's ongoing composition session, to make
1688 // sure we are in a consistent state.
1689 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1691 UpdateCompositionInfo(true);
1694 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1695 const gfx::Range& replacement_range,
1696 bool keep_selection) {
1697 if (!ShouldHandleImeEvent())
1698 return;
1699 ImeEventGuard guard(this);
1700 handling_input_event_ = true;
1701 if (text.length())
1702 webwidget_->confirmComposition(text);
1703 else if (keep_selection)
1704 webwidget_->confirmComposition(WebWidget::KeepSelection);
1705 else
1706 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1707 handling_input_event_ = false;
1708 UpdateCompositionInfo(true);
1711 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1712 // During shutdown we can just ignore this message.
1713 if (!webwidget_)
1714 return;
1716 // Even if the browser provides an empty damage rect, it's still expecting to
1717 // receive a repaint ack so just damage the entire widget bounds.
1718 if (size_to_paint.IsEmpty()) {
1719 size_to_paint = size_;
1722 set_next_paint_is_repaint_ack();
1723 if (compositor_)
1724 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1727 void RenderWidget::OnSyntheticGestureCompleted() {
1728 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1730 pending_synthetic_gesture_callbacks_.front().Run();
1731 pending_synthetic_gesture_callbacks_.pop();
1734 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1735 if (!webwidget_)
1736 return;
1737 webwidget_->setTextDirection(direction);
1740 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1741 const gfx::Rect& window_screen_rect) {
1742 if (screen_metrics_emulator_) {
1743 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1744 view_screen_rect, window_screen_rect);
1745 } else {
1746 view_screen_rect_ = view_screen_rect;
1747 window_screen_rect_ = window_screen_rect;
1749 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1752 void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) {
1753 if (compositor_)
1754 compositor_->SetSurfaceIdNamespace(surface_id_namespace);
1757 void RenderWidget::showImeIfNeeded() {
1758 OnShowImeIfNeeded();
1761 void RenderWidget::OnShowImeIfNeeded() {
1762 #if defined(OS_ANDROID) || defined(USE_AURA)
1763 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1764 #endif
1766 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1767 // virtual keyboard.
1768 #if !defined(OS_ANDROID)
1769 FocusChangeComplete();
1770 #endif
1773 #if defined(OS_ANDROID)
1774 void RenderWidget::IncrementOutstandingImeEventAcks() {
1775 ++outstanding_ime_acks_;
1778 void RenderWidget::OnImeEventAck() {
1779 --outstanding_ime_acks_;
1780 DCHECK(outstanding_ime_acks_ >= 0);
1782 #endif
1784 bool RenderWidget::ShouldHandleImeEvent() {
1785 #if defined(OS_ANDROID)
1786 return !!webwidget_ && outstanding_ime_acks_ == 0;
1787 #else
1788 return !!webwidget_;
1789 #endif
1792 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1793 if (handling_event_type_ == WebInputEvent::MouseMove) {
1794 // If we pause multiple times during a single mouse move event, we should
1795 // only send ACK once.
1796 if (!ignore_ack_for_mouse_move_from_debugger_) {
1797 InputEventAck ack(handling_event_type_, INPUT_EVENT_ACK_STATE_CONSUMED);
1798 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1799 return true;
1802 return false;
1805 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1806 ignore_ack_for_mouse_move_from_debugger_ = true;
1809 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1810 if (device_scale_factor_ == device_scale_factor)
1811 return;
1813 device_scale_factor_ = device_scale_factor;
1814 ScheduleComposite();
1817 bool RenderWidget::SetDeviceColorProfile(
1818 const std::vector<char>& color_profile) {
1819 if (device_color_profile_ == color_profile)
1820 return false;
1822 device_color_profile_ = color_profile;
1823 return true;
1826 void RenderWidget::ResetDeviceColorProfileForTesting() {
1827 if (!device_color_profile_.empty())
1828 device_color_profile_.clear();
1829 device_color_profile_.push_back('0');
1832 void RenderWidget::OnOrientationChange() {
1835 gfx::Vector2d RenderWidget::GetScrollOffset() {
1836 // Bare RenderWidgets don't support scroll offset.
1837 return gfx::Vector2d();
1840 void RenderWidget::SetHidden(bool hidden) {
1841 if (is_hidden_ == hidden)
1842 return;
1844 // The status has changed. Tell the RenderThread about it and ensure
1845 // throttled acks are released in case frame production ceases.
1846 is_hidden_ = hidden;
1847 FlushPendingInputEventAck();
1849 if (is_hidden_)
1850 RenderThreadImpl::current()->WidgetHidden();
1851 else
1852 RenderThreadImpl::current()->WidgetRestored();
1855 void RenderWidget::DidToggleFullscreen() {
1856 if (!webwidget_)
1857 return;
1859 if (is_fullscreen_granted_) {
1860 webwidget_->didEnterFullScreen();
1861 } else {
1862 webwidget_->didExitFullScreen();
1866 bool RenderWidget::next_paint_is_resize_ack() const {
1867 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1870 void RenderWidget::set_next_paint_is_resize_ack() {
1871 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1874 void RenderWidget::set_next_paint_is_repaint_ack() {
1875 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1878 static bool IsDateTimeInput(ui::TextInputType type) {
1879 return type == ui::TEXT_INPUT_TYPE_DATE ||
1880 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1881 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1882 type == ui::TEXT_INPUT_TYPE_MONTH ||
1883 type == ui::TEXT_INPUT_TYPE_TIME ||
1884 type == ui::TEXT_INPUT_TYPE_WEEK;
1888 void RenderWidget::StartHandlingImeEvent() {
1889 DCHECK(!handling_ime_event_);
1890 handling_ime_event_ = true;
1893 void RenderWidget::FinishHandlingImeEvent() {
1894 DCHECK(handling_ime_event_);
1895 handling_ime_event_ = false;
1896 // While handling an ime event, text input state and selection bounds updates
1897 // are ignored. These must explicitly be updated once finished handling the
1898 // ime event.
1899 UpdateSelectionBounds();
1900 #if defined(OS_ANDROID)
1901 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1902 #endif
1905 void RenderWidget::UpdateTextInputType() {
1906 TRACE_EVENT0("renderer", "RenderWidget::UpdateTextInputType");
1907 ui::TextInputType new_type = GetTextInputType();
1908 if (IsDateTimeInput(new_type))
1909 return; // Not considered as a text input field in WebKit/Chromium.
1911 bool new_can_compose_inline = CanComposeInline();
1913 blink::WebTextInputInfo new_info;
1914 if (webwidget_)
1915 new_info = webwidget_->textInputInfo();
1916 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1917 int new_flags = new_info.flags;
1919 if (text_input_type_ != new_type
1920 || can_compose_inline_ != new_can_compose_inline
1921 || text_input_mode_ != new_mode
1922 || text_input_flags_ != new_flags) {
1923 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1924 new_type,
1925 new_mode,
1926 new_can_compose_inline,
1927 new_flags));
1928 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;
1935 #if defined(OS_ANDROID) || defined(USE_AURA)
1936 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1937 ChangeSource change_source) {
1938 TRACE_EVENT0("renderer", "RenderWidget::UpdateTextInputState");
1939 if (handling_ime_event_)
1940 return;
1941 ui::TextInputType new_type = GetTextInputType();
1942 if (IsDateTimeInput(new_type))
1943 return; // Not considered as a text input field in WebKit/Chromium.
1945 blink::WebTextInputInfo new_info;
1946 if (webwidget_)
1947 new_info = webwidget_->textInputInfo();
1949 bool new_can_compose_inline = CanComposeInline();
1951 // Only sends text input params if they are changed or if the ime should be
1952 // shown.
1953 if (show_ime == SHOW_IME_IF_NEEDED ||
1954 (text_input_type_ != new_type ||
1955 text_input_info_ != new_info ||
1956 can_compose_inline_ != new_can_compose_inline)
1957 #if defined(OS_ANDROID)
1958 || text_field_is_dirty_
1959 #endif
1961 ViewHostMsg_TextInputState_Params p;
1962 p.type = new_type;
1963 p.flags = new_info.flags;
1964 p.value = new_info.value.utf8();
1965 p.selection_start = new_info.selectionStart;
1966 p.selection_end = new_info.selectionEnd;
1967 p.composition_start = new_info.compositionStart;
1968 p.composition_end = new_info.compositionEnd;
1969 p.can_compose_inline = new_can_compose_inline;
1970 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1971 #if defined(USE_AURA)
1972 p.is_non_ime_change = true;
1973 #endif
1974 #if defined(OS_ANDROID)
1975 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1976 text_field_is_dirty_;
1977 if (p.is_non_ime_change)
1978 IncrementOutstandingImeEventAcks();
1979 text_field_is_dirty_ = false;
1980 #endif
1981 #if defined(USE_AURA)
1982 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1983 new_type,
1984 text_input_mode_,
1985 new_can_compose_inline,
1986 new_info.flags));
1987 #endif
1988 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
1990 text_input_info_ = new_info;
1991 text_input_type_ = new_type;
1992 can_compose_inline_ = new_can_compose_inline;
1993 text_input_flags_ = new_info.flags;
1996 #endif
1998 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1999 WebRect focus_webrect;
2000 WebRect anchor_webrect;
2001 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
2002 *focus = focus_webrect;
2003 *anchor = anchor_webrect;
2006 void RenderWidget::UpdateSelectionBounds() {
2007 TRACE_EVENT0("renderer", "RenderWidget::UpdateSelectionBounds");
2008 if (!webwidget_)
2009 return;
2010 if (handling_ime_event_)
2011 return;
2013 // With composited selection updates, the selection bounds will be reported
2014 // directly by the compositor, in which case explicit IPC selection
2015 // notifications should be suppressed.
2016 if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
2017 ViewHostMsg_SelectionBounds_Params params;
2018 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2019 if (selection_anchor_rect_ != params.anchor_rect ||
2020 selection_focus_rect_ != params.focus_rect) {
2021 selection_anchor_rect_ = params.anchor_rect;
2022 selection_focus_rect_ = params.focus_rect;
2023 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2024 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2025 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2029 UpdateCompositionInfo(false);
2032 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2033 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2034 static_assert(int(blink::WebTextInputType##a) \
2035 == int(ui::TEXT_INPUT_TYPE_##b), \
2036 "mismatching enums: " #a)
2038 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2039 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2040 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2041 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2042 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2043 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2044 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2045 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2046 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2047 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2048 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2049 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2050 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2051 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2052 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2053 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2054 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2056 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2057 blink::WebTextInputType type) {
2058 // Check the type is in the range representable by ui::TextInputType.
2059 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2060 "blink::WebTextInputType and ui::TextInputType not synchronized";
2061 return static_cast<ui::TextInputType>(type);
2064 ui::TextInputType RenderWidget::GetTextInputType() {
2065 if (webwidget_)
2066 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2067 return ui::TEXT_INPUT_TYPE_NONE;
2070 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2071 #if defined(OS_ANDROID)
2072 // TODO(yukawa): Start sending character bounds when the browser side
2073 // implementation becomes ready (crbug.com/424866).
2074 #else
2075 TRACE_EVENT0("renderer", "RenderWidget::UpdateCompositionInfo");
2076 gfx::Range range = gfx::Range();
2077 if (should_update_range) {
2078 GetCompositionRange(&range);
2079 } else {
2080 range = composition_range_;
2082 std::vector<gfx::Rect> character_bounds;
2083 GetCompositionCharacterBounds(&character_bounds);
2085 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2086 return;
2087 composition_character_bounds_ = character_bounds;
2088 composition_range_ = range;
2089 Send(new InputHostMsg_ImeCompositionRangeChanged(
2090 routing_id(), composition_range_, composition_character_bounds_));
2091 #endif
2094 void RenderWidget::GetCompositionCharacterBounds(
2095 std::vector<gfx::Rect>* bounds) {
2096 DCHECK(bounds);
2097 bounds->clear();
2100 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2101 size_t location, length;
2102 if (webwidget_->compositionRange(&location, &length)) {
2103 range->set_start(location);
2104 range->set_end(location + length);
2105 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2106 range->set_start(location);
2107 range->set_end(location + length);
2108 } else {
2109 *range = gfx::Range::InvalidRange();
2113 bool RenderWidget::ShouldUpdateCompositionInfo(
2114 const gfx::Range& range,
2115 const std::vector<gfx::Rect>& bounds) {
2116 if (composition_range_ != range)
2117 return true;
2118 if (bounds.size() != composition_character_bounds_.size())
2119 return true;
2120 for (size_t i = 0; i < bounds.size(); ++i) {
2121 if (bounds[i] != composition_character_bounds_[i])
2122 return true;
2124 return false;
2127 #if defined(OS_ANDROID)
2128 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2129 // If not initialized, default to white. Note that 0 is different from black
2130 // as black still has alpha 0xFF.
2131 if (!bg_color)
2132 bg_color = SK_ColorWHITE;
2134 if (bg_color != body_background_color_) {
2135 body_background_color_ = bg_color;
2136 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2140 bool RenderWidget::DoesRecordFullLayer() const {
2141 SynchronousCompositorFactory* synchronous_compositor_factory =
2142 SynchronousCompositorFactory::GetInstance();
2144 // We assume that the absence of synchronous_compositor_factory
2145 // means we are in Chrome. In chrome, we want to clip, i.e.
2146 // *not* to record the full layer.
2147 if (!synchronous_compositor_factory)
2148 return false;
2150 return synchronous_compositor_factory->RecordFullLayer();
2152 #endif
2154 bool RenderWidget::CanComposeInline() {
2155 return true;
2158 WebScreenInfo RenderWidget::screenInfo() {
2159 return screen_info_;
2162 float RenderWidget::deviceScaleFactor() {
2163 return device_scale_factor_;
2166 void RenderWidget::resetInputMethod() {
2167 ImeEventGuard guard(this);
2168 // If the last text input type is not None, then we should finish any
2169 // ongoing composition regardless of the new text input type.
2170 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2171 // If a composition text exists, then we need to let the browser process
2172 // to cancel the input method's ongoing composition session.
2173 if (webwidget_->confirmComposition())
2174 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2177 UpdateCompositionInfo(true);
2180 #if defined(OS_ANDROID)
2181 void RenderWidget::showUnhandledTapUIIfNeeded(
2182 const WebPoint& tapped_position,
2183 const WebNode& tapped_node,
2184 bool page_changed) {
2185 DCHECK(handling_input_event_);
2186 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2187 !tapped_node.isContentEditable() &&
2188 !tapped_node.isInsideFocusableElementOrARIAWidget();
2189 if (should_trigger) {
2190 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2191 tapped_position.x, tapped_position.y));
2194 #endif
2196 void RenderWidget::didHandleGestureEvent(
2197 const WebGestureEvent& event,
2198 bool event_cancelled) {
2199 #if defined(OS_ANDROID) || defined(USE_AURA)
2200 if (event_cancelled)
2201 return;
2202 if (event.type == WebInputEvent::GestureTap) {
2203 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2204 } else if (event.type == WebInputEvent::GestureLongPress) {
2205 DCHECK(webwidget_);
2206 if (webwidget_->textInputInfo().value.isEmpty())
2207 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2208 else
2209 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2211 #endif
2214 void RenderWidget::didOverscroll(
2215 const blink::WebFloatSize& unusedDelta,
2216 const blink::WebFloatSize& accumulatedRootOverScroll,
2217 const blink::WebFloatPoint& position,
2218 const blink::WebFloatSize& velocity) {
2219 DidOverscrollParams params;
2220 params.accumulated_overscroll = gfx::Vector2dF(
2221 accumulatedRootOverScroll.width, accumulatedRootOverScroll.height);
2222 params.latest_overscroll_delta =
2223 gfx::Vector2dF(unusedDelta.width, unusedDelta.height);
2224 // TODO(sataya.m): don't negate velocity once http://crbug.com/499743 is
2225 // fixed.
2226 params.current_fling_velocity =
2227 gfx::Vector2dF(-velocity.width, -velocity.height);
2228 params.causal_event_viewport_point = gfx::PointF(position.x, position.y);
2230 // If we're currently handling an event, stash the overscroll data such that
2231 // it can be bundled in the event ack.
2232 if (handling_event_overscroll_) {
2233 handling_event_overscroll_->reset(new DidOverscrollParams(params));
2234 return;
2237 Send(new InputHostMsg_DidOverscroll(routing_id_, params));
2240 void RenderWidget::StartCompositor() {
2241 // For widgets that are never visible, we don't need the compositor to run
2242 // at all.
2243 if (never_visible_)
2244 return;
2245 // In tests without a RenderThreadImpl, don't set ready as this kicks
2246 // off creating output surfaces that the test can't create.
2247 if (!RenderThreadImpl::current())
2248 return;
2249 compositor_->StartCompositor();
2252 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2253 size_t i = 0;
2254 for (; i < plugin_window_moves_.size(); ++i) {
2255 if (plugin_window_moves_[i].window == move.window) {
2256 if (move.rects_valid) {
2257 plugin_window_moves_[i] = move;
2258 } else {
2259 plugin_window_moves_[i].visible = move.visible;
2261 break;
2265 if (i == plugin_window_moves_.size())
2266 plugin_window_moves_.push_back(move);
2269 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2270 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2271 i != plugin_window_moves_.end(); ++i) {
2272 if (i->window == window) {
2273 plugin_window_moves_.erase(i);
2274 break;
2280 RenderWidgetCompositor* RenderWidget::compositor() const {
2281 return compositor_.get();
2284 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2285 return false;
2288 bool RenderWidget::WillHandleGestureEvent(
2289 const blink::WebGestureEvent& event) {
2290 return false;
2293 void RenderWidget::ObserveWheelEventAndResult(
2294 const blink::WebMouseWheelEvent& wheel_event,
2295 const gfx::Vector2dF& wheel_unused_delta,
2296 bool event_processed) {
2297 if (!compositor_deps_->IsElasticOverscrollEnabled())
2298 return;
2300 cc::InputHandlerScrollResult scroll_result;
2301 scroll_result.did_scroll = event_processed;
2302 scroll_result.did_overscroll_root = !wheel_unused_delta.IsZero();
2303 scroll_result.unused_scroll_delta = wheel_unused_delta;
2305 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2306 InputHandlerManager* input_handler_manager =
2307 render_thread ? render_thread->input_handler_manager() : NULL;
2308 if (input_handler_manager) {
2309 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2310 routing_id_, wheel_event, scroll_result);
2314 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2315 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2318 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2319 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2320 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2321 "mismatching enums: " #a)
2323 inline content::TouchAction& operator|=(content::TouchAction& a,
2324 content::TouchAction b) {
2325 a = static_cast<content::TouchAction>(static_cast<int>(a) |
2326 static_cast<int>(b));
2327 return a;
2330 void RenderWidget::setTouchAction(
2331 blink::WebTouchAction web_touch_action) {
2333 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2334 // when blink is emulating touch with mouse).
2335 if (handling_event_type_ != WebInputEvent::TouchStart)
2336 return;
2338 // Verify the same values are used by the types so we can cast between them.
2339 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2340 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2341 STATIC_ASSERT_WTI_ENUM_MATCH(PanLeft, PAN_LEFT);
2342 STATIC_ASSERT_WTI_ENUM_MATCH(PanRight, PAN_RIGHT);
2343 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2344 STATIC_ASSERT_WTI_ENUM_MATCH(PanUp, PAN_UP);
2345 STATIC_ASSERT_WTI_ENUM_MATCH(PanDown, PAN_DOWN);
2346 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2347 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2349 content::TouchAction content_touch_action =
2350 static_cast<content::TouchAction>(web_touch_action);
2351 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2354 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2355 #if defined(OS_ANDROID)
2356 text_field_is_dirty_ = true;
2357 #endif
2360 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2361 return true;
2364 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2365 RenderWidget::CreateGraphicsContext3D() {
2366 if (!webwidget_)
2367 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2368 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2369 switches::kDisableGpuCompositing))
2370 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2371 if (!RenderThreadImpl::current())
2372 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2373 CauseForGpuLaunch cause =
2374 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2375 scoped_refptr<GpuChannelHost> gpu_channel_host(
2376 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2377 if (!gpu_channel_host.get())
2378 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2380 // Explicitly disable antialiasing for the compositor. As of the time of
2381 // this writing, the only platform that supported antialiasing for the
2382 // compositor was Mac OS X, because the on-screen OpenGL context creation
2383 // code paths on Windows and Linux didn't yet have multisampling support.
2384 // Mac OS X essentially always behaves as though it's rendering offscreen.
2385 // Multisampling has a heavy cost especially on devices with relatively low
2386 // fill rate like most notebooks, and the Mac implementation would need to
2387 // be optimized to resolve directly into the IOSurface shared between the
2388 // GPU and browser processes. For these reasons and to avoid platform
2389 // disparities we explicitly disable antialiasing.
2390 blink::WebGraphicsContext3D::Attributes attributes;
2391 attributes.antialias = false;
2392 attributes.shareResources = true;
2393 attributes.noAutomaticFlushes = true;
2394 attributes.depth = false;
2395 attributes.stencil = false;
2396 bool lose_context_when_out_of_memory = true;
2397 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2398 #if defined(OS_ANDROID)
2399 // If we raster too fast we become upload bound, and pending
2400 // uploads consume memory. For maximum upload throughput, we would
2401 // want to allow for upload_throughput * pipeline_time of pending
2402 // uploads, after which we are just wasting memory. Since we don't
2403 // know our upload throughput yet, this just caps our memory usage.
2404 size_t divider = 1;
2405 if (base::SysInfo::IsLowEndDevice())
2406 divider = 6;
2407 // For reference Nexus10 can upload 1MB in about 2.5ms.
2408 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2409 // Deadline to draw a frame to achieve 60 frames per second.
2410 const size_t kMillisecondsPerFrame = 16;
2411 // Assuming a two frame deep pipeline between the CPU and the GPU.
2412 size_t max_transfer_buffer_usage_mb =
2413 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2414 static const size_t kBytesPerMegabyte = 1024 * 1024;
2415 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2416 // to avoid unnecessarily stalling the compositor thread.
2417 limits.mapped_memory_reclaim_limit =
2418 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2419 #endif
2421 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2422 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2423 GetURLForGraphicsContext3D(),
2424 gpu_channel_host.get(),
2425 attributes,
2426 lose_context_when_out_of_memory,
2427 limits,
2428 NULL));
2429 return context.Pass();
2432 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2433 render_frame_proxies_.AddObserver(proxy);
2436 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2437 render_frame_proxies_.RemoveObserver(proxy);
2440 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2441 render_frames_.AddObserver(frame);
2444 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2445 render_frames_.RemoveObserver(frame);
2448 #if defined(VIDEO_HOLE)
2449 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2450 video_hole_frames_.AddObserver(frame);
2453 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2454 video_hole_frames_.RemoveObserver(frame);
2456 #endif // defined(VIDEO_HOLE)
2458 } // namespace content