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"
8 #include "base/command_line.h"
9 #include "base/debug/trace_event.h"
10 #include "base/debug/trace_event_synthetic_delay.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/singleton.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/histogram.h"
16 #include "base/stl_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "build/build_config.h"
19 #include "cc/base/switches.h"
20 #include "cc/debug/benchmark_instrumentation.h"
21 #include "cc/output/output_surface.h"
22 #include "cc/trees/layer_tree_host.h"
23 #include "content/child/npapi/webplugin.h"
24 #include "content/common/gpu/client/context_provider_command_buffer.h"
25 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
26 #include "content/common/gpu/gpu_process_launch_causes.h"
27 #include "content/common/input/synthetic_gesture_packet.h"
28 #include "content/common/input/web_input_event_traits.h"
29 #include "content/common/input_messages.h"
30 #include "content/common/swapped_out_messages.h"
31 #include "content/common/view_messages.h"
32 #include "content/public/common/content_switches.h"
33 #include "content/public/common/context_menu_params.h"
34 #include "content/renderer/cursor_utils.h"
35 #include "content/renderer/external_popup_menu.h"
36 #include "content/renderer/gpu/compositor_output_surface.h"
37 #include "content/renderer/gpu/compositor_software_output_device.h"
38 #include "content/renderer/gpu/delegated_compositor_output_surface.h"
39 #include "content/renderer/gpu/mailbox_output_surface.h"
40 #include "content/renderer/gpu/render_widget_compositor.h"
41 #include "content/renderer/ime_event_guard.h"
42 #include "content/renderer/input/input_handler_manager.h"
43 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
44 #include "content/renderer/render_frame_impl.h"
45 #include "content/renderer/render_process.h"
46 #include "content/renderer/render_thread_impl.h"
47 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
48 #include "content/renderer/resizing_mode_selector.h"
49 #include "ipc/ipc_sync_message.h"
50 #include "skia/ext/platform_canvas.h"
51 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
52 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
53 #include "third_party/WebKit/public/platform/WebRect.h"
54 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
55 #include "third_party/WebKit/public/platform/WebSize.h"
56 #include "third_party/WebKit/public/platform/WebString.h"
57 #include "third_party/WebKit/public/web/WebPagePopup.h"
58 #include "third_party/WebKit/public/web/WebPopupMenu.h"
59 #include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
60 #include "third_party/WebKit/public/web/WebRange.h"
61 #include "third_party/skia/include/core/SkShader.h"
62 #include "ui/base/ui_base_switches.h"
63 #include "ui/gfx/frame_time.h"
64 #include "ui/gfx/point_conversions.h"
65 #include "ui/gfx/rect_conversions.h"
66 #include "ui/gfx/size_conversions.h"
67 #include "ui/gfx/skia_util.h"
68 #include "ui/gl/gl_switches.h"
69 #include "ui/surface/transport_dib.h"
71 #if defined(OS_ANDROID)
72 #include <android/keycodes.h>
73 #include "base/android/sys_utils.h"
74 #include "content/renderer/android/synchronous_compositor_factory.h"
78 #include "ipc/ipc_channel_posix.h"
79 #include "third_party/skia/include/core/SkMallocPixelRef.h"
80 #include "third_party/skia/include/core/SkPixelRef.h"
81 #endif // defined(OS_POSIX)
83 #include "third_party/WebKit/public/web/WebWidget.h"
85 using blink::WebCompositionUnderline;
86 using blink::WebCursorInfo;
87 using blink::WebGestureEvent;
88 using blink::WebInputEvent;
89 using blink::WebKeyboardEvent;
90 using blink::WebMouseEvent;
91 using blink::WebMouseWheelEvent;
92 using blink::WebNavigationPolicy;
93 using blink::WebPagePopup;
94 using blink::WebPopupMenu;
95 using blink::WebPopupMenuInfo;
96 using blink::WebPopupType;
97 using blink::WebRange;
99 using blink::WebScreenInfo;
100 using blink::WebSize;
101 using blink::WebTextDirection;
102 using blink::WebTouchEvent;
103 using blink::WebTouchPoint;
104 using blink::WebVector;
105 using blink::WebWidget;
109 typedef std::map<std::string, ui::TextInputMode> TextInputModeMap;
111 class TextInputModeMapSingleton {
113 static TextInputModeMapSingleton* GetInstance() {
114 return Singleton<TextInputModeMapSingleton>::get();
116 TextInputModeMapSingleton() {
117 map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM;
118 map_["latin"] = ui::TEXT_INPUT_MODE_LATIN;
119 map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME;
120 map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE;
121 map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN;
122 map_["kana"] = ui::TEXT_INPUT_MODE_KANA;
123 map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA;
124 map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC;
125 map_["tel"] = ui::TEXT_INPUT_MODE_TEL;
126 map_["email"] = ui::TEXT_INPUT_MODE_EMAIL;
127 map_["url"] = ui::TEXT_INPUT_MODE_URL;
129 const TextInputModeMap& map() const { return map_; }
131 TextInputModeMap map_;
133 friend struct DefaultSingletonTraits<TextInputModeMapSingleton>;
135 DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton);
138 ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) {
139 static TextInputModeMapSingleton* singleton =
140 TextInputModeMapSingleton::GetInstance();
141 TextInputModeMap::const_iterator it =
142 singleton->map().find(input_mode.utf8());
143 if (it == singleton->map().end())
144 return ui::TEXT_INPUT_MODE_DEFAULT;
148 // TODO(brianderson): Replace the hard-coded threshold with a fraction of
149 // the BeginMainFrame interval.
150 // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to
151 // be spent in input hanlders before input starts getting throttled.
152 const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166;
158 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
160 class RenderWidget::ScreenMetricsEmulator {
162 ScreenMetricsEmulator(
163 RenderWidget* widget,
164 const gfx::Rect& device_rect,
165 const gfx::Rect& widget_rect,
166 float device_scale_factor,
168 virtual ~ScreenMetricsEmulator();
170 float scale() { return scale_; }
171 gfx::Point offset() { return offset_; }
172 gfx::Rect widget_rect() const { return widget_rect_; }
173 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
175 void ChangeEmulationParams(
176 const gfx::Rect& device_rect,
177 const gfx::Rect& widget_rect,
178 float device_scale_factor,
181 // The following methods alter handlers' behavior for messages related to
182 // widget size and position.
183 void OnResizeMessage(const ViewMsg_Resize_Params& params);
184 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
185 const gfx::Rect& window_screen_rect);
186 void OnShowContextMenu(ContextMenuParams* params);
189 void CalculateScaleAndOffset();
190 void Apply(float overdraw_bottom_height,
191 gfx::Rect resizer_rect, bool is_fullscreen);
193 RenderWidget* widget_;
195 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
196 gfx::Rect device_rect_;
197 gfx::Rect widget_rect_;
198 float device_scale_factor_;
201 // The computed scale and offset used to fit widget into browser window.
205 // Original values to restore back after emulation ends.
206 gfx::Size original_size_;
207 gfx::Size original_physical_backing_size_;
208 blink::WebScreenInfo original_screen_info_;
209 gfx::Rect original_view_screen_rect_;
210 gfx::Rect original_window_screen_rect_;
213 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
214 RenderWidget* widget,
215 const gfx::Rect& device_rect,
216 const gfx::Rect& widget_rect,
217 float device_scale_factor,
220 device_rect_(device_rect),
221 widget_rect_(widget_rect),
222 device_scale_factor_(device_scale_factor),
223 fit_to_view_(fit_to_view),
225 original_size_ = widget_->size_;
226 original_physical_backing_size_ = widget_->physical_backing_size_;
227 original_screen_info_ = widget_->screen_info_;
228 original_view_screen_rect_ = widget_->view_screen_rect_;
229 original_window_screen_rect_ = widget_->window_screen_rect_;
230 Apply(widget_->overdraw_bottom_height_,
231 widget_->resizer_rect_, widget_->is_fullscreen_);
234 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
235 widget_->screen_info_ = original_screen_info_;
237 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
238 widget_->SetScreenMetricsEmulationParameters(0.f, gfx::Point(), 1.f);
239 widget_->view_screen_rect_ = original_view_screen_rect_;
240 widget_->window_screen_rect_ = original_window_screen_rect_;
241 widget_->Resize(original_size_, original_physical_backing_size_,
242 widget_->overdraw_bottom_height_, widget_->resizer_rect_,
243 widget_->is_fullscreen_, NO_RESIZE_ACK);
246 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
247 const gfx::Rect& device_rect,
248 const gfx::Rect& widget_rect,
249 float device_scale_factor,
251 device_rect_ = device_rect;
252 widget_rect_ = widget_rect;
253 device_scale_factor_ = device_scale_factor;
254 fit_to_view_ = fit_to_view;
255 Apply(widget_->overdraw_bottom_height_,
256 widget_->resizer_rect_, widget_->is_fullscreen_);
259 void RenderWidget::ScreenMetricsEmulator::CalculateScaleAndOffset() {
261 DCHECK(!original_size_.IsEmpty());
263 int width_with_gutter =
264 std::max(original_size_.width() - 2 * device_rect_.x(), 1);
265 int height_with_gutter =
266 std::max(original_size_.height() - 2 * device_rect_.y(), 1);
268 static_cast<float>(widget_rect_.width()) / width_with_gutter;
270 static_cast<float>(widget_rect_.height()) / height_with_gutter;
271 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
272 scale_ = 1.f / ratio;
274 // Center emulated view inside available view space.
275 offset_.set_x((original_size_.width() - scale_ * widget_rect_.width()) / 2);
277 (original_size_.height() - scale_ * widget_rect_.height()) / 2);
280 offset_.SetPoint(0, 0);
284 void RenderWidget::ScreenMetricsEmulator::Apply(
285 float overdraw_bottom_height, gfx::Rect resizer_rect, bool is_fullscreen) {
286 gfx::Rect applied_widget_rect = widget_rect_;
287 if (widget_rect_.size().IsEmpty()) {
289 offset_.SetPoint(0, 0);
290 applied_widget_rect =
291 gfx::Rect(original_view_screen_rect_.origin(), original_size_);
293 CalculateScaleAndOffset();
296 if (device_rect_.size().IsEmpty()) {
297 widget_->screen_info_.rect = original_screen_info_.rect;
298 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
299 widget_->window_screen_rect_ = original_window_screen_rect_;
301 widget_->screen_info_.rect = gfx::Rect(device_rect_.size());
302 widget_->screen_info_.availableRect = gfx::Rect(device_rect_.size());
303 widget_->window_screen_rect_ = widget_->screen_info_.availableRect;
306 float applied_device_scale_factor = device_scale_factor_ ?
307 device_scale_factor_ : original_screen_info_.deviceScaleFactor;
308 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
310 // Pass three emulation parameters to the blink side:
311 // - we keep the real device scale factor in compositor to produce sharp image
312 // even when emulating different scale factor;
313 // - in order to fit into view, WebView applies offset and scale to the
315 widget_->SetScreenMetricsEmulationParameters(
316 original_screen_info_.deviceScaleFactor, offset_, scale_);
318 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
319 widget_->view_screen_rect_ = applied_widget_rect;
321 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
322 original_size_, original_screen_info_.deviceScaleFactor));
323 widget_->Resize(applied_widget_rect.size(), physical_backing_size,
324 overdraw_bottom_height, resizer_rect, is_fullscreen, NO_RESIZE_ACK);
327 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
328 const ViewMsg_Resize_Params& params) {
329 bool need_ack = params.new_size != original_size_ &&
330 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
331 original_size_ = params.new_size;
332 original_physical_backing_size_ = params.physical_backing_size;
333 original_screen_info_ = params.screen_info;
334 Apply(params.overdraw_bottom_height, params.resizer_rect,
335 params.is_fullscreen);
338 widget_->set_next_paint_is_resize_ack();
339 if (widget_->compositor_)
340 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
344 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
345 const gfx::Rect& view_screen_rect,
346 const gfx::Rect& window_screen_rect) {
347 original_view_screen_rect_ = view_screen_rect;
348 original_window_screen_rect_ = window_screen_rect;
349 if (device_rect_.size().IsEmpty())
350 widget_->window_screen_rect_ = window_screen_rect;
351 if (widget_rect_.size().IsEmpty())
352 widget_->view_screen_rect_ = view_screen_rect;
355 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
356 ContextMenuParams* params) {
358 params->x += offset_.x();
360 params->y += offset_.y();
363 // RenderWidget ---------------------------------------------------------------
365 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
366 const blink::WebScreenInfo& screen_info,
369 : routing_id_(MSG_ROUTING_NONE),
372 opener_id_(MSG_ROUTING_NONE),
373 init_complete_(false),
374 current_paint_buf_(NULL),
375 overdraw_bottom_height_(0.f),
376 next_paint_flags_(0),
377 filtered_time_per_frame_(0.0f),
378 update_reply_pending_(false),
379 auto_resize_mode_(false),
380 need_update_rect_for_auto_resize_(false),
381 using_asynchronous_swapbuffers_(false),
382 num_swapbuffers_complete_pending_(0),
385 is_fullscreen_(false),
386 needs_repainting_on_restore_(false),
388 handling_input_event_(false),
389 handling_ime_event_(false),
390 handling_touchstart_event_(false),
392 is_swapped_out_(swapped_out),
393 input_method_is_active_(false),
394 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
395 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
396 can_compose_inline_(true),
397 popup_type_(popup_type),
398 pending_window_rect_count_(0),
399 suppress_next_char_events_(false),
400 is_accelerated_compositing_active_(false),
401 was_accelerated_compositing_ever_active_(false),
402 animation_update_pending_(false),
403 invalidation_task_posted_(false),
404 screen_info_(screen_info),
405 device_scale_factor_(screen_info_.deviceScaleFactor),
406 is_threaded_compositing_enabled_(false),
407 next_output_surface_id_(0),
408 #if defined(OS_ANDROID)
409 outstanding_ime_acks_(0),
411 popup_origin_scale_for_emulation_(0.f),
412 resizing_mode_selector_(new ResizingModeSelector()),
413 context_menu_source_type_(ui::MENU_SOURCE_MOUSE) {
415 RenderProcess::current()->AddRefProcess();
416 DCHECK(RenderThread::Get());
417 has_disable_gpu_vsync_switch_ = CommandLine::ForCurrentProcess()->HasSwitch(
418 switches::kDisableGpuVsync);
419 is_threaded_compositing_enabled_ =
420 CommandLine::ForCurrentProcess()->HasSwitch(
421 switches::kEnableThreadedCompositing);
423 legacy_software_mode_stats_ = cc::RenderingStatsInstrumentation::Create();
424 if (CommandLine::ForCurrentProcess()->HasSwitch(
425 cc::switches::kEnableGpuBenchmarking))
426 legacy_software_mode_stats_->set_record_rendering_stats(true);
429 RenderWidget::~RenderWidget() {
430 DCHECK(!webwidget_) << "Leaking our WebWidget!";
431 STLDeleteElements(&updates_pending_swap_);
432 if (current_paint_buf_) {
433 if (RenderProcess::current()) {
434 // If the RenderProcess is already gone, it will have released all DIBs
435 // in its destructor anyway.
436 RenderProcess::current()->ReleaseTransportDIB(current_paint_buf_);
438 current_paint_buf_ = NULL;
441 // If we are swapped out, we have released already.
442 if (!is_swapped_out_ && RenderProcess::current())
443 RenderProcess::current()->ReleaseProcess();
447 RenderWidget* RenderWidget::Create(int32 opener_id,
448 blink::WebPopupType popup_type,
449 const blink::WebScreenInfo& screen_info) {
450 DCHECK(opener_id != MSG_ROUTING_NONE);
451 scoped_refptr<RenderWidget> widget(
452 new RenderWidget(popup_type, screen_info, false, false));
453 if (widget->Init(opener_id)) { // adds reference on success.
460 WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
461 switch (render_widget->popup_type_) {
462 case blink::WebPopupTypeNone: // Nothing to create.
464 case blink::WebPopupTypeSelect:
465 case blink::WebPopupTypeSuggestion:
466 return WebPopupMenu::create(render_widget);
467 case blink::WebPopupTypePage:
468 return WebPagePopup::create(render_widget);
475 bool RenderWidget::Init(int32 opener_id) {
476 return DoInit(opener_id,
477 RenderWidget::CreateWebWidget(this),
478 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
479 &routing_id_, &surface_id_));
482 bool RenderWidget::DoInit(int32 opener_id,
483 WebWidget* web_widget,
484 IPC::SyncMessage* create_widget_message) {
487 if (opener_id != MSG_ROUTING_NONE)
488 opener_id_ = opener_id;
490 webwidget_ = web_widget;
492 bool result = RenderThread::Get()->Send(create_widget_message);
494 RenderThread::Get()->AddRoute(routing_id_, this);
495 // Take a reference on behalf of the RenderThread. This will be balanced
496 // when we receive ViewMsg_Close.
498 if (RenderThreadImpl::current()) {
499 RenderThreadImpl::current()->WidgetCreated();
501 RenderThreadImpl::current()->WidgetHidden();
505 // The above Send can fail when the tab is closing.
510 // This is used to complete pending inits and non-pending inits.
511 void RenderWidget::CompleteInit() {
512 DCHECK(routing_id_ != MSG_ROUTING_NONE);
514 init_complete_ = true;
516 if (webwidget_ && is_threaded_compositing_enabled_) {
517 webwidget_->enterForceCompositingMode(true);
520 compositor_->setSurfaceReady();
524 Send(new ViewHostMsg_RenderViewReady(routing_id_));
527 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
528 // We should only toggle between states.
529 DCHECK(is_swapped_out_ != is_swapped_out);
530 is_swapped_out_ = is_swapped_out;
532 // If we are swapping out, we will call ReleaseProcess, allowing the process
533 // to exit if all of its RenderViews are swapped out. We wait until the
534 // WasSwappedOut call to do this, to avoid showing the sad tab.
535 // If we are swapping in, we call AddRefProcess to prevent the process from
538 RenderProcess::current()->AddRefProcess();
541 bool RenderWidget::UsingSynchronousRendererCompositor() const {
542 #if defined(OS_ANDROID)
543 return SynchronousCompositorFactory::GetInstance() != NULL;
549 void RenderWidget::EnableScreenMetricsEmulation(
550 const gfx::Rect& device_rect,
551 const gfx::Rect& widget_rect,
552 float device_scale_factor,
554 if (!screen_metrics_emulator_) {
555 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this,
556 device_rect, widget_rect, device_scale_factor, fit_to_view));
558 screen_metrics_emulator_->ChangeEmulationParams(device_rect,
559 widget_rect, device_scale_factor, fit_to_view);
563 void RenderWidget::DisableScreenMetricsEmulation() {
564 screen_metrics_emulator_.reset();
567 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
568 ScreenMetricsEmulator* emulator) {
569 popup_origin_scale_for_emulation_ = emulator->scale();
570 popup_view_origin_for_emulation_ = emulator->widget_rect().origin();
571 popup_screen_origin_for_emulation_ = gfx::Point(
572 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
573 emulator->original_screen_rect().origin().y() + emulator->offset().y());
576 void RenderWidget::SetScreenMetricsEmulationParameters(
577 float device_scale_factor,
578 const gfx::Point& root_layer_offset,
579 float root_layer_scale) {
580 // This is only supported in RenderView.
584 #if defined(OS_MACOSX) || defined(OS_ANDROID)
585 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
586 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
587 popup->SetOriginScaleAndOffsetForEmulation(
588 emulator->scale(), emulator->offset());
592 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
593 if (screen_metrics_emulator_)
594 screen_metrics_emulator_->OnShowContextMenu(params);
597 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
599 // Regardless of whether threaded compositing is enabled, always
600 // use this mechanism to force the compositor to redraw. However,
601 // the invalidation code path below is still needed for the
602 // non-threaded case.
603 compositor_->SetNeedsForcedRedraw();
608 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
610 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
611 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
612 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
613 OnCursorVisibilityChange)
614 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
615 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
616 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
617 OnSyntheticGestureCompleted)
618 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
619 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
620 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
621 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
622 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
623 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
624 IPC_MESSAGE_HANDLER(ViewMsg_WasSwappedOut, OnWasSwappedOut)
625 IPC_MESSAGE_HANDLER(ViewMsg_UpdateRect_ACK, OnUpdateRectAck)
626 IPC_MESSAGE_HANDLER(ViewMsg_SwapBuffers_ACK, OnSwapBuffersComplete)
627 IPC_MESSAGE_HANDLER(ViewMsg_SetInputMethodActive, OnSetInputMethodActive)
628 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowShown, OnCandidateWindowShown)
629 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowUpdated,
630 OnCandidateWindowUpdated)
631 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowHidden, OnCandidateWindowHidden)
632 IPC_MESSAGE_HANDLER(ViewMsg_ImeSetComposition, OnImeSetComposition)
633 IPC_MESSAGE_HANDLER(ViewMsg_ImeConfirmComposition, OnImeConfirmComposition)
634 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
635 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
636 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
637 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
638 #if defined(OS_ANDROID)
639 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
640 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
642 IPC_MESSAGE_HANDLER(ViewMsg_Snapshot, OnSnapshot)
643 IPC_MESSAGE_UNHANDLED(handled = false)
644 IPC_END_MESSAGE_MAP()
648 bool RenderWidget::Send(IPC::Message* message) {
649 // Don't send any messages after the browser has told us to close, and filter
650 // most outgoing messages while swapped out.
651 if ((is_swapped_out_ &&
652 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
658 // If given a messsage without a routing ID, then assign our routing ID.
659 if (message->routing_id() == MSG_ROUTING_NONE)
660 message->set_routing_id(routing_id_);
662 return RenderThread::Get()->Send(message);
665 void RenderWidget::Resize(const gfx::Size& new_size,
666 const gfx::Size& physical_backing_size,
667 float overdraw_bottom_height,
668 const gfx::Rect& resizer_rect,
670 ResizeAck resize_ack) {
671 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
672 // A resize ack shouldn't be requested if we have not ACK'd the previous
674 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
675 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
678 // Ignore this during shutdown.
683 compositor_->setViewportSize(new_size, physical_backing_size);
684 compositor_->SetOverdrawBottomHeight(overdraw_bottom_height);
687 physical_backing_size_ = physical_backing_size;
688 overdraw_bottom_height_ = overdraw_bottom_height;
689 resizer_rect_ = resizer_rect;
691 // NOTE: We may have entered fullscreen mode without changing our size.
692 bool fullscreen_change = is_fullscreen_ != is_fullscreen;
693 if (fullscreen_change)
694 WillToggleFullscreen();
695 is_fullscreen_ = is_fullscreen;
697 if (size_ != new_size) {
698 // TODO(darin): We should not need to reset this here.
699 needs_repainting_on_restore_ = false;
703 paint_aggregator_.ClearPendingUpdate();
705 // When resizing, we want to wait to paint before ACK'ing the resize. This
706 // ensures that we only resize as fast as we can paint. We only need to
707 // send an ACK if we are resized to a non-empty rect.
708 webwidget_->resize(new_size);
710 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
711 // Resize should have caused an invalidation of the entire view.
712 DCHECK(new_size.IsEmpty() || is_accelerated_compositing_active_ ||
713 paint_aggregator_.HasPendingUpdate());
715 } else if (!resizing_mode_selector_->is_synchronous_mode()) {
716 resize_ack = NO_RESIZE_ACK;
719 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
720 // For empty size or empty physical_backing_size, there is no next paint
721 // (along with which to send the ack) until they are set to non-empty.
722 resize_ack = NO_RESIZE_ACK;
725 // Send the Resize_ACK flag once we paint again if requested.
726 if (resize_ack == SEND_RESIZE_ACK)
727 set_next_paint_is_resize_ack();
729 if (fullscreen_change)
730 DidToggleFullscreen();
732 // If a resize ack is requested and it isn't set-up, then no more resizes will
733 // come in and in general things will go wrong.
734 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
737 void RenderWidget::ResizeSynchronously(const gfx::Rect& new_position) {
738 Resize(new_position.size(), new_position.size(), overdraw_bottom_height_,
739 gfx::Rect(), is_fullscreen_, NO_RESIZE_ACK);
740 view_screen_rect_ = new_position;
741 window_screen_rect_ = new_position;
743 initial_pos_ = new_position;
746 void RenderWidget::OnClose() {
751 // Browser correspondence is no longer needed at this point.
752 if (routing_id_ != MSG_ROUTING_NONE) {
753 if (RenderThreadImpl::current())
754 RenderThreadImpl::current()->WidgetDestroyed();
755 RenderThread::Get()->RemoveRoute(routing_id_);
759 // If there is a Send call on the stack, then it could be dangerous to close
760 // now. Post a task that only gets invoked when there are no nested message
762 base::MessageLoop::current()->PostNonNestableTask(
763 FROM_HERE, base::Bind(&RenderWidget::Close, this));
765 // Balances the AddRef taken when we called AddRoute.
769 // Got a response from the browser after the renderer decided to create a new
771 void RenderWidget::OnCreatingNewAck() {
772 DCHECK(routing_id_ != MSG_ROUTING_NONE);
777 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
778 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
781 if (screen_metrics_emulator_) {
782 screen_metrics_emulator_->OnResizeMessage(params);
786 screen_info_ = params.screen_info;
787 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
788 Resize(params.new_size, params.physical_backing_size,
789 params.overdraw_bottom_height, params.resizer_rect,
790 params.is_fullscreen, SEND_RESIZE_ACK);
793 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
794 if (resizer_rect_ != resizer_rect) {
795 gfx::Rect view_rect(size_);
797 gfx::Rect old_damage_rect = gfx::IntersectRects(view_rect, resizer_rect_);
798 if (!old_damage_rect.IsEmpty())
799 paint_aggregator_.InvalidateRect(old_damage_rect);
801 gfx::Rect new_damage_rect = gfx::IntersectRects(view_rect, resizer_rect);
802 if (!new_damage_rect.IsEmpty())
803 paint_aggregator_.InvalidateRect(new_damage_rect);
805 resizer_rect_ = resizer_rect;
808 webwidget_->didChangeWindowResizerRect();
812 void RenderWidget::OnWasHidden() {
813 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
814 // Go into a mode where we stop generating paint and scrolling events.
818 void RenderWidget::OnWasShown(bool needs_repainting) {
819 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
820 // During shutdown we can just ignore this message.
827 if (!needs_repainting && !needs_repainting_on_restore_)
829 needs_repainting_on_restore_ = false;
831 // Tag the next paint as a restore ack, which is picked up by
832 // DoDeferredUpdate when it sends out the next PaintRect message.
833 set_next_paint_is_restore_ack();
835 // Generate a full repaint.
836 if (!is_accelerated_compositing_active_) {
837 didInvalidateRect(gfx::Rect(size_.width(), size_.height()));
840 compositor_->SetNeedsForcedRedraw();
845 void RenderWidget::OnWasSwappedOut() {
846 // If we have been swapped out and no one else is using this process,
847 // it's safe to exit now. If we get swapped back in, we will call
848 // AddRefProcess in SetSwappedOut.
850 RenderProcess::current()->ReleaseProcess();
853 void RenderWidget::OnRequestMoveAck() {
854 DCHECK(pending_window_rect_count_);
855 pending_window_rect_count_--;
858 void RenderWidget::OnUpdateRectAck() {
859 TRACE_EVENT0("renderer", "RenderWidget::OnUpdateRectAck");
860 DCHECK(update_reply_pending_);
861 update_reply_pending_ = false;
863 // If we sent an UpdateRect message with a zero-sized bitmap, then we should
864 // have no current paint buffer.
865 if (current_paint_buf_) {
866 RenderProcess::current()->ReleaseTransportDIB(current_paint_buf_);
867 current_paint_buf_ = NULL;
870 // If swapbuffers is still pending, then defer the update until the
871 // swapbuffers occurs.
872 if (num_swapbuffers_complete_pending_ >= kMaxSwapBuffersPending) {
873 TRACE_EVENT0("renderer", "EarlyOut_SwapStillPending");
877 // Notify subclasses that software rendering was flushed to the screen.
878 if (!is_accelerated_compositing_active_) {
882 // Continue painting if necessary...
883 DoDeferredUpdateAndSendInputAck();
886 bool RenderWidget::SupportsAsynchronousSwapBuffers() {
887 // Contexts using the command buffer support asynchronous swapbuffers.
888 // See RenderWidget::CreateOutputSurface().
889 if (RenderThreadImpl::current()->compositor_message_loop_proxy().get())
895 GURL RenderWidget::GetURLForGraphicsContext3D() {
899 bool RenderWidget::ForceCompositingModeEnabled() {
903 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
905 #if defined(OS_ANDROID)
906 if (SynchronousCompositorFactory* factory =
907 SynchronousCompositorFactory::GetInstance()) {
908 return factory->CreateOutputSurface(routing_id());
912 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
913 bool use_software = fallback;
914 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
917 scoped_refptr<ContextProviderCommandBuffer> context_provider;
919 // Explicitly disable antialiasing for the compositor. As of the time of
920 // this writing, the only platform that supported antialiasing for the
921 // compositor was Mac OS X, because the on-screen OpenGL context creation
922 // code paths on Windows and Linux didn't yet have multisampling support.
923 // Mac OS X essentially always behaves as though it's rendering offscreen.
924 // Multisampling has a heavy cost especially on devices with relatively low
925 // fill rate like most notebooks, and the Mac implementation would need to
926 // be optimized to resolve directly into the IOSurface shared between the
927 // GPU and browser processes. For these reasons and to avoid platform
928 // disparities we explicitly disable antialiasing.
929 blink::WebGraphicsContext3D::Attributes attributes;
930 attributes.antialias = false;
931 attributes.shareResources = true;
932 attributes.noAutomaticFlushes = true;
933 attributes.depth = false;
934 attributes.stencil = false;
935 context_provider = ContextProviderCommandBuffer::Create(
936 CreateGraphicsContext3D(attributes),
938 if (!context_provider.get()) {
939 // Cause the compositor to wait and try again.
940 return scoped_ptr<cc::OutputSurface>();
944 uint32 output_surface_id = next_output_surface_id_++;
945 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer) &&
946 !command_line.HasSwitch(switches::kDisableDelegatedRenderer)) {
947 DCHECK(is_threaded_compositing_enabled_);
948 return scoped_ptr<cc::OutputSurface>(
949 new DelegatedCompositorOutputSurface(
954 if (!context_provider.get()) {
955 if (!command_line.HasSwitch(switches::kEnableSoftwareCompositing))
956 return scoped_ptr<cc::OutputSurface>();
958 scoped_ptr<cc::SoftwareOutputDevice> software_device(
959 new CompositorSoftwareOutputDevice());
961 return scoped_ptr<cc::OutputSurface>(new CompositorOutputSurface(
965 software_device.Pass(),
969 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
970 DCHECK(is_threaded_compositing_enabled_);
971 cc::ResourceFormat format = cc::RGBA_8888;
972 #if defined(OS_ANDROID)
973 if (base::android::SysUtils::IsLowEndDevice())
974 format = cc::RGB_565;
976 return scoped_ptr<cc::OutputSurface>(
977 new MailboxOutputSurface(
981 scoped_ptr<cc::SoftwareOutputDevice>(),
984 bool use_swap_compositor_frame_message = false;
985 return scoped_ptr<cc::OutputSurface>(
986 new CompositorOutputSurface(
990 scoped_ptr<cc::SoftwareOutputDevice>(),
991 use_swap_compositor_frame_message));
994 void RenderWidget::OnSwapBuffersAborted() {
995 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
996 while (!updates_pending_swap_.empty()) {
997 ViewHostMsg_UpdateRect* msg = updates_pending_swap_.front();
998 updates_pending_swap_.pop_front();
999 // msg can be NULL if the swap doesn't correspond to an DoDeferredUpdate
1000 // compositing pass, hence doesn't require an UpdateRect message.
1004 num_swapbuffers_complete_pending_ = 0;
1005 using_asynchronous_swapbuffers_ = false;
1006 // Schedule another frame so the compositor learns about it.
1007 scheduleComposite();
1010 void RenderWidget::OnSwapBuffersPosted() {
1011 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1013 if (using_asynchronous_swapbuffers_) {
1014 ViewHostMsg_UpdateRect* msg = NULL;
1015 // pending_update_params_ can be NULL if the swap doesn't correspond to an
1016 // DoDeferredUpdate compositing pass, hence doesn't require an UpdateRect
1018 if (pending_update_params_) {
1019 msg = new ViewHostMsg_UpdateRect(routing_id_, *pending_update_params_);
1020 pending_update_params_.reset();
1022 updates_pending_swap_.push_back(msg);
1023 num_swapbuffers_complete_pending_++;
1027 void RenderWidget::OnSwapBuffersComplete() {
1028 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1030 // Notify subclasses that composited rendering was flushed to the screen.
1033 // When compositing deactivates, we reset the swapbuffers pending count. The
1034 // swapbuffers acks may still arrive, however.
1035 if (num_swapbuffers_complete_pending_ == 0) {
1036 TRACE_EVENT0("renderer", "EarlyOut_ZeroSwapbuffersPending");
1039 DCHECK(!updates_pending_swap_.empty());
1040 ViewHostMsg_UpdateRect* msg = updates_pending_swap_.front();
1041 updates_pending_swap_.pop_front();
1042 // msg can be NULL if the swap doesn't correspond to an DoDeferredUpdate
1043 // compositing pass, hence doesn't require an UpdateRect message.
1046 num_swapbuffers_complete_pending_--;
1048 // If update reply is still pending, then defer the update until that reply
1050 if (update_reply_pending_) {
1051 TRACE_EVENT0("renderer", "EarlyOut_UpdateReplyPending");
1055 // If we are not accelerated rendering, then this is a stale swapbuffers from
1056 // when we were previously rendering. However, if an invalidation task is not
1057 // posted, there may be software rendering work pending. In that case, don't
1059 if (!is_accelerated_compositing_active_ && invalidation_task_posted_) {
1060 TRACE_EVENT0("renderer", "EarlyOut_AcceleratedCompositingOff");
1064 // Do not call DoDeferredUpdate unless there's animation work to be done or
1065 // a real invalidation. This prevents rendering in response to a swapbuffers
1066 // callback coming back after we've navigated away from the page that
1068 if (!animation_update_pending_ && !paint_aggregator_.HasPendingUpdate()) {
1069 TRACE_EVENT0("renderer", "EarlyOut_NoPendingUpdate");
1073 // Continue painting if necessary...
1074 DoDeferredUpdateAndSendInputAck();
1077 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1078 const ui::LatencyInfo& latency_info,
1079 bool is_keyboard_shortcut) {
1080 handling_input_event_ = true;
1082 handling_input_event_ = false;
1086 base::TimeTicks start_time;
1087 if (base::TimeTicks::IsHighResNowFastAndReliable())
1088 start_time = base::TimeTicks::HighResNow();
1090 const char* const event_name =
1091 WebInputEventTraits::GetName(input_event->type);
1092 TRACE_EVENT1("renderer", "RenderWidget::OnHandleInputEvent",
1093 "event", event_name);
1094 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1096 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1097 ui::LatencyInfo swap_latency_info(latency_info);
1099 latency_info_swap_promise_monitor =
1100 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1103 latency_info_.push_back(latency_info);
1106 base::TimeDelta now = base::TimeDelta::FromInternalValue(
1107 base::TimeTicks::Now().ToInternalValue());
1109 int64 delta = static_cast<int64>(
1110 (now.InSecondsF() - input_event->timeStampSeconds) *
1111 base::Time::kMicrosecondsPerSecond);
1112 UMA_HISTOGRAM_CUSTOM_COUNTS("Event.AggregatedLatency.Renderer2",
1113 delta, 1, 10000000, 100);
1114 base::HistogramBase* counter_for_type =
1115 base::Histogram::FactoryGet(
1116 base::StringPrintf("Event.Latency.Renderer2.%s", event_name),
1120 base::HistogramBase::kUmaTargetedHistogramFlag);
1121 counter_for_type->Add(delta);
1123 if (WebInputEvent::isUserGestureEventType(input_event->type))
1124 WillProcessUserGesture();
1126 bool prevent_default = false;
1127 if (WebInputEvent::isMouseEventType(input_event->type)) {
1128 const WebMouseEvent& mouse_event =
1129 *static_cast<const WebMouseEvent*>(input_event);
1130 TRACE_EVENT2("renderer", "HandleMouseMove",
1131 "x", mouse_event.x, "y", mouse_event.y);
1132 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1133 prevent_default = WillHandleMouseEvent(mouse_event);
1136 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1137 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1138 #if defined(OS_ANDROID)
1139 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1140 // case it should behave like a select key (i.e. causing a click if a button
1141 // is focused). However, if a text field is focused (2), its intended
1142 // behavior is to just show the IME and don't propagate the key.
1143 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1144 // when clicked on an input text field and cause the form submit if clicked
1145 // when the submit button is focused, but not vice-versa.
1146 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1147 // but at this point we have to swallow the event for the scenario (2).
1148 const WebKeyboardEvent& key_event =
1149 *static_cast<const WebKeyboardEvent*>(input_event);
1150 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1151 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1152 OnShowImeIfNeeded();
1153 prevent_default = true;
1158 if (WebInputEvent::isGestureEventType(input_event->type)) {
1159 const WebGestureEvent& gesture_event =
1160 *static_cast<const WebGestureEvent*>(input_event);
1161 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1162 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1165 if (input_event->type == WebInputEvent::TouchStart)
1166 handling_touchstart_event_ = true;
1168 bool processed = prevent_default;
1169 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1170 suppress_next_char_events_ = false;
1171 if (!processed && webwidget_)
1172 processed = webwidget_->handleInputEvent(*input_event);
1175 handling_touchstart_event_ = false;
1177 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1178 // it's not processed by webkit, then we need to suppress the upcoming Char
1180 if (!processed && is_keyboard_shortcut)
1181 suppress_next_char_events_ = true;
1183 InputEventAckState ack_result = processed ?
1184 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1185 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1186 const WebTouchEvent& touch_event =
1187 *static_cast<const WebTouchEvent*>(input_event);
1188 // Hit-test for all the pressed touch points. If there is a touch-handler
1189 // for any of the touch points, then the renderer should continue to receive
1191 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1192 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1193 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1194 HasTouchEventHandlersAt(
1195 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1196 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1202 bool event_type_can_be_rate_limited =
1203 input_event->type == WebInputEvent::MouseMove ||
1204 input_event->type == WebInputEvent::MouseWheel ||
1205 input_event->type == WebInputEvent::TouchMove;
1207 bool frame_pending = paint_aggregator_.HasPendingUpdate();
1208 if (is_accelerated_compositing_active_) {
1209 frame_pending = compositor_ &&
1210 compositor_->BeginMainFrameRequested();
1213 // If we don't have a fast and accurate HighResNow, we assume the input
1214 // handlers are heavy and rate limit them.
1215 bool rate_limiting_wanted = true;
1216 if (base::TimeTicks::IsHighResNowFastAndReliable()) {
1217 base::TimeTicks end_time = base::TimeTicks::HighResNow();
1218 total_input_handling_time_this_frame_ += (end_time - start_time);
1219 rate_limiting_wanted =
1220 total_input_handling_time_this_frame_.InMicroseconds() >
1221 kInputHandlingTimeThrottlingThresholdMicroseconds;
1224 if (!WebInputEventTraits::IgnoresAckDisposition(input_event->type)) {
1225 scoped_ptr<IPC::Message> response(
1226 new InputHostMsg_HandleInputEvent_ACK(routing_id_,
1229 swap_latency_info));
1230 if (rate_limiting_wanted && event_type_can_be_rate_limited &&
1231 frame_pending && !is_hidden_) {
1232 // We want to rate limit the input events in this case, so we'll wait for
1233 // painting to finish before ACKing this message.
1234 TRACE_EVENT_INSTANT0("renderer",
1235 "RenderWidget::OnHandleInputEvent ack throttled",
1236 TRACE_EVENT_SCOPE_THREAD);
1237 if (pending_input_event_ack_) {
1238 // As two different kinds of events could cause us to postpone an ack
1239 // we send it now, if we have one pending. The Browser should never
1240 // send us the same kind of event we are delaying the ack for.
1241 Send(pending_input_event_ack_.release());
1243 pending_input_event_ack_ = response.Pass();
1245 compositor_->NotifyInputThrottledUntilCommit();
1247 Send(response.release());
1251 #if defined(OS_ANDROID)
1252 // Allow the IME to be shown when the focus changes as a consequence
1253 // of a processed touch end event.
1254 if (input_event->type == WebInputEvent::TouchEnd && processed)
1255 UpdateTextInputState(true, true);
1256 #elif defined(USE_AURA)
1257 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1259 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1260 input_event->type == WebInputEvent::MouseUp))
1261 UpdateTextInputState(true, false);
1264 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1265 handling_input_event_ = false;
1267 if (!prevent_default) {
1268 if (WebInputEvent::isKeyboardEventType(input_event->type))
1269 DidHandleKeyEvent();
1270 if (WebInputEvent::isMouseEventType(input_event->type))
1271 DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1272 if (WebInputEvent::isTouchEventType(input_event->type))
1273 DidHandleTouchEvent(*(static_cast<const WebTouchEvent*>(input_event)));
1277 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1279 webwidget_->setCursorVisibilityState(is_visible);
1282 void RenderWidget::OnMouseCaptureLost() {
1284 webwidget_->mouseCaptureLost();
1287 void RenderWidget::OnSetFocus(bool enable) {
1288 has_focus_ = enable;
1290 webwidget_->setFocus(enable);
1293 void RenderWidget::ClearFocus() {
1294 // We may have got the focus from the browser before this gets processed, in
1295 // which case we do not want to unfocus ourself.
1296 if (!has_focus_ && webwidget_)
1297 webwidget_->setFocus(false);
1300 void RenderWidget::PaintRect(const gfx::Rect& rect,
1301 const gfx::Point& canvas_origin,
1302 skia::PlatformCanvas* canvas) {
1303 TRACE_EVENT2("renderer", "PaintRect",
1304 "width", rect.width(), "height", rect.height());
1308 // Bring the canvas into the coordinate system of the paint rect.
1309 canvas->translate(static_cast<SkScalar>(-canvas_origin.x()),
1310 static_cast<SkScalar>(-canvas_origin.y()));
1312 // If there is a custom background, tile it.
1313 if (!background_.empty()) {
1315 skia::RefPtr<SkShader> shader = skia::AdoptRef(
1316 SkShader::CreateBitmapShader(background_,
1317 SkShader::kRepeat_TileMode,
1318 SkShader::kRepeat_TileMode));
1319 paint.setShader(shader.get());
1321 // Use kSrc_Mode to handle background_ transparency properly.
1322 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1324 // Canvas could contain multiple update rects. Clip to given rect so that
1325 // we don't accidentally clear other update rects.
1327 canvas->scale(device_scale_factor_, device_scale_factor_);
1328 canvas->clipRect(gfx::RectToSkRect(rect));
1329 canvas->drawPaint(paint);
1333 // First see if this rect is a plugin that can paint itself faster.
1334 TransportDIB* optimized_dib = NULL;
1335 gfx::Rect optimized_copy_rect, optimized_copy_location;
1336 float dib_scale_factor;
1337 PepperPluginInstanceImpl* optimized_instance =
1338 GetBitmapForOptimizedPluginPaint(rect, &optimized_dib,
1339 &optimized_copy_location,
1340 &optimized_copy_rect,
1342 if (optimized_instance) {
1343 #if defined(ENABLE_PLUGINS)
1344 // This plugin can be optimize-painted and we can just ask it to paint
1345 // itself. We don't actually need the TransportDIB in this case.
1347 // This is an optimization for PPAPI plugins that know they're on top of
1348 // the page content. If this rect is inside such a plugin, we can save some
1349 // time and avoid re-rendering the page content which we know will be
1350 // covered by the plugin later (this time can be significant, especially
1351 // for a playing movie that is invalidating a lot).
1353 // In the plugin movie case, hopefully the similar call to
1354 // GetBitmapForOptimizedPluginPaint in DoDeferredUpdate handles the
1355 // painting, because that avoids copying the plugin image to a different
1356 // paint rect. Unfortunately, if anything on the page is animating other
1357 // than the movie, it break this optimization since the union of the
1358 // invalid regions will be larger than the plugin.
1360 // This code optimizes that case, where we can still avoid painting in
1361 // WebKit and filling the background (which can be slow) and just painting
1362 // the plugin. Unlike the DoDeferredUpdate case, an extra copy is still
1364 SkAutoCanvasRestore auto_restore(canvas, true);
1365 canvas->scale(device_scale_factor_, device_scale_factor_);
1366 optimized_instance->Paint(canvas, optimized_copy_location, rect);
1370 // Normal painting case.
1371 base::TimeTicks start_time;
1372 if (!is_accelerated_compositing_active_)
1373 start_time = legacy_software_mode_stats_->StartRecording();
1375 webwidget_->paint(canvas, rect);
1377 if (!is_accelerated_compositing_active_) {
1378 base::TimeDelta paint_time =
1379 legacy_software_mode_stats_->EndRecording(start_time);
1380 int64 painted_pixel_count = rect.width() * rect.height();
1381 legacy_software_mode_stats_->AddPaint(paint_time, painted_pixel_count);
1384 // Flush to underlying bitmap. TODO(darin): is this needed?
1385 skia::GetTopDevice(*canvas)->accessBitmap(false);
1388 PaintDebugBorder(rect, canvas);
1392 void RenderWidget::PaintDebugBorder(const gfx::Rect& rect,
1393 skia::PlatformCanvas* canvas) {
1394 static bool kPaintBorder =
1395 CommandLine::ForCurrentProcess()->HasSwitch(switches::kShowPaintRects);
1399 // Cycle through these colors to help distinguish new paint rects.
1400 const SkColor colors[] = {
1401 SkColorSetARGB(0x3F, 0xFF, 0, 0),
1402 SkColorSetARGB(0x3F, 0xFF, 0, 0xFF),
1403 SkColorSetARGB(0x3F, 0, 0, 0xFF),
1405 static int color_selector = 0;
1408 paint.setStyle(SkPaint::kStroke_Style);
1409 paint.setColor(colors[color_selector++ % arraysize(colors)]);
1410 paint.setStrokeWidth(1);
1413 irect.set(rect.x(), rect.y(), rect.right() - 1, rect.bottom() - 1);
1414 canvas->drawIRect(irect, paint);
1417 void RenderWidget::AnimationCallback() {
1418 TRACE_EVENT0("renderer", "RenderWidget::AnimationCallback");
1419 if (!animation_update_pending_) {
1420 TRACE_EVENT0("renderer", "EarlyOut_NoAnimationUpdatePending");
1423 if (!animation_floor_time_.is_null() && IsRenderingVSynced()) {
1424 // Record when we fired (according to base::Time::Now()) relative to when
1425 // we posted the task to quantify how much the base::Time/base::TimeTicks
1426 // skew is affecting animations.
1427 base::TimeDelta animation_callback_delay = base::Time::Now() -
1428 (animation_floor_time_ - base::TimeDelta::FromMilliseconds(16));
1429 UMA_HISTOGRAM_CUSTOM_TIMES("Renderer4.AnimationCallbackDelayTime",
1430 animation_callback_delay,
1431 base::TimeDelta::FromMilliseconds(0),
1432 base::TimeDelta::FromMilliseconds(30),
1435 DoDeferredUpdateAndSendInputAck();
1438 void RenderWidget::AnimateIfNeeded() {
1439 if (!animation_update_pending_)
1442 // Target 60FPS if vsync is on. Go as fast as we can if vsync is off.
1443 base::TimeDelta animationInterval = IsRenderingVSynced() ?
1444 base::TimeDelta::FromMilliseconds(16) : base::TimeDelta();
1446 base::Time now = base::Time::Now();
1448 // animation_floor_time_ is the earliest time that we should animate when
1449 // using the dead reckoning software scheduler. If we're using swapbuffers
1450 // complete callbacks to rate limit, we can ignore this floor.
1451 if (now >= animation_floor_time_ || num_swapbuffers_complete_pending_ > 0) {
1452 TRACE_EVENT0("renderer", "RenderWidget::AnimateIfNeeded")
1453 animation_floor_time_ = now + animationInterval;
1454 // Set a timer to call us back after animationInterval before
1455 // running animation callbacks so that if a callback requests another
1456 // we'll be sure to run it at the proper time.
1457 animation_timer_.Stop();
1458 animation_timer_.Start(FROM_HERE, animationInterval, this,
1459 &RenderWidget::AnimationCallback);
1460 animation_update_pending_ = false;
1461 if (is_accelerated_compositing_active_ && compositor_) {
1462 compositor_->UpdateAnimations(base::TimeTicks::Now());
1464 double frame_begin_time =
1465 (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
1466 webwidget_->animate(frame_begin_time);
1470 TRACE_EVENT0("renderer", "EarlyOut_AnimatedTooRecently");
1471 if (!animation_timer_.IsRunning()) {
1472 // This code uses base::Time::Now() to calculate the floor and next fire
1473 // time because javascript's Date object uses base::Time::Now(). The
1474 // message loop uses base::TimeTicks, which on windows can have a
1475 // different granularity than base::Time.
1476 // The upshot of all this is that this function might be called before
1477 // base::Time::Now() has advanced past the animation_floor_time_. To
1478 // avoid exposing this delay to javascript, we keep posting delayed
1479 // tasks until base::Time::Now() has advanced far enough.
1480 base::TimeDelta delay = animation_floor_time_ - now;
1481 animation_timer_.Start(FROM_HERE, delay, this,
1482 &RenderWidget::AnimationCallback);
1486 bool RenderWidget::IsRenderingVSynced() {
1487 // TODO(nduca): Forcing a driver to disable vsync (e.g. in a control panel) is
1488 // not caught by this check. This will lead to artificially low frame rates
1489 // for people who force vsync off at a driver level and expect Chrome to speed
1491 return !has_disable_gpu_vsync_switch_;
1494 void RenderWidget::InvalidationCallback() {
1495 TRACE_EVENT0("renderer", "RenderWidget::InvalidationCallback");
1496 invalidation_task_posted_ = false;
1497 DoDeferredUpdateAndSendInputAck();
1500 void RenderWidget::FlushPendingInputEventAck() {
1501 if (pending_input_event_ack_)
1502 Send(pending_input_event_ack_.release());
1503 total_input_handling_time_this_frame_ = base::TimeDelta();
1506 void RenderWidget::DoDeferredUpdateAndSendInputAck() {
1508 FlushPendingInputEventAck();
1511 void RenderWidget::DoDeferredUpdate() {
1512 TRACE_EVENT0("renderer", "RenderWidget::DoDeferredUpdate");
1513 TRACE_EVENT_SCOPED_SAMPLING_STATE("Chrome", "Paint");
1518 if (!init_complete_) {
1519 TRACE_EVENT0("renderer", "EarlyOut_InitNotComplete");
1522 if (update_reply_pending_) {
1523 TRACE_EVENT0("renderer", "EarlyOut_UpdateReplyPending");
1526 if (is_accelerated_compositing_active_ &&
1527 num_swapbuffers_complete_pending_ >= kMaxSwapBuffersPending) {
1528 TRACE_EVENT0("renderer", "EarlyOut_MaxSwapBuffersPending");
1532 // Suppress updating when we are hidden.
1533 if (is_hidden_ || size_.IsEmpty() || is_swapped_out_) {
1534 paint_aggregator_.ClearPendingUpdate();
1535 needs_repainting_on_restore_ = true;
1536 TRACE_EVENT0("renderer", "EarlyOut_NotVisible");
1540 // Tracking of frame rate jitter
1541 base::TimeTicks frame_begin_ticks = gfx::FrameTime::Now();
1542 InstrumentWillBeginFrame(0);
1545 // Layout may generate more invalidation. It may also enable the
1546 // GPU acceleration, so make sure to run layout before we send the
1547 // GpuRenderingActivated message.
1548 webwidget_->layout();
1550 // Check for whether we need to track swap buffers. We need to do that after
1551 // layout() because it may have switched us to accelerated compositing.
1552 if (is_accelerated_compositing_active_)
1553 using_asynchronous_swapbuffers_ = SupportsAsynchronousSwapBuffers();
1555 // The following two can result in further layout and possibly
1556 // enable GPU acceleration so they need to be called before any painting
1558 UpdateTextInputType();
1559 #if defined(OS_ANDROID)
1560 UpdateSelectionRootBounds();
1562 UpdateSelectionBounds();
1564 // Suppress painting if nothing is dirty. This has to be done after updating
1565 // animations running layout as these may generate further invalidations.
1566 if (!paint_aggregator_.HasPendingUpdate()) {
1567 TRACE_EVENT0("renderer", "EarlyOut_NoPendingUpdate");
1568 InstrumentDidCancelFrame();
1572 if (!is_accelerated_compositing_active_ &&
1573 !is_threaded_compositing_enabled_ &&
1574 (ForceCompositingModeEnabled() ||
1575 was_accelerated_compositing_ever_active_)) {
1576 webwidget_->enterForceCompositingMode(true);
1579 if (!last_do_deferred_update_time_.is_null()) {
1580 base::TimeDelta delay = frame_begin_ticks - last_do_deferred_update_time_;
1581 if (is_accelerated_compositing_active_) {
1582 UMA_HISTOGRAM_CUSTOM_TIMES("Renderer4.AccelDoDeferredUpdateDelay",
1584 base::TimeDelta::FromMilliseconds(1),
1585 base::TimeDelta::FromMilliseconds(120),
1588 UMA_HISTOGRAM_CUSTOM_TIMES("Renderer4.SoftwareDoDeferredUpdateDelay",
1590 base::TimeDelta::FromMilliseconds(1),
1591 base::TimeDelta::FromMilliseconds(120),
1595 // Calculate filtered time per frame:
1596 float frame_time_elapsed = static_cast<float>(delay.InSecondsF());
1597 filtered_time_per_frame_ =
1598 0.9f * filtered_time_per_frame_ + 0.1f * frame_time_elapsed;
1600 last_do_deferred_update_time_ = frame_begin_ticks;
1602 if (!is_accelerated_compositing_active_) {
1603 legacy_software_mode_stats_->IncrementFrameCount(1, true);
1604 cc::BenchmarkInstrumentation::IssueMainThreadRenderingStatsEvent(
1605 legacy_software_mode_stats_->main_thread_rendering_stats());
1606 legacy_software_mode_stats_->AccumulateAndClearMainThreadStats();
1609 // OK, save the pending update to a local since painting may cause more
1610 // invalidation. Some WebCore rendering objects only layout when painted.
1611 PaintAggregator::PendingUpdate update;
1612 paint_aggregator_.PopPendingUpdate(&update);
1614 gfx::Rect scroll_damage = update.GetScrollDamage();
1615 gfx::Rect bounds = gfx::UnionRects(update.GetPaintBounds(), scroll_damage);
1617 // A plugin may be able to do an optimized paint. First check this, in which
1618 // case we can skip all of the bitmap generation and regular paint code.
1619 // This optimization allows PPAPI plugins that declare themselves on top of
1620 // the page (like a traditional windowed plugin) to be able to animate (think
1621 // movie playing) without repeatedly re-painting the page underneath, or
1622 // copying the plugin backing store (since we can send the plugin's backing
1623 // store directly to the browser).
1625 // This optimization only works when the entire invalid region is contained
1626 // within the plugin. There is a related optimization in PaintRect for the
1627 // case where there may be multiple invalid regions.
1628 TransportDIB* dib = NULL;
1629 gfx::Rect optimized_copy_rect, optimized_copy_location;
1630 float dib_scale_factor = 1;
1631 DCHECK(!pending_update_params_.get());
1632 pending_update_params_.reset(new ViewHostMsg_UpdateRect_Params);
1633 pending_update_params_->scroll_delta = update.scroll_delta;
1634 pending_update_params_->scroll_rect = update.scroll_rect;
1635 pending_update_params_->view_size = size_;
1636 pending_update_params_->plugin_window_moves.swap(plugin_window_moves_);
1637 pending_update_params_->flags = next_paint_flags_;
1638 pending_update_params_->scroll_offset = GetScrollOffset();
1639 pending_update_params_->needs_ack = true;
1640 pending_update_params_->scale_factor = device_scale_factor_;
1641 next_paint_flags_ = 0;
1642 need_update_rect_for_auto_resize_ = false;
1644 if (!is_accelerated_compositing_active_)
1645 pending_update_params_->latency_info.swap(latency_info_);
1647 latency_info_.clear();
1649 if (update.scroll_rect.IsEmpty() &&
1650 !is_accelerated_compositing_active_ &&
1651 GetBitmapForOptimizedPluginPaint(bounds, &dib, &optimized_copy_location,
1652 &optimized_copy_rect,
1653 &dib_scale_factor)) {
1654 // Only update the part of the plugin that actually changed.
1655 optimized_copy_rect.Intersect(bounds);
1656 pending_update_params_->bitmap = dib->id();
1657 pending_update_params_->bitmap_rect = optimized_copy_location;
1658 pending_update_params_->copy_rects.push_back(optimized_copy_rect);
1659 pending_update_params_->scale_factor = dib_scale_factor;
1660 } else if (!is_accelerated_compositing_active_) {
1661 // Compute a buffer for painting and cache it.
1663 bool fractional_scale = device_scale_factor_ -
1664 static_cast<int>(device_scale_factor_) != 0;
1665 if (fractional_scale) {
1666 // Damage might not be DIP aligned. Inflate damage to compensate.
1667 bounds.Inset(-1, -1);
1668 bounds.Intersect(gfx::Rect(size_));
1671 gfx::Rect pixel_bounds = gfx::ToEnclosingRect(
1672 gfx::ScaleRect(bounds, device_scale_factor_));
1674 scoped_ptr<skia::PlatformCanvas> canvas(
1675 RenderProcess::current()->GetDrawingCanvas(¤t_paint_buf_,
1682 // We may get back a smaller canvas than we asked for.
1683 // TODO(darin): This seems like it could cause painting problems!
1684 DCHECK_EQ(pixel_bounds.width(), canvas->getDevice()->width());
1685 DCHECK_EQ(pixel_bounds.height(), canvas->getDevice()->height());
1686 pixel_bounds.set_width(canvas->getDevice()->width());
1687 pixel_bounds.set_height(canvas->getDevice()->height());
1688 bounds.set_width(pixel_bounds.width() / device_scale_factor_);
1689 bounds.set_height(pixel_bounds.height() / device_scale_factor_);
1691 HISTOGRAM_COUNTS_100("MPArch.RW_PaintRectCount", update.paint_rects.size());
1693 pending_update_params_->bitmap = current_paint_buf_->id();
1694 pending_update_params_->bitmap_rect = bounds;
1696 std::vector<gfx::Rect>& copy_rects = pending_update_params_->copy_rects;
1697 // The scroll damage is just another rectangle to paint and copy.
1698 copy_rects.swap(update.paint_rects);
1699 if (!scroll_damage.IsEmpty())
1700 copy_rects.push_back(scroll_damage);
1702 for (size_t i = 0; i < copy_rects.size(); ++i) {
1703 gfx::Rect rect = copy_rects[i];
1704 if (fractional_scale) {
1705 // Damage might not be DPI aligned. Inflate rect to compensate.
1708 PaintRect(rect, pixel_bounds.origin(), canvas.get());
1711 // Software FPS tick for performance tests. The accelerated path traces the
1712 // frame events in didCommitAndDrawCompositorFrame. See
1713 // tab_capture_performancetest.cc.
1714 // NOTE: Tests may break if this event is renamed or moved.
1715 UNSHIPPED_TRACE_EVENT_INSTANT0("test_fps", "TestFrameTickSW",
1716 TRACE_EVENT_SCOPE_THREAD);
1717 } else { // Accelerated compositing path
1719 // If painting is done via the gpu process then we don't set any damage
1720 // rects to save the browser process from doing unecessary work.
1721 pending_update_params_->bitmap_rect = bounds;
1722 pending_update_params_->scroll_rect = gfx::Rect();
1723 // We don't need an ack, because we're not sharing a DIB with the browser.
1724 // If it needs to (e.g. composited UI), the GPU process does its own ACK
1725 // with the browser for the GPU surface.
1726 pending_update_params_->needs_ack = false;
1727 Composite(frame_begin_ticks);
1730 // If we're holding a pending input event ACK, send the ACK before sending the
1731 // UpdateReply message so we can receive another input event before the
1732 // UpdateRect_ACK on platforms where the UpdateRect_ACK is sent from within
1733 // the UpdateRect IPC message handler.
1734 FlushPendingInputEventAck();
1736 // If Composite() called SwapBuffers, pending_update_params_ will be reset (in
1737 // OnSwapBuffersPosted), meaning a message has been added to the
1738 // updates_pending_swap_ queue, that will be sent later. Otherwise, we send
1740 if (pending_update_params_) {
1741 // sending an ack to browser process that the paint is complete...
1742 update_reply_pending_ = pending_update_params_->needs_ack;
1743 Send(new ViewHostMsg_UpdateRect(routing_id_, *pending_update_params_));
1744 pending_update_params_.reset();
1747 // If we're software rendering then we're done initiating the paint.
1748 if (!is_accelerated_compositing_active_)
1752 void RenderWidget::Composite(base::TimeTicks frame_begin_time) {
1753 DCHECK(is_accelerated_compositing_active_);
1754 if (compositor_) // TODO(jamesr): Figure out how this can be null.
1755 compositor_->Composite(frame_begin_time);
1758 ///////////////////////////////////////////////////////////////////////////////
1761 void RenderWidget::didInvalidateRect(const WebRect& rect) {
1762 // The invalidated rect might be outside the bounds of the view.
1763 gfx::Rect view_rect(size_);
1764 gfx::Rect damaged_rect = gfx::IntersectRects(view_rect, rect);
1765 if (damaged_rect.IsEmpty())
1768 paint_aggregator_.InvalidateRect(damaged_rect);
1770 // We may not need to schedule another call to DoDeferredUpdate.
1771 if (invalidation_task_posted_)
1773 if (!paint_aggregator_.HasPendingUpdate())
1775 if (update_reply_pending_ ||
1776 num_swapbuffers_complete_pending_ >= kMaxSwapBuffersPending)
1779 // When GPU rendering, combine pending animations and invalidations into
1781 if (is_accelerated_compositing_active_ &&
1782 animation_update_pending_ &&
1783 animation_timer_.IsRunning())
1786 // Perform updating asynchronously. This serves two purposes:
1787 // 1) Ensures that we call WebView::Paint without a bunch of other junk
1788 // on the call stack.
1789 // 2) Allows us to collect more damage rects before painting to help coalesce
1790 // the work that we will need to do.
1791 invalidation_task_posted_ = true;
1792 base::MessageLoop::current()->PostTask(
1793 FROM_HERE, base::Bind(&RenderWidget::InvalidationCallback, this));
1796 void RenderWidget::didScrollRect(int dx, int dy,
1797 const WebRect& clip_rect) {
1798 // Drop scrolls on the floor when we are in compositing mode.
1799 // TODO(nduca): stop WebViewImpl from sending scrolls in the first place.
1800 if (is_accelerated_compositing_active_)
1803 // The scrolled rect might be outside the bounds of the view.
1804 gfx::Rect view_rect(size_);
1805 gfx::Rect damaged_rect = gfx::IntersectRects(view_rect, clip_rect);
1806 if (damaged_rect.IsEmpty())
1809 paint_aggregator_.ScrollRect(gfx::Vector2d(dx, dy), damaged_rect);
1811 // We may not need to schedule another call to DoDeferredUpdate.
1812 if (invalidation_task_posted_)
1814 if (!paint_aggregator_.HasPendingUpdate())
1816 if (update_reply_pending_ ||
1817 num_swapbuffers_complete_pending_ >= kMaxSwapBuffersPending)
1820 // When GPU rendering, combine pending animations and invalidations into
1822 if (is_accelerated_compositing_active_ &&
1823 animation_update_pending_ &&
1824 animation_timer_.IsRunning())
1827 // Perform updating asynchronously. This serves two purposes:
1828 // 1) Ensures that we call WebView::Paint without a bunch of other junk
1829 // on the call stack.
1830 // 2) Allows us to collect more damage rects before painting to help coalesce
1831 // the work that we will need to do.
1832 invalidation_task_posted_ = true;
1833 base::MessageLoop::current()->PostTask(
1834 FROM_HERE, base::Bind(&RenderWidget::InvalidationCallback, this));
1837 void RenderWidget::didAutoResize(const WebSize& new_size) {
1838 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1841 // If we don't clear PaintAggregator after changing autoResize state, then
1842 // we might end up in a situation where bitmap_rect is larger than the
1843 // view_size. By clearing PaintAggregator, we ensure that we don't end up
1844 // with invalid damage rects.
1845 paint_aggregator_.ClearPendingUpdate();
1847 if (resizing_mode_selector_->is_synchronous_mode()) {
1848 WebRect new_pos(rootWindowRect().x,
1852 view_screen_rect_ = new_pos;
1853 window_screen_rect_ = new_pos;
1856 AutoResizeCompositor();
1858 if (!resizing_mode_selector_->is_synchronous_mode())
1859 need_update_rect_for_auto_resize_ = true;
1863 void RenderWidget::AutoResizeCompositor() {
1864 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1865 device_scale_factor_));
1867 compositor_->setViewportSize(size_, physical_backing_size_);
1870 // FIXME: To be removed as soon as chromium and blink side changes land
1871 // didActivateCompositor with parameters is still kept in order to land
1872 // these changes s-chromium - https://codereview.chromium.org/137893025/.
1873 // s-blink - https://codereview.chromium.org/138523003/
1874 void RenderWidget::didActivateCompositor(int input_handler_identifier) {
1875 TRACE_EVENT0("gpu", "RenderWidget::didActivateCompositor");
1877 #if !defined(OS_MACOSX)
1878 if (!is_accelerated_compositing_active_) {
1879 // When not in accelerated compositing mode, in certain cases (e.g. waiting
1880 // for a resize or if no backing store) the RenderWidgetHost is blocking the
1881 // browser's UI thread for some time, waiting for an UpdateRect. If we are
1882 // going to switch to accelerated compositing, the GPU process may need
1883 // round-trips to the browser's UI thread before finishing the frame,
1884 // causing deadlocks if we delay the UpdateRect until we receive the
1885 // OnSwapBuffersComplete. So send a dummy message that will unblock the
1886 // browser's UI thread. This is not necessary on Mac, because SwapBuffers
1887 // now unblocks GetBackingStore on Mac.
1888 Send(new ViewHostMsg_UpdateIsDelayed(routing_id_));
1892 is_accelerated_compositing_active_ = true;
1893 Send(new ViewHostMsg_DidActivateAcceleratedCompositing(
1894 routing_id_, is_accelerated_compositing_active_));
1896 if (!was_accelerated_compositing_ever_active_) {
1897 was_accelerated_compositing_ever_active_ = true;
1898 webwidget_->enterForceCompositingMode(true);
1902 void RenderWidget::didActivateCompositor() {
1903 TRACE_EVENT0("gpu", "RenderWidget::didActivateCompositor");
1905 #if !defined(OS_MACOSX)
1906 if (!is_accelerated_compositing_active_) {
1907 // When not in accelerated compositing mode, in certain cases (e.g. waiting
1908 // for a resize or if no backing store) the RenderWidgetHost is blocking the
1909 // browser's UI thread for some time, waiting for an UpdateRect. If we are
1910 // going to switch to accelerated compositing, the GPU process may need
1911 // round-trips to the browser's UI thread before finishing the frame,
1912 // causing deadlocks if we delay the UpdateRect until we receive the
1913 // OnSwapBuffersComplete. So send a dummy message that will unblock the
1914 // browser's UI thread. This is not necessary on Mac, because SwapBuffers
1915 // now unblocks GetBackingStore on Mac.
1916 Send(new ViewHostMsg_UpdateIsDelayed(routing_id_));
1920 is_accelerated_compositing_active_ = true;
1921 Send(new ViewHostMsg_DidActivateAcceleratedCompositing(
1922 routing_id_, is_accelerated_compositing_active_));
1924 if (!was_accelerated_compositing_ever_active_) {
1925 was_accelerated_compositing_ever_active_ = true;
1926 webwidget_->enterForceCompositingMode(true);
1930 void RenderWidget::didDeactivateCompositor() {
1931 TRACE_EVENT0("gpu", "RenderWidget::didDeactivateCompositor");
1933 is_accelerated_compositing_active_ = false;
1934 Send(new ViewHostMsg_DidActivateAcceleratedCompositing(
1935 routing_id_, is_accelerated_compositing_active_));
1937 if (using_asynchronous_swapbuffers_)
1938 using_asynchronous_swapbuffers_ = false;
1940 // In single-threaded mode, we exit force compositing mode and re-enter in
1941 // DoDeferredUpdate() if appropriate. In threaded compositing mode,
1942 // DoDeferredUpdate() is bypassed and WebKit is responsible for exiting and
1943 // entering force compositing mode at the appropriate times.
1944 if (!is_threaded_compositing_enabled_)
1945 webwidget_->enterForceCompositingMode(false);
1948 void RenderWidget::initializeLayerTreeView() {
1949 compositor_ = RenderWidgetCompositor::Create(
1950 this, is_threaded_compositing_enabled_);
1954 compositor_->setViewportSize(size_, physical_backing_size_);
1956 compositor_->setSurfaceReady();
1959 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1960 return compositor_.get();
1963 void RenderWidget::suppressCompositorScheduling(bool enable) {
1965 compositor_->SetSuppressScheduleComposite(enable);
1968 void RenderWidget::willBeginCompositorFrame() {
1969 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1971 DCHECK(RenderThreadImpl::current()->compositor_message_loop_proxy().get());
1973 // The following two can result in further layout and possibly
1974 // enable GPU acceleration so they need to be called before any painting
1976 UpdateTextInputType();
1977 #if defined(OS_ANDROID)
1978 UpdateTextInputState(false, true);
1979 UpdateSelectionRootBounds();
1981 UpdateSelectionBounds();
1984 void RenderWidget::didBecomeReadyForAdditionalInput() {
1985 TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1986 FlushPendingInputEventAck();
1989 void RenderWidget::DidCommitCompositorFrame() {
1990 FOR_EACH_OBSERVER(RenderFrameImpl, swapped_out_frames_,
1991 DidCommitCompositorFrame());
1994 void RenderWidget::didCommitAndDrawCompositorFrame() {
1995 TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1996 // Accelerated FPS tick for performance tests. See
1997 // tab_capture_performancetest.cc. NOTE: Tests may break if this event is
1998 // renamed or moved.
1999 UNSHIPPED_TRACE_EVENT_INSTANT0("test_fps", "TestFrameTickGPU",
2000 TRACE_EVENT_SCOPE_THREAD);
2001 // Notify subclasses that we initiated the paint operation.
2005 void RenderWidget::didCompleteSwapBuffers() {
2006 TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
2008 // Notify subclasses threaded composited rendering was flushed to the screen.
2011 if (update_reply_pending_)
2014 if (!next_paint_flags_ &&
2015 !need_update_rect_for_auto_resize_ &&
2016 !plugin_window_moves_.size()) {
2020 ViewHostMsg_UpdateRect_Params params;
2021 params.view_size = size_;
2022 params.plugin_window_moves.swap(plugin_window_moves_);
2023 params.flags = next_paint_flags_;
2024 params.scroll_offset = GetScrollOffset();
2025 params.needs_ack = false;
2026 params.scale_factor = device_scale_factor_;
2028 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
2029 next_paint_flags_ = 0;
2030 need_update_rect_for_auto_resize_ = false;
2033 void RenderWidget::scheduleComposite() {
2034 if (RenderThreadImpl::current()->compositor_message_loop_proxy().get() &&
2036 compositor_->setNeedsAnimate();
2038 // TODO(nduca): replace with something a little less hacky. The reason this
2039 // hack is still used is because the Invalidate-DoDeferredUpdate loop
2040 // contains a lot of host-renderer synchronization logic that is still
2041 // important for the accelerated compositing case. The option of simply
2042 // duplicating all that code is less desirable than "faking out" the
2043 // invalidation path using a magical damage rect.
2044 didInvalidateRect(WebRect(0, 0, 1, 1));
2048 void RenderWidget::scheduleAnimation() {
2049 if (animation_update_pending_)
2052 TRACE_EVENT0("gpu", "RenderWidget::scheduleAnimation");
2053 animation_update_pending_ = true;
2054 if (!animation_timer_.IsRunning()) {
2055 animation_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(0), this,
2056 &RenderWidget::AnimationCallback);
2060 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
2061 // TODO(darin): Eliminate this temporary.
2063 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
2064 // Only send a SetCursor message if we need to make a change.
2065 if (!current_cursor_.IsEqual(cursor)) {
2066 current_cursor_ = cursor;
2067 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
2071 // We are supposed to get a single call to Show for a newly created RenderWidget
2072 // that was created via RenderWidget::CreateWebView. So, we wait until this
2073 // point to dispatch the ShowWidget message.
2075 // This method provides us with the information about how to display the newly
2076 // created RenderWidget (i.e., as a blocked popup or as a new tab).
2078 void RenderWidget::show(WebNavigationPolicy) {
2079 DCHECK(!did_show_) << "received extraneous Show call";
2080 DCHECK(routing_id_ != MSG_ROUTING_NONE);
2081 DCHECK(opener_id_ != MSG_ROUTING_NONE);
2087 // NOTE: initial_pos_ may still have its default values at this point, but
2088 // that's okay. It'll be ignored if as_popup is false, or the browser
2089 // process will impose a default position otherwise.
2090 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_pos_));
2091 SetPendingWindowRect(initial_pos_);
2094 void RenderWidget::didFocus() {
2097 void RenderWidget::didBlur() {
2100 void RenderWidget::DoDeferredClose() {
2101 Send(new ViewHostMsg_Close(routing_id_));
2104 void RenderWidget::closeWidgetSoon() {
2105 if (is_swapped_out_) {
2106 // This widget is currently swapped out, and the active widget is in a
2107 // different process. Have the browser route the close request to the
2108 // active widget instead, so that the correct unload handlers are run.
2109 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
2113 // If a page calls window.close() twice, we'll end up here twice, but that's
2114 // OK. It is safe to send multiple Close messages.
2116 // Ask the RenderWidgetHost to initiate close. We could be called from deep
2117 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
2118 // could be closed before the JS finishes executing. So instead, post a
2119 // message back to the message loop, which won't run until the JS is
2120 // complete, and then the Close message can be sent.
2121 base::MessageLoop::current()->PostTask(
2122 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
2125 void RenderWidget::QueueSyntheticGesture(
2126 scoped_ptr<SyntheticGestureParams> gesture_params,
2127 const SyntheticGestureCompletionCallback& callback) {
2128 DCHECK(!callback.is_null());
2130 pending_synthetic_gesture_callbacks_.push(callback);
2132 SyntheticGesturePacket gesture_packet;
2133 gesture_packet.set_gesture_params(gesture_params.Pass());
2135 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
2138 void RenderWidget::Close() {
2140 webwidget_->willCloseLayerTreeView();
2141 compositor_.reset();
2142 webwidget_->close();
2147 WebRect RenderWidget::windowRect() {
2148 if (pending_window_rect_count_)
2149 return pending_window_rect_;
2151 return view_screen_rect_;
2154 void RenderWidget::setToolTipText(const blink::WebString& text,
2155 WebTextDirection hint) {
2156 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
2159 void RenderWidget::setWindowRect(const WebRect& rect) {
2161 if (popup_origin_scale_for_emulation_) {
2162 float scale = popup_origin_scale_for_emulation_;
2163 pos.x = popup_screen_origin_for_emulation_.x() +
2164 (pos.x - popup_view_origin_for_emulation_.x()) * scale;
2165 pos.y = popup_screen_origin_for_emulation_.y() +
2166 (pos.y - popup_view_origin_for_emulation_.y()) * scale;
2169 if (!resizing_mode_selector_->is_synchronous_mode()) {
2171 Send(new ViewHostMsg_RequestMove(routing_id_, pos));
2172 SetPendingWindowRect(pos);
2177 ResizeSynchronously(pos);
2181 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
2182 pending_window_rect_ = rect;
2183 pending_window_rect_count_++;
2186 WebRect RenderWidget::rootWindowRect() {
2187 if (pending_window_rect_count_) {
2188 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
2189 // the RootWindowRect is probably going to return wrong results since the
2190 // browser may not have processed the Move yet. There isn't really anything
2191 // good to do in this case, and it shouldn't happen - since this size is
2192 // only really needed for windowToScreen, which is only used for Popups.
2193 return pending_window_rect_;
2196 return window_screen_rect_;
2199 WebRect RenderWidget::windowResizerRect() {
2200 return resizer_rect_;
2203 void RenderWidget::OnSetInputMethodActive(bool is_active) {
2204 // To prevent this renderer process from sending unnecessary IPC messages to
2205 // a browser process, we permit the renderer process to send IPC messages
2206 // only during the input method attached to the browser process is active.
2207 input_method_is_active_ = is_active;
2210 void RenderWidget::OnCandidateWindowShown() {
2211 webwidget_->didShowCandidateWindow();
2214 void RenderWidget::OnCandidateWindowUpdated() {
2215 webwidget_->didUpdateCandidateWindow();
2218 void RenderWidget::OnCandidateWindowHidden() {
2219 webwidget_->didHideCandidateWindow();
2222 void RenderWidget::OnImeSetComposition(
2223 const base::string16& text,
2224 const std::vector<WebCompositionUnderline>& underlines,
2225 int selection_start, int selection_end) {
2226 if (!ShouldHandleImeEvent())
2228 ImeEventGuard guard(this);
2229 if (!webwidget_->setComposition(
2230 text, WebVector<WebCompositionUnderline>(underlines),
2231 selection_start, selection_end)) {
2232 // If we failed to set the composition text, then we need to let the browser
2233 // process to cancel the input method's ongoing composition session, to make
2234 // sure we are in a consistent state.
2235 Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
2237 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
2238 UpdateCompositionInfo(true);
2242 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
2243 const gfx::Range& replacement_range,
2244 bool keep_selection) {
2245 if (!ShouldHandleImeEvent())
2247 ImeEventGuard guard(this);
2248 handling_input_event_ = true;
2250 webwidget_->confirmComposition(text);
2251 else if (keep_selection)
2252 webwidget_->confirmComposition(WebWidget::KeepSelection);
2254 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
2255 handling_input_event_ = false;
2256 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
2257 UpdateCompositionInfo(true);
2261 void RenderWidget::OnSnapshot(const gfx::Rect& src_subrect) {
2264 if (OnSnapshotHelper(src_subrect, &snapshot)) {
2265 Send(new ViewHostMsg_Snapshot(routing_id(), true, snapshot));
2267 Send(new ViewHostMsg_Snapshot(routing_id(), false, SkBitmap()));
2271 bool RenderWidget::OnSnapshotHelper(const gfx::Rect& src_subrect,
2272 SkBitmap* snapshot) {
2273 base::TimeTicks beginning_time = base::TimeTicks::Now();
2275 if (!webwidget_ || src_subrect.IsEmpty())
2278 gfx::Rect viewport_size = gfx::IntersectRects(
2279 src_subrect, gfx::Rect(physical_backing_size_));
2281 skia::RefPtr<SkCanvas> canvas = skia::AdoptRef(
2282 skia::CreatePlatformCanvas(viewport_size.width(),
2283 viewport_size.height(),
2286 skia::RETURN_NULL_ON_FAILURE));
2291 webwidget_->layout();
2293 PaintRect(viewport_size, viewport_size.origin(), canvas.get());
2296 const SkBitmap& bitmap = skia::GetTopDevice(*canvas)->accessBitmap(false);
2297 if (!bitmap.copyTo(snapshot, kPMColor_SkColorType))
2300 UMA_HISTOGRAM_TIMES("Renderer4.Snapshot",
2301 base::TimeTicks::Now() - beginning_time);
2305 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
2306 // During shutdown we can just ignore this message.
2310 // Even if the browser provides an empty damage rect, it's still expecting to
2311 // receive a repaint ack so just damage the entire widget bounds.
2312 if (size_to_paint.IsEmpty()) {
2313 size_to_paint = size_;
2316 set_next_paint_is_repaint_ack();
2317 if (is_accelerated_compositing_active_ && compositor_) {
2318 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
2320 gfx::Rect repaint_rect(size_to_paint.width(), size_to_paint.height());
2321 didInvalidateRect(repaint_rect);
2325 void RenderWidget::OnSyntheticGestureCompleted() {
2326 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
2328 pending_synthetic_gesture_callbacks_.front().Run();
2329 pending_synthetic_gesture_callbacks_.pop();
2332 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
2335 webwidget_->setTextDirection(direction);
2338 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
2339 const gfx::Rect& window_screen_rect) {
2340 if (screen_metrics_emulator_) {
2341 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
2342 view_screen_rect, window_screen_rect);
2344 view_screen_rect_ = view_screen_rect;
2345 window_screen_rect_ = window_screen_rect;
2347 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
2350 #if defined(OS_ANDROID)
2351 void RenderWidget::OnShowImeIfNeeded() {
2352 UpdateTextInputState(true, true);
2355 void RenderWidget::IncrementOutstandingImeEventAcks() {
2356 ++outstanding_ime_acks_;
2359 void RenderWidget::OnImeEventAck() {
2360 --outstanding_ime_acks_;
2361 DCHECK(outstanding_ime_acks_ >= 0);
2365 bool RenderWidget::ShouldHandleImeEvent() {
2366 #if defined(OS_ANDROID)
2367 return !!webwidget_ && outstanding_ime_acks_ == 0;
2369 return !!webwidget_;
2373 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
2374 if (device_scale_factor_ == device_scale_factor)
2377 device_scale_factor_ = device_scale_factor;
2379 if (!is_accelerated_compositing_active_) {
2380 didInvalidateRect(gfx::Rect(size_.width(), size_.height()));
2382 scheduleComposite();
2386 PepperPluginInstanceImpl* RenderWidget::GetBitmapForOptimizedPluginPaint(
2387 const gfx::Rect& paint_bounds,
2389 gfx::Rect* location,
2391 float* scale_factor) {
2392 // Bare RenderWidgets don't support optimized plugin painting.
2396 gfx::Vector2d RenderWidget::GetScrollOffset() {
2397 // Bare RenderWidgets don't support scroll offset.
2398 return gfx::Vector2d();
2401 void RenderWidget::SetHidden(bool hidden) {
2402 if (is_hidden_ == hidden)
2405 // The status has changed. Tell the RenderThread about it.
2406 is_hidden_ = hidden;
2408 RenderThreadImpl::current()->WidgetHidden();
2410 RenderThreadImpl::current()->WidgetRestored();
2413 void RenderWidget::WillToggleFullscreen() {
2417 if (is_fullscreen_) {
2418 webwidget_->willExitFullScreen();
2420 webwidget_->willEnterFullScreen();
2424 void RenderWidget::DidToggleFullscreen() {
2428 if (is_fullscreen_) {
2429 webwidget_->didEnterFullScreen();
2431 webwidget_->didExitFullScreen();
2435 void RenderWidget::SetBackground(const SkBitmap& background) {
2436 background_ = background;
2438 // Generate a full repaint.
2439 didInvalidateRect(gfx::Rect(size_.width(), size_.height()));
2442 bool RenderWidget::next_paint_is_resize_ack() const {
2443 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
2446 bool RenderWidget::next_paint_is_restore_ack() const {
2447 return ViewHostMsg_UpdateRect_Flags::is_restore_ack(next_paint_flags_);
2450 void RenderWidget::set_next_paint_is_resize_ack() {
2451 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
2454 void RenderWidget::set_next_paint_is_restore_ack() {
2455 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESTORE_ACK;
2458 void RenderWidget::set_next_paint_is_repaint_ack() {
2459 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
2462 static bool IsDateTimeInput(ui::TextInputType type) {
2463 return type == ui::TEXT_INPUT_TYPE_DATE ||
2464 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
2465 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
2466 type == ui::TEXT_INPUT_TYPE_MONTH ||
2467 type == ui::TEXT_INPUT_TYPE_TIME ||
2468 type == ui::TEXT_INPUT_TYPE_WEEK;
2472 void RenderWidget::StartHandlingImeEvent() {
2473 DCHECK(!handling_ime_event_);
2474 handling_ime_event_ = true;
2477 void RenderWidget::FinishHandlingImeEvent() {
2478 DCHECK(handling_ime_event_);
2479 handling_ime_event_ = false;
2480 // While handling an ime event, text input state and selection bounds updates
2481 // are ignored. These must explicitly be updated once finished handling the
2483 #if defined(OS_ANDROID)
2484 UpdateSelectionRootBounds();
2486 UpdateSelectionBounds();
2487 #if defined(OS_ANDROID)
2488 UpdateTextInputState(false, false);
2492 void RenderWidget::UpdateTextInputType() {
2493 // On Windows, not only an IME but also an on-screen keyboard relies on the
2494 // latest TextInputType to optimize its layout and functionality. Thus
2495 // |input_method_is_active_| is no longer an appropriate condition to suppress
2496 // TextInputTypeChanged IPC on Windows.
2497 // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
2498 // on other platforms as well as Windows if the overhead is acceptable.
2499 #if !defined(OS_WIN)
2500 if (!input_method_is_active_)
2504 ui::TextInputType new_type = GetTextInputType();
2505 if (IsDateTimeInput(new_type))
2506 return; // Not considered as a text input field in WebKit/Chromium.
2508 bool new_can_compose_inline = CanComposeInline();
2510 blink::WebTextInputInfo new_info;
2512 new_info = webwidget_->textInputInfo();
2513 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
2515 if (text_input_type_ != new_type
2516 || can_compose_inline_ != new_can_compose_inline
2517 || text_input_mode_ != new_mode) {
2518 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
2521 new_can_compose_inline));
2522 text_input_type_ = new_type;
2523 can_compose_inline_ = new_can_compose_inline;
2524 text_input_mode_ = new_mode;
2528 #if defined(OS_ANDROID) || defined(USE_AURA)
2529 void RenderWidget::UpdateTextInputState(bool show_ime_if_needed,
2530 bool send_ime_ack) {
2531 if (handling_ime_event_)
2533 if (!show_ime_if_needed && !input_method_is_active_)
2535 ui::TextInputType new_type = GetTextInputType();
2536 if (IsDateTimeInput(new_type))
2537 return; // Not considered as a text input field in WebKit/Chromium.
2539 blink::WebTextInputInfo new_info;
2541 new_info = webwidget_->textInputInfo();
2543 bool new_can_compose_inline = CanComposeInline();
2545 // Only sends text input params if they are changed or if the ime should be
2547 if (show_ime_if_needed || (text_input_type_ != new_type
2548 || text_input_info_ != new_info
2549 || can_compose_inline_ != new_can_compose_inline)) {
2550 ViewHostMsg_TextInputState_Params p;
2551 #if defined(USE_AURA)
2552 p.require_ack = false;
2555 p.value = new_info.value.utf8();
2556 p.selection_start = new_info.selectionStart;
2557 p.selection_end = new_info.selectionEnd;
2558 p.composition_start = new_info.compositionStart;
2559 p.composition_end = new_info.compositionEnd;
2560 p.can_compose_inline = new_can_compose_inline;
2561 p.show_ime_if_needed = show_ime_if_needed;
2562 #if defined(OS_ANDROID)
2563 p.require_ack = send_ime_ack;
2565 IncrementOutstandingImeEventAcks();
2567 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
2569 text_input_info_ = new_info;
2570 text_input_type_ = new_type;
2571 can_compose_inline_ = new_can_compose_inline;
2576 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
2577 WebRect focus_webrect;
2578 WebRect anchor_webrect;
2579 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
2580 *focus = focus_webrect;
2581 *anchor = anchor_webrect;
2584 void RenderWidget::UpdateSelectionBounds() {
2587 if (handling_ime_event_)
2590 ViewHostMsg_SelectionBounds_Params params;
2591 GetSelectionBounds(¶ms.anchor_rect, ¶ms.focus_rect);
2592 if (selection_anchor_rect_ != params.anchor_rect ||
2593 selection_focus_rect_ != params.focus_rect) {
2594 selection_anchor_rect_ = params.anchor_rect;
2595 selection_focus_rect_ = params.focus_rect;
2596 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
2597 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
2598 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
2600 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
2601 UpdateCompositionInfo(false);
2605 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
2606 COMPILE_ASSERT(int(blink::WebTextInputTypeNone) == \
2607 int(ui::TEXT_INPUT_TYPE_NONE), mismatching_enums);
2608 COMPILE_ASSERT(int(blink::WebTextInputTypeText) == \
2609 int(ui::TEXT_INPUT_TYPE_TEXT), mismatching_enums);
2610 COMPILE_ASSERT(int(blink::WebTextInputTypePassword) == \
2611 int(ui::TEXT_INPUT_TYPE_PASSWORD), mismatching_enums);
2612 COMPILE_ASSERT(int(blink::WebTextInputTypeSearch) == \
2613 int(ui::TEXT_INPUT_TYPE_SEARCH), mismatching_enums);
2614 COMPILE_ASSERT(int(blink::WebTextInputTypeEmail) == \
2615 int(ui::TEXT_INPUT_TYPE_EMAIL), mismatching_enums);
2616 COMPILE_ASSERT(int(blink::WebTextInputTypeNumber) == \
2617 int(ui::TEXT_INPUT_TYPE_NUMBER), mismatching_enums);
2618 COMPILE_ASSERT(int(blink::WebTextInputTypeTelephone) == \
2619 int(ui::TEXT_INPUT_TYPE_TELEPHONE), mismatching_enums);
2620 COMPILE_ASSERT(int(blink::WebTextInputTypeURL) == \
2621 int(ui::TEXT_INPUT_TYPE_URL), mismatching_enums);
2622 COMPILE_ASSERT(int(blink::WebTextInputTypeDate) == \
2623 int(ui::TEXT_INPUT_TYPE_DATE), mismatching_enum);
2624 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTime) == \
2625 int(ui::TEXT_INPUT_TYPE_DATE_TIME), mismatching_enum);
2626 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeLocal) == \
2627 int(ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL), mismatching_enum);
2628 COMPILE_ASSERT(int(blink::WebTextInputTypeMonth) == \
2629 int(ui::TEXT_INPUT_TYPE_MONTH), mismatching_enum);
2630 COMPILE_ASSERT(int(blink::WebTextInputTypeTime) == \
2631 int(ui::TEXT_INPUT_TYPE_TIME), mismatching_enum);
2632 COMPILE_ASSERT(int(blink::WebTextInputTypeWeek) == \
2633 int(ui::TEXT_INPUT_TYPE_WEEK), mismatching_enum);
2634 COMPILE_ASSERT(int(blink::WebTextInputTypeTextArea) == \
2635 int(ui::TEXT_INPUT_TYPE_TEXT_AREA), mismatching_enums);
2636 COMPILE_ASSERT(int(blink::WebTextInputTypeContentEditable) == \
2637 int(ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE), mismatching_enums);
2638 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeField) == \
2639 int(ui::TEXT_INPUT_TYPE_DATE_TIME_FIELD), mismatching_enums);
2641 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2642 blink::WebTextInputType type) {
2643 // Check the type is in the range representable by ui::TextInputType.
2644 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2645 "blink::WebTextInputType and ui::TextInputType not synchronized";
2646 return static_cast<ui::TextInputType>(type);
2649 ui::TextInputType RenderWidget::GetTextInputType() {
2651 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2652 return ui::TEXT_INPUT_TYPE_NONE;
2655 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
2656 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2657 gfx::Range range = gfx::Range();
2658 if (should_update_range) {
2659 GetCompositionRange(&range);
2661 range = composition_range_;
2663 std::vector<gfx::Rect> character_bounds;
2664 GetCompositionCharacterBounds(&character_bounds);
2666 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2668 composition_character_bounds_ = character_bounds;
2669 composition_range_ = range;
2670 Send(new ViewHostMsg_ImeCompositionRangeChanged(
2671 routing_id(), composition_range_, composition_character_bounds_));
2674 void RenderWidget::GetCompositionCharacterBounds(
2675 std::vector<gfx::Rect>* bounds) {
2680 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2681 size_t location, length;
2682 if (webwidget_->compositionRange(&location, &length)) {
2683 range->set_start(location);
2684 range->set_end(location + length);
2685 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2686 range->set_start(location);
2687 range->set_end(location + length);
2689 *range = gfx::Range::InvalidRange();
2693 bool RenderWidget::ShouldUpdateCompositionInfo(
2694 const gfx::Range& range,
2695 const std::vector<gfx::Rect>& bounds) {
2696 if (composition_range_ != range)
2698 if (bounds.size() != composition_character_bounds_.size())
2700 for (size_t i = 0; i < bounds.size(); ++i) {
2701 if (bounds[i] != composition_character_bounds_[i])
2708 bool RenderWidget::CanComposeInline() {
2712 WebScreenInfo RenderWidget::screenInfo() {
2713 return screen_info_;
2716 float RenderWidget::deviceScaleFactor() {
2717 return device_scale_factor_;
2720 void RenderWidget::resetInputMethod() {
2721 if (!input_method_is_active_)
2724 ImeEventGuard guard(this);
2725 // If the last text input type is not None, then we should finish any
2726 // ongoing composition regardless of the new text input type.
2727 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2728 // If a composition text exists, then we need to let the browser process
2729 // to cancel the input method's ongoing composition session.
2730 if (webwidget_->confirmComposition())
2731 Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
2734 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
2735 UpdateCompositionInfo(true);
2739 void RenderWidget::didHandleGestureEvent(
2740 const WebGestureEvent& event,
2741 bool event_cancelled) {
2742 #if defined(OS_ANDROID) || defined(USE_AURA)
2743 if (event_cancelled)
2745 if (event.type == WebInputEvent::GestureTap ||
2746 event.type == WebInputEvent::GestureLongPress) {
2747 UpdateTextInputState(true, true);
2752 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2754 for (; i < plugin_window_moves_.size(); ++i) {
2755 if (plugin_window_moves_[i].window == move.window) {
2756 if (move.rects_valid) {
2757 plugin_window_moves_[i] = move;
2759 plugin_window_moves_[i].visible = move.visible;
2765 if (i == plugin_window_moves_.size())
2766 plugin_window_moves_.push_back(move);
2769 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2770 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2771 i != plugin_window_moves_.end(); ++i) {
2772 if (i->window == window) {
2773 plugin_window_moves_.erase(i);
2780 RenderWidgetCompositor* RenderWidget::compositor() const {
2781 return compositor_.get();
2784 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2788 bool RenderWidget::WillHandleGestureEvent(
2789 const blink::WebGestureEvent& event) {
2793 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2794 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2797 void RenderWidget::setTouchAction(
2798 blink::WebTouchAction web_touch_action) {
2800 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2801 // when blink is emulating touch with mouse).
2802 if (!handling_touchstart_event_)
2805 // Verify the same values are used by the types so we can cast between them.
2806 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_AUTO) ==
2807 blink::WebTouchActionAuto,
2808 enum_values_must_match_for_touch_action);
2809 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_NONE) ==
2810 blink::WebTouchActionNone,
2811 enum_values_must_match_for_touch_action);
2812 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_X) ==
2813 blink::WebTouchActionPanX,
2814 enum_values_must_match_for_touch_action);
2815 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_Y) ==
2816 blink::WebTouchActionPanY,
2817 enum_values_must_match_for_touch_action);
2819 static_cast<blink::WebTouchAction>(TOUCH_ACTION_PINCH_ZOOM) ==
2820 blink::WebTouchActionPinchZoom,
2821 enum_values_must_match_for_touch_action);
2823 content::TouchAction content_touch_action =
2824 static_cast<content::TouchAction>(web_touch_action);
2825 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2828 #if defined(OS_ANDROID)
2829 void RenderWidget::UpdateSelectionRootBounds() {
2833 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2837 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2838 RenderWidget::CreateGraphicsContext3D(
2839 const blink::WebGraphicsContext3D::Attributes& attributes) {
2841 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2842 if (CommandLine::ForCurrentProcess()->HasSwitch(
2843 switches::kDisableGpuCompositing))
2844 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2845 if (!RenderThreadImpl::current())
2846 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2847 CauseForGpuLaunch cause =
2848 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2849 scoped_refptr<GpuChannelHost> gpu_channel_host(
2850 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2851 if (!gpu_channel_host)
2852 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2854 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2855 #if defined(OS_ANDROID)
2856 // If we raster too fast we become upload bound, and pending
2857 // uploads consume memory. For maximum upload throughput, we would
2858 // want to allow for upload_throughput * pipeline_time of pending
2859 // uploads, after which we are just wasting memory. Since we don't
2860 // know our upload throughput yet, this just caps our memory usage.
2862 if (base::android::SysUtils::IsLowEndDevice())
2864 // For reference Nexus10 can upload 1MB in about 2.5ms.
2865 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2866 // Deadline to draw a frame to achieve 60 frames per second.
2867 const size_t kMillisecondsPerFrame = 16;
2868 // Assuming a two frame deep pipeline between the CPU and the GPU.
2869 size_t max_transfer_buffer_usage_mb =
2870 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2871 static const size_t kBytesPerMegabyte = 1024 * 1024;
2872 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2873 // to avoid unnecessarily stalling the compositor thread.
2874 limits.mapped_memory_reclaim_limit =
2875 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2878 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2879 new WebGraphicsContext3DCommandBufferImpl(
2881 GetURLForGraphicsContext3D(),
2882 gpu_channel_host.get(),
2884 false /* bind generates resources */,
2887 return context.Pass();
2890 void RenderWidget::RegisterSwappedOutChildFrame(RenderFrameImpl* frame) {
2891 swapped_out_frames_.AddObserver(frame);
2894 void RenderWidget::UnregisterSwappedOutChildFrame(RenderFrameImpl* frame) {
2895 swapped_out_frames_.RemoveObserver(frame);
2898 } // namespace content