third_party/re2: Remove remove-static-initializers.patch.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob1aab8b42fc06fd0573f5d5ab6d503e42ea25e637
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 "content/child/npapi/webplugin.h"
26 #include "content/common/gpu/client/context_provider_command_buffer.h"
27 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
28 #include "content/common/gpu/gpu_process_launch_causes.h"
29 #include "content/common/input/synthetic_gesture_packet.h"
30 #include "content/common/input/web_input_event_traits.h"
31 #include "content/common/input_messages.h"
32 #include "content/common/swapped_out_messages.h"
33 #include "content/common/view_messages.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/context_menu_params.h"
36 #include "content/renderer/cursor_utils.h"
37 #include "content/renderer/external_popup_menu.h"
38 #include "content/renderer/gpu/compositor_output_surface.h"
39 #include "content/renderer/gpu/compositor_software_output_device.h"
40 #include "content/renderer/gpu/delegated_compositor_output_surface.h"
41 #include "content/renderer/gpu/frame_swap_message_queue.h"
42 #include "content/renderer/gpu/mailbox_output_surface.h"
43 #include "content/renderer/gpu/queue_message_swap_promise.h"
44 #include "content/renderer/gpu/render_widget_compositor.h"
45 #include "content/renderer/ime_event_guard.h"
46 #include "content/renderer/input/input_handler_manager.h"
47 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
48 #include "content/renderer/render_frame_impl.h"
49 #include "content/renderer/render_frame_proxy.h"
50 #include "content/renderer/render_process.h"
51 #include "content/renderer/render_thread_impl.h"
52 #include "content/renderer/renderer_blink_platform_impl.h"
53 #include "content/renderer/resizing_mode_selector.h"
54 #include "ipc/ipc_sync_message.h"
55 #include "skia/ext/platform_canvas.h"
56 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
57 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
58 #include "third_party/WebKit/public/platform/WebPoint.h"
59 #include "third_party/WebKit/public/platform/WebRect.h"
60 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
61 #include "third_party/WebKit/public/platform/WebSize.h"
62 #include "third_party/WebKit/public/platform/WebString.h"
63 #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
64 #include "third_party/WebKit/public/web/WebFrameWidget.h"
65 #include "third_party/WebKit/public/web/WebLocalFrame.h"
66 #include "third_party/WebKit/public/web/WebNode.h"
67 #include "third_party/WebKit/public/web/WebPagePopup.h"
68 #include "third_party/WebKit/public/web/WebPopupMenu.h"
69 #include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
70 #include "third_party/WebKit/public/web/WebRange.h"
71 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
72 #include "third_party/WebKit/public/web/WebView.h"
73 #include "third_party/skia/include/core/SkShader.h"
74 #include "ui/base/ui_base_switches.h"
75 #include "ui/gfx/frame_time.h"
76 #include "ui/gfx/geometry/point_conversions.h"
77 #include "ui/gfx/geometry/rect_conversions.h"
78 #include "ui/gfx/geometry/size_conversions.h"
79 #include "ui/gfx/skia_util.h"
80 #include "ui/gl/gl_switches.h"
81 #include "ui/surface/transport_dib.h"
83 #if defined(OS_ANDROID)
84 #include <android/keycodes.h>
85 #include "content/renderer/android/synchronous_compositor_factory.h"
86 #endif
88 #if defined(OS_POSIX)
89 #include "ipc/ipc_channel_posix.h"
90 #include "third_party/skia/include/core/SkMallocPixelRef.h"
91 #include "third_party/skia/include/core/SkPixelRef.h"
92 #endif // defined(OS_POSIX)
94 #include "third_party/WebKit/public/web/WebWidget.h"
96 using blink::WebCompositionUnderline;
97 using blink::WebCursorInfo;
98 using blink::WebDeviceEmulationParams;
99 using blink::WebGestureEvent;
100 using blink::WebInputEvent;
101 using blink::WebKeyboardEvent;
102 using blink::WebMouseEvent;
103 using blink::WebMouseWheelEvent;
104 using blink::WebNavigationPolicy;
105 using blink::WebNode;
106 using blink::WebPagePopup;
107 using blink::WebPoint;
108 using blink::WebPopupMenu;
109 using blink::WebPopupMenuInfo;
110 using blink::WebPopupType;
111 using blink::WebRange;
112 using blink::WebRect;
113 using blink::WebScreenInfo;
114 using blink::WebSize;
115 using blink::WebTextDirection;
116 using blink::WebTouchEvent;
117 using blink::WebTouchPoint;
118 using blink::WebVector;
119 using blink::WebWidget;
121 namespace {
123 typedef std::map<std::string, ui::TextInputMode> TextInputModeMap;
125 class TextInputModeMapSingleton {
126 public:
127 static TextInputModeMapSingleton* GetInstance() {
128 return Singleton<TextInputModeMapSingleton>::get();
130 TextInputModeMapSingleton() {
131 map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM;
132 map_["latin"] = ui::TEXT_INPUT_MODE_LATIN;
133 map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME;
134 map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE;
135 map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN;
136 map_["kana"] = ui::TEXT_INPUT_MODE_KANA;
137 map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA;
138 map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC;
139 map_["tel"] = ui::TEXT_INPUT_MODE_TEL;
140 map_["email"] = ui::TEXT_INPUT_MODE_EMAIL;
141 map_["url"] = ui::TEXT_INPUT_MODE_URL;
143 const TextInputModeMap& map() const { return map_; }
144 private:
145 TextInputModeMap map_;
147 friend struct DefaultSingletonTraits<TextInputModeMapSingleton>;
149 DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton);
152 ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) {
153 static TextInputModeMapSingleton* singleton =
154 TextInputModeMapSingleton::GetInstance();
155 TextInputModeMap::const_iterator it =
156 singleton->map().find(input_mode.utf8());
157 if (it == singleton->map().end())
158 return ui::TEXT_INPUT_MODE_DEFAULT;
159 return it->second;
162 // TODO(brianderson): Replace the hard-coded threshold with a fraction of
163 // the BeginMainFrame interval.
164 // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to
165 // be spent in input hanlders before input starts getting throttled.
166 const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166;
168 int64 GetEventLatencyMicros(const WebInputEvent& event, base::TimeTicks now) {
169 return (now - base::TimeDelta::FromSecondsD(event.timeStampSeconds))
170 .ToInternalValue();
173 void LogInputEventLatencyUma(const WebInputEvent& event, base::TimeTicks now) {
174 UMA_HISTOGRAM_CUSTOM_COUNTS(
175 "Event.AggregatedLatency.Renderer2",
176 GetEventLatencyMicros(event, now),
178 10000000,
179 100);
181 #define CASE_TYPE(t) \
182 case WebInputEvent::t: \
183 UMA_HISTOGRAM_CUSTOM_COUNTS( \
184 "Event.Latency.Renderer2." #t, \
185 GetEventLatencyMicros(event, now), \
186 1, \
187 10000000, \
188 100); \
189 break;
191 switch(event.type) {
192 CASE_TYPE(Undefined);
193 CASE_TYPE(MouseDown);
194 CASE_TYPE(MouseUp);
195 CASE_TYPE(MouseMove);
196 CASE_TYPE(MouseEnter);
197 CASE_TYPE(MouseLeave);
198 CASE_TYPE(ContextMenu);
199 CASE_TYPE(MouseWheel);
200 CASE_TYPE(RawKeyDown);
201 CASE_TYPE(KeyDown);
202 CASE_TYPE(KeyUp);
203 CASE_TYPE(Char);
204 CASE_TYPE(GestureScrollBegin);
205 CASE_TYPE(GestureScrollEnd);
206 CASE_TYPE(GestureScrollUpdate);
207 CASE_TYPE(GestureFlingStart);
208 CASE_TYPE(GestureFlingCancel);
209 CASE_TYPE(GestureShowPress);
210 CASE_TYPE(GestureTap);
211 CASE_TYPE(GestureTapUnconfirmed);
212 CASE_TYPE(GestureTapDown);
213 CASE_TYPE(GestureTapCancel);
214 CASE_TYPE(GestureDoubleTap);
215 CASE_TYPE(GestureTwoFingerTap);
216 CASE_TYPE(GestureLongPress);
217 CASE_TYPE(GestureLongTap);
218 CASE_TYPE(GesturePinchBegin);
219 CASE_TYPE(GesturePinchEnd);
220 CASE_TYPE(GesturePinchUpdate);
221 CASE_TYPE(TouchStart);
222 CASE_TYPE(TouchMove);
223 CASE_TYPE(TouchEnd);
224 CASE_TYPE(TouchCancel);
225 default:
226 // Must include default to let blink::WebInputEvent add new event types
227 // before they're added here.
228 DLOG(WARNING) << "Unhandled WebInputEvent type: " << event.type;
229 break;
232 #undef CASE_TYPE
235 } // namespace
237 namespace content {
239 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
241 class RenderWidget::ScreenMetricsEmulator {
242 public:
243 ScreenMetricsEmulator(
244 RenderWidget* widget,
245 const WebDeviceEmulationParams& params);
246 virtual ~ScreenMetricsEmulator();
248 // Scale and offset used to convert between host coordinates
249 // and webwidget coordinates.
250 float scale() { return scale_; }
251 gfx::PointF offset() { return offset_; }
252 gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
253 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
254 const WebScreenInfo& original_screen_info() { return original_screen_info_; }
256 void ChangeEmulationParams(
257 const WebDeviceEmulationParams& params);
259 // The following methods alter handlers' behavior for messages related to
260 // widget size and position.
261 void OnResizeMessage(const ViewMsg_Resize_Params& params);
262 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
263 const gfx::Rect& window_screen_rect);
264 void OnShowContextMenu(ContextMenuParams* params);
265 gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
267 private:
268 void Reapply();
269 void Apply(bool top_controls_shrink_blink_size,
270 float top_controls_height,
271 gfx::Rect resizer_rect,
272 bool is_fullscreen_granted,
273 blink::WebDisplayMode display_mode);
275 RenderWidget* widget_;
277 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
278 WebDeviceEmulationParams params_;
280 // The computed scale and offset used to fit widget into browser window.
281 float scale_;
282 gfx::PointF offset_;
284 // Widget rect as passed to webwidget.
285 gfx::Rect applied_widget_rect_;
287 // Original values to restore back after emulation ends.
288 gfx::Size original_size_;
289 gfx::Size original_physical_backing_size_;
290 gfx::Size original_visible_viewport_size_;
291 blink::WebScreenInfo original_screen_info_;
292 gfx::Rect original_view_screen_rect_;
293 gfx::Rect original_window_screen_rect_;
296 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
297 RenderWidget* widget,
298 const WebDeviceEmulationParams& params)
299 : widget_(widget),
300 params_(params),
301 scale_(1.f) {
302 original_size_ = widget_->size_;
303 original_physical_backing_size_ = widget_->physical_backing_size_;
304 original_visible_viewport_size_ = widget_->visible_viewport_size_;
305 original_screen_info_ = widget_->screen_info_;
306 original_view_screen_rect_ = widget_->view_screen_rect_;
307 original_window_screen_rect_ = widget_->window_screen_rect_;
308 Apply(widget_->top_controls_shrink_blink_size_,
309 widget_->top_controls_height_,
310 widget_->resizer_rect_,
311 widget_->is_fullscreen_granted_,
312 widget_->display_mode_);
315 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
316 widget_->screen_info_ = original_screen_info_;
318 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
319 widget_->SetScreenMetricsEmulationParameters(false, params_);
320 widget_->view_screen_rect_ = original_view_screen_rect_;
321 widget_->window_screen_rect_ = original_window_screen_rect_;
322 widget_->Resize(original_size_,
323 original_physical_backing_size_,
324 widget_->top_controls_shrink_blink_size_,
325 widget_->top_controls_height_,
326 original_visible_viewport_size_,
327 widget_->resizer_rect_,
328 widget_->is_fullscreen_granted_,
329 widget_->display_mode_,
330 NO_RESIZE_ACK);
333 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
334 const WebDeviceEmulationParams& params) {
335 params_ = params;
336 Reapply();
339 void RenderWidget::ScreenMetricsEmulator::Reapply() {
340 Apply(widget_->top_controls_shrink_blink_size_,
341 widget_->top_controls_height_,
342 widget_->resizer_rect_,
343 widget_->is_fullscreen_granted_,
344 widget_->display_mode_);
347 void RenderWidget::ScreenMetricsEmulator::Apply(
348 bool top_controls_shrink_blink_size,
349 float top_controls_height,
350 gfx::Rect resizer_rect,
351 bool is_fullscreen_granted,
352 blink::WebDisplayMode display_mode) {
353 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
354 if (!applied_widget_rect_.width())
355 applied_widget_rect_.set_width(original_size_.width());
356 if (!applied_widget_rect_.height())
357 applied_widget_rect_.set_height(original_size_.height());
359 if (params_.fitToView && !original_size_.IsEmpty()) {
360 int original_width = std::max(original_size_.width(), 1);
361 int original_height = std::max(original_size_.height(), 1);
362 float width_ratio =
363 static_cast<float>(applied_widget_rect_.width()) / original_width;
364 float height_ratio =
365 static_cast<float>(applied_widget_rect_.height()) / original_height;
366 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
367 scale_ = 1.f / ratio;
369 // Center emulated view inside available view space.
370 offset_.set_x(
371 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
372 offset_.set_y(
373 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
374 } else {
375 scale_ = params_.scale;
376 offset_.SetPoint(params_.offset.x, params_.offset.y);
379 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
380 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
381 widget_->screen_info_.rect = original_screen_info_.rect;
382 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
383 widget_->window_screen_rect_ = original_window_screen_rect_;
384 } else {
385 applied_widget_rect_.set_origin(gfx::Point(0, 0));
386 widget_->screen_info_.rect = applied_widget_rect_;
387 widget_->screen_info_.availableRect = applied_widget_rect_;
388 widget_->window_screen_rect_ = applied_widget_rect_;
391 float applied_device_scale_factor = params_.deviceScaleFactor ?
392 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
393 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
395 // Pass three emulation parameters to the blink side:
396 // - we keep the real device scale factor in compositor to produce sharp image
397 // even when emulating different scale factor;
398 // - in order to fit into view, WebView applies offset and scale to the
399 // root layer.
400 blink::WebDeviceEmulationParams modified_params = params_;
401 modified_params.deviceScaleFactor = original_screen_info_.deviceScaleFactor;
402 modified_params.offset = blink::WebFloatPoint(offset_.x(), offset_.y());
403 modified_params.scale = scale_;
404 widget_->SetScreenMetricsEmulationParameters(true, modified_params);
406 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
407 widget_->view_screen_rect_ = applied_widget_rect_;
409 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
410 original_size_, original_screen_info_.deviceScaleFactor));
411 widget_->Resize(applied_widget_rect_.size(),
412 physical_backing_size,
413 top_controls_shrink_blink_size,
414 top_controls_height,
415 applied_widget_rect_.size(),
416 resizer_rect,
417 is_fullscreen_granted,
418 display_mode,
419 NO_RESIZE_ACK);
422 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
423 const ViewMsg_Resize_Params& params) {
424 bool need_ack = params.new_size != original_size_ &&
425 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
426 original_size_ = params.new_size;
427 original_physical_backing_size_ = params.physical_backing_size;
428 original_screen_info_ = params.screen_info;
429 original_visible_viewport_size_ = params.visible_viewport_size;
430 Apply(params.top_controls_shrink_blink_size,
431 params.top_controls_height,
432 params.resizer_rect,
433 params.is_fullscreen_granted,
434 params.display_mode);
436 if (need_ack) {
437 widget_->set_next_paint_is_resize_ack();
438 if (widget_->compositor_)
439 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
443 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
444 const gfx::Rect& view_screen_rect,
445 const gfx::Rect& window_screen_rect) {
446 original_view_screen_rect_ = view_screen_rect;
447 original_window_screen_rect_ = window_screen_rect;
448 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
449 Reapply();
452 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
453 ContextMenuParams* params) {
454 params->x *= scale_;
455 params->x += offset_.x();
456 params->y *= scale_;
457 params->y += offset_.y();
460 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
461 const gfx::Rect& anchor) {
462 gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
463 scaled.set_x(scaled.x() + offset_.x());
464 scaled.set_y(scaled.y() + offset_.y());
465 return scaled;
468 // RenderWidget ---------------------------------------------------------------
470 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
471 const blink::WebScreenInfo& screen_info,
472 bool swapped_out,
473 bool hidden,
474 bool never_visible)
475 : routing_id_(MSG_ROUTING_NONE),
476 surface_id_(0),
477 compositor_deps_(nullptr),
478 webwidget_(nullptr),
479 opener_id_(MSG_ROUTING_NONE),
480 init_complete_(false),
481 top_controls_shrink_blink_size_(false),
482 top_controls_height_(0.f),
483 next_paint_flags_(0),
484 auto_resize_mode_(false),
485 need_update_rect_for_auto_resize_(false),
486 did_show_(false),
487 is_hidden_(hidden),
488 never_visible_(never_visible),
489 is_fullscreen_granted_(false),
490 display_mode_(blink::WebDisplayModeUndefined),
491 has_focus_(false),
492 handling_input_event_(false),
493 handling_ime_event_(false),
494 handling_event_type_(WebInputEvent::Undefined),
495 ignore_ack_for_mouse_move_from_debugger_(false),
496 closing_(false),
497 host_closing_(false),
498 is_swapped_out_(swapped_out),
499 input_method_is_active_(false),
500 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
501 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
502 text_input_flags_(0),
503 can_compose_inline_(true),
504 popup_type_(popup_type),
505 pending_window_rect_count_(0),
506 suppress_next_char_events_(false),
507 screen_info_(screen_info),
508 device_scale_factor_(screen_info_.deviceScaleFactor),
509 current_event_latency_info_(NULL),
510 next_output_surface_id_(0),
511 #if defined(OS_ANDROID)
512 text_field_is_dirty_(false),
513 outstanding_ime_acks_(0),
514 body_background_color_(SK_ColorWHITE),
515 #endif
516 popup_origin_scale_for_emulation_(0.f),
517 frame_swap_message_queue_(new FrameSwapMessageQueue()),
518 resizing_mode_selector_(new ResizingModeSelector()),
519 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
520 has_host_context_menu_location_(false) {
521 if (!swapped_out)
522 RenderProcess::current()->AddRefProcess();
523 DCHECK(RenderThread::Get());
524 device_color_profile_.push_back('0');
527 RenderWidget::~RenderWidget() {
528 DCHECK(!webwidget_) << "Leaking our WebWidget!";
530 // If we are swapped out, we have released already.
531 if (!is_swapped_out_ && RenderProcess::current())
532 RenderProcess::current()->ReleaseProcess();
535 // static
536 RenderWidget* RenderWidget::Create(int32 opener_id,
537 CompositorDependencies* compositor_deps,
538 blink::WebPopupType popup_type,
539 const blink::WebScreenInfo& screen_info) {
540 DCHECK(opener_id != MSG_ROUTING_NONE);
541 scoped_refptr<RenderWidget> widget(
542 new RenderWidget(popup_type, screen_info, false, false, false));
543 if (widget->Init(opener_id, compositor_deps)) { // adds reference on success.
544 return widget.get();
546 return NULL;
549 // static
550 RenderWidget* RenderWidget::CreateForFrame(
551 int routing_id,
552 int surface_id,
553 bool hidden,
554 const blink::WebScreenInfo& screen_info,
555 CompositorDependencies* compositor_deps,
556 blink::WebLocalFrame* frame) {
557 CHECK_NE(routing_id, MSG_ROUTING_NONE);
558 scoped_refptr<RenderWidget> widget(new RenderWidget(
559 blink::WebPopupTypeNone, screen_info, false, hidden, false));
560 widget->routing_id_ = routing_id;
561 widget->surface_id_ = surface_id;
562 widget->compositor_deps_ = compositor_deps;
563 // DoInit increments the reference count on |widget|, keeping it alive after
564 // this function returns.
565 if (widget->DoInit(MSG_ROUTING_NONE, compositor_deps,
566 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
567 nullptr)) {
568 widget->CompleteInit();
569 return widget.get();
571 return nullptr;
574 // static
575 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
576 switch (render_widget->popup_type_) {
577 case blink::WebPopupTypeNone: // Nothing to create.
578 break;
579 case blink::WebPopupTypeSelect:
580 case blink::WebPopupTypeSuggestion:
581 return WebPopupMenu::create(render_widget);
582 case blink::WebPopupTypePage:
583 return WebPagePopup::create(render_widget);
584 default:
585 NOTREACHED();
587 return NULL;
590 // static
591 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
592 RenderWidget* render_widget,
593 blink::WebLocalFrame* frame) {
594 return blink::WebFrameWidget::create(render_widget, frame);
597 bool RenderWidget::Init(int32 opener_id,
598 CompositorDependencies* compositor_deps) {
599 return DoInit(opener_id, compositor_deps, RenderWidget::CreateWebWidget(this),
600 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
601 &routing_id_, &surface_id_));
604 bool RenderWidget::DoInit(int32 opener_id,
605 CompositorDependencies* compositor_deps,
606 WebWidget* web_widget,
607 IPC::SyncMessage* create_widget_message) {
608 DCHECK(!webwidget_);
610 if (opener_id != MSG_ROUTING_NONE)
611 opener_id_ = opener_id;
613 compositor_deps_ = compositor_deps;
614 webwidget_ = web_widget;
616 bool result = true;
617 if (create_widget_message)
618 result = RenderThread::Get()->Send(create_widget_message);
620 if (result) {
621 RenderThread::Get()->AddRoute(routing_id_, this);
622 // Take a reference on behalf of the RenderThread. This will be balanced
623 // when we receive ViewMsg_Close.
624 AddRef();
625 if (RenderThreadImpl::current()) {
626 RenderThreadImpl::current()->WidgetCreated();
627 if (is_hidden_)
628 RenderThreadImpl::current()->WidgetHidden();
630 return true;
631 } else {
632 // The above Send can fail when the tab is closing.
633 return false;
637 // This is used to complete pending inits and non-pending inits.
638 void RenderWidget::CompleteInit() {
639 DCHECK(routing_id_ != MSG_ROUTING_NONE);
641 init_complete_ = true;
643 if (compositor_)
644 StartCompositor();
646 Send(new ViewHostMsg_RenderViewReady(routing_id_));
649 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
650 // We should only toggle between states.
651 DCHECK(is_swapped_out_ != is_swapped_out);
652 is_swapped_out_ = is_swapped_out;
654 // If we are swapping out, we will call ReleaseProcess, allowing the process
655 // to exit if all of its RenderViews are swapped out. We wait until the
656 // WasSwappedOut call to do this, to allow the unload handler to finish.
657 // If we are swapping in, we call AddRefProcess to prevent the process from
658 // exiting.
659 if (!is_swapped_out_)
660 RenderProcess::current()->AddRefProcess();
663 void RenderWidget::WasSwappedOut() {
664 // If we have been swapped out and no one else is using this process,
665 // it's safe to exit now.
666 CHECK(is_swapped_out_);
667 RenderProcess::current()->ReleaseProcess();
670 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
671 ScreenMetricsEmulator* emulator) {
672 popup_origin_scale_for_emulation_ = emulator->scale();
673 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
674 popup_screen_origin_for_emulation_ = gfx::Point(
675 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
676 emulator->original_screen_rect().origin().y() + emulator->offset().y());
677 screen_info_ = emulator->original_screen_info();
678 device_scale_factor_ = screen_info_.deviceScaleFactor;
681 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
682 if (screen_metrics_emulator_)
683 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
684 return anchor;
687 void RenderWidget::SetScreenMetricsEmulationParameters(
688 bool enabled,
689 const blink::WebDeviceEmulationParams& params) {
690 // This is only supported in RenderView.
691 NOTREACHED();
694 #if defined(OS_MACOSX) || defined(OS_ANDROID)
695 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
696 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
697 popup->SetOriginScaleAndOffsetForEmulation(
698 emulator->scale(), emulator->offset());
700 #endif
702 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
703 if (screen_metrics_emulator_)
704 screen_metrics_emulator_->OnShowContextMenu(params);
707 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
708 if (compositor_) {
709 // Regardless of whether threaded compositing is enabled, always
710 // use this mechanism to force the compositor to redraw. However,
711 // the invalidation code path below is still needed for the
712 // non-threaded case.
713 compositor_->SetNeedsForcedRedraw();
715 scheduleComposite();
718 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
719 bool handled = true;
720 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
721 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
722 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
723 OnCursorVisibilityChange)
724 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
725 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
726 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
727 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
728 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
729 OnSyntheticGestureCompleted)
730 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
731 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
732 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
733 IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation,
734 OnEnableDeviceEmulation)
735 IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation,
736 OnDisableDeviceEmulation)
737 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
738 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
739 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
740 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
741 IPC_MESSAGE_HANDLER(ViewMsg_SetInputMethodActive, OnSetInputMethodActive)
742 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowShown, OnCandidateWindowShown)
743 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowUpdated,
744 OnCandidateWindowUpdated)
745 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowHidden, OnCandidateWindowHidden)
746 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
747 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
748 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
749 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
750 #if defined(OS_ANDROID)
751 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
752 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
753 #endif
754 IPC_MESSAGE_UNHANDLED(handled = false)
755 IPC_END_MESSAGE_MAP()
756 return handled;
759 bool RenderWidget::Send(IPC::Message* message) {
760 // Don't send any messages after the browser has told us to close, and filter
761 // most outgoing messages while swapped out.
762 if ((is_swapped_out_ &&
763 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
764 closing_) {
765 delete message;
766 return false;
769 // If given a messsage without a routing ID, then assign our routing ID.
770 if (message->routing_id() == MSG_ROUTING_NONE)
771 message->set_routing_id(routing_id_);
773 return RenderThread::Get()->Send(message);
776 void RenderWidget::Resize(const gfx::Size& new_size,
777 const gfx::Size& physical_backing_size,
778 bool top_controls_shrink_blink_size,
779 float top_controls_height,
780 const gfx::Size& visible_viewport_size,
781 const gfx::Rect& resizer_rect,
782 bool is_fullscreen_granted,
783 blink::WebDisplayMode display_mode,
784 const ResizeAck resize_ack) {
785 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
786 // A resize ack shouldn't be requested if we have not ACK'd the previous
787 // one.
788 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
789 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
792 // Ignore this during shutdown.
793 if (!webwidget_)
794 return;
796 if (compositor_) {
797 compositor_->setViewportSize(new_size, physical_backing_size);
800 physical_backing_size_ = physical_backing_size;
801 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
802 top_controls_height_ = top_controls_height;
803 visible_viewport_size_ = visible_viewport_size;
804 resizer_rect_ = resizer_rect;
806 // NOTE: We may have entered fullscreen mode without changing our size.
807 bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted;
808 if (fullscreen_change)
809 WillToggleFullscreen();
810 is_fullscreen_granted_ = is_fullscreen_granted;
811 display_mode_ = display_mode;
813 webwidget_->setTopControlsHeight(top_controls_height,
814 top_controls_shrink_blink_size_);
816 if (size_ != new_size) {
817 size_ = new_size;
819 // When resizing, we want to wait to paint before ACK'ing the resize. This
820 // ensures that we only resize as fast as we can paint. We only need to
821 // send an ACK if we are resized to a non-empty rect.
822 webwidget_->resize(new_size);
825 webwidget()->resizePinchViewport(gfx::Size(
826 visible_viewport_size.width(),
827 visible_viewport_size.height()));
829 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
830 // In this case there is no paint/composite and therefore no
831 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
832 // ack through a fake ViewHostMsg_UpdateRect or a different message.
833 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
836 // Send the Resize_ACK flag once we paint again if requested.
837 if (resize_ack == SEND_RESIZE_ACK)
838 set_next_paint_is_resize_ack();
840 if (fullscreen_change)
841 DidToggleFullscreen();
843 // If a resize ack is requested and it isn't set-up, then no more resizes will
844 // come in and in general things will go wrong.
845 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
848 void RenderWidget::SetWindowRectSynchronously(
849 const gfx::Rect& new_window_rect) {
850 Resize(new_window_rect.size(),
851 new_window_rect.size(),
852 top_controls_shrink_blink_size_,
853 top_controls_height_,
854 new_window_rect.size(),
855 gfx::Rect(),
856 is_fullscreen_granted_,
857 display_mode_,
858 NO_RESIZE_ACK);
859 view_screen_rect_ = new_window_rect;
860 window_screen_rect_ = new_window_rect;
861 if (!did_show_)
862 initial_rect_ = new_window_rect;
865 void RenderWidget::OnClose() {
866 if (closing_)
867 return;
868 NotifyOnClose();
869 closing_ = true;
871 // Browser correspondence is no longer needed at this point.
872 if (routing_id_ != MSG_ROUTING_NONE) {
873 RenderThread::Get()->RemoveRoute(routing_id_);
874 SetHidden(false);
875 if (RenderThreadImpl::current())
876 RenderThreadImpl::current()->WidgetDestroyed();
879 // If there is a Send call on the stack, then it could be dangerous to close
880 // now. Post a task that only gets invoked when there are no nested message
881 // loops.
882 RenderThread::Get()->GetTaskRunner()->PostNonNestableTask(
883 FROM_HERE, base::Bind(&RenderWidget::Close, this));
885 // Balances the AddRef taken when we called AddRoute.
886 Release();
889 // Got a response from the browser after the renderer decided to create a new
890 // view.
891 void RenderWidget::OnCreatingNewAck() {
892 DCHECK(routing_id_ != MSG_ROUTING_NONE);
894 CompleteInit();
897 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
898 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
899 return;
901 if (screen_metrics_emulator_) {
902 screen_metrics_emulator_->OnResizeMessage(params);
903 return;
906 bool orientation_changed =
907 screen_info_.orientationAngle != params.screen_info.orientationAngle;
909 screen_info_ = params.screen_info;
910 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
911 Resize(params.new_size,
912 params.physical_backing_size,
913 params.top_controls_shrink_blink_size,
914 params.top_controls_height,
915 params.visible_viewport_size,
916 params.resizer_rect,
917 params.is_fullscreen_granted,
918 params.display_mode,
919 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
921 if (orientation_changed)
922 OnOrientationChange();
925 void RenderWidget::OnEnableDeviceEmulation(
926 const blink::WebDeviceEmulationParams& params) {
927 if (!screen_metrics_emulator_)
928 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
929 else
930 screen_metrics_emulator_->ChangeEmulationParams(params);
933 void RenderWidget::OnDisableDeviceEmulation() {
934 screen_metrics_emulator_.reset();
937 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
938 SetDeviceColorProfile(color_profile);
941 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
942 if (resizer_rect_ == resizer_rect)
943 return;
944 resizer_rect_ = resizer_rect;
945 if (webwidget_)
946 webwidget_->didChangeWindowResizerRect();
949 void RenderWidget::OnWasHidden() {
950 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
951 // Go into a mode where we stop generating paint and scrolling events.
952 SetHidden(true);
953 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
954 WasHidden());
957 void RenderWidget::OnWasShown(bool needs_repainting,
958 const ui::LatencyInfo& latency_info) {
959 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
960 // During shutdown we can just ignore this message.
961 if (!webwidget_)
962 return;
964 // See OnWasHidden
965 SetHidden(false);
966 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
967 WasShown());
969 if (!needs_repainting)
970 return;
972 // Generate a full repaint.
973 if (compositor_) {
974 ui::LatencyInfo swap_latency_info(latency_info);
975 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
976 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
977 compositor_->SetNeedsForcedRedraw();
979 scheduleComposite();
982 void RenderWidget::OnRequestMoveAck() {
983 DCHECK(pending_window_rect_count_);
984 pending_window_rect_count_--;
987 GURL RenderWidget::GetURLForGraphicsContext3D() {
988 return GURL();
991 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
992 // For widgets that are never visible, we don't start the compositor, so we
993 // never get a request for a cc::OutputSurface.
994 DCHECK(!never_visible_);
996 #if defined(OS_ANDROID)
997 if (SynchronousCompositorFactory* factory =
998 SynchronousCompositorFactory::GetInstance()) {
999 return factory->CreateOutputSurface(routing_id(),
1000 frame_swap_message_queue_);
1002 #endif
1004 const base::CommandLine& command_line =
1005 *base::CommandLine::ForCurrentProcess();
1006 bool use_software = fallback;
1007 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1008 use_software = true;
1010 scoped_refptr<ContextProviderCommandBuffer> context_provider;
1011 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
1012 if (!use_software) {
1013 context_provider = ContextProviderCommandBuffer::Create(
1014 CreateGraphicsContext3D(), "RenderCompositor");
1015 if (!context_provider.get()) {
1016 // Cause the compositor to wait and try again.
1017 return scoped_ptr<cc::OutputSurface>();
1020 worker_context_provider = ContextProviderCommandBuffer::Create(
1021 CreateGraphicsContext3D(), "RenderWorker");
1022 if (!worker_context_provider.get()) {
1023 // Cause the compositor to wait and try again.
1024 return scoped_ptr<cc::OutputSurface>();
1028 uint32 output_surface_id = next_output_surface_id_++;
1029 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1030 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1031 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1032 routing_id(), output_surface_id, context_provider,
1033 worker_context_provider, frame_swap_message_queue_));
1035 if (!context_provider.get()) {
1036 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1037 new CompositorSoftwareOutputDevice());
1039 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1040 routing_id(), output_surface_id, nullptr, nullptr,
1041 software_device.Pass(), frame_swap_message_queue_, true));
1044 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1045 // Composite-to-mailbox is currently used for layout tests in order to cause
1046 // them to draw inside in the renderer to do the readback there. This should
1047 // no longer be the case when crbug.com/311404 is fixed.
1048 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1049 cc::ResourceFormat format = cc::RGBA_8888;
1050 if (base::SysInfo::IsLowEndDevice())
1051 format = cc::RGB_565;
1052 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1053 routing_id(), output_surface_id, context_provider,
1054 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1055 frame_swap_message_queue_, format));
1057 bool use_swap_compositor_frame_message = false;
1058 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1059 routing_id(), output_surface_id, context_provider,
1060 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1061 frame_swap_message_queue_, use_swap_compositor_frame_message));
1064 void RenderWidget::OnSwapBuffersAborted() {
1065 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1066 // Schedule another frame so the compositor learns about it.
1067 scheduleComposite();
1070 void RenderWidget::OnSwapBuffersPosted() {
1071 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1074 void RenderWidget::OnSwapBuffersComplete() {
1075 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1077 // Notify subclasses that composited rendering was flushed to the screen.
1078 DidFlushPaint();
1081 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1082 const ui::LatencyInfo& latency_info,
1083 bool is_keyboard_shortcut) {
1084 base::AutoReset<bool> handling_input_event_resetter(
1085 &handling_input_event_, true);
1086 if (!input_event)
1087 return;
1088 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1089 &handling_event_type_, input_event->type);
1090 #if defined(OS_ANDROID)
1091 // On Android, when a key is pressed or sent from the Keyboard using IME,
1092 // |AdapterInputConnection| generates input key events to make sure all JS
1093 // listeners that monitor KeyUp and KeyDown events receive the proper key
1094 // code. Since this input key event comes from IME, we need to set the
1095 // IME event guard here to make sure it does not interfere with other IME
1096 // events.
1097 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1098 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1099 const WebKeyboardEvent& key_event =
1100 *static_cast<const WebKeyboardEvent*>(input_event);
1101 // Some keys are special and it's essential that no events get blocked.
1102 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1103 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1104 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1105 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1106 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1107 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1108 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1110 #endif
1112 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
1113 &latency_info);
1115 base::TimeTicks start_time;
1116 if (base::TimeTicks::IsHighResolution())
1117 start_time = base::TimeTicks::Now();
1119 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1120 "event", WebInputEventTraits::GetName(input_event->type));
1121 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1122 TRACE_EVENT_FLOW_STEP0(
1123 "input,benchmark",
1124 "LatencyInfo.Flow",
1125 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
1126 "HanldeInputEventMain");
1128 // If we don't have a high res timer, these metrics won't be accurate enough
1129 // to be worth collecting. Note that this does introduce some sampling bias.
1130 if (!start_time.is_null())
1131 LogInputEventLatencyUma(*input_event, start_time);
1133 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1134 ui::LatencyInfo swap_latency_info(latency_info);
1135 if (compositor_) {
1136 latency_info_swap_promise_monitor =
1137 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1138 .Pass();
1141 bool prevent_default = false;
1142 if (WebInputEvent::isMouseEventType(input_event->type)) {
1143 const WebMouseEvent& mouse_event =
1144 *static_cast<const WebMouseEvent*>(input_event);
1145 TRACE_EVENT2("renderer", "HandleMouseMove",
1146 "x", mouse_event.x, "y", mouse_event.y);
1147 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1148 prevent_default = WillHandleMouseEvent(mouse_event);
1151 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1152 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1153 #if defined(OS_ANDROID)
1154 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1155 // case it should behave like a select key (i.e. causing a click if a button
1156 // is focused). However, if a text field is focused (2), its intended
1157 // behavior is to just show the IME and don't propagate the key.
1158 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1159 // when clicked on an input text field and cause the form submit if clicked
1160 // when the submit button is focused, but not vice-versa.
1161 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1162 // but at this point we have to swallow the event for the scenario (2).
1163 const WebKeyboardEvent& key_event =
1164 *static_cast<const WebKeyboardEvent*>(input_event);
1165 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1166 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1167 OnShowImeIfNeeded();
1168 prevent_default = true;
1170 #endif
1173 if (WebInputEvent::isGestureEventType(input_event->type)) {
1174 const WebGestureEvent& gesture_event =
1175 *static_cast<const WebGestureEvent*>(input_event);
1176 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1177 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1180 bool processed = prevent_default;
1181 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1182 suppress_next_char_events_ = false;
1183 if (!processed && webwidget_)
1184 processed = webwidget_->handleInputEvent(*input_event);
1187 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1188 // it's not processed by webkit, then we need to suppress the upcoming Char
1189 // events.
1190 if (!processed && is_keyboard_shortcut)
1191 suppress_next_char_events_ = true;
1193 InputEventAckState ack_result = processed ?
1194 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1195 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1196 const WebTouchEvent& touch_event =
1197 *static_cast<const WebTouchEvent*>(input_event);
1198 // Hit-test for all the pressed touch points. If there is a touch-handler
1199 // for any of the touch points, then the renderer should continue to receive
1200 // touch events.
1201 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1202 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1203 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1204 HasTouchEventHandlersAt(
1205 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1206 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1207 break;
1212 // Send mouse wheel events and their disposition to the compositor thread, so
1213 // that they can be used to produce the elastic overscroll effect on Mac.
1214 if (input_event->type == WebInputEvent::MouseWheel) {
1215 ObserveWheelEventAndResult(
1216 static_cast<const WebMouseWheelEvent&>(*input_event), processed);
1219 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1221 // If we don't have a fast and accurate Now(), we assume the input handlers
1222 // are heavy and rate limit them.
1223 bool rate_limiting_wanted =
1224 input_event->type == WebInputEvent::MouseMove ||
1225 input_event->type == WebInputEvent::MouseWheel;
1226 if (rate_limiting_wanted && !start_time.is_null()) {
1227 base::TimeTicks end_time = base::TimeTicks::Now();
1228 total_input_handling_time_this_frame_ += (end_time - start_time);
1229 rate_limiting_wanted =
1230 total_input_handling_time_this_frame_.InMicroseconds() >
1231 kInputHandlingTimeThrottlingThresholdMicroseconds;
1234 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1236 // Note that we can't use handling_event_type_ here since it will be overriden
1237 // by reentrant calls for events after the paused one.
1238 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1239 input_event->type == WebInputEvent::MouseMove;
1240 if (!WebInputEventTraits::IgnoresAckDisposition(*input_event) && !no_ack) {
1241 InputHostMsg_HandleInputEvent_ACK_Params ack;
1242 ack.type = input_event->type;
1243 ack.state = ack_result;
1244 ack.latency = swap_latency_info;
1245 scoped_ptr<IPC::Message> response(
1246 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1247 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1248 // We want to rate limit the input events in this case, so we'll wait for
1249 // painting to finish before ACKing this message.
1250 TRACE_EVENT_INSTANT0("renderer",
1251 "RenderWidget::OnHandleInputEvent ack throttled",
1252 TRACE_EVENT_SCOPE_THREAD);
1253 if (pending_input_event_ack_) {
1254 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1255 pending_input_event_ack_.get());
1256 // As two different kinds of events could cause us to postpone an ack
1257 // we send it now, if we have one pending. The Browser should never
1258 // send us the same kind of event we are delaying the ack for.
1259 Send(pending_input_event_ack_.release());
1261 pending_input_event_ack_ = response.Pass();
1262 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1263 pending_input_event_ack_.get());
1264 if (compositor_)
1265 compositor_->NotifyInputThrottledUntilCommit();
1266 } else {
1267 Send(response.release());
1270 if (input_event->type == WebInputEvent::MouseMove)
1271 ignore_ack_for_mouse_move_from_debugger_ = false;
1273 #if defined(OS_ANDROID)
1274 // Allow the IME to be shown when the focus changes as a consequence
1275 // of a processed touch end event.
1276 if (input_event->type == WebInputEvent::TouchEnd && processed)
1277 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1278 #elif defined(USE_AURA)
1279 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1280 // change.
1281 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1282 input_event->type == WebInputEvent::MouseUp)) {
1283 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1285 #endif
1287 if (!prevent_default) {
1288 if (WebInputEvent::isKeyboardEventType(input_event->type))
1289 DidHandleKeyEvent();
1290 if (WebInputEvent::isMouseEventType(input_event->type))
1291 DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1292 if (WebInputEvent::isTouchEventType(input_event->type))
1293 DidHandleTouchEvent(*(static_cast<const WebTouchEvent*>(input_event)));
1296 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1297 // virtual keyboard.
1298 #if !defined(OS_ANDROID)
1299 // Virtual keyboard is not supported, so react to focus change immediately.
1300 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1301 input_event->type == WebInputEvent::MouseUp)) {
1302 FocusChangeComplete();
1304 #endif
1307 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1308 if (webwidget_)
1309 webwidget_->setCursorVisibilityState(is_visible);
1312 void RenderWidget::OnMouseCaptureLost() {
1313 if (webwidget_)
1314 webwidget_->mouseCaptureLost();
1317 void RenderWidget::OnSetFocus(bool enable) {
1318 has_focus_ = enable;
1319 if (webwidget_)
1320 webwidget_->setFocus(enable);
1323 void RenderWidget::ClearFocus() {
1324 // We may have got the focus from the browser before this gets processed, in
1325 // which case we do not want to unfocus ourself.
1326 if (!has_focus_ && webwidget_)
1327 webwidget_->setFocus(false);
1330 void RenderWidget::FlushPendingInputEventAck() {
1331 if (pending_input_event_ack_) {
1332 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1333 pending_input_event_ack_.get());
1334 Send(pending_input_event_ack_.release());
1336 total_input_handling_time_this_frame_ = base::TimeDelta();
1339 ///////////////////////////////////////////////////////////////////////////////
1340 // WebWidgetClient
1342 void RenderWidget::didAutoResize(const WebSize& new_size) {
1343 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1344 size_ = new_size;
1346 if (resizing_mode_selector_->is_synchronous_mode()) {
1347 WebRect new_pos(rootWindowRect().x,
1348 rootWindowRect().y,
1349 new_size.width,
1350 new_size.height);
1351 view_screen_rect_ = new_pos;
1352 window_screen_rect_ = new_pos;
1355 AutoResizeCompositor();
1357 if (!resizing_mode_selector_->is_synchronous_mode())
1358 need_update_rect_for_auto_resize_ = true;
1362 void RenderWidget::AutoResizeCompositor() {
1363 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1364 device_scale_factor_));
1365 if (compositor_)
1366 compositor_->setViewportSize(size_, physical_backing_size_);
1369 void RenderWidget::initializeLayerTreeView() {
1370 DCHECK(!host_closing_);
1372 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1373 compositor_->setViewportSize(size_, physical_backing_size_);
1374 if (init_complete_)
1375 StartCompositor();
1378 void RenderWidget::WillCloseLayerTreeView() {
1379 if (host_closing_)
1380 return;
1382 // Prevent new compositors or output surfaces from being created.
1383 host_closing_ = true;
1385 // Always send this notification to prevent new layer tree views from
1386 // being created, even if one hasn't been created yet.
1387 if (webwidget_)
1388 webwidget_->willCloseLayerTreeView();
1391 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1392 return compositor_.get();
1395 void RenderWidget::willBeginCompositorFrame() {
1396 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1398 // The following two can result in further layout and possibly
1399 // enable GPU acceleration so they need to be called before any painting
1400 // is done.
1401 UpdateTextInputType();
1402 #if defined(OS_ANDROID)
1403 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1404 #endif
1405 UpdateSelectionBounds();
1408 void RenderWidget::didBecomeReadyForAdditionalInput() {
1409 TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1410 FlushPendingInputEventAck();
1413 void RenderWidget::DidCommitCompositorFrame() {
1414 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1415 DidCommitCompositorFrame());
1416 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1417 DidCommitCompositorFrame());
1418 #if defined(VIDEO_HOLE)
1419 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1420 DidCommitCompositorFrame());
1421 #endif // defined(VIDEO_HOLE)
1424 // static
1425 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1426 IPC::Message* msg,
1427 MessageDeliveryPolicy policy,
1428 FrameSwapMessageQueue* frame_swap_message_queue,
1429 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1430 int source_frame_number) {
1431 bool first_message_for_frame = false;
1432 frame_swap_message_queue->QueueMessageForFrame(policy,
1433 source_frame_number,
1434 make_scoped_ptr(msg),
1435 &first_message_for_frame);
1436 if (first_message_for_frame) {
1437 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1438 sync_message_filter, frame_swap_message_queue, source_frame_number));
1439 return promise;
1441 return nullptr;
1444 void RenderWidget::QueueMessage(IPC::Message* msg,
1445 MessageDeliveryPolicy policy) {
1446 // RenderThreadImpl::current() is NULL in some tests.
1447 if (!compositor_ || !RenderThreadImpl::current()) {
1448 Send(msg);
1449 return;
1452 scoped_ptr<cc::SwapPromise> swap_promise =
1453 QueueMessageImpl(msg,
1454 policy,
1455 frame_swap_message_queue_.get(),
1456 RenderThreadImpl::current()->sync_message_filter(),
1457 compositor_->GetSourceFrameNumber());
1459 if (swap_promise) {
1460 compositor_->QueueSwapPromise(swap_promise.Pass());
1461 // Request a commit. This might either A) request a commit ahead of time
1462 // or B) request a commit which is not needed because there are not
1463 // pending updates. If B) then the commit will be skipped and the swap
1464 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1465 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1466 // can_cancel_commit is not unset.
1467 compositor_->SetNeedsUpdateLayers();
1471 void RenderWidget::didCommitAndDrawCompositorFrame() {
1472 // NOTE: Tests may break if this event is renamed or moved. See
1473 // tab_capture_performancetest.cc.
1474 TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1475 // Notify subclasses that we initiated the paint operation.
1476 DidInitiatePaint();
1479 void RenderWidget::didCompleteSwapBuffers() {
1480 TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
1482 // Notify subclasses threaded composited rendering was flushed to the screen.
1483 DidFlushPaint();
1485 if (!next_paint_flags_ &&
1486 !need_update_rect_for_auto_resize_ &&
1487 !plugin_window_moves_.size()) {
1488 return;
1491 ViewHostMsg_UpdateRect_Params params;
1492 params.view_size = size_;
1493 params.plugin_window_moves.swap(plugin_window_moves_);
1494 params.flags = next_paint_flags_;
1496 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1497 next_paint_flags_ = 0;
1498 need_update_rect_for_auto_resize_ = false;
1501 void RenderWidget::scheduleComposite() {
1502 if (compositor_ &&
1503 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1504 compositor_->setNeedsAnimate();
1508 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1509 // TODO(darin): Eliminate this temporary.
1510 WebCursor cursor;
1511 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1512 // Only send a SetCursor message if we need to make a change.
1513 if (!current_cursor_.IsEqual(cursor)) {
1514 current_cursor_ = cursor;
1515 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1519 // We are supposed to get a single call to Show for a newly created RenderWidget
1520 // that was created via RenderWidget::CreateWebView. So, we wait until this
1521 // point to dispatch the ShowWidget message.
1523 // This method provides us with the information about how to display the newly
1524 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1526 void RenderWidget::show(WebNavigationPolicy) {
1527 DCHECK(!did_show_) << "received extraneous Show call";
1528 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1529 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1531 if (did_show_)
1532 return;
1534 did_show_ = true;
1535 // NOTE: initial_rect_ may still have its default values at this point, but
1536 // that's okay. It'll be ignored if as_popup is false, or the browser
1537 // process will impose a default position otherwise.
1538 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1539 SetPendingWindowRect(initial_rect_);
1542 void RenderWidget::didFocus() {
1545 void RenderWidget::didBlur() {
1548 void RenderWidget::DoDeferredClose() {
1549 WillCloseLayerTreeView();
1550 Send(new ViewHostMsg_Close(routing_id_));
1553 void RenderWidget::NotifyOnClose() {
1554 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose());
1557 void RenderWidget::closeWidgetSoon() {
1558 if (is_swapped_out_) {
1559 // This widget is currently swapped out, and the active widget is in a
1560 // different process. Have the browser route the close request to the
1561 // active widget instead, so that the correct unload handlers are run.
1562 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1563 return;
1566 // If a page calls window.close() twice, we'll end up here twice, but that's
1567 // OK. It is safe to send multiple Close messages.
1569 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1570 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1571 // could be closed before the JS finishes executing. So instead, post a
1572 // message back to the message loop, which won't run until the JS is
1573 // complete, and then the Close message can be sent.
1574 RenderThread::Get()->GetTaskRunner()->PostTask(
1575 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1578 void RenderWidget::QueueSyntheticGesture(
1579 scoped_ptr<SyntheticGestureParams> gesture_params,
1580 const SyntheticGestureCompletionCallback& callback) {
1581 DCHECK(!callback.is_null());
1583 pending_synthetic_gesture_callbacks_.push(callback);
1585 SyntheticGesturePacket gesture_packet;
1586 gesture_packet.set_gesture_params(gesture_params.Pass());
1588 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1591 void RenderWidget::Close() {
1592 screen_metrics_emulator_.reset();
1593 WillCloseLayerTreeView();
1594 compositor_.reset();
1595 if (webwidget_) {
1596 webwidget_->close();
1597 webwidget_ = NULL;
1601 WebRect RenderWidget::windowRect() {
1602 if (pending_window_rect_count_)
1603 return pending_window_rect_;
1605 return view_screen_rect_;
1608 void RenderWidget::setToolTipText(const blink::WebString& text,
1609 WebTextDirection hint) {
1610 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1613 void RenderWidget::setWindowRect(const WebRect& rect) {
1614 WebRect window_rect = rect;
1615 if (popup_origin_scale_for_emulation_) {
1616 float scale = popup_origin_scale_for_emulation_;
1617 window_rect.x = popup_screen_origin_for_emulation_.x() +
1618 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1619 window_rect.y = popup_screen_origin_for_emulation_.y() +
1620 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1623 if (!resizing_mode_selector_->is_synchronous_mode()) {
1624 if (did_show_) {
1625 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1626 SetPendingWindowRect(window_rect);
1627 } else {
1628 initial_rect_ = window_rect;
1630 } else {
1631 SetWindowRectSynchronously(window_rect);
1635 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1636 pending_window_rect_ = rect;
1637 pending_window_rect_count_++;
1640 WebRect RenderWidget::rootWindowRect() {
1641 if (pending_window_rect_count_) {
1642 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1643 // the RootWindowRect is probably going to return wrong results since the
1644 // browser may not have processed the Move yet. There isn't really anything
1645 // good to do in this case, and it shouldn't happen - since this size is
1646 // only really needed for windowToScreen, which is only used for Popups.
1647 return pending_window_rect_;
1650 return window_screen_rect_;
1653 WebRect RenderWidget::windowResizerRect() {
1654 return resizer_rect_;
1657 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1658 // To prevent this renderer process from sending unnecessary IPC messages to
1659 // a browser process, we permit the renderer process to send IPC messages
1660 // only during the input method attached to the browser process is active.
1661 input_method_is_active_ = is_active;
1664 void RenderWidget::OnCandidateWindowShown() {
1665 webwidget_->didShowCandidateWindow();
1668 void RenderWidget::OnCandidateWindowUpdated() {
1669 webwidget_->didUpdateCandidateWindow();
1672 void RenderWidget::OnCandidateWindowHidden() {
1673 webwidget_->didHideCandidateWindow();
1676 void RenderWidget::OnImeSetComposition(
1677 const base::string16& text,
1678 const std::vector<WebCompositionUnderline>& underlines,
1679 int selection_start, int selection_end) {
1680 if (!ShouldHandleImeEvent())
1681 return;
1682 ImeEventGuard guard(this);
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::showImeIfNeeded() {
1753 OnShowImeIfNeeded();
1756 void RenderWidget::OnShowImeIfNeeded() {
1757 #if defined(OS_ANDROID) || defined(USE_AURA)
1758 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1759 #endif
1761 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1762 // virtual keyboard.
1763 #if !defined(OS_ANDROID)
1764 FocusChangeComplete();
1765 #endif
1768 #if defined(OS_ANDROID)
1769 void RenderWidget::IncrementOutstandingImeEventAcks() {
1770 ++outstanding_ime_acks_;
1773 void RenderWidget::OnImeEventAck() {
1774 --outstanding_ime_acks_;
1775 DCHECK(outstanding_ime_acks_ >= 0);
1777 #endif
1779 bool RenderWidget::ShouldHandleImeEvent() {
1780 #if defined(OS_ANDROID)
1781 return !!webwidget_ && outstanding_ime_acks_ == 0;
1782 #else
1783 return !!webwidget_;
1784 #endif
1787 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1788 if (handling_event_type_ == WebInputEvent::MouseMove) {
1789 // If we pause multiple times during a single mouse move event, we should
1790 // only send ACK once.
1791 if (!ignore_ack_for_mouse_move_from_debugger_) {
1792 InputHostMsg_HandleInputEvent_ACK_Params ack;
1793 ack.type = handling_event_type_;
1794 ack.state = INPUT_EVENT_ACK_STATE_CONSUMED;
1795 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1796 return true;
1799 return false;
1802 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1803 ignore_ack_for_mouse_move_from_debugger_ = true;
1806 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1807 if (device_scale_factor_ == device_scale_factor)
1808 return;
1810 device_scale_factor_ = device_scale_factor;
1811 scheduleComposite();
1814 bool RenderWidget::SetDeviceColorProfile(
1815 const std::vector<char>& color_profile) {
1816 if (device_color_profile_ == color_profile)
1817 return false;
1819 device_color_profile_ = color_profile;
1820 return true;
1823 void RenderWidget::ResetDeviceColorProfileForTesting() {
1824 if (!device_color_profile_.empty())
1825 device_color_profile_.clear();
1826 device_color_profile_.push_back('0');
1829 void RenderWidget::OnOrientationChange() {
1832 gfx::Vector2d RenderWidget::GetScrollOffset() {
1833 // Bare RenderWidgets don't support scroll offset.
1834 return gfx::Vector2d();
1837 void RenderWidget::SetHidden(bool hidden) {
1838 if (is_hidden_ == hidden)
1839 return;
1841 // The status has changed. Tell the RenderThread about it and ensure
1842 // throttled acks are released in case frame production ceases.
1843 is_hidden_ = hidden;
1844 FlushPendingInputEventAck();
1846 if (is_hidden_)
1847 RenderThreadImpl::current()->WidgetHidden();
1848 else
1849 RenderThreadImpl::current()->WidgetRestored();
1852 void RenderWidget::WillToggleFullscreen() {
1853 if (!webwidget_)
1854 return;
1856 if (is_fullscreen_granted_) {
1857 webwidget_->willExitFullScreen();
1858 } else {
1859 webwidget_->willEnterFullScreen();
1863 void RenderWidget::DidToggleFullscreen() {
1864 if (!webwidget_)
1865 return;
1867 if (is_fullscreen_granted_) {
1868 webwidget_->didEnterFullScreen();
1869 } else {
1870 webwidget_->didExitFullScreen();
1874 bool RenderWidget::next_paint_is_resize_ack() const {
1875 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1878 void RenderWidget::set_next_paint_is_resize_ack() {
1879 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1882 void RenderWidget::set_next_paint_is_repaint_ack() {
1883 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1886 static bool IsDateTimeInput(ui::TextInputType type) {
1887 return type == ui::TEXT_INPUT_TYPE_DATE ||
1888 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1889 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1890 type == ui::TEXT_INPUT_TYPE_MONTH ||
1891 type == ui::TEXT_INPUT_TYPE_TIME ||
1892 type == ui::TEXT_INPUT_TYPE_WEEK;
1896 void RenderWidget::StartHandlingImeEvent() {
1897 DCHECK(!handling_ime_event_);
1898 handling_ime_event_ = true;
1901 void RenderWidget::FinishHandlingImeEvent() {
1902 DCHECK(handling_ime_event_);
1903 handling_ime_event_ = false;
1904 // While handling an ime event, text input state and selection bounds updates
1905 // are ignored. These must explicitly be updated once finished handling the
1906 // ime event.
1907 UpdateSelectionBounds();
1908 #if defined(OS_ANDROID)
1909 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1910 #endif
1913 void RenderWidget::UpdateTextInputType() {
1914 // On Windows, not only an IME but also an on-screen keyboard relies on the
1915 // latest TextInputType to optimize its layout and functionality. Thus
1916 // |input_method_is_active_| is no longer an appropriate condition to suppress
1917 // TextInputTypeChanged IPC on Windows.
1918 // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
1919 // on other platforms as well as Windows if the overhead is acceptable.
1920 #if !defined(OS_WIN)
1921 if (!input_method_is_active_)
1922 return;
1923 #endif
1925 ui::TextInputType new_type = GetTextInputType();
1926 if (IsDateTimeInput(new_type))
1927 return; // Not considered as a text input field in WebKit/Chromium.
1929 bool new_can_compose_inline = CanComposeInline();
1931 blink::WebTextInputInfo new_info;
1932 if (webwidget_)
1933 new_info = webwidget_->textInputInfo();
1934 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1935 int new_flags = new_info.flags;
1937 if (text_input_type_ != new_type
1938 || can_compose_inline_ != new_can_compose_inline
1939 || text_input_mode_ != new_mode
1940 || text_input_flags_ != new_flags) {
1941 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1942 new_type,
1943 new_mode,
1944 new_can_compose_inline,
1945 new_flags));
1946 text_input_type_ = new_type;
1947 can_compose_inline_ = new_can_compose_inline;
1948 text_input_mode_ = new_mode;
1949 text_input_flags_ = new_flags;
1953 #if defined(OS_ANDROID) || defined(USE_AURA)
1954 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1955 ChangeSource change_source) {
1956 if (handling_ime_event_)
1957 return;
1958 if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1959 return;
1960 ui::TextInputType new_type = GetTextInputType();
1961 if (IsDateTimeInput(new_type))
1962 return; // Not considered as a text input field in WebKit/Chromium.
1964 blink::WebTextInputInfo new_info;
1965 if (webwidget_)
1966 new_info = webwidget_->textInputInfo();
1968 bool new_can_compose_inline = CanComposeInline();
1970 // Only sends text input params if they are changed or if the ime should be
1971 // shown.
1972 if (show_ime == SHOW_IME_IF_NEEDED ||
1973 (text_input_type_ != new_type ||
1974 text_input_info_ != new_info ||
1975 can_compose_inline_ != new_can_compose_inline)
1976 #if defined(OS_ANDROID)
1977 || text_field_is_dirty_
1978 #endif
1980 ViewHostMsg_TextInputState_Params p;
1981 p.type = new_type;
1982 p.flags = new_info.flags;
1983 p.value = new_info.value.utf8();
1984 p.selection_start = new_info.selectionStart;
1985 p.selection_end = new_info.selectionEnd;
1986 p.composition_start = new_info.compositionStart;
1987 p.composition_end = new_info.compositionEnd;
1988 p.can_compose_inline = new_can_compose_inline;
1989 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1990 #if defined(USE_AURA)
1991 p.is_non_ime_change = true;
1992 #endif
1993 #if defined(OS_ANDROID)
1994 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1995 text_field_is_dirty_;
1996 if (p.is_non_ime_change)
1997 IncrementOutstandingImeEventAcks();
1998 text_field_is_dirty_ = false;
1999 #endif
2000 #if defined(USE_AURA)
2001 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
2002 new_type,
2003 text_input_mode_,
2004 new_can_compose_inline,
2005 new_info.flags));
2006 #endif
2007 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
2009 text_input_info_ = new_info;
2010 text_input_type_ = new_type;
2011 can_compose_inline_ = new_can_compose_inline;
2012 text_input_flags_ = new_info.flags;
2015 #endif
2017 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
2018 WebRect focus_webrect;
2019 WebRect anchor_webrect;
2020 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
2021 *focus = focus_webrect;
2022 *anchor = anchor_webrect;
2025 void RenderWidget::UpdateSelectionBounds() {
2026 if (!webwidget_)
2027 return;
2028 if (handling_ime_event_)
2029 return;
2031 // With composited selection updates, the selection bounds will be reported
2032 // directly by the compositor, in which case explicit IPC selection
2033 // notifications should be suppressed.
2034 if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
2035 ViewHostMsg_SelectionBounds_Params params;
2036 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2037 if (selection_anchor_rect_ != params.anchor_rect ||
2038 selection_focus_rect_ != params.focus_rect) {
2039 selection_anchor_rect_ = params.anchor_rect;
2040 selection_focus_rect_ = params.focus_rect;
2041 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2042 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2043 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2047 UpdateCompositionInfo(false);
2050 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2051 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2052 static_assert(int(blink::WebTextInputType##a) \
2053 == int(ui::TEXT_INPUT_TYPE_##b), \
2054 "mismatching enums: " #a)
2056 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2057 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2058 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2059 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2060 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2061 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2062 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2063 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2064 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2065 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2066 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2067 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2068 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2069 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2070 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2071 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2072 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2074 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2075 blink::WebTextInputType type) {
2076 // Check the type is in the range representable by ui::TextInputType.
2077 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2078 "blink::WebTextInputType and ui::TextInputType not synchronized";
2079 return static_cast<ui::TextInputType>(type);
2082 ui::TextInputType RenderWidget::GetTextInputType() {
2083 if (webwidget_)
2084 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2085 return ui::TEXT_INPUT_TYPE_NONE;
2088 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2089 #if defined(OS_ANDROID)
2090 // TODO(yukawa): Start sending character bounds when the browser side
2091 // implementation becomes ready (crbug.com/424866).
2092 #else
2093 gfx::Range range = gfx::Range();
2094 if (should_update_range) {
2095 GetCompositionRange(&range);
2096 } else {
2097 range = composition_range_;
2099 std::vector<gfx::Rect> character_bounds;
2100 GetCompositionCharacterBounds(&character_bounds);
2102 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2103 return;
2104 composition_character_bounds_ = character_bounds;
2105 composition_range_ = range;
2106 Send(new InputHostMsg_ImeCompositionRangeChanged(
2107 routing_id(), composition_range_, composition_character_bounds_));
2108 #endif
2111 void RenderWidget::GetCompositionCharacterBounds(
2112 std::vector<gfx::Rect>* bounds) {
2113 DCHECK(bounds);
2114 bounds->clear();
2117 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2118 size_t location, length;
2119 if (webwidget_->compositionRange(&location, &length)) {
2120 range->set_start(location);
2121 range->set_end(location + length);
2122 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2123 range->set_start(location);
2124 range->set_end(location + length);
2125 } else {
2126 *range = gfx::Range::InvalidRange();
2130 bool RenderWidget::ShouldUpdateCompositionInfo(
2131 const gfx::Range& range,
2132 const std::vector<gfx::Rect>& bounds) {
2133 if (composition_range_ != range)
2134 return true;
2135 if (bounds.size() != composition_character_bounds_.size())
2136 return true;
2137 for (size_t i = 0; i < bounds.size(); ++i) {
2138 if (bounds[i] != composition_character_bounds_[i])
2139 return true;
2141 return false;
2144 #if defined(OS_ANDROID)
2145 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2146 // If not initialized, default to white. Note that 0 is different from black
2147 // as black still has alpha 0xFF.
2148 if (!bg_color)
2149 bg_color = SK_ColorWHITE;
2151 if (bg_color != body_background_color_) {
2152 body_background_color_ = bg_color;
2153 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2157 bool RenderWidget::DoesRecordFullLayer() const {
2158 SynchronousCompositorFactory* synchronous_compositor_factory =
2159 SynchronousCompositorFactory::GetInstance();
2161 // We assume that the absence of synchronous_compositor_factory
2162 // means we are in Chrome. In chrome, we want to clip, i.e.
2163 // *not* to record the full layer.
2164 if (!synchronous_compositor_factory)
2165 return false;
2167 return synchronous_compositor_factory->RecordFullLayer();
2169 #endif
2171 bool RenderWidget::CanComposeInline() {
2172 return true;
2175 WebScreenInfo RenderWidget::screenInfo() {
2176 return screen_info_;
2179 float RenderWidget::deviceScaleFactor() {
2180 return device_scale_factor_;
2183 void RenderWidget::resetInputMethod() {
2184 if (!input_method_is_active_)
2185 return;
2187 ImeEventGuard guard(this);
2188 // If the last text input type is not None, then we should finish any
2189 // ongoing composition regardless of the new text input type.
2190 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2191 // If a composition text exists, then we need to let the browser process
2192 // to cancel the input method's ongoing composition session.
2193 if (webwidget_->confirmComposition())
2194 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2197 UpdateCompositionInfo(true);
2200 #if defined(OS_ANDROID)
2201 void RenderWidget::showUnhandledTapUIIfNeeded(
2202 const WebPoint& tapped_position,
2203 const WebNode& tapped_node,
2204 bool page_changed) {
2205 DCHECK(handling_input_event_);
2206 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2207 !tapped_node.isContentEditable() &&
2208 !tapped_node.isInsideFocusableElementOrARIAWidget();
2209 if (should_trigger) {
2210 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2211 tapped_position.x, tapped_position.y));
2214 #endif
2216 void RenderWidget::didHandleGestureEvent(
2217 const WebGestureEvent& event,
2218 bool event_cancelled) {
2219 #if defined(OS_ANDROID) || defined(USE_AURA)
2220 if (event_cancelled)
2221 return;
2222 if (event.type == WebInputEvent::GestureTap) {
2223 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2224 } else if (event.type == WebInputEvent::GestureLongPress) {
2225 DCHECK(webwidget_);
2226 if (webwidget_->textInputInfo().value.isEmpty())
2227 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2228 else
2229 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2231 #endif
2234 void RenderWidget::StartCompositor() {
2235 // For widgets that are never visible, we don't need the compositor to run
2236 // at all.
2237 if (never_visible_)
2238 return;
2239 // In tests without a RenderThreadImpl, don't set ready as this kicks
2240 // off creating output surfaces that the test can't create.
2241 if (!RenderThreadImpl::current())
2242 return;
2243 compositor_->StartCompositor();
2246 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2247 size_t i = 0;
2248 for (; i < plugin_window_moves_.size(); ++i) {
2249 if (plugin_window_moves_[i].window == move.window) {
2250 if (move.rects_valid) {
2251 plugin_window_moves_[i] = move;
2252 } else {
2253 plugin_window_moves_[i].visible = move.visible;
2255 break;
2259 if (i == plugin_window_moves_.size())
2260 plugin_window_moves_.push_back(move);
2263 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2264 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2265 i != plugin_window_moves_.end(); ++i) {
2266 if (i->window == window) {
2267 plugin_window_moves_.erase(i);
2268 break;
2274 RenderWidgetCompositor* RenderWidget::compositor() const {
2275 return compositor_.get();
2278 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2279 return false;
2282 bool RenderWidget::WillHandleGestureEvent(
2283 const blink::WebGestureEvent& event) {
2284 return false;
2287 void RenderWidget::ObserveWheelEventAndResult(
2288 const blink::WebMouseWheelEvent& wheel_event,
2289 bool event_processed) {
2290 if (!compositor_deps_->IsElasticOverscrollEnabled())
2291 return;
2293 // Blink does not accurately compute scroll bubbling or overscroll. For now,
2294 // assume that an unprocessed event was entirely an overscroll, and that a
2295 // processed event was entirely scroll.
2296 // TODO(ccameron): Retrieve an accurate scroll result from Blink.
2297 // http://crbug.com/442859
2298 cc::InputHandlerScrollResult scroll_result;
2299 if (event_processed) {
2300 scroll_result.did_scroll = true;
2301 } else {
2302 scroll_result.did_overscroll_root = true;
2303 scroll_result.unused_scroll_delta =
2304 gfx::Vector2dF(-wheel_event.deltaX, -wheel_event.deltaY);
2307 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2308 InputHandlerManager* input_handler_manager =
2309 render_thread ? render_thread->input_handler_manager() : NULL;
2310 if (input_handler_manager) {
2311 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2312 routing_id_, wheel_event, scroll_result);
2316 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2317 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2320 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2321 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2322 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2323 "mismatching enums: " #a)
2325 void RenderWidget::setTouchAction(
2326 blink::WebTouchAction web_touch_action) {
2328 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2329 // when blink is emulating touch with mouse).
2330 if (handling_event_type_ != WebInputEvent::TouchStart)
2331 return;
2333 // Verify the same values are used by the types so we can cast between them.
2334 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2335 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2336 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2337 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2338 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2340 content::TouchAction content_touch_action =
2341 static_cast<content::TouchAction>(web_touch_action);
2342 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2345 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2346 #if defined(OS_ANDROID)
2347 text_field_is_dirty_ = true;
2348 #endif
2351 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2352 return true;
2355 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2356 RenderWidget::CreateGraphicsContext3D() {
2357 if (!webwidget_)
2358 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2359 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2360 switches::kDisableGpuCompositing))
2361 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2362 if (!RenderThreadImpl::current())
2363 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2364 CauseForGpuLaunch cause =
2365 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2366 scoped_refptr<GpuChannelHost> gpu_channel_host(
2367 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2368 if (!gpu_channel_host.get())
2369 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2371 // Explicitly disable antialiasing for the compositor. As of the time of
2372 // this writing, the only platform that supported antialiasing for the
2373 // compositor was Mac OS X, because the on-screen OpenGL context creation
2374 // code paths on Windows and Linux didn't yet have multisampling support.
2375 // Mac OS X essentially always behaves as though it's rendering offscreen.
2376 // Multisampling has a heavy cost especially on devices with relatively low
2377 // fill rate like most notebooks, and the Mac implementation would need to
2378 // be optimized to resolve directly into the IOSurface shared between the
2379 // GPU and browser processes. For these reasons and to avoid platform
2380 // disparities we explicitly disable antialiasing.
2381 blink::WebGraphicsContext3D::Attributes attributes;
2382 attributes.antialias = false;
2383 attributes.shareResources = true;
2384 attributes.noAutomaticFlushes = true;
2385 attributes.depth = false;
2386 attributes.stencil = false;
2387 bool lose_context_when_out_of_memory = true;
2388 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2389 #if defined(OS_ANDROID)
2390 // If we raster too fast we become upload bound, and pending
2391 // uploads consume memory. For maximum upload throughput, we would
2392 // want to allow for upload_throughput * pipeline_time of pending
2393 // uploads, after which we are just wasting memory. Since we don't
2394 // know our upload throughput yet, this just caps our memory usage.
2395 size_t divider = 1;
2396 if (base::SysInfo::IsLowEndDevice())
2397 divider = 6;
2398 // For reference Nexus10 can upload 1MB in about 2.5ms.
2399 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2400 // Deadline to draw a frame to achieve 60 frames per second.
2401 const size_t kMillisecondsPerFrame = 16;
2402 // Assuming a two frame deep pipeline between the CPU and the GPU.
2403 size_t max_transfer_buffer_usage_mb =
2404 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2405 static const size_t kBytesPerMegabyte = 1024 * 1024;
2406 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2407 // to avoid unnecessarily stalling the compositor thread.
2408 limits.mapped_memory_reclaim_limit =
2409 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2410 #endif
2412 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2413 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2414 GetURLForGraphicsContext3D(),
2415 gpu_channel_host.get(),
2416 attributes,
2417 lose_context_when_out_of_memory,
2418 limits,
2419 NULL));
2420 return context.Pass();
2423 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2424 render_frame_proxies_.AddObserver(proxy);
2427 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2428 render_frame_proxies_.RemoveObserver(proxy);
2431 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2432 render_frames_.AddObserver(frame);
2435 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2436 render_frames_.RemoveObserver(frame);
2439 #if defined(VIDEO_HOLE)
2440 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2441 video_hole_frames_.AddObserver(frame);
2444 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2445 video_hole_frames_.RemoveObserver(frame);
2447 #endif // defined(VIDEO_HOLE)
2449 } // namespace content