Refactor WebsiteSettings to operate on a SecurityInfo
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob8997a58307d4207416a25d7e8cc9e1a9b69e6467
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 base::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 base::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(double event_timestamp, base::TimeTicks now) {
165 return (now - base::TimeDelta::FromSecondsD(event_timestamp))
166 .ToInternalValue();
169 void LogInputEventLatencyUmaImpl(WebInputEvent::Type event_type,
170 double event_timestamp,
171 base::TimeTicks now) {
172 UMA_HISTOGRAM_CUSTOM_COUNTS("Event.AggregatedLatency.Renderer2",
173 GetEventLatencyMicros(event_timestamp, now), 1,
174 10000000, 100);
176 #define CASE_TYPE(t) \
177 case WebInputEvent::t: \
178 UMA_HISTOGRAM_CUSTOM_COUNTS("Event.Latency.Renderer2." #t, \
179 GetEventLatencyMicros(event_timestamp, now), \
180 1, 10000000, 100); \
181 break;
183 switch (event_type) {
184 CASE_TYPE(Undefined);
185 CASE_TYPE(MouseDown);
186 CASE_TYPE(MouseUp);
187 CASE_TYPE(MouseMove);
188 CASE_TYPE(MouseEnter);
189 CASE_TYPE(MouseLeave);
190 CASE_TYPE(ContextMenu);
191 CASE_TYPE(MouseWheel);
192 CASE_TYPE(RawKeyDown);
193 CASE_TYPE(KeyDown);
194 CASE_TYPE(KeyUp);
195 CASE_TYPE(Char);
196 CASE_TYPE(GestureScrollBegin);
197 CASE_TYPE(GestureScrollEnd);
198 CASE_TYPE(GestureScrollUpdate);
199 CASE_TYPE(GestureFlingStart);
200 CASE_TYPE(GestureFlingCancel);
201 CASE_TYPE(GestureShowPress);
202 CASE_TYPE(GestureTap);
203 CASE_TYPE(GestureTapUnconfirmed);
204 CASE_TYPE(GestureTapDown);
205 CASE_TYPE(GestureTapCancel);
206 CASE_TYPE(GestureDoubleTap);
207 CASE_TYPE(GestureTwoFingerTap);
208 CASE_TYPE(GestureLongPress);
209 CASE_TYPE(GestureLongTap);
210 CASE_TYPE(GesturePinchBegin);
211 CASE_TYPE(GesturePinchEnd);
212 CASE_TYPE(GesturePinchUpdate);
213 CASE_TYPE(TouchStart);
214 CASE_TYPE(TouchMove);
215 CASE_TYPE(TouchEnd);
216 CASE_TYPE(TouchCancel);
217 default:
218 // Must include default to let blink::WebInputEvent add new event types
219 // before they're added here.
220 DLOG(WARNING) << "Unhandled WebInputEvent type: " << event_type;
221 break;
224 #undef CASE_TYPE
227 void LogInputEventLatencyUma(const WebInputEvent& event, base::TimeTicks now,
228 const ui::LatencyInfo& latency_info) {
229 LogInputEventLatencyUmaImpl(event.type, event.timeStampSeconds, now);
230 for (size_t i = 0; i < latency_info.coalesced_events_size(); i++) {
231 LogInputEventLatencyUmaImpl(
232 event.type,
233 latency_info.timestamps_of_coalesced_events()[i],
234 now);
238 } // namespace
240 namespace content {
242 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
244 class RenderWidget::ScreenMetricsEmulator {
245 public:
246 ScreenMetricsEmulator(
247 RenderWidget* widget,
248 const WebDeviceEmulationParams& params);
249 virtual ~ScreenMetricsEmulator();
251 // Scale and offset used to convert between host coordinates
252 // and webwidget coordinates.
253 float scale() { return scale_; }
254 gfx::PointF offset() { return offset_; }
255 gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
256 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
257 const WebScreenInfo& original_screen_info() { return original_screen_info_; }
259 void ChangeEmulationParams(
260 const WebDeviceEmulationParams& params);
262 // The following methods alter handlers' behavior for messages related to
263 // widget size and position.
264 void OnResizeMessage(const ViewMsg_Resize_Params& params);
265 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
266 const gfx::Rect& window_screen_rect);
267 void OnShowContextMenu(ContextMenuParams* params);
268 gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
270 private:
271 void Reapply();
272 void Apply(bool top_controls_shrink_blink_size,
273 float top_controls_height,
274 gfx::Rect resizer_rect,
275 bool is_fullscreen_granted,
276 blink::WebDisplayMode display_mode);
278 RenderWidget* widget_;
280 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
281 WebDeviceEmulationParams params_;
283 // The computed scale and offset used to fit widget into browser window.
284 float scale_;
285 gfx::PointF offset_;
287 // Widget rect as passed to webwidget.
288 gfx::Rect applied_widget_rect_;
290 // Original values to restore back after emulation ends.
291 gfx::Size original_size_;
292 gfx::Size original_physical_backing_size_;
293 gfx::Size original_visible_viewport_size_;
294 blink::WebScreenInfo original_screen_info_;
295 gfx::Rect original_view_screen_rect_;
296 gfx::Rect original_window_screen_rect_;
299 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
300 RenderWidget* widget,
301 const WebDeviceEmulationParams& params)
302 : widget_(widget),
303 params_(params),
304 scale_(1.f) {
305 original_size_ = widget_->size_;
306 original_physical_backing_size_ = widget_->physical_backing_size_;
307 original_visible_viewport_size_ = widget_->visible_viewport_size_;
308 original_screen_info_ = widget_->screen_info_;
309 original_view_screen_rect_ = widget_->view_screen_rect_;
310 original_window_screen_rect_ = widget_->window_screen_rect_;
311 Apply(widget_->top_controls_shrink_blink_size_,
312 widget_->top_controls_height_,
313 widget_->resizer_rect_,
314 widget_->is_fullscreen_granted_,
315 widget_->display_mode_);
318 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
319 widget_->screen_info_ = original_screen_info_;
321 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
322 widget_->SetScreenMetricsEmulationParameters(false, params_);
323 widget_->view_screen_rect_ = original_view_screen_rect_;
324 widget_->window_screen_rect_ = original_window_screen_rect_;
325 widget_->Resize(original_size_,
326 original_physical_backing_size_,
327 widget_->top_controls_shrink_blink_size_,
328 widget_->top_controls_height_,
329 original_visible_viewport_size_,
330 widget_->resizer_rect_,
331 widget_->is_fullscreen_granted_,
332 widget_->display_mode_,
333 NO_RESIZE_ACK);
336 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
337 const WebDeviceEmulationParams& params) {
338 params_ = params;
339 Reapply();
342 void RenderWidget::ScreenMetricsEmulator::Reapply() {
343 Apply(widget_->top_controls_shrink_blink_size_,
344 widget_->top_controls_height_,
345 widget_->resizer_rect_,
346 widget_->is_fullscreen_granted_,
347 widget_->display_mode_);
350 void RenderWidget::ScreenMetricsEmulator::Apply(
351 bool top_controls_shrink_blink_size,
352 float top_controls_height,
353 gfx::Rect resizer_rect,
354 bool is_fullscreen_granted,
355 blink::WebDisplayMode display_mode) {
356 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
357 if (!applied_widget_rect_.width())
358 applied_widget_rect_.set_width(original_size_.width());
359 if (!applied_widget_rect_.height())
360 applied_widget_rect_.set_height(original_size_.height());
362 if (params_.fitToView && !original_size_.IsEmpty()) {
363 int original_width = std::max(original_size_.width(), 1);
364 int original_height = std::max(original_size_.height(), 1);
365 float width_ratio =
366 static_cast<float>(applied_widget_rect_.width()) / original_width;
367 float height_ratio =
368 static_cast<float>(applied_widget_rect_.height()) / original_height;
369 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
370 scale_ = 1.f / ratio;
372 // Center emulated view inside available view space.
373 offset_.set_x(
374 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
375 offset_.set_y(
376 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
377 } else {
378 scale_ = params_.scale;
379 offset_.SetPoint(params_.offset.x, params_.offset.y);
382 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
383 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
384 widget_->screen_info_.rect = original_screen_info_.rect;
385 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
386 widget_->window_screen_rect_ = original_window_screen_rect_;
387 } else {
388 applied_widget_rect_.set_origin(params_.viewPosition);
389 gfx::Rect screen_rect = applied_widget_rect_;
390 if (!params_.screenSize.isEmpty()) {
391 screen_rect =
392 gfx::Rect(0, 0, params_.screenSize.width, params_.screenSize.height);
394 widget_->screen_info_.rect = screen_rect;
395 widget_->screen_info_.availableRect = screen_rect;
396 widget_->window_screen_rect_ = applied_widget_rect_;
399 float applied_device_scale_factor = params_.deviceScaleFactor ?
400 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
401 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
403 // Pass three emulation parameters to the blink side:
404 // - we keep the real device scale factor in compositor to produce sharp image
405 // even when emulating different scale factor;
406 // - in order to fit into view, WebView applies offset and scale to the
407 // root layer.
408 blink::WebDeviceEmulationParams modified_params = params_;
409 modified_params.deviceScaleFactor = original_screen_info_.deviceScaleFactor;
410 modified_params.offset = blink::WebFloatPoint(offset_.x(), offset_.y());
411 modified_params.scale = scale_;
412 widget_->SetScreenMetricsEmulationParameters(true, modified_params);
414 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
415 widget_->view_screen_rect_ = applied_widget_rect_;
417 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
418 original_size_, original_screen_info_.deviceScaleFactor));
419 widget_->Resize(applied_widget_rect_.size(),
420 physical_backing_size,
421 top_controls_shrink_blink_size,
422 top_controls_height,
423 applied_widget_rect_.size(),
424 resizer_rect,
425 is_fullscreen_granted,
426 display_mode,
427 NO_RESIZE_ACK);
430 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
431 const ViewMsg_Resize_Params& params) {
432 bool need_ack = params.new_size != original_size_ &&
433 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
434 original_size_ = params.new_size;
435 original_physical_backing_size_ = params.physical_backing_size;
436 original_screen_info_ = params.screen_info;
437 original_visible_viewport_size_ = params.visible_viewport_size;
438 Apply(params.top_controls_shrink_blink_size,
439 params.top_controls_height,
440 params.resizer_rect,
441 params.is_fullscreen_granted,
442 params.display_mode);
444 if (need_ack) {
445 widget_->set_next_paint_is_resize_ack();
446 if (widget_->compositor_)
447 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
451 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
452 const gfx::Rect& view_screen_rect,
453 const gfx::Rect& window_screen_rect) {
454 original_view_screen_rect_ = view_screen_rect;
455 original_window_screen_rect_ = window_screen_rect;
456 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
457 Reapply();
460 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
461 ContextMenuParams* params) {
462 params->x *= scale_;
463 params->x += offset_.x();
464 params->y *= scale_;
465 params->y += offset_.y();
468 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
469 const gfx::Rect& anchor) {
470 gfx::Rect scaled = gfx::ScaleToEnclosedRect(anchor, scale_);
471 scaled.set_x(scaled.x() + offset_.x());
472 scaled.set_y(scaled.y() + offset_.y());
473 return scaled;
476 // RenderWidget ---------------------------------------------------------------
478 RenderWidget::RenderWidget(CompositorDependencies* compositor_deps,
479 blink::WebPopupType popup_type,
480 const blink::WebScreenInfo& screen_info,
481 bool swapped_out,
482 bool hidden,
483 bool never_visible)
484 : routing_id_(MSG_ROUTING_NONE),
485 surface_id_(0),
486 compositor_deps_(compositor_deps),
487 webwidget_(nullptr),
488 opener_id_(MSG_ROUTING_NONE),
489 init_complete_(false),
490 top_controls_shrink_blink_size_(false),
491 top_controls_height_(0.f),
492 next_paint_flags_(0),
493 auto_resize_mode_(false),
494 need_update_rect_for_auto_resize_(false),
495 did_show_(false),
496 is_hidden_(hidden),
497 never_visible_(never_visible),
498 is_fullscreen_granted_(false),
499 display_mode_(blink::WebDisplayModeUndefined),
500 has_focus_(false),
501 handling_input_event_(false),
502 handling_event_overscroll_(nullptr),
503 handling_ime_event_(false),
504 handling_event_type_(WebInputEvent::Undefined),
505 ignore_ack_for_mouse_move_from_debugger_(false),
506 closing_(false),
507 host_closing_(false),
508 is_swapped_out_(swapped_out),
509 for_oopif_(false),
510 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
511 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
512 text_input_flags_(0),
513 can_compose_inline_(true),
514 popup_type_(popup_type),
515 pending_window_rect_count_(0),
516 suppress_next_char_events_(false),
517 screen_info_(screen_info),
518 device_scale_factor_(screen_info_.deviceScaleFactor),
519 next_output_surface_id_(0),
520 #if defined(OS_ANDROID)
521 text_field_is_dirty_(false),
522 #endif
523 popup_origin_scale_for_emulation_(0.f),
524 frame_swap_message_queue_(new FrameSwapMessageQueue()),
525 resizing_mode_selector_(new ResizingModeSelector()),
526 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
527 has_host_context_menu_location_(false) {
528 if (!swapped_out)
529 RenderProcess::current()->AddRefProcess();
530 DCHECK(RenderThread::Get());
531 device_color_profile_.push_back('0');
532 #if defined(OS_ANDROID)
533 text_input_info_history_.push_back(blink::WebTextInputInfo());
534 #endif
537 RenderWidget::~RenderWidget() {
538 DCHECK(!webwidget_) << "Leaking our WebWidget!";
540 // If we are swapped out, we have released already.
541 if (!is_swapped_out_ && RenderProcess::current())
542 RenderProcess::current()->ReleaseProcess();
545 // static
546 RenderWidget* RenderWidget::Create(int32 opener_id,
547 CompositorDependencies* compositor_deps,
548 blink::WebPopupType popup_type,
549 const blink::WebScreenInfo& screen_info) {
550 DCHECK(opener_id != MSG_ROUTING_NONE);
551 scoped_refptr<RenderWidget> widget(new RenderWidget(
552 compositor_deps, popup_type, screen_info, false, false, false));
553 if (widget->Init(opener_id)) { // adds reference on success.
554 return widget.get();
556 return NULL;
559 // static
560 RenderWidget* RenderWidget::CreateForFrame(
561 int routing_id,
562 int surface_id,
563 bool hidden,
564 const blink::WebScreenInfo& screen_info,
565 CompositorDependencies* compositor_deps,
566 blink::WebLocalFrame* frame) {
567 CHECK_NE(routing_id, MSG_ROUTING_NONE);
568 scoped_refptr<RenderWidget> widget(
569 new RenderWidget(compositor_deps, blink::WebPopupTypeNone, screen_info,
570 false, hidden, false));
571 widget->routing_id_ = routing_id;
572 widget->surface_id_ = surface_id;
573 widget->for_oopif_ = true;
574 // DoInit increments the reference count on |widget|, keeping it alive after
575 // this function returns.
576 if (widget->DoInit(MSG_ROUTING_NONE,
577 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
578 nullptr)) {
579 widget->CompleteInit();
580 return widget.get();
582 return nullptr;
585 // static
586 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
587 RenderWidget* render_widget,
588 blink::WebLocalFrame* frame) {
589 return blink::WebFrameWidget::create(render_widget, frame);
592 // static
593 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
594 switch (render_widget->popup_type_) {
595 case blink::WebPopupTypeNone: // Nothing to create.
596 break;
597 case blink::WebPopupTypePage:
598 return WebPagePopup::create(render_widget);
599 default:
600 NOTREACHED();
602 return NULL;
605 void RenderWidget::CloseForFrame() {
606 OnClose();
609 bool RenderWidget::Init(int32 opener_id) {
610 return DoInit(opener_id, RenderWidget::CreateWebWidget(this),
611 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
612 &routing_id_, &surface_id_));
615 bool RenderWidget::DoInit(int32 opener_id,
616 WebWidget* web_widget,
617 IPC::SyncMessage* create_widget_message) {
618 DCHECK(!webwidget_);
620 if (opener_id != MSG_ROUTING_NONE)
621 opener_id_ = opener_id;
623 webwidget_ = web_widget;
625 bool result = true;
626 if (create_widget_message)
627 result = RenderThread::Get()->Send(create_widget_message);
629 if (result) {
630 RenderThread::Get()->AddRoute(routing_id_, this);
631 // Take a reference on behalf of the RenderThread. This will be balanced
632 // when we receive ViewMsg_Close.
633 AddRef();
634 if (RenderThreadImpl::current()) {
635 RenderThreadImpl::current()->WidgetCreated();
636 if (is_hidden_)
637 RenderThreadImpl::current()->WidgetHidden();
639 return true;
640 } else {
641 // The above Send can fail when the tab is closing.
642 return false;
646 // This is used to complete pending inits and non-pending inits.
647 void RenderWidget::CompleteInit() {
648 DCHECK(routing_id_ != MSG_ROUTING_NONE);
650 init_complete_ = true;
652 if (compositor_)
653 StartCompositor();
655 Send(new ViewHostMsg_RenderViewReady(routing_id_));
658 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
659 // We should only toggle between states.
660 DCHECK(is_swapped_out_ != is_swapped_out);
661 is_swapped_out_ = is_swapped_out;
663 // If we are swapping out, we will call ReleaseProcess, allowing the process
664 // to exit if all of its RenderViews are swapped out. We wait until the
665 // WasSwappedOut call to do this, to allow the unload handler to finish.
666 // If we are swapping in, we call AddRefProcess to prevent the process from
667 // exiting.
668 if (!is_swapped_out_)
669 RenderProcess::current()->AddRefProcess();
672 void RenderWidget::WasSwappedOut() {
673 // If we have been swapped out and no one else is using this process,
674 // it's safe to exit now.
675 CHECK(is_swapped_out_);
676 RenderProcess::current()->ReleaseProcess();
679 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
680 ScreenMetricsEmulator* emulator) {
681 popup_origin_scale_for_emulation_ = emulator->scale();
682 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
683 popup_screen_origin_for_emulation_ = gfx::Point(
684 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
685 emulator->original_screen_rect().origin().y() + emulator->offset().y());
686 screen_info_ = emulator->original_screen_info();
687 device_scale_factor_ = screen_info_.deviceScaleFactor;
690 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
691 if (screen_metrics_emulator_)
692 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
693 return anchor;
696 void RenderWidget::SetScreenMetricsEmulationParameters(
697 bool enabled,
698 const blink::WebDeviceEmulationParams& params) {
699 // This is only supported in RenderView.
700 NOTREACHED();
703 #if defined(OS_MACOSX) || defined(OS_ANDROID)
704 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
705 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
706 popup->SetOriginScaleAndOffsetForEmulation(
707 emulator->scale(), emulator->offset());
709 #endif
711 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
712 if (screen_metrics_emulator_)
713 screen_metrics_emulator_->OnShowContextMenu(params);
716 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
717 bool handled = true;
718 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
719 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
720 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
721 OnCursorVisibilityChange)
722 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
723 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
724 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
725 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
726 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
727 OnSyntheticGestureCompleted)
728 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
729 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
730 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
731 IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation,
732 OnEnableDeviceEmulation)
733 IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation,
734 OnDisableDeviceEmulation)
735 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
736 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
737 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
738 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
739 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
740 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
741 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
742 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
743 IPC_MESSAGE_HANDLER(ViewMsg_SetSurfaceIdNamespace, OnSetSurfaceIdNamespace)
744 #if defined(OS_ANDROID)
745 IPC_MESSAGE_HANDLER(InputMsg_ImeEventAck, OnImeEventAck)
746 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
747 #endif
748 IPC_MESSAGE_UNHANDLED(handled = false)
749 IPC_END_MESSAGE_MAP()
750 return handled;
753 bool RenderWidget::Send(IPC::Message* message) {
754 // Don't send any messages after the browser has told us to close, and filter
755 // most outgoing messages while swapped out.
756 if ((is_swapped_out_ &&
757 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
758 closing_) {
759 delete message;
760 return false;
763 // If given a messsage without a routing ID, then assign our routing ID.
764 if (message->routing_id() == MSG_ROUTING_NONE)
765 message->set_routing_id(routing_id_);
767 return RenderThread::Get()->Send(message);
770 void RenderWidget::Resize(const gfx::Size& new_size,
771 const gfx::Size& physical_backing_size,
772 bool top_controls_shrink_blink_size,
773 float top_controls_height,
774 const gfx::Size& visible_viewport_size,
775 const gfx::Rect& resizer_rect,
776 bool is_fullscreen_granted,
777 blink::WebDisplayMode display_mode,
778 const ResizeAck resize_ack) {
779 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
780 // A resize ack shouldn't be requested if we have not ACK'd the previous
781 // one.
782 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
783 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
786 // Ignore this during shutdown.
787 if (!webwidget_)
788 return;
790 if (compositor_) {
791 compositor_->setViewportSize(new_size, physical_backing_size);
794 physical_backing_size_ = physical_backing_size;
795 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
796 top_controls_height_ = top_controls_height;
797 visible_viewport_size_ = visible_viewport_size;
798 resizer_rect_ = resizer_rect;
800 // NOTE: We may have entered fullscreen mode without changing our size.
801 bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted;
802 is_fullscreen_granted_ = is_fullscreen_granted;
803 display_mode_ = display_mode;
805 webwidget_->setTopControlsHeight(top_controls_height,
806 top_controls_shrink_blink_size_);
808 if (size_ != new_size) {
809 size_ = new_size;
811 // When resizing, we want to wait to paint before ACK'ing the resize. This
812 // ensures that we only resize as fast as we can paint. We only need to
813 // send an ACK if we are resized to a non-empty rect.
814 webwidget_->resize(new_size);
817 webwidget()->resizePinchViewport(gfx::Size(
818 visible_viewport_size.width(),
819 visible_viewport_size.height()));
821 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
822 // In this case there is no paint/composite and therefore no
823 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
824 // ack through a fake ViewHostMsg_UpdateRect or a different message.
825 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
828 // Send the Resize_ACK flag once we paint again if requested.
829 if (resize_ack == SEND_RESIZE_ACK)
830 set_next_paint_is_resize_ack();
832 if (fullscreen_change)
833 DidToggleFullscreen();
835 // If a resize ack is requested and it isn't set-up, then no more resizes will
836 // come in and in general things will go wrong.
837 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
840 void RenderWidget::SetWindowRectSynchronously(
841 const gfx::Rect& new_window_rect) {
842 Resize(new_window_rect.size(),
843 new_window_rect.size(),
844 top_controls_shrink_blink_size_,
845 top_controls_height_,
846 new_window_rect.size(),
847 gfx::Rect(),
848 is_fullscreen_granted_,
849 display_mode_,
850 NO_RESIZE_ACK);
851 view_screen_rect_ = new_window_rect;
852 window_screen_rect_ = new_window_rect;
853 if (!did_show_)
854 initial_rect_ = new_window_rect;
857 void RenderWidget::OnClose() {
858 DCHECK(content::RenderThread::Get());
859 if (closing_)
860 return;
861 NotifyOnClose();
862 closing_ = true;
864 // Browser correspondence is no longer needed at this point.
865 if (routing_id_ != MSG_ROUTING_NONE) {
866 RenderThread::Get()->RemoveRoute(routing_id_);
867 SetHidden(false);
868 if (RenderThreadImpl::current())
869 RenderThreadImpl::current()->WidgetDestroyed();
872 if (for_oopif_) {
873 // Widgets for frames may be created and closed at any time while the frame
874 // is alive. However, the closing process must happen synchronously. Frame
875 // widget and frames hold pointers to each other. If Close() is deferred to
876 // the message loop like in the non-frame widget case, WebWidget::close()
877 // can end up accessing members of an already-deleted frame.
878 Close();
879 } else {
880 // If there is a Send call on the stack, then it could be dangerous to close
881 // now. Post a task that only gets invoked when there are no nested message
882 // loops.
883 base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(
884 FROM_HERE, base::Bind(&RenderWidget::Close, this));
887 // Balances the AddRef taken when we called AddRoute.
888 Release();
891 // Got a response from the browser after the renderer decided to create a new
892 // view.
893 void RenderWidget::OnCreatingNewAck() {
894 DCHECK(routing_id_ != MSG_ROUTING_NONE);
896 CompleteInit();
899 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
900 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
901 return;
903 if (screen_metrics_emulator_) {
904 screen_metrics_emulator_->OnResizeMessage(params);
905 return;
908 bool orientation_changed =
909 screen_info_.orientationAngle != params.screen_info.orientationAngle;
911 screen_info_ = params.screen_info;
912 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
913 Resize(params.new_size,
914 params.physical_backing_size,
915 params.top_controls_shrink_blink_size,
916 params.top_controls_height,
917 params.visible_viewport_size,
918 params.resizer_rect,
919 params.is_fullscreen_granted,
920 params.display_mode,
921 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
923 if (orientation_changed)
924 OnOrientationChange();
927 void RenderWidget::OnEnableDeviceEmulation(
928 const blink::WebDeviceEmulationParams& params) {
929 if (!screen_metrics_emulator_)
930 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
931 else
932 screen_metrics_emulator_->ChangeEmulationParams(params);
935 void RenderWidget::OnDisableDeviceEmulation() {
936 screen_metrics_emulator_.reset();
939 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
940 SetDeviceColorProfile(color_profile);
943 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
944 if (resizer_rect_ == resizer_rect)
945 return;
946 resizer_rect_ = resizer_rect;
947 if (webwidget_)
948 webwidget_->didChangeWindowResizerRect();
951 void RenderWidget::OnWasHidden() {
952 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
953 // Go into a mode where we stop generating paint and scrolling events.
954 SetHidden(true);
955 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
956 WasHidden());
959 void RenderWidget::OnWasShown(bool needs_repainting,
960 const ui::LatencyInfo& latency_info) {
961 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
962 // During shutdown we can just ignore this message.
963 if (!webwidget_)
964 return;
966 // See OnWasHidden
967 SetHidden(false);
968 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
969 WasShown());
971 if (!needs_repainting)
972 return;
974 // Generate a full repaint.
975 if (compositor_) {
976 ui::LatencyInfo swap_latency_info(latency_info);
977 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
978 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
979 compositor_->SetNeedsForcedRedraw();
981 ScheduleComposite();
984 void RenderWidget::OnRequestMoveAck() {
985 DCHECK(pending_window_rect_count_);
986 pending_window_rect_count_--;
989 GURL RenderWidget::GetURLForGraphicsContext3D() {
990 return GURL();
993 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
994 // For widgets that are never visible, we don't start the compositor, so we
995 // never get a request for a cc::OutputSurface.
996 DCHECK(!never_visible_);
998 #if defined(OS_ANDROID)
999 if (SynchronousCompositorFactory* factory =
1000 SynchronousCompositorFactory::GetInstance()) {
1001 return factory->CreateOutputSurface(routing_id(), surface_id(),
1002 frame_swap_message_queue_);
1004 #endif
1006 const base::CommandLine& command_line =
1007 *base::CommandLine::ForCurrentProcess();
1008 bool use_software = fallback;
1009 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1010 use_software = true;
1012 scoped_refptr<ContextProviderCommandBuffer> context_provider;
1013 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
1014 if (!use_software) {
1015 context_provider = ContextProviderCommandBuffer::Create(
1016 CreateGraphicsContext3D(true), RENDER_COMPOSITOR_CONTEXT);
1017 if (!context_provider.get()) {
1018 // Cause the compositor to wait and try again.
1019 return scoped_ptr<cc::OutputSurface>();
1022 worker_context_provider = ContextProviderCommandBuffer::Create(
1023 CreateGraphicsContext3D(false), RENDER_WORKER_CONTEXT);
1024 if (!worker_context_provider.get()) {
1025 // Cause the compositor to wait and try again.
1026 return scoped_ptr<cc::OutputSurface>();
1030 uint32 output_surface_id = next_output_surface_id_++;
1031 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1032 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1033 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1034 routing_id(), output_surface_id, context_provider,
1035 worker_context_provider, frame_swap_message_queue_));
1037 if (!context_provider.get()) {
1038 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1039 new cc::SoftwareOutputDevice());
1041 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1042 routing_id(), output_surface_id, nullptr, nullptr,
1043 software_device.Pass(), frame_swap_message_queue_, true));
1046 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1047 // Composite-to-mailbox is currently used for layout tests in order to cause
1048 // them to draw inside in the renderer to do the readback there. This should
1049 // no longer be the case when crbug.com/311404 is fixed.
1050 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1051 cc::ResourceFormat format = cc::RGBA_8888;
1052 if (base::SysInfo::IsLowEndDevice())
1053 format = cc::RGB_565;
1054 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1055 routing_id(), output_surface_id, context_provider,
1056 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1057 frame_swap_message_queue_, format));
1059 bool use_swap_compositor_frame_message = false;
1060 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1061 routing_id(), output_surface_id, context_provider,
1062 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1063 frame_swap_message_queue_, use_swap_compositor_frame_message));
1066 void RenderWidget::OnSwapBuffersAborted() {
1067 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1068 // Schedule another frame so the compositor learns about it.
1069 ScheduleComposite();
1072 void RenderWidget::OnSwapBuffersPosted() {
1073 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1076 void RenderWidget::OnSwapBuffersComplete() {
1077 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1079 // Notify subclasses that composited rendering was flushed to the screen.
1080 DidFlushPaint();
1083 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1084 const ui::LatencyInfo& latency_info,
1085 bool is_keyboard_shortcut) {
1086 if (!input_event)
1087 return;
1088 base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_,
1089 true);
1090 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1091 &handling_event_type_, input_event->type);
1093 // Calls into |didOverscroll()| while handling this event will populate
1094 // |event_overscroll|, which in turn will be bundled with the event ack.
1095 scoped_ptr<DidOverscrollParams> event_overscroll;
1096 base::AutoReset<scoped_ptr<DidOverscrollParams>*>
1097 handling_event_overscroll_resetter(&handling_event_overscroll_,
1098 &event_overscroll);
1100 #if defined(OS_ANDROID)
1101 // On Android, when a key is pressed or sent from the Keyboard using IME,
1102 // |AdapterInputConnection| generates input key events to make sure all JS
1103 // listeners that monitor KeyUp and KeyDown events receive the proper key
1104 // code. Since this input key event comes from IME, we need to set the
1105 // IME event guard here to make sure it does not interfere with other IME
1106 // events.
1107 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1108 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1109 const WebKeyboardEvent& key_event =
1110 *static_cast<const WebKeyboardEvent*>(input_event);
1111 // Some keys are special and it's essential that no events get blocked.
1112 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1113 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1114 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1115 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1116 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1117 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1118 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1120 #endif
1122 base::TimeTicks start_time;
1123 if (base::TimeTicks::IsHighResolution())
1124 start_time = base::TimeTicks::Now();
1126 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1127 "event", WebInputEventTraits::GetName(input_event->type));
1128 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1129 TRACE_EVENT_WITH_FLOW1("input,benchmark",
1130 "LatencyInfo.Flow",
1131 TRACE_ID_DONT_MANGLE(latency_info.trace_id()),
1132 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
1133 "step", "HandleInputEventMain");
1135 // If we don't have a high res timer, these metrics won't be accurate enough
1136 // to be worth collecting. Note that this does introduce some sampling bias.
1137 if (!start_time.is_null())
1138 LogInputEventLatencyUma(*input_event, start_time, latency_info);
1140 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1141 ui::LatencyInfo swap_latency_info(latency_info);
1142 if (compositor_) {
1143 latency_info_swap_promise_monitor =
1144 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1145 .Pass();
1148 bool prevent_default = false;
1149 if (WebInputEvent::isMouseEventType(input_event->type)) {
1150 const WebMouseEvent& mouse_event =
1151 *static_cast<const WebMouseEvent*>(input_event);
1152 TRACE_EVENT2("renderer", "HandleMouseMove",
1153 "x", mouse_event.x, "y", mouse_event.y);
1154 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1155 prevent_default = WillHandleMouseEvent(mouse_event);
1158 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1159 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1160 #if defined(OS_ANDROID)
1161 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1162 // case it should behave like a select key (i.e. causing a click if a button
1163 // is focused). However, if a text field is focused (2), its intended
1164 // behavior is to just show the IME and don't propagate the key.
1165 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1166 // when clicked on an input text field and cause the form submit if clicked
1167 // when the submit button is focused, but not vice-versa.
1168 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1169 // but at this point we have to swallow the event for the scenario (2).
1170 const WebKeyboardEvent& key_event =
1171 *static_cast<const WebKeyboardEvent*>(input_event);
1172 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1173 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1174 OnShowImeIfNeeded();
1175 prevent_default = true;
1177 #endif
1180 if (WebInputEvent::isGestureEventType(input_event->type)) {
1181 const WebGestureEvent& gesture_event =
1182 *static_cast<const WebGestureEvent*>(input_event);
1183 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1184 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1187 bool processed = prevent_default;
1188 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1189 suppress_next_char_events_ = false;
1190 if (!processed && webwidget_)
1191 processed = webwidget_->handleInputEvent(*input_event);
1194 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1195 // it's not processed by webkit, then we need to suppress the upcoming Char
1196 // events.
1197 if (!processed && is_keyboard_shortcut)
1198 suppress_next_char_events_ = true;
1200 InputEventAckState ack_result = processed ?
1201 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1202 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1203 const WebTouchEvent& touch_event =
1204 *static_cast<const WebTouchEvent*>(input_event);
1205 // Hit-test for all the pressed touch points. If there is a touch-handler
1206 // for any of the touch points, then the renderer should continue to receive
1207 // touch events.
1208 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1209 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1210 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1211 HasTouchEventHandlersAt(
1212 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1213 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1214 break;
1219 // Send mouse wheel events and their disposition to the compositor thread, so
1220 // that they can be used to produce the elastic overscroll effect on Mac.
1221 if (input_event->type == WebInputEvent::MouseWheel) {
1222 ObserveWheelEventAndResult(
1223 static_cast<const WebMouseWheelEvent&>(*input_event),
1224 event_overscroll ? event_overscroll->latest_overscroll_delta
1225 : gfx::Vector2dF(),
1226 processed);
1229 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1231 // If we don't have a fast and accurate Now(), we assume the input handlers
1232 // are heavy and rate limit them.
1233 bool rate_limiting_wanted =
1234 input_event->type == WebInputEvent::MouseMove ||
1235 input_event->type == WebInputEvent::MouseWheel;
1236 if (rate_limiting_wanted && !start_time.is_null()) {
1237 base::TimeTicks end_time = base::TimeTicks::Now();
1238 total_input_handling_time_this_frame_ += (end_time - start_time);
1239 rate_limiting_wanted =
1240 total_input_handling_time_this_frame_.InMicroseconds() >
1241 kInputHandlingTimeThrottlingThresholdMicroseconds;
1244 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1246 // Note that we can't use handling_event_type_ here since it will be overriden
1247 // by reentrant calls for events after the paused one.
1248 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1249 input_event->type == WebInputEvent::MouseMove;
1250 if (WebInputEventTraits::WillReceiveAckFromRenderer(*input_event) &&
1251 !no_ack) {
1252 InputEventAck ack(input_event->type, ack_result, swap_latency_info,
1253 event_overscroll.Pass(),
1254 WebInputEventTraits::GetUniqueTouchEventId(*input_event));
1255 scoped_ptr<IPC::Message> response(
1256 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1257 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1258 // We want to rate limit the input events in this case, so we'll wait for
1259 // painting to finish before ACKing this message.
1260 TRACE_EVENT_INSTANT0("renderer",
1261 "RenderWidget::OnHandleInputEvent ack throttled",
1262 TRACE_EVENT_SCOPE_THREAD);
1263 if (pending_input_event_ack_) {
1264 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1265 pending_input_event_ack_.get());
1266 // As two different kinds of events could cause us to postpone an ack
1267 // we send it now, if we have one pending. The Browser should never
1268 // send us the same kind of event we are delaying the ack for.
1269 Send(pending_input_event_ack_.release());
1271 pending_input_event_ack_ = response.Pass();
1272 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1273 pending_input_event_ack_.get());
1274 if (compositor_)
1275 compositor_->NotifyInputThrottledUntilCommit();
1276 } else {
1277 Send(response.release());
1279 } else {
1280 DCHECK(!event_overscroll) << "Unexpected overscroll for un-acked event";
1282 if (!no_ack && RenderThreadImpl::current()) {
1283 RenderThreadImpl::current()
1284 ->GetRendererScheduler()
1285 ->DidHandleInputEventOnMainThread(*input_event);
1287 if (input_event->type == WebInputEvent::MouseMove)
1288 ignore_ack_for_mouse_move_from_debugger_ = false;
1290 #if defined(OS_ANDROID)
1291 // Allow the IME to be shown when the focus changes as a consequence
1292 // of a processed touch end event.
1293 if (input_event->type == WebInputEvent::TouchEnd && processed)
1294 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1295 #elif defined(USE_AURA)
1296 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1297 // change.
1298 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1299 input_event->type == WebInputEvent::MouseUp)) {
1300 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1302 #endif
1304 if (!prevent_default) {
1305 if (WebInputEvent::isKeyboardEventType(input_event->type))
1306 DidHandleKeyEvent();
1309 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1310 // virtual keyboard.
1311 #if !defined(OS_ANDROID)
1312 // Virtual keyboard is not supported, so react to focus change immediately.
1313 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1314 input_event->type == WebInputEvent::MouseUp)) {
1315 FocusChangeComplete();
1317 #endif
1320 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1321 if (webwidget_)
1322 webwidget_->setCursorVisibilityState(is_visible);
1325 void RenderWidget::OnMouseCaptureLost() {
1326 if (webwidget_)
1327 webwidget_->mouseCaptureLost();
1330 void RenderWidget::OnSetFocus(bool enable) {
1331 has_focus_ = enable;
1332 if (webwidget_)
1333 webwidget_->setFocus(enable);
1336 void RenderWidget::ClearFocus() {
1337 // We may have got the focus from the browser before this gets processed, in
1338 // which case we do not want to unfocus ourself.
1339 if (!has_focus_ && webwidget_)
1340 webwidget_->setFocus(false);
1343 void RenderWidget::FlushPendingInputEventAck() {
1344 if (pending_input_event_ack_) {
1345 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1346 pending_input_event_ack_.get());
1347 Send(pending_input_event_ack_.release());
1349 total_input_handling_time_this_frame_ = base::TimeDelta();
1352 ///////////////////////////////////////////////////////////////////////////////
1353 // WebWidgetClient
1355 void RenderWidget::didAutoResize(const WebSize& new_size) {
1356 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1357 size_ = new_size;
1359 if (resizing_mode_selector_->is_synchronous_mode()) {
1360 WebRect new_pos(rootWindowRect().x,
1361 rootWindowRect().y,
1362 new_size.width,
1363 new_size.height);
1364 view_screen_rect_ = new_pos;
1365 window_screen_rect_ = new_pos;
1368 AutoResizeCompositor();
1370 if (!resizing_mode_selector_->is_synchronous_mode())
1371 need_update_rect_for_auto_resize_ = true;
1375 void RenderWidget::AutoResizeCompositor() {
1376 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1377 device_scale_factor_));
1378 if (compositor_)
1379 compositor_->setViewportSize(size_, physical_backing_size_);
1382 void RenderWidget::initializeLayerTreeView() {
1383 DCHECK(!host_closing_);
1385 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1386 compositor_->setViewportSize(size_, physical_backing_size_);
1387 if (init_complete_)
1388 StartCompositor();
1391 void RenderWidget::WillCloseLayerTreeView() {
1392 if (host_closing_)
1393 return;
1395 // Prevent new compositors or output surfaces from being created.
1396 host_closing_ = true;
1398 // Always send this notification to prevent new layer tree views from
1399 // being created, even if one hasn't been created yet.
1400 if (webwidget_)
1401 webwidget_->willCloseLayerTreeView();
1404 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1405 return compositor_.get();
1408 void RenderWidget::didFirstVisuallyNonEmptyLayout() {
1409 QueueMessage(
1410 new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
1411 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
1414 void RenderWidget::didFirstLayoutAfterFinishedParsing() {
1415 // TODO(dglazkov): Use this hook to drive CapturePageInfo.
1418 void RenderWidget::WillBeginCompositorFrame() {
1419 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1421 // The UpdateTextInputState can result in further layout and possibly
1422 // enable GPU acceleration so they need to be called before any painting
1423 // is done.
1424 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1425 UpdateSelectionBounds();
1428 void RenderWidget::DidCommitCompositorFrame() {
1429 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1430 DidCommitCompositorFrame());
1431 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1432 DidCommitCompositorFrame());
1433 #if defined(VIDEO_HOLE)
1434 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1435 DidCommitCompositorFrame());
1436 #endif // defined(VIDEO_HOLE)
1437 FlushPendingInputEventAck();
1440 void RenderWidget::DidCommitAndDrawCompositorFrame() {
1441 // NOTE: Tests may break if this event is renamed or moved. See
1442 // tab_capture_performancetest.cc.
1443 TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame");
1444 // Notify subclasses that we initiated the paint operation.
1445 DidInitiatePaint();
1448 void RenderWidget::DidCompleteSwapBuffers() {
1449 TRACE_EVENT0("renderer", "RenderWidget::DidCompleteSwapBuffers");
1451 // Notify subclasses threaded composited rendering was flushed to the screen.
1452 DidFlushPaint();
1454 if (!next_paint_flags_ &&
1455 !need_update_rect_for_auto_resize_ &&
1456 !plugin_window_moves_.size()) {
1457 return;
1460 ViewHostMsg_UpdateRect_Params params;
1461 params.view_size = size_;
1462 params.plugin_window_moves.swap(plugin_window_moves_);
1463 params.flags = next_paint_flags_;
1465 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1466 next_paint_flags_ = 0;
1467 need_update_rect_for_auto_resize_ = false;
1470 void RenderWidget::ScheduleComposite() {
1471 if (compositor_ &&
1472 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1473 compositor_->setNeedsAnimate();
1477 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
1478 if (compositor_) {
1479 // Regardless of whether threaded compositing is enabled, always
1480 // use this mechanism to force the compositor to redraw. However,
1481 // the invalidation code path below is still needed for the
1482 // non-threaded case.
1483 compositor_->SetNeedsForcedRedraw();
1485 ScheduleComposite();
1488 // static
1489 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1490 IPC::Message* msg,
1491 MessageDeliveryPolicy policy,
1492 FrameSwapMessageQueue* frame_swap_message_queue,
1493 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1494 int source_frame_number) {
1495 bool first_message_for_frame = false;
1496 frame_swap_message_queue->QueueMessageForFrame(policy,
1497 source_frame_number,
1498 make_scoped_ptr(msg),
1499 &first_message_for_frame);
1500 if (first_message_for_frame) {
1501 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1502 sync_message_filter, frame_swap_message_queue, source_frame_number));
1503 return promise;
1505 return nullptr;
1508 void RenderWidget::QueueMessage(IPC::Message* msg,
1509 MessageDeliveryPolicy policy) {
1510 // RenderThreadImpl::current() is NULL in some tests.
1511 if (!compositor_ || !RenderThreadImpl::current()) {
1512 Send(msg);
1513 return;
1516 scoped_ptr<cc::SwapPromise> swap_promise =
1517 QueueMessageImpl(msg,
1518 policy,
1519 frame_swap_message_queue_.get(),
1520 RenderThreadImpl::current()->sync_message_filter(),
1521 compositor_->GetSourceFrameNumber());
1523 if (swap_promise) {
1524 compositor_->QueueSwapPromise(swap_promise.Pass());
1525 // Request a commit. This might either A) request a commit ahead of time
1526 // or B) request a commit which is not needed because there are not
1527 // pending updates. If B) then the commit will be skipped and the swap
1528 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1529 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1530 // can_cancel_commit is not unset.
1531 compositor_->SetNeedsUpdateLayers();
1535 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1536 // TODO(darin): Eliminate this temporary.
1537 WebCursor cursor;
1538 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1539 // Only send a SetCursor message if we need to make a change.
1540 if (!current_cursor_.IsEqual(cursor)) {
1541 current_cursor_ = cursor;
1542 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1546 // We are supposed to get a single call to Show for a newly created RenderWidget
1547 // that was created via RenderWidget::CreateWebView. So, we wait until this
1548 // point to dispatch the ShowWidget message.
1550 // This method provides us with the information about how to display the newly
1551 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1553 void RenderWidget::show(WebNavigationPolicy) {
1554 DCHECK(!did_show_) << "received extraneous Show call";
1555 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1556 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1558 if (did_show_)
1559 return;
1561 did_show_ = true;
1562 // NOTE: initial_rect_ may still have its default values at this point, but
1563 // that's okay. It'll be ignored if as_popup is false, or the browser
1564 // process will impose a default position otherwise.
1565 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1566 SetPendingWindowRect(initial_rect_);
1569 void RenderWidget::didFocus() {
1572 void RenderWidget::didBlur() {
1575 void RenderWidget::DoDeferredClose() {
1576 WillCloseLayerTreeView();
1577 Send(new ViewHostMsg_Close(routing_id_));
1580 void RenderWidget::NotifyOnClose() {
1581 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose());
1584 void RenderWidget::closeWidgetSoon() {
1585 DCHECK(content::RenderThread::Get());
1586 if (is_swapped_out_) {
1587 // This widget is currently swapped out, and the active widget is in a
1588 // different process. Have the browser route the close request to the
1589 // active widget instead, so that the correct unload handlers are run.
1590 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1591 return;
1594 // If a page calls window.close() twice, we'll end up here twice, but that's
1595 // OK. It is safe to send multiple Close messages.
1597 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1598 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1599 // could be closed before the JS finishes executing. So instead, post a
1600 // message back to the message loop, which won't run until the JS is
1601 // complete, and then the Close message can be sent.
1602 base::ThreadTaskRunnerHandle::Get()->PostTask(
1603 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1606 void RenderWidget::QueueSyntheticGesture(
1607 scoped_ptr<SyntheticGestureParams> gesture_params,
1608 const SyntheticGestureCompletionCallback& callback) {
1609 DCHECK(!callback.is_null());
1611 pending_synthetic_gesture_callbacks_.push(callback);
1613 SyntheticGesturePacket gesture_packet;
1614 gesture_packet.set_gesture_params(gesture_params.Pass());
1616 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1619 void RenderWidget::Close() {
1620 screen_metrics_emulator_.reset();
1621 WillCloseLayerTreeView();
1622 compositor_.reset();
1623 if (webwidget_) {
1624 webwidget_->close();
1625 webwidget_ = NULL;
1629 WebRect RenderWidget::windowRect() {
1630 if (pending_window_rect_count_)
1631 return pending_window_rect_;
1633 return view_screen_rect_;
1636 void RenderWidget::setToolTipText(const blink::WebString& text,
1637 WebTextDirection hint) {
1638 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1641 void RenderWidget::setWindowRect(const WebRect& rect) {
1642 WebRect window_rect = rect;
1643 if (popup_origin_scale_for_emulation_) {
1644 float scale = popup_origin_scale_for_emulation_;
1645 window_rect.x = popup_screen_origin_for_emulation_.x() +
1646 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1647 window_rect.y = popup_screen_origin_for_emulation_.y() +
1648 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1651 if (!resizing_mode_selector_->is_synchronous_mode()) {
1652 if (did_show_) {
1653 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1654 SetPendingWindowRect(window_rect);
1655 } else {
1656 initial_rect_ = window_rect;
1658 } else {
1659 SetWindowRectSynchronously(window_rect);
1663 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1664 pending_window_rect_ = rect;
1665 pending_window_rect_count_++;
1668 WebRect RenderWidget::rootWindowRect() {
1669 if (pending_window_rect_count_) {
1670 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1671 // the RootWindowRect is probably going to return wrong results since the
1672 // browser may not have processed the Move yet. There isn't really anything
1673 // good to do in this case, and it shouldn't happen - since this size is
1674 // only really needed for windowToScreen, which is only used for Popups.
1675 return pending_window_rect_;
1678 return window_screen_rect_;
1681 WebRect RenderWidget::windowResizerRect() {
1682 return resizer_rect_;
1685 void RenderWidget::OnImeSetComposition(
1686 const base::string16& text,
1687 const std::vector<WebCompositionUnderline>& underlines,
1688 int selection_start, int selection_end) {
1689 if (!ShouldHandleImeEvent())
1690 return;
1691 ImeEventGuard guard(this);
1692 if (!webwidget_->setComposition(
1693 text, WebVector<WebCompositionUnderline>(underlines),
1694 selection_start, selection_end)) {
1695 // If we failed to set the composition text, then we need to let the browser
1696 // process to cancel the input method's ongoing composition session, to make
1697 // sure we are in a consistent state.
1698 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1700 UpdateCompositionInfo(true);
1703 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1704 const gfx::Range& replacement_range,
1705 bool keep_selection) {
1706 if (!ShouldHandleImeEvent())
1707 return;
1708 ImeEventGuard guard(this);
1709 handling_input_event_ = true;
1710 if (text.length())
1711 webwidget_->confirmComposition(text);
1712 else if (keep_selection)
1713 webwidget_->confirmComposition(WebWidget::KeepSelection);
1714 else
1715 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1716 handling_input_event_ = false;
1717 UpdateCompositionInfo(true);
1720 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1721 // During shutdown we can just ignore this message.
1722 if (!webwidget_)
1723 return;
1725 // Even if the browser provides an empty damage rect, it's still expecting to
1726 // receive a repaint ack so just damage the entire widget bounds.
1727 if (size_to_paint.IsEmpty()) {
1728 size_to_paint = size_;
1731 set_next_paint_is_repaint_ack();
1732 if (compositor_)
1733 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1736 void RenderWidget::OnSyntheticGestureCompleted() {
1737 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1739 pending_synthetic_gesture_callbacks_.front().Run();
1740 pending_synthetic_gesture_callbacks_.pop();
1743 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1744 if (!webwidget_)
1745 return;
1746 webwidget_->setTextDirection(direction);
1749 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1750 const gfx::Rect& window_screen_rect) {
1751 if (screen_metrics_emulator_) {
1752 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1753 view_screen_rect, window_screen_rect);
1754 } else {
1755 view_screen_rect_ = view_screen_rect;
1756 window_screen_rect_ = window_screen_rect;
1758 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1761 void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) {
1762 if (compositor_)
1763 compositor_->SetSurfaceIdNamespace(surface_id_namespace);
1766 void RenderWidget::showImeIfNeeded() {
1767 OnShowImeIfNeeded();
1770 void RenderWidget::OnShowImeIfNeeded() {
1771 #if defined(OS_ANDROID) || defined(USE_AURA)
1772 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1773 #endif
1775 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1776 // virtual keyboard.
1777 #if !defined(OS_ANDROID)
1778 FocusChangeComplete();
1779 #endif
1782 #if defined(OS_ANDROID)
1783 void RenderWidget::OnImeEventSentForAck(const blink::WebTextInputInfo& info) {
1784 text_input_info_history_.push_back(info);
1787 void RenderWidget::OnImeEventAck() {
1788 DCHECK_GE(text_input_info_history_.size(), 1u);
1789 text_input_info_history_.pop_front();
1791 #endif
1793 bool RenderWidget::ShouldHandleImeEvent() {
1794 #if defined(OS_ANDROID)
1795 if (!webwidget_)
1796 return false;
1798 // We cannot handle IME events if there is any chance that the event we are
1799 // receiving here from the browser is based on the state that is different
1800 // from our current one as indicated by |text_input_info_|.
1801 // The states the browser might be in are:
1802 // text_input_info_history_[0] - current state ack'd by browser
1803 // text_input_info_history_[1...N] - pending state changes
1804 for (size_t i = 0u; i < text_input_info_history_.size() - 1u; ++i) {
1805 if (text_input_info_history_[i] != text_input_info_)
1806 return false;
1808 return true;
1809 #else
1810 return !!webwidget_;
1811 #endif
1814 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1815 if (handling_event_type_ == WebInputEvent::MouseMove) {
1816 // If we pause multiple times during a single mouse move event, we should
1817 // only send ACK once.
1818 if (!ignore_ack_for_mouse_move_from_debugger_) {
1819 InputEventAck ack(handling_event_type_, INPUT_EVENT_ACK_STATE_CONSUMED);
1820 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1821 return true;
1824 return false;
1827 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1828 ignore_ack_for_mouse_move_from_debugger_ = true;
1831 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1832 if (device_scale_factor_ == device_scale_factor)
1833 return;
1835 device_scale_factor_ = device_scale_factor;
1836 ScheduleComposite();
1839 bool RenderWidget::SetDeviceColorProfile(
1840 const std::vector<char>& color_profile) {
1841 if (device_color_profile_ == color_profile)
1842 return false;
1844 device_color_profile_ = color_profile;
1845 return true;
1848 void RenderWidget::ResetDeviceColorProfileForTesting() {
1849 if (!device_color_profile_.empty())
1850 device_color_profile_.clear();
1851 device_color_profile_.push_back('0');
1854 void RenderWidget::OnOrientationChange() {
1857 gfx::Vector2d RenderWidget::GetScrollOffset() {
1858 // Bare RenderWidgets don't support scroll offset.
1859 return gfx::Vector2d();
1862 void RenderWidget::SetHidden(bool hidden) {
1863 if (is_hidden_ == hidden)
1864 return;
1866 // The status has changed. Tell the RenderThread about it and ensure
1867 // throttled acks are released in case frame production ceases.
1868 is_hidden_ = hidden;
1869 FlushPendingInputEventAck();
1871 if (is_hidden_)
1872 RenderThreadImpl::current()->WidgetHidden();
1873 else
1874 RenderThreadImpl::current()->WidgetRestored();
1877 void RenderWidget::DidToggleFullscreen() {
1878 if (!webwidget_)
1879 return;
1881 if (is_fullscreen_granted_) {
1882 webwidget_->didEnterFullScreen();
1883 } else {
1884 webwidget_->didExitFullScreen();
1888 bool RenderWidget::next_paint_is_resize_ack() const {
1889 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1892 void RenderWidget::set_next_paint_is_resize_ack() {
1893 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1896 void RenderWidget::set_next_paint_is_repaint_ack() {
1897 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1900 static bool IsDateTimeInput(ui::TextInputType type) {
1901 return type == ui::TEXT_INPUT_TYPE_DATE ||
1902 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1903 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1904 type == ui::TEXT_INPUT_TYPE_MONTH ||
1905 type == ui::TEXT_INPUT_TYPE_TIME ||
1906 type == ui::TEXT_INPUT_TYPE_WEEK;
1910 void RenderWidget::StartHandlingImeEvent() {
1911 DCHECK(!handling_ime_event_);
1912 handling_ime_event_ = true;
1915 void RenderWidget::FinishHandlingImeEvent() {
1916 DCHECK(handling_ime_event_);
1917 handling_ime_event_ = false;
1918 // While handling an ime event, text input state and selection bounds updates
1919 // are ignored. These must explicitly be updated once finished handling the
1920 // ime event.
1921 UpdateSelectionBounds();
1922 #if defined(OS_ANDROID)
1923 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1924 #endif
1927 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1928 ChangeSource change_source) {
1929 TRACE_EVENT0("renderer", "RenderWidget::UpdateTextInputState");
1930 if (handling_ime_event_)
1931 return;
1932 ui::TextInputType new_type = GetTextInputType();
1933 if (IsDateTimeInput(new_type))
1934 return; // Not considered as a text input field in WebKit/Chromium.
1936 blink::WebTextInputInfo new_info;
1937 if (webwidget_)
1938 new_info = webwidget_->textInputInfo();
1939 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1941 bool new_can_compose_inline = CanComposeInline();
1943 // Only sends text input params if they are changed or if the ime should be
1944 // shown.
1945 if (show_ime == SHOW_IME_IF_NEEDED ||
1946 (text_input_type_ != new_type ||
1947 text_input_mode_ != new_mode ||
1948 text_input_info_ != new_info ||
1949 can_compose_inline_ != new_can_compose_inline)
1950 #if defined(OS_ANDROID)
1951 || text_field_is_dirty_
1952 #endif
1954 ViewHostMsg_TextInputState_Params params;
1955 params.type = new_type;
1956 params.mode = new_mode;
1957 params.flags = new_info.flags;
1958 params.value = new_info.value.utf8();
1959 params.selection_start = new_info.selectionStart;
1960 params.selection_end = new_info.selectionEnd;
1961 params.composition_start = new_info.compositionStart;
1962 params.composition_end = new_info.compositionEnd;
1963 params.can_compose_inline = new_can_compose_inline;
1964 params.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1965 #if defined(USE_AURA)
1966 params.is_non_ime_change = true;
1967 #endif
1968 #if defined(OS_ANDROID)
1969 params.is_non_ime_change = (change_source == FROM_NON_IME) ||
1970 text_field_is_dirty_;
1971 if (params.is_non_ime_change)
1972 OnImeEventSentForAck(new_info);
1973 text_field_is_dirty_ = false;
1974 #endif
1975 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), params));
1977 text_input_info_ = new_info;
1978 text_input_type_ = new_type;
1979 text_input_mode_ = new_mode;
1980 can_compose_inline_ = new_can_compose_inline;
1981 text_input_flags_ = new_info.flags;
1985 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1986 WebRect focus_webrect;
1987 WebRect anchor_webrect;
1988 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1989 *focus = focus_webrect;
1990 *anchor = anchor_webrect;
1993 void RenderWidget::UpdateSelectionBounds() {
1994 TRACE_EVENT0("renderer", "RenderWidget::UpdateSelectionBounds");
1995 if (!webwidget_)
1996 return;
1997 if (handling_ime_event_)
1998 return;
2000 #if defined(USE_AURA)
2001 // TODO(mohsen): For now, always send explicit selection IPC notifications for
2002 // Aura beucause composited selection updates are not working for webview tags
2003 // which regresses IME inside webview. Remove this when composited selection
2004 // updates are fixed for webviews. See, http://crbug.com/510568.
2005 bool send_ipc = true;
2006 #else
2007 // With composited selection updates, the selection bounds will be reported
2008 // directly by the compositor, in which case explicit IPC selection
2009 // notifications should be suppressed.
2010 bool send_ipc =
2011 !blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled();
2012 #endif
2013 if (send_ipc) {
2014 ViewHostMsg_SelectionBounds_Params params;
2015 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2016 if (selection_anchor_rect_ != params.anchor_rect ||
2017 selection_focus_rect_ != params.focus_rect) {
2018 selection_anchor_rect_ = params.anchor_rect;
2019 selection_focus_rect_ = params.focus_rect;
2020 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2021 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2022 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2026 UpdateCompositionInfo(false);
2029 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2030 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2031 static_assert(int(blink::WebTextInputType##a) \
2032 == int(ui::TEXT_INPUT_TYPE_##b), \
2033 "mismatching enums: " #a)
2035 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2036 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2037 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2038 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2039 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2040 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2041 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2042 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2043 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2044 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2045 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2046 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2047 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2048 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2049 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2050 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2051 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2053 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2054 blink::WebTextInputType type) {
2055 // Check the type is in the range representable by ui::TextInputType.
2056 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2057 "blink::WebTextInputType and ui::TextInputType not synchronized";
2058 return static_cast<ui::TextInputType>(type);
2061 ui::TextInputType RenderWidget::GetTextInputType() {
2062 if (webwidget_)
2063 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2064 return ui::TEXT_INPUT_TYPE_NONE;
2067 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2068 #if defined(OS_ANDROID)
2069 // TODO(yukawa): Start sending character bounds when the browser side
2070 // implementation becomes ready (crbug.com/424866).
2071 #else
2072 TRACE_EVENT0("renderer", "RenderWidget::UpdateCompositionInfo");
2073 gfx::Range range = gfx::Range();
2074 if (should_update_range) {
2075 GetCompositionRange(&range);
2076 } else {
2077 range = composition_range_;
2079 std::vector<gfx::Rect> character_bounds;
2080 GetCompositionCharacterBounds(&character_bounds);
2082 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2083 return;
2084 composition_character_bounds_ = character_bounds;
2085 composition_range_ = range;
2086 Send(new InputHostMsg_ImeCompositionRangeChanged(
2087 routing_id(), composition_range_, composition_character_bounds_));
2088 #endif
2091 void RenderWidget::GetCompositionCharacterBounds(
2092 std::vector<gfx::Rect>* bounds) {
2093 DCHECK(bounds);
2094 bounds->clear();
2097 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2098 size_t location, length;
2099 if (webwidget_->compositionRange(&location, &length)) {
2100 range->set_start(location);
2101 range->set_end(location + length);
2102 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2103 range->set_start(location);
2104 range->set_end(location + length);
2105 } else {
2106 *range = gfx::Range::InvalidRange();
2110 bool RenderWidget::ShouldUpdateCompositionInfo(
2111 const gfx::Range& range,
2112 const std::vector<gfx::Rect>& bounds) {
2113 if (composition_range_ != range)
2114 return true;
2115 if (bounds.size() != composition_character_bounds_.size())
2116 return true;
2117 for (size_t i = 0; i < bounds.size(); ++i) {
2118 if (bounds[i] != composition_character_bounds_[i])
2119 return true;
2121 return false;
2124 #if defined(OS_ANDROID)
2125 bool RenderWidget::DoesRecordFullLayer() const {
2126 return false;
2128 #endif
2130 bool RenderWidget::CanComposeInline() {
2131 return true;
2134 WebScreenInfo RenderWidget::screenInfo() {
2135 return screen_info_;
2138 float RenderWidget::deviceScaleFactor() {
2139 return device_scale_factor_;
2142 void RenderWidget::resetInputMethod() {
2143 ImeEventGuard guard(this);
2144 // If the last text input type is not None, then we should finish any
2145 // ongoing composition regardless of the new text input type.
2146 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2147 // If a composition text exists, then we need to let the browser process
2148 // to cancel the input method's ongoing composition session.
2149 if (webwidget_->confirmComposition())
2150 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2153 UpdateCompositionInfo(true);
2156 #if defined(OS_ANDROID)
2157 void RenderWidget::showUnhandledTapUIIfNeeded(
2158 const WebPoint& tapped_position,
2159 const WebNode& tapped_node,
2160 bool page_changed) {
2161 DCHECK(handling_input_event_);
2162 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2163 !tapped_node.isContentEditable() &&
2164 !tapped_node.isInsideFocusableElementOrARIAWidget();
2165 if (should_trigger) {
2166 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2167 tapped_position.x, tapped_position.y));
2170 #endif
2172 void RenderWidget::didHandleGestureEvent(
2173 const WebGestureEvent& event,
2174 bool event_cancelled) {
2175 #if defined(OS_ANDROID) || defined(USE_AURA)
2176 if (event_cancelled)
2177 return;
2178 if (event.type == WebInputEvent::GestureTap) {
2179 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2180 } else if (event.type == WebInputEvent::GestureLongPress) {
2181 DCHECK(webwidget_);
2182 if (webwidget_->textInputInfo().value.isEmpty())
2183 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2184 else
2185 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2187 #endif
2190 void RenderWidget::didOverscroll(
2191 const blink::WebFloatSize& unusedDelta,
2192 const blink::WebFloatSize& accumulatedRootOverScroll,
2193 const blink::WebFloatPoint& position,
2194 const blink::WebFloatSize& velocity) {
2195 DidOverscrollParams params;
2196 params.accumulated_overscroll = gfx::Vector2dF(
2197 accumulatedRootOverScroll.width, accumulatedRootOverScroll.height);
2198 params.latest_overscroll_delta =
2199 gfx::Vector2dF(unusedDelta.width, unusedDelta.height);
2200 // TODO(sataya.m): don't negate velocity once http://crbug.com/499743 is
2201 // fixed.
2202 params.current_fling_velocity =
2203 gfx::Vector2dF(-velocity.width, -velocity.height);
2204 params.causal_event_viewport_point = gfx::PointF(position.x, position.y);
2206 // If we're currently handling an event, stash the overscroll data such that
2207 // it can be bundled in the event ack.
2208 if (handling_event_overscroll_) {
2209 handling_event_overscroll_->reset(new DidOverscrollParams(params));
2210 return;
2213 Send(new InputHostMsg_DidOverscroll(routing_id_, params));
2216 void RenderWidget::StartCompositor() {
2217 // For widgets that are never visible, we don't need the compositor to run
2218 // at all.
2219 if (never_visible_)
2220 return;
2221 // In tests without a RenderThreadImpl, don't set ready as this kicks
2222 // off creating output surfaces that the test can't create.
2223 if (!RenderThreadImpl::current())
2224 return;
2225 compositor_->StartCompositor();
2228 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2229 size_t i = 0;
2230 for (; i < plugin_window_moves_.size(); ++i) {
2231 if (plugin_window_moves_[i].window == move.window) {
2232 if (move.rects_valid) {
2233 plugin_window_moves_[i] = move;
2234 } else {
2235 plugin_window_moves_[i].visible = move.visible;
2237 break;
2241 if (i == plugin_window_moves_.size())
2242 plugin_window_moves_.push_back(move);
2245 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2246 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2247 i != plugin_window_moves_.end(); ++i) {
2248 if (i->window == window) {
2249 plugin_window_moves_.erase(i);
2250 break;
2256 RenderWidgetCompositor* RenderWidget::compositor() const {
2257 return compositor_.get();
2260 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2261 return false;
2264 bool RenderWidget::WillHandleGestureEvent(
2265 const blink::WebGestureEvent& event) {
2266 return false;
2269 void RenderWidget::ObserveWheelEventAndResult(
2270 const blink::WebMouseWheelEvent& wheel_event,
2271 const gfx::Vector2dF& wheel_unused_delta,
2272 bool event_processed) {
2273 if (!compositor_deps_->IsElasticOverscrollEnabled())
2274 return;
2276 cc::InputHandlerScrollResult scroll_result;
2277 scroll_result.did_scroll = event_processed;
2278 scroll_result.did_overscroll_root = !wheel_unused_delta.IsZero();
2279 scroll_result.unused_scroll_delta = wheel_unused_delta;
2281 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2282 InputHandlerManager* input_handler_manager =
2283 render_thread ? render_thread->input_handler_manager() : NULL;
2284 if (input_handler_manager) {
2285 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2286 routing_id_, wheel_event, scroll_result);
2290 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2291 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2294 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2295 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2296 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2297 "mismatching enums: " #a)
2299 inline content::TouchAction& operator|=(content::TouchAction& a,
2300 content::TouchAction b) {
2301 a = static_cast<content::TouchAction>(static_cast<int>(a) |
2302 static_cast<int>(b));
2303 return a;
2306 void RenderWidget::setTouchAction(
2307 blink::WebTouchAction web_touch_action) {
2309 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2310 // when blink is emulating touch with mouse).
2311 if (handling_event_type_ != WebInputEvent::TouchStart)
2312 return;
2314 // Verify the same values are used by the types so we can cast between them.
2315 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2316 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2317 STATIC_ASSERT_WTI_ENUM_MATCH(PanLeft, PAN_LEFT);
2318 STATIC_ASSERT_WTI_ENUM_MATCH(PanRight, PAN_RIGHT);
2319 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2320 STATIC_ASSERT_WTI_ENUM_MATCH(PanUp, PAN_UP);
2321 STATIC_ASSERT_WTI_ENUM_MATCH(PanDown, PAN_DOWN);
2322 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2323 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2325 content::TouchAction content_touch_action =
2326 static_cast<content::TouchAction>(web_touch_action);
2327 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2330 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2331 #if defined(OS_ANDROID)
2332 text_field_is_dirty_ = true;
2333 #endif
2336 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2337 return true;
2340 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2341 RenderWidget::CreateGraphicsContext3D(bool compositor) {
2342 if (!webwidget_)
2343 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2344 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2345 switches::kDisableGpuCompositing))
2346 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2347 if (!RenderThreadImpl::current())
2348 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2349 CauseForGpuLaunch cause =
2350 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2351 scoped_refptr<GpuChannelHost> gpu_channel_host(
2352 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2353 if (!gpu_channel_host.get())
2354 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2356 // Explicitly disable antialiasing for the compositor. As of the time of
2357 // this writing, the only platform that supported antialiasing for the
2358 // compositor was Mac OS X, because the on-screen OpenGL context creation
2359 // code paths on Windows and Linux didn't yet have multisampling support.
2360 // Mac OS X essentially always behaves as though it's rendering offscreen.
2361 // Multisampling has a heavy cost especially on devices with relatively low
2362 // fill rate like most notebooks, and the Mac implementation would need to
2363 // be optimized to resolve directly into the IOSurface shared between the
2364 // GPU and browser processes. For these reasons and to avoid platform
2365 // disparities we explicitly disable antialiasing.
2366 blink::WebGraphicsContext3D::Attributes attributes;
2367 attributes.antialias = false;
2368 attributes.shareResources = true;
2369 attributes.noAutomaticFlushes = true;
2370 attributes.depth = false;
2371 attributes.stencil = false;
2372 bool lose_context_when_out_of_memory = true;
2373 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2374 #if defined(OS_ANDROID)
2375 // If we raster too fast we become upload bound, and pending
2376 // uploads consume memory. For maximum upload throughput, we would
2377 // want to allow for upload_throughput * pipeline_time of pending
2378 // uploads, after which we are just wasting memory. Since we don't
2379 // know our upload throughput yet, this just caps our memory usage.
2380 size_t divider = 1;
2381 if (base::SysInfo::IsLowEndDevice())
2382 divider = 6;
2383 // For reference Nexus10 can upload 1MB in about 2.5ms.
2384 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2385 // Deadline to draw a frame to achieve 60 frames per second.
2386 const size_t kMillisecondsPerFrame = 16;
2387 // Assuming a two frame deep pipeline between the CPU and the GPU.
2388 size_t max_transfer_buffer_usage_mb =
2389 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2390 static const size_t kBytesPerMegabyte = 1024 * 1024;
2391 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2392 // to avoid unnecessarily stalling the compositor thread.
2393 limits.mapped_memory_reclaim_limit =
2394 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2395 #endif
2396 if (compositor) {
2397 limits.command_buffer_size = 64 * 1024;
2398 limits.start_transfer_buffer_size = 64 * 1024;
2399 limits.min_transfer_buffer_size = 64 * 1024;
2402 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2403 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2404 GetURLForGraphicsContext3D(),
2405 gpu_channel_host.get(),
2406 attributes,
2407 lose_context_when_out_of_memory,
2408 limits,
2409 NULL));
2410 return context.Pass();
2413 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2414 render_frame_proxies_.AddObserver(proxy);
2417 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2418 render_frame_proxies_.RemoveObserver(proxy);
2421 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2422 render_frames_.AddObserver(frame);
2425 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2426 render_frames_.RemoveObserver(frame);
2429 #if defined(VIDEO_HOLE)
2430 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2431 video_hole_frames_.AddObserver(frame);
2434 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2435 video_hole_frames_.RemoveObserver(frame);
2437 #endif // defined(VIDEO_HOLE)
2439 } // namespace content