cc: Remove unused disable_hi_res_timer_tasks_on_battery flag.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob8c5c6d6893bfbfd4f368e714bfa72c5c94e0759e
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::Point 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);
274 RenderWidget* widget_;
276 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
277 WebDeviceEmulationParams params_;
279 // The computed scale and offset used to fit widget into browser window.
280 float scale_;
281 gfx::Point offset_;
283 // Widget rect as passed to webwidget.
284 gfx::Rect applied_widget_rect_;
286 // Original values to restore back after emulation ends.
287 gfx::Size original_size_;
288 gfx::Size original_physical_backing_size_;
289 gfx::Size original_visible_viewport_size_;
290 blink::WebScreenInfo original_screen_info_;
291 gfx::Rect original_view_screen_rect_;
292 gfx::Rect original_window_screen_rect_;
295 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
296 RenderWidget* widget,
297 const WebDeviceEmulationParams& params)
298 : widget_(widget),
299 params_(params),
300 scale_(1.f) {
301 original_size_ = widget_->size_;
302 original_physical_backing_size_ = widget_->physical_backing_size_;
303 original_visible_viewport_size_ = widget_->visible_viewport_size_;
304 original_screen_info_ = widget_->screen_info_;
305 original_view_screen_rect_ = widget_->view_screen_rect_;
306 original_window_screen_rect_ = widget_->window_screen_rect_;
307 Apply(widget_->top_controls_shrink_blink_size_,
308 widget_->top_controls_height_,
309 widget_->resizer_rect_,
310 widget_->is_fullscreen_);
313 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
314 widget_->screen_info_ = original_screen_info_;
316 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
317 widget_->SetScreenMetricsEmulationParameters(0.f, gfx::Point(), 1.f);
318 widget_->view_screen_rect_ = original_view_screen_rect_;
319 widget_->window_screen_rect_ = original_window_screen_rect_;
320 widget_->Resize(original_size_,
321 original_physical_backing_size_,
322 widget_->top_controls_shrink_blink_size_,
323 widget_->top_controls_height_,
324 original_visible_viewport_size_,
325 widget_->resizer_rect_,
326 widget_->is_fullscreen_,
327 NO_RESIZE_ACK);
330 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
331 const WebDeviceEmulationParams& params) {
332 params_ = params;
333 Reapply();
336 void RenderWidget::ScreenMetricsEmulator::Reapply() {
337 Apply(widget_->top_controls_shrink_blink_size_,
338 widget_->top_controls_height_,
339 widget_->resizer_rect_,
340 widget_->is_fullscreen_);
343 void RenderWidget::ScreenMetricsEmulator::Apply(
344 bool top_controls_shrink_blink_size,
345 float top_controls_height,
346 gfx::Rect resizer_rect,
347 bool is_fullscreen) {
348 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
349 if (!applied_widget_rect_.width())
350 applied_widget_rect_.set_width(original_size_.width());
351 if (!applied_widget_rect_.height())
352 applied_widget_rect_.set_height(original_size_.height());
354 if (params_.fitToView && !original_size_.IsEmpty()) {
355 int original_width = std::max(original_size_.width(), 1);
356 int original_height = std::max(original_size_.height(), 1);
357 float width_ratio =
358 static_cast<float>(applied_widget_rect_.width()) / original_width;
359 float height_ratio =
360 static_cast<float>(applied_widget_rect_.height()) / original_height;
361 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
362 scale_ = 1.f / ratio;
364 // Center emulated view inside available view space.
365 offset_.set_x(
366 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
367 offset_.set_y(
368 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
369 } else {
370 scale_ = params_.scale;
371 offset_.SetPoint(params_.offset.x, params_.offset.y);
374 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
375 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
376 widget_->screen_info_.rect = original_screen_info_.rect;
377 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
378 widget_->window_screen_rect_ = original_window_screen_rect_;
379 } else {
380 applied_widget_rect_.set_origin(gfx::Point(0, 0));
381 widget_->screen_info_.rect = applied_widget_rect_;
382 widget_->screen_info_.availableRect = applied_widget_rect_;
383 widget_->window_screen_rect_ = applied_widget_rect_;
386 float applied_device_scale_factor = params_.deviceScaleFactor ?
387 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
388 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
390 // Pass three emulation parameters to the blink side:
391 // - we keep the real device scale factor in compositor to produce sharp image
392 // even when emulating different scale factor;
393 // - in order to fit into view, WebView applies offset and scale to the
394 // root layer.
395 widget_->SetScreenMetricsEmulationParameters(
396 original_screen_info_.deviceScaleFactor, offset_, scale_);
398 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
399 widget_->view_screen_rect_ = applied_widget_rect_;
401 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
402 original_size_, original_screen_info_.deviceScaleFactor));
403 widget_->Resize(applied_widget_rect_.size(),
404 physical_backing_size,
405 top_controls_shrink_blink_size,
406 top_controls_height,
407 applied_widget_rect_.size(),
408 resizer_rect,
409 is_fullscreen,
410 NO_RESIZE_ACK);
413 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
414 const ViewMsg_Resize_Params& params) {
415 bool need_ack = params.new_size != original_size_ &&
416 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
417 original_size_ = params.new_size;
418 original_physical_backing_size_ = params.physical_backing_size;
419 original_screen_info_ = params.screen_info;
420 original_visible_viewport_size_ = params.visible_viewport_size;
421 Apply(params.top_controls_shrink_blink_size,
422 params.top_controls_height,
423 params.resizer_rect,
424 params.is_fullscreen);
426 if (need_ack) {
427 widget_->set_next_paint_is_resize_ack();
428 if (widget_->compositor_)
429 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
433 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
434 const gfx::Rect& view_screen_rect,
435 const gfx::Rect& window_screen_rect) {
436 original_view_screen_rect_ = view_screen_rect;
437 original_window_screen_rect_ = window_screen_rect;
438 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
439 Reapply();
442 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
443 ContextMenuParams* params) {
444 params->x *= scale_;
445 params->x += offset_.x();
446 params->y *= scale_;
447 params->y += offset_.y();
450 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
451 const gfx::Rect& anchor) {
452 gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
453 scaled.set_x(scaled.x() + offset_.x());
454 scaled.set_y(scaled.y() + offset_.y());
455 return scaled;
458 // RenderWidget ---------------------------------------------------------------
460 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
461 const blink::WebScreenInfo& screen_info,
462 bool swapped_out,
463 bool hidden,
464 bool never_visible)
465 : routing_id_(MSG_ROUTING_NONE),
466 surface_id_(0),
467 compositor_deps_(nullptr),
468 webwidget_(nullptr),
469 opener_id_(MSG_ROUTING_NONE),
470 init_complete_(false),
471 top_controls_shrink_blink_size_(false),
472 top_controls_height_(0.f),
473 next_paint_flags_(0),
474 auto_resize_mode_(false),
475 need_update_rect_for_auto_resize_(false),
476 did_show_(false),
477 is_hidden_(hidden),
478 never_visible_(never_visible),
479 is_fullscreen_(false),
480 has_focus_(false),
481 handling_input_event_(false),
482 handling_ime_event_(false),
483 handling_event_type_(WebInputEvent::Undefined),
484 ignore_ack_for_mouse_move_from_debugger_(false),
485 closing_(false),
486 host_closing_(false),
487 is_swapped_out_(swapped_out),
488 input_method_is_active_(false),
489 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
490 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
491 text_input_flags_(0),
492 can_compose_inline_(true),
493 popup_type_(popup_type),
494 pending_window_rect_count_(0),
495 suppress_next_char_events_(false),
496 screen_info_(screen_info),
497 device_scale_factor_(screen_info_.deviceScaleFactor),
498 current_event_latency_info_(NULL),
499 next_output_surface_id_(0),
500 #if defined(OS_ANDROID)
501 text_field_is_dirty_(false),
502 outstanding_ime_acks_(0),
503 body_background_color_(SK_ColorWHITE),
504 #endif
505 popup_origin_scale_for_emulation_(0.f),
506 frame_swap_message_queue_(new FrameSwapMessageQueue()),
507 resizing_mode_selector_(new ResizingModeSelector()),
508 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
509 has_host_context_menu_location_(false) {
510 if (!swapped_out)
511 RenderProcess::current()->AddRefProcess();
512 DCHECK(RenderThread::Get());
513 device_color_profile_.push_back('0');
516 RenderWidget::~RenderWidget() {
517 DCHECK(!webwidget_) << "Leaking our WebWidget!";
519 // If we are swapped out, we have released already.
520 if (!is_swapped_out_ && RenderProcess::current())
521 RenderProcess::current()->ReleaseProcess();
524 // static
525 RenderWidget* RenderWidget::Create(int32 opener_id,
526 CompositorDependencies* compositor_deps,
527 blink::WebPopupType popup_type,
528 const blink::WebScreenInfo& screen_info) {
529 DCHECK(opener_id != MSG_ROUTING_NONE);
530 scoped_refptr<RenderWidget> widget(
531 new RenderWidget(popup_type, screen_info, false, false, false));
532 if (widget->Init(opener_id, compositor_deps)) { // adds reference on success.
533 return widget.get();
535 return NULL;
538 // static
539 RenderWidget* RenderWidget::CreateForFrame(
540 int routing_id,
541 int surface_id,
542 bool hidden,
543 const blink::WebScreenInfo& screen_info,
544 CompositorDependencies* compositor_deps,
545 blink::WebLocalFrame* frame) {
546 CHECK_NE(routing_id, MSG_ROUTING_NONE);
547 scoped_refptr<RenderWidget> widget(new RenderWidget(
548 blink::WebPopupTypeNone, screen_info, false, hidden, false));
549 widget->routing_id_ = routing_id;
550 widget->surface_id_ = surface_id;
551 widget->compositor_deps_ = compositor_deps;
552 // DoInit increments the reference count on |widget|, keeping it alive after
553 // this function returns.
554 if (widget->DoInit(MSG_ROUTING_NONE, compositor_deps,
555 RenderWidget::CreateWebFrameWidget(widget.get(), frame),
556 nullptr)) {
557 widget->CompleteInit();
558 return widget.get();
560 return nullptr;
563 // static
564 blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
565 switch (render_widget->popup_type_) {
566 case blink::WebPopupTypeNone: // Nothing to create.
567 break;
568 case blink::WebPopupTypeSelect:
569 case blink::WebPopupTypeSuggestion:
570 return WebPopupMenu::create(render_widget);
571 case blink::WebPopupTypePage:
572 return WebPagePopup::create(render_widget);
573 default:
574 NOTREACHED();
576 return NULL;
579 // static
580 blink::WebWidget* RenderWidget::CreateWebFrameWidget(
581 RenderWidget* render_widget,
582 blink::WebLocalFrame* frame) {
583 return blink::WebFrameWidget::create(render_widget, frame);
586 bool RenderWidget::Init(int32 opener_id,
587 CompositorDependencies* compositor_deps) {
588 return DoInit(opener_id, compositor_deps, RenderWidget::CreateWebWidget(this),
589 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
590 &routing_id_, &surface_id_));
593 bool RenderWidget::DoInit(int32 opener_id,
594 CompositorDependencies* compositor_deps,
595 WebWidget* web_widget,
596 IPC::SyncMessage* create_widget_message) {
597 DCHECK(!webwidget_);
599 if (opener_id != MSG_ROUTING_NONE)
600 opener_id_ = opener_id;
602 compositor_deps_ = compositor_deps;
603 webwidget_ = web_widget;
605 bool result = true;
606 if (create_widget_message)
607 result = RenderThread::Get()->Send(create_widget_message);
609 if (result) {
610 RenderThread::Get()->AddRoute(routing_id_, this);
611 // Take a reference on behalf of the RenderThread. This will be balanced
612 // when we receive ViewMsg_Close.
613 AddRef();
614 if (RenderThreadImpl::current()) {
615 RenderThreadImpl::current()->WidgetCreated();
616 if (is_hidden_)
617 RenderThreadImpl::current()->WidgetHidden();
619 return true;
620 } else {
621 // The above Send can fail when the tab is closing.
622 return false;
626 // This is used to complete pending inits and non-pending inits.
627 void RenderWidget::CompleteInit() {
628 DCHECK(routing_id_ != MSG_ROUTING_NONE);
630 init_complete_ = true;
632 if (compositor_)
633 StartCompositor();
635 Send(new ViewHostMsg_RenderViewReady(routing_id_));
638 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
639 // We should only toggle between states.
640 DCHECK(is_swapped_out_ != is_swapped_out);
641 is_swapped_out_ = is_swapped_out;
643 // If we are swapping out, we will call ReleaseProcess, allowing the process
644 // to exit if all of its RenderViews are swapped out. We wait until the
645 // WasSwappedOut call to do this, to allow the unload handler to finish.
646 // If we are swapping in, we call AddRefProcess to prevent the process from
647 // exiting.
648 if (!is_swapped_out_)
649 RenderProcess::current()->AddRefProcess();
652 void RenderWidget::WasSwappedOut() {
653 // If we have been swapped out and no one else is using this process,
654 // it's safe to exit now.
655 CHECK(is_swapped_out_);
656 RenderProcess::current()->ReleaseProcess();
659 void RenderWidget::EnableScreenMetricsEmulation(
660 const WebDeviceEmulationParams& params) {
661 if (!screen_metrics_emulator_)
662 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
663 else
664 screen_metrics_emulator_->ChangeEmulationParams(params);
667 void RenderWidget::DisableScreenMetricsEmulation() {
668 screen_metrics_emulator_.reset();
671 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
672 ScreenMetricsEmulator* emulator) {
673 popup_origin_scale_for_emulation_ = emulator->scale();
674 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
675 popup_screen_origin_for_emulation_ = gfx::Point(
676 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
677 emulator->original_screen_rect().origin().y() + emulator->offset().y());
678 screen_info_ = emulator->original_screen_info();
679 device_scale_factor_ = screen_info_.deviceScaleFactor;
682 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
683 if (screen_metrics_emulator_)
684 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
685 return anchor;
688 void RenderWidget::SetScreenMetricsEmulationParameters(
689 float device_scale_factor,
690 const gfx::Point& root_layer_offset,
691 float root_layer_scale) {
692 // This is only supported in RenderView.
693 NOTREACHED();
696 #if defined(OS_MACOSX) || defined(OS_ANDROID)
697 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
698 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
699 popup->SetOriginScaleAndOffsetForEmulation(
700 emulator->scale(), emulator->offset());
702 #endif
704 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
705 if (screen_metrics_emulator_)
706 screen_metrics_emulator_->OnShowContextMenu(params);
709 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
710 if (compositor_) {
711 // Regardless of whether threaded compositing is enabled, always
712 // use this mechanism to force the compositor to redraw. However,
713 // the invalidation code path below is still needed for the
714 // non-threaded case.
715 compositor_->SetNeedsForcedRedraw();
717 scheduleComposite();
720 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
721 bool handled = true;
722 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
723 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
724 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
725 OnCursorVisibilityChange)
726 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
727 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
728 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
729 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
730 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
731 OnSyntheticGestureCompleted)
732 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
733 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
734 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
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_SetInputMethodActive, OnSetInputMethodActive)
740 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowShown, OnCandidateWindowShown)
741 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowUpdated,
742 OnCandidateWindowUpdated)
743 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowHidden, OnCandidateWindowHidden)
744 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
745 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
746 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
747 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
748 #if defined(OS_ANDROID)
749 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
750 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
751 #endif
752 IPC_MESSAGE_UNHANDLED(handled = false)
753 IPC_END_MESSAGE_MAP()
754 return handled;
757 bool RenderWidget::Send(IPC::Message* message) {
758 // Don't send any messages after the browser has told us to close, and filter
759 // most outgoing messages while swapped out.
760 if ((is_swapped_out_ &&
761 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
762 closing_) {
763 delete message;
764 return false;
767 // If given a messsage without a routing ID, then assign our routing ID.
768 if (message->routing_id() == MSG_ROUTING_NONE)
769 message->set_routing_id(routing_id_);
771 return RenderThread::Get()->Send(message);
774 void RenderWidget::Resize(const gfx::Size& new_size,
775 const gfx::Size& physical_backing_size,
776 bool top_controls_shrink_blink_size,
777 float top_controls_height,
778 const gfx::Size& visible_viewport_size,
779 const gfx::Rect& resizer_rect,
780 bool is_fullscreen,
781 const ResizeAck resize_ack) {
782 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
783 // A resize ack shouldn't be requested if we have not ACK'd the previous
784 // one.
785 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
786 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
789 // Ignore this during shutdown.
790 if (!webwidget_)
791 return;
793 if (compositor_) {
794 compositor_->setViewportSize(new_size, physical_backing_size);
797 physical_backing_size_ = physical_backing_size;
798 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
799 top_controls_height_ = top_controls_height;
800 visible_viewport_size_ = visible_viewport_size;
801 resizer_rect_ = resizer_rect;
803 // NOTE: We may have entered fullscreen mode without changing our size.
804 bool fullscreen_change = is_fullscreen_ != is_fullscreen;
805 if (fullscreen_change)
806 WillToggleFullscreen();
807 is_fullscreen_ = is_fullscreen;
809 webwidget_->setTopControlsHeight(top_controls_height,
810 top_controls_shrink_blink_size_);
812 if (size_ != new_size) {
813 size_ = new_size;
815 // When resizing, we want to wait to paint before ACK'ing the resize. This
816 // ensures that we only resize as fast as we can paint. We only need to
817 // send an ACK if we are resized to a non-empty rect.
818 webwidget_->resize(new_size);
821 webwidget()->resizePinchViewport(gfx::Size(
822 visible_viewport_size.width(),
823 visible_viewport_size.height()));
825 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
826 // In this case there is no paint/composite and therefore no
827 // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the
828 // ack through a fake ViewHostMsg_UpdateRect or a different message.
829 DCHECK_EQ(resize_ack, NO_RESIZE_ACK);
832 // Send the Resize_ACK flag once we paint again if requested.
833 if (resize_ack == SEND_RESIZE_ACK)
834 set_next_paint_is_resize_ack();
836 if (fullscreen_change)
837 DidToggleFullscreen();
839 // If a resize ack is requested and it isn't set-up, then no more resizes will
840 // come in and in general things will go wrong.
841 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
844 void RenderWidget::SetWindowRectSynchronously(
845 const gfx::Rect& new_window_rect) {
846 Resize(new_window_rect.size(),
847 new_window_rect.size(),
848 top_controls_shrink_blink_size_,
849 top_controls_height_,
850 new_window_rect.size(),
851 gfx::Rect(),
852 is_fullscreen_,
853 NO_RESIZE_ACK);
854 view_screen_rect_ = new_window_rect;
855 window_screen_rect_ = new_window_rect;
856 if (!did_show_)
857 initial_rect_ = new_window_rect;
860 void RenderWidget::OnClose() {
861 if (closing_)
862 return;
863 closing_ = true;
865 // Browser correspondence is no longer needed at this point.
866 if (routing_id_ != MSG_ROUTING_NONE) {
867 if (RenderThreadImpl::current())
868 RenderThreadImpl::current()->WidgetDestroyed();
869 RenderThread::Get()->RemoveRoute(routing_id_);
870 SetHidden(false);
873 // If there is a Send call on the stack, then it could be dangerous to close
874 // now. Post a task that only gets invoked when there are no nested message
875 // loops.
876 RenderThread::Get()->GetTaskRunner()->PostNonNestableTask(
877 FROM_HERE, base::Bind(&RenderWidget::Close, this));
879 // Balances the AddRef taken when we called AddRoute.
880 Release();
883 // Got a response from the browser after the renderer decided to create a new
884 // view.
885 void RenderWidget::OnCreatingNewAck() {
886 DCHECK(routing_id_ != MSG_ROUTING_NONE);
888 CompleteInit();
891 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
892 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
893 return;
895 if (screen_metrics_emulator_) {
896 screen_metrics_emulator_->OnResizeMessage(params);
897 return;
900 bool orientation_changed =
901 screen_info_.orientationAngle != params.screen_info.orientationAngle;
903 screen_info_ = params.screen_info;
904 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
905 Resize(params.new_size,
906 params.physical_backing_size,
907 params.top_controls_shrink_blink_size,
908 params.top_controls_height,
909 params.visible_viewport_size,
910 params.resizer_rect,
911 params.is_fullscreen,
912 params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK);
914 if (orientation_changed)
915 OnOrientationChange();
918 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
919 SetDeviceColorProfile(color_profile);
922 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
923 if (resizer_rect_ == resizer_rect)
924 return;
925 resizer_rect_ = resizer_rect;
926 if (webwidget_)
927 webwidget_->didChangeWindowResizerRect();
930 void RenderWidget::OnWasHidden() {
931 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
932 // Go into a mode where we stop generating paint and scrolling events.
933 SetHidden(true);
934 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
935 WasHidden());
938 void RenderWidget::OnWasShown(bool needs_repainting,
939 const ui::LatencyInfo& latency_info) {
940 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
941 // During shutdown we can just ignore this message.
942 if (!webwidget_)
943 return;
945 // See OnWasHidden
946 SetHidden(false);
947 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
948 WasShown());
950 if (!needs_repainting)
951 return;
953 // Generate a full repaint.
954 if (compositor_) {
955 ui::LatencyInfo swap_latency_info(latency_info);
956 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
957 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
958 compositor_->SetNeedsForcedRedraw();
960 scheduleComposite();
963 void RenderWidget::OnRequestMoveAck() {
964 DCHECK(pending_window_rect_count_);
965 pending_window_rect_count_--;
968 GURL RenderWidget::GetURLForGraphicsContext3D() {
969 return GURL();
972 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
973 // For widgets that are never visible, we don't start the compositor, so we
974 // never get a request for a cc::OutputSurface.
975 DCHECK(!never_visible_);
977 #if defined(OS_ANDROID)
978 if (SynchronousCompositorFactory* factory =
979 SynchronousCompositorFactory::GetInstance()) {
980 return factory->CreateOutputSurface(routing_id(),
981 frame_swap_message_queue_);
983 #endif
985 const base::CommandLine& command_line =
986 *base::CommandLine::ForCurrentProcess();
987 bool use_software = fallback;
988 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
989 use_software = true;
991 scoped_refptr<ContextProviderCommandBuffer> context_provider;
992 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider;
993 if (!use_software) {
994 context_provider = ContextProviderCommandBuffer::Create(
995 CreateGraphicsContext3D(), "RenderCompositor");
996 if (!context_provider.get()) {
997 // Cause the compositor to wait and try again.
998 return scoped_ptr<cc::OutputSurface>();
1001 worker_context_provider = ContextProviderCommandBuffer::Create(
1002 CreateGraphicsContext3D(), "RenderWorker");
1003 if (!worker_context_provider.get()) {
1004 // Cause the compositor to wait and try again.
1005 return scoped_ptr<cc::OutputSurface>();
1009 uint32 output_surface_id = next_output_surface_id_++;
1010 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1011 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1012 return scoped_ptr<cc::OutputSurface>(new DelegatedCompositorOutputSurface(
1013 routing_id(), output_surface_id, context_provider,
1014 worker_context_provider, frame_swap_message_queue_));
1016 if (!context_provider.get()) {
1017 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1018 new CompositorSoftwareOutputDevice());
1020 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1021 routing_id(), output_surface_id, nullptr, nullptr,
1022 software_device.Pass(), frame_swap_message_queue_, true));
1025 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1026 // Composite-to-mailbox is currently used for layout tests in order to cause
1027 // them to draw inside in the renderer to do the readback there. This should
1028 // no longer be the case when crbug.com/311404 is fixed.
1029 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1030 cc::ResourceFormat format = cc::RGBA_8888;
1031 if (base::SysInfo::IsLowEndDevice())
1032 format = cc::RGB_565;
1033 return scoped_ptr<cc::OutputSurface>(new MailboxOutputSurface(
1034 routing_id(), output_surface_id, context_provider,
1035 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1036 frame_swap_message_queue_, format));
1038 bool use_swap_compositor_frame_message = false;
1039 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
1040 routing_id(), output_surface_id, context_provider,
1041 worker_context_provider, scoped_ptr<cc::SoftwareOutputDevice>(),
1042 frame_swap_message_queue_, use_swap_compositor_frame_message));
1045 void RenderWidget::OnSwapBuffersAborted() {
1046 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1047 // Schedule another frame so the compositor learns about it.
1048 scheduleComposite();
1051 void RenderWidget::OnSwapBuffersPosted() {
1052 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1055 void RenderWidget::OnSwapBuffersComplete() {
1056 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1058 // Notify subclasses that composited rendering was flushed to the screen.
1059 DidFlushPaint();
1062 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1063 const ui::LatencyInfo& latency_info,
1064 bool is_keyboard_shortcut) {
1065 base::AutoReset<bool> handling_input_event_resetter(
1066 &handling_input_event_, true);
1067 if (!input_event)
1068 return;
1069 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1070 &handling_event_type_, input_event->type);
1071 #if defined(OS_ANDROID)
1072 // On Android, when a key is pressed or sent from the Keyboard using IME,
1073 // |AdapterInputConnection| generates input key events to make sure all JS
1074 // listeners that monitor KeyUp and KeyDown events receive the proper key
1075 // code. Since this input key event comes from IME, we need to set the
1076 // IME event guard here to make sure it does not interfere with other IME
1077 // events.
1078 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1079 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1080 const WebKeyboardEvent& key_event =
1081 *static_cast<const WebKeyboardEvent*>(input_event);
1082 // Some keys are special and it's essential that no events get blocked.
1083 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1084 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1085 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1086 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1087 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1088 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1089 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1091 #endif
1093 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
1094 &latency_info);
1096 base::TimeTicks start_time;
1097 if (base::TimeTicks::IsHighResolution())
1098 start_time = base::TimeTicks::Now();
1100 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1101 "event", WebInputEventTraits::GetName(input_event->type));
1102 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1103 TRACE_EVENT_FLOW_STEP0(
1104 "input,benchmark",
1105 "LatencyInfo.Flow",
1106 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
1107 "HanldeInputEventMain");
1109 // If we don't have a high res timer, these metrics won't be accurate enough
1110 // to be worth collecting. Note that this does introduce some sampling bias.
1111 if (!start_time.is_null())
1112 LogInputEventLatencyUma(*input_event, start_time);
1114 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1115 ui::LatencyInfo swap_latency_info(latency_info);
1116 if (compositor_) {
1117 latency_info_swap_promise_monitor =
1118 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1119 .Pass();
1122 bool prevent_default = false;
1123 if (WebInputEvent::isMouseEventType(input_event->type)) {
1124 const WebMouseEvent& mouse_event =
1125 *static_cast<const WebMouseEvent*>(input_event);
1126 TRACE_EVENT2("renderer", "HandleMouseMove",
1127 "x", mouse_event.x, "y", mouse_event.y);
1128 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1129 prevent_default = WillHandleMouseEvent(mouse_event);
1132 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1133 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1134 #if defined(OS_ANDROID)
1135 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1136 // case it should behave like a select key (i.e. causing a click if a button
1137 // is focused). However, if a text field is focused (2), its intended
1138 // behavior is to just show the IME and don't propagate the key.
1139 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1140 // when clicked on an input text field and cause the form submit if clicked
1141 // when the submit button is focused, but not vice-versa.
1142 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1143 // but at this point we have to swallow the event for the scenario (2).
1144 const WebKeyboardEvent& key_event =
1145 *static_cast<const WebKeyboardEvent*>(input_event);
1146 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1147 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1148 OnShowImeIfNeeded();
1149 prevent_default = true;
1151 #endif
1154 if (WebInputEvent::isGestureEventType(input_event->type)) {
1155 const WebGestureEvent& gesture_event =
1156 *static_cast<const WebGestureEvent*>(input_event);
1157 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1158 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1161 bool processed = prevent_default;
1162 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1163 suppress_next_char_events_ = false;
1164 if (!processed && webwidget_)
1165 processed = webwidget_->handleInputEvent(*input_event);
1168 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1169 // it's not processed by webkit, then we need to suppress the upcoming Char
1170 // events.
1171 if (!processed && is_keyboard_shortcut)
1172 suppress_next_char_events_ = true;
1174 InputEventAckState ack_result = processed ?
1175 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1176 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1177 const WebTouchEvent& touch_event =
1178 *static_cast<const WebTouchEvent*>(input_event);
1179 // Hit-test for all the pressed touch points. If there is a touch-handler
1180 // for any of the touch points, then the renderer should continue to receive
1181 // touch events.
1182 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1183 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1184 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1185 HasTouchEventHandlersAt(
1186 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1187 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1188 break;
1193 // Send mouse wheel events and their disposition to the compositor thread, so
1194 // that they can be used to produce the elastic overscroll effect on Mac.
1195 if (input_event->type == WebInputEvent::MouseWheel) {
1196 ObserveWheelEventAndResult(
1197 static_cast<const WebMouseWheelEvent&>(*input_event), processed);
1200 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1202 // If we don't have a fast and accurate Now(), we assume the input handlers
1203 // are heavy and rate limit them.
1204 bool rate_limiting_wanted =
1205 input_event->type == WebInputEvent::MouseMove ||
1206 input_event->type == WebInputEvent::MouseWheel;
1207 if (rate_limiting_wanted && !start_time.is_null()) {
1208 base::TimeTicks end_time = base::TimeTicks::Now();
1209 total_input_handling_time_this_frame_ += (end_time - start_time);
1210 rate_limiting_wanted =
1211 total_input_handling_time_this_frame_.InMicroseconds() >
1212 kInputHandlingTimeThrottlingThresholdMicroseconds;
1215 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1217 // Note that we can't use handling_event_type_ here since it will be overriden
1218 // by reentrant calls for events after the paused one.
1219 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1220 input_event->type == WebInputEvent::MouseMove;
1221 if (!WebInputEventTraits::IgnoresAckDisposition(*input_event) && !no_ack) {
1222 InputHostMsg_HandleInputEvent_ACK_Params ack;
1223 ack.type = input_event->type;
1224 ack.state = ack_result;
1225 ack.latency = swap_latency_info;
1226 scoped_ptr<IPC::Message> response(
1227 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1228 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1229 // We want to rate limit the input events in this case, so we'll wait for
1230 // painting to finish before ACKing this message.
1231 TRACE_EVENT_INSTANT0("renderer",
1232 "RenderWidget::OnHandleInputEvent ack throttled",
1233 TRACE_EVENT_SCOPE_THREAD);
1234 if (pending_input_event_ack_) {
1235 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1236 pending_input_event_ack_.get());
1237 // As two different kinds of events could cause us to postpone an ack
1238 // we send it now, if we have one pending. The Browser should never
1239 // send us the same kind of event we are delaying the ack for.
1240 Send(pending_input_event_ack_.release());
1242 pending_input_event_ack_ = response.Pass();
1243 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1244 pending_input_event_ack_.get());
1245 if (compositor_)
1246 compositor_->NotifyInputThrottledUntilCommit();
1247 } else {
1248 Send(response.release());
1251 if (input_event->type == WebInputEvent::MouseMove)
1252 ignore_ack_for_mouse_move_from_debugger_ = false;
1254 #if defined(OS_ANDROID)
1255 // Allow the IME to be shown when the focus changes as a consequence
1256 // of a processed touch end event.
1257 if (input_event->type == WebInputEvent::TouchEnd && processed)
1258 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1259 #elif defined(USE_AURA)
1260 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1261 // change.
1262 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1263 input_event->type == WebInputEvent::MouseUp)) {
1264 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1266 #endif
1268 if (!prevent_default) {
1269 if (WebInputEvent::isKeyboardEventType(input_event->type))
1270 DidHandleKeyEvent();
1271 if (WebInputEvent::isMouseEventType(input_event->type))
1272 DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1273 if (WebInputEvent::isTouchEventType(input_event->type))
1274 DidHandleTouchEvent(*(static_cast<const WebTouchEvent*>(input_event)));
1277 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1278 // virtual keyboard.
1279 #if !defined(OS_ANDROID)
1280 // Virtual keyboard is not supported, so react to focus change immediately.
1281 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1282 input_event->type == WebInputEvent::MouseUp)) {
1283 FocusChangeComplete();
1285 #endif
1288 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1289 if (webwidget_)
1290 webwidget_->setCursorVisibilityState(is_visible);
1293 void RenderWidget::OnMouseCaptureLost() {
1294 if (webwidget_)
1295 webwidget_->mouseCaptureLost();
1298 void RenderWidget::OnSetFocus(bool enable) {
1299 has_focus_ = enable;
1300 if (webwidget_)
1301 webwidget_->setFocus(enable);
1304 void RenderWidget::ClearFocus() {
1305 // We may have got the focus from the browser before this gets processed, in
1306 // which case we do not want to unfocus ourself.
1307 if (!has_focus_ && webwidget_)
1308 webwidget_->setFocus(false);
1311 void RenderWidget::FlushPendingInputEventAck() {
1312 if (pending_input_event_ack_) {
1313 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1314 pending_input_event_ack_.get());
1315 Send(pending_input_event_ack_.release());
1317 total_input_handling_time_this_frame_ = base::TimeDelta();
1320 ///////////////////////////////////////////////////////////////////////////////
1321 // WebWidgetClient
1323 void RenderWidget::didAutoResize(const WebSize& new_size) {
1324 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1325 size_ = new_size;
1327 if (resizing_mode_selector_->is_synchronous_mode()) {
1328 WebRect new_pos(rootWindowRect().x,
1329 rootWindowRect().y,
1330 new_size.width,
1331 new_size.height);
1332 view_screen_rect_ = new_pos;
1333 window_screen_rect_ = new_pos;
1336 AutoResizeCompositor();
1338 if (!resizing_mode_selector_->is_synchronous_mode())
1339 need_update_rect_for_auto_resize_ = true;
1343 void RenderWidget::AutoResizeCompositor() {
1344 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1345 device_scale_factor_));
1346 if (compositor_)
1347 compositor_->setViewportSize(size_, physical_backing_size_);
1350 void RenderWidget::initializeLayerTreeView() {
1351 DCHECK(!host_closing_);
1353 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1354 compositor_->setViewportSize(size_, physical_backing_size_);
1355 if (init_complete_)
1356 StartCompositor();
1359 void RenderWidget::WillCloseLayerTreeView() {
1360 if (host_closing_)
1361 return;
1363 // Prevent new compositors or output surfaces from being created.
1364 host_closing_ = true;
1366 // Always send this notification to prevent new layer tree views from
1367 // being created, even if one hasn't been created yet.
1368 if (webwidget_)
1369 webwidget_->willCloseLayerTreeView();
1372 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1373 return compositor_.get();
1376 void RenderWidget::willBeginCompositorFrame() {
1377 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1379 // The following two can result in further layout and possibly
1380 // enable GPU acceleration so they need to be called before any painting
1381 // is done.
1382 UpdateTextInputType();
1383 #if defined(OS_ANDROID)
1384 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1385 #endif
1386 UpdateSelectionBounds();
1389 void RenderWidget::didBecomeReadyForAdditionalInput() {
1390 TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1391 FlushPendingInputEventAck();
1394 void RenderWidget::DidCommitCompositorFrame() {
1395 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
1396 DidCommitCompositorFrame());
1397 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1398 DidCommitCompositorFrame());
1399 #if defined(VIDEO_HOLE)
1400 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1401 DidCommitCompositorFrame());
1402 #endif // defined(VIDEO_HOLE)
1405 // static
1406 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1407 IPC::Message* msg,
1408 MessageDeliveryPolicy policy,
1409 FrameSwapMessageQueue* frame_swap_message_queue,
1410 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1411 int source_frame_number) {
1412 bool first_message_for_frame = false;
1413 frame_swap_message_queue->QueueMessageForFrame(policy,
1414 source_frame_number,
1415 make_scoped_ptr(msg),
1416 &first_message_for_frame);
1417 if (first_message_for_frame) {
1418 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1419 sync_message_filter, frame_swap_message_queue, source_frame_number));
1420 return promise;
1422 return nullptr;
1425 void RenderWidget::QueueMessage(IPC::Message* msg,
1426 MessageDeliveryPolicy policy) {
1427 // RenderThreadImpl::current() is NULL in some tests.
1428 if (!compositor_ || !RenderThreadImpl::current()) {
1429 Send(msg);
1430 return;
1433 scoped_ptr<cc::SwapPromise> swap_promise =
1434 QueueMessageImpl(msg,
1435 policy,
1436 frame_swap_message_queue_.get(),
1437 RenderThreadImpl::current()->sync_message_filter(),
1438 compositor_->GetSourceFrameNumber());
1440 if (swap_promise) {
1441 compositor_->QueueSwapPromise(swap_promise.Pass());
1442 // Request a commit. This might either A) request a commit ahead of time
1443 // or B) request a commit which is not needed because there are not
1444 // pending updates. If B) then the commit will be skipped and the swap
1445 // promises will be broken (see EarlyOut_NoUpdates). To achieve that we
1446 // call SetNeedsUpdateLayers instead of SetNeedsCommit so that
1447 // can_cancel_commit is not unset.
1448 compositor_->SetNeedsUpdateLayers();
1452 void RenderWidget::didCommitAndDrawCompositorFrame() {
1453 // NOTE: Tests may break if this event is renamed or moved. See
1454 // tab_capture_performancetest.cc.
1455 TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1456 // Notify subclasses that we initiated the paint operation.
1457 DidInitiatePaint();
1460 void RenderWidget::didCompleteSwapBuffers() {
1461 TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
1463 // Notify subclasses threaded composited rendering was flushed to the screen.
1464 DidFlushPaint();
1466 if (!next_paint_flags_ &&
1467 !need_update_rect_for_auto_resize_ &&
1468 !plugin_window_moves_.size()) {
1469 return;
1472 ViewHostMsg_UpdateRect_Params params;
1473 params.view_size = size_;
1474 params.plugin_window_moves.swap(plugin_window_moves_);
1475 params.flags = next_paint_flags_;
1477 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1478 next_paint_flags_ = 0;
1479 need_update_rect_for_auto_resize_ = false;
1482 void RenderWidget::scheduleComposite() {
1483 if (compositor_ &&
1484 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1485 compositor_->setNeedsAnimate();
1489 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1490 // TODO(darin): Eliminate this temporary.
1491 WebCursor cursor;
1492 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1493 // Only send a SetCursor message if we need to make a change.
1494 if (!current_cursor_.IsEqual(cursor)) {
1495 current_cursor_ = cursor;
1496 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1500 // We are supposed to get a single call to Show for a newly created RenderWidget
1501 // that was created via RenderWidget::CreateWebView. So, we wait until this
1502 // point to dispatch the ShowWidget message.
1504 // This method provides us with the information about how to display the newly
1505 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1507 void RenderWidget::show(WebNavigationPolicy) {
1508 DCHECK(!did_show_) << "received extraneous Show call";
1509 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1510 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1512 if (did_show_)
1513 return;
1515 did_show_ = true;
1516 // NOTE: initial_rect_ may still have its default values at this point, but
1517 // that's okay. It'll be ignored if as_popup is false, or the browser
1518 // process will impose a default position otherwise.
1519 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1520 SetPendingWindowRect(initial_rect_);
1523 void RenderWidget::didFocus() {
1526 void RenderWidget::didBlur() {
1529 void RenderWidget::DoDeferredClose() {
1530 WillCloseLayerTreeView();
1531 Send(new ViewHostMsg_Close(routing_id_));
1534 void RenderWidget::closeWidgetSoon() {
1535 if (is_swapped_out_) {
1536 // This widget is currently swapped out, and the active widget is in a
1537 // different process. Have the browser route the close request to the
1538 // active widget instead, so that the correct unload handlers are run.
1539 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1540 return;
1543 // If a page calls window.close() twice, we'll end up here twice, but that's
1544 // OK. It is safe to send multiple Close messages.
1546 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1547 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1548 // could be closed before the JS finishes executing. So instead, post a
1549 // message back to the message loop, which won't run until the JS is
1550 // complete, and then the Close message can be sent.
1551 RenderThread::Get()->GetTaskRunner()->PostTask(
1552 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1555 void RenderWidget::QueueSyntheticGesture(
1556 scoped_ptr<SyntheticGestureParams> gesture_params,
1557 const SyntheticGestureCompletionCallback& callback) {
1558 DCHECK(!callback.is_null());
1560 pending_synthetic_gesture_callbacks_.push(callback);
1562 SyntheticGesturePacket gesture_packet;
1563 gesture_packet.set_gesture_params(gesture_params.Pass());
1565 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1568 void RenderWidget::Close() {
1569 screen_metrics_emulator_.reset();
1570 WillCloseLayerTreeView();
1571 compositor_.reset();
1572 if (webwidget_) {
1573 webwidget_->close();
1574 webwidget_ = NULL;
1578 WebRect RenderWidget::windowRect() {
1579 if (pending_window_rect_count_)
1580 return pending_window_rect_;
1582 return view_screen_rect_;
1585 void RenderWidget::setToolTipText(const blink::WebString& text,
1586 WebTextDirection hint) {
1587 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1590 void RenderWidget::setWindowRect(const WebRect& rect) {
1591 WebRect window_rect = rect;
1592 if (popup_origin_scale_for_emulation_) {
1593 float scale = popup_origin_scale_for_emulation_;
1594 window_rect.x = popup_screen_origin_for_emulation_.x() +
1595 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1596 window_rect.y = popup_screen_origin_for_emulation_.y() +
1597 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1600 if (!resizing_mode_selector_->is_synchronous_mode()) {
1601 if (did_show_) {
1602 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1603 SetPendingWindowRect(window_rect);
1604 } else {
1605 initial_rect_ = window_rect;
1607 } else {
1608 SetWindowRectSynchronously(window_rect);
1612 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1613 pending_window_rect_ = rect;
1614 pending_window_rect_count_++;
1617 WebRect RenderWidget::rootWindowRect() {
1618 if (pending_window_rect_count_) {
1619 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1620 // the RootWindowRect is probably going to return wrong results since the
1621 // browser may not have processed the Move yet. There isn't really anything
1622 // good to do in this case, and it shouldn't happen - since this size is
1623 // only really needed for windowToScreen, which is only used for Popups.
1624 return pending_window_rect_;
1627 return window_screen_rect_;
1630 WebRect RenderWidget::windowResizerRect() {
1631 return resizer_rect_;
1634 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1635 // To prevent this renderer process from sending unnecessary IPC messages to
1636 // a browser process, we permit the renderer process to send IPC messages
1637 // only during the input method attached to the browser process is active.
1638 input_method_is_active_ = is_active;
1641 void RenderWidget::OnCandidateWindowShown() {
1642 webwidget_->didShowCandidateWindow();
1645 void RenderWidget::OnCandidateWindowUpdated() {
1646 webwidget_->didUpdateCandidateWindow();
1649 void RenderWidget::OnCandidateWindowHidden() {
1650 webwidget_->didHideCandidateWindow();
1653 void RenderWidget::OnImeSetComposition(
1654 const base::string16& text,
1655 const std::vector<WebCompositionUnderline>& underlines,
1656 int selection_start, int selection_end) {
1657 if (!ShouldHandleImeEvent())
1658 return;
1659 ImeEventGuard guard(this);
1660 if (!webwidget_->setComposition(
1661 text, WebVector<WebCompositionUnderline>(underlines),
1662 selection_start, selection_end)) {
1663 // If we failed to set the composition text, then we need to let the browser
1664 // process to cancel the input method's ongoing composition session, to make
1665 // sure we are in a consistent state.
1666 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1668 UpdateCompositionInfo(true);
1671 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1672 const gfx::Range& replacement_range,
1673 bool keep_selection) {
1674 if (!ShouldHandleImeEvent())
1675 return;
1676 ImeEventGuard guard(this);
1677 handling_input_event_ = true;
1678 if (text.length())
1679 webwidget_->confirmComposition(text);
1680 else if (keep_selection)
1681 webwidget_->confirmComposition(WebWidget::KeepSelection);
1682 else
1683 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1684 handling_input_event_ = false;
1685 UpdateCompositionInfo(true);
1688 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1689 // During shutdown we can just ignore this message.
1690 if (!webwidget_)
1691 return;
1693 // Even if the browser provides an empty damage rect, it's still expecting to
1694 // receive a repaint ack so just damage the entire widget bounds.
1695 if (size_to_paint.IsEmpty()) {
1696 size_to_paint = size_;
1699 set_next_paint_is_repaint_ack();
1700 if (compositor_)
1701 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1704 void RenderWidget::OnSyntheticGestureCompleted() {
1705 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1707 pending_synthetic_gesture_callbacks_.front().Run();
1708 pending_synthetic_gesture_callbacks_.pop();
1711 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1712 if (!webwidget_)
1713 return;
1714 webwidget_->setTextDirection(direction);
1717 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1718 const gfx::Rect& window_screen_rect) {
1719 if (screen_metrics_emulator_) {
1720 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1721 view_screen_rect, window_screen_rect);
1722 } else {
1723 view_screen_rect_ = view_screen_rect;
1724 window_screen_rect_ = window_screen_rect;
1726 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1729 void RenderWidget::showImeIfNeeded() {
1730 OnShowImeIfNeeded();
1733 void RenderWidget::OnShowImeIfNeeded() {
1734 #if defined(OS_ANDROID) || defined(USE_AURA)
1735 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1736 #endif
1738 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1739 // virtual keyboard.
1740 #if !defined(OS_ANDROID)
1741 FocusChangeComplete();
1742 #endif
1745 #if defined(OS_ANDROID)
1746 void RenderWidget::IncrementOutstandingImeEventAcks() {
1747 ++outstanding_ime_acks_;
1750 void RenderWidget::OnImeEventAck() {
1751 --outstanding_ime_acks_;
1752 DCHECK(outstanding_ime_acks_ >= 0);
1754 #endif
1756 bool RenderWidget::ShouldHandleImeEvent() {
1757 #if defined(OS_ANDROID)
1758 return !!webwidget_ && outstanding_ime_acks_ == 0;
1759 #else
1760 return !!webwidget_;
1761 #endif
1764 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1765 if (handling_event_type_ == WebInputEvent::MouseMove) {
1766 // If we pause multiple times during a single mouse move event, we should
1767 // only send ACK once.
1768 if (!ignore_ack_for_mouse_move_from_debugger_) {
1769 InputHostMsg_HandleInputEvent_ACK_Params ack;
1770 ack.type = handling_event_type_;
1771 ack.state = INPUT_EVENT_ACK_STATE_CONSUMED;
1772 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1774 return true;
1776 return false;
1779 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1780 ignore_ack_for_mouse_move_from_debugger_ = true;
1783 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1784 if (device_scale_factor_ == device_scale_factor)
1785 return;
1787 device_scale_factor_ = device_scale_factor;
1788 scheduleComposite();
1791 bool RenderWidget::SetDeviceColorProfile(
1792 const std::vector<char>& color_profile) {
1793 if (device_color_profile_ == color_profile)
1794 return false;
1796 device_color_profile_ = color_profile;
1797 return true;
1800 void RenderWidget::ResetDeviceColorProfileForTesting() {
1801 if (!device_color_profile_.empty())
1802 device_color_profile_.clear();
1803 device_color_profile_.push_back('0');
1806 void RenderWidget::OnOrientationChange() {
1809 gfx::Vector2d RenderWidget::GetScrollOffset() {
1810 // Bare RenderWidgets don't support scroll offset.
1811 return gfx::Vector2d();
1814 void RenderWidget::SetHidden(bool hidden) {
1815 if (is_hidden_ == hidden)
1816 return;
1818 // The status has changed. Tell the RenderThread about it and ensure
1819 // throttled acks are released in case frame production ceases.
1820 is_hidden_ = hidden;
1821 FlushPendingInputEventAck();
1823 if (is_hidden_)
1824 RenderThreadImpl::current()->WidgetHidden();
1825 else
1826 RenderThreadImpl::current()->WidgetRestored();
1829 void RenderWidget::WillToggleFullscreen() {
1830 if (!webwidget_)
1831 return;
1833 if (is_fullscreen_) {
1834 webwidget_->willExitFullScreen();
1835 } else {
1836 webwidget_->willEnterFullScreen();
1840 void RenderWidget::DidToggleFullscreen() {
1841 if (!webwidget_)
1842 return;
1844 if (is_fullscreen_) {
1845 webwidget_->didEnterFullScreen();
1846 } else {
1847 webwidget_->didExitFullScreen();
1851 bool RenderWidget::next_paint_is_resize_ack() const {
1852 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1855 void RenderWidget::set_next_paint_is_resize_ack() {
1856 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1859 void RenderWidget::set_next_paint_is_repaint_ack() {
1860 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1863 static bool IsDateTimeInput(ui::TextInputType type) {
1864 return type == ui::TEXT_INPUT_TYPE_DATE ||
1865 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1866 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1867 type == ui::TEXT_INPUT_TYPE_MONTH ||
1868 type == ui::TEXT_INPUT_TYPE_TIME ||
1869 type == ui::TEXT_INPUT_TYPE_WEEK;
1873 void RenderWidget::StartHandlingImeEvent() {
1874 DCHECK(!handling_ime_event_);
1875 handling_ime_event_ = true;
1878 void RenderWidget::FinishHandlingImeEvent() {
1879 DCHECK(handling_ime_event_);
1880 handling_ime_event_ = false;
1881 // While handling an ime event, text input state and selection bounds updates
1882 // are ignored. These must explicitly be updated once finished handling the
1883 // ime event.
1884 UpdateSelectionBounds();
1885 #if defined(OS_ANDROID)
1886 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1887 #endif
1890 void RenderWidget::UpdateTextInputType() {
1891 // On Windows, not only an IME but also an on-screen keyboard relies on the
1892 // latest TextInputType to optimize its layout and functionality. Thus
1893 // |input_method_is_active_| is no longer an appropriate condition to suppress
1894 // TextInputTypeChanged IPC on Windows.
1895 // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
1896 // on other platforms as well as Windows if the overhead is acceptable.
1897 #if !defined(OS_WIN)
1898 if (!input_method_is_active_)
1899 return;
1900 #endif
1902 ui::TextInputType new_type = GetTextInputType();
1903 if (IsDateTimeInput(new_type))
1904 return; // Not considered as a text input field in WebKit/Chromium.
1906 bool new_can_compose_inline = CanComposeInline();
1908 blink::WebTextInputInfo new_info;
1909 if (webwidget_)
1910 new_info = webwidget_->textInputInfo();
1911 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1912 int new_flags = new_info.flags;
1914 if (text_input_type_ != new_type
1915 || can_compose_inline_ != new_can_compose_inline
1916 || text_input_mode_ != new_mode
1917 || text_input_flags_ != new_flags) {
1918 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1919 new_type,
1920 new_mode,
1921 new_can_compose_inline,
1922 new_flags));
1923 text_input_type_ = new_type;
1924 can_compose_inline_ = new_can_compose_inline;
1925 text_input_mode_ = new_mode;
1926 text_input_flags_ = new_flags;
1930 #if defined(OS_ANDROID) || defined(USE_AURA)
1931 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1932 ChangeSource change_source) {
1933 if (handling_ime_event_)
1934 return;
1935 if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1936 return;
1937 ui::TextInputType new_type = GetTextInputType();
1938 if (IsDateTimeInput(new_type))
1939 return; // Not considered as a text input field in WebKit/Chromium.
1941 blink::WebTextInputInfo new_info;
1942 if (webwidget_)
1943 new_info = webwidget_->textInputInfo();
1945 bool new_can_compose_inline = CanComposeInline();
1947 // Only sends text input params if they are changed or if the ime should be
1948 // shown.
1949 if (show_ime == SHOW_IME_IF_NEEDED ||
1950 (text_input_type_ != new_type ||
1951 text_input_info_ != new_info ||
1952 can_compose_inline_ != new_can_compose_inline)
1953 #if defined(OS_ANDROID)
1954 || text_field_is_dirty_
1955 #endif
1957 ViewHostMsg_TextInputState_Params p;
1958 p.type = new_type;
1959 p.flags = new_info.flags;
1960 p.value = new_info.value.utf8();
1961 p.selection_start = new_info.selectionStart;
1962 p.selection_end = new_info.selectionEnd;
1963 p.composition_start = new_info.compositionStart;
1964 p.composition_end = new_info.compositionEnd;
1965 p.can_compose_inline = new_can_compose_inline;
1966 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1967 #if defined(USE_AURA)
1968 p.is_non_ime_change = true;
1969 #endif
1970 #if defined(OS_ANDROID)
1971 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1972 text_field_is_dirty_;
1973 if (p.is_non_ime_change)
1974 IncrementOutstandingImeEventAcks();
1975 text_field_is_dirty_ = false;
1976 #endif
1977 #if defined(USE_AURA)
1978 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1979 new_type,
1980 text_input_mode_,
1981 new_can_compose_inline,
1982 new_info.flags));
1983 #endif
1984 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
1986 text_input_info_ = new_info;
1987 text_input_type_ = new_type;
1988 can_compose_inline_ = new_can_compose_inline;
1989 text_input_flags_ = new_info.flags;
1992 #endif
1994 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1995 WebRect focus_webrect;
1996 WebRect anchor_webrect;
1997 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1998 *focus = focus_webrect;
1999 *anchor = anchor_webrect;
2002 void RenderWidget::UpdateSelectionBounds() {
2003 if (!webwidget_)
2004 return;
2005 if (handling_ime_event_)
2006 return;
2008 // With composited selection updates, the selection bounds will be reported
2009 // directly by the compositor, in which case explicit IPC selection
2010 // notifications should be suppressed.
2011 if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
2012 ViewHostMsg_SelectionBounds_Params params;
2013 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2014 if (selection_anchor_rect_ != params.anchor_rect ||
2015 selection_focus_rect_ != params.focus_rect) {
2016 selection_anchor_rect_ = params.anchor_rect;
2017 selection_focus_rect_ = params.focus_rect;
2018 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2019 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2020 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2024 UpdateCompositionInfo(false);
2027 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2028 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2029 static_assert(int(blink::WebTextInputType##a) \
2030 == int(ui::TEXT_INPUT_TYPE_##b), \
2031 "mismatching enums: " #a)
2033 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2034 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2035 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2036 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2037 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2038 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2039 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2040 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2041 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2042 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2043 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2044 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2045 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2046 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2047 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2048 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2049 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2051 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2052 blink::WebTextInputType type) {
2053 // Check the type is in the range representable by ui::TextInputType.
2054 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2055 "blink::WebTextInputType and ui::TextInputType not synchronized";
2056 return static_cast<ui::TextInputType>(type);
2059 ui::TextInputType RenderWidget::GetTextInputType() {
2060 if (webwidget_)
2061 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2062 return ui::TEXT_INPUT_TYPE_NONE;
2065 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2066 #if defined(OS_ANDROID)
2067 // TODO(yukawa): Start sending character bounds when the browser side
2068 // implementation becomes ready (crbug.com/424866).
2069 #else
2070 gfx::Range range = gfx::Range();
2071 if (should_update_range) {
2072 GetCompositionRange(&range);
2073 } else {
2074 range = composition_range_;
2076 std::vector<gfx::Rect> character_bounds;
2077 GetCompositionCharacterBounds(&character_bounds);
2079 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2080 return;
2081 composition_character_bounds_ = character_bounds;
2082 composition_range_ = range;
2083 Send(new InputHostMsg_ImeCompositionRangeChanged(
2084 routing_id(), composition_range_, composition_character_bounds_));
2085 #endif
2088 void RenderWidget::GetCompositionCharacterBounds(
2089 std::vector<gfx::Rect>* bounds) {
2090 DCHECK(bounds);
2091 bounds->clear();
2094 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2095 size_t location, length;
2096 if (webwidget_->compositionRange(&location, &length)) {
2097 range->set_start(location);
2098 range->set_end(location + length);
2099 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2100 range->set_start(location);
2101 range->set_end(location + length);
2102 } else {
2103 *range = gfx::Range::InvalidRange();
2107 bool RenderWidget::ShouldUpdateCompositionInfo(
2108 const gfx::Range& range,
2109 const std::vector<gfx::Rect>& bounds) {
2110 if (composition_range_ != range)
2111 return true;
2112 if (bounds.size() != composition_character_bounds_.size())
2113 return true;
2114 for (size_t i = 0; i < bounds.size(); ++i) {
2115 if (bounds[i] != composition_character_bounds_[i])
2116 return true;
2118 return false;
2121 #if defined(OS_ANDROID)
2122 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2123 // If not initialized, default to white. Note that 0 is different from black
2124 // as black still has alpha 0xFF.
2125 if (!bg_color)
2126 bg_color = SK_ColorWHITE;
2128 if (bg_color != body_background_color_) {
2129 body_background_color_ = bg_color;
2130 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2134 bool RenderWidget::DoesRecordFullLayer() const {
2135 SynchronousCompositorFactory* synchronous_compositor_factory =
2136 SynchronousCompositorFactory::GetInstance();
2138 // We assume that the absence of synchronous_compositor_factory
2139 // means we are in Chrome. In chrome, we want to clip, i.e.
2140 // *not* to record the full layer.
2141 if (!synchronous_compositor_factory)
2142 return false;
2144 return synchronous_compositor_factory->RecordFullLayer();
2146 #endif
2148 bool RenderWidget::CanComposeInline() {
2149 return true;
2152 WebScreenInfo RenderWidget::screenInfo() {
2153 return screen_info_;
2156 float RenderWidget::deviceScaleFactor() {
2157 return device_scale_factor_;
2160 void RenderWidget::resetInputMethod() {
2161 if (!input_method_is_active_)
2162 return;
2164 ImeEventGuard guard(this);
2165 // If the last text input type is not None, then we should finish any
2166 // ongoing composition regardless of the new text input type.
2167 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2168 // If a composition text exists, then we need to let the browser process
2169 // to cancel the input method's ongoing composition session.
2170 if (webwidget_->confirmComposition())
2171 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2174 UpdateCompositionInfo(true);
2177 #if defined(OS_ANDROID)
2178 void RenderWidget::showUnhandledTapUIIfNeeded(
2179 const WebPoint& tapped_position,
2180 const WebNode& tapped_node,
2181 bool page_changed) {
2182 DCHECK(handling_input_event_);
2183 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2184 !tapped_node.isContentEditable() &&
2185 !tapped_node.isInsideFocusableElementOrARIAWidget();
2186 if (should_trigger) {
2187 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2188 tapped_position.x, tapped_position.y));
2191 #endif
2193 void RenderWidget::didHandleGestureEvent(
2194 const WebGestureEvent& event,
2195 bool event_cancelled) {
2196 #if defined(OS_ANDROID) || defined(USE_AURA)
2197 if (event_cancelled)
2198 return;
2199 if (event.type == WebInputEvent::GestureTap) {
2200 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2201 } else if (event.type == WebInputEvent::GestureLongPress) {
2202 DCHECK(webwidget_);
2203 if (webwidget_->textInputInfo().value.isEmpty())
2204 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2205 else
2206 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2208 #endif
2211 void RenderWidget::StartCompositor() {
2212 // For widgets that are never visible, we don't need the compositor to run
2213 // at all.
2214 if (never_visible_)
2215 return;
2216 // In tests without a RenderThreadImpl, don't set ready as this kicks
2217 // off creating output surfaces that the test can't create.
2218 if (!RenderThreadImpl::current())
2219 return;
2220 compositor_->StartCompositor();
2223 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2224 size_t i = 0;
2225 for (; i < plugin_window_moves_.size(); ++i) {
2226 if (plugin_window_moves_[i].window == move.window) {
2227 if (move.rects_valid) {
2228 plugin_window_moves_[i] = move;
2229 } else {
2230 plugin_window_moves_[i].visible = move.visible;
2232 break;
2236 if (i == plugin_window_moves_.size())
2237 plugin_window_moves_.push_back(move);
2240 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2241 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2242 i != plugin_window_moves_.end(); ++i) {
2243 if (i->window == window) {
2244 plugin_window_moves_.erase(i);
2245 break;
2251 RenderWidgetCompositor* RenderWidget::compositor() const {
2252 return compositor_.get();
2255 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2256 return false;
2259 bool RenderWidget::WillHandleGestureEvent(
2260 const blink::WebGestureEvent& event) {
2261 return false;
2264 void RenderWidget::ObserveWheelEventAndResult(
2265 const blink::WebMouseWheelEvent& wheel_event,
2266 bool event_processed) {
2267 if (!compositor_deps_->IsElasticOverscrollEnabled())
2268 return;
2270 // Blink does not accurately compute scroll bubbling or overscroll. For now,
2271 // assume that an unprocessed event was entirely an overscroll, and that a
2272 // processed event was entirely scroll.
2273 // TODO(ccameron): Retrieve an accurate scroll result from Blink.
2274 // http://crbug.com/442859
2275 cc::InputHandlerScrollResult scroll_result;
2276 if (event_processed) {
2277 scroll_result.did_scroll = true;
2278 } else {
2279 scroll_result.did_overscroll_root = true;
2280 scroll_result.unused_scroll_delta =
2281 gfx::Vector2dF(-wheel_event.deltaX, -wheel_event.deltaY);
2284 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2285 InputHandlerManager* input_handler_manager =
2286 render_thread ? render_thread->input_handler_manager() : NULL;
2287 if (input_handler_manager) {
2288 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2289 routing_id_, wheel_event, scroll_result);
2293 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2294 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2297 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2298 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2299 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2300 "mismatching enums: " #a)
2302 void RenderWidget::setTouchAction(
2303 blink::WebTouchAction web_touch_action) {
2305 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2306 // when blink is emulating touch with mouse).
2307 if (handling_event_type_ != WebInputEvent::TouchStart)
2308 return;
2310 // Verify the same values are used by the types so we can cast between them.
2311 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2312 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2313 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2314 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2315 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2317 content::TouchAction content_touch_action =
2318 static_cast<content::TouchAction>(web_touch_action);
2319 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2322 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2323 #if defined(OS_ANDROID)
2324 text_field_is_dirty_ = true;
2325 #endif
2328 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2329 return true;
2332 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2333 RenderWidget::CreateGraphicsContext3D() {
2334 if (!webwidget_)
2335 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2336 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2337 switches::kDisableGpuCompositing))
2338 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2339 if (!RenderThreadImpl::current())
2340 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2341 CauseForGpuLaunch cause =
2342 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2343 scoped_refptr<GpuChannelHost> gpu_channel_host(
2344 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2345 if (!gpu_channel_host.get())
2346 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2348 // Explicitly disable antialiasing for the compositor. As of the time of
2349 // this writing, the only platform that supported antialiasing for the
2350 // compositor was Mac OS X, because the on-screen OpenGL context creation
2351 // code paths on Windows and Linux didn't yet have multisampling support.
2352 // Mac OS X essentially always behaves as though it's rendering offscreen.
2353 // Multisampling has a heavy cost especially on devices with relatively low
2354 // fill rate like most notebooks, and the Mac implementation would need to
2355 // be optimized to resolve directly into the IOSurface shared between the
2356 // GPU and browser processes. For these reasons and to avoid platform
2357 // disparities we explicitly disable antialiasing.
2358 blink::WebGraphicsContext3D::Attributes attributes;
2359 attributes.antialias = false;
2360 attributes.shareResources = true;
2361 attributes.noAutomaticFlushes = true;
2362 attributes.depth = false;
2363 attributes.stencil = false;
2364 bool lose_context_when_out_of_memory = true;
2365 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2366 #if defined(OS_ANDROID)
2367 // If we raster too fast we become upload bound, and pending
2368 // uploads consume memory. For maximum upload throughput, we would
2369 // want to allow for upload_throughput * pipeline_time of pending
2370 // uploads, after which we are just wasting memory. Since we don't
2371 // know our upload throughput yet, this just caps our memory usage.
2372 size_t divider = 1;
2373 if (base::SysInfo::IsLowEndDevice())
2374 divider = 6;
2375 // For reference Nexus10 can upload 1MB in about 2.5ms.
2376 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2377 // Deadline to draw a frame to achieve 60 frames per second.
2378 const size_t kMillisecondsPerFrame = 16;
2379 // Assuming a two frame deep pipeline between the CPU and the GPU.
2380 size_t max_transfer_buffer_usage_mb =
2381 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2382 static const size_t kBytesPerMegabyte = 1024 * 1024;
2383 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2384 // to avoid unnecessarily stalling the compositor thread.
2385 limits.mapped_memory_reclaim_limit =
2386 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2387 #endif
2389 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2390 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2391 GetURLForGraphicsContext3D(),
2392 gpu_channel_host.get(),
2393 attributes,
2394 lose_context_when_out_of_memory,
2395 limits,
2396 NULL));
2397 return context.Pass();
2400 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2401 render_frame_proxies_.AddObserver(proxy);
2404 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2405 render_frame_proxies_.RemoveObserver(proxy);
2408 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2409 render_frames_.AddObserver(frame);
2412 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2413 render_frames_.RemoveObserver(frame);
2416 #if defined(VIDEO_HOLE)
2417 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2418 video_hole_frames_.AddObserver(frame);
2421 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2422 video_hole_frames_.RemoveObserver(frame);
2424 #endif // defined(VIDEO_HOLE)
2426 } // namespace content