Implement HasPermission() method in PermissionService.
[chromium-blink-merge.git] / content / renderer / render_widget.cc
blob537694ea95cf7573da4334b78af6a6b0059e8990
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_widget.h"
7 #include "base/auto_reset.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/debug/trace_event_synthetic_delay.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/singleton.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/stl_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/sys_info.h"
20 #include "build/build_config.h"
21 #include "cc/base/switches.h"
22 #include "cc/debug/benchmark_instrumentation.h"
23 #include "cc/output/output_surface.h"
24 #include "cc/trees/layer_tree_host.h"
25 #include "content/child/npapi/webplugin.h"
26 #include "content/common/gpu/client/context_provider_command_buffer.h"
27 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
28 #include "content/common/gpu/gpu_process_launch_causes.h"
29 #include "content/common/input/synthetic_gesture_packet.h"
30 #include "content/common/input/web_input_event_traits.h"
31 #include "content/common/input_messages.h"
32 #include "content/common/swapped_out_messages.h"
33 #include "content/common/view_messages.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/context_menu_params.h"
36 #include "content/renderer/cursor_utils.h"
37 #include "content/renderer/external_popup_menu.h"
38 #include "content/renderer/gpu/compositor_output_surface.h"
39 #include "content/renderer/gpu/compositor_software_output_device.h"
40 #include "content/renderer/gpu/delegated_compositor_output_surface.h"
41 #include "content/renderer/gpu/frame_swap_message_queue.h"
42 #include "content/renderer/gpu/mailbox_output_surface.h"
43 #include "content/renderer/gpu/queue_message_swap_promise.h"
44 #include "content/renderer/gpu/render_widget_compositor.h"
45 #include "content/renderer/ime_event_guard.h"
46 #include "content/renderer/input/input_handler_manager.h"
47 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
48 #include "content/renderer/render_frame_impl.h"
49 #include "content/renderer/render_frame_proxy.h"
50 #include "content/renderer/render_process.h"
51 #include "content/renderer/render_thread_impl.h"
52 #include "content/renderer/renderer_blink_platform_impl.h"
53 #include "content/renderer/resizing_mode_selector.h"
54 #include "ipc/ipc_sync_message.h"
55 #include "skia/ext/platform_canvas.h"
56 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
57 #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h"
58 #include "third_party/WebKit/public/platform/WebRect.h"
59 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
60 #include "third_party/WebKit/public/platform/WebSize.h"
61 #include "third_party/WebKit/public/platform/WebString.h"
62 #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h"
63 #include "third_party/WebKit/public/web/WebPagePopup.h"
64 #include "third_party/WebKit/public/web/WebPopupMenu.h"
65 #include "third_party/WebKit/public/web/WebPopupMenuInfo.h"
66 #include "third_party/WebKit/public/web/WebRange.h"
67 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
68 #include "third_party/skia/include/core/SkShader.h"
69 #include "ui/base/ui_base_switches.h"
70 #include "ui/gfx/frame_time.h"
71 #include "ui/gfx/point_conversions.h"
72 #include "ui/gfx/rect_conversions.h"
73 #include "ui/gfx/size_conversions.h"
74 #include "ui/gfx/skia_util.h"
75 #include "ui/gl/gl_switches.h"
76 #include "ui/surface/transport_dib.h"
78 #if defined(OS_ANDROID)
79 #include <android/keycodes.h>
80 #include "base/android/build_info.h"
81 #include "content/renderer/android/synchronous_compositor_factory.h"
82 #endif
84 #if defined(OS_POSIX)
85 #include "ipc/ipc_channel_posix.h"
86 #include "third_party/skia/include/core/SkMallocPixelRef.h"
87 #include "third_party/skia/include/core/SkPixelRef.h"
88 #endif // defined(OS_POSIX)
90 #include "third_party/WebKit/public/web/WebWidget.h"
92 using blink::WebCompositionUnderline;
93 using blink::WebCursorInfo;
94 using blink::WebDeviceEmulationParams;
95 using blink::WebGestureEvent;
96 using blink::WebInputEvent;
97 using blink::WebKeyboardEvent;
98 using blink::WebMouseEvent;
99 using blink::WebMouseWheelEvent;
100 using blink::WebNavigationPolicy;
101 using blink::WebPagePopup;
102 using blink::WebPopupMenu;
103 using blink::WebPopupMenuInfo;
104 using blink::WebPopupType;
105 using blink::WebRange;
106 using blink::WebRect;
107 using blink::WebScreenInfo;
108 using blink::WebSize;
109 using blink::WebTextDirection;
110 using blink::WebTouchEvent;
111 using blink::WebTouchPoint;
112 using blink::WebVector;
113 using blink::WebWidget;
115 namespace {
117 typedef std::map<std::string, ui::TextInputMode> TextInputModeMap;
119 class TextInputModeMapSingleton {
120 public:
121 static TextInputModeMapSingleton* GetInstance() {
122 return Singleton<TextInputModeMapSingleton>::get();
124 TextInputModeMapSingleton() {
125 map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM;
126 map_["latin"] = ui::TEXT_INPUT_MODE_LATIN;
127 map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME;
128 map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE;
129 map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN;
130 map_["kana"] = ui::TEXT_INPUT_MODE_KANA;
131 map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA;
132 map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC;
133 map_["tel"] = ui::TEXT_INPUT_MODE_TEL;
134 map_["email"] = ui::TEXT_INPUT_MODE_EMAIL;
135 map_["url"] = ui::TEXT_INPUT_MODE_URL;
137 const TextInputModeMap& map() const { return map_; }
138 private:
139 TextInputModeMap map_;
141 friend struct DefaultSingletonTraits<TextInputModeMapSingleton>;
143 DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton);
146 ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) {
147 static TextInputModeMapSingleton* singleton =
148 TextInputModeMapSingleton::GetInstance();
149 TextInputModeMap::const_iterator it =
150 singleton->map().find(input_mode.utf8());
151 if (it == singleton->map().end())
152 return ui::TEXT_INPUT_MODE_DEFAULT;
153 return it->second;
156 bool IsThreadedCompositingEnabled() {
157 content::RenderThreadImpl* impl = content::RenderThreadImpl::current();
158 return impl && !!impl->compositor_message_loop_proxy().get();
161 // TODO(brianderson): Replace the hard-coded threshold with a fraction of
162 // the BeginMainFrame interval.
163 // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to
164 // be spent in input hanlders before input starts getting throttled.
165 const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166;
167 int64 GetEventLatencyMicros(const WebInputEvent& event, base::TimeTicks now) {
168 return (now - base::TimeDelta::FromSecondsD(event.timeStampSeconds))
169 .ToInternalValue();
172 void LogInputEventLatencyUma(const WebInputEvent& event, base::TimeTicks now) {
173 UMA_HISTOGRAM_CUSTOM_COUNTS(
174 "Event.AggregatedLatency.Renderer2",
175 GetEventLatencyMicros(event, now),
177 10000000,
178 100);
180 #define CASE_TYPE(t) \
181 case WebInputEvent::t: \
182 UMA_HISTOGRAM_CUSTOM_COUNTS( \
183 "Event.Latency.Renderer2." #t, \
184 GetEventLatencyMicros(event, now), \
185 1, \
186 10000000, \
187 100); \
188 break;
190 switch(event.type) {
191 CASE_TYPE(Undefined);
192 CASE_TYPE(MouseDown);
193 CASE_TYPE(MouseUp);
194 CASE_TYPE(MouseMove);
195 CASE_TYPE(MouseEnter);
196 CASE_TYPE(MouseLeave);
197 CASE_TYPE(ContextMenu);
198 CASE_TYPE(MouseWheel);
199 CASE_TYPE(RawKeyDown);
200 CASE_TYPE(KeyDown);
201 CASE_TYPE(KeyUp);
202 CASE_TYPE(Char);
203 CASE_TYPE(GestureScrollBegin);
204 CASE_TYPE(GestureScrollEnd);
205 CASE_TYPE(GestureScrollUpdate);
206 CASE_TYPE(GestureFlingStart);
207 CASE_TYPE(GestureFlingCancel);
208 CASE_TYPE(GestureShowPress);
209 CASE_TYPE(GestureTap);
210 CASE_TYPE(GestureTapUnconfirmed);
211 CASE_TYPE(GestureTapDown);
212 CASE_TYPE(GestureTapCancel);
213 CASE_TYPE(GestureDoubleTap);
214 CASE_TYPE(GestureTwoFingerTap);
215 CASE_TYPE(GestureLongPress);
216 CASE_TYPE(GestureLongTap);
217 CASE_TYPE(GesturePinchBegin);
218 CASE_TYPE(GesturePinchEnd);
219 CASE_TYPE(GesturePinchUpdate);
220 CASE_TYPE(TouchStart);
221 CASE_TYPE(TouchMove);
222 CASE_TYPE(TouchEnd);
223 CASE_TYPE(TouchCancel);
224 default:
225 // Must include default to let blink::WebInputEvent add new event types
226 // before they're added here.
227 DLOG(WARNING) << "Unhandled WebInputEvent type: " << event.type;
228 break;
231 #undef CASE_TYPE
234 } // namespace
236 namespace content {
238 // RenderWidget::ScreenMetricsEmulator ----------------------------------------
240 class RenderWidget::ScreenMetricsEmulator {
241 public:
242 ScreenMetricsEmulator(
243 RenderWidget* widget,
244 const WebDeviceEmulationParams& params);
245 virtual ~ScreenMetricsEmulator();
247 // Scale and offset used to convert between host coordinates
248 // and webwidget coordinates.
249 float scale() { return scale_; }
250 gfx::Point offset() { return offset_; }
251 gfx::Rect applied_widget_rect() const { return applied_widget_rect_; }
252 gfx::Rect original_screen_rect() const { return original_view_screen_rect_; }
253 const WebScreenInfo& original_screen_info() { return original_screen_info_; }
255 void ChangeEmulationParams(
256 const WebDeviceEmulationParams& params);
258 // The following methods alter handlers' behavior for messages related to
259 // widget size and position.
260 void OnResizeMessage(const ViewMsg_Resize_Params& params);
261 void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect,
262 const gfx::Rect& window_screen_rect);
263 void OnShowContextMenu(ContextMenuParams* params);
264 gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor);
266 private:
267 void Reapply();
268 void Apply(bool top_controls_shrink_blink_size,
269 float top_controls_height,
270 gfx::Rect resizer_rect,
271 bool is_fullscreen);
273 RenderWidget* widget_;
275 // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
276 WebDeviceEmulationParams params_;
278 // The computed scale and offset used to fit widget into browser window.
279 float scale_;
280 gfx::Point offset_;
282 // Widget rect as passed to webwidget.
283 gfx::Rect applied_widget_rect_;
285 // Original values to restore back after emulation ends.
286 gfx::Size original_size_;
287 gfx::Size original_physical_backing_size_;
288 gfx::Size original_visible_viewport_size_;
289 blink::WebScreenInfo original_screen_info_;
290 gfx::Rect original_view_screen_rect_;
291 gfx::Rect original_window_screen_rect_;
294 RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator(
295 RenderWidget* widget,
296 const WebDeviceEmulationParams& params)
297 : widget_(widget),
298 params_(params),
299 scale_(1.f) {
300 original_size_ = widget_->size_;
301 original_physical_backing_size_ = widget_->physical_backing_size_;
302 original_visible_viewport_size_ = widget_->visible_viewport_size_;
303 original_screen_info_ = widget_->screen_info_;
304 original_view_screen_rect_ = widget_->view_screen_rect_;
305 original_window_screen_rect_ = widget_->window_screen_rect_;
306 Apply(widget_->top_controls_shrink_blink_size_,
307 widget_->top_controls_height_,
308 widget_->resizer_rect_,
309 widget_->is_fullscreen_);
312 RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() {
313 widget_->screen_info_ = original_screen_info_;
315 widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor);
316 widget_->SetScreenMetricsEmulationParameters(0.f, gfx::Point(), 1.f);
317 widget_->view_screen_rect_ = original_view_screen_rect_;
318 widget_->window_screen_rect_ = original_window_screen_rect_;
319 widget_->Resize(original_size_,
320 original_physical_backing_size_,
321 widget_->top_controls_shrink_blink_size_,
322 widget_->top_controls_height_,
323 original_visible_viewport_size_,
324 widget_->resizer_rect_,
325 widget_->is_fullscreen_,
326 NO_RESIZE_ACK);
329 void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams(
330 const WebDeviceEmulationParams& params) {
331 params_ = params;
332 Reapply();
335 void RenderWidget::ScreenMetricsEmulator::Reapply() {
336 Apply(widget_->top_controls_shrink_blink_size_,
337 widget_->top_controls_height_,
338 widget_->resizer_rect_,
339 widget_->is_fullscreen_);
342 void RenderWidget::ScreenMetricsEmulator::Apply(
343 bool top_controls_shrink_blink_size,
344 float top_controls_height,
345 gfx::Rect resizer_rect,
346 bool is_fullscreen) {
347 applied_widget_rect_.set_size(gfx::Size(params_.viewSize));
348 if (!applied_widget_rect_.width())
349 applied_widget_rect_.set_width(original_size_.width());
350 if (!applied_widget_rect_.height())
351 applied_widget_rect_.set_height(original_size_.height());
353 if (params_.fitToView && !original_size_.IsEmpty()) {
354 int original_width = std::max(original_size_.width(), 1);
355 int original_height = std::max(original_size_.height(), 1);
356 float width_ratio =
357 static_cast<float>(applied_widget_rect_.width()) / original_width;
358 float height_ratio =
359 static_cast<float>(applied_widget_rect_.height()) / original_height;
360 float ratio = std::max(1.0f, std::max(width_ratio, height_ratio));
361 scale_ = 1.f / ratio;
363 // Center emulated view inside available view space.
364 offset_.set_x(
365 (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2);
366 offset_.set_y(
367 (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2);
368 } else {
369 scale_ = params_.scale;
370 offset_.SetPoint(params_.offset.x, params_.offset.y);
373 if (params_.screenPosition == WebDeviceEmulationParams::Desktop) {
374 applied_widget_rect_.set_origin(original_view_screen_rect_.origin());
375 widget_->screen_info_.rect = original_screen_info_.rect;
376 widget_->screen_info_.availableRect = original_screen_info_.availableRect;
377 widget_->window_screen_rect_ = original_window_screen_rect_;
378 } else {
379 applied_widget_rect_.set_origin(gfx::Point(0, 0));
380 widget_->screen_info_.rect = applied_widget_rect_;
381 widget_->screen_info_.availableRect = applied_widget_rect_;
382 widget_->window_screen_rect_ = applied_widget_rect_;
385 float applied_device_scale_factor = params_.deviceScaleFactor ?
386 params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor;
387 widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor;
389 // Pass three emulation parameters to the blink side:
390 // - we keep the real device scale factor in compositor to produce sharp image
391 // even when emulating different scale factor;
392 // - in order to fit into view, WebView applies offset and scale to the
393 // root layer.
394 widget_->SetScreenMetricsEmulationParameters(
395 original_screen_info_.deviceScaleFactor, offset_, scale_);
397 widget_->SetDeviceScaleFactor(applied_device_scale_factor);
398 widget_->view_screen_rect_ = applied_widget_rect_;
400 gfx::Size physical_backing_size = gfx::ToCeiledSize(gfx::ScaleSize(
401 original_size_, original_screen_info_.deviceScaleFactor));
402 widget_->Resize(applied_widget_rect_.size(),
403 physical_backing_size,
404 top_controls_shrink_blink_size,
405 top_controls_height,
406 applied_widget_rect_.size(),
407 resizer_rect,
408 is_fullscreen,
409 NO_RESIZE_ACK);
412 void RenderWidget::ScreenMetricsEmulator::OnResizeMessage(
413 const ViewMsg_Resize_Params& params) {
414 bool need_ack = params.new_size != original_size_ &&
415 !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty();
416 original_size_ = params.new_size;
417 original_physical_backing_size_ = params.physical_backing_size;
418 original_screen_info_ = params.screen_info;
419 original_visible_viewport_size_ = params.visible_viewport_size;
420 Apply(params.top_controls_shrink_blink_size,
421 params.top_controls_height,
422 params.resizer_rect,
423 params.is_fullscreen);
425 if (need_ack) {
426 widget_->set_next_paint_is_resize_ack();
427 if (widget_->compositor_)
428 widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_));
432 void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage(
433 const gfx::Rect& view_screen_rect,
434 const gfx::Rect& window_screen_rect) {
435 original_view_screen_rect_ = view_screen_rect;
436 original_window_screen_rect_ = window_screen_rect;
437 if (params_.screenPosition == WebDeviceEmulationParams::Desktop)
438 Reapply();
441 void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu(
442 ContextMenuParams* params) {
443 params->x *= scale_;
444 params->x += offset_.x();
445 params->y *= scale_;
446 params->y += offset_.y();
449 gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor(
450 const gfx::Rect& anchor) {
451 gfx::Rect scaled = gfx::ToEnclosedRect(gfx::ScaleRect(anchor, scale_));
452 scaled.set_x(scaled.x() + offset_.x());
453 scaled.set_y(scaled.y() + offset_.y());
454 return scaled;
457 // RenderWidget ---------------------------------------------------------------
459 RenderWidget::RenderWidget(blink::WebPopupType popup_type,
460 const blink::WebScreenInfo& screen_info,
461 bool swapped_out,
462 bool hidden,
463 bool never_visible)
464 : routing_id_(MSG_ROUTING_NONE),
465 surface_id_(0),
466 webwidget_(NULL),
467 opener_id_(MSG_ROUTING_NONE),
468 init_complete_(false),
469 top_controls_shrink_blink_size_(false),
470 top_controls_height_(0.f),
471 next_paint_flags_(0),
472 auto_resize_mode_(false),
473 need_update_rect_for_auto_resize_(false),
474 did_show_(false),
475 is_hidden_(hidden),
476 never_visible_(never_visible),
477 is_fullscreen_(false),
478 has_focus_(false),
479 handling_input_event_(false),
480 handling_ime_event_(false),
481 handling_event_type_(WebInputEvent::Undefined),
482 ignore_ack_for_mouse_move_from_debugger_(false),
483 closing_(false),
484 host_closing_(false),
485 is_swapped_out_(swapped_out),
486 input_method_is_active_(false),
487 text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
488 text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT),
489 text_input_flags_(0),
490 can_compose_inline_(true),
491 popup_type_(popup_type),
492 pending_window_rect_count_(0),
493 suppress_next_char_events_(false),
494 screen_info_(screen_info),
495 device_scale_factor_(screen_info_.deviceScaleFactor),
496 current_event_latency_info_(NULL),
497 next_output_surface_id_(0),
498 #if defined(OS_ANDROID)
499 text_field_is_dirty_(false),
500 outstanding_ime_acks_(0),
501 body_background_color_(SK_ColorWHITE),
502 #endif
503 popup_origin_scale_for_emulation_(0.f),
504 frame_swap_message_queue_(new FrameSwapMessageQueue()),
505 resizing_mode_selector_(new ResizingModeSelector()),
506 context_menu_source_type_(ui::MENU_SOURCE_MOUSE),
507 has_host_context_menu_location_(false) {
508 if (!swapped_out)
509 RenderProcess::current()->AddRefProcess();
510 DCHECK(RenderThread::Get());
511 device_color_profile_.push_back('0');
514 RenderWidget::~RenderWidget() {
515 DCHECK(!webwidget_) << "Leaking our WebWidget!";
517 // If we are swapped out, we have released already.
518 if (!is_swapped_out_ && RenderProcess::current())
519 RenderProcess::current()->ReleaseProcess();
522 // static
523 RenderWidget* RenderWidget::Create(int32 opener_id,
524 blink::WebPopupType popup_type,
525 const blink::WebScreenInfo& screen_info) {
526 DCHECK(opener_id != MSG_ROUTING_NONE);
527 scoped_refptr<RenderWidget> widget(
528 new RenderWidget(popup_type, screen_info, false, false, false));
529 if (widget->Init(opener_id)) { // adds reference on success.
530 return widget.get();
532 return NULL;
535 // static
536 WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) {
537 switch (render_widget->popup_type_) {
538 case blink::WebPopupTypeNone: // Nothing to create.
539 break;
540 case blink::WebPopupTypeSelect:
541 case blink::WebPopupTypeSuggestion:
542 return WebPopupMenu::create(render_widget);
543 case blink::WebPopupTypePage:
544 return WebPagePopup::create(render_widget);
545 default:
546 NOTREACHED();
548 return NULL;
551 bool RenderWidget::Init(int32 opener_id) {
552 return DoInit(opener_id,
553 RenderWidget::CreateWebWidget(this),
554 new ViewHostMsg_CreateWidget(opener_id, popup_type_,
555 &routing_id_, &surface_id_));
558 bool RenderWidget::DoInit(int32 opener_id,
559 WebWidget* web_widget,
560 IPC::SyncMessage* create_widget_message) {
561 DCHECK(!webwidget_);
563 if (opener_id != MSG_ROUTING_NONE)
564 opener_id_ = opener_id;
566 webwidget_ = web_widget;
568 bool result = RenderThread::Get()->Send(create_widget_message);
569 if (result) {
570 RenderThread::Get()->AddRoute(routing_id_, this);
571 // Take a reference on behalf of the RenderThread. This will be balanced
572 // when we receive ViewMsg_Close.
573 AddRef();
574 if (RenderThreadImpl::current()) {
575 RenderThreadImpl::current()->WidgetCreated();
576 if (is_hidden_)
577 RenderThreadImpl::current()->WidgetHidden();
579 return true;
580 } else {
581 // The above Send can fail when the tab is closing.
582 return false;
586 // This is used to complete pending inits and non-pending inits.
587 void RenderWidget::CompleteInit() {
588 DCHECK(routing_id_ != MSG_ROUTING_NONE);
590 init_complete_ = true;
592 if (compositor_)
593 StartCompositor();
595 Send(new ViewHostMsg_RenderViewReady(routing_id_));
598 void RenderWidget::SetSwappedOut(bool is_swapped_out) {
599 // We should only toggle between states.
600 DCHECK(is_swapped_out_ != is_swapped_out);
601 is_swapped_out_ = is_swapped_out;
603 // If we are swapping out, we will call ReleaseProcess, allowing the process
604 // to exit if all of its RenderViews are swapped out. We wait until the
605 // WasSwappedOut call to do this, to allow the unload handler to finish.
606 // If we are swapping in, we call AddRefProcess to prevent the process from
607 // exiting.
608 if (!is_swapped_out_)
609 RenderProcess::current()->AddRefProcess();
612 void RenderWidget::WasSwappedOut() {
613 // If we have been swapped out and no one else is using this process,
614 // it's safe to exit now.
615 CHECK(is_swapped_out_);
616 RenderProcess::current()->ReleaseProcess();
619 void RenderWidget::EnableScreenMetricsEmulation(
620 const WebDeviceEmulationParams& params) {
621 if (!screen_metrics_emulator_)
622 screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params));
623 else
624 screen_metrics_emulator_->ChangeEmulationParams(params);
627 void RenderWidget::DisableScreenMetricsEmulation() {
628 screen_metrics_emulator_.reset();
631 void RenderWidget::SetPopupOriginAdjustmentsForEmulation(
632 ScreenMetricsEmulator* emulator) {
633 popup_origin_scale_for_emulation_ = emulator->scale();
634 popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin();
635 popup_screen_origin_for_emulation_ = gfx::Point(
636 emulator->original_screen_rect().origin().x() + emulator->offset().x(),
637 emulator->original_screen_rect().origin().y() + emulator->offset().y());
638 screen_info_ = emulator->original_screen_info();
639 device_scale_factor_ = screen_info_.deviceScaleFactor;
642 gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) {
643 if (screen_metrics_emulator_)
644 return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor);
645 return anchor;
648 void RenderWidget::SetScreenMetricsEmulationParameters(
649 float device_scale_factor,
650 const gfx::Point& root_layer_offset,
651 float root_layer_scale) {
652 // This is only supported in RenderView.
653 NOTREACHED();
656 #if defined(OS_MACOSX) || defined(OS_ANDROID)
657 void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation(
658 ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) {
659 popup->SetOriginScaleAndOffsetForEmulation(
660 emulator->scale(), emulator->offset());
662 #endif
664 void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) {
665 if (screen_metrics_emulator_)
666 screen_metrics_emulator_->OnShowContextMenu(params);
669 void RenderWidget::ScheduleCompositeWithForcedRedraw() {
670 if (compositor_) {
671 // Regardless of whether threaded compositing is enabled, always
672 // use this mechanism to force the compositor to redraw. However,
673 // the invalidation code path below is still needed for the
674 // non-threaded case.
675 compositor_->SetNeedsForcedRedraw();
677 scheduleComposite();
680 bool RenderWidget::OnMessageReceived(const IPC::Message& message) {
681 bool handled = true;
682 IPC_BEGIN_MESSAGE_MAP(RenderWidget, message)
683 IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
684 IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange,
685 OnCursorVisibilityChange)
686 IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition)
687 IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition)
688 IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost)
689 IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus)
690 IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted,
691 OnSyntheticGestureCompleted)
692 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
693 IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck)
694 IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize)
695 IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile)
696 IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect)
697 IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden)
698 IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown)
699 IPC_MESSAGE_HANDLER(ViewMsg_SetInputMethodActive, OnSetInputMethodActive)
700 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowShown, OnCandidateWindowShown)
701 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowUpdated,
702 OnCandidateWindowUpdated)
703 IPC_MESSAGE_HANDLER(ViewMsg_CandidateWindowHidden, OnCandidateWindowHidden)
704 IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint)
705 IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection)
706 IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck)
707 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects)
708 #if defined(OS_ANDROID)
709 IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded)
710 IPC_MESSAGE_HANDLER(ViewMsg_ImeEventAck, OnImeEventAck)
711 #endif
712 IPC_MESSAGE_UNHANDLED(handled = false)
713 IPC_END_MESSAGE_MAP()
714 return handled;
717 bool RenderWidget::Send(IPC::Message* message) {
718 // Don't send any messages after the browser has told us to close, and filter
719 // most outgoing messages while swapped out.
720 if ((is_swapped_out_ &&
721 !SwappedOutMessages::CanSendWhileSwappedOut(message)) ||
722 closing_) {
723 delete message;
724 return false;
727 // If given a messsage without a routing ID, then assign our routing ID.
728 if (message->routing_id() == MSG_ROUTING_NONE)
729 message->set_routing_id(routing_id_);
731 return RenderThread::Get()->Send(message);
734 void RenderWidget::Resize(const gfx::Size& new_size,
735 const gfx::Size& physical_backing_size,
736 bool top_controls_shrink_blink_size,
737 float top_controls_height,
738 const gfx::Size& visible_viewport_size,
739 const gfx::Rect& resizer_rect,
740 bool is_fullscreen,
741 ResizeAck resize_ack) {
742 if (resizing_mode_selector_->NeverUsesSynchronousResize()) {
743 // A resize ack shouldn't be requested if we have not ACK'd the previous
744 // one.
745 DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack());
746 DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK);
749 // Ignore this during shutdown.
750 if (!webwidget_)
751 return;
753 if (compositor_) {
754 compositor_->setViewportSize(new_size, physical_backing_size);
755 compositor_->SetTopControlsShrinkBlinkSize(top_controls_shrink_blink_size);
756 compositor_->SetTopControlsHeight(top_controls_height);
759 physical_backing_size_ = physical_backing_size;
760 top_controls_shrink_blink_size_ = top_controls_shrink_blink_size;
761 top_controls_height_ = top_controls_height;
762 visible_viewport_size_ = visible_viewport_size;
763 resizer_rect_ = resizer_rect;
765 // NOTE: We may have entered fullscreen mode without changing our size.
766 bool fullscreen_change = is_fullscreen_ != is_fullscreen;
767 if (fullscreen_change)
768 WillToggleFullscreen();
769 is_fullscreen_ = is_fullscreen;
771 webwidget_->setTopControlsLayoutHeight(top_controls_shrink_blink_size_
772 ? top_controls_height : 0.f);
774 if (size_ != new_size) {
775 size_ = new_size;
777 // When resizing, we want to wait to paint before ACK'ing the resize. This
778 // ensures that we only resize as fast as we can paint. We only need to
779 // send an ACK if we are resized to a non-empty rect.
780 webwidget_->resize(new_size);
781 } else if (!resizing_mode_selector_->is_synchronous_mode()) {
782 resize_ack = NO_RESIZE_ACK;
785 webwidget()->resizePinchViewport(gfx::Size(
786 visible_viewport_size.width(),
787 visible_viewport_size.height()));
789 if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) {
790 // For empty size or empty physical_backing_size, there is no next paint
791 // (along with which to send the ack) until they are set to non-empty.
792 resize_ack = NO_RESIZE_ACK;
795 // Send the Resize_ACK flag once we paint again if requested.
796 if (resize_ack == SEND_RESIZE_ACK)
797 set_next_paint_is_resize_ack();
799 if (fullscreen_change)
800 DidToggleFullscreen();
802 // If a resize ack is requested and it isn't set-up, then no more resizes will
803 // come in and in general things will go wrong.
804 DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack());
807 void RenderWidget::ResizeSynchronously(
808 const gfx::Rect& new_position,
809 const gfx::Size& visible_viewport_size) {
810 Resize(new_position.size(),
811 new_position.size(),
812 top_controls_shrink_blink_size_,
813 top_controls_height_,
814 visible_viewport_size,
815 gfx::Rect(),
816 is_fullscreen_,
817 NO_RESIZE_ACK);
818 view_screen_rect_ = new_position;
819 window_screen_rect_ = new_position;
820 if (!did_show_)
821 initial_pos_ = new_position;
824 void RenderWidget::OnClose() {
825 if (closing_)
826 return;
827 closing_ = true;
829 // Browser correspondence is no longer needed at this point.
830 if (routing_id_ != MSG_ROUTING_NONE) {
831 if (RenderThreadImpl::current())
832 RenderThreadImpl::current()->WidgetDestroyed();
833 RenderThread::Get()->RemoveRoute(routing_id_);
834 SetHidden(false);
837 // If there is a Send call on the stack, then it could be dangerous to close
838 // now. Post a task that only gets invoked when there are no nested message
839 // loops.
840 base::MessageLoop::current()->PostNonNestableTask(
841 FROM_HERE, base::Bind(&RenderWidget::Close, this));
843 // Balances the AddRef taken when we called AddRoute.
844 Release();
847 // Got a response from the browser after the renderer decided to create a new
848 // view.
849 void RenderWidget::OnCreatingNewAck() {
850 DCHECK(routing_id_ != MSG_ROUTING_NONE);
852 CompleteInit();
855 void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) {
856 if (resizing_mode_selector_->ShouldAbortOnResize(this, params))
857 return;
859 if (screen_metrics_emulator_) {
860 screen_metrics_emulator_->OnResizeMessage(params);
861 return;
864 bool orientation_changed =
865 screen_info_.orientationAngle != params.screen_info.orientationAngle;
867 screen_info_ = params.screen_info;
868 SetDeviceScaleFactor(screen_info_.deviceScaleFactor);
869 Resize(params.new_size,
870 params.physical_backing_size,
871 params.top_controls_shrink_blink_size,
872 params.top_controls_height,
873 params.visible_viewport_size,
874 params.resizer_rect,
875 params.is_fullscreen,
876 SEND_RESIZE_ACK);
878 if (orientation_changed)
879 OnOrientationChange();
882 void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) {
883 SetDeviceColorProfile(color_profile);
886 void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) {
887 if (resizer_rect_ == resizer_rect)
888 return;
889 resizer_rect_ = resizer_rect;
890 if (webwidget_)
891 webwidget_->didChangeWindowResizerRect();
894 void RenderWidget::OnWasHidden() {
895 TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden");
896 // Go into a mode where we stop generating paint and scrolling events.
897 SetHidden(true);
898 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
899 WasHidden());
902 void RenderWidget::OnWasShown(bool needs_repainting,
903 const ui::LatencyInfo& latency_info) {
904 TRACE_EVENT0("renderer", "RenderWidget::OnWasShown");
905 // During shutdown we can just ignore this message.
906 if (!webwidget_)
907 return;
909 // See OnWasHidden
910 SetHidden(false);
911 FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_,
912 WasShown());
914 if (!needs_repainting)
915 return;
917 // Generate a full repaint.
918 if (compositor_) {
919 ui::LatencyInfo swap_latency_info(latency_info);
920 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor(
921 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info));
922 compositor_->SetNeedsForcedRedraw();
924 scheduleComposite();
927 void RenderWidget::OnRequestMoveAck() {
928 DCHECK(pending_window_rect_count_);
929 pending_window_rect_count_--;
932 GURL RenderWidget::GetURLForGraphicsContext3D() {
933 return GURL();
936 scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) {
937 // For widgets that are never visible, we don't start the compositor, so we
938 // never get a request for a cc::OutputSurface.
939 DCHECK(!never_visible_);
941 #if defined(OS_ANDROID)
942 if (SynchronousCompositorFactory* factory =
943 SynchronousCompositorFactory::GetInstance()) {
944 return factory->CreateOutputSurface(routing_id(),
945 frame_swap_message_queue_);
947 #endif
949 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
950 bool use_software = fallback;
951 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
952 use_software = true;
954 scoped_refptr<ContextProviderCommandBuffer> context_provider;
955 if (!use_software) {
956 context_provider = ContextProviderCommandBuffer::Create(
957 CreateGraphicsContext3D(), "RenderCompositor");
958 if (!context_provider.get()) {
959 // Cause the compositor to wait and try again.
960 return scoped_ptr<cc::OutputSurface>();
964 uint32 output_surface_id = next_output_surface_id_++;
965 if (command_line.HasSwitch(switches::kEnableDelegatedRenderer)) {
966 DCHECK(IsThreadedCompositingEnabled());
967 return scoped_ptr<cc::OutputSurface>(
968 new DelegatedCompositorOutputSurface(routing_id(),
969 output_surface_id,
970 context_provider,
971 frame_swap_message_queue_));
973 if (!context_provider.get()) {
974 scoped_ptr<cc::SoftwareOutputDevice> software_device(
975 new CompositorSoftwareOutputDevice());
977 return scoped_ptr<cc::OutputSurface>(
978 new CompositorOutputSurface(routing_id(),
979 output_surface_id,
980 NULL,
981 software_device.Pass(),
982 frame_swap_message_queue_,
983 true));
986 if (command_line.HasSwitch(cc::switches::kCompositeToMailbox)) {
987 // Composite-to-mailbox is currently used for layout tests in order to cause
988 // them to draw inside in the renderer to do the readback there. This should
989 // no longer be the case when crbug.com/311404 is fixed.
990 DCHECK(IsThreadedCompositingEnabled() ||
991 RenderThreadImpl::current()->layout_test_mode());
992 cc::ResourceFormat format = cc::RGBA_8888;
993 if (base::SysInfo::IsLowEndDevice())
994 format = cc::RGB_565;
995 return scoped_ptr<cc::OutputSurface>(
996 new MailboxOutputSurface(routing_id(),
997 output_surface_id,
998 context_provider,
999 scoped_ptr<cc::SoftwareOutputDevice>(),
1000 frame_swap_message_queue_,
1001 format));
1003 bool use_swap_compositor_frame_message = false;
1004 return scoped_ptr<cc::OutputSurface>(
1005 new CompositorOutputSurface(routing_id(),
1006 output_surface_id,
1007 context_provider,
1008 scoped_ptr<cc::SoftwareOutputDevice>(),
1009 frame_swap_message_queue_,
1010 use_swap_compositor_frame_message));
1013 void RenderWidget::OnSwapBuffersAborted() {
1014 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted");
1015 // Schedule another frame so the compositor learns about it.
1016 scheduleComposite();
1019 void RenderWidget::OnSwapBuffersPosted() {
1020 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted");
1023 void RenderWidget::OnSwapBuffersComplete() {
1024 TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete");
1026 // Notify subclasses that composited rendering was flushed to the screen.
1027 DidFlushPaint();
1030 void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event,
1031 const ui::LatencyInfo& latency_info,
1032 bool is_keyboard_shortcut) {
1033 base::AutoReset<bool> handling_input_event_resetter(
1034 &handling_input_event_, true);
1035 if (!input_event)
1036 return;
1037 base::AutoReset<WebInputEvent::Type> handling_event_type_resetter(
1038 &handling_event_type_, input_event->type);
1039 #if defined(OS_ANDROID)
1040 // On Android, when a key is pressed or sent from the Keyboard using IME,
1041 // |AdapterInputConnection| generates input key events to make sure all JS
1042 // listeners that monitor KeyUp and KeyDown events receive the proper key
1043 // code. Since this input key event comes from IME, we need to set the
1044 // IME event guard here to make sure it does not interfere with other IME
1045 // events.
1046 scoped_ptr<ImeEventGuard> ime_event_guard_maybe;
1047 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1048 const WebKeyboardEvent& key_event =
1049 *static_cast<const WebKeyboardEvent*>(input_event);
1050 // Some keys are special and it's essential that no events get blocked.
1051 if (key_event.nativeKeyCode != AKEYCODE_TAB &&
1052 key_event.nativeKeyCode != AKEYCODE_DPAD_CENTER &&
1053 key_event.nativeKeyCode != AKEYCODE_DPAD_LEFT &&
1054 key_event.nativeKeyCode != AKEYCODE_DPAD_RIGHT &&
1055 key_event.nativeKeyCode != AKEYCODE_DPAD_UP &&
1056 key_event.nativeKeyCode != AKEYCODE_DPAD_DOWN)
1057 ime_event_guard_maybe.reset(new ImeEventGuard(this));
1059 #endif
1061 base::AutoReset<const ui::LatencyInfo*> resetter(&current_event_latency_info_,
1062 &latency_info);
1064 base::TimeTicks start_time;
1065 if (base::TimeTicks::IsHighResNowFastAndReliable())
1066 start_time = base::TimeTicks::HighResNow();
1068 TRACE_EVENT1("renderer", "RenderWidget::OnHandleInputEvent",
1069 "event", WebInputEventTraits::GetName(input_event->type));
1070 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent");
1071 TRACE_EVENT_FLOW_STEP0(
1072 "input",
1073 "LatencyInfo.Flow",
1074 TRACE_ID_DONT_MANGLE(latency_info.trace_id),
1075 "HanldeInputEventMain");
1077 // If we don't have a high res timer, these metrics won't be accurate enough
1078 // to be worth collecting. Note that this does introduce some sampling bias.
1079 if (!start_time.is_null())
1080 LogInputEventLatencyUma(*input_event, start_time);
1082 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1083 ui::LatencyInfo swap_latency_info(latency_info);
1084 if (compositor_) {
1085 latency_info_swap_promise_monitor =
1086 compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)
1087 .Pass();
1090 bool prevent_default = false;
1091 if (WebInputEvent::isMouseEventType(input_event->type)) {
1092 const WebMouseEvent& mouse_event =
1093 *static_cast<const WebMouseEvent*>(input_event);
1094 TRACE_EVENT2("renderer", "HandleMouseMove",
1095 "x", mouse_event.x, "y", mouse_event.y);
1096 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
1097 prevent_default = WillHandleMouseEvent(mouse_event);
1100 if (WebInputEvent::isKeyboardEventType(input_event->type)) {
1101 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
1102 #if defined(OS_ANDROID)
1103 // The DPAD_CENTER key on Android has a dual semantic: (1) in the general
1104 // case it should behave like a select key (i.e. causing a click if a button
1105 // is focused). However, if a text field is focused (2), its intended
1106 // behavior is to just show the IME and don't propagate the key.
1107 // A typical use case is a web form: the DPAD_CENTER should bring up the IME
1108 // when clicked on an input text field and cause the form submit if clicked
1109 // when the submit button is focused, but not vice-versa.
1110 // The UI layer takes care of translating DPAD_CENTER into a RETURN key,
1111 // but at this point we have to swallow the event for the scenario (2).
1112 const WebKeyboardEvent& key_event =
1113 *static_cast<const WebKeyboardEvent*>(input_event);
1114 if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER &&
1115 GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
1116 OnShowImeIfNeeded();
1117 prevent_default = true;
1119 #endif
1122 if (WebInputEvent::isGestureEventType(input_event->type)) {
1123 const WebGestureEvent& gesture_event =
1124 *static_cast<const WebGestureEvent*>(input_event);
1125 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
1126 prevent_default = prevent_default || WillHandleGestureEvent(gesture_event);
1129 bool processed = prevent_default;
1130 if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) {
1131 suppress_next_char_events_ = false;
1132 if (!processed && webwidget_)
1133 processed = webwidget_->handleInputEvent(*input_event);
1136 // If this RawKeyDown event corresponds to a browser keyboard shortcut and
1137 // it's not processed by webkit, then we need to suppress the upcoming Char
1138 // events.
1139 if (!processed && is_keyboard_shortcut)
1140 suppress_next_char_events_ = true;
1142 InputEventAckState ack_result = processed ?
1143 INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1144 if (!processed && input_event->type == WebInputEvent::TouchStart) {
1145 const WebTouchEvent& touch_event =
1146 *static_cast<const WebTouchEvent*>(input_event);
1147 // Hit-test for all the pressed touch points. If there is a touch-handler
1148 // for any of the touch points, then the renderer should continue to receive
1149 // touch events.
1150 ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS;
1151 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
1152 if (touch_event.touches[i].state == WebTouchPoint::StatePressed &&
1153 HasTouchEventHandlersAt(
1154 gfx::ToFlooredPoint(touch_event.touches[i].position))) {
1155 ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED;
1156 break;
1161 bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested();
1163 // If we don't have a fast and accurate HighResNow, we assume the input
1164 // handlers are heavy and rate limit them.
1165 bool rate_limiting_wanted =
1166 input_event->type == WebInputEvent::MouseMove ||
1167 input_event->type == WebInputEvent::MouseWheel;
1168 if (rate_limiting_wanted && !start_time.is_null()) {
1169 base::TimeTicks end_time = base::TimeTicks::HighResNow();
1170 total_input_handling_time_this_frame_ += (end_time - start_time);
1171 rate_limiting_wanted =
1172 total_input_handling_time_this_frame_.InMicroseconds() >
1173 kInputHandlingTimeThrottlingThresholdMicroseconds;
1176 TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent");
1178 // Note that we can't use handling_event_type_ here since it will be overriden
1179 // by reentrant calls for events after the paused one.
1180 bool no_ack = ignore_ack_for_mouse_move_from_debugger_ &&
1181 input_event->type == WebInputEvent::MouseMove;
1182 if (!WebInputEventTraits::IgnoresAckDisposition(*input_event) && !no_ack) {
1183 InputHostMsg_HandleInputEvent_ACK_Params ack;
1184 ack.type = input_event->type;
1185 ack.state = ack_result;
1186 ack.latency = swap_latency_info;
1187 scoped_ptr<IPC::Message> response(
1188 new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1189 if (rate_limiting_wanted && frame_pending && !is_hidden_) {
1190 // We want to rate limit the input events in this case, so we'll wait for
1191 // painting to finish before ACKing this message.
1192 TRACE_EVENT_INSTANT0("renderer",
1193 "RenderWidget::OnHandleInputEvent ack throttled",
1194 TRACE_EVENT_SCOPE_THREAD);
1195 if (pending_input_event_ack_) {
1196 // As two different kinds of events could cause us to postpone an ack
1197 // we send it now, if we have one pending. The Browser should never
1198 // send us the same kind of event we are delaying the ack for.
1199 Send(pending_input_event_ack_.release());
1201 pending_input_event_ack_ = response.Pass();
1202 if (compositor_)
1203 compositor_->NotifyInputThrottledUntilCommit();
1204 } else {
1205 Send(response.release());
1208 if (input_event->type == WebInputEvent::MouseMove)
1209 ignore_ack_for_mouse_move_from_debugger_ = false;
1211 #if defined(OS_ANDROID)
1212 // Allow the IME to be shown when the focus changes as a consequence
1213 // of a processed touch end event.
1214 if (input_event->type == WebInputEvent::TouchEnd && processed)
1215 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1216 #elif defined(USE_AURA)
1217 // Show the virtual keyboard if enabled and a user gesture triggers a focus
1218 // change.
1219 if (processed && (input_event->type == WebInputEvent::TouchEnd ||
1220 input_event->type == WebInputEvent::MouseUp))
1221 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME);
1222 #endif
1224 if (!prevent_default) {
1225 if (WebInputEvent::isKeyboardEventType(input_event->type))
1226 DidHandleKeyEvent();
1227 if (WebInputEvent::isMouseEventType(input_event->type))
1228 DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
1229 if (WebInputEvent::isTouchEventType(input_event->type))
1230 DidHandleTouchEvent(*(static_cast<const WebTouchEvent*>(input_event)));
1234 void RenderWidget::OnCursorVisibilityChange(bool is_visible) {
1235 if (webwidget_)
1236 webwidget_->setCursorVisibilityState(is_visible);
1239 void RenderWidget::OnMouseCaptureLost() {
1240 if (webwidget_)
1241 webwidget_->mouseCaptureLost();
1244 void RenderWidget::OnSetFocus(bool enable) {
1245 has_focus_ = enable;
1246 if (webwidget_)
1247 webwidget_->setFocus(enable);
1250 void RenderWidget::ClearFocus() {
1251 // We may have got the focus from the browser before this gets processed, in
1252 // which case we do not want to unfocus ourself.
1253 if (!has_focus_ && webwidget_)
1254 webwidget_->setFocus(false);
1257 void RenderWidget::FlushPendingInputEventAck() {
1258 if (pending_input_event_ack_)
1259 Send(pending_input_event_ack_.release());
1260 total_input_handling_time_this_frame_ = base::TimeDelta();
1263 ///////////////////////////////////////////////////////////////////////////////
1264 // WebWidgetClient
1266 void RenderWidget::didAutoResize(const WebSize& new_size) {
1267 if (size_.width() != new_size.width || size_.height() != new_size.height) {
1268 size_ = new_size;
1270 if (resizing_mode_selector_->is_synchronous_mode()) {
1271 WebRect new_pos(rootWindowRect().x,
1272 rootWindowRect().y,
1273 new_size.width,
1274 new_size.height);
1275 view_screen_rect_ = new_pos;
1276 window_screen_rect_ = new_pos;
1279 AutoResizeCompositor();
1281 if (!resizing_mode_selector_->is_synchronous_mode())
1282 need_update_rect_for_auto_resize_ = true;
1286 void RenderWidget::AutoResizeCompositor() {
1287 physical_backing_size_ = gfx::ToCeiledSize(gfx::ScaleSize(size_,
1288 device_scale_factor_));
1289 if (compositor_)
1290 compositor_->setViewportSize(size_, physical_backing_size_);
1293 void RenderWidget::initializeLayerTreeView() {
1294 DCHECK(!host_closing_);
1296 compositor_ =
1297 RenderWidgetCompositor::Create(this, IsThreadedCompositingEnabled());
1298 compositor_->setViewportSize(size_, physical_backing_size_);
1299 if (init_complete_)
1300 StartCompositor();
1303 void RenderWidget::WillCloseLayerTreeView() {
1304 if (host_closing_)
1305 return;
1307 // Prevent new compositors or output surfaces from being created.
1308 host_closing_ = true;
1310 // Always send this notification to prevent new layer tree views from
1311 // being created, even if one hasn't been created yet.
1312 if (webwidget_)
1313 webwidget_->willCloseLayerTreeView();
1316 blink::WebLayerTreeView* RenderWidget::layerTreeView() {
1317 return compositor_.get();
1320 void RenderWidget::willBeginCompositorFrame() {
1321 TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame");
1323 // The following two can result in further layout and possibly
1324 // enable GPU acceleration so they need to be called before any painting
1325 // is done.
1326 UpdateTextInputType();
1327 #if defined(OS_ANDROID)
1328 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1329 #endif
1330 UpdateSelectionBounds();
1333 void RenderWidget::didBecomeReadyForAdditionalInput() {
1334 TRACE_EVENT0("renderer", "RenderWidget::didBecomeReadyForAdditionalInput");
1335 FlushPendingInputEventAck();
1338 void RenderWidget::DidCommitCompositorFrame() {
1339 FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_,
1340 DidCommitCompositorFrame());
1341 #if defined(VIDEO_HOLE)
1342 FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_,
1343 DidCommitCompositorFrame());
1344 #endif // defined(VIDEO_HOLE)
1347 // static
1348 scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl(
1349 IPC::Message* msg,
1350 MessageDeliveryPolicy policy,
1351 FrameSwapMessageQueue* frame_swap_message_queue,
1352 scoped_refptr<IPC::SyncMessageFilter> sync_message_filter,
1353 bool commit_requested,
1354 int source_frame_number) {
1355 if (policy == MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE &&
1356 // No need for lock: this gets changed only on this thread.
1357 !commit_requested &&
1358 // No need for lock: Messages are only enqueued from this thread, if we
1359 // don't have any now, no other thread will add any.
1360 frame_swap_message_queue->Empty()) {
1361 sync_message_filter->Send(msg);
1362 return nullptr;
1365 bool first_message_for_frame = false;
1366 frame_swap_message_queue->QueueMessageForFrame(policy,
1367 source_frame_number,
1368 make_scoped_ptr(msg),
1369 &first_message_for_frame);
1370 if (first_message_for_frame) {
1371 scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise(
1372 sync_message_filter, frame_swap_message_queue, source_frame_number));
1373 return promise;
1375 return nullptr;
1378 void RenderWidget::QueueMessage(IPC::Message* msg,
1379 MessageDeliveryPolicy policy) {
1380 // RenderThreadImpl::current() is NULL in some tests.
1381 if (!compositor_ || !RenderThreadImpl::current()) {
1382 Send(msg);
1383 return;
1386 scoped_ptr<cc::SwapPromise> swap_promise =
1387 QueueMessageImpl(msg,
1388 policy,
1389 frame_swap_message_queue_.get(),
1390 RenderThreadImpl::current()->sync_message_filter(),
1391 compositor_->commitRequested(),
1392 compositor_->GetSourceFrameNumber());
1394 if (swap_promise) {
1395 compositor_->QueueSwapPromise(swap_promise.Pass());
1396 compositor_->SetNeedsCommit();
1400 void RenderWidget::didCommitAndDrawCompositorFrame() {
1401 // NOTE: Tests may break if this event is renamed or moved. See
1402 // tab_capture_performancetest.cc.
1403 TRACE_EVENT0("gpu", "RenderWidget::didCommitAndDrawCompositorFrame");
1404 // Notify subclasses that we initiated the paint operation.
1405 DidInitiatePaint();
1408 void RenderWidget::didCompleteSwapBuffers() {
1409 TRACE_EVENT0("renderer", "RenderWidget::didCompleteSwapBuffers");
1411 // Notify subclasses threaded composited rendering was flushed to the screen.
1412 DidFlushPaint();
1414 if (!next_paint_flags_ &&
1415 !need_update_rect_for_auto_resize_ &&
1416 !plugin_window_moves_.size()) {
1417 return;
1420 ViewHostMsg_UpdateRect_Params params;
1421 params.view_size = size_;
1422 params.plugin_window_moves.swap(plugin_window_moves_);
1423 params.flags = next_paint_flags_;
1425 Send(new ViewHostMsg_UpdateRect(routing_id_, params));
1426 next_paint_flags_ = 0;
1427 need_update_rect_for_auto_resize_ = false;
1430 void RenderWidget::scheduleComposite() {
1431 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1432 // render_thread may be NULL in tests.
1433 if (render_thread && render_thread->compositor_message_loop_proxy().get() &&
1434 compositor_) {
1435 compositor_->setNeedsAnimate();
1439 void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) {
1440 // TODO(darin): Eliminate this temporary.
1441 WebCursor cursor;
1442 InitializeCursorFromWebKitCursorInfo(&cursor, cursor_info);
1443 // Only send a SetCursor message if we need to make a change.
1444 if (!current_cursor_.IsEqual(cursor)) {
1445 current_cursor_ = cursor;
1446 Send(new ViewHostMsg_SetCursor(routing_id_, cursor));
1450 // We are supposed to get a single call to Show for a newly created RenderWidget
1451 // that was created via RenderWidget::CreateWebView. So, we wait until this
1452 // point to dispatch the ShowWidget message.
1454 // This method provides us with the information about how to display the newly
1455 // created RenderWidget (i.e., as a blocked popup or as a new tab).
1457 void RenderWidget::show(WebNavigationPolicy) {
1458 DCHECK(!did_show_) << "received extraneous Show call";
1459 DCHECK(routing_id_ != MSG_ROUTING_NONE);
1460 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1462 if (did_show_)
1463 return;
1465 did_show_ = true;
1466 // NOTE: initial_pos_ may still have its default values at this point, but
1467 // that's okay. It'll be ignored if as_popup is false, or the browser
1468 // process will impose a default position otherwise.
1469 Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_pos_));
1470 SetPendingWindowRect(initial_pos_);
1473 void RenderWidget::didFocus() {
1476 void RenderWidget::didBlur() {
1479 void RenderWidget::DoDeferredClose() {
1480 WillCloseLayerTreeView();
1481 Send(new ViewHostMsg_Close(routing_id_));
1484 void RenderWidget::closeWidgetSoon() {
1485 if (is_swapped_out_) {
1486 // This widget is currently swapped out, and the active widget is in a
1487 // different process. Have the browser route the close request to the
1488 // active widget instead, so that the correct unload handlers are run.
1489 Send(new ViewHostMsg_RouteCloseEvent(routing_id_));
1490 return;
1493 // If a page calls window.close() twice, we'll end up here twice, but that's
1494 // OK. It is safe to send multiple Close messages.
1496 // Ask the RenderWidgetHost to initiate close. We could be called from deep
1497 // in Javascript. If we ask the RendwerWidgetHost to close now, the window
1498 // could be closed before the JS finishes executing. So instead, post a
1499 // message back to the message loop, which won't run until the JS is
1500 // complete, and then the Close message can be sent.
1501 base::MessageLoop::current()->PostTask(
1502 FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this));
1505 void RenderWidget::QueueSyntheticGesture(
1506 scoped_ptr<SyntheticGestureParams> gesture_params,
1507 const SyntheticGestureCompletionCallback& callback) {
1508 DCHECK(!callback.is_null());
1510 pending_synthetic_gesture_callbacks_.push(callback);
1512 SyntheticGesturePacket gesture_packet;
1513 gesture_packet.set_gesture_params(gesture_params.Pass());
1515 Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet));
1518 void RenderWidget::Close() {
1519 screen_metrics_emulator_.reset();
1520 WillCloseLayerTreeView();
1521 compositor_.reset();
1522 if (webwidget_) {
1523 webwidget_->close();
1524 webwidget_ = NULL;
1528 WebRect RenderWidget::windowRect() {
1529 if (pending_window_rect_count_)
1530 return pending_window_rect_;
1532 return view_screen_rect_;
1535 void RenderWidget::setToolTipText(const blink::WebString& text,
1536 WebTextDirection hint) {
1537 Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint));
1540 void RenderWidget::setWindowRect(const WebRect& rect) {
1541 WebRect pos = rect;
1542 if (popup_origin_scale_for_emulation_) {
1543 float scale = popup_origin_scale_for_emulation_;
1544 pos.x = popup_screen_origin_for_emulation_.x() +
1545 (pos.x - popup_view_origin_for_emulation_.x()) * scale;
1546 pos.y = popup_screen_origin_for_emulation_.y() +
1547 (pos.y - popup_view_origin_for_emulation_.y()) * scale;
1550 if (!resizing_mode_selector_->is_synchronous_mode()) {
1551 if (did_show_) {
1552 Send(new ViewHostMsg_RequestMove(routing_id_, pos));
1553 SetPendingWindowRect(pos);
1554 } else {
1555 initial_pos_ = pos;
1557 } else {
1558 ResizeSynchronously(pos, visible_viewport_size_);
1562 void RenderWidget::SetPendingWindowRect(const WebRect& rect) {
1563 pending_window_rect_ = rect;
1564 pending_window_rect_count_++;
1567 WebRect RenderWidget::rootWindowRect() {
1568 if (pending_window_rect_count_) {
1569 // NOTE(mbelshe): If there is a pending_window_rect_, then getting
1570 // the RootWindowRect is probably going to return wrong results since the
1571 // browser may not have processed the Move yet. There isn't really anything
1572 // good to do in this case, and it shouldn't happen - since this size is
1573 // only really needed for windowToScreen, which is only used for Popups.
1574 return pending_window_rect_;
1577 return window_screen_rect_;
1580 WebRect RenderWidget::windowResizerRect() {
1581 return resizer_rect_;
1584 void RenderWidget::OnSetInputMethodActive(bool is_active) {
1585 // To prevent this renderer process from sending unnecessary IPC messages to
1586 // a browser process, we permit the renderer process to send IPC messages
1587 // only during the input method attached to the browser process is active.
1588 input_method_is_active_ = is_active;
1591 void RenderWidget::OnCandidateWindowShown() {
1592 webwidget_->didShowCandidateWindow();
1595 void RenderWidget::OnCandidateWindowUpdated() {
1596 webwidget_->didUpdateCandidateWindow();
1599 void RenderWidget::OnCandidateWindowHidden() {
1600 webwidget_->didHideCandidateWindow();
1603 void RenderWidget::OnImeSetComposition(
1604 const base::string16& text,
1605 const std::vector<WebCompositionUnderline>& underlines,
1606 int selection_start, int selection_end) {
1607 if (!ShouldHandleImeEvent())
1608 return;
1609 ImeEventGuard guard(this);
1610 if (!webwidget_->setComposition(
1611 text, WebVector<WebCompositionUnderline>(underlines),
1612 selection_start, selection_end)) {
1613 // If we failed to set the composition text, then we need to let the browser
1614 // process to cancel the input method's ongoing composition session, to make
1615 // sure we are in a consistent state.
1616 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1618 UpdateCompositionInfo(true);
1621 void RenderWidget::OnImeConfirmComposition(const base::string16& text,
1622 const gfx::Range& replacement_range,
1623 bool keep_selection) {
1624 if (!ShouldHandleImeEvent())
1625 return;
1626 ImeEventGuard guard(this);
1627 handling_input_event_ = true;
1628 if (text.length())
1629 webwidget_->confirmComposition(text);
1630 else if (keep_selection)
1631 webwidget_->confirmComposition(WebWidget::KeepSelection);
1632 else
1633 webwidget_->confirmComposition(WebWidget::DoNotKeepSelection);
1634 handling_input_event_ = false;
1635 UpdateCompositionInfo(true);
1638 void RenderWidget::OnRepaint(gfx::Size size_to_paint) {
1639 // During shutdown we can just ignore this message.
1640 if (!webwidget_)
1641 return;
1643 // Even if the browser provides an empty damage rect, it's still expecting to
1644 // receive a repaint ack so just damage the entire widget bounds.
1645 if (size_to_paint.IsEmpty()) {
1646 size_to_paint = size_;
1649 set_next_paint_is_repaint_ack();
1650 if (compositor_)
1651 compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint));
1654 void RenderWidget::OnSyntheticGestureCompleted() {
1655 DCHECK(!pending_synthetic_gesture_callbacks_.empty());
1657 pending_synthetic_gesture_callbacks_.front().Run();
1658 pending_synthetic_gesture_callbacks_.pop();
1661 void RenderWidget::OnSetTextDirection(WebTextDirection direction) {
1662 if (!webwidget_)
1663 return;
1664 webwidget_->setTextDirection(direction);
1667 void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect,
1668 const gfx::Rect& window_screen_rect) {
1669 if (screen_metrics_emulator_) {
1670 screen_metrics_emulator_->OnUpdateScreenRectsMessage(
1671 view_screen_rect, window_screen_rect);
1672 } else {
1673 view_screen_rect_ = view_screen_rect;
1674 window_screen_rect_ = window_screen_rect;
1676 Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id()));
1679 void RenderWidget::showImeIfNeeded() {
1680 OnShowImeIfNeeded();
1683 void RenderWidget::OnShowImeIfNeeded() {
1684 #if defined(OS_ANDROID) || defined(USE_AURA)
1685 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
1686 #endif
1689 #if defined(OS_ANDROID)
1690 void RenderWidget::IncrementOutstandingImeEventAcks() {
1691 ++outstanding_ime_acks_;
1694 void RenderWidget::OnImeEventAck() {
1695 --outstanding_ime_acks_;
1696 DCHECK(outstanding_ime_acks_ >= 0);
1698 #endif
1700 bool RenderWidget::ShouldHandleImeEvent() {
1701 #if defined(OS_ANDROID)
1702 return !!webwidget_ && outstanding_ime_acks_ == 0;
1703 #else
1704 return !!webwidget_;
1705 #endif
1708 bool RenderWidget::SendAckForMouseMoveFromDebugger() {
1709 if (handling_event_type_ == WebInputEvent::MouseMove) {
1710 // If we pause multiple times during a single mouse move event, we should
1711 // only send ACK once.
1712 if (!ignore_ack_for_mouse_move_from_debugger_) {
1713 InputHostMsg_HandleInputEvent_ACK_Params ack;
1714 ack.type = handling_event_type_;
1715 ack.state = INPUT_EVENT_ACK_STATE_CONSUMED;
1716 Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack));
1718 return true;
1720 return false;
1723 void RenderWidget::IgnoreAckForMouseMoveFromDebugger() {
1724 ignore_ack_for_mouse_move_from_debugger_ = true;
1727 void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) {
1728 if (device_scale_factor_ == device_scale_factor)
1729 return;
1731 device_scale_factor_ = device_scale_factor;
1732 scheduleComposite();
1735 bool RenderWidget::SetDeviceColorProfile(
1736 const std::vector<char>& color_profile) {
1737 if (device_color_profile_ == color_profile)
1738 return false;
1740 device_color_profile_ = color_profile;
1741 return true;
1744 void RenderWidget::ResetDeviceColorProfileForTesting() {
1745 if (!device_color_profile_.empty())
1746 device_color_profile_.clear();
1747 device_color_profile_.push_back('0');
1750 void RenderWidget::OnOrientationChange() {
1753 gfx::Vector2d RenderWidget::GetScrollOffset() {
1754 // Bare RenderWidgets don't support scroll offset.
1755 return gfx::Vector2d();
1758 void RenderWidget::SetHidden(bool hidden) {
1759 if (is_hidden_ == hidden)
1760 return;
1762 // The status has changed. Tell the RenderThread about it.
1763 is_hidden_ = hidden;
1764 if (is_hidden_)
1765 RenderThreadImpl::current()->WidgetHidden();
1766 else
1767 RenderThreadImpl::current()->WidgetRestored();
1770 void RenderWidget::WillToggleFullscreen() {
1771 if (!webwidget_)
1772 return;
1774 if (is_fullscreen_) {
1775 webwidget_->willExitFullScreen();
1776 } else {
1777 webwidget_->willEnterFullScreen();
1781 void RenderWidget::DidToggleFullscreen() {
1782 if (!webwidget_)
1783 return;
1785 if (is_fullscreen_) {
1786 webwidget_->didEnterFullScreen();
1787 } else {
1788 webwidget_->didExitFullScreen();
1792 bool RenderWidget::next_paint_is_resize_ack() const {
1793 return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_);
1796 void RenderWidget::set_next_paint_is_resize_ack() {
1797 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK;
1800 void RenderWidget::set_next_paint_is_repaint_ack() {
1801 next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK;
1804 static bool IsDateTimeInput(ui::TextInputType type) {
1805 return type == ui::TEXT_INPUT_TYPE_DATE ||
1806 type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
1807 type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
1808 type == ui::TEXT_INPUT_TYPE_MONTH ||
1809 type == ui::TEXT_INPUT_TYPE_TIME ||
1810 type == ui::TEXT_INPUT_TYPE_WEEK;
1814 void RenderWidget::StartHandlingImeEvent() {
1815 DCHECK(!handling_ime_event_);
1816 handling_ime_event_ = true;
1819 void RenderWidget::FinishHandlingImeEvent() {
1820 DCHECK(handling_ime_event_);
1821 handling_ime_event_ = false;
1822 // While handling an ime event, text input state and selection bounds updates
1823 // are ignored. These must explicitly be updated once finished handling the
1824 // ime event.
1825 UpdateSelectionBounds();
1826 #if defined(OS_ANDROID)
1827 UpdateTextInputState(NO_SHOW_IME, FROM_IME);
1828 #endif
1831 void RenderWidget::UpdateTextInputType() {
1832 // On Windows, not only an IME but also an on-screen keyboard relies on the
1833 // latest TextInputType to optimize its layout and functionality. Thus
1834 // |input_method_is_active_| is no longer an appropriate condition to suppress
1835 // TextInputTypeChanged IPC on Windows.
1836 // TODO(yukawa, yoichio): Consider to stop checking |input_method_is_active_|
1837 // on other platforms as well as Windows if the overhead is acceptable.
1838 #if !defined(OS_WIN)
1839 if (!input_method_is_active_)
1840 return;
1841 #endif
1843 ui::TextInputType new_type = GetTextInputType();
1844 if (IsDateTimeInput(new_type))
1845 return; // Not considered as a text input field in WebKit/Chromium.
1847 bool new_can_compose_inline = CanComposeInline();
1849 blink::WebTextInputInfo new_info;
1850 if (webwidget_)
1851 new_info = webwidget_->textInputInfo();
1852 const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode);
1853 int new_flags = new_info.flags;
1855 if (text_input_type_ != new_type
1856 || can_compose_inline_ != new_can_compose_inline
1857 || text_input_mode_ != new_mode
1858 || text_input_flags_ != new_flags) {
1859 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1860 new_type,
1861 new_mode,
1862 new_can_compose_inline,
1863 new_flags));
1864 text_input_type_ = new_type;
1865 can_compose_inline_ = new_can_compose_inline;
1866 text_input_mode_ = new_mode;
1867 text_input_flags_ = new_flags;
1871 #if defined(OS_ANDROID) || defined(USE_AURA)
1872 void RenderWidget::UpdateTextInputState(ShowIme show_ime,
1873 ChangeSource change_source) {
1874 if (handling_ime_event_)
1875 return;
1876 if (show_ime == NO_SHOW_IME && !input_method_is_active_)
1877 return;
1878 ui::TextInputType new_type = GetTextInputType();
1879 if (IsDateTimeInput(new_type))
1880 return; // Not considered as a text input field in WebKit/Chromium.
1882 blink::WebTextInputInfo new_info;
1883 if (webwidget_)
1884 new_info = webwidget_->textInputInfo();
1886 bool new_can_compose_inline = CanComposeInline();
1888 // Only sends text input params if they are changed or if the ime should be
1889 // shown.
1890 if (show_ime == SHOW_IME_IF_NEEDED ||
1891 (text_input_type_ != new_type ||
1892 text_input_info_ != new_info ||
1893 can_compose_inline_ != new_can_compose_inline)
1894 #if defined(OS_ANDROID)
1895 || text_field_is_dirty_
1896 #endif
1898 ViewHostMsg_TextInputState_Params p;
1899 p.type = new_type;
1900 p.flags = new_info.flags;
1901 p.value = new_info.value.utf8();
1902 p.selection_start = new_info.selectionStart;
1903 p.selection_end = new_info.selectionEnd;
1904 p.composition_start = new_info.compositionStart;
1905 p.composition_end = new_info.compositionEnd;
1906 p.can_compose_inline = new_can_compose_inline;
1907 p.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED);
1908 #if defined(USE_AURA)
1909 p.is_non_ime_change = true;
1910 #endif
1911 #if defined(OS_ANDROID)
1912 p.is_non_ime_change = (change_source == FROM_NON_IME) ||
1913 text_field_is_dirty_;
1914 if (p.is_non_ime_change)
1915 IncrementOutstandingImeEventAcks();
1916 text_field_is_dirty_ = false;
1917 #endif
1918 #if defined(USE_AURA)
1919 Send(new ViewHostMsg_TextInputTypeChanged(routing_id(),
1920 new_type,
1921 text_input_mode_,
1922 new_can_compose_inline,
1923 new_info.flags));
1924 #endif
1925 Send(new ViewHostMsg_TextInputStateChanged(routing_id(), p));
1927 text_input_info_ = new_info;
1928 text_input_type_ = new_type;
1929 can_compose_inline_ = new_can_compose_inline;
1930 text_input_flags_ = new_info.flags;
1933 #endif
1935 void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) {
1936 WebRect focus_webrect;
1937 WebRect anchor_webrect;
1938 webwidget_->selectionBounds(focus_webrect, anchor_webrect);
1939 *focus = focus_webrect;
1940 *anchor = anchor_webrect;
1943 void RenderWidget::UpdateSelectionBounds() {
1944 if (!webwidget_)
1945 return;
1946 if (handling_ime_event_)
1947 return;
1949 // With composited selection updates, the selection bounds will be reported
1950 // directly by the compositor, in which case explicit IPC selection
1951 // notifications should be suppressed.
1952 if (!blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled()) {
1953 ViewHostMsg_SelectionBounds_Params params;
1954 GetSelectionBounds(&params.anchor_rect, &params.focus_rect);
1955 if (selection_anchor_rect_ != params.anchor_rect ||
1956 selection_focus_rect_ != params.focus_rect) {
1957 selection_anchor_rect_ = params.anchor_rect;
1958 selection_focus_rect_ = params.focus_rect;
1959 webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir);
1960 params.is_anchor_first = webwidget_->isSelectionAnchorFirst();
1961 Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params));
1965 UpdateCompositionInfo(false);
1968 // Check blink::WebTextInputType and ui::TextInputType is kept in sync.
1969 COMPILE_ASSERT(int(blink::WebTextInputTypeNone) == \
1970 int(ui::TEXT_INPUT_TYPE_NONE), mismatching_enums);
1971 COMPILE_ASSERT(int(blink::WebTextInputTypeText) == \
1972 int(ui::TEXT_INPUT_TYPE_TEXT), mismatching_enums);
1973 COMPILE_ASSERT(int(blink::WebTextInputTypePassword) == \
1974 int(ui::TEXT_INPUT_TYPE_PASSWORD), mismatching_enums);
1975 COMPILE_ASSERT(int(blink::WebTextInputTypeSearch) == \
1976 int(ui::TEXT_INPUT_TYPE_SEARCH), mismatching_enums);
1977 COMPILE_ASSERT(int(blink::WebTextInputTypeEmail) == \
1978 int(ui::TEXT_INPUT_TYPE_EMAIL), mismatching_enums);
1979 COMPILE_ASSERT(int(blink::WebTextInputTypeNumber) == \
1980 int(ui::TEXT_INPUT_TYPE_NUMBER), mismatching_enums);
1981 COMPILE_ASSERT(int(blink::WebTextInputTypeTelephone) == \
1982 int(ui::TEXT_INPUT_TYPE_TELEPHONE), mismatching_enums);
1983 COMPILE_ASSERT(int(blink::WebTextInputTypeURL) == \
1984 int(ui::TEXT_INPUT_TYPE_URL), mismatching_enums);
1985 COMPILE_ASSERT(int(blink::WebTextInputTypeDate) == \
1986 int(ui::TEXT_INPUT_TYPE_DATE), mismatching_enum);
1987 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTime) == \
1988 int(ui::TEXT_INPUT_TYPE_DATE_TIME), mismatching_enum);
1989 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeLocal) == \
1990 int(ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL), mismatching_enum);
1991 COMPILE_ASSERT(int(blink::WebTextInputTypeMonth) == \
1992 int(ui::TEXT_INPUT_TYPE_MONTH), mismatching_enum);
1993 COMPILE_ASSERT(int(blink::WebTextInputTypeTime) == \
1994 int(ui::TEXT_INPUT_TYPE_TIME), mismatching_enum);
1995 COMPILE_ASSERT(int(blink::WebTextInputTypeWeek) == \
1996 int(ui::TEXT_INPUT_TYPE_WEEK), mismatching_enum);
1997 COMPILE_ASSERT(int(blink::WebTextInputTypeTextArea) == \
1998 int(ui::TEXT_INPUT_TYPE_TEXT_AREA), mismatching_enums);
1999 COMPILE_ASSERT(int(blink::WebTextInputTypeContentEditable) == \
2000 int(ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE), mismatching_enums);
2001 COMPILE_ASSERT(int(blink::WebTextInputTypeDateTimeField) == \
2002 int(ui::TEXT_INPUT_TYPE_DATE_TIME_FIELD), mismatching_enums);
2004 ui::TextInputType RenderWidget::WebKitToUiTextInputType(
2005 blink::WebTextInputType type) {
2006 // Check the type is in the range representable by ui::TextInputType.
2007 DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) <<
2008 "blink::WebTextInputType and ui::TextInputType not synchronized";
2009 return static_cast<ui::TextInputType>(type);
2012 ui::TextInputType RenderWidget::GetTextInputType() {
2013 if (webwidget_)
2014 return WebKitToUiTextInputType(webwidget_->textInputInfo().type);
2015 return ui::TEXT_INPUT_TYPE_NONE;
2018 void RenderWidget::UpdateCompositionInfo(bool should_update_range) {
2019 #if defined(OS_ANDROID)
2020 // Sending composition info makes sense only in Lollipop (API level 21)
2021 // and above due to the API availability.
2022 if (base::android::BuildInfo::GetInstance()->sdk_int() < 21)
2023 return;
2024 #endif
2026 gfx::Range range = gfx::Range();
2027 if (should_update_range) {
2028 GetCompositionRange(&range);
2029 } else {
2030 range = composition_range_;
2032 std::vector<gfx::Rect> character_bounds;
2033 GetCompositionCharacterBounds(&character_bounds);
2035 if (!ShouldUpdateCompositionInfo(range, character_bounds))
2036 return;
2037 composition_character_bounds_ = character_bounds;
2038 composition_range_ = range;
2039 Send(new InputHostMsg_ImeCompositionRangeChanged(
2040 routing_id(), composition_range_, composition_character_bounds_));
2043 void RenderWidget::GetCompositionCharacterBounds(
2044 std::vector<gfx::Rect>* bounds) {
2045 DCHECK(bounds);
2046 bounds->clear();
2049 void RenderWidget::GetCompositionRange(gfx::Range* range) {
2050 size_t location, length;
2051 if (webwidget_->compositionRange(&location, &length)) {
2052 range->set_start(location);
2053 range->set_end(location + length);
2054 } else if (webwidget_->caretOrSelectionRange(&location, &length)) {
2055 range->set_start(location);
2056 range->set_end(location + length);
2057 } else {
2058 *range = gfx::Range::InvalidRange();
2062 bool RenderWidget::ShouldUpdateCompositionInfo(
2063 const gfx::Range& range,
2064 const std::vector<gfx::Rect>& bounds) {
2065 if (composition_range_ != range)
2066 return true;
2067 if (bounds.size() != composition_character_bounds_.size())
2068 return true;
2069 for (size_t i = 0; i < bounds.size(); ++i) {
2070 if (bounds[i] != composition_character_bounds_[i])
2071 return true;
2073 return false;
2076 #if defined(OS_ANDROID)
2077 void RenderWidget::DidChangeBodyBackgroundColor(SkColor bg_color) {
2078 // If not initialized, default to white. Note that 0 is different from black
2079 // as black still has alpha 0xFF.
2080 if (!bg_color)
2081 bg_color = SK_ColorWHITE;
2083 if (bg_color != body_background_color_) {
2084 body_background_color_ = bg_color;
2085 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(routing_id(), bg_color));
2089 bool RenderWidget::DoesRecordFullLayer() const {
2090 SynchronousCompositorFactory* synchronous_compositor_factory =
2091 SynchronousCompositorFactory::GetInstance();
2093 // We assume that the absence of synchronous_compositor_factory
2094 // means we are in Chrome. In chrome, we want to clip, i.e.
2095 // *not* to record the full layer.
2096 if (!synchronous_compositor_factory)
2097 return false;
2099 return synchronous_compositor_factory->RecordFullLayer();
2101 #endif
2103 bool RenderWidget::CanComposeInline() {
2104 return true;
2107 WebScreenInfo RenderWidget::screenInfo() {
2108 return screen_info_;
2111 float RenderWidget::deviceScaleFactor() {
2112 return device_scale_factor_;
2115 void RenderWidget::resetInputMethod() {
2116 if (!input_method_is_active_)
2117 return;
2119 ImeEventGuard guard(this);
2120 // If the last text input type is not None, then we should finish any
2121 // ongoing composition regardless of the new text input type.
2122 if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) {
2123 // If a composition text exists, then we need to let the browser process
2124 // to cancel the input method's ongoing composition session.
2125 if (webwidget_->confirmComposition())
2126 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
2129 UpdateCompositionInfo(true);
2132 void RenderWidget::didHandleGestureEvent(
2133 const WebGestureEvent& event,
2134 bool event_cancelled) {
2135 #if defined(OS_ANDROID) || defined(USE_AURA)
2136 if (event_cancelled)
2137 return;
2138 if (event.type == WebInputEvent::GestureTap) {
2139 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2140 } else if (event.type == WebInputEvent::GestureLongPress) {
2141 DCHECK(webwidget_);
2142 if (webwidget_->textInputInfo().value.isEmpty())
2143 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
2144 else
2145 UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME);
2147 #endif
2150 void RenderWidget::StartCompositor() {
2151 // For widgets that are never visible, we don't need the compositor to run
2152 // at all.
2153 if (never_visible_)
2154 return;
2155 compositor_->setSurfaceReady();
2158 void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) {
2159 size_t i = 0;
2160 for (; i < plugin_window_moves_.size(); ++i) {
2161 if (plugin_window_moves_[i].window == move.window) {
2162 if (move.rects_valid) {
2163 plugin_window_moves_[i] = move;
2164 } else {
2165 plugin_window_moves_[i].visible = move.visible;
2167 break;
2171 if (i == plugin_window_moves_.size())
2172 plugin_window_moves_.push_back(move);
2175 void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) {
2176 for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin();
2177 i != plugin_window_moves_.end(); ++i) {
2178 if (i->window == window) {
2179 plugin_window_moves_.erase(i);
2180 break;
2186 RenderWidgetCompositor* RenderWidget::compositor() const {
2187 return compositor_.get();
2190 bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
2191 return false;
2194 bool RenderWidget::WillHandleGestureEvent(
2195 const blink::WebGestureEvent& event) {
2196 return false;
2199 void RenderWidget::hasTouchEventHandlers(bool has_handlers) {
2200 Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers));
2203 void RenderWidget::setTouchAction(
2204 blink::WebTouchAction web_touch_action) {
2206 // Ignore setTouchAction calls that result from synthetic touch events (eg.
2207 // when blink is emulating touch with mouse).
2208 if (handling_event_type_ != WebInputEvent::TouchStart)
2209 return;
2211 // Verify the same values are used by the types so we can cast between them.
2212 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_AUTO) ==
2213 blink::WebTouchActionAuto,
2214 enum_values_must_match_for_touch_action);
2215 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_NONE) ==
2216 blink::WebTouchActionNone,
2217 enum_values_must_match_for_touch_action);
2218 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_X) ==
2219 blink::WebTouchActionPanX,
2220 enum_values_must_match_for_touch_action);
2221 COMPILE_ASSERT(static_cast<blink::WebTouchAction>(TOUCH_ACTION_PAN_Y) ==
2222 blink::WebTouchActionPanY,
2223 enum_values_must_match_for_touch_action);
2224 COMPILE_ASSERT(
2225 static_cast<blink::WebTouchAction>(TOUCH_ACTION_PINCH_ZOOM) ==
2226 blink::WebTouchActionPinchZoom,
2227 enum_values_must_match_for_touch_action);
2229 content::TouchAction content_touch_action =
2230 static_cast<content::TouchAction>(web_touch_action);
2231 Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action));
2234 void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() {
2235 #if defined(OS_ANDROID)
2236 text_field_is_dirty_ = true;
2237 #endif
2240 bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const {
2241 return true;
2244 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
2245 RenderWidget::CreateGraphicsContext3D() {
2246 if (!webwidget_)
2247 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2248 if (CommandLine::ForCurrentProcess()->HasSwitch(
2249 switches::kDisableGpuCompositing))
2250 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2251 if (!RenderThreadImpl::current())
2252 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2253 CauseForGpuLaunch cause =
2254 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
2255 scoped_refptr<GpuChannelHost> gpu_channel_host(
2256 RenderThreadImpl::current()->EstablishGpuChannelSync(cause));
2257 if (!gpu_channel_host.get())
2258 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
2260 // Explicitly disable antialiasing for the compositor. As of the time of
2261 // this writing, the only platform that supported antialiasing for the
2262 // compositor was Mac OS X, because the on-screen OpenGL context creation
2263 // code paths on Windows and Linux didn't yet have multisampling support.
2264 // Mac OS X essentially always behaves as though it's rendering offscreen.
2265 // Multisampling has a heavy cost especially on devices with relatively low
2266 // fill rate like most notebooks, and the Mac implementation would need to
2267 // be optimized to resolve directly into the IOSurface shared between the
2268 // GPU and browser processes. For these reasons and to avoid platform
2269 // disparities we explicitly disable antialiasing.
2270 blink::WebGraphicsContext3D::Attributes attributes;
2271 attributes.antialias = false;
2272 attributes.shareResources = true;
2273 attributes.noAutomaticFlushes = true;
2274 attributes.depth = false;
2275 attributes.stencil = false;
2276 bool lose_context_when_out_of_memory = true;
2277 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits;
2278 #if defined(OS_ANDROID)
2279 // If we raster too fast we become upload bound, and pending
2280 // uploads consume memory. For maximum upload throughput, we would
2281 // want to allow for upload_throughput * pipeline_time of pending
2282 // uploads, after which we are just wasting memory. Since we don't
2283 // know our upload throughput yet, this just caps our memory usage.
2284 size_t divider = 1;
2285 if (base::SysInfo::IsLowEndDevice())
2286 divider = 6;
2287 // For reference Nexus10 can upload 1MB in about 2.5ms.
2288 const double max_mb_uploaded_per_ms = 2.0 / (5 * divider);
2289 // Deadline to draw a frame to achieve 60 frames per second.
2290 const size_t kMillisecondsPerFrame = 16;
2291 // Assuming a two frame deep pipeline between the CPU and the GPU.
2292 size_t max_transfer_buffer_usage_mb =
2293 static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms);
2294 static const size_t kBytesPerMegabyte = 1024 * 1024;
2295 // We keep the MappedMemoryReclaimLimit the same as the upload limit
2296 // to avoid unnecessarily stalling the compositor thread.
2297 limits.mapped_memory_reclaim_limit =
2298 max_transfer_buffer_usage_mb * kBytesPerMegabyte;
2299 #endif
2301 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
2302 new WebGraphicsContext3DCommandBufferImpl(surface_id(),
2303 GetURLForGraphicsContext3D(),
2304 gpu_channel_host.get(),
2305 attributes,
2306 lose_context_when_out_of_memory,
2307 limits,
2308 NULL));
2309 return context.Pass();
2312 void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) {
2313 render_frame_proxies_.AddObserver(proxy);
2316 void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) {
2317 render_frame_proxies_.RemoveObserver(proxy);
2320 void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) {
2321 render_frames_.AddObserver(frame);
2324 void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) {
2325 render_frames_.RemoveObserver(frame);
2328 #if defined(VIDEO_HOLE)
2329 void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) {
2330 video_hole_frames_.AddObserver(frame);
2333 void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) {
2334 video_hole_frames_.RemoveObserver(frame);
2336 #endif // defined(VIDEO_HOLE)
2338 } // namespace content