Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob3d693b95f9230d20494738dc0faa56e4d1d3af9e
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_webkitplatformsupport_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/skia/include/core/SkShader.h"
68 #include "ui/base/ui_base_switches.h"
69 #include "ui/gfx/frame_time.h"
70 #include "ui/gfx/point_conversions.h"
71 #include "ui/gfx/rect_conversions.h"
72 #include "ui/gfx/size_conversions.h"
73 #include "ui/gfx/skia_util.h"
74 #include "ui/gl/gl_switches.h"
75 #include "ui/surface/transport_dib.h"
77 #if defined(OS_ANDROID)
78 #include <android/keycodes.h>
79 #include "content/renderer/android/synchronous_compositor_factory.h"
80 #endif
82 #if defined(OS_POSIX)
83 #include "ipc/ipc_channel_posix.h"
84 #include "third_party/skia/include/core/SkMallocPixelRef.h"
85 #include "third_party/skia/include/core/SkPixelRef.h"
86 #endif // defined(OS_POSIX)
88 #include "third_party/WebKit/public/web/WebWidget.h"
90 using blink::WebCompositionUnderline;
91 using blink::WebCursorInfo;
92 using blink::WebDeviceEmulationParams;
93 using blink::WebGestureEvent;
94 using blink::WebInputEvent;
95 using blink::WebKeyboardEvent;
96 using blink::WebMouseEvent;
97 using blink::WebMouseWheelEvent;
98 using blink::WebNavigationPolicy;
99 using blink::WebPagePopup;
100 using blink::WebPopupMenu;
101 using blink::WebPopupMenuInfo;
102 using blink::WebPopupType;
103 using blink::WebRange;
104 using blink::WebRect;
105 using blink::WebScreenInfo;
106 using blink::WebSize;
107 using blink::WebTextDirection;
108 using blink::WebTouchEvent;
109 using blink::WebTouchPoint;
110 using blink::WebVector;
111 using blink::WebWidget;
113 namespace {
115 typedef std::map<std::string, ui::TextInputMode> TextInputModeMap;
117 class TextInputModeMapSingleton {
118 public:
119 static TextInputModeMapSingleton* GetInstance() {
120 return Singleton<TextInputModeMapSingleton>::get();
122 TextInputModeMapSingleton() {
123 map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM;
124 map_["latin"] = ui::TEXT_INPUT_MODE_LATIN;
125 map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME;
126 map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE;
127 map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN;
128 map_["kana"] = ui::TEXT_INPUT_MODE_KANA;
129 map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA;
130 map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC;
131 map_["tel"] = ui::TEXT_INPUT_MODE_TEL;
132 map_["email"] = ui::TEXT_INPUT_MODE_EMAIL;
133 map_["url"] = ui::TEXT_INPUT_MODE_URL;
135 const TextInputModeMap& map() const { return map_; }
136 private:
137 TextInputModeMap map_;
139 friend struct DefaultSingletonTraits<TextInputModeMapSingleton>;
141 DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton);
144 ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) {
145 static TextInputModeMapSingleton* singleton =
146 TextInputModeMapSingleton::GetInstance();
147 TextInputModeMap::const_iterator it =
148 singleton->map().find(input_mode.utf8());
149 if (it == singleton->map().end())
150 return ui::TEXT_INPUT_MODE_DEFAULT;
151 return it->second;
154 bool IsThreadedCompositingEnabled() {
155 content::RenderThreadImpl* impl = content::RenderThreadImpl::current();
156 return impl && !!impl->compositor_message_loop_proxy().get();
159 // TODO(brianderson): Replace the hard-coded threshold with a fraction of
160 // the BeginMainFrame interval.
161 // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to
162 // be spent in input hanlders before input starts getting throttled.
163 const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166;
165 } // namespace
167 namespace content {
169 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
171 class RenderWidget::ScreenMetricsEmulator {
172 public:
173 ScreenMetricsEmulator(
174 RenderWidget* widget,
175 const WebDeviceEmulationParams& params);
176 virtual ~ScreenMetricsEmulator();
178 // Scale and offset used to convert between host coordinates
179 // and webwidget coordinates.
180 float scale() { return scale_; }
181 gfx::Point offset() { return offset_; }
182 gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
183 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
184 const WebScreenInfo& original_screen_info() { return original_screen_info_; }
186 void ChangeEmulationParams(
187 const WebDeviceEmulationParams& params);
189 // The following methods alter handlers' behavior for messages related to
190 // widget size and position.
191 void OnResizeMessage(const ViewMsg_Resize_Params& params);
192 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
193 const gfx::Rect& window_screen_rect);
194 void OnShowContextMenu(ContextMenuParams* params);
195 gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
197 private:
198 void Reapply();
199 void Apply(float top_controls_layout_height,
200 gfx::Rect resizer_rect,
201 bool is_fullscreen);
203 RenderWidget* widget_;
205 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
206 WebDeviceEmulationParams params_;
208 // The computed scale and offset used to fit widget into browser window.
209 float scale_;
210 gfx::Point offset_;
212 // Widget rect as passed to webwidget.
213 gfx::Rect applied_widget_rect_;
215 // Original values to restore back after emulation ends.
216 gfx::Size original_size_;
217 gfx::Size original_physical_backing_size_;
218 gfx::Size original_visible_viewport_size_;
219 blink::WebScreenInfo original_screen_info_;
220 gfx::Rect original_view_screen_rect_;
221 gfx::Rect original_window_screen_rect_;
224 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
225 RenderWidget* widget,
226 const WebDeviceEmulationParams& params)
227 : widget_(widget),
228 params_(params),
229 scale_(1.f) {
230 original_size_ = widget_->size_;
231 original_physical_backing_size_ = widget_->physical_backing_size_;
232 original_visible_viewport_size_ = widget_->visible_viewport_size_;
233 original_screen_info_ = widget_->screen_info_;
234 original_view_screen_rect_ = widget_->view_screen_rect_;
235 original_window_screen_rect_ = widget_->window_screen_rect_;
236 Apply(widget_->top_controls_layout_height_, widget_->resizer_rect_,
237 widget_->is_fullscreen_);
240 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
241 widget_->screen_info_ = original_screen_info_;
243 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
244 widget_->SetScreenMetricsEmulationParameters(0.f, gfx::Point(), 1.f);
245 widget_->view_screen_rect_ = original_view_screen_rect_;
246 widget_->window_screen_rect_ = original_window_screen_rect_;
247 widget_->Resize(original_size_,
248 original_physical_backing_size_,
249 widget_->top_controls_layout_height_,
250 original_visible_viewport_size_,
251 widget_->resizer_rect_,
252 widget_->is_fullscreen_,
253 NO_RESIZE_ACK);
256 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
257 const WebDeviceEmulationParams& params) {
258 params_ = params;
259 Reapply();
262 void RenderWidget::ScreenMetricsEmulator::Reapply() {
263 Apply(widget_->top_controls_layout_height_, widget_->resizer_rect_,
264 widget_->is_fullscreen_);
267 void RenderWidget::ScreenMetricsEmulator::Apply(
268 float top_controls_layout_height,
269 gfx::Rect resizer_rect,
270 bool is_fullscreen) {
271 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
272 if (!applied_widget_rect_.width())
273 applied_widget_rect_.set_width(original_size_.width());
274 if (!applied_widget_rect_.height())
275 applied_widget_rect_.set_height(original_size_.height());
277 if (params_.fitToView && !original_size_.IsEmpty()) {
278 int original_width = std::max(original_size_.width(), 1);
279 int original_height = std::max(original_size_.height(), 1);
280 float width_ratio =
281 static_cast<float>(applied_widget_rect_.width()) / original_width;
282 float height_ratio =
283 static_cast<float>(applied_widget_rect_.height()) / original_height;
284 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
285 scale_ = 1.f / ratio;
287 // Center emulated view inside available view space.
288 offset_.set_x(
289 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
290 offset_.set_y(
291 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
292 } else {
293 scale_ = params_.scale;
294 offset_.SetPoint(params_.offset.x, params_.offset.y);
297 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
298 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
299 widget_->screen_info_.rect = original_screen_info_.rect;
300 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
301 widget_->window_screen_rect_ = original_window_screen_rect_;
302 } else {
303 applied_widget_rect_.set_origin(gfx::Point(0, 0));
304 widget_->screen_info_.rect = applied_widget_rect_;
305 widget_->screen_info_.availableRect = applied_widget_rect_;
306 widget_->window_screen_rect_ = applied_widget_rect_;
309 float applied_device_scale_factor = params_.deviceScaleFactor ?
310 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
311 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
313 // Pass three emulation parameters to the blink side:
314 // - we keep the real device scale factor in compositor to produce sharp image
315 // even when emulating different scale factor;
316 // - in order to fit into view, WebView applies offset and scale to the
317 // root layer.
318 widget_->SetScreenMetricsEmulationParameters(
319 original_screen_info_.deviceScaleFactor, offset_, scale_);
321 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
322 widget_->view_screen_rect_ = applied_widget_rect_;
324 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
325 original_size_, original_screen_info_.deviceScaleFactor));
326 widget_->Resize(applied_widget_rect_.size(), physical_backing_size,
327 top_controls_layout_height, applied_widget_rect_.size(), resizer_rect,
328 is_fullscreen, NO_RESIZE_ACK);
331 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
332 const ViewMsg_Resize_Params& params) {
333 bool need_ack = params.new_size != original_size_ &&
334 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
335 original_size_ = params.new_size;
336 original_physical_backing_size_ = params.physical_backing_size;
337 original_screen_info_ = params.screen_info;
338 original_visible_viewport_size_ = params.visible_viewport_size;
339 Apply(params.top_controls_layout_height, params.resizer_rect,
340 params.is_fullscreen);
342 if (need_ack) {
343 widget_->set_next_paint_is_resize_ack();
344 if (widget_->compositor_)
345 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
349 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
350 const gfx::Rect& view_screen_rect,
351 const gfx::Rect& window_screen_rect) {
352 original_view_screen_rect_ = view_screen_rect;
353 original_window_screen_rect_ = window_screen_rect;
354 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
355 Reapply();
358 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
359 ContextMenuParams* params) {
360 params->x *= scale_;
361 params->x += offset_.x();
362 params->y *= scale_;
363 params->y += offset_.y();
366 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
367 const gfx::Rect& anchor) {
368 gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
369 scaled.set_x(scaled.x() + offset_.x());
370 scaled.set_y(scaled.y() + offset_.y());
371 return scaled;
374 // RenderWidget ---------------------------------------------------------------
376 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
377 const blink::WebScreenInfo& screen_info,
378 bool swapped_out,
379 bool hidden,
380 bool never_visible)
381 : routing_id_(MSG_ROUTING_NONE),
382 surface_id_(0),
383 webwidget_(NULL),
384 opener_id_(MSG_ROUTING_NONE),
385 init_complete_(false),
386 top_controls_layout_height_(0.f),
387 next_paint_flags_(0),
388 auto_resize_mode_(false),
389 need_update_rect_for_auto_resize_(false),
390 did_show_(false),
391 is_hidden_(hidden),
392 never_visible_(never_visible),
393 is_fullscreen_(false),
394 has_focus_(false),
395 handling_input_event_(false),
396 handling_ime_event_(false),
397 handling_event_type_(WebInputEvent::Undefined),
398 ignore_ack_for_mouse_move_from_debugger_(false),
399 closing_(false),
400 host_closing_(false),
401 is_swapped_out_(swapped_out),
402 input_method_is_active_(false),
403 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
404 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
405 can_compose_inline_(true),
406 popup_type_(popup_type),
407 pending_window_rect_count_(0),
408 suppress_next_char_events_(false),
409 screen_info_(screen_info),
410 device_scale_factor_(screen_info_.deviceScaleFactor),
411 current_event_latency_info_(NULL),
412 next_output_surface_id_(0),
413 #if defined(OS_ANDROID)
414 text_field_is_dirty_(false),
415 outstanding_ime_acks_(0),
416 body_background_color_(SK_ColorWHITE),
417 #endif
418 popup_origin_scale_for_emulation_(0.f),
419 frame_swap_message_queue_(new FrameSwapMessageQueue()),
420 resizing_mode_selector_(new ResizingModeSelector()),
421 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
422 has_host_context_menu_location_(false) {
423 if (!swapped_out)
424 RenderProcess::current()->AddRefProcess();
425 DCHECK(RenderThread::Get());
426 device_color_profile_.push_back('0');
429 RenderWidget::~RenderWidget() {
430 DCHECK(!webwidget_) << "Leaking our WebWidget!";
432 // If we are swapped out, we have released already.
433 if (!is_swapped_out_ && RenderProcess::current())
434 RenderProcess::current()->ReleaseProcess();
437 // static
438 RenderWidget* RenderWidget::Create(int32 opener_id,
439 blink::WebPopupType popup_type,
440 const blink::WebScreenInfo& screen_info) {
441 DCHECK(opener_id != MSG_ROUTING_NONE);
442 scoped_refptr<RenderWidget> widget(
443 new RenderWidget(popup_type, screen_info, false, false, false));
444 if (widget->Init(opener_id)) { // adds reference on success.
445 return widget.get();
447 return NULL;
450 // static
451 WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
452 switch (render_widget->popup_type_) {
453 case blink::WebPopupTypeNone: // Nothing to create.
454 break;
455 case blink::WebPopupTypeSelect:
456 case blink::WebPopupTypeSuggestion:
457 return WebPopupMenu::create(render_widget);
458 case blink::WebPopupTypePage:
459 return WebPagePopup::create(render_widget);
460 default:
461 NOTREACHED();
463 return NULL;
466 bool RenderWidget::Init(int32 opener_id) {
467 return DoInit(opener_id,
468 RenderWidget::CreateWebWidget(this),
469 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
470 &routing_id_, &surface_id_));
473 bool RenderWidget::DoInit(int32 opener_id,
474 WebWidget* web_widget,
475 IPC::SyncMessage* create_widget_message) {
476 DCHECK(!webwidget_);
478 if (opener_id != MSG_ROUTING_NONE)
479 opener_id_ = opener_id;
481 webwidget_ = web_widget;
483 bool result = RenderThread::Get()->Send(create_widget_message);
484 if (result) {
485 RenderThread::Get()->AddRoute(routing_id_, this);
486 // Take a reference on behalf of the RenderThread. This will be balanced
487 // when we receive ViewMsg_Close.
488 AddRef();
489 if (RenderThreadImpl::current()) {
490 RenderThreadImpl::current()->WidgetCreated();
491 if (is_hidden_)
492 RenderThreadImpl::current()->WidgetHidden();
494 return true;
495 } else {
496 // The above Send can fail when the tab is closing.
497 return false;
501 // This is used to complete pending inits and non-pending inits.
502 void RenderWidget::CompleteInit() {
503 DCHECK(routing_id_ != MSG_ROUTING_NONE);
505 init_complete_ = true;
507 if (compositor_)
508 StartCompositor();
510 Send(new ViewHostMsg_RenderViewReady(routing_id_));
513 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
514 // We should only toggle between states.
515 DCHECK(is_swapped_out_ != is_swapped_out);
516 is_swapped_out_ = is_swapped_out;
518 // If we are swapping out, we will call ReleaseProcess, allowing the process
519 // to exit if all of its RenderViews are swapped out. We wait until the
520 // WasSwappedOut call to do this, to allow the unload handler to finish.
521 // If we are swapping in, we call AddRefProcess to prevent the process from
522 // exiting.
523 if (!is_swapped_out_)
524 RenderProcess::current()->AddRefProcess();
527 void RenderWidget::WasSwappedOut() {
528 // If we have been swapped out and no one else is using this process,
529 // it's safe to exit now.
530 CHECK(is_swapped_out_);
531 RenderProcess::current()->ReleaseProcess();
534 void RenderWidget::EnableScreenMetricsEmulation(
535 const WebDeviceEmulationParams& params) {
536 if (!screen_metrics_emulator_)
537 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
538 else
539 screen_metrics_emulator_->ChangeEmulationParams(params);
542 void RenderWidget::DisableScreenMetricsEmulation() {
543 screen_metrics_emulator_.reset();
546 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
547 ScreenMetricsEmulator* emulator) {
548 popup_origin_scale_for_emulation_ = emulator->scale();
549 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
550 popup_screen_origin_for_emulation_ = gfx::Point(
551 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
552 emulator->original_screen_rect().origin().y() + emulator->offset().y());
553 screen_info_ = emulator->original_screen_info();
554 device_scale_factor_ = screen_info_.deviceScaleFactor;
557 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
558 if (screen_metrics_emulator_)
559 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
560 return anchor;
563 void RenderWidget::SetScreenMetricsEmulationParameters(
564 float device_scale_factor,
565 const gfx::Point& root_layer_offset,
566 float root_layer_scale) {
567 // This is only supported in RenderView.
568 NOTREACHED();
571 #if defined(OS_MACOSX) || defined(OS_ANDROID)
572 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
573 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
574 popup->SetOriginScaleAndOffsetForEmulation(
575 emulator->scale(), emulator->offset());
577 #endif
579 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
580 if (screen_metrics_emulator_)
581 screen_metrics_emulator_->OnShowContextMenu(params);
584 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
585 if (compositor_) {
586 // Regardless of whether threaded compositing is enabled, always
587 // use this mechanism to force the compositor to redraw. However,
588 // the invalidation code path below is still needed for the
589 // non-threaded case.
590 compositor_->SetNeedsForcedRedraw();
592 scheduleComposite();
595 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
596 bool handled = true;
597 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
598 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
599 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
600 OnCursorVisibilityChange)
601 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
602 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
603 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
604 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
605 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
606 OnSyntheticGestureCompleted)
607 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
608 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
609 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
610 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
611 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
612 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
613 IPC_MESSAGE_HANDLER(ViewMsg_SetInputMethodActive, OnSetInputMethodActive)
614 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowShown, OnCandidateWindowShown)
615 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowUpdated,
616 OnCandidateWindowUpdated)
617 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowHidden, OnCandidateWindowHidden)
618 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
619 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
620 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
621 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
622 #if defined(OS_ANDROID)
623 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
624 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
625 #endif
626 IPC_MESSAGE_UNHANDLED(handled = false)
627 IPC_END_MESSAGE_MAP()
628 return handled;
631 bool RenderWidget::Send(IPC::Message* message) {
632 // Don't send any messages after the browser has told us to close, and filter
633 // most outgoing messages while swapped out.
634 if ((is_swapped_out_ &&
635 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
636 closing_) {
637 delete message;
638 return false;
641 // If given a messsage without a routing ID, then assign our routing ID.
642 if (message->routing_id() == MSG_ROUTING_NONE)
643 message->set_routing_id(routing_id_);
645 return RenderThread::Get()->Send(message);
648 void RenderWidget::Resize(const gfx::Size& new_size,
649 const gfx::Size& physical_backing_size,
650 float top_controls_layout_height,
651 const gfx::Size& visible_viewport_size,
652 const gfx::Rect& resizer_rect,
653 bool is_fullscreen,
654 ResizeAck resize_ack) {
655 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
656 // A resize ack shouldn't be requested if we have not ACK'd the previous
657 // one.
658 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
659 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
662 // Ignore this during shutdown.
663 if (!webwidget_)
664 return;
666 if (compositor_) {
667 compositor_->setViewportSize(new_size, physical_backing_size);
668 compositor_->SetTopControlsLayoutHeight(top_controls_layout_height);
671 physical_backing_size_ = physical_backing_size;
672 top_controls_layout_height_ = top_controls_layout_height;
673 visible_viewport_size_ = visible_viewport_size;
674 resizer_rect_ = resizer_rect;
676 // NOTE: We may have entered fullscreen mode without changing our size.
677 bool fullscreen_change = is_fullscreen_ != is_fullscreen;
678 if (fullscreen_change)
679 WillToggleFullscreen();
680 is_fullscreen_ = is_fullscreen;
682 if (size_ != new_size) {
683 size_ = new_size;
685 // When resizing, we want to wait to paint before ACK'ing the resize. This
686 // ensures that we only resize as fast as we can paint. We only need to
687 // send an ACK if we are resized to a non-empty rect.
688 webwidget_->resize(new_size);
689 } else if (!resizing_mode_selector_->is_synchronous_mode()) {
690 resize_ack = NO_RESIZE_ACK;
693 webwidget()->resizePinchViewport(gfx::Size(
694 visible_viewport_size.width(),
695 visible_viewport_size.height()));
697 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
698 // For empty size or empty physical_backing_size, there is no next paint
699 // (along with which to send the ack) until they are set to non-empty.
700 resize_ack = NO_RESIZE_ACK;
703 // Send the Resize_ACK flag once we paint again if requested.
704 if (resize_ack == SEND_RESIZE_ACK)
705 set_next_paint_is_resize_ack();
707 if (fullscreen_change)
708 DidToggleFullscreen();
710 // If a resize ack is requested and it isn't set-up, then no more resizes will
711 // come in and in general things will go wrong.
712 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
715 void RenderWidget::ResizeSynchronously(const gfx::Rect& new_position) {
716 Resize(new_position.size(),
717 new_position.size(),
718 top_controls_layout_height_,
719 visible_viewport_size_,
720 gfx::Rect(),
721 is_fullscreen_,
722 NO_RESIZE_ACK);
723 view_screen_rect_ = new_position;
724 window_screen_rect_ = new_position;
725 if (!did_show_)
726 initial_pos_ = new_position;
729 void RenderWidget::OnClose() {
730 if (closing_)
731 return;
732 closing_ = true;
734 // Browser correspondence is no longer needed at this point.
735 if (routing_id_ != MSG_ROUTING_NONE) {
736 if (RenderThreadImpl::current())
737 RenderThreadImpl::current()->WidgetDestroyed();
738 RenderThread::Get()->RemoveRoute(routing_id_);
739 SetHidden(false);
742 // If there is a Send call on the stack, then it could be dangerous to close
743 // now. Post a task that only gets invoked when there are no nested message
744 // loops.
745 base::MessageLoop::current()->PostNonNestableTask(
746 FROM_HERE, base::Bind(&RenderWidget::Close, this));
748 // Balances the AddRef taken when we called AddRoute.
749 Release();
752 // Got a response from the browser after the renderer decided to create a new
753 // view.
754 void RenderWidget::OnCreatingNewAck() {
755 DCHECK(routing_id_ != MSG_ROUTING_NONE);
757 CompleteInit();
760 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
761 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
762 return;
764 if (screen_metrics_emulator_) {
765 screen_metrics_emulator_->OnResizeMessage(params);
766 return;
769 bool orientation_changed =
770 screen_info_.orientationAngle != params.screen_info.orientationAngle;
772 screen_info_ = params.screen_info;
773 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
774 Resize(params.new_size, params.physical_backing_size,
775 params.top_controls_layout_height,
776 params.visible_viewport_size, params.resizer_rect,
777 params.is_fullscreen, SEND_RESIZE_ACK);
779 if (orientation_changed)
780 OnOrientationChange();
783 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
784 if (resizer_rect_ == resizer_rect)
785 return;
786 resizer_rect_ = resizer_rect;
787 if (webwidget_)
788 webwidget_->didChangeWindowResizerRect();
791 void RenderWidget::OnWasHidden() {
792 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
793 // Go into a mode where we stop generating paint and scrolling events.
794 SetHidden(true);
795 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
796 WasHidden());
799 void RenderWidget::OnWasShown(bool needs_repainting,
800 const ui::LatencyInfo& latency_info) {
801 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
802 // During shutdown we can just ignore this message.
803 if (!webwidget_)
804 return;
806 // See OnWasHidden
807 SetHidden(false);
808 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
809 WasShown());
811 if (!needs_repainting)
812 return;
814 // Generate a full repaint.
815 if (compositor_) {
816 ui::LatencyInfo swap_latency_info(latency_info);
817 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
818 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
819 compositor_->SetNeedsForcedRedraw();
821 scheduleComposite();
824 void RenderWidget::OnRequestMoveAck() {
825 DCHECK(pending_window_rect_count_);
826 pending_window_rect_count_--;
829 GURL RenderWidget::GetURLForGraphicsContext3D() {
830 return GURL();
833 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
834 // For widgets that are never visible, we don't start the compositor, so we
835 // never get a request for a cc::OutputSurface.
836 DCHECK(!never_visible_);
838 #if defined(OS_ANDROID)
839 if (SynchronousCompositorFactory* factory =
840 SynchronousCompositorFactory::GetInstance()) {
841 return factory->CreateOutputSurface(routing_id(),
842 frame_swap_message_queue_);
844 #endif
846 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
847 bool use_software = fallback;
848 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
849 use_software = true;
851 scoped_refptr<ContextProviderCommandBuffer> context_provider;
852 if (!use_software) {
853 context_provider = ContextProviderCommandBuffer::Create(
854 CreateGraphicsContext3D(), "RenderCompositor");
855 if (!context_provider.get()) {
856 // Cause the compositor to wait and try again.
857 return scoped_ptr<cc::OutputSurface>();
861 uint32 output_surface_id = next_output_surface_id_++;
862 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
863 DCHECK(IsThreadedCompositingEnabled());
864 return scoped_ptr<cc::OutputSurface>(
865 new DelegatedCompositorOutputSurface(routing_id(),
866 output_surface_id,
867 context_provider,
868 frame_swap_message_queue_));
870 if (!context_provider.get()) {
871 scoped_ptr<cc::SoftwareOutputDevice> software_device(
872 new CompositorSoftwareOutputDevice());
874 return scoped_ptr<cc::OutputSurface>(
875 new CompositorOutputSurface(routing_id(),
876 output_surface_id,
877 NULL,
878 software_device.Pass(),
879 frame_swap_message_queue_,
880 true));
883 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
884 // Composite-to-mailbox is currently used for layout tests in order to cause
885 // them to draw inside in the renderer to do the readback there. This should
886 // no longer be the case when crbug.com/311404 is fixed.
887 DCHECK(IsThreadedCompositingEnabled() ||
888 RenderThreadImpl::current()->layout_test_mode());
889 cc::ResourceFormat format = cc::RGBA_8888;
890 if (base::SysInfo::IsLowEndDevice())
891 format = cc::RGB_565;
892 return scoped_ptr<cc::OutputSurface>(
893 new MailboxOutputSurface(routing_id(),
894 output_surface_id,
895 context_provider,
896 scoped_ptr<cc::SoftwareOutputDevice>(),
897 frame_swap_message_queue_,
898 format));
900 bool use_swap_compositor_frame_message = false;
901 return scoped_ptr<cc::OutputSurface>(
902 new CompositorOutputSurface(routing_id(),
903 output_surface_id,
904 context_provider,
905 scoped_ptr<cc::SoftwareOutputDevice>(),
906 frame_swap_message_queue_,
907 use_swap_compositor_frame_message));
910 void RenderWidget::OnSwapBuffersAborted() {
911 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
912 // Schedule another frame so the compositor learns about it.
913 scheduleComposite();
916 void RenderWidget::OnSwapBuffersPosted() {
917 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
920 void RenderWidget::OnSwapBuffersComplete() {
921 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
923 // Notify subclasses that composited rendering was flushed to the screen.
924 DidFlushPaint();
927 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
928 const ui::LatencyInfo& latency_info,
929 bool is_keyboard_shortcut) {
930 base::AutoReset<bool> handling_input_event_resetter(
931 &handling_input_event_, true);
932 if (!input_event)
933 return;
934 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
935 &handling_event_type_, input_event->type);
936 #if defined(OS_ANDROID)
937 // On Android, when the delete key or forward delete key is pressed using IME,
938 // |AdapterInputConnection| generates input key events to make sure all JS
939 // listeners that monitor KeyUp and KeyDown events receive the proper key
940 // code. Since this input key event comes from IME, we need to set the
941 // IME event guard here to make sure it does not interfere with other IME
942 // events.
943 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
944 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
945 const WebKeyboardEvent& key_event =
946 *static_cast<const WebKeyboardEvent*>(input_event);
947 if (key_event.nativeKeyCode == AKEYCODE_FORWARD_DEL ||
948 key_event.nativeKeyCode == AKEYCODE_DEL) {
949 ime_event_guard_maybe.reset(new ImeEventGuard(this));
952 #endif
954 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
955 &latency_info);
957 base::TimeTicks start_time;
958 if (base::TimeTicks::IsHighResNowFastAndReliable())
959 start_time = base::TimeTicks::HighResNow();
961 const char* const event_name =
962 WebInputEventTraits::GetName(input_event->type);
963 TRACE_EVENT1("renderer", "RenderWidget::OnHandleInputEvent",
964 "event", event_name);
965 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
966 TRACE_EVENT_FLOW_STEP0(
967 "input",
968 "LatencyInfo.Flow",
969 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
970 "HanldeInputEventMain");
972 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
973 ui::LatencyInfo swap_latency_info(latency_info);
974 if (compositor_) {
975 latency_info_swap_promise_monitor =
976 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
977 .Pass();
980 if (base::TimeTicks::IsHighResNowFastAndReliable()) {
981 // If we don't have a high res timer, these metrics won't be accurate enough
982 // to be worth collecting. Note that this does introduce some sampling bias.
984 base::TimeDelta now = base::TimeDelta::FromInternalValue(
985 base::TimeTicks::HighResNow().ToInternalValue());
987 int64 delta =
988 static_cast<int64>((now.InSecondsF() - input_event->timeStampSeconds) *
989 base::Time::kMicrosecondsPerSecond);
991 UMA_HISTOGRAM_CUSTOM_COUNTS(
992 "Event.AggregatedLatency.Renderer2", delta, 1, 10000000, 100);
993 base::HistogramBase* counter_for_type = base::Histogram::FactoryGet(
994 base::StringPrintf("Event.Latency.Renderer2.%s", event_name),
996 10000000,
997 100,
998 base::HistogramBase::kUmaTargetedHistogramFlag);
999 counter_for_type->Add(delta);
1002 bool prevent_default = false;
1003 if (WebInputEvent::isMouseEventType(input_event->type)) {
1004 const WebMouseEvent& mouse_event =
1005 *static_cast<const WebMouseEvent*>(input_event);
1006 TRACE_EVENT2("renderer", "HandleMouseMove",
1007 "x", mouse_event.x, "y", mouse_event.y);
1008 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1009 prevent_default = WillHandleMouseEvent(mouse_event);
1012 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1013 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1014 #if defined(OS_ANDROID)
1015 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1016 // case it should behave like a select key (i.e. causing a click if a button
1017 // is focused). However, if a text field is focused (2), its intended
1018 // behavior is to just show the IME and don't propagate the key.
1019 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1020 // when clicked on an input text field and cause the form submit if clicked
1021 // when the submit button is focused, but not vice-versa.
1022 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1023 // but at this point we have to swallow the event for the scenario (2).
1024 const WebKeyboardEvent& key_event =
1025 *static_cast<const WebKeyboardEvent*>(input_event);
1026 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1027 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1028 OnShowImeIfNeeded();
1029 prevent_default = true;
1031 #endif
1034 if (WebInputEvent::isGestureEventType(input_event->type)) {
1035 const WebGestureEvent& gesture_event =
1036 *static_cast<const WebGestureEvent*>(input_event);
1037 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1038 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1041 bool processed = prevent_default;
1042 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1043 suppress_next_char_events_ = false;
1044 if (!processed && webwidget_)
1045 processed = webwidget_->handleInputEvent(*input_event);
1048 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1049 // it's not processed by webkit, then we need to suppress the upcoming Char
1050 // events.
1051 if (!processed && is_keyboard_shortcut)
1052 suppress_next_char_events_ = true;
1054 InputEventAckState ack_result = processed ?
1055 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1056 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1057 const WebTouchEvent& touch_event =
1058 *static_cast<const WebTouchEvent*>(input_event);
1059 // Hit-test for all the pressed touch points. If there is a touch-handler
1060 // for any of the touch points, then the renderer should continue to receive
1061 // touch events.
1062 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1063 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1064 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1065 HasTouchEventHandlersAt(
1066 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1067 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1068 break;
1073 // Unconsumed touchmove acks should never be throttled as they're required to
1074 // dispatch compositor-handled scroll gestures.
1075 bool event_type_can_be_rate_limited =
1076 input_event->type == WebInputEvent::MouseMove ||
1077 input_event->type == WebInputEvent::MouseWheel ||
1078 (input_event->type == WebInputEvent::TouchMove &&
1079 ack_result == INPUT_EVENT_ACK_STATE_CONSUMED);
1081 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1083 // If we don't have a fast and accurate HighResNow, we assume the input
1084 // handlers are heavy and rate limit them.
1085 bool rate_limiting_wanted = true;
1086 if (base::TimeTicks::IsHighResNowFastAndReliable()) {
1087 base::TimeTicks end_time = base::TimeTicks::HighResNow();
1088 total_input_handling_time_this_frame_ += (end_time - start_time);
1089 rate_limiting_wanted =
1090 total_input_handling_time_this_frame_.InMicroseconds() >
1091 kInputHandlingTimeThrottlingThresholdMicroseconds;
1094 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1096 // Note that we can't use handling_event_type_ here since it will be overriden
1097 // by reentrant calls for events after the paused one.
1098 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1099 input_event->type == WebInputEvent::MouseMove;
1100 if (!WebInputEventTraits::IgnoresAckDisposition(*input_event) && !no_ack) {
1101 InputHostMsg_HandleInputEvent_ACK_Params ack;
1102 ack.type = input_event->type;
1103 ack.state = ack_result;
1104 ack.latency = swap_latency_info;
1105 scoped_ptr<IPC::Message> response(
1106 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1107 if (rate_limiting_wanted && event_type_can_be_rate_limited &&
1108 frame_pending && !is_hidden_) {
1109 // We want to rate limit the input events in this case, so we'll wait for
1110 // painting to finish before ACKing this message.
1111 TRACE_EVENT_INSTANT0("renderer",
1112 "RenderWidget::OnHandleInputEvent ack throttled",
1113 TRACE_EVENT_SCOPE_THREAD);
1114 if (pending_input_event_ack_) {
1115 // As two different kinds of events could cause us to postpone an ack
1116 // we send it now, if we have one pending. The Browser should never
1117 // send us the same kind of event we are delaying the ack for.
1118 Send(pending_input_event_ack_.release());
1120 pending_input_event_ack_ = response.Pass();
1121 if (compositor_)
1122 compositor_->NotifyInputThrottledUntilCommit();
1123 } else {
1124 Send(response.release());
1127 if (input_event->type == WebInputEvent::MouseMove)
1128 ignore_ack_for_mouse_move_from_debugger_ = false;
1130 #if defined(OS_ANDROID)
1131 // Allow the IME to be shown when the focus changes as a consequence
1132 // of a processed touch end event.
1133 if (input_event->type == WebInputEvent::TouchEnd && processed)
1134 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1135 #elif defined(USE_AURA)
1136 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1137 // change.
1138 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1139 input_event->type == WebInputEvent::MouseUp))
1140 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1141 #endif
1143 if (!prevent_default) {
1144 if (WebInputEvent::isKeyboardEventType(input_event->type))
1145 DidHandleKeyEvent();
1146 if (WebInputEvent::isMouseEventType(input_event->type))
1147 DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1148 if (WebInputEvent::isTouchEventType(input_event->type))
1149 DidHandleTouchEvent(*(static_cast<const WebTouchEvent*>(input_event)));
1153 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1154 if (webwidget_)
1155 webwidget_->setCursorVisibilityState(is_visible);
1158 void RenderWidget::OnMouseCaptureLost() {
1159 if (webwidget_)
1160 webwidget_->mouseCaptureLost();
1163 void RenderWidget::OnSetFocus(bool enable) {
1164 has_focus_ = enable;
1165 if (webwidget_)
1166 webwidget_->setFocus(enable);
1169 void RenderWidget::ClearFocus() {
1170 // We may have got the focus from the browser before this gets processed, in
1171 // which case we do not want to unfocus ourself.
1172 if (!has_focus_ && webwidget_)
1173 webwidget_->setFocus(false);
1176 void RenderWidget::FlushPendingInputEventAck() {
1177 if (pending_input_event_ack_)
1178 Send(pending_input_event_ack_.release());
1179 total_input_handling_time_this_frame_ = base::TimeDelta();
1182 ///////////////////////////////////////////////////////////////////////////////
1183 // WebWidgetClient
1185 void RenderWidget::didAutoResize(const WebSize& new_size) {
1186 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1187 size_ = new_size;
1189 if (resizing_mode_selector_->is_synchronous_mode()) {
1190 WebRect new_pos(rootWindowRect().x,
1191 rootWindowRect().y,
1192 new_size.width,
1193 new_size.height);
1194 view_screen_rect_ = new_pos;
1195 window_screen_rect_ = new_pos;
1198 AutoResizeCompositor();
1200 if (!resizing_mode_selector_->is_synchronous_mode())
1201 need_update_rect_for_auto_resize_ = true;
1205 void RenderWidget::AutoResizeCompositor() {
1206 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1207 device_scale_factor_));
1208 if (compositor_)
1209 compositor_->setViewportSize(size_, physical_backing_size_);
1212 void RenderWidget::initializeLayerTreeView() {
1213 DCHECK(!host_closing_);
1215 compositor_ =
1216 RenderWidgetCompositor::Create(this, IsThreadedCompositingEnabled());
1217 compositor_->setViewportSize(size_, physical_backing_size_);
1218 if (init_complete_)
1219 StartCompositor();
1222 void RenderWidget::DestroyLayerTreeView() {
1223 // Always send this notification to prevent new layer tree views from
1224 // being created, even if one hasn't been created yet.
1225 if (webwidget_)
1226 webwidget_->willCloseLayerTreeView();
1227 compositor_.reset();
1230 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1231 return compositor_.get();
1234 void RenderWidget::willBeginCompositorFrame() {
1235 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1237 // The following two can result in further layout and possibly
1238 // enable GPU acceleration so they need to be called before any painting
1239 // is done.
1240 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1241 UpdateSelectionBounds();
1244 void RenderWidget::didBecomeReadyForAdditionalInput() {
1245 TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1246 FlushPendingInputEventAck();
1249 void RenderWidget::DidCommitCompositorFrame() {
1250 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1251 DidCommitCompositorFrame());
1252 #if defined(VIDEO_HOLE)
1253 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1254 DidCommitCompositorFrame());
1255 #endif // defined(VIDEO_HOLE)
1258 // static
1259 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1260 IPC::Message* msg,
1261 MessageDeliveryPolicy policy,
1262 FrameSwapMessageQueue* frame_swap_message_queue,
1263 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1264 bool commit_requested,
1265 int source_frame_number) {
1266 if (policy == MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE &&
1267 // No need for lock: this gets changed only on this thread.
1268 !commit_requested &&
1269 // No need for lock: Messages are only enqueued from this thread, if we
1270 // don't have any now, no other thread will add any.
1271 frame_swap_message_queue->Empty()) {
1272 sync_message_filter->Send(msg);
1273 return scoped_ptr<cc::SwapPromise>();
1276 bool first_message_for_frame = false;
1277 frame_swap_message_queue->QueueMessageForFrame(policy,
1278 source_frame_number,
1279 make_scoped_ptr(msg),
1280 &first_message_for_frame);
1281 if (first_message_for_frame) {
1282 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1283 sync_message_filter, frame_swap_message_queue, source_frame_number));
1284 return promise.PassAs<cc::SwapPromise>();
1286 return scoped_ptr<cc::SwapPromise>();
1289 void RenderWidget::QueueMessage(IPC::Message* msg,
1290 MessageDeliveryPolicy policy) {
1291 // RenderThreadImpl::current() is NULL in some tests.
1292 if (!compositor_ || !RenderThreadImpl::current()) {
1293 Send(msg);
1294 return;
1297 scoped_ptr<cc::SwapPromise> swap_promise =
1298 QueueMessageImpl(msg,
1299 policy,
1300 frame_swap_message_queue_.get(),
1301 RenderThreadImpl::current()->sync_message_filter(),
1302 compositor_->commitRequested(),
1303 compositor_->GetSourceFrameNumber());
1305 if (swap_promise) {
1306 compositor_->QueueSwapPromise(swap_promise.Pass());
1307 compositor_->SetNeedsCommit();
1311 void RenderWidget::didCommitAndDrawCompositorFrame() {
1312 // NOTE: Tests may break if this event is renamed or moved. See
1313 // tab_capture_performancetest.cc.
1314 TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1315 // Notify subclasses that we initiated the paint operation.
1316 DidInitiatePaint();
1319 void RenderWidget::didCompleteSwapBuffers() {
1320 TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
1322 // Notify subclasses threaded composited rendering was flushed to the screen.
1323 DidFlushPaint();
1325 if (!next_paint_flags_ &&
1326 !need_update_rect_for_auto_resize_ &&
1327 !plugin_window_moves_.size()) {
1328 return;
1331 ViewHostMsg_UpdateRect_Params params;
1332 params.view_size = size_;
1333 params.plugin_window_moves.swap(plugin_window_moves_);
1334 params.flags = next_paint_flags_;
1335 params.scroll_offset = GetScrollOffset();
1336 params.scale_factor = device_scale_factor_;
1338 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1339 next_paint_flags_ = 0;
1340 need_update_rect_for_auto_resize_ = false;
1343 void RenderWidget::scheduleComposite() {
1344 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1345 // render_thread may be NULL in tests.
1346 if (render_thread && render_thread->compositor_message_loop_proxy().get() &&
1347 compositor_) {
1348 compositor_->setNeedsAnimate();
1352 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1353 // TODO(darin): Eliminate this temporary.
1354 WebCursor cursor;
1355 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1356 // Only send a SetCursor message if we need to make a change.
1357 if (!current_cursor_.IsEqual(cursor)) {
1358 current_cursor_ = cursor;
1359 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1363 // We are supposed to get a single call to Show for a newly created RenderWidget
1364 // that was created via RenderWidget::CreateWebView. So, we wait until this
1365 // point to dispatch the ShowWidget message.
1367 // This method provides us with the information about how to display the newly
1368 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1370 void RenderWidget::show(WebNavigationPolicy) {
1371 DCHECK(!did_show_) << "received extraneous Show call";
1372 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1373 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1375 if (did_show_)
1376 return;
1378 did_show_ = true;
1379 // NOTE: initial_pos_ may still have its default values at this point, but
1380 // that's okay. It'll be ignored if as_popup is false, or the browser
1381 // process will impose a default position otherwise.
1382 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_pos_));
1383 SetPendingWindowRect(initial_pos_);
1386 void RenderWidget::didFocus() {
1389 void RenderWidget::didBlur() {
1392 void RenderWidget::DoDeferredClose() {
1393 // No more compositing is possible. This prevents shutdown races between
1394 // previously posted CreateOutputSurface tasks and the host being unable to
1395 // create them because the close message was handled.
1396 DestroyLayerTreeView();
1397 // Also prevent new compositors from being created.
1398 host_closing_ = true;
1399 Send(new ViewHostMsg_Close(routing_id_));
1402 void RenderWidget::closeWidgetSoon() {
1403 if (is_swapped_out_) {
1404 // This widget is currently swapped out, and the active widget is in a
1405 // different process. Have the browser route the close request to the
1406 // active widget instead, so that the correct unload handlers are run.
1407 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1408 return;
1411 // If a page calls window.close() twice, we'll end up here twice, but that's
1412 // OK. It is safe to send multiple Close messages.
1414 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1415 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1416 // could be closed before the JS finishes executing. So instead, post a
1417 // message back to the message loop, which won't run until the JS is
1418 // complete, and then the Close message can be sent.
1419 base::MessageLoop::current()->PostTask(
1420 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1423 void RenderWidget::QueueSyntheticGesture(
1424 scoped_ptr<SyntheticGestureParams> gesture_params,
1425 const SyntheticGestureCompletionCallback& callback) {
1426 DCHECK(!callback.is_null());
1428 pending_synthetic_gesture_callbacks_.push(callback);
1430 SyntheticGesturePacket gesture_packet;
1431 gesture_packet.set_gesture_params(gesture_params.Pass());
1433 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1436 void RenderWidget::Close() {
1437 screen_metrics_emulator_.reset();
1438 DestroyLayerTreeView();
1439 if (webwidget_) {
1440 webwidget_->close();
1441 webwidget_ = NULL;
1445 WebRect RenderWidget::windowRect() {
1446 if (pending_window_rect_count_)
1447 return pending_window_rect_;
1449 return view_screen_rect_;
1452 void RenderWidget::setToolTipText(const blink::WebString& text,
1453 WebTextDirection hint) {
1454 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1457 void RenderWidget::setWindowRect(const WebRect& rect) {
1458 WebRect pos = rect;
1459 if (popup_origin_scale_for_emulation_) {
1460 float scale = popup_origin_scale_for_emulation_;
1461 pos.x = popup_screen_origin_for_emulation_.x() +
1462 (pos.x - popup_view_origin_for_emulation_.x()) * scale;
1463 pos.y = popup_screen_origin_for_emulation_.y() +
1464 (pos.y - popup_view_origin_for_emulation_.y()) * scale;
1467 if (!resizing_mode_selector_->is_synchronous_mode()) {
1468 if (did_show_) {
1469 Send(new ViewHostMsg_RequestMove(routing_id_, pos));
1470 SetPendingWindowRect(pos);
1471 } else {
1472 initial_pos_ = pos;
1474 } else {
1475 ResizeSynchronously(pos);
1479 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1480 pending_window_rect_ = rect;
1481 pending_window_rect_count_++;
1484 WebRect RenderWidget::rootWindowRect() {
1485 if (pending_window_rect_count_) {
1486 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1487 // the RootWindowRect is probably going to return wrong results since the
1488 // browser may not have processed the Move yet. There isn't really anything
1489 // good to do in this case, and it shouldn't happen - since this size is
1490 // only really needed for windowToScreen, which is only used for Popups.
1491 return pending_window_rect_;
1494 return window_screen_rect_;
1497 WebRect RenderWidget::windowResizerRect() {
1498 return resizer_rect_;
1501 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1502 // To prevent this renderer process from sending unnecessary IPC messages to
1503 // a browser process, we permit the renderer process to send IPC messages
1504 // only during the input method attached to the browser process is active.
1505 input_method_is_active_ = is_active;
1508 void RenderWidget::OnCandidateWindowShown() {
1509 webwidget_->didShowCandidateWindow();
1512 void RenderWidget::OnCandidateWindowUpdated() {
1513 webwidget_->didUpdateCandidateWindow();
1516 void RenderWidget::OnCandidateWindowHidden() {
1517 webwidget_->didHideCandidateWindow();
1520 void RenderWidget::OnImeSetComposition(
1521 const base::string16& text,
1522 const std::vector<WebCompositionUnderline>& underlines,
1523 int selection_start, int selection_end) {
1524 if (!ShouldHandleImeEvent())
1525 return;
1526 ImeEventGuard guard(this);
1527 if (!webwidget_->setComposition(
1528 text, WebVector<WebCompositionUnderline>(underlines),
1529 selection_start, selection_end)) {
1530 // If we failed to set the composition text, then we need to let the browser
1531 // process to cancel the input method's ongoing composition session, to make
1532 // sure we are in a consistent state.
1533 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1535 #if defined(OS_MACOSX) || defined(USE_AURA)
1536 UpdateCompositionInfo(true);
1537 #endif
1540 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1541 const gfx::Range& replacement_range,
1542 bool keep_selection) {
1543 if (!ShouldHandleImeEvent())
1544 return;
1545 ImeEventGuard guard(this);
1546 handling_input_event_ = true;
1547 if (text.length())
1548 webwidget_->confirmComposition(text);
1549 else if (keep_selection)
1550 webwidget_->confirmComposition(WebWidget::KeepSelection);
1551 else
1552 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1553 handling_input_event_ = false;
1554 #if defined(OS_MACOSX) || defined(USE_AURA)
1555 UpdateCompositionInfo(true);
1556 #endif
1559 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1560 // During shutdown we can just ignore this message.
1561 if (!webwidget_)
1562 return;
1564 // Even if the browser provides an empty damage rect, it's still expecting to
1565 // receive a repaint ack so just damage the entire widget bounds.
1566 if (size_to_paint.IsEmpty()) {
1567 size_to_paint = size_;
1570 set_next_paint_is_repaint_ack();
1571 if (compositor_)
1572 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1575 void RenderWidget::OnSyntheticGestureCompleted() {
1576 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1578 pending_synthetic_gesture_callbacks_.front().Run();
1579 pending_synthetic_gesture_callbacks_.pop();
1582 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1583 if (!webwidget_)
1584 return;
1585 webwidget_->setTextDirection(direction);
1588 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1589 const gfx::Rect& window_screen_rect) {
1590 if (screen_metrics_emulator_) {
1591 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1592 view_screen_rect, window_screen_rect);
1593 } else {
1594 view_screen_rect_ = view_screen_rect;
1595 window_screen_rect_ = window_screen_rect;
1597 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1600 void RenderWidget::showImeIfNeeded() {
1601 OnShowImeIfNeeded();
1604 void RenderWidget::OnShowImeIfNeeded() {
1605 #if defined(OS_ANDROID) || defined(USE_AURA)
1606 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1607 #endif
1610 #if defined(OS_ANDROID)
1611 void RenderWidget::IncrementOutstandingImeEventAcks() {
1612 ++outstanding_ime_acks_;
1615 void RenderWidget::OnImeEventAck() {
1616 --outstanding_ime_acks_;
1617 DCHECK(outstanding_ime_acks_ >= 0);
1619 #endif
1621 bool RenderWidget::ShouldHandleImeEvent() {
1622 #if defined(OS_ANDROID)
1623 return !!webwidget_ && outstanding_ime_acks_ == 0;
1624 #else
1625 return !!webwidget_;
1626 #endif
1629 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1630 if (handling_event_type_ == WebInputEvent::MouseMove) {
1631 // If we pause multiple times during a single mouse move event, we should
1632 // only send ACK once.
1633 if (!ignore_ack_for_mouse_move_from_debugger_) {
1634 InputHostMsg_HandleInputEvent_ACK_Params ack;
1635 ack.type = handling_event_type_;
1636 ack.state = INPUT_EVENT_ACK_STATE_CONSUMED;
1637 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1639 return true;
1641 return false;
1644 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1645 ignore_ack_for_mouse_move_from_debugger_ = true;
1648 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1649 if (device_scale_factor_ == device_scale_factor)
1650 return;
1652 device_scale_factor_ = device_scale_factor;
1653 scheduleComposite();
1656 bool RenderWidget::SetDeviceColorProfile(
1657 const std::vector<char>& color_profile) {
1658 if (device_color_profile_ == color_profile)
1659 return false;
1661 device_color_profile_ = color_profile;
1662 return true;
1665 void RenderWidget::OnOrientationChange() {
1668 gfx::Vector2d RenderWidget::GetScrollOffset() {
1669 // Bare RenderWidgets don't support scroll offset.
1670 return gfx::Vector2d();
1673 void RenderWidget::SetHidden(bool hidden) {
1674 if (is_hidden_ == hidden)
1675 return;
1677 // The status has changed. Tell the RenderThread about it.
1678 is_hidden_ = hidden;
1679 if (is_hidden_)
1680 RenderThreadImpl::current()->WidgetHidden();
1681 else
1682 RenderThreadImpl::current()->WidgetRestored();
1685 void RenderWidget::WillToggleFullscreen() {
1686 if (!webwidget_)
1687 return;
1689 if (is_fullscreen_) {
1690 webwidget_->willExitFullScreen();
1691 } else {
1692 webwidget_->willEnterFullScreen();
1696 void RenderWidget::DidToggleFullscreen() {
1697 if (!webwidget_)
1698 return;
1700 if (is_fullscreen_) {
1701 webwidget_->didEnterFullScreen();
1702 } else {
1703 webwidget_->didExitFullScreen();
1707 bool RenderWidget::next_paint_is_resize_ack() const {
1708 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1711 void RenderWidget::set_next_paint_is_resize_ack() {
1712 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1715 void RenderWidget::set_next_paint_is_repaint_ack() {
1716 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1719 static bool IsDateTimeInput(ui::TextInputType type) {
1720 return type == ui::TEXT_INPUT_TYPE_DATE ||
1721 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1722 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1723 type == ui::TEXT_INPUT_TYPE_MONTH ||
1724 type == ui::TEXT_INPUT_TYPE_TIME ||
1725 type == ui::TEXT_INPUT_TYPE_WEEK;
1729 void RenderWidget::StartHandlingImeEvent() {
1730 DCHECK(!handling_ime_event_);
1731 handling_ime_event_ = true;
1734 void RenderWidget::FinishHandlingImeEvent() {
1735 DCHECK(handling_ime_event_);
1736 handling_ime_event_ = false;
1737 // While handling an ime event, text input state and selection bounds updates
1738 // are ignored. These must explicitly be updated once finished handling the
1739 // ime event.
1740 UpdateSelectionBounds();
1741 #if defined(OS_ANDROID)
1742 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1743 #endif
1746 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1747 ChangeSource change_source) {
1748 if (handling_ime_event_)
1749 return;
1750 if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1751 return;
1752 ui::TextInputType new_type = GetTextInputType();
1753 if (IsDateTimeInput(new_type))
1754 return; // Not considered as a text input field in WebKit/Chromium.
1756 blink::WebTextInputInfo new_info;
1757 if (webwidget_)
1758 new_info = webwidget_->textInputInfo();
1759 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1761 bool new_can_compose_inline = CanComposeInline();
1763 // Only sends text input params if they are changed or if the ime should be
1764 // shown.
1765 if (show_ime == SHOW_IME_IF_NEEDED ||
1766 (text_input_type_ != new_type ||
1767 text_input_mode_ != new_mode ||
1768 text_input_info_ != new_info ||
1769 can_compose_inline_ != new_can_compose_inline)
1770 #if defined(OS_ANDROID)
1771 || text_field_is_dirty_
1772 #endif
1774 ViewHostMsg_TextInputState_Params p;
1775 p.type = new_type;
1776 p.flags = new_info.flags;
1777 p.mode = new_mode;
1778 p.value = new_info.value.utf8();
1779 p.selection_start = new_info.selectionStart;
1780 p.selection_end = new_info.selectionEnd;
1781 p.composition_start = new_info.compositionStart;
1782 p.composition_end = new_info.compositionEnd;
1783 p.can_compose_inline = new_can_compose_inline;
1784 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1785 #if defined(USE_AURA)
1786 p.is_non_ime_change = true;
1787 #endif
1788 #if defined(OS_ANDROID)
1789 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1790 text_field_is_dirty_;
1791 if (p.is_non_ime_change)
1792 IncrementOutstandingImeEventAcks();
1793 text_field_is_dirty_ = false;
1794 #endif
1795 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
1797 text_input_info_ = new_info;
1798 text_input_type_ = new_type;
1799 text_input_mode_ = new_mode;
1800 can_compose_inline_ = new_can_compose_inline;
1804 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1805 WebRect focus_webrect;
1806 WebRect anchor_webrect;
1807 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1808 *focus = focus_webrect;
1809 *anchor = anchor_webrect;
1812 void RenderWidget::UpdateSelectionBounds() {
1813 if (!webwidget_)
1814 return;
1815 if (handling_ime_event_)
1816 return;
1818 ViewHostMsg_SelectionBounds_Params params;
1819 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
1820 if (selection_anchor_rect_ != params.anchor_rect ||
1821 selection_focus_rect_ != params.focus_rect) {
1822 selection_anchor_rect_ = params.anchor_rect;
1823 selection_focus_rect_ = params.focus_rect;
1824 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
1825 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
1826 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
1828 #if defined(OS_MACOSX) || defined(USE_AURA)
1829 UpdateCompositionInfo(false);
1830 #endif
1833 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
1834 COMPILE_ASSERT(int(blink::WebTextInputTypeNone) == \
1835 int(ui::TEXT_INPUT_TYPE_NONE), mismatching_enums);
1836 COMPILE_ASSERT(int(blink::WebTextInputTypeText) == \
1837 int(ui::TEXT_INPUT_TYPE_TEXT), mismatching_enums);
1838 COMPILE_ASSERT(int(blink::WebTextInputTypePassword) == \
1839 int(ui::TEXT_INPUT_TYPE_PASSWORD), mismatching_enums);
1840 COMPILE_ASSERT(int(blink::WebTextInputTypeSearch) == \
1841 int(ui::TEXT_INPUT_TYPE_SEARCH), mismatching_enums);
1842 COMPILE_ASSERT(int(blink::WebTextInputTypeEmail) == \
1843 int(ui::TEXT_INPUT_TYPE_EMAIL), mismatching_enums);
1844 COMPILE_ASSERT(int(blink::WebTextInputTypeNumber) == \
1845 int(ui::TEXT_INPUT_TYPE_NUMBER), mismatching_enums);
1846 COMPILE_ASSERT(int(blink::WebTextInputTypeTelephone) == \
1847 int(ui::TEXT_INPUT_TYPE_TELEPHONE), mismatching_enums);
1848 COMPILE_ASSERT(int(blink::WebTextInputTypeURL) == \
1849 int(ui::TEXT_INPUT_TYPE_URL), mismatching_enums);
1850 COMPILE_ASSERT(int(blink::WebTextInputTypeDate) == \
1851 int(ui::TEXT_INPUT_TYPE_DATE), mismatching_enum);
1852 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTime) == \
1853 int(ui::TEXT_INPUT_TYPE_DATE_TIME), mismatching_enum);
1854 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeLocal) == \
1855 int(ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL), mismatching_enum);
1856 COMPILE_ASSERT(int(blink::WebTextInputTypeMonth) == \
1857 int(ui::TEXT_INPUT_TYPE_MONTH), mismatching_enum);
1858 COMPILE_ASSERT(int(blink::WebTextInputTypeTime) == \
1859 int(ui::TEXT_INPUT_TYPE_TIME), mismatching_enum);
1860 COMPILE_ASSERT(int(blink::WebTextInputTypeWeek) == \
1861 int(ui::TEXT_INPUT_TYPE_WEEK), mismatching_enum);
1862 COMPILE_ASSERT(int(blink::WebTextInputTypeTextArea) == \
1863 int(ui::TEXT_INPUT_TYPE_TEXT_AREA), mismatching_enums);
1864 COMPILE_ASSERT(int(blink::WebTextInputTypeContentEditable) == \
1865 int(ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE), mismatching_enums);
1866 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeField) == \
1867 int(ui::TEXT_INPUT_TYPE_DATE_TIME_FIELD), mismatching_enums);
1869 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
1870 blink::WebTextInputType type) {
1871 // Check the type is in the range representable by ui::TextInputType.
1872 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
1873 "blink::WebTextInputType and ui::TextInputType not synchronized";
1874 return static_cast<ui::TextInputType>(type);
1877 ui::TextInputType RenderWidget::GetTextInputType() {
1878 if (webwidget_)
1879 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
1880 return ui::TEXT_INPUT_TYPE_NONE;
1883 #if defined(OS_MACOSX) || defined(USE_AURA)
1884 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
1885 gfx::Range range = gfx::Range();
1886 if (should_update_range) {
1887 GetCompositionRange(&range);
1888 } else {
1889 range = composition_range_;
1891 std::vector<gfx::Rect> character_bounds;
1892 GetCompositionCharacterBounds(&character_bounds);
1894 if (!ShouldUpdateCompositionInfo(range, character_bounds))
1895 return;
1896 composition_character_bounds_ = character_bounds;
1897 composition_range_ = range;
1898 Send(new InputHostMsg_ImeCompositionRangeChanged(
1899 routing_id(), composition_range_, composition_character_bounds_));
1902 void RenderWidget::GetCompositionCharacterBounds(
1903 std::vector<gfx::Rect>* bounds) {
1904 DCHECK(bounds);
1905 bounds->clear();
1908 void RenderWidget::GetCompositionRange(gfx::Range* range) {
1909 size_t location, length;
1910 if (webwidget_->compositionRange(&location, &length)) {
1911 range->set_start(location);
1912 range->set_end(location + length);
1913 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
1914 range->set_start(location);
1915 range->set_end(location + length);
1916 } else {
1917 *range = gfx::Range::InvalidRange();
1921 bool RenderWidget::ShouldUpdateCompositionInfo(
1922 const gfx::Range& range,
1923 const std::vector<gfx::Rect>& bounds) {
1924 if (composition_range_ != range)
1925 return true;
1926 if (bounds.size() != composition_character_bounds_.size())
1927 return true;
1928 for (size_t i = 0; i < bounds.size(); ++i) {
1929 if (bounds[i] != composition_character_bounds_[i])
1930 return true;
1932 return false;
1934 #endif
1936 #if defined(OS_ANDROID)
1937 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
1938 // If not initialized, default to white. Note that 0 is different from black
1939 // as black still has alpha 0xFF.
1940 if (!bg_color)
1941 bg_color = SK_ColorWHITE;
1943 if (bg_color != body_background_color_) {
1944 body_background_color_ = bg_color;
1945 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
1948 #endif
1950 bool RenderWidget::CanComposeInline() {
1951 return true;
1954 WebScreenInfo RenderWidget::screenInfo() {
1955 return screen_info_;
1958 float RenderWidget::deviceScaleFactor() {
1959 return device_scale_factor_;
1962 void RenderWidget::resetInputMethod() {
1963 if (!input_method_is_active_)
1964 return;
1966 ImeEventGuard guard(this);
1967 // If the last text input type is not None, then we should finish any
1968 // ongoing composition regardless of the new text input type.
1969 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
1970 // If a composition text exists, then we need to let the browser process
1971 // to cancel the input method's ongoing composition session.
1972 if (webwidget_->confirmComposition())
1973 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1976 #if defined(OS_MACOSX) || defined(USE_AURA)
1977 UpdateCompositionInfo(true);
1978 #endif
1981 void RenderWidget::didHandleGestureEvent(
1982 const WebGestureEvent& event,
1983 bool event_cancelled) {
1984 #if defined(OS_ANDROID) || defined(USE_AURA)
1985 if (event_cancelled)
1986 return;
1987 if (event.type == WebInputEvent::GestureTap) {
1988 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1989 } else if (event.type == WebInputEvent::GestureLongPress) {
1990 DCHECK(webwidget_);
1991 if (webwidget_->textInputInfo().value.isEmpty())
1992 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1993 else
1994 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1996 #endif
1999 void RenderWidget::StartCompositor() {
2000 // For widgets that are never visible, we don't need the compositor to run
2001 // at all.
2002 if (never_visible_)
2003 return;
2004 compositor_->setSurfaceReady();
2007 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2008 size_t i = 0;
2009 for (; i < plugin_window_moves_.size(); ++i) {
2010 if (plugin_window_moves_[i].window == move.window) {
2011 if (move.rects_valid) {
2012 plugin_window_moves_[i] = move;
2013 } else {
2014 plugin_window_moves_[i].visible = move.visible;
2016 break;
2020 if (i == plugin_window_moves_.size())
2021 plugin_window_moves_.push_back(move);
2024 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2025 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2026 i != plugin_window_moves_.end(); ++i) {
2027 if (i->window == window) {
2028 plugin_window_moves_.erase(i);
2029 break;
2035 RenderWidgetCompositor* RenderWidget::compositor() const {
2036 return compositor_.get();
2039 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2040 return false;
2043 bool RenderWidget::WillHandleGestureEvent(
2044 const blink::WebGestureEvent& event) {
2045 return false;
2048 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2049 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2052 void RenderWidget::setTouchAction(
2053 blink::WebTouchAction web_touch_action) {
2055 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2056 // when blink is emulating touch with mouse).
2057 if (handling_event_type_ != WebInputEvent::TouchStart)
2058 return;
2060 // Verify the same values are used by the types so we can cast between them.
2061 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_AUTO) ==
2062 blink::WebTouchActionAuto,
2063 enum_values_must_match_for_touch_action);
2064 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_NONE) ==
2065 blink::WebTouchActionNone,
2066 enum_values_must_match_for_touch_action);
2067 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_X) ==
2068 blink::WebTouchActionPanX,
2069 enum_values_must_match_for_touch_action);
2070 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_Y) ==
2071 blink::WebTouchActionPanY,
2072 enum_values_must_match_for_touch_action);
2073 COMPILE_ASSERT(
2074 static_cast<blink::WebTouchAction>(TOUCH_ACTION_PINCH_ZOOM) ==
2075 blink::WebTouchActionPinchZoom,
2076 enum_values_must_match_for_touch_action);
2078 content::TouchAction content_touch_action =
2079 static_cast<content::TouchAction>(web_touch_action);
2080 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2083 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2084 #if defined(OS_ANDROID)
2085 text_field_is_dirty_ = true;
2086 #endif
2089 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2090 return true;
2093 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2094 RenderWidget::CreateGraphicsContext3D() {
2095 if (!webwidget_)
2096 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2097 if (CommandLine::ForCurrentProcess()->HasSwitch(
2098 switches::kDisableGpuCompositing))
2099 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2100 if (!RenderThreadImpl::current())
2101 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2102 CauseForGpuLaunch cause =
2103 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2104 scoped_refptr<GpuChannelHost> gpu_channel_host(
2105 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2106 if (!gpu_channel_host.get())
2107 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2109 // Explicitly disable antialiasing for the compositor. As of the time of
2110 // this writing, the only platform that supported antialiasing for the
2111 // compositor was Mac OS X, because the on-screen OpenGL context creation
2112 // code paths on Windows and Linux didn't yet have multisampling support.
2113 // Mac OS X essentially always behaves as though it's rendering offscreen.
2114 // Multisampling has a heavy cost especially on devices with relatively low
2115 // fill rate like most notebooks, and the Mac implementation would need to
2116 // be optimized to resolve directly into the IOSurface shared between the
2117 // GPU and browser processes. For these reasons and to avoid platform
2118 // disparities we explicitly disable antialiasing.
2119 blink::WebGraphicsContext3D::Attributes attributes;
2120 attributes.antialias = false;
2121 attributes.shareResources = true;
2122 attributes.noAutomaticFlushes = true;
2123 attributes.depth = false;
2124 attributes.stencil = false;
2125 bool lose_context_when_out_of_memory = true;
2126 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2127 #if defined(OS_ANDROID)
2128 // If we raster too fast we become upload bound, and pending
2129 // uploads consume memory. For maximum upload throughput, we would
2130 // want to allow for upload_throughput * pipeline_time of pending
2131 // uploads, after which we are just wasting memory. Since we don't
2132 // know our upload throughput yet, this just caps our memory usage.
2133 size_t divider = 1;
2134 if (base::SysInfo::IsLowEndDevice())
2135 divider = 6;
2136 // For reference Nexus10 can upload 1MB in about 2.5ms.
2137 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2138 // Deadline to draw a frame to achieve 60 frames per second.
2139 const size_t kMillisecondsPerFrame = 16;
2140 // Assuming a two frame deep pipeline between the CPU and the GPU.
2141 size_t max_transfer_buffer_usage_mb =
2142 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2143 static const size_t kBytesPerMegabyte = 1024 * 1024;
2144 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2145 // to avoid unnecessarily stalling the compositor thread.
2146 limits.mapped_memory_reclaim_limit =
2147 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2148 #endif
2150 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2151 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2152 GetURLForGraphicsContext3D(),
2153 gpu_channel_host.get(),
2154 attributes,
2155 lose_context_when_out_of_memory,
2156 limits,
2157 NULL));
2158 return context.Pass();
2161 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2162 render_frame_proxies_.AddObserver(proxy);
2165 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2166 render_frame_proxies_.RemoveObserver(proxy);
2169 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2170 render_frames_.AddObserver(frame);
2173 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2174 render_frames_.RemoveObserver(frame);
2177 #if defined(VIDEO_HOLE)
2178 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2179 video_hole_frames_.AddObserver(frame);
2182 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2183 video_hole_frames_.RemoveObserver(frame);
2185 #endif // defined(VIDEO_HOLE)
2187 } // namespace content