cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob242f5a21561a3398651b6f78e6ef1fb59d10ee3c
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/debug/trace_event.h"
11 #include "base/debug/trace_event_synthetic_delay.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/singleton.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/stl_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/sys_info.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/WebRect.h"
59 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
60 #include "third_party/WebKit/public/platform/WebSize.h"
61 #include "third_party/WebKit/public/platform/WebString.h"
62 #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
63 #include "third_party/WebKit/public/web/WebPagePopup.h"
64 #include "third_party/WebKit/public/web/WebPopupMenu.h"
65 #include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
66 #include "third_party/WebKit/public/web/WebRange.h"
67 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
68 #include "third_party/skia/include/core/SkShader.h"
69 #include "ui/base/ui_base_switches.h"
70 #include "ui/gfx/frame_time.h"
71 #include "ui/gfx/point_conversions.h"
72 #include "ui/gfx/rect_conversions.h"
73 #include "ui/gfx/size_conversions.h"
74 #include "ui/gfx/skia_util.h"
75 #include "ui/gl/gl_switches.h"
76 #include "ui/surface/transport_dib.h"
78 #if defined(OS_ANDROID)
79 #include <android/keycodes.h>
80 #include "base/android/build_info.h"
81 #include "content/renderer/android/synchronous_compositor_factory.h"
82 #endif
84 #if defined(OS_POSIX)
85 #include "ipc/ipc_channel_posix.h"
86 #include "third_party/skia/include/core/SkMallocPixelRef.h"
87 #include "third_party/skia/include/core/SkPixelRef.h"
88 #endif // defined(OS_POSIX)
90 #include "third_party/WebKit/public/web/WebWidget.h"
92 using blink::WebCompositionUnderline;
93 using blink::WebCursorInfo;
94 using blink::WebDeviceEmulationParams;
95 using blink::WebGestureEvent;
96 using blink::WebInputEvent;
97 using blink::WebKeyboardEvent;
98 using blink::WebMouseEvent;
99 using blink::WebMouseWheelEvent;
100 using blink::WebNavigationPolicy;
101 using blink::WebPagePopup;
102 using blink::WebPopupMenu;
103 using blink::WebPopupMenuInfo;
104 using blink::WebPopupType;
105 using blink::WebRange;
106 using blink::WebRect;
107 using blink::WebScreenInfo;
108 using blink::WebSize;
109 using blink::WebTextDirection;
110 using blink::WebTouchEvent;
111 using blink::WebTouchPoint;
112 using blink::WebVector;
113 using blink::WebWidget;
115 namespace {
117 typedef std::map<std::string, ui::TextInputMode> TextInputModeMap;
119 class TextInputModeMapSingleton {
120 public:
121 static TextInputModeMapSingleton* GetInstance() {
122 return Singleton<TextInputModeMapSingleton>::get();
124 TextInputModeMapSingleton() {
125 map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM;
126 map_["latin"] = ui::TEXT_INPUT_MODE_LATIN;
127 map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME;
128 map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE;
129 map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN;
130 map_["kana"] = ui::TEXT_INPUT_MODE_KANA;
131 map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA;
132 map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC;
133 map_["tel"] = ui::TEXT_INPUT_MODE_TEL;
134 map_["email"] = ui::TEXT_INPUT_MODE_EMAIL;
135 map_["url"] = ui::TEXT_INPUT_MODE_URL;
137 const TextInputModeMap& map() const { return map_; }
138 private:
139 TextInputModeMap map_;
141 friend struct DefaultSingletonTraits<TextInputModeMapSingleton>;
143 DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton);
146 ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) {
147 static TextInputModeMapSingleton* singleton =
148 TextInputModeMapSingleton::GetInstance();
149 TextInputModeMap::const_iterator it =
150 singleton->map().find(input_mode.utf8());
151 if (it == singleton->map().end())
152 return ui::TEXT_INPUT_MODE_DEFAULT;
153 return it->second;
156 bool IsThreadedCompositingEnabled() {
157 content::RenderThreadImpl* impl = content::RenderThreadImpl::current();
158 return impl && !!impl->compositor_message_loop_proxy().get();
161 // TODO(brianderson): Replace the hard-coded threshold with a fraction of
162 // the BeginMainFrame interval.
163 // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to
164 // be spent in input hanlders before input starts getting throttled.
165 const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166;
167 } // namespace
169 namespace content {
171 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
173 class RenderWidget::ScreenMetricsEmulator {
174 public:
175 ScreenMetricsEmulator(
176 RenderWidget* widget,
177 const WebDeviceEmulationParams& params);
178 virtual ~ScreenMetricsEmulator();
180 // Scale and offset used to convert between host coordinates
181 // and webwidget coordinates.
182 float scale() { return scale_; }
183 gfx::Point offset() { return offset_; }
184 gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
185 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
186 const WebScreenInfo& original_screen_info() { return original_screen_info_; }
188 void ChangeEmulationParams(
189 const WebDeviceEmulationParams& params);
191 // The following methods alter handlers' behavior for messages related to
192 // widget size and position.
193 void OnResizeMessage(const ViewMsg_Resize_Params& params);
194 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
195 const gfx::Rect& window_screen_rect);
196 void OnShowContextMenu(ContextMenuParams* params);
197 gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
199 private:
200 void Reapply();
201 void Apply(float top_controls_layout_height,
202 gfx::Rect resizer_rect,
203 bool is_fullscreen);
205 RenderWidget* widget_;
207 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
208 WebDeviceEmulationParams params_;
210 // The computed scale and offset used to fit widget into browser window.
211 float scale_;
212 gfx::Point offset_;
214 // Widget rect as passed to webwidget.
215 gfx::Rect applied_widget_rect_;
217 // Original values to restore back after emulation ends.
218 gfx::Size original_size_;
219 gfx::Size original_physical_backing_size_;
220 gfx::Size original_visible_viewport_size_;
221 blink::WebScreenInfo original_screen_info_;
222 gfx::Rect original_view_screen_rect_;
223 gfx::Rect original_window_screen_rect_;
226 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
227 RenderWidget* widget,
228 const WebDeviceEmulationParams& params)
229 : widget_(widget),
230 params_(params),
231 scale_(1.f) {
232 original_size_ = widget_->size_;
233 original_physical_backing_size_ = widget_->physical_backing_size_;
234 original_visible_viewport_size_ = widget_->visible_viewport_size_;
235 original_screen_info_ = widget_->screen_info_;
236 original_view_screen_rect_ = widget_->view_screen_rect_;
237 original_window_screen_rect_ = widget_->window_screen_rect_;
238 Apply(widget_->top_controls_layout_height_, widget_->resizer_rect_,
239 widget_->is_fullscreen_);
242 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
243 widget_->screen_info_ = original_screen_info_;
245 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
246 widget_->SetScreenMetricsEmulationParameters(0.f, gfx::Point(), 1.f);
247 widget_->view_screen_rect_ = original_view_screen_rect_;
248 widget_->window_screen_rect_ = original_window_screen_rect_;
249 widget_->Resize(original_size_,
250 original_physical_backing_size_,
251 widget_->top_controls_layout_height_,
252 original_visible_viewport_size_,
253 widget_->resizer_rect_,
254 widget_->is_fullscreen_,
255 NO_RESIZE_ACK);
258 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
259 const WebDeviceEmulationParams& params) {
260 params_ = params;
261 Reapply();
264 void RenderWidget::ScreenMetricsEmulator::Reapply() {
265 Apply(widget_->top_controls_layout_height_, widget_->resizer_rect_,
266 widget_->is_fullscreen_);
269 void RenderWidget::ScreenMetricsEmulator::Apply(
270 float top_controls_layout_height,
271 gfx::Rect resizer_rect,
272 bool is_fullscreen) {
273 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
274 if (!applied_widget_rect_.width())
275 applied_widget_rect_.set_width(original_size_.width());
276 if (!applied_widget_rect_.height())
277 applied_widget_rect_.set_height(original_size_.height());
279 if (params_.fitToView && !original_size_.IsEmpty()) {
280 int original_width = std::max(original_size_.width(), 1);
281 int original_height = std::max(original_size_.height(), 1);
282 float width_ratio =
283 static_cast<float>(applied_widget_rect_.width()) / original_width;
284 float height_ratio =
285 static_cast<float>(applied_widget_rect_.height()) / original_height;
286 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
287 scale_ = 1.f / ratio;
289 // Center emulated view inside available view space.
290 offset_.set_x(
291 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
292 offset_.set_y(
293 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
294 } else {
295 scale_ = params_.scale;
296 offset_.SetPoint(params_.offset.x, params_.offset.y);
299 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
300 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
301 widget_->screen_info_.rect = original_screen_info_.rect;
302 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
303 widget_->window_screen_rect_ = original_window_screen_rect_;
304 } else {
305 applied_widget_rect_.set_origin(gfx::Point(0, 0));
306 widget_->screen_info_.rect = applied_widget_rect_;
307 widget_->screen_info_.availableRect = applied_widget_rect_;
308 widget_->window_screen_rect_ = applied_widget_rect_;
311 float applied_device_scale_factor = params_.deviceScaleFactor ?
312 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
313 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
315 // Pass three emulation parameters to the blink side:
316 // - we keep the real device scale factor in compositor to produce sharp image
317 // even when emulating different scale factor;
318 // - in order to fit into view, WebView applies offset and scale to the
319 // root layer.
320 widget_->SetScreenMetricsEmulationParameters(
321 original_screen_info_.deviceScaleFactor, offset_, scale_);
323 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
324 widget_->view_screen_rect_ = applied_widget_rect_;
326 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
327 original_size_, original_screen_info_.deviceScaleFactor));
328 widget_->Resize(applied_widget_rect_.size(), physical_backing_size,
329 top_controls_layout_height, applied_widget_rect_.size(), resizer_rect,
330 is_fullscreen, NO_RESIZE_ACK);
333 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
334 const ViewMsg_Resize_Params& params) {
335 bool need_ack = params.new_size != original_size_ &&
336 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
337 original_size_ = params.new_size;
338 original_physical_backing_size_ = params.physical_backing_size;
339 original_screen_info_ = params.screen_info;
340 original_visible_viewport_size_ = params.visible_viewport_size;
341 Apply(params.top_controls_layout_height, params.resizer_rect,
342 params.is_fullscreen);
344 if (need_ack) {
345 widget_->set_next_paint_is_resize_ack();
346 if (widget_->compositor_)
347 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
351 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
352 const gfx::Rect& view_screen_rect,
353 const gfx::Rect& window_screen_rect) {
354 original_view_screen_rect_ = view_screen_rect;
355 original_window_screen_rect_ = window_screen_rect;
356 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
357 Reapply();
360 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
361 ContextMenuParams* params) {
362 params->x *= scale_;
363 params->x += offset_.x();
364 params->y *= scale_;
365 params->y += offset_.y();
368 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
369 const gfx::Rect& anchor) {
370 gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
371 scaled.set_x(scaled.x() + offset_.x());
372 scaled.set_y(scaled.y() + offset_.y());
373 return scaled;
376 // RenderWidget ---------------------------------------------------------------
378 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
379 const blink::WebScreenInfo& screen_info,
380 bool swapped_out,
381 bool hidden,
382 bool never_visible)
383 : routing_id_(MSG_ROUTING_NONE),
384 surface_id_(0),
385 webwidget_(NULL),
386 opener_id_(MSG_ROUTING_NONE),
387 init_complete_(false),
388 top_controls_layout_height_(0.f),
389 next_paint_flags_(0),
390 auto_resize_mode_(false),
391 need_update_rect_for_auto_resize_(false),
392 did_show_(false),
393 is_hidden_(hidden),
394 never_visible_(never_visible),
395 is_fullscreen_(false),
396 has_focus_(false),
397 handling_input_event_(false),
398 handling_ime_event_(false),
399 handling_event_type_(WebInputEvent::Undefined),
400 ignore_ack_for_mouse_move_from_debugger_(false),
401 closing_(false),
402 host_closing_(false),
403 is_swapped_out_(swapped_out),
404 input_method_is_active_(false),
405 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
406 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
407 text_input_flags_(0),
408 can_compose_inline_(true),
409 popup_type_(popup_type),
410 pending_window_rect_count_(0),
411 suppress_next_char_events_(false),
412 screen_info_(screen_info),
413 device_scale_factor_(screen_info_.deviceScaleFactor),
414 current_event_latency_info_(NULL),
415 next_output_surface_id_(0),
416 #if defined(OS_ANDROID)
417 text_field_is_dirty_(false),
418 outstanding_ime_acks_(0),
419 body_background_color_(SK_ColorWHITE),
420 #endif
421 popup_origin_scale_for_emulation_(0.f),
422 frame_swap_message_queue_(new FrameSwapMessageQueue()),
423 resizing_mode_selector_(new ResizingModeSelector()),
424 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
425 has_host_context_menu_location_(false) {
426 if (!swapped_out)
427 RenderProcess::current()->AddRefProcess();
428 DCHECK(RenderThread::Get());
429 device_color_profile_.push_back('0');
432 RenderWidget::~RenderWidget() {
433 DCHECK(!webwidget_) << "Leaking our WebWidget!";
435 // If we are swapped out, we have released already.
436 if (!is_swapped_out_ && RenderProcess::current())
437 RenderProcess::current()->ReleaseProcess();
440 // static
441 RenderWidget* RenderWidget::Create(int32 opener_id,
442 blink::WebPopupType popup_type,
443 const blink::WebScreenInfo& screen_info) {
444 DCHECK(opener_id != MSG_ROUTING_NONE);
445 scoped_refptr<RenderWidget> widget(
446 new RenderWidget(popup_type, screen_info, false, false, false));
447 if (widget->Init(opener_id)) { // adds reference on success.
448 return widget.get();
450 return NULL;
453 // static
454 WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
455 switch (render_widget->popup_type_) {
456 case blink::WebPopupTypeNone: // Nothing to create.
457 break;
458 case blink::WebPopupTypeSelect:
459 case blink::WebPopupTypeSuggestion:
460 return WebPopupMenu::create(render_widget);
461 case blink::WebPopupTypePage:
462 return WebPagePopup::create(render_widget);
463 default:
464 NOTREACHED();
466 return NULL;
469 bool RenderWidget::Init(int32 opener_id) {
470 return DoInit(opener_id,
471 RenderWidget::CreateWebWidget(this),
472 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
473 &routing_id_, &surface_id_));
476 bool RenderWidget::DoInit(int32 opener_id,
477 WebWidget* web_widget,
478 IPC::SyncMessage* create_widget_message) {
479 DCHECK(!webwidget_);
481 if (opener_id != MSG_ROUTING_NONE)
482 opener_id_ = opener_id;
484 webwidget_ = web_widget;
486 bool result = RenderThread::Get()->Send(create_widget_message);
487 if (result) {
488 RenderThread::Get()->AddRoute(routing_id_, this);
489 // Take a reference on behalf of the RenderThread. This will be balanced
490 // when we receive ViewMsg_Close.
491 AddRef();
492 if (RenderThreadImpl::current()) {
493 RenderThreadImpl::current()->WidgetCreated();
494 if (is_hidden_)
495 RenderThreadImpl::current()->WidgetHidden();
497 return true;
498 } else {
499 // The above Send can fail when the tab is closing.
500 return false;
504 // This is used to complete pending inits and non-pending inits.
505 void RenderWidget::CompleteInit() {
506 DCHECK(routing_id_ != MSG_ROUTING_NONE);
508 init_complete_ = true;
510 if (compositor_)
511 StartCompositor();
513 Send(new ViewHostMsg_RenderViewReady(routing_id_));
516 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
517 // We should only toggle between states.
518 DCHECK(is_swapped_out_ != is_swapped_out);
519 is_swapped_out_ = is_swapped_out;
521 // If we are swapping out, we will call ReleaseProcess, allowing the process
522 // to exit if all of its RenderViews are swapped out. We wait until the
523 // WasSwappedOut call to do this, to allow the unload handler to finish.
524 // If we are swapping in, we call AddRefProcess to prevent the process from
525 // exiting.
526 if (!is_swapped_out_)
527 RenderProcess::current()->AddRefProcess();
530 void RenderWidget::WasSwappedOut() {
531 // If we have been swapped out and no one else is using this process,
532 // it's safe to exit now.
533 CHECK(is_swapped_out_);
534 RenderProcess::current()->ReleaseProcess();
537 void RenderWidget::EnableScreenMetricsEmulation(
538 const WebDeviceEmulationParams& params) {
539 if (!screen_metrics_emulator_)
540 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
541 else
542 screen_metrics_emulator_->ChangeEmulationParams(params);
545 void RenderWidget::DisableScreenMetricsEmulation() {
546 screen_metrics_emulator_.reset();
549 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
550 ScreenMetricsEmulator* emulator) {
551 popup_origin_scale_for_emulation_ = emulator->scale();
552 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
553 popup_screen_origin_for_emulation_ = gfx::Point(
554 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
555 emulator->original_screen_rect().origin().y() + emulator->offset().y());
556 screen_info_ = emulator->original_screen_info();
557 device_scale_factor_ = screen_info_.deviceScaleFactor;
560 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
561 if (screen_metrics_emulator_)
562 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
563 return anchor;
566 void RenderWidget::SetScreenMetricsEmulationParameters(
567 float device_scale_factor,
568 const gfx::Point& root_layer_offset,
569 float root_layer_scale) {
570 // This is only supported in RenderView.
571 NOTREACHED();
574 #if defined(OS_MACOSX) || defined(OS_ANDROID)
575 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
576 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
577 popup->SetOriginScaleAndOffsetForEmulation(
578 emulator->scale(), emulator->offset());
580 #endif
582 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
583 if (screen_metrics_emulator_)
584 screen_metrics_emulator_->OnShowContextMenu(params);
587 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
588 if (compositor_) {
589 // Regardless of whether threaded compositing is enabled, always
590 // use this mechanism to force the compositor to redraw. However,
591 // the invalidation code path below is still needed for the
592 // non-threaded case.
593 compositor_->SetNeedsForcedRedraw();
595 scheduleComposite();
598 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
599 bool handled = true;
600 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
601 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
602 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
603 OnCursorVisibilityChange)
604 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
605 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
606 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
607 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
608 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
609 OnSyntheticGestureCompleted)
610 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
611 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
612 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
613 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
614 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
615 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
616 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
617 IPC_MESSAGE_HANDLER(ViewMsg_SetInputMethodActive, OnSetInputMethodActive)
618 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowShown, OnCandidateWindowShown)
619 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowUpdated,
620 OnCandidateWindowUpdated)
621 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowHidden, OnCandidateWindowHidden)
622 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
623 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
624 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
625 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
626 #if defined(OS_ANDROID)
627 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
628 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
629 #endif
630 IPC_MESSAGE_UNHANDLED(handled = false)
631 IPC_END_MESSAGE_MAP()
632 return handled;
635 bool RenderWidget::Send(IPC::Message* message) {
636 // Don't send any messages after the browser has told us to close, and filter
637 // most outgoing messages while swapped out.
638 if ((is_swapped_out_ &&
639 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
640 closing_) {
641 delete message;
642 return false;
645 // If given a messsage without a routing ID, then assign our routing ID.
646 if (message->routing_id() == MSG_ROUTING_NONE)
647 message->set_routing_id(routing_id_);
649 return RenderThread::Get()->Send(message);
652 void RenderWidget::Resize(const gfx::Size& new_size,
653 const gfx::Size& physical_backing_size,
654 float top_controls_layout_height,
655 const gfx::Size& visible_viewport_size,
656 const gfx::Rect& resizer_rect,
657 bool is_fullscreen,
658 ResizeAck resize_ack) {
659 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
660 // A resize ack shouldn't be requested if we have not ACK'd the previous
661 // one.
662 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
663 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
666 // Ignore this during shutdown.
667 if (!webwidget_)
668 return;
670 if (compositor_) {
671 compositor_->setViewportSize(new_size, physical_backing_size);
672 compositor_->SetTopControlsLayoutHeight(top_controls_layout_height);
675 physical_backing_size_ = physical_backing_size;
676 top_controls_layout_height_ = top_controls_layout_height;
677 visible_viewport_size_ = visible_viewport_size;
678 resizer_rect_ = resizer_rect;
680 // NOTE: We may have entered fullscreen mode without changing our size.
681 bool fullscreen_change = is_fullscreen_ != is_fullscreen;
682 if (fullscreen_change)
683 WillToggleFullscreen();
684 is_fullscreen_ = is_fullscreen;
686 webwidget_->setTopControlsLayoutHeight(top_controls_layout_height);
688 if (size_ != new_size) {
689 size_ = new_size;
691 // When resizing, we want to wait to paint before ACK'ing the resize. This
692 // ensures that we only resize as fast as we can paint. We only need to
693 // send an ACK if we are resized to a non-empty rect.
694 webwidget_->resize(new_size);
695 } else if (!resizing_mode_selector_->is_synchronous_mode()) {
696 resize_ack = NO_RESIZE_ACK;
699 webwidget()->resizePinchViewport(gfx::Size(
700 visible_viewport_size.width(),
701 visible_viewport_size.height()));
703 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
704 // For empty size or empty physical_backing_size, there is no next paint
705 // (along with which to send the ack) until they are set to non-empty.
706 resize_ack = NO_RESIZE_ACK;
709 // Send the Resize_ACK flag once we paint again if requested.
710 if (resize_ack == SEND_RESIZE_ACK)
711 set_next_paint_is_resize_ack();
713 if (fullscreen_change)
714 DidToggleFullscreen();
716 // If a resize ack is requested and it isn't set-up, then no more resizes will
717 // come in and in general things will go wrong.
718 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
721 void RenderWidget::ResizeSynchronously(const gfx::Rect& new_position) {
722 Resize(new_position.size(),
723 new_position.size(),
724 top_controls_layout_height_,
725 visible_viewport_size_,
726 gfx::Rect(),
727 is_fullscreen_,
728 NO_RESIZE_ACK);
729 view_screen_rect_ = new_position;
730 window_screen_rect_ = new_position;
731 if (!did_show_)
732 initial_pos_ = new_position;
735 void RenderWidget::OnClose() {
736 if (closing_)
737 return;
738 closing_ = true;
740 // Browser correspondence is no longer needed at this point.
741 if (routing_id_ != MSG_ROUTING_NONE) {
742 if (RenderThreadImpl::current())
743 RenderThreadImpl::current()->WidgetDestroyed();
744 RenderThread::Get()->RemoveRoute(routing_id_);
745 SetHidden(false);
748 // If there is a Send call on the stack, then it could be dangerous to close
749 // now. Post a task that only gets invoked when there are no nested message
750 // loops.
751 base::MessageLoop::current()->PostNonNestableTask(
752 FROM_HERE, base::Bind(&RenderWidget::Close, this));
754 // Balances the AddRef taken when we called AddRoute.
755 Release();
758 // Got a response from the browser after the renderer decided to create a new
759 // view.
760 void RenderWidget::OnCreatingNewAck() {
761 DCHECK(routing_id_ != MSG_ROUTING_NONE);
763 CompleteInit();
766 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
767 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
768 return;
770 if (screen_metrics_emulator_) {
771 screen_metrics_emulator_->OnResizeMessage(params);
772 return;
775 bool orientation_changed =
776 screen_info_.orientationAngle != params.screen_info.orientationAngle;
778 screen_info_ = params.screen_info;
779 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
780 Resize(params.new_size, params.physical_backing_size,
781 params.top_controls_layout_height,
782 params.visible_viewport_size, params.resizer_rect,
783 params.is_fullscreen, SEND_RESIZE_ACK);
785 if (orientation_changed)
786 OnOrientationChange();
789 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
790 SetDeviceColorProfile(color_profile);
793 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
794 if (resizer_rect_ == resizer_rect)
795 return;
796 resizer_rect_ = resizer_rect;
797 if (webwidget_)
798 webwidget_->didChangeWindowResizerRect();
801 void RenderWidget::OnWasHidden() {
802 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
803 // Go into a mode where we stop generating paint and scrolling events.
804 SetHidden(true);
805 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
806 WasHidden());
809 void RenderWidget::OnWasShown(bool needs_repainting,
810 const ui::LatencyInfo& latency_info) {
811 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
812 // During shutdown we can just ignore this message.
813 if (!webwidget_)
814 return;
816 // See OnWasHidden
817 SetHidden(false);
818 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
819 WasShown());
821 if (!needs_repainting)
822 return;
824 // Generate a full repaint.
825 if (compositor_) {
826 ui::LatencyInfo swap_latency_info(latency_info);
827 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
828 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
829 compositor_->SetNeedsForcedRedraw();
831 scheduleComposite();
834 void RenderWidget::OnRequestMoveAck() {
835 DCHECK(pending_window_rect_count_);
836 pending_window_rect_count_--;
839 GURL RenderWidget::GetURLForGraphicsContext3D() {
840 return GURL();
843 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
844 // For widgets that are never visible, we don't start the compositor, so we
845 // never get a request for a cc::OutputSurface.
846 DCHECK(!never_visible_);
848 #if defined(OS_ANDROID)
849 if (SynchronousCompositorFactory* factory =
850 SynchronousCompositorFactory::GetInstance()) {
851 return factory->CreateOutputSurface(routing_id(),
852 frame_swap_message_queue_);
854 #endif
856 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
857 bool use_software = fallback;
858 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
859 use_software = true;
861 scoped_refptr<ContextProviderCommandBuffer> context_provider;
862 if (!use_software) {
863 context_provider = ContextProviderCommandBuffer::Create(
864 CreateGraphicsContext3D(), "RenderCompositor");
865 if (!context_provider.get()) {
866 // Cause the compositor to wait and try again.
867 return scoped_ptr<cc::OutputSurface>();
871 uint32 output_surface_id = next_output_surface_id_++;
872 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
873 DCHECK(IsThreadedCompositingEnabled());
874 return scoped_ptr<cc::OutputSurface>(
875 new DelegatedCompositorOutputSurface(routing_id(),
876 output_surface_id,
877 context_provider,
878 frame_swap_message_queue_));
880 if (!context_provider.get()) {
881 scoped_ptr<cc::SoftwareOutputDevice> software_device(
882 new CompositorSoftwareOutputDevice());
884 return scoped_ptr<cc::OutputSurface>(
885 new CompositorOutputSurface(routing_id(),
886 output_surface_id,
887 NULL,
888 software_device.Pass(),
889 frame_swap_message_queue_,
890 true));
893 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
894 // Composite-to-mailbox is currently used for layout tests in order to cause
895 // them to draw inside in the renderer to do the readback there. This should
896 // no longer be the case when crbug.com/311404 is fixed.
897 DCHECK(IsThreadedCompositingEnabled() ||
898 RenderThreadImpl::current()->layout_test_mode());
899 cc::ResourceFormat format = cc::RGBA_8888;
900 if (base::SysInfo::IsLowEndDevice())
901 format = cc::RGB_565;
902 return scoped_ptr<cc::OutputSurface>(
903 new MailboxOutputSurface(routing_id(),
904 output_surface_id,
905 context_provider,
906 scoped_ptr<cc::SoftwareOutputDevice>(),
907 frame_swap_message_queue_,
908 format));
910 bool use_swap_compositor_frame_message = false;
911 return scoped_ptr<cc::OutputSurface>(
912 new CompositorOutputSurface(routing_id(),
913 output_surface_id,
914 context_provider,
915 scoped_ptr<cc::SoftwareOutputDevice>(),
916 frame_swap_message_queue_,
917 use_swap_compositor_frame_message));
920 void RenderWidget::OnSwapBuffersAborted() {
921 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
922 // Schedule another frame so the compositor learns about it.
923 scheduleComposite();
926 void RenderWidget::OnSwapBuffersPosted() {
927 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
930 void RenderWidget::OnSwapBuffersComplete() {
931 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
933 // Notify subclasses that composited rendering was flushed to the screen.
934 DidFlushPaint();
937 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
938 const ui::LatencyInfo& latency_info,
939 bool is_keyboard_shortcut) {
940 base::AutoReset<bool> handling_input_event_resetter(
941 &handling_input_event_, true);
942 if (!input_event)
943 return;
944 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
945 &handling_event_type_, input_event->type);
946 #if defined(OS_ANDROID)
947 // On Android, when a key is pressed or sent from the Keyboard using IME,
948 // |AdapterInputConnection| generates input key events to make sure all JS
949 // listeners that monitor KeyUp and KeyDown events receive the proper key
950 // code. Since this input key event comes from IME, we need to set the
951 // IME event guard here to make sure it does not interfere with other IME
952 // events.
953 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
954 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
955 const WebKeyboardEvent& key_event =
956 *static_cast<const WebKeyboardEvent*>(input_event);
957 // Some keys are special and it's essential that no events get blocked.
958 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
959 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER)
960 ime_event_guard_maybe.reset(new ImeEventGuard(this));
962 #endif
964 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
965 &latency_info);
967 base::TimeTicks start_time;
968 if (base::TimeTicks::IsHighResNowFastAndReliable())
969 start_time = base::TimeTicks::HighResNow();
971 const char* const event_name =
972 WebInputEventTraits::GetName(input_event->type);
973 TRACE_EVENT1("renderer", "RenderWidget::OnHandleInputEvent",
974 "event", event_name);
975 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
976 TRACE_EVENT_FLOW_STEP0(
977 "input",
978 "LatencyInfo.Flow",
979 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
980 "HanldeInputEventMain");
982 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
983 ui::LatencyInfo swap_latency_info(latency_info);
984 if (compositor_) {
985 latency_info_swap_promise_monitor =
986 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
987 .Pass();
990 if (base::TimeTicks::IsHighResNowFastAndReliable()) {
991 // If we don't have a high res timer, these metrics won't be accurate enough
992 // to be worth collecting. Note that this does introduce some sampling bias.
994 base::TimeDelta now = base::TimeDelta::FromInternalValue(
995 base::TimeTicks::HighResNow().ToInternalValue());
997 int64 delta =
998 static_cast<int64>((now.InSecondsF() - input_event->timeStampSeconds) *
999 base::Time::kMicrosecondsPerSecond);
1001 UMA_HISTOGRAM_CUSTOM_COUNTS(
1002 "Event.AggregatedLatency.Renderer2", delta, 1, 10000000, 100);
1003 base::HistogramBase* counter_for_type = base::Histogram::FactoryGet(
1004 base::StringPrintf("Event.Latency.Renderer2.%s", event_name),
1006 10000000,
1007 100,
1008 base::HistogramBase::kUmaTargetedHistogramFlag);
1009 counter_for_type->Add(delta);
1012 bool prevent_default = false;
1013 if (WebInputEvent::isMouseEventType(input_event->type)) {
1014 const WebMouseEvent& mouse_event =
1015 *static_cast<const WebMouseEvent*>(input_event);
1016 TRACE_EVENT2("renderer", "HandleMouseMove",
1017 "x", mouse_event.x, "y", mouse_event.y);
1018 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1019 prevent_default = WillHandleMouseEvent(mouse_event);
1022 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1023 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1024 #if defined(OS_ANDROID)
1025 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1026 // case it should behave like a select key (i.e. causing a click if a button
1027 // is focused). However, if a text field is focused (2), its intended
1028 // behavior is to just show the IME and don't propagate the key.
1029 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1030 // when clicked on an input text field and cause the form submit if clicked
1031 // when the submit button is focused, but not vice-versa.
1032 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1033 // but at this point we have to swallow the event for the scenario (2).
1034 const WebKeyboardEvent& key_event =
1035 *static_cast<const WebKeyboardEvent*>(input_event);
1036 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1037 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1038 OnShowImeIfNeeded();
1039 prevent_default = true;
1041 #endif
1044 if (WebInputEvent::isGestureEventType(input_event->type)) {
1045 const WebGestureEvent& gesture_event =
1046 *static_cast<const WebGestureEvent*>(input_event);
1047 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1048 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1051 bool processed = prevent_default;
1052 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1053 suppress_next_char_events_ = false;
1054 if (!processed && webwidget_)
1055 processed = webwidget_->handleInputEvent(*input_event);
1058 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1059 // it's not processed by webkit, then we need to suppress the upcoming Char
1060 // events.
1061 if (!processed && is_keyboard_shortcut)
1062 suppress_next_char_events_ = true;
1064 InputEventAckState ack_result = processed ?
1065 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1066 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1067 const WebTouchEvent& touch_event =
1068 *static_cast<const WebTouchEvent*>(input_event);
1069 // Hit-test for all the pressed touch points. If there is a touch-handler
1070 // for any of the touch points, then the renderer should continue to receive
1071 // touch events.
1072 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1073 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1074 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1075 HasTouchEventHandlersAt(
1076 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1077 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1078 break;
1083 bool event_type_can_be_rate_limited =
1084 input_event->type == WebInputEvent::MouseMove ||
1085 input_event->type == WebInputEvent::MouseWheel;
1087 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1089 // If we don't have a fast and accurate HighResNow, we assume the input
1090 // handlers are heavy and rate limit them.
1091 bool rate_limiting_wanted = true;
1092 if (base::TimeTicks::IsHighResNowFastAndReliable()) {
1093 base::TimeTicks end_time = base::TimeTicks::HighResNow();
1094 total_input_handling_time_this_frame_ += (end_time - start_time);
1095 rate_limiting_wanted =
1096 total_input_handling_time_this_frame_.InMicroseconds() >
1097 kInputHandlingTimeThrottlingThresholdMicroseconds;
1100 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1102 // Note that we can't use handling_event_type_ here since it will be overriden
1103 // by reentrant calls for events after the paused one.
1104 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1105 input_event->type == WebInputEvent::MouseMove;
1106 if (!WebInputEventTraits::IgnoresAckDisposition(*input_event) && !no_ack) {
1107 InputHostMsg_HandleInputEvent_ACK_Params ack;
1108 ack.type = input_event->type;
1109 ack.state = ack_result;
1110 ack.latency = swap_latency_info;
1111 scoped_ptr<IPC::Message> response(
1112 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1113 if (rate_limiting_wanted && event_type_can_be_rate_limited &&
1114 frame_pending && !is_hidden_) {
1115 // We want to rate limit the input events in this case, so we'll wait for
1116 // painting to finish before ACKing this message.
1117 TRACE_EVENT_INSTANT0("renderer",
1118 "RenderWidget::OnHandleInputEvent ack throttled",
1119 TRACE_EVENT_SCOPE_THREAD);
1120 if (pending_input_event_ack_) {
1121 // As two different kinds of events could cause us to postpone an ack
1122 // we send it now, if we have one pending. The Browser should never
1123 // send us the same kind of event we are delaying the ack for.
1124 Send(pending_input_event_ack_.release());
1126 pending_input_event_ack_ = response.Pass();
1127 if (compositor_)
1128 compositor_->NotifyInputThrottledUntilCommit();
1129 } else {
1130 Send(response.release());
1133 if (input_event->type == WebInputEvent::MouseMove)
1134 ignore_ack_for_mouse_move_from_debugger_ = false;
1136 #if defined(OS_ANDROID)
1137 // Allow the IME to be shown when the focus changes as a consequence
1138 // of a processed touch end event.
1139 if (input_event->type == WebInputEvent::TouchEnd && processed)
1140 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1141 #elif defined(USE_AURA)
1142 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1143 // change.
1144 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1145 input_event->type == WebInputEvent::MouseUp))
1146 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1147 #endif
1149 if (!prevent_default) {
1150 if (WebInputEvent::isKeyboardEventType(input_event->type))
1151 DidHandleKeyEvent();
1152 if (WebInputEvent::isMouseEventType(input_event->type))
1153 DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1154 if (WebInputEvent::isTouchEventType(input_event->type))
1155 DidHandleTouchEvent(*(static_cast<const WebTouchEvent*>(input_event)));
1159 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1160 if (webwidget_)
1161 webwidget_->setCursorVisibilityState(is_visible);
1164 void RenderWidget::OnMouseCaptureLost() {
1165 if (webwidget_)
1166 webwidget_->mouseCaptureLost();
1169 void RenderWidget::OnSetFocus(bool enable) {
1170 has_focus_ = enable;
1171 if (webwidget_)
1172 webwidget_->setFocus(enable);
1175 void RenderWidget::ClearFocus() {
1176 // We may have got the focus from the browser before this gets processed, in
1177 // which case we do not want to unfocus ourself.
1178 if (!has_focus_ && webwidget_)
1179 webwidget_->setFocus(false);
1182 void RenderWidget::FlushPendingInputEventAck() {
1183 if (pending_input_event_ack_)
1184 Send(pending_input_event_ack_.release());
1185 total_input_handling_time_this_frame_ = base::TimeDelta();
1188 ///////////////////////////////////////////////////////////////////////////////
1189 // WebWidgetClient
1191 void RenderWidget::didAutoResize(const WebSize& new_size) {
1192 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1193 size_ = new_size;
1195 if (resizing_mode_selector_->is_synchronous_mode()) {
1196 WebRect new_pos(rootWindowRect().x,
1197 rootWindowRect().y,
1198 new_size.width,
1199 new_size.height);
1200 view_screen_rect_ = new_pos;
1201 window_screen_rect_ = new_pos;
1204 AutoResizeCompositor();
1206 if (!resizing_mode_selector_->is_synchronous_mode())
1207 need_update_rect_for_auto_resize_ = true;
1211 void RenderWidget::AutoResizeCompositor() {
1212 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1213 device_scale_factor_));
1214 if (compositor_)
1215 compositor_->setViewportSize(size_, physical_backing_size_);
1218 void RenderWidget::initializeLayerTreeView() {
1219 DCHECK(!host_closing_);
1221 compositor_ =
1222 RenderWidgetCompositor::Create(this, IsThreadedCompositingEnabled());
1223 compositor_->setViewportSize(size_, physical_backing_size_);
1224 if (init_complete_)
1225 StartCompositor();
1228 void RenderWidget::DestroyLayerTreeView() {
1229 // Always send this notification to prevent new layer tree views from
1230 // being created, even if one hasn't been created yet.
1231 if (webwidget_)
1232 webwidget_->willCloseLayerTreeView();
1233 compositor_.reset();
1236 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1237 return compositor_.get();
1240 void RenderWidget::willBeginCompositorFrame() {
1241 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1243 // The following two can result in further layout and possibly
1244 // enable GPU acceleration so they need to be called before any painting
1245 // is done.
1246 UpdateTextInputType();
1247 #if defined(OS_ANDROID)
1248 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1249 #endif
1250 UpdateSelectionBounds();
1253 void RenderWidget::didBecomeReadyForAdditionalInput() {
1254 TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1255 FlushPendingInputEventAck();
1258 void RenderWidget::DidCommitCompositorFrame() {
1259 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1260 DidCommitCompositorFrame());
1261 #if defined(VIDEO_HOLE)
1262 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1263 DidCommitCompositorFrame());
1264 #endif // defined(VIDEO_HOLE)
1267 // static
1268 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1269 IPC::Message* msg,
1270 MessageDeliveryPolicy policy,
1271 FrameSwapMessageQueue* frame_swap_message_queue,
1272 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1273 bool commit_requested,
1274 int source_frame_number) {
1275 if (policy == MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE &&
1276 // No need for lock: this gets changed only on this thread.
1277 !commit_requested &&
1278 // No need for lock: Messages are only enqueued from this thread, if we
1279 // don't have any now, no other thread will add any.
1280 frame_swap_message_queue->Empty()) {
1281 sync_message_filter->Send(msg);
1282 return nullptr;
1285 bool first_message_for_frame = false;
1286 frame_swap_message_queue->QueueMessageForFrame(policy,
1287 source_frame_number,
1288 make_scoped_ptr(msg),
1289 &first_message_for_frame);
1290 if (first_message_for_frame) {
1291 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1292 sync_message_filter, frame_swap_message_queue, source_frame_number));
1293 return promise;
1295 return nullptr;
1298 void RenderWidget::QueueMessage(IPC::Message* msg,
1299 MessageDeliveryPolicy policy) {
1300 // RenderThreadImpl::current() is NULL in some tests.
1301 if (!compositor_ || !RenderThreadImpl::current()) {
1302 Send(msg);
1303 return;
1306 scoped_ptr<cc::SwapPromise> swap_promise =
1307 QueueMessageImpl(msg,
1308 policy,
1309 frame_swap_message_queue_.get(),
1310 RenderThreadImpl::current()->sync_message_filter(),
1311 compositor_->commitRequested(),
1312 compositor_->GetSourceFrameNumber());
1314 if (swap_promise) {
1315 compositor_->QueueSwapPromise(swap_promise.Pass());
1316 compositor_->SetNeedsCommit();
1320 void RenderWidget::didCommitAndDrawCompositorFrame() {
1321 // NOTE: Tests may break if this event is renamed or moved. See
1322 // tab_capture_performancetest.cc.
1323 TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1324 // Notify subclasses that we initiated the paint operation.
1325 DidInitiatePaint();
1328 void RenderWidget::didCompleteSwapBuffers() {
1329 TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
1331 // Notify subclasses threaded composited rendering was flushed to the screen.
1332 DidFlushPaint();
1334 if (!next_paint_flags_ &&
1335 !need_update_rect_for_auto_resize_ &&
1336 !plugin_window_moves_.size()) {
1337 return;
1340 ViewHostMsg_UpdateRect_Params params;
1341 params.view_size = size_;
1342 params.plugin_window_moves.swap(plugin_window_moves_);
1343 params.flags = next_paint_flags_;
1345 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1346 next_paint_flags_ = 0;
1347 need_update_rect_for_auto_resize_ = false;
1350 void RenderWidget::scheduleComposite() {
1351 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1352 // render_thread may be NULL in tests.
1353 if (render_thread && render_thread->compositor_message_loop_proxy().get() &&
1354 compositor_) {
1355 compositor_->setNeedsAnimate();
1359 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1360 // TODO(darin): Eliminate this temporary.
1361 WebCursor cursor;
1362 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1363 // Only send a SetCursor message if we need to make a change.
1364 if (!current_cursor_.IsEqual(cursor)) {
1365 current_cursor_ = cursor;
1366 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1370 // We are supposed to get a single call to Show for a newly created RenderWidget
1371 // that was created via RenderWidget::CreateWebView. So, we wait until this
1372 // point to dispatch the ShowWidget message.
1374 // This method provides us with the information about how to display the newly
1375 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1377 void RenderWidget::show(WebNavigationPolicy) {
1378 DCHECK(!did_show_) << "received extraneous Show call";
1379 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1380 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1382 if (did_show_)
1383 return;
1385 did_show_ = true;
1386 // NOTE: initial_pos_ may still have its default values at this point, but
1387 // that's okay. It'll be ignored if as_popup is false, or the browser
1388 // process will impose a default position otherwise.
1389 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_pos_));
1390 SetPendingWindowRect(initial_pos_);
1393 void RenderWidget::didFocus() {
1396 void RenderWidget::didBlur() {
1399 void RenderWidget::DoDeferredClose() {
1400 // No more compositing is possible. This prevents shutdown races between
1401 // previously posted CreateOutputSurface tasks and the host being unable to
1402 // create them because the close message was handled.
1403 DestroyLayerTreeView();
1404 // Also prevent new compositors from being created.
1405 host_closing_ = true;
1406 Send(new ViewHostMsg_Close(routing_id_));
1409 void RenderWidget::closeWidgetSoon() {
1410 if (is_swapped_out_) {
1411 // This widget is currently swapped out, and the active widget is in a
1412 // different process. Have the browser route the close request to the
1413 // active widget instead, so that the correct unload handlers are run.
1414 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1415 return;
1418 // If a page calls window.close() twice, we'll end up here twice, but that's
1419 // OK. It is safe to send multiple Close messages.
1421 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1422 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1423 // could be closed before the JS finishes executing. So instead, post a
1424 // message back to the message loop, which won't run until the JS is
1425 // complete, and then the Close message can be sent.
1426 base::MessageLoop::current()->PostNonNestableTask(
1427 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1430 void RenderWidget::QueueSyntheticGesture(
1431 scoped_ptr<SyntheticGestureParams> gesture_params,
1432 const SyntheticGestureCompletionCallback& callback) {
1433 DCHECK(!callback.is_null());
1435 pending_synthetic_gesture_callbacks_.push(callback);
1437 SyntheticGesturePacket gesture_packet;
1438 gesture_packet.set_gesture_params(gesture_params.Pass());
1440 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1443 void RenderWidget::Close() {
1444 screen_metrics_emulator_.reset();
1445 DestroyLayerTreeView();
1446 if (webwidget_) {
1447 webwidget_->close();
1448 webwidget_ = NULL;
1452 WebRect RenderWidget::windowRect() {
1453 if (pending_window_rect_count_)
1454 return pending_window_rect_;
1456 return view_screen_rect_;
1459 void RenderWidget::setToolTipText(const blink::WebString& text,
1460 WebTextDirection hint) {
1461 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1464 void RenderWidget::setWindowRect(const WebRect& rect) {
1465 WebRect pos = rect;
1466 if (popup_origin_scale_for_emulation_) {
1467 float scale = popup_origin_scale_for_emulation_;
1468 pos.x = popup_screen_origin_for_emulation_.x() +
1469 (pos.x - popup_view_origin_for_emulation_.x()) * scale;
1470 pos.y = popup_screen_origin_for_emulation_.y() +
1471 (pos.y - popup_view_origin_for_emulation_.y()) * scale;
1474 if (!resizing_mode_selector_->is_synchronous_mode()) {
1475 if (did_show_) {
1476 Send(new ViewHostMsg_RequestMove(routing_id_, pos));
1477 SetPendingWindowRect(pos);
1478 } else {
1479 initial_pos_ = pos;
1481 } else {
1482 ResizeSynchronously(pos);
1486 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1487 pending_window_rect_ = rect;
1488 pending_window_rect_count_++;
1491 WebRect RenderWidget::rootWindowRect() {
1492 if (pending_window_rect_count_) {
1493 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1494 // the RootWindowRect is probably going to return wrong results since the
1495 // browser may not have processed the Move yet. There isn't really anything
1496 // good to do in this case, and it shouldn't happen - since this size is
1497 // only really needed for windowToScreen, which is only used for Popups.
1498 return pending_window_rect_;
1501 return window_screen_rect_;
1504 WebRect RenderWidget::windowResizerRect() {
1505 return resizer_rect_;
1508 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1509 // To prevent this renderer process from sending unnecessary IPC messages to
1510 // a browser process, we permit the renderer process to send IPC messages
1511 // only during the input method attached to the browser process is active.
1512 input_method_is_active_ = is_active;
1515 void RenderWidget::OnCandidateWindowShown() {
1516 webwidget_->didShowCandidateWindow();
1519 void RenderWidget::OnCandidateWindowUpdated() {
1520 webwidget_->didUpdateCandidateWindow();
1523 void RenderWidget::OnCandidateWindowHidden() {
1524 webwidget_->didHideCandidateWindow();
1527 void RenderWidget::OnImeSetComposition(
1528 const base::string16& text,
1529 const std::vector<WebCompositionUnderline>& underlines,
1530 int selection_start, int selection_end) {
1531 if (!ShouldHandleImeEvent())
1532 return;
1533 ImeEventGuard guard(this);
1534 if (!webwidget_->setComposition(
1535 text, WebVector<WebCompositionUnderline>(underlines),
1536 selection_start, selection_end)) {
1537 // If we failed to set the composition text, then we need to let the browser
1538 // process to cancel the input method's ongoing composition session, to make
1539 // sure we are in a consistent state.
1540 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1542 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
1543 UpdateCompositionInfo(true);
1544 #endif
1547 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1548 const gfx::Range& replacement_range,
1549 bool keep_selection) {
1550 if (!ShouldHandleImeEvent())
1551 return;
1552 ImeEventGuard guard(this);
1553 handling_input_event_ = true;
1554 if (text.length())
1555 webwidget_->confirmComposition(text);
1556 else if (keep_selection)
1557 webwidget_->confirmComposition(WebWidget::KeepSelection);
1558 else
1559 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1560 handling_input_event_ = false;
1561 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
1562 UpdateCompositionInfo(true);
1563 #endif
1566 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1567 // During shutdown we can just ignore this message.
1568 if (!webwidget_)
1569 return;
1571 // Even if the browser provides an empty damage rect, it's still expecting to
1572 // receive a repaint ack so just damage the entire widget bounds.
1573 if (size_to_paint.IsEmpty()) {
1574 size_to_paint = size_;
1577 set_next_paint_is_repaint_ack();
1578 if (compositor_)
1579 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1582 void RenderWidget::OnSyntheticGestureCompleted() {
1583 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1585 pending_synthetic_gesture_callbacks_.front().Run();
1586 pending_synthetic_gesture_callbacks_.pop();
1589 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1590 if (!webwidget_)
1591 return;
1592 webwidget_->setTextDirection(direction);
1595 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1596 const gfx::Rect& window_screen_rect) {
1597 if (screen_metrics_emulator_) {
1598 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1599 view_screen_rect, window_screen_rect);
1600 } else {
1601 view_screen_rect_ = view_screen_rect;
1602 window_screen_rect_ = window_screen_rect;
1604 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1607 void RenderWidget::showImeIfNeeded() {
1608 OnShowImeIfNeeded();
1611 void RenderWidget::OnShowImeIfNeeded() {
1612 #if defined(OS_ANDROID) || defined(USE_AURA)
1613 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1614 #endif
1617 #if defined(OS_ANDROID)
1618 void RenderWidget::IncrementOutstandingImeEventAcks() {
1619 ++outstanding_ime_acks_;
1622 void RenderWidget::OnImeEventAck() {
1623 --outstanding_ime_acks_;
1624 DCHECK(outstanding_ime_acks_ >= 0);
1626 #endif
1628 bool RenderWidget::ShouldHandleImeEvent() {
1629 #if defined(OS_ANDROID)
1630 return !!webwidget_ && outstanding_ime_acks_ == 0;
1631 #else
1632 return !!webwidget_;
1633 #endif
1636 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1637 if (handling_event_type_ == WebInputEvent::MouseMove) {
1638 // If we pause multiple times during a single mouse move event, we should
1639 // only send ACK once.
1640 if (!ignore_ack_for_mouse_move_from_debugger_) {
1641 InputHostMsg_HandleInputEvent_ACK_Params ack;
1642 ack.type = handling_event_type_;
1643 ack.state = INPUT_EVENT_ACK_STATE_CONSUMED;
1644 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1646 return true;
1648 return false;
1651 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1652 ignore_ack_for_mouse_move_from_debugger_ = true;
1655 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1656 if (device_scale_factor_ == device_scale_factor)
1657 return;
1659 device_scale_factor_ = device_scale_factor;
1660 scheduleComposite();
1663 bool RenderWidget::SetDeviceColorProfile(
1664 const std::vector<char>& color_profile) {
1665 if (device_color_profile_ == color_profile)
1666 return false;
1668 device_color_profile_ = color_profile;
1669 return true;
1672 void RenderWidget::ResetDeviceColorProfileForTesting() {
1673 if (!device_color_profile_.empty())
1674 device_color_profile_.clear();
1675 device_color_profile_.push_back('0');
1678 void RenderWidget::OnOrientationChange() {
1681 gfx::Vector2d RenderWidget::GetScrollOffset() {
1682 // Bare RenderWidgets don't support scroll offset.
1683 return gfx::Vector2d();
1686 void RenderWidget::SetHidden(bool hidden) {
1687 if (is_hidden_ == hidden)
1688 return;
1690 // The status has changed. Tell the RenderThread about it.
1691 is_hidden_ = hidden;
1692 if (is_hidden_)
1693 RenderThreadImpl::current()->WidgetHidden();
1694 else
1695 RenderThreadImpl::current()->WidgetRestored();
1698 void RenderWidget::WillToggleFullscreen() {
1699 if (!webwidget_)
1700 return;
1702 if (is_fullscreen_) {
1703 webwidget_->willExitFullScreen();
1704 } else {
1705 webwidget_->willEnterFullScreen();
1709 void RenderWidget::DidToggleFullscreen() {
1710 if (!webwidget_)
1711 return;
1713 if (is_fullscreen_) {
1714 webwidget_->didEnterFullScreen();
1715 } else {
1716 webwidget_->didExitFullScreen();
1720 bool RenderWidget::next_paint_is_resize_ack() const {
1721 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1724 void RenderWidget::set_next_paint_is_resize_ack() {
1725 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1728 void RenderWidget::set_next_paint_is_repaint_ack() {
1729 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1732 static bool IsDateTimeInput(ui::TextInputType type) {
1733 return type == ui::TEXT_INPUT_TYPE_DATE ||
1734 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1735 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1736 type == ui::TEXT_INPUT_TYPE_MONTH ||
1737 type == ui::TEXT_INPUT_TYPE_TIME ||
1738 type == ui::TEXT_INPUT_TYPE_WEEK;
1742 void RenderWidget::StartHandlingImeEvent() {
1743 DCHECK(!handling_ime_event_);
1744 handling_ime_event_ = true;
1747 void RenderWidget::FinishHandlingImeEvent() {
1748 DCHECK(handling_ime_event_);
1749 handling_ime_event_ = false;
1750 // While handling an ime event, text input state and selection bounds updates
1751 // are ignored. These must explicitly be updated once finished handling the
1752 // ime event.
1753 UpdateSelectionBounds();
1754 #if defined(OS_ANDROID)
1755 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1756 #endif
1759 void RenderWidget::UpdateTextInputType() {
1760 // On Windows, not only an IME but also an on-screen keyboard relies on the
1761 // latest TextInputType to optimize its layout and functionality. Thus
1762 // |input_method_is_active_| is no longer an appropriate condition to suppress
1763 // TextInputTypeChanged IPC on Windows.
1764 // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
1765 // on other platforms as well as Windows if the overhead is acceptable.
1766 #if !defined(OS_WIN)
1767 if (!input_method_is_active_)
1768 return;
1769 #endif
1771 ui::TextInputType new_type = GetTextInputType();
1772 if (IsDateTimeInput(new_type))
1773 return; // Not considered as a text input field in WebKit/Chromium.
1775 bool new_can_compose_inline = CanComposeInline();
1777 blink::WebTextInputInfo new_info;
1778 if (webwidget_)
1779 new_info = webwidget_->textInputInfo();
1780 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1781 int new_flags = new_info.flags;
1783 if (text_input_type_ != new_type
1784 || can_compose_inline_ != new_can_compose_inline
1785 || text_input_mode_ != new_mode
1786 || text_input_flags_ != new_flags) {
1787 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1788 new_type,
1789 new_mode,
1790 new_can_compose_inline,
1791 new_flags));
1792 text_input_type_ = new_type;
1793 can_compose_inline_ = new_can_compose_inline;
1794 text_input_mode_ = new_mode;
1795 text_input_flags_ = new_flags;
1799 #if defined(OS_ANDROID) || defined(USE_AURA)
1800 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1801 ChangeSource change_source) {
1802 if (handling_ime_event_)
1803 return;
1804 if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1805 return;
1806 ui::TextInputType new_type = GetTextInputType();
1807 if (IsDateTimeInput(new_type))
1808 return; // Not considered as a text input field in WebKit/Chromium.
1810 blink::WebTextInputInfo new_info;
1811 if (webwidget_)
1812 new_info = webwidget_->textInputInfo();
1814 bool new_can_compose_inline = CanComposeInline();
1816 // Only sends text input params if they are changed or if the ime should be
1817 // shown.
1818 if (show_ime == SHOW_IME_IF_NEEDED ||
1819 (text_input_type_ != new_type ||
1820 text_input_info_ != new_info ||
1821 can_compose_inline_ != new_can_compose_inline)
1822 #if defined(OS_ANDROID)
1823 || text_field_is_dirty_
1824 #endif
1826 ViewHostMsg_TextInputState_Params p;
1827 p.type = new_type;
1828 p.flags = new_info.flags;
1829 p.value = new_info.value.utf8();
1830 p.selection_start = new_info.selectionStart;
1831 p.selection_end = new_info.selectionEnd;
1832 p.composition_start = new_info.compositionStart;
1833 p.composition_end = new_info.compositionEnd;
1834 p.can_compose_inline = new_can_compose_inline;
1835 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1836 #if defined(USE_AURA)
1837 p.is_non_ime_change = true;
1838 #endif
1839 #if defined(OS_ANDROID)
1840 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1841 text_field_is_dirty_;
1842 if (p.is_non_ime_change)
1843 IncrementOutstandingImeEventAcks();
1844 text_field_is_dirty_ = false;
1845 #endif
1846 #if defined(USE_AURA)
1847 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1848 new_type,
1849 text_input_mode_,
1850 new_can_compose_inline,
1851 new_info.flags));
1852 #endif
1853 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
1855 text_input_info_ = new_info;
1856 text_input_type_ = new_type;
1857 can_compose_inline_ = new_can_compose_inline;
1858 text_input_flags_ = new_info.flags;
1861 #endif
1863 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1864 WebRect focus_webrect;
1865 WebRect anchor_webrect;
1866 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1867 *focus = focus_webrect;
1868 *anchor = anchor_webrect;
1871 void RenderWidget::UpdateSelectionBounds() {
1872 if (!webwidget_)
1873 return;
1874 if (handling_ime_event_)
1875 return;
1877 // With composited selection updates, the selection bounds will be reported
1878 // directly by the compositor, in which case explicit IPC selection
1879 // notifications should be suppressed.
1880 if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
1881 ViewHostMsg_SelectionBounds_Params params;
1882 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
1883 if (selection_anchor_rect_ != params.anchor_rect ||
1884 selection_focus_rect_ != params.focus_rect) {
1885 selection_anchor_rect_ = params.anchor_rect;
1886 selection_focus_rect_ = params.focus_rect;
1887 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
1888 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
1889 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
1893 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
1894 UpdateCompositionInfo(false);
1895 #endif
1898 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
1899 COMPILE_ASSERT(int(blink::WebTextInputTypeNone) == \
1900 int(ui::TEXT_INPUT_TYPE_NONE), mismatching_enums);
1901 COMPILE_ASSERT(int(blink::WebTextInputTypeText) == \
1902 int(ui::TEXT_INPUT_TYPE_TEXT), mismatching_enums);
1903 COMPILE_ASSERT(int(blink::WebTextInputTypePassword) == \
1904 int(ui::TEXT_INPUT_TYPE_PASSWORD), mismatching_enums);
1905 COMPILE_ASSERT(int(blink::WebTextInputTypeSearch) == \
1906 int(ui::TEXT_INPUT_TYPE_SEARCH), mismatching_enums);
1907 COMPILE_ASSERT(int(blink::WebTextInputTypeEmail) == \
1908 int(ui::TEXT_INPUT_TYPE_EMAIL), mismatching_enums);
1909 COMPILE_ASSERT(int(blink::WebTextInputTypeNumber) == \
1910 int(ui::TEXT_INPUT_TYPE_NUMBER), mismatching_enums);
1911 COMPILE_ASSERT(int(blink::WebTextInputTypeTelephone) == \
1912 int(ui::TEXT_INPUT_TYPE_TELEPHONE), mismatching_enums);
1913 COMPILE_ASSERT(int(blink::WebTextInputTypeURL) == \
1914 int(ui::TEXT_INPUT_TYPE_URL), mismatching_enums);
1915 COMPILE_ASSERT(int(blink::WebTextInputTypeDate) == \
1916 int(ui::TEXT_INPUT_TYPE_DATE), mismatching_enum);
1917 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTime) == \
1918 int(ui::TEXT_INPUT_TYPE_DATE_TIME), mismatching_enum);
1919 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeLocal) == \
1920 int(ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL), mismatching_enum);
1921 COMPILE_ASSERT(int(blink::WebTextInputTypeMonth) == \
1922 int(ui::TEXT_INPUT_TYPE_MONTH), mismatching_enum);
1923 COMPILE_ASSERT(int(blink::WebTextInputTypeTime) == \
1924 int(ui::TEXT_INPUT_TYPE_TIME), mismatching_enum);
1925 COMPILE_ASSERT(int(blink::WebTextInputTypeWeek) == \
1926 int(ui::TEXT_INPUT_TYPE_WEEK), mismatching_enum);
1927 COMPILE_ASSERT(int(blink::WebTextInputTypeTextArea) == \
1928 int(ui::TEXT_INPUT_TYPE_TEXT_AREA), mismatching_enums);
1929 COMPILE_ASSERT(int(blink::WebTextInputTypeContentEditable) == \
1930 int(ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE), mismatching_enums);
1931 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeField) == \
1932 int(ui::TEXT_INPUT_TYPE_DATE_TIME_FIELD), mismatching_enums);
1934 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
1935 blink::WebTextInputType type) {
1936 // Check the type is in the range representable by ui::TextInputType.
1937 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
1938 "blink::WebTextInputType and ui::TextInputType not synchronized";
1939 return static_cast<ui::TextInputType>(type);
1942 ui::TextInputType RenderWidget::GetTextInputType() {
1943 if (webwidget_)
1944 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
1945 return ui::TEXT_INPUT_TYPE_NONE;
1948 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
1949 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
1950 #if defined(OS_ANDROID)
1951 // Sending composition info makes sense only in Lollipop (API level 21)
1952 // and above due to the API availability.
1953 if (base::android::BuildInfo::GetInstance()->sdk_int() < 21)
1954 return;
1955 #endif
1957 gfx::Range range = gfx::Range();
1958 if (should_update_range) {
1959 GetCompositionRange(&range);
1960 } else {
1961 range = composition_range_;
1963 std::vector<gfx::Rect> character_bounds;
1964 GetCompositionCharacterBounds(&character_bounds);
1966 if (!ShouldUpdateCompositionInfo(range, character_bounds))
1967 return;
1968 composition_character_bounds_ = character_bounds;
1969 composition_range_ = range;
1970 Send(new InputHostMsg_ImeCompositionRangeChanged(
1971 routing_id(), composition_range_, composition_character_bounds_));
1974 void RenderWidget::GetCompositionCharacterBounds(
1975 std::vector<gfx::Rect>* bounds) {
1976 DCHECK(bounds);
1977 bounds->clear();
1980 void RenderWidget::GetCompositionRange(gfx::Range* range) {
1981 size_t location, length;
1982 if (webwidget_->compositionRange(&location, &length)) {
1983 range->set_start(location);
1984 range->set_end(location + length);
1985 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
1986 range->set_start(location);
1987 range->set_end(location + length);
1988 } else {
1989 *range = gfx::Range::InvalidRange();
1993 bool RenderWidget::ShouldUpdateCompositionInfo(
1994 const gfx::Range& range,
1995 const std::vector<gfx::Rect>& bounds) {
1996 if (composition_range_ != range)
1997 return true;
1998 if (bounds.size() != composition_character_bounds_.size())
1999 return true;
2000 for (size_t i = 0; i < bounds.size(); ++i) {
2001 if (bounds[i] != composition_character_bounds_[i])
2002 return true;
2004 return false;
2006 #endif
2008 #if defined(OS_ANDROID)
2009 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2010 // If not initialized, default to white. Note that 0 is different from black
2011 // as black still has alpha 0xFF.
2012 if (!bg_color)
2013 bg_color = SK_ColorWHITE;
2015 if (bg_color != body_background_color_) {
2016 body_background_color_ = bg_color;
2017 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2020 #endif
2022 bool RenderWidget::CanComposeInline() {
2023 return true;
2026 WebScreenInfo RenderWidget::screenInfo() {
2027 return screen_info_;
2030 float RenderWidget::deviceScaleFactor() {
2031 return device_scale_factor_;
2034 void RenderWidget::resetInputMethod() {
2035 if (!input_method_is_active_)
2036 return;
2038 ImeEventGuard guard(this);
2039 // If the last text input type is not None, then we should finish any
2040 // ongoing composition regardless of the new text input type.
2041 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2042 // If a composition text exists, then we need to let the browser process
2043 // to cancel the input method's ongoing composition session.
2044 if (webwidget_->confirmComposition())
2045 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2048 #if defined(OS_MACOSX) || defined(USE_AURA) || defined(OS_ANDROID)
2049 UpdateCompositionInfo(true);
2050 #endif
2053 void RenderWidget::didHandleGestureEvent(
2054 const WebGestureEvent& event,
2055 bool event_cancelled) {
2056 #if defined(OS_ANDROID) || defined(USE_AURA)
2057 if (event_cancelled)
2058 return;
2059 if (event.type == WebInputEvent::GestureTap) {
2060 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2061 } else if (event.type == WebInputEvent::GestureLongPress) {
2062 DCHECK(webwidget_);
2063 if (webwidget_->textInputInfo().value.isEmpty())
2064 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2065 else
2066 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2068 #endif
2071 void RenderWidget::StartCompositor() {
2072 // For widgets that are never visible, we don't need the compositor to run
2073 // at all.
2074 if (never_visible_)
2075 return;
2076 compositor_->setSurfaceReady();
2079 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2080 size_t i = 0;
2081 for (; i < plugin_window_moves_.size(); ++i) {
2082 if (plugin_window_moves_[i].window == move.window) {
2083 if (move.rects_valid) {
2084 plugin_window_moves_[i] = move;
2085 } else {
2086 plugin_window_moves_[i].visible = move.visible;
2088 break;
2092 if (i == plugin_window_moves_.size())
2093 plugin_window_moves_.push_back(move);
2096 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2097 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2098 i != plugin_window_moves_.end(); ++i) {
2099 if (i->window == window) {
2100 plugin_window_moves_.erase(i);
2101 break;
2107 RenderWidgetCompositor* RenderWidget::compositor() const {
2108 return compositor_.get();
2111 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2112 return false;
2115 bool RenderWidget::WillHandleGestureEvent(
2116 const blink::WebGestureEvent& event) {
2117 return false;
2120 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2121 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2124 void RenderWidget::setTouchAction(
2125 blink::WebTouchAction web_touch_action) {
2127 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2128 // when blink is emulating touch with mouse).
2129 if (handling_event_type_ != WebInputEvent::TouchStart)
2130 return;
2132 // Verify the same values are used by the types so we can cast between them.
2133 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_AUTO) ==
2134 blink::WebTouchActionAuto,
2135 enum_values_must_match_for_touch_action);
2136 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_NONE) ==
2137 blink::WebTouchActionNone,
2138 enum_values_must_match_for_touch_action);
2139 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_X) ==
2140 blink::WebTouchActionPanX,
2141 enum_values_must_match_for_touch_action);
2142 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_Y) ==
2143 blink::WebTouchActionPanY,
2144 enum_values_must_match_for_touch_action);
2145 COMPILE_ASSERT(
2146 static_cast<blink::WebTouchAction>(TOUCH_ACTION_PINCH_ZOOM) ==
2147 blink::WebTouchActionPinchZoom,
2148 enum_values_must_match_for_touch_action);
2150 content::TouchAction content_touch_action =
2151 static_cast<content::TouchAction>(web_touch_action);
2152 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2155 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2156 #if defined(OS_ANDROID)
2157 text_field_is_dirty_ = true;
2158 #endif
2161 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2162 return true;
2165 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2166 RenderWidget::CreateGraphicsContext3D() {
2167 if (!webwidget_)
2168 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2169 if (CommandLine::ForCurrentProcess()->HasSwitch(
2170 switches::kDisableGpuCompositing))
2171 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2172 if (!RenderThreadImpl::current())
2173 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2174 CauseForGpuLaunch cause =
2175 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2176 scoped_refptr<GpuChannelHost> gpu_channel_host(
2177 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2178 if (!gpu_channel_host.get())
2179 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2181 // Explicitly disable antialiasing for the compositor. As of the time of
2182 // this writing, the only platform that supported antialiasing for the
2183 // compositor was Mac OS X, because the on-screen OpenGL context creation
2184 // code paths on Windows and Linux didn't yet have multisampling support.
2185 // Mac OS X essentially always behaves as though it's rendering offscreen.
2186 // Multisampling has a heavy cost especially on devices with relatively low
2187 // fill rate like most notebooks, and the Mac implementation would need to
2188 // be optimized to resolve directly into the IOSurface shared between the
2189 // GPU and browser processes. For these reasons and to avoid platform
2190 // disparities we explicitly disable antialiasing.
2191 blink::WebGraphicsContext3D::Attributes attributes;
2192 attributes.antialias = false;
2193 attributes.shareResources = true;
2194 attributes.noAutomaticFlushes = true;
2195 attributes.depth = false;
2196 attributes.stencil = false;
2197 bool lose_context_when_out_of_memory = true;
2198 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2199 #if defined(OS_ANDROID)
2200 // If we raster too fast we become upload bound, and pending
2201 // uploads consume memory. For maximum upload throughput, we would
2202 // want to allow for upload_throughput * pipeline_time of pending
2203 // uploads, after which we are just wasting memory. Since we don't
2204 // know our upload throughput yet, this just caps our memory usage.
2205 size_t divider = 1;
2206 if (base::SysInfo::IsLowEndDevice())
2207 divider = 6;
2208 // For reference Nexus10 can upload 1MB in about 2.5ms.
2209 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2210 // Deadline to draw a frame to achieve 60 frames per second.
2211 const size_t kMillisecondsPerFrame = 16;
2212 // Assuming a two frame deep pipeline between the CPU and the GPU.
2213 size_t max_transfer_buffer_usage_mb =
2214 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2215 static const size_t kBytesPerMegabyte = 1024 * 1024;
2216 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2217 // to avoid unnecessarily stalling the compositor thread.
2218 limits.mapped_memory_reclaim_limit =
2219 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2220 #endif
2222 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2223 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2224 GetURLForGraphicsContext3D(),
2225 gpu_channel_host.get(),
2226 attributes,
2227 lose_context_when_out_of_memory,
2228 limits,
2229 NULL));
2230 return context.Pass();
2233 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2234 render_frame_proxies_.AddObserver(proxy);
2237 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2238 render_frame_proxies_.RemoveObserver(proxy);
2241 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2242 render_frames_.AddObserver(frame);
2245 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2246 render_frames_.RemoveObserver(frame);
2249 #if defined(VIDEO_HOLE)
2250 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2251 video_hole_frames_.AddObserver(frame);
2254 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2255 video_hole_frames_.RemoveObserver(frame);
2257 #endif // defined(VIDEO_HOLE)
2259 } // namespace content