[ServiceWorker] Implement WebServiceWorkerContextClient::openWindow().
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob9cc9899a4fb9dd44ffbbccede7c54b668cdd2894
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 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);
795 compositor_->SetTopControlsShrinkBlinkSize(top_controls_shrink_blink_size);
796 compositor_->SetTopControlsHeight(top_controls_height);
799 physical_backing_size_ = physical_backing_size;
800 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
801 top_controls_height_ = top_controls_height;
802 visible_viewport_size_ = visible_viewport_size;
803 resizer_rect_ = resizer_rect;
805 // NOTE: We may have entered fullscreen mode without changing our size.
806 bool fullscreen_change = is_fullscreen_ != is_fullscreen;
807 if (fullscreen_change)
808 WillToggleFullscreen();
809 is_fullscreen_ = is_fullscreen;
811 webwidget_->setTopControlsLayoutHeight(top_controls_shrink_blink_size_
812 ? top_controls_height : 0.f);
814 if (size_ != new_size) {
815 size_ = new_size;
817 // When resizing, we want to wait to paint before ACK'ing the resize. This
818 // ensures that we only resize as fast as we can paint. We only need to
819 // send an ACK if we are resized to a non-empty rect.
820 webwidget_->resize(new_size);
821 } else if (!resizing_mode_selector_->is_synchronous_mode()) {
822 resize_ack = NO_RESIZE_ACK;
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 // For empty size or empty physical_backing_size, there is no next paint
831 // (along with which to send the ack) until they are set to non-empty.
832 resize_ack = NO_RESIZE_ACK;
835 // Send the Resize_ACK flag once we paint again if requested.
836 if (resize_ack == SEND_RESIZE_ACK)
837 set_next_paint_is_resize_ack();
839 if (fullscreen_change)
840 DidToggleFullscreen();
842 // If a resize ack is requested and it isn't set-up, then no more resizes will
843 // come in and in general things will go wrong.
844 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
847 void RenderWidget::SetWindowRectSynchronously(
848 const gfx::Rect& new_window_rect) {
849 Resize(new_window_rect.size(),
850 new_window_rect.size(),
851 top_controls_shrink_blink_size_,
852 top_controls_height_,
853 new_window_rect.size(),
854 gfx::Rect(),
855 is_fullscreen_,
856 NO_RESIZE_ACK);
857 view_screen_rect_ = new_window_rect;
858 window_screen_rect_ = new_window_rect;
859 if (!did_show_)
860 initial_rect_ = new_window_rect;
863 void RenderWidget::OnClose() {
864 if (closing_)
865 return;
866 closing_ = true;
868 // Browser correspondence is no longer needed at this point.
869 if (routing_id_ != MSG_ROUTING_NONE) {
870 if (RenderThreadImpl::current())
871 RenderThreadImpl::current()->WidgetDestroyed();
872 RenderThread::Get()->RemoveRoute(routing_id_);
873 SetHidden(false);
876 // If there is a Send call on the stack, then it could be dangerous to close
877 // now. Post a task that only gets invoked when there are no nested message
878 // loops.
879 RenderThread::Get()->GetTaskRunner()->PostNonNestableTask(
880 FROM_HERE, base::Bind(&RenderWidget::Close, this));
882 // Balances the AddRef taken when we called AddRoute.
883 Release();
886 // Got a response from the browser after the renderer decided to create a new
887 // view.
888 void RenderWidget::OnCreatingNewAck() {
889 DCHECK(routing_id_ != MSG_ROUTING_NONE);
891 CompleteInit();
894 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
895 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
896 return;
898 if (screen_metrics_emulator_) {
899 screen_metrics_emulator_->OnResizeMessage(params);
900 return;
903 bool orientation_changed =
904 screen_info_.orientationAngle != params.screen_info.orientationAngle;
906 screen_info_ = params.screen_info;
907 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
908 Resize(params.new_size,
909 params.physical_backing_size,
910 params.top_controls_shrink_blink_size,
911 params.top_controls_height,
912 params.visible_viewport_size,
913 params.resizer_rect,
914 params.is_fullscreen,
915 SEND_RESIZE_ACK);
917 if (orientation_changed)
918 OnOrientationChange();
921 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
922 SetDeviceColorProfile(color_profile);
925 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
926 if (resizer_rect_ == resizer_rect)
927 return;
928 resizer_rect_ = resizer_rect;
929 if (webwidget_)
930 webwidget_->didChangeWindowResizerRect();
933 void RenderWidget::OnWasHidden() {
934 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
935 // Go into a mode where we stop generating paint and scrolling events.
936 SetHidden(true);
937 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
938 WasHidden());
941 void RenderWidget::OnWasShown(bool needs_repainting,
942 const ui::LatencyInfo& latency_info) {
943 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
944 // During shutdown we can just ignore this message.
945 if (!webwidget_)
946 return;
948 // See OnWasHidden
949 SetHidden(false);
950 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
951 WasShown());
953 if (!needs_repainting)
954 return;
956 // Generate a full repaint.
957 if (compositor_) {
958 ui::LatencyInfo swap_latency_info(latency_info);
959 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
960 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
961 compositor_->SetNeedsForcedRedraw();
963 scheduleComposite();
966 void RenderWidget::OnRequestMoveAck() {
967 DCHECK(pending_window_rect_count_);
968 pending_window_rect_count_--;
971 GURL RenderWidget::GetURLForGraphicsContext3D() {
972 return GURL();
975 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
976 // For widgets that are never visible, we don't start the compositor, so we
977 // never get a request for a cc::OutputSurface.
978 DCHECK(!never_visible_);
980 #if defined(OS_ANDROID)
981 if (SynchronousCompositorFactory* factory =
982 SynchronousCompositorFactory::GetInstance()) {
983 return factory->CreateOutputSurface(routing_id(),
984 frame_swap_message_queue_);
986 #endif
988 const base::CommandLine& command_line =
989 *base::CommandLine::ForCurrentProcess();
990 bool use_software = fallback;
991 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
992 use_software = true;
994 scoped_refptr<ContextProviderCommandBuffer> context_provider;
995 if (!use_software) {
996 context_provider = ContextProviderCommandBuffer::Create(
997 CreateGraphicsContext3D(), "RenderCompositor");
998 if (!context_provider.get()) {
999 // Cause the compositor to wait and try again.
1000 return scoped_ptr<cc::OutputSurface>();
1004 uint32 output_surface_id = next_output_surface_id_++;
1005 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
1006 DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner());
1007 return scoped_ptr<cc::OutputSurface>(
1008 new DelegatedCompositorOutputSurface(routing_id(),
1009 output_surface_id,
1010 context_provider,
1011 frame_swap_message_queue_));
1013 if (!context_provider.get()) {
1014 scoped_ptr<cc::SoftwareOutputDevice> software_device(
1015 new CompositorSoftwareOutputDevice());
1017 return scoped_ptr<cc::OutputSurface>(
1018 new CompositorOutputSurface(routing_id(),
1019 output_surface_id,
1020 NULL,
1021 software_device.Pass(),
1022 frame_swap_message_queue_,
1023 true));
1026 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
1027 // Composite-to-mailbox is currently used for layout tests in order to cause
1028 // them to draw inside in the renderer to do the readback there. This should
1029 // no longer be the case when crbug.com/311404 is fixed.
1030 DCHECK(RenderThreadImpl::current()->layout_test_mode());
1031 cc::ResourceFormat format = cc::RGBA_8888;
1032 if (base::SysInfo::IsLowEndDevice())
1033 format = cc::RGB_565;
1034 return scoped_ptr<cc::OutputSurface>(
1035 new MailboxOutputSurface(routing_id(),
1036 output_surface_id,
1037 context_provider,
1038 scoped_ptr<cc::SoftwareOutputDevice>(),
1039 frame_swap_message_queue_,
1040 format));
1042 bool use_swap_compositor_frame_message = false;
1043 return scoped_ptr<cc::OutputSurface>(
1044 new CompositorOutputSurface(routing_id(),
1045 output_surface_id,
1046 context_provider,
1047 scoped_ptr<cc::SoftwareOutputDevice>(),
1048 frame_swap_message_queue_,
1049 use_swap_compositor_frame_message));
1052 void RenderWidget::OnSwapBuffersAborted() {
1053 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1054 // Schedule another frame so the compositor learns about it.
1055 scheduleComposite();
1058 void RenderWidget::OnSwapBuffersPosted() {
1059 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1062 void RenderWidget::OnSwapBuffersComplete() {
1063 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1065 // Notify subclasses that composited rendering was flushed to the screen.
1066 DidFlushPaint();
1069 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1070 const ui::LatencyInfo& latency_info,
1071 bool is_keyboard_shortcut) {
1072 base::AutoReset<bool> handling_input_event_resetter(
1073 &handling_input_event_, true);
1074 if (!input_event)
1075 return;
1076 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1077 &handling_event_type_, input_event->type);
1078 #if defined(OS_ANDROID)
1079 // On Android, when a key is pressed or sent from the Keyboard using IME,
1080 // |AdapterInputConnection| generates input key events to make sure all JS
1081 // listeners that monitor KeyUp and KeyDown events receive the proper key
1082 // code. Since this input key event comes from IME, we need to set the
1083 // IME event guard here to make sure it does not interfere with other IME
1084 // events.
1085 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1086 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1087 const WebKeyboardEvent& key_event =
1088 *static_cast<const WebKeyboardEvent*>(input_event);
1089 // Some keys are special and it's essential that no events get blocked.
1090 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1091 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1092 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1093 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1094 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1095 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1096 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1098 #endif
1100 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
1101 &latency_info);
1103 base::TimeTicks start_time;
1104 if (base::TimeTicks::IsHighResolution())
1105 start_time = base::TimeTicks::Now();
1107 TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent",
1108 "event", WebInputEventTraits::GetName(input_event->type));
1109 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1110 TRACE_EVENT_FLOW_STEP0(
1111 "input,benchmark",
1112 "LatencyInfo.Flow",
1113 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
1114 "HanldeInputEventMain");
1116 // If we don't have a high res timer, these metrics won't be accurate enough
1117 // to be worth collecting. Note that this does introduce some sampling bias.
1118 if (!start_time.is_null())
1119 LogInputEventLatencyUma(*input_event, start_time);
1121 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1122 ui::LatencyInfo swap_latency_info(latency_info);
1123 if (compositor_) {
1124 latency_info_swap_promise_monitor =
1125 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1126 .Pass();
1129 bool prevent_default = false;
1130 if (WebInputEvent::isMouseEventType(input_event->type)) {
1131 const WebMouseEvent& mouse_event =
1132 *static_cast<const WebMouseEvent*>(input_event);
1133 TRACE_EVENT2("renderer", "HandleMouseMove",
1134 "x", mouse_event.x, "y", mouse_event.y);
1135 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1136 prevent_default = WillHandleMouseEvent(mouse_event);
1139 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1140 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1141 #if defined(OS_ANDROID)
1142 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1143 // case it should behave like a select key (i.e. causing a click if a button
1144 // is focused). However, if a text field is focused (2), its intended
1145 // behavior is to just show the IME and don't propagate the key.
1146 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1147 // when clicked on an input text field and cause the form submit if clicked
1148 // when the submit button is focused, but not vice-versa.
1149 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1150 // but at this point we have to swallow the event for the scenario (2).
1151 const WebKeyboardEvent& key_event =
1152 *static_cast<const WebKeyboardEvent*>(input_event);
1153 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1154 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1155 OnShowImeIfNeeded();
1156 prevent_default = true;
1158 #endif
1161 if (WebInputEvent::isGestureEventType(input_event->type)) {
1162 const WebGestureEvent& gesture_event =
1163 *static_cast<const WebGestureEvent*>(input_event);
1164 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1165 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1168 bool processed = prevent_default;
1169 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1170 suppress_next_char_events_ = false;
1171 if (!processed && webwidget_)
1172 processed = webwidget_->handleInputEvent(*input_event);
1175 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1176 // it's not processed by webkit, then we need to suppress the upcoming Char
1177 // events.
1178 if (!processed && is_keyboard_shortcut)
1179 suppress_next_char_events_ = true;
1181 InputEventAckState ack_result = processed ?
1182 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1183 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1184 const WebTouchEvent& touch_event =
1185 *static_cast<const WebTouchEvent*>(input_event);
1186 // Hit-test for all the pressed touch points. If there is a touch-handler
1187 // for any of the touch points, then the renderer should continue to receive
1188 // touch events.
1189 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1190 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1191 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1192 HasTouchEventHandlersAt(
1193 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1194 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1195 break;
1200 // Send mouse wheel events and their disposition to the compositor thread, so
1201 // that they can be used to produce the elastic overscroll effect on Mac.
1202 if (input_event->type == WebInputEvent::MouseWheel) {
1203 ObserveWheelEventAndResult(
1204 static_cast<const WebMouseWheelEvent&>(*input_event), processed);
1207 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1209 // If we don't have a fast and accurate Now(), we assume the input handlers
1210 // are heavy and rate limit them.
1211 bool rate_limiting_wanted =
1212 input_event->type == WebInputEvent::MouseMove ||
1213 input_event->type == WebInputEvent::MouseWheel;
1214 if (rate_limiting_wanted && !start_time.is_null()) {
1215 base::TimeTicks end_time = base::TimeTicks::Now();
1216 total_input_handling_time_this_frame_ += (end_time - start_time);
1217 rate_limiting_wanted =
1218 total_input_handling_time_this_frame_.InMicroseconds() >
1219 kInputHandlingTimeThrottlingThresholdMicroseconds;
1222 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1224 // Note that we can't use handling_event_type_ here since it will be overriden
1225 // by reentrant calls for events after the paused one.
1226 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1227 input_event->type == WebInputEvent::MouseMove;
1228 if (!WebInputEventTraits::IgnoresAckDisposition(*input_event) && !no_ack) {
1229 InputHostMsg_HandleInputEvent_ACK_Params ack;
1230 ack.type = input_event->type;
1231 ack.state = ack_result;
1232 ack.latency = swap_latency_info;
1233 scoped_ptr<IPC::Message> response(
1234 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1235 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1236 // We want to rate limit the input events in this case, so we'll wait for
1237 // painting to finish before ACKing this message.
1238 TRACE_EVENT_INSTANT0("renderer",
1239 "RenderWidget::OnHandleInputEvent ack throttled",
1240 TRACE_EVENT_SCOPE_THREAD);
1241 if (pending_input_event_ack_) {
1242 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1243 pending_input_event_ack_.get());
1244 // As two different kinds of events could cause us to postpone an ack
1245 // we send it now, if we have one pending. The Browser should never
1246 // send us the same kind of event we are delaying the ack for.
1247 Send(pending_input_event_ack_.release());
1249 pending_input_event_ack_ = response.Pass();
1250 TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck",
1251 pending_input_event_ack_.get());
1252 if (compositor_)
1253 compositor_->NotifyInputThrottledUntilCommit();
1254 } else {
1255 Send(response.release());
1258 if (input_event->type == WebInputEvent::MouseMove)
1259 ignore_ack_for_mouse_move_from_debugger_ = false;
1261 #if defined(OS_ANDROID)
1262 // Allow the IME to be shown when the focus changes as a consequence
1263 // of a processed touch end event.
1264 if (input_event->type == WebInputEvent::TouchEnd && processed)
1265 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1266 #elif defined(USE_AURA)
1267 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1268 // change.
1269 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1270 input_event->type == WebInputEvent::MouseUp)) {
1271 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1273 #endif
1275 if (!prevent_default) {
1276 if (WebInputEvent::isKeyboardEventType(input_event->type))
1277 DidHandleKeyEvent();
1278 if (WebInputEvent::isMouseEventType(input_event->type))
1279 DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1280 if (WebInputEvent::isTouchEventType(input_event->type))
1281 DidHandleTouchEvent(*(static_cast<const WebTouchEvent*>(input_event)));
1284 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1285 // virtual keyboard.
1286 #if !defined(OS_ANDROID)
1287 // Virtual keyboard is not supported, so react to focus change immediately.
1288 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1289 input_event->type == WebInputEvent::MouseUp)) {
1290 FocusChangeComplete();
1292 #endif
1295 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1296 if (webwidget_)
1297 webwidget_->setCursorVisibilityState(is_visible);
1300 void RenderWidget::OnMouseCaptureLost() {
1301 if (webwidget_)
1302 webwidget_->mouseCaptureLost();
1305 void RenderWidget::OnSetFocus(bool enable) {
1306 has_focus_ = enable;
1307 if (webwidget_)
1308 webwidget_->setFocus(enable);
1311 void RenderWidget::ClearFocus() {
1312 // We may have got the focus from the browser before this gets processed, in
1313 // which case we do not want to unfocus ourself.
1314 if (!has_focus_ && webwidget_)
1315 webwidget_->setFocus(false);
1318 void RenderWidget::FlushPendingInputEventAck() {
1319 if (pending_input_event_ack_) {
1320 TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck",
1321 pending_input_event_ack_.get());
1322 Send(pending_input_event_ack_.release());
1324 total_input_handling_time_this_frame_ = base::TimeDelta();
1327 ///////////////////////////////////////////////////////////////////////////////
1328 // WebWidgetClient
1330 void RenderWidget::didAutoResize(const WebSize& new_size) {
1331 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1332 size_ = new_size;
1334 if (resizing_mode_selector_->is_synchronous_mode()) {
1335 WebRect new_pos(rootWindowRect().x,
1336 rootWindowRect().y,
1337 new_size.width,
1338 new_size.height);
1339 view_screen_rect_ = new_pos;
1340 window_screen_rect_ = new_pos;
1343 AutoResizeCompositor();
1345 if (!resizing_mode_selector_->is_synchronous_mode())
1346 need_update_rect_for_auto_resize_ = true;
1350 void RenderWidget::AutoResizeCompositor() {
1351 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1352 device_scale_factor_));
1353 if (compositor_)
1354 compositor_->setViewportSize(size_, physical_backing_size_);
1357 void RenderWidget::initializeLayerTreeView() {
1358 DCHECK(!host_closing_);
1360 compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_);
1361 compositor_->setViewportSize(size_, physical_backing_size_);
1362 if (init_complete_)
1363 StartCompositor();
1366 void RenderWidget::WillCloseLayerTreeView() {
1367 if (host_closing_)
1368 return;
1370 // Prevent new compositors or output surfaces from being created.
1371 host_closing_ = true;
1373 // Always send this notification to prevent new layer tree views from
1374 // being created, even if one hasn't been created yet.
1375 if (webwidget_)
1376 webwidget_->willCloseLayerTreeView();
1379 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1380 return compositor_.get();
1383 void RenderWidget::willBeginCompositorFrame() {
1384 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1386 // The following two can result in further layout and possibly
1387 // enable GPU acceleration so they need to be called before any painting
1388 // is done.
1389 UpdateTextInputType();
1390 #if defined(OS_ANDROID)
1391 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1392 #endif
1393 UpdateSelectionBounds();
1396 void RenderWidget::didBecomeReadyForAdditionalInput() {
1397 TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1398 FlushPendingInputEventAck();
1401 void RenderWidget::DidCommitCompositorFrame() {
1402 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1403 DidCommitCompositorFrame());
1404 #if defined(VIDEO_HOLE)
1405 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1406 DidCommitCompositorFrame());
1407 #endif // defined(VIDEO_HOLE)
1410 // static
1411 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1412 IPC::Message* msg,
1413 MessageDeliveryPolicy policy,
1414 FrameSwapMessageQueue* frame_swap_message_queue,
1415 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1416 bool commit_requested,
1417 int source_frame_number) {
1418 if (policy == MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE &&
1419 // No need for lock: this gets changed only on this thread.
1420 !commit_requested &&
1421 // No need for lock: Messages are only enqueued from this thread, if we
1422 // don't have any now, no other thread will add any.
1423 frame_swap_message_queue->Empty()) {
1424 sync_message_filter->Send(msg);
1425 return nullptr;
1428 bool first_message_for_frame = false;
1429 frame_swap_message_queue->QueueMessageForFrame(policy,
1430 source_frame_number,
1431 make_scoped_ptr(msg),
1432 &first_message_for_frame);
1433 if (first_message_for_frame) {
1434 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1435 sync_message_filter, frame_swap_message_queue, source_frame_number));
1436 return promise;
1438 return nullptr;
1441 void RenderWidget::QueueMessage(IPC::Message* msg,
1442 MessageDeliveryPolicy policy) {
1443 // RenderThreadImpl::current() is NULL in some tests.
1444 if (!compositor_ || !RenderThreadImpl::current()) {
1445 Send(msg);
1446 return;
1449 scoped_ptr<cc::SwapPromise> swap_promise =
1450 QueueMessageImpl(msg,
1451 policy,
1452 frame_swap_message_queue_.get(),
1453 RenderThreadImpl::current()->sync_message_filter(),
1454 compositor_->BeginMainFrameRequested(),
1455 compositor_->GetSourceFrameNumber());
1457 if (swap_promise) {
1458 compositor_->QueueSwapPromise(swap_promise.Pass());
1459 compositor_->SetNeedsCommit();
1463 void RenderWidget::didCommitAndDrawCompositorFrame() {
1464 // NOTE: Tests may break if this event is renamed or moved. See
1465 // tab_capture_performancetest.cc.
1466 TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1467 // Notify subclasses that we initiated the paint operation.
1468 DidInitiatePaint();
1471 void RenderWidget::didCompleteSwapBuffers() {
1472 TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
1474 // Notify subclasses threaded composited rendering was flushed to the screen.
1475 DidFlushPaint();
1477 if (!next_paint_flags_ &&
1478 !need_update_rect_for_auto_resize_ &&
1479 !plugin_window_moves_.size()) {
1480 return;
1483 ViewHostMsg_UpdateRect_Params params;
1484 params.view_size = size_;
1485 params.plugin_window_moves.swap(plugin_window_moves_);
1486 params.flags = next_paint_flags_;
1488 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1489 next_paint_flags_ = 0;
1490 need_update_rect_for_auto_resize_ = false;
1493 void RenderWidget::scheduleComposite() {
1494 if (compositor_ &&
1495 compositor_deps_->GetCompositorImplThreadTaskRunner().get()) {
1496 compositor_->setNeedsAnimate();
1500 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1501 // TODO(darin): Eliminate this temporary.
1502 WebCursor cursor;
1503 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1504 // Only send a SetCursor message if we need to make a change.
1505 if (!current_cursor_.IsEqual(cursor)) {
1506 current_cursor_ = cursor;
1507 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1511 // We are supposed to get a single call to Show for a newly created RenderWidget
1512 // that was created via RenderWidget::CreateWebView. So, we wait until this
1513 // point to dispatch the ShowWidget message.
1515 // This method provides us with the information about how to display the newly
1516 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1518 void RenderWidget::show(WebNavigationPolicy) {
1519 DCHECK(!did_show_) << "received extraneous Show call";
1520 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1521 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1523 if (did_show_)
1524 return;
1526 did_show_ = true;
1527 // NOTE: initial_rect_ may still have its default values at this point, but
1528 // that's okay. It'll be ignored if as_popup is false, or the browser
1529 // process will impose a default position otherwise.
1530 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_));
1531 SetPendingWindowRect(initial_rect_);
1534 void RenderWidget::didFocus() {
1537 void RenderWidget::didBlur() {
1540 void RenderWidget::DoDeferredClose() {
1541 WillCloseLayerTreeView();
1542 Send(new ViewHostMsg_Close(routing_id_));
1545 void RenderWidget::closeWidgetSoon() {
1546 if (is_swapped_out_) {
1547 // This widget is currently swapped out, and the active widget is in a
1548 // different process. Have the browser route the close request to the
1549 // active widget instead, so that the correct unload handlers are run.
1550 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1551 return;
1554 // If a page calls window.close() twice, we'll end up here twice, but that's
1555 // OK. It is safe to send multiple Close messages.
1557 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1558 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1559 // could be closed before the JS finishes executing. So instead, post a
1560 // message back to the message loop, which won't run until the JS is
1561 // complete, and then the Close message can be sent.
1562 RenderThread::Get()->GetTaskRunner()->PostTask(
1563 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1566 void RenderWidget::QueueSyntheticGesture(
1567 scoped_ptr<SyntheticGestureParams> gesture_params,
1568 const SyntheticGestureCompletionCallback& callback) {
1569 DCHECK(!callback.is_null());
1571 pending_synthetic_gesture_callbacks_.push(callback);
1573 SyntheticGesturePacket gesture_packet;
1574 gesture_packet.set_gesture_params(gesture_params.Pass());
1576 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1579 void RenderWidget::Close() {
1580 screen_metrics_emulator_.reset();
1581 WillCloseLayerTreeView();
1582 compositor_.reset();
1583 if (webwidget_) {
1584 webwidget_->close();
1585 webwidget_ = NULL;
1589 WebRect RenderWidget::windowRect() {
1590 if (pending_window_rect_count_)
1591 return pending_window_rect_;
1593 return view_screen_rect_;
1596 void RenderWidget::setToolTipText(const blink::WebString& text,
1597 WebTextDirection hint) {
1598 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1601 void RenderWidget::setWindowRect(const WebRect& rect) {
1602 WebRect window_rect = rect;
1603 if (popup_origin_scale_for_emulation_) {
1604 float scale = popup_origin_scale_for_emulation_;
1605 window_rect.x = popup_screen_origin_for_emulation_.x() +
1606 (window_rect.x - popup_view_origin_for_emulation_.x()) * scale;
1607 window_rect.y = popup_screen_origin_for_emulation_.y() +
1608 (window_rect.y - popup_view_origin_for_emulation_.y()) * scale;
1611 if (!resizing_mode_selector_->is_synchronous_mode()) {
1612 if (did_show_) {
1613 Send(new ViewHostMsg_RequestMove(routing_id_, window_rect));
1614 SetPendingWindowRect(window_rect);
1615 } else {
1616 initial_rect_ = window_rect;
1618 } else {
1619 SetWindowRectSynchronously(window_rect);
1623 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1624 pending_window_rect_ = rect;
1625 pending_window_rect_count_++;
1628 WebRect RenderWidget::rootWindowRect() {
1629 if (pending_window_rect_count_) {
1630 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1631 // the RootWindowRect is probably going to return wrong results since the
1632 // browser may not have processed the Move yet. There isn't really anything
1633 // good to do in this case, and it shouldn't happen - since this size is
1634 // only really needed for windowToScreen, which is only used for Popups.
1635 return pending_window_rect_;
1638 return window_screen_rect_;
1641 WebRect RenderWidget::windowResizerRect() {
1642 return resizer_rect_;
1645 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1646 // To prevent this renderer process from sending unnecessary IPC messages to
1647 // a browser process, we permit the renderer process to send IPC messages
1648 // only during the input method attached to the browser process is active.
1649 input_method_is_active_ = is_active;
1652 void RenderWidget::OnCandidateWindowShown() {
1653 webwidget_->didShowCandidateWindow();
1656 void RenderWidget::OnCandidateWindowUpdated() {
1657 webwidget_->didUpdateCandidateWindow();
1660 void RenderWidget::OnCandidateWindowHidden() {
1661 webwidget_->didHideCandidateWindow();
1664 void RenderWidget::OnImeSetComposition(
1665 const base::string16& text,
1666 const std::vector<WebCompositionUnderline>& underlines,
1667 int selection_start, int selection_end) {
1668 if (!ShouldHandleImeEvent())
1669 return;
1670 ImeEventGuard guard(this);
1671 if (!webwidget_->setComposition(
1672 text, WebVector<WebCompositionUnderline>(underlines),
1673 selection_start, selection_end)) {
1674 // If we failed to set the composition text, then we need to let the browser
1675 // process to cancel the input method's ongoing composition session, to make
1676 // sure we are in a consistent state.
1677 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1679 UpdateCompositionInfo(true);
1682 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1683 const gfx::Range& replacement_range,
1684 bool keep_selection) {
1685 if (!ShouldHandleImeEvent())
1686 return;
1687 ImeEventGuard guard(this);
1688 handling_input_event_ = true;
1689 if (text.length())
1690 webwidget_->confirmComposition(text);
1691 else if (keep_selection)
1692 webwidget_->confirmComposition(WebWidget::KeepSelection);
1693 else
1694 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1695 handling_input_event_ = false;
1696 UpdateCompositionInfo(true);
1699 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1700 // During shutdown we can just ignore this message.
1701 if (!webwidget_)
1702 return;
1704 // Even if the browser provides an empty damage rect, it's still expecting to
1705 // receive a repaint ack so just damage the entire widget bounds.
1706 if (size_to_paint.IsEmpty()) {
1707 size_to_paint = size_;
1710 set_next_paint_is_repaint_ack();
1711 if (compositor_)
1712 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1715 void RenderWidget::OnSyntheticGestureCompleted() {
1716 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1718 pending_synthetic_gesture_callbacks_.front().Run();
1719 pending_synthetic_gesture_callbacks_.pop();
1722 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1723 if (!webwidget_)
1724 return;
1725 webwidget_->setTextDirection(direction);
1728 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1729 const gfx::Rect& window_screen_rect) {
1730 if (screen_metrics_emulator_) {
1731 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1732 view_screen_rect, window_screen_rect);
1733 } else {
1734 view_screen_rect_ = view_screen_rect;
1735 window_screen_rect_ = window_screen_rect;
1737 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1740 void RenderWidget::showImeIfNeeded() {
1741 OnShowImeIfNeeded();
1744 void RenderWidget::OnShowImeIfNeeded() {
1745 #if defined(OS_ANDROID) || defined(USE_AURA)
1746 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1747 #endif
1749 // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
1750 // virtual keyboard.
1751 #if !defined(OS_ANDROID)
1752 FocusChangeComplete();
1753 #endif
1756 #if defined(OS_ANDROID)
1757 void RenderWidget::IncrementOutstandingImeEventAcks() {
1758 ++outstanding_ime_acks_;
1761 void RenderWidget::OnImeEventAck() {
1762 --outstanding_ime_acks_;
1763 DCHECK(outstanding_ime_acks_ >= 0);
1765 #endif
1767 bool RenderWidget::ShouldHandleImeEvent() {
1768 #if defined(OS_ANDROID)
1769 return !!webwidget_ && outstanding_ime_acks_ == 0;
1770 #else
1771 return !!webwidget_;
1772 #endif
1775 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1776 if (handling_event_type_ == WebInputEvent::MouseMove) {
1777 // If we pause multiple times during a single mouse move event, we should
1778 // only send ACK once.
1779 if (!ignore_ack_for_mouse_move_from_debugger_) {
1780 InputHostMsg_HandleInputEvent_ACK_Params ack;
1781 ack.type = handling_event_type_;
1782 ack.state = INPUT_EVENT_ACK_STATE_CONSUMED;
1783 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1785 return true;
1787 return false;
1790 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1791 ignore_ack_for_mouse_move_from_debugger_ = true;
1794 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1795 if (device_scale_factor_ == device_scale_factor)
1796 return;
1798 device_scale_factor_ = device_scale_factor;
1799 scheduleComposite();
1802 bool RenderWidget::SetDeviceColorProfile(
1803 const std::vector<char>& color_profile) {
1804 if (device_color_profile_ == color_profile)
1805 return false;
1807 device_color_profile_ = color_profile;
1808 return true;
1811 void RenderWidget::ResetDeviceColorProfileForTesting() {
1812 if (!device_color_profile_.empty())
1813 device_color_profile_.clear();
1814 device_color_profile_.push_back('0');
1817 void RenderWidget::OnOrientationChange() {
1820 gfx::Vector2d RenderWidget::GetScrollOffset() {
1821 // Bare RenderWidgets don't support scroll offset.
1822 return gfx::Vector2d();
1825 void RenderWidget::SetHidden(bool hidden) {
1826 if (is_hidden_ == hidden)
1827 return;
1829 // The status has changed. Tell the RenderThread about it and ensure
1830 // throttled acks are released in case frame production ceases.
1831 is_hidden_ = hidden;
1832 FlushPendingInputEventAck();
1834 if (is_hidden_)
1835 RenderThreadImpl::current()->WidgetHidden();
1836 else
1837 RenderThreadImpl::current()->WidgetRestored();
1840 void RenderWidget::WillToggleFullscreen() {
1841 if (!webwidget_)
1842 return;
1844 if (is_fullscreen_) {
1845 webwidget_->willExitFullScreen();
1846 } else {
1847 webwidget_->willEnterFullScreen();
1851 void RenderWidget::DidToggleFullscreen() {
1852 if (!webwidget_)
1853 return;
1855 if (is_fullscreen_) {
1856 webwidget_->didEnterFullScreen();
1857 } else {
1858 webwidget_->didExitFullScreen();
1862 bool RenderWidget::next_paint_is_resize_ack() const {
1863 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1866 void RenderWidget::set_next_paint_is_resize_ack() {
1867 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1870 void RenderWidget::set_next_paint_is_repaint_ack() {
1871 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1874 static bool IsDateTimeInput(ui::TextInputType type) {
1875 return type == ui::TEXT_INPUT_TYPE_DATE ||
1876 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1877 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1878 type == ui::TEXT_INPUT_TYPE_MONTH ||
1879 type == ui::TEXT_INPUT_TYPE_TIME ||
1880 type == ui::TEXT_INPUT_TYPE_WEEK;
1884 void RenderWidget::StartHandlingImeEvent() {
1885 DCHECK(!handling_ime_event_);
1886 handling_ime_event_ = true;
1889 void RenderWidget::FinishHandlingImeEvent() {
1890 DCHECK(handling_ime_event_);
1891 handling_ime_event_ = false;
1892 // While handling an ime event, text input state and selection bounds updates
1893 // are ignored. These must explicitly be updated once finished handling the
1894 // ime event.
1895 UpdateSelectionBounds();
1896 #if defined(OS_ANDROID)
1897 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1898 #endif
1901 void RenderWidget::UpdateTextInputType() {
1902 // On Windows, not only an IME but also an on-screen keyboard relies on the
1903 // latest TextInputType to optimize its layout and functionality. Thus
1904 // |input_method_is_active_| is no longer an appropriate condition to suppress
1905 // TextInputTypeChanged IPC on Windows.
1906 // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
1907 // on other platforms as well as Windows if the overhead is acceptable.
1908 #if !defined(OS_WIN)
1909 if (!input_method_is_active_)
1910 return;
1911 #endif
1913 ui::TextInputType new_type = GetTextInputType();
1914 if (IsDateTimeInput(new_type))
1915 return; // Not considered as a text input field in WebKit/Chromium.
1917 bool new_can_compose_inline = CanComposeInline();
1919 blink::WebTextInputInfo new_info;
1920 if (webwidget_)
1921 new_info = webwidget_->textInputInfo();
1922 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1923 int new_flags = new_info.flags;
1925 if (text_input_type_ != new_type
1926 || can_compose_inline_ != new_can_compose_inline
1927 || text_input_mode_ != new_mode
1928 || text_input_flags_ != new_flags) {
1929 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1930 new_type,
1931 new_mode,
1932 new_can_compose_inline,
1933 new_flags));
1934 text_input_type_ = new_type;
1935 can_compose_inline_ = new_can_compose_inline;
1936 text_input_mode_ = new_mode;
1937 text_input_flags_ = new_flags;
1941 #if defined(OS_ANDROID) || defined(USE_AURA)
1942 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1943 ChangeSource change_source) {
1944 if (handling_ime_event_)
1945 return;
1946 if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1947 return;
1948 ui::TextInputType new_type = GetTextInputType();
1949 if (IsDateTimeInput(new_type))
1950 return; // Not considered as a text input field in WebKit/Chromium.
1952 blink::WebTextInputInfo new_info;
1953 if (webwidget_)
1954 new_info = webwidget_->textInputInfo();
1956 bool new_can_compose_inline = CanComposeInline();
1958 // Only sends text input params if they are changed or if the ime should be
1959 // shown.
1960 if (show_ime == SHOW_IME_IF_NEEDED ||
1961 (text_input_type_ != new_type ||
1962 text_input_info_ != new_info ||
1963 can_compose_inline_ != new_can_compose_inline)
1964 #if defined(OS_ANDROID)
1965 || text_field_is_dirty_
1966 #endif
1968 ViewHostMsg_TextInputState_Params p;
1969 p.type = new_type;
1970 p.flags = new_info.flags;
1971 p.value = new_info.value.utf8();
1972 p.selection_start = new_info.selectionStart;
1973 p.selection_end = new_info.selectionEnd;
1974 p.composition_start = new_info.compositionStart;
1975 p.composition_end = new_info.compositionEnd;
1976 p.can_compose_inline = new_can_compose_inline;
1977 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1978 #if defined(USE_AURA)
1979 p.is_non_ime_change = true;
1980 #endif
1981 #if defined(OS_ANDROID)
1982 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1983 text_field_is_dirty_;
1984 if (p.is_non_ime_change)
1985 IncrementOutstandingImeEventAcks();
1986 text_field_is_dirty_ = false;
1987 #endif
1988 #if defined(USE_AURA)
1989 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1990 new_type,
1991 text_input_mode_,
1992 new_can_compose_inline,
1993 new_info.flags));
1994 #endif
1995 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
1997 text_input_info_ = new_info;
1998 text_input_type_ = new_type;
1999 can_compose_inline_ = new_can_compose_inline;
2000 text_input_flags_ = new_info.flags;
2003 #endif
2005 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
2006 WebRect focus_webrect;
2007 WebRect anchor_webrect;
2008 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
2009 *focus = focus_webrect;
2010 *anchor = anchor_webrect;
2013 void RenderWidget::UpdateSelectionBounds() {
2014 if (!webwidget_)
2015 return;
2016 if (handling_ime_event_)
2017 return;
2019 // With composited selection updates, the selection bounds will be reported
2020 // directly by the compositor, in which case explicit IPC selection
2021 // notifications should be suppressed.
2022 if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
2023 ViewHostMsg_SelectionBounds_Params params;
2024 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
2025 if (selection_anchor_rect_ != params.anchor_rect ||
2026 selection_focus_rect_ != params.focus_rect) {
2027 selection_anchor_rect_ = params.anchor_rect;
2028 selection_focus_rect_ = params.focus_rect;
2029 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2030 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2031 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2035 UpdateCompositionInfo(false);
2038 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2039 #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \
2040 static_assert(int(blink::WebTextInputType##a) \
2041 == int(ui::TEXT_INPUT_TYPE_##b), \
2042 "mismatching enums: " #a)
2044 STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE);
2045 STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT);
2046 STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD);
2047 STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH);
2048 STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL);
2049 STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER);
2050 STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE);
2051 STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL);
2052 STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE);
2053 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME);
2054 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL);
2055 STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH);
2056 STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME);
2057 STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK);
2058 STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA);
2059 STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE);
2060 STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD);
2062 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2063 blink::WebTextInputType type) {
2064 // Check the type is in the range representable by ui::TextInputType.
2065 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2066 "blink::WebTextInputType and ui::TextInputType not synchronized";
2067 return static_cast<ui::TextInputType>(type);
2070 ui::TextInputType RenderWidget::GetTextInputType() {
2071 if (webwidget_)
2072 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2073 return ui::TEXT_INPUT_TYPE_NONE;
2076 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2077 #if defined(OS_ANDROID)
2078 // TODO(yukawa): Start sending character bounds when the browser side
2079 // implementation becomes ready (crbug.com/424866).
2080 #else
2081 gfx::Range range = gfx::Range();
2082 if (should_update_range) {
2083 GetCompositionRange(&range);
2084 } else {
2085 range = composition_range_;
2087 std::vector<gfx::Rect> character_bounds;
2088 GetCompositionCharacterBounds(&character_bounds);
2090 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2091 return;
2092 composition_character_bounds_ = character_bounds;
2093 composition_range_ = range;
2094 Send(new InputHostMsg_ImeCompositionRangeChanged(
2095 routing_id(), composition_range_, composition_character_bounds_));
2096 #endif
2099 void RenderWidget::GetCompositionCharacterBounds(
2100 std::vector<gfx::Rect>* bounds) {
2101 DCHECK(bounds);
2102 bounds->clear();
2105 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2106 size_t location, length;
2107 if (webwidget_->compositionRange(&location, &length)) {
2108 range->set_start(location);
2109 range->set_end(location + length);
2110 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2111 range->set_start(location);
2112 range->set_end(location + length);
2113 } else {
2114 *range = gfx::Range::InvalidRange();
2118 bool RenderWidget::ShouldUpdateCompositionInfo(
2119 const gfx::Range& range,
2120 const std::vector<gfx::Rect>& bounds) {
2121 if (composition_range_ != range)
2122 return true;
2123 if (bounds.size() != composition_character_bounds_.size())
2124 return true;
2125 for (size_t i = 0; i < bounds.size(); ++i) {
2126 if (bounds[i] != composition_character_bounds_[i])
2127 return true;
2129 return false;
2132 #if defined(OS_ANDROID)
2133 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2134 // If not initialized, default to white. Note that 0 is different from black
2135 // as black still has alpha 0xFF.
2136 if (!bg_color)
2137 bg_color = SK_ColorWHITE;
2139 if (bg_color != body_background_color_) {
2140 body_background_color_ = bg_color;
2141 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2145 bool RenderWidget::DoesRecordFullLayer() const {
2146 SynchronousCompositorFactory* synchronous_compositor_factory =
2147 SynchronousCompositorFactory::GetInstance();
2149 // We assume that the absence of synchronous_compositor_factory
2150 // means we are in Chrome. In chrome, we want to clip, i.e.
2151 // *not* to record the full layer.
2152 if (!synchronous_compositor_factory)
2153 return false;
2155 return synchronous_compositor_factory->RecordFullLayer();
2157 #endif
2159 bool RenderWidget::CanComposeInline() {
2160 return true;
2163 WebScreenInfo RenderWidget::screenInfo() {
2164 return screen_info_;
2167 float RenderWidget::deviceScaleFactor() {
2168 return device_scale_factor_;
2171 void RenderWidget::resetInputMethod() {
2172 if (!input_method_is_active_)
2173 return;
2175 ImeEventGuard guard(this);
2176 // If the last text input type is not None, then we should finish any
2177 // ongoing composition regardless of the new text input type.
2178 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2179 // If a composition text exists, then we need to let the browser process
2180 // to cancel the input method's ongoing composition session.
2181 if (webwidget_->confirmComposition())
2182 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2185 UpdateCompositionInfo(true);
2188 #if defined(OS_ANDROID)
2189 void RenderWidget::showUnhandledTapUIIfNeeded(
2190 const WebPoint& tapped_position,
2191 const WebNode& tapped_node,
2192 bool page_changed) {
2193 DCHECK(handling_input_event_);
2194 bool should_trigger = !page_changed && tapped_node.isTextNode() &&
2195 !tapped_node.isContentEditable();
2196 if (should_trigger) {
2197 Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_,
2198 tapped_position.x, tapped_position.y));
2201 #endif
2203 void RenderWidget::didHandleGestureEvent(
2204 const WebGestureEvent& event,
2205 bool event_cancelled) {
2206 #if defined(OS_ANDROID) || defined(USE_AURA)
2207 if (event_cancelled)
2208 return;
2209 if (event.type == WebInputEvent::GestureTap) {
2210 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2211 } else if (event.type == WebInputEvent::GestureLongPress) {
2212 DCHECK(webwidget_);
2213 if (webwidget_->textInputInfo().value.isEmpty())
2214 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2215 else
2216 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2218 #endif
2221 void RenderWidget::StartCompositor() {
2222 // For widgets that are never visible, we don't need the compositor to run
2223 // at all.
2224 if (never_visible_)
2225 return;
2226 // In tests without a RenderThreadImpl, don't set ready as this kicks
2227 // off creating output surfaces that the test can't create.
2228 if (!RenderThreadImpl::current())
2229 return;
2230 compositor_->StartCompositor();
2233 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2234 size_t i = 0;
2235 for (; i < plugin_window_moves_.size(); ++i) {
2236 if (plugin_window_moves_[i].window == move.window) {
2237 if (move.rects_valid) {
2238 plugin_window_moves_[i] = move;
2239 } else {
2240 plugin_window_moves_[i].visible = move.visible;
2242 break;
2246 if (i == plugin_window_moves_.size())
2247 plugin_window_moves_.push_back(move);
2250 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2251 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2252 i != plugin_window_moves_.end(); ++i) {
2253 if (i->window == window) {
2254 plugin_window_moves_.erase(i);
2255 break;
2261 RenderWidgetCompositor* RenderWidget::compositor() const {
2262 return compositor_.get();
2265 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2266 return false;
2269 bool RenderWidget::WillHandleGestureEvent(
2270 const blink::WebGestureEvent& event) {
2271 return false;
2274 void RenderWidget::ObserveWheelEventAndResult(
2275 const blink::WebMouseWheelEvent& wheel_event,
2276 bool event_processed) {
2277 if (!compositor_deps_->IsElasticOverscrollEnabled())
2278 return;
2280 // Blink does not accurately compute scroll bubbling or overscroll. For now,
2281 // assume that an unprocessed event was entirely an overscroll, and that a
2282 // processed event was entirely scroll.
2283 // TODO(ccameron): Retrieve an accurate scroll result from Blink.
2284 // http://crbug.com/442859
2285 cc::InputHandlerScrollResult scroll_result;
2286 if (event_processed) {
2287 scroll_result.did_scroll = true;
2288 } else {
2289 scroll_result.did_overscroll_root = true;
2290 scroll_result.unused_scroll_delta =
2291 gfx::Vector2dF(-wheel_event.deltaX, -wheel_event.deltaY);
2294 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2295 InputHandlerManager* input_handler_manager =
2296 render_thread ? render_thread->input_handler_manager() : NULL;
2297 if (input_handler_manager) {
2298 input_handler_manager->ObserveWheelEventAndResultOnMainThread(
2299 routing_id_, wheel_event, scroll_result);
2303 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2304 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2307 // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync
2308 #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \
2309 static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \
2310 "mismatching enums: " #a)
2312 void RenderWidget::setTouchAction(
2313 blink::WebTouchAction web_touch_action) {
2315 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2316 // when blink is emulating touch with mouse).
2317 if (handling_event_type_ != WebInputEvent::TouchStart)
2318 return;
2320 // Verify the same values are used by the types so we can cast between them.
2321 STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO);
2322 STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE);
2323 STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X);
2324 STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y);
2325 STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM);
2327 content::TouchAction content_touch_action =
2328 static_cast<content::TouchAction>(web_touch_action);
2329 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2332 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2333 #if defined(OS_ANDROID)
2334 text_field_is_dirty_ = true;
2335 #endif
2338 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2339 return true;
2342 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2343 RenderWidget::CreateGraphicsContext3D() {
2344 if (!webwidget_)
2345 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2346 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2347 switches::kDisableGpuCompositing))
2348 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2349 if (!RenderThreadImpl::current())
2350 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2351 CauseForGpuLaunch cause =
2352 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2353 scoped_refptr<GpuChannelHost> gpu_channel_host(
2354 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2355 if (!gpu_channel_host.get())
2356 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2358 // Explicitly disable antialiasing for the compositor. As of the time of
2359 // this writing, the only platform that supported antialiasing for the
2360 // compositor was Mac OS X, because the on-screen OpenGL context creation
2361 // code paths on Windows and Linux didn't yet have multisampling support.
2362 // Mac OS X essentially always behaves as though it's rendering offscreen.
2363 // Multisampling has a heavy cost especially on devices with relatively low
2364 // fill rate like most notebooks, and the Mac implementation would need to
2365 // be optimized to resolve directly into the IOSurface shared between the
2366 // GPU and browser processes. For these reasons and to avoid platform
2367 // disparities we explicitly disable antialiasing.
2368 blink::WebGraphicsContext3D::Attributes attributes;
2369 attributes.antialias = false;
2370 attributes.shareResources = true;
2371 attributes.noAutomaticFlushes = true;
2372 attributes.depth = false;
2373 attributes.stencil = false;
2374 bool lose_context_when_out_of_memory = true;
2375 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2376 #if defined(OS_ANDROID)
2377 // If we raster too fast we become upload bound, and pending
2378 // uploads consume memory. For maximum upload throughput, we would
2379 // want to allow for upload_throughput * pipeline_time of pending
2380 // uploads, after which we are just wasting memory. Since we don't
2381 // know our upload throughput yet, this just caps our memory usage.
2382 size_t divider = 1;
2383 if (base::SysInfo::IsLowEndDevice())
2384 divider = 6;
2385 // For reference Nexus10 can upload 1MB in about 2.5ms.
2386 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2387 // Deadline to draw a frame to achieve 60 frames per second.
2388 const size_t kMillisecondsPerFrame = 16;
2389 // Assuming a two frame deep pipeline between the CPU and the GPU.
2390 size_t max_transfer_buffer_usage_mb =
2391 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2392 static const size_t kBytesPerMegabyte = 1024 * 1024;
2393 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2394 // to avoid unnecessarily stalling the compositor thread.
2395 limits.mapped_memory_reclaim_limit =
2396 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2397 #endif
2399 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2400 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2401 GetURLForGraphicsContext3D(),
2402 gpu_channel_host.get(),
2403 attributes,
2404 lose_context_when_out_of_memory,
2405 limits,
2406 NULL));
2407 return context.Pass();
2410 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2411 render_frame_proxies_.AddObserver(proxy);
2414 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2415 render_frame_proxies_.RemoveObserver(proxy);
2418 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2419 render_frames_.AddObserver(frame);
2422 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2423 render_frames_.RemoveObserver(frame);
2426 #if defined(VIDEO_HOLE)
2427 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2428 video_hole_frames_.AddObserver(frame);
2431 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2432 video_hole_frames_.RemoveObserver(frame);
2434 #endif // defined(VIDEO_HOLE)
2436 } // namespace content