Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / content / renderer / browser_plugin / browser_plugin.cc
blobc2b73247e2508f3ab7f0e7cec619614902447b1e
1 // Copyright 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/browser_plugin/browser_plugin.h"
7 #include "base/command_line.h"
8 #include "base/location.h"
9 #include "base/single_thread_task_runner.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/thread_task_runner_handle.h"
13 #include "cc/surfaces/surface.h"
14 #include "content/common/browser_plugin/browser_plugin_constants.h"
15 #include "content/common/browser_plugin/browser_plugin_messages.h"
16 #include "content/common/view_messages.h"
17 #include "content/public/common/content_client.h"
18 #include "content/public/common/content_switches.h"
19 #include "content/public/renderer/browser_plugin_delegate.h"
20 #include "content/public/renderer/content_renderer_client.h"
21 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
22 #include "content/renderer/child_frame_compositing_helper.h"
23 #include "content/renderer/cursor_utils.h"
24 #include "content/renderer/drop_data_builder.h"
25 #include "content/renderer/render_thread_impl.h"
26 #include "content/renderer/sad_plugin.h"
27 #include "third_party/WebKit/public/platform/WebRect.h"
28 #include "third_party/WebKit/public/web/WebDocument.h"
29 #include "third_party/WebKit/public/web/WebElement.h"
30 #include "third_party/WebKit/public/web/WebInputEvent.h"
31 #include "third_party/WebKit/public/web/WebLocalFrame.h"
32 #include "third_party/WebKit/public/web/WebPluginContainer.h"
33 #include "third_party/WebKit/public/web/WebView.h"
34 #include "third_party/skia/include/core/SkCanvas.h"
35 #include "ui/events/keycodes/keyboard_codes.h"
37 using blink::WebCanvas;
38 using blink::WebPluginContainer;
39 using blink::WebPoint;
40 using blink::WebRect;
41 using blink::WebURL;
42 using blink::WebVector;
44 namespace {
45 using PluginContainerMap =
46 std::map<blink::WebPluginContainer*, content::BrowserPlugin*>;
47 static base::LazyInstance<PluginContainerMap> g_plugin_container_map =
48 LAZY_INSTANCE_INITIALIZER;
49 } // namespace
51 namespace content {
53 // static
54 BrowserPlugin* BrowserPlugin::GetFromNode(blink::WebNode& node) {
55 blink::WebPluginContainer* container = node.pluginContainer();
56 if (!container)
57 return nullptr;
59 PluginContainerMap* browser_plugins = g_plugin_container_map.Pointer();
60 PluginContainerMap::iterator it = browser_plugins->find(container);
61 return it == browser_plugins->end() ? nullptr : it->second;
64 BrowserPlugin::BrowserPlugin(
65 RenderFrame* render_frame,
66 const base::WeakPtr<BrowserPluginDelegate>& delegate)
67 : attached_(false),
68 render_frame_routing_id_(render_frame->GetRoutingID()),
69 container_(nullptr),
70 sad_guest_(nullptr),
71 guest_crashed_(false),
72 plugin_focused_(false),
73 visible_(true),
74 mouse_locked_(false),
75 ready_(false),
76 browser_plugin_instance_id_(browser_plugin::kInstanceIDNone),
77 contents_opaque_(true),
78 delegate_(delegate),
79 weak_ptr_factory_(this) {
80 browser_plugin_instance_id_ =
81 BrowserPluginManager::Get()->GetNextInstanceID();
83 if (delegate_)
84 delegate_->SetElementInstanceID(browser_plugin_instance_id_);
87 BrowserPlugin::~BrowserPlugin() {
88 if (compositing_helper_.get())
89 compositing_helper_->OnContainerDestroy();
91 if (delegate_) {
92 delegate_->DidDestroyElement();
93 delegate_.reset();
96 BrowserPluginManager::Get()->RemoveBrowserPlugin(browser_plugin_instance_id_);
99 bool BrowserPlugin::OnMessageReceived(const IPC::Message& message) {
100 bool handled = true;
101 IPC_BEGIN_MESSAGE_MAP(BrowserPlugin, message)
102 IPC_MESSAGE_HANDLER(BrowserPluginMsg_AdvanceFocus, OnAdvanceFocus)
103 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginMsg_CompositorFrameSwapped,
104 OnCompositorFrameSwapped(message))
105 IPC_MESSAGE_HANDLER(BrowserPluginMsg_GuestGone, OnGuestGone)
106 IPC_MESSAGE_HANDLER(BrowserPluginMsg_SetContentsOpaque, OnSetContentsOpaque)
107 IPC_MESSAGE_HANDLER(BrowserPluginMsg_SetCursor, OnSetCursor)
108 IPC_MESSAGE_HANDLER(BrowserPluginMsg_SetMouseLock, OnSetMouseLock)
109 IPC_MESSAGE_HANDLER(BrowserPluginMsg_SetTooltipText, OnSetTooltipText)
110 IPC_MESSAGE_HANDLER(BrowserPluginMsg_ShouldAcceptTouchEvents,
111 OnShouldAcceptTouchEvents)
112 IPC_MESSAGE_HANDLER(BrowserPluginMsg_SetChildFrameSurface,
113 OnSetChildFrameSurface)
114 IPC_END_MESSAGE_MAP()
115 return handled;
118 void BrowserPlugin::OnSetChildFrameSurface(
119 int browser_plugin_instance_id,
120 const cc::SurfaceId& surface_id,
121 const gfx::Size& frame_size,
122 float scale_factor,
123 const cc::SurfaceSequence& sequence) {
124 if (!attached())
125 return;
127 EnableCompositing(true);
128 DCHECK(compositing_helper_.get());
130 compositing_helper_->OnSetSurface(surface_id, frame_size, scale_factor,
131 sequence);
134 void BrowserPlugin::SendSatisfySequence(const cc::SurfaceSequence& sequence) {
135 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_SatisfySequence(
136 render_frame_routing_id_, browser_plugin_instance_id_, sequence));
139 void BrowserPlugin::UpdateDOMAttribute(const std::string& attribute_name,
140 const base::string16& attribute_value) {
141 if (!container())
142 return;
144 blink::WebElement element = container()->element();
145 blink::WebString web_attribute_name =
146 blink::WebString::fromUTF8(attribute_name);
147 element.setAttribute(web_attribute_name, attribute_value);
150 void BrowserPlugin::Attach() {
151 Detach();
153 BrowserPluginHostMsg_Attach_Params attach_params;
154 attach_params.focused = ShouldGuestBeFocused();
155 attach_params.visible = visible_;
156 attach_params.view_rect = view_rect();
157 attach_params.is_full_page_plugin = false;
158 if (container()) {
159 blink::WebLocalFrame* frame = container()->element().document().frame();
160 attach_params.is_full_page_plugin =
161 frame->view()->mainFrame()->document().isPluginDocument();
163 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_Attach(
164 render_frame_routing_id_,
165 browser_plugin_instance_id_,
166 attach_params));
168 attached_ = true;
171 void BrowserPlugin::Detach() {
172 if (!attached())
173 return;
175 attached_ = false;
176 guest_crashed_ = false;
177 EnableCompositing(false);
178 if (compositing_helper_.get()) {
179 compositing_helper_->OnContainerDestroy();
180 compositing_helper_ = nullptr;
183 BrowserPluginManager::Get()->Send(
184 new BrowserPluginHostMsg_Detach(browser_plugin_instance_id_));
187 void BrowserPlugin::DidCommitCompositorFrame() {
188 if (compositing_helper_.get())
189 compositing_helper_->DidCommitCompositorFrame();
192 void BrowserPlugin::OnAdvanceFocus(int browser_plugin_instance_id,
193 bool reverse) {
194 auto render_frame = RenderFrameImpl::FromRoutingID(render_frame_routing_id());
195 auto render_view = render_frame ? render_frame->GetRenderView() : nullptr;
196 if (!render_view)
197 return;
198 render_view->GetWebView()->advanceFocus(reverse);
201 void BrowserPlugin::OnCompositorFrameSwapped(const IPC::Message& message) {
202 if (!attached())
203 return;
205 BrowserPluginMsg_CompositorFrameSwapped::Param param;
206 if (!BrowserPluginMsg_CompositorFrameSwapped::Read(&message, &param))
207 return;
208 // Note that there is no need to send ACK for this message.
209 // If the guest has updated pixels then it is no longer crashed.
210 guest_crashed_ = false;
212 scoped_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame);
213 base::get<1>(param).frame.AssignTo(frame.get());
215 EnableCompositing(true);
216 compositing_helper_->OnCompositorFrameSwapped(
217 frame.Pass(),
218 base::get<1>(param).producing_route_id,
219 base::get<1>(param).output_surface_id,
220 base::get<1>(param).producing_host_id,
221 base::get<1>(param).shared_memory_handle);
224 void BrowserPlugin::OnGuestGone(int browser_plugin_instance_id) {
225 guest_crashed_ = true;
227 // Turn off compositing so we can display the sad graphic. Changes to
228 // compositing state will show up at a later time after a layout and commit.
229 EnableCompositing(false);
231 // Queue up showing the sad graphic to give content embedders an opportunity
232 // to fire their listeners and potentially overlay the webview with custom
233 // behavior. If the BrowserPlugin is destroyed in the meantime, then the
234 // task will not be executed.
235 base::ThreadTaskRunnerHandle::Get()->PostTask(
236 FROM_HERE, base::Bind(&BrowserPlugin::ShowSadGraphic,
237 weak_ptr_factory_.GetWeakPtr()));
240 void BrowserPlugin::OnSetContentsOpaque(int browser_plugin_instance_id,
241 bool opaque) {
242 if (contents_opaque_ == opaque)
243 return;
244 contents_opaque_ = opaque;
245 if (compositing_helper_.get())
246 compositing_helper_->SetContentsOpaque(opaque);
249 void BrowserPlugin::OnSetCursor(int browser_plugin_instance_id,
250 const WebCursor& cursor) {
251 cursor_ = cursor;
254 void BrowserPlugin::OnSetMouseLock(int browser_plugin_instance_id,
255 bool enable) {
256 auto render_frame = RenderFrameImpl::FromRoutingID(render_frame_routing_id());
257 auto render_view = static_cast<RenderViewImpl*>(
258 render_frame ? render_frame->GetRenderView() : nullptr);
259 if (enable) {
260 if (mouse_locked_ || !render_view)
261 return;
262 render_view->mouse_lock_dispatcher()->LockMouse(this);
263 } else {
264 if (!mouse_locked_) {
265 OnLockMouseACK(false);
266 return;
268 if (!render_view)
269 return;
270 render_view->mouse_lock_dispatcher()->UnlockMouse(this);
274 void BrowserPlugin::OnSetTooltipText(int instance_id,
275 const base::string16& tooltip_text) {
276 // Show tooltip text by setting the BrowserPlugin's |title| attribute.
277 UpdateDOMAttribute("title", tooltip_text);
280 void BrowserPlugin::OnShouldAcceptTouchEvents(int browser_plugin_instance_id,
281 bool accept) {
282 if (container()) {
283 container()->requestTouchEventType(
284 accept ? WebPluginContainer::TouchEventRequestTypeRaw
285 : WebPluginContainer::TouchEventRequestTypeNone);
289 void BrowserPlugin::ShowSadGraphic() {
290 // If the BrowserPlugin is scheduled to be deleted, then container_ will be
291 // nullptr so we shouldn't attempt to access it.
292 if (container_)
293 container_->invalidate();
296 void BrowserPlugin::UpdateInternalInstanceId() {
297 // This is a way to notify observers of our attributes that this plugin is
298 // available in render tree.
299 // TODO(lazyboy): This should be done through the delegate instead. Perhaps
300 // by firing an event from there.
301 UpdateDOMAttribute(
302 "internalinstanceid",
303 base::UTF8ToUTF16(base::IntToString(browser_plugin_instance_id_)));
306 void BrowserPlugin::UpdateGuestFocusState(blink::WebFocusType focus_type) {
307 if (!attached())
308 return;
309 bool should_be_focused = ShouldGuestBeFocused();
310 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_SetFocus(
311 browser_plugin_instance_id_,
312 should_be_focused,
313 focus_type));
316 bool BrowserPlugin::ShouldGuestBeFocused() const {
317 bool embedder_focused = false;
318 auto render_frame = RenderFrameImpl::FromRoutingID(render_frame_routing_id());
319 auto render_view = static_cast<RenderViewImpl*>(
320 render_frame ? render_frame->GetRenderView() : nullptr);
321 if (render_view)
322 embedder_focused = render_view->has_focus();
323 return plugin_focused_ && embedder_focused;
326 WebPluginContainer* BrowserPlugin::container() const {
327 return container_;
330 bool BrowserPlugin::initialize(WebPluginContainer* container) {
331 if (!container)
332 return false;
334 container_ = container;
335 container_->setWantsWheelEvents(true);
337 g_plugin_container_map.Get().insert(std::make_pair(container_, this));
339 BrowserPluginManager::Get()->AddBrowserPlugin(
340 browser_plugin_instance_id_, this);
342 // Defer attach call so that if there's any pending browser plugin
343 // destruction, then it can progress first.
344 base::ThreadTaskRunnerHandle::Get()->PostTask(
345 FROM_HERE, base::Bind(&BrowserPlugin::UpdateInternalInstanceId,
346 weak_ptr_factory_.GetWeakPtr()));
347 return true;
350 void BrowserPlugin::EnableCompositing(bool enable) {
351 bool enabled = !!compositing_helper_.get();
352 if (enabled == enable)
353 return;
355 if (enable) {
356 DCHECK(!compositing_helper_.get());
357 if (!compositing_helper_.get()) {
358 compositing_helper_ = ChildFrameCompositingHelper::CreateForBrowserPlugin(
359 weak_ptr_factory_.GetWeakPtr());
362 compositing_helper_->EnableCompositing(enable);
363 compositing_helper_->SetContentsOpaque(contents_opaque_);
365 if (!enable) {
366 DCHECK(compositing_helper_.get());
367 compositing_helper_->OnContainerDestroy();
368 compositing_helper_ = nullptr;
372 void BrowserPlugin::destroy() {
373 if (container_) {
374 // The BrowserPlugin's WebPluginContainer is deleted immediately after this
375 // call returns, so let's not keep a reference to it around.
376 g_plugin_container_map.Get().erase(container_);
379 container_ = nullptr;
380 // Will be a no-op if the mouse is not currently locked.
381 auto render_frame = RenderFrameImpl::FromRoutingID(render_frame_routing_id());
382 auto render_view = static_cast<RenderViewImpl*>(
383 render_frame ? render_frame->GetRenderView() : nullptr);
384 if (render_view)
385 render_view->mouse_lock_dispatcher()->OnLockTargetDestroyed(this);
386 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
389 v8::Local<v8::Object> BrowserPlugin::v8ScriptableObject(v8::Isolate* isolate) {
390 if (!delegate_)
391 return v8::Local<v8::Object>();
393 return delegate_->V8ScriptableObject(isolate);
396 bool BrowserPlugin::supportsKeyboardFocus() const {
397 return true;
400 bool BrowserPlugin::supportsEditCommands() const {
401 return true;
404 bool BrowserPlugin::supportsInputMethod() const {
405 return true;
408 bool BrowserPlugin::canProcessDrag() const {
409 return true;
412 void BrowserPlugin::paint(WebCanvas* canvas, const WebRect& rect) {
413 if (guest_crashed_) {
414 if (!sad_guest_) // Lazily initialize bitmap.
415 sad_guest_ = GetContentClient()->renderer()->GetSadWebViewBitmap();
416 // content_shell does not have the sad plugin bitmap, so we'll paint black
417 // instead to make it clear that something went wrong.
418 if (sad_guest_) {
419 PaintSadPlugin(canvas, view_rect_, *sad_guest_);
420 return;
423 SkAutoCanvasRestore auto_restore(canvas, true);
424 canvas->translate(view_rect_.x(), view_rect_.y());
425 SkRect image_data_rect = SkRect::MakeXYWH(
426 SkIntToScalar(0),
427 SkIntToScalar(0),
428 SkIntToScalar(view_rect_.width()),
429 SkIntToScalar(view_rect_.height()));
430 canvas->clipRect(image_data_rect);
431 // Paint black or white in case we have nothing in our backing store or we
432 // need to show a gutter.
433 SkPaint paint;
434 paint.setStyle(SkPaint::kFill_Style);
435 paint.setColor(guest_crashed_ ? SK_ColorBLACK : SK_ColorWHITE);
436 canvas->drawRect(image_data_rect, paint);
439 // static
440 bool BrowserPlugin::ShouldForwardToBrowserPlugin(
441 const IPC::Message& message) {
442 return IPC_MESSAGE_CLASS(message) == BrowserPluginMsgStart;
445 void BrowserPlugin::updateGeometry(const WebRect& window_rect,
446 const WebRect& clip_rect,
447 const WebRect& unobscured_rect,
448 const WebVector<WebRect>& cut_outs_rects,
449 bool is_visible) {
450 gfx::Rect old_view_rect = view_rect_;
451 view_rect_ = window_rect;
453 if (!ready_) {
454 if (delegate_)
455 delegate_->Ready();
456 ready_ = true;
459 if (delegate_ && (view_rect_.size() != old_view_rect.size()))
460 delegate_->DidResizeElement(view_rect_.size());
462 if (!attached())
463 return;
465 if (old_view_rect.size() == view_rect_.size()) {
466 // Let the browser know about the updated view rect.
467 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_UpdateGeometry(
468 browser_plugin_instance_id_, view_rect_));
469 return;
473 void BrowserPlugin::updateFocus(bool focused, blink::WebFocusType focus_type) {
474 plugin_focused_ = focused;
475 UpdateGuestFocusState(focus_type);
478 void BrowserPlugin::updateVisibility(bool visible) {
479 if (visible_ == visible)
480 return;
482 visible_ = visible;
483 if (!attached())
484 return;
486 if (compositing_helper_.get())
487 compositing_helper_->UpdateVisibility(visible);
489 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_SetVisibility(
490 browser_plugin_instance_id_,
491 visible));
494 bool BrowserPlugin::acceptsInputEvents() {
495 return true;
498 bool BrowserPlugin::handleInputEvent(const blink::WebInputEvent& event,
499 blink::WebCursorInfo& cursor_info) {
500 if (guest_crashed_ || !attached())
501 return false;
503 if (event.type == blink::WebInputEvent::ContextMenu)
504 return true;
506 if (blink::WebInputEvent::isKeyboardEventType(event.type) &&
507 !edit_commands_.empty()) {
508 BrowserPluginManager::Get()->Send(
509 new BrowserPluginHostMsg_SetEditCommandsForNextKeyEvent(
510 browser_plugin_instance_id_,
511 edit_commands_));
512 edit_commands_.clear();
515 BrowserPluginManager::Get()->Send(
516 new BrowserPluginHostMsg_HandleInputEvent(browser_plugin_instance_id_,
517 view_rect_,
518 &event));
519 GetWebKitCursorInfo(cursor_, &cursor_info);
520 return true;
523 bool BrowserPlugin::handleDragStatusUpdate(blink::WebDragStatus drag_status,
524 const blink::WebDragData& drag_data,
525 blink::WebDragOperationsMask mask,
526 const blink::WebPoint& position,
527 const blink::WebPoint& screen) {
528 if (guest_crashed_ || !attached())
529 return false;
530 BrowserPluginManager::Get()->Send(
531 new BrowserPluginHostMsg_DragStatusUpdate(
532 browser_plugin_instance_id_,
533 drag_status,
534 DropDataBuilder::Build(drag_data),
535 mask,
536 position));
537 return true;
540 void BrowserPlugin::didReceiveResponse(
541 const blink::WebURLResponse& response) {
544 void BrowserPlugin::didReceiveData(const char* data, int data_length) {
545 if (delegate_)
546 delegate_->DidReceiveData(data, data_length);
549 void BrowserPlugin::didFinishLoading() {
550 if (delegate_)
551 delegate_->DidFinishLoading();
554 void BrowserPlugin::didFailLoading(const blink::WebURLError& error) {
557 void BrowserPlugin::didFinishLoadingFrameRequest(const blink::WebURL& url,
558 void* notify_data) {
561 void BrowserPlugin::didFailLoadingFrameRequest(
562 const blink::WebURL& url,
563 void* notify_data,
564 const blink::WebURLError& error) {
567 bool BrowserPlugin::executeEditCommand(const blink::WebString& name) {
568 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_ExecuteEditCommand(
569 browser_plugin_instance_id_,
570 name.utf8()));
572 // BrowserPlugin swallows edit commands.
573 return true;
576 bool BrowserPlugin::executeEditCommand(const blink::WebString& name,
577 const blink::WebString& value) {
578 edit_commands_.push_back(EditCommand(name.utf8(), value.utf8()));
579 // BrowserPlugin swallows edit commands.
580 return true;
583 bool BrowserPlugin::setComposition(
584 const blink::WebString& text,
585 const blink::WebVector<blink::WebCompositionUnderline>& underlines,
586 int selectionStart,
587 int selectionEnd) {
588 if (!attached())
589 return false;
590 std::vector<blink::WebCompositionUnderline> std_underlines;
591 for (size_t i = 0; i < underlines.size(); ++i) {
592 std_underlines.push_back(underlines[i]);
594 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_ImeSetComposition(
595 browser_plugin_instance_id_,
596 text.utf8(),
597 std_underlines,
598 selectionStart,
599 selectionEnd));
600 // TODO(kochi): This assumes the IPC handling always succeeds.
601 return true;
604 bool BrowserPlugin::confirmComposition(
605 const blink::WebString& text,
606 blink::WebWidget::ConfirmCompositionBehavior selectionBehavior) {
607 if (!attached())
608 return false;
609 bool keep_selection = (selectionBehavior == blink::WebWidget::KeepSelection);
610 BrowserPluginManager::Get()->Send(
611 new BrowserPluginHostMsg_ImeConfirmComposition(
612 browser_plugin_instance_id_,
613 text.utf8(),
614 keep_selection));
615 // TODO(kochi): This assumes the IPC handling always succeeds.
616 return true;
619 void BrowserPlugin::extendSelectionAndDelete(int before, int after) {
620 if (!attached())
621 return;
622 BrowserPluginManager::Get()->Send(
623 new BrowserPluginHostMsg_ExtendSelectionAndDelete(
624 browser_plugin_instance_id_,
625 before,
626 after));
629 void BrowserPlugin::OnLockMouseACK(bool succeeded) {
630 mouse_locked_ = succeeded;
631 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_LockMouse_ACK(
632 browser_plugin_instance_id_,
633 succeeded));
636 void BrowserPlugin::OnMouseLockLost() {
637 mouse_locked_ = false;
638 BrowserPluginManager::Get()->Send(new BrowserPluginHostMsg_UnlockMouse_ACK(
639 browser_plugin_instance_id_));
642 bool BrowserPlugin::HandleMouseLockedInputEvent(
643 const blink::WebMouseEvent& event) {
644 BrowserPluginManager::Get()->Send(
645 new BrowserPluginHostMsg_HandleInputEvent(browser_plugin_instance_id_,
646 view_rect_,
647 &event));
648 return true;
651 } // namespace content