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 // A BrowserPluginGuest is the browser side of a browser <--> embedder
6 // renderer channel. A BrowserPlugin (a WebPlugin) is on the embedder
7 // renderer side of browser <--> embedder renderer communication.
9 // BrowserPluginGuest lives on the UI thread of the browser process. Any
10 // messages about the guest render process that the embedder might be interested
11 // in receiving should be listened for here.
13 // BrowserPluginGuest is a WebContentsDelegate and WebContentsObserver for the
14 // guest WebContents. BrowserPluginGuest operates under the assumption that the
15 // guest will be accessible through only one RenderViewHost for the lifetime of
16 // the guest WebContents. Thus, cross-process navigation is not supported.
18 #ifndef CONTENT_BROWSER_BROWSER_PLUGIN_BROWSER_PLUGIN_GUEST_H_
19 #define CONTENT_BROWSER_BROWSER_PLUGIN_BROWSER_PLUGIN_GUEST_H_
24 #include "base/compiler_specific.h"
25 #include "base/id_map.h"
26 #include "base/memory/shared_memory.h"
27 #include "base/memory/weak_ptr.h"
28 #include "base/values.h"
29 #include "content/common/edit_command.h"
30 #include "content/port/common/input_event_ack_state.h"
31 #include "content/public/browser/browser_plugin_guest_delegate.h"
32 #include "content/public/browser/javascript_dialog_manager.h"
33 #include "content/public/browser/web_contents_delegate.h"
34 #include "content/public/browser/web_contents_observer.h"
35 #include "content/public/common/browser_plugin_permission_type.h"
36 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
37 #include "third_party/WebKit/public/web/WebDragOperation.h"
38 #include "third_party/WebKit/public/web/WebDragStatus.h"
39 #include "third_party/WebKit/public/web/WebInputEvent.h"
40 #include "ui/base/ime/text_input_mode.h"
41 #include "ui/base/ime/text_input_type.h"
42 #include "ui/gfx/rect.h"
43 #include "ui/surface/transport_dib.h"
45 struct BrowserPluginHostMsg_AutoSize_Params;
46 struct BrowserPluginHostMsg_Attach_Params;
47 struct BrowserPluginHostMsg_ResizeGuest_Params;
48 struct FrameHostMsg_BuffersSwappedACK_Params;
49 struct FrameHostMsg_CompositorFrameSwappedACK_Params;
50 struct FrameHostMsg_ReclaimCompositorResources_Params;
51 struct ViewHostMsg_CreateWindow_Params;
52 #if defined(OS_MACOSX)
53 struct ViewHostMsg_ShowPopup_Params;
55 struct ViewHostMsg_UpdateRect_Params;
59 class CompositorFrameAck;
72 class BrowserPluginHostFactory;
73 class BrowserPluginEmbedder;
74 class BrowserPluginGuestManager;
75 class RenderProcessHost;
76 class RenderWidgetHostView;
79 struct MediaStreamRequest;
81 // A browser plugin guest provides functionality for WebContents to operate in
82 // the guest role and implements guest-specific overrides for ViewHostMsg_*
85 // When a guest is initially created, it is in an unattached state. That is,
86 // it is not visible anywhere and has no embedder WebContents assigned.
87 // A BrowserPluginGuest is said to be "attached" if it has an embedder.
88 // A BrowserPluginGuest can also create a new unattached guest via
89 // CreateNewWindow. The newly created guest will live in the same partition,
90 // which means it can share storage and can script this guest.
91 class CONTENT_EXPORT BrowserPluginGuest
92 : public JavaScriptDialogManager,
93 public WebContentsDelegate,
94 public WebContentsObserver,
95 public base::SupportsWeakPtr<BrowserPluginGuest> {
97 typedef base::Callback<void(bool)> GeolocationCallback;
98 virtual ~BrowserPluginGuest();
100 // The WebContents passed into the factory method here has not been
101 // initialized yet and so it does not yet hold a SiteInstance.
102 // BrowserPluginGuest must be constructed and installed into a WebContents
103 // prior to its initialization because WebContents needs to determine what
104 // type of WebContentsView to construct on initialization. The content
105 // embedder needs to be aware of |guest_site_instance| on the guest's
106 // construction and so we pass it in here.
107 static BrowserPluginGuest* Create(
109 SiteInstance* guest_site_instance,
110 WebContentsImpl* web_contents,
111 scoped_ptr<base::DictionaryValue> extra_params);
113 static BrowserPluginGuest* CreateWithOpener(
115 bool has_render_view,
116 WebContentsImpl* web_contents,
117 BrowserPluginGuest* opener);
119 // Called when the embedder WebContents is destroyed to give the
120 // BrowserPluginGuest an opportunity to clean up after itself.
121 void EmbedderDestroyed();
123 // Called when the embedder WebContents changes visibility.
124 void EmbedderVisibilityChanged(bool visible);
126 // Destroys the guest WebContents and all its associated state, including
127 // this BrowserPluginGuest, and its new unattached windows.
130 // Returns the identifier that uniquely identifies a browser plugin guest
131 // within an embedder.
132 int instance_id() const { return instance_id_; }
134 bool OnMessageReceivedFromEmbedder(const IPC::Message& message);
136 void Initialize(const BrowserPluginHostMsg_Attach_Params& params,
137 WebContentsImpl* embedder_web_contents);
139 WebContentsImpl* embedder_web_contents() const {
140 return embedder_web_contents_;
143 // Returns the embedder's RenderWidgetHostView if it is available.
144 // Returns NULL otherwise.
145 RenderWidgetHostView* GetEmbedderRenderWidgetHostView();
147 bool focused() const { return focused_; }
148 bool visible() const { return guest_visible_; }
149 void clear_damage_buffer() { damage_buffer_.reset(); }
150 bool is_in_destruction() { return is_in_destruction_; }
152 BrowserPluginGuest* opener() const { return opener_.get(); }
154 // Returns whether the mouse pointer was unlocked.
155 bool UnlockMouseIfNecessary(const NativeWebKeyboardEvent& event);
157 void UpdateVisibility();
159 void CopyFromCompositingSurface(
160 gfx::Rect src_subrect,
162 const base::Callback<void(bool, const SkBitmap&)>& callback);
164 // WebContentsObserver implementation.
165 virtual void DidCommitProvisionalLoadForFrame(
167 const base::string16& frame_unique_name,
170 PageTransition transition_type,
171 RenderViewHost* render_view_host) OVERRIDE;
172 virtual void DidStopLoading(RenderViewHost* render_view_host) OVERRIDE;
174 virtual void RenderViewReady() OVERRIDE;
175 virtual void RenderProcessGone(base::TerminationStatus status) OVERRIDE;
176 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
178 // WebContentsDelegate implementation.
179 virtual bool AddMessageToConsole(WebContents* source,
181 const base::string16& message,
183 const base::string16& source_id) OVERRIDE;
184 // If a new window is created with target="_blank" and rel="noreferrer", then
185 // this method is called, indicating that the new WebContents is ready to be
187 virtual void AddNewContents(WebContents* source,
188 WebContents* new_contents,
189 WindowOpenDisposition disposition,
190 const gfx::Rect& initial_pos,
192 bool* was_blocked) OVERRIDE;
193 virtual void CanDownload(RenderViewHost* render_view_host,
195 const std::string& request_method,
196 const base::Callback<void(bool)>& callback) OVERRIDE;
197 virtual void LoadProgressChanged(WebContents* source,
198 double progress) OVERRIDE;
199 virtual void CloseContents(WebContents* source) OVERRIDE;
200 virtual JavaScriptDialogManager* GetJavaScriptDialogManager() OVERRIDE;
201 virtual bool HandleContextMenu(const ContextMenuParams& params) OVERRIDE;
202 virtual void HandleKeyboardEvent(
204 const NativeWebKeyboardEvent& event) OVERRIDE;
205 virtual WebContents* OpenURLFromTab(WebContents* source,
206 const OpenURLParams& params) OVERRIDE;
207 virtual void WebContentsCreated(WebContents* source_contents,
208 int64 source_frame_id,
209 const base::string16& frame_name,
210 const GURL& target_url,
211 WebContents* new_contents) OVERRIDE;
212 virtual void RendererUnresponsive(WebContents* source) OVERRIDE;
213 virtual void RendererResponsive(WebContents* source) OVERRIDE;
214 virtual void RunFileChooser(WebContents* web_contents,
215 const FileChooserParams& params) OVERRIDE;
216 virtual bool ShouldFocusPageAfterCrash() OVERRIDE;
217 virtual void RequestMediaAccessPermission(
218 WebContents* web_contents,
219 const MediaStreamRequest& request,
220 const MediaResponseCallback& callback) OVERRIDE;
222 // JavaScriptDialogManager implementation.
223 virtual void RunJavaScriptDialog(
224 WebContents* web_contents,
225 const GURL& origin_url,
226 const std::string& accept_lang,
227 JavaScriptMessageType javascript_message_type,
228 const base::string16& message_text,
229 const base::string16& default_prompt_text,
230 const DialogClosedCallback& callback,
231 bool* did_suppress_message) OVERRIDE;
232 virtual void RunBeforeUnloadDialog(
233 WebContents* web_contents,
234 const base::string16& message_text,
236 const DialogClosedCallback& callback) OVERRIDE;
237 virtual bool HandleJavaScriptDialog(
238 WebContents* web_contents,
240 const base::string16* prompt_override) OVERRIDE;
241 virtual void CancelActiveAndPendingDialogs(
242 WebContents* web_contents) OVERRIDE;
243 virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE;
245 // Exposes the protected web_contents() from WebContentsObserver.
246 WebContentsImpl* GetWebContents();
248 // Overridden in tests.
249 virtual void SetDamageBuffer(
250 const BrowserPluginHostMsg_ResizeGuest_Params& params);
252 gfx::Point GetScreenCoordinates(const gfx::Point& relative_position) const;
254 // Helper to send messages to embedder. This methods fills the message with
255 // the correct routing id.
256 // Overridden in test implementation since we want to intercept certain
257 // messages for testing.
258 virtual void SendMessageToEmbedder(IPC::Message* msg);
260 // Returns whether the guest is attached to an embedder.
261 bool attached() const { return embedder_web_contents_ != NULL; }
263 // Attaches this BrowserPluginGuest to the provided |embedder_web_contents|
264 // and initializes the guest with the provided |params|. Attaching a guest
265 // to an embedder implies that this guest's lifetime is no longer managed
266 // by its opener, and it can begin loading resources. |extra_params| are
267 // parameters passed into BrowserPlugin from JavaScript to be forwarded to
268 // the content embedder.
269 void Attach(WebContentsImpl* embedder_web_contents,
270 BrowserPluginHostMsg_Attach_Params params,
271 const base::DictionaryValue& extra_params);
273 // Requests geolocation permission through Embedder JavaScript API.
274 void AskEmbedderForGeolocationPermission(int bridge_id,
275 const GURL& requesting_frame,
276 const GeolocationCallback& callback);
277 // Cancels pending geolocation request.
278 void CancelGeolocationRequest(int bridge_id);
280 // Allow the embedder to call this for unhandled messages when
281 // BrowserPluginGuest is already destroyed.
282 static void AcknowledgeBufferPresent(int route_id,
284 const std::string& mailbox_name,
287 // Returns whether BrowserPluginGuest is interested in receiving the given
289 static bool ShouldForwardToBrowserPluginGuest(const IPC::Message& message);
290 gfx::Rect ToGuestRect(const gfx::Rect& rect);
292 void DragSourceEndedAt(int client_x, int client_y, int screen_x,
293 int screen_y, blink::WebDragOperation operation);
295 void DragSourceMovedTo(int client_x, int client_y,
296 int screen_x, int screen_y);
298 // Called when the drag started by this guest ends at an OS-level.
299 void EndSystemDrag();
301 // |this| takes ownership of |delegate|.
302 void SetDelegate(BrowserPluginGuestDelegate* delegate);
304 void RespondToPermissionRequest(int request_id,
306 const std::string& user_input);
308 // Overrides factory for testing. Default (NULL) value indicates regular
309 // (non-test) environment.
310 static void set_factory_for_testing(BrowserPluginHostFactory* factory) {
311 BrowserPluginGuest::factory_ = factory;
315 class EmbedderWebContentsObserver;
316 friend class TestBrowserPluginGuest;
318 class DownloadRequest;
319 class GeolocationRequest;
320 class JavaScriptDialogRequest;
321 // MediaRequest because of naming conflicts with MediaStreamRequest.
323 class NewWindowRequest;
324 class PermissionRequest;
325 class PointerLockRequest;
327 // Tracks the name, and target URL of the new window and whether or not it has
328 // changed since the WebContents has been created and before the new window
329 // has been attached to a BrowserPlugin. Once the first navigation commits, we
330 // no longer track this information.
331 struct NewWindowInfo {
335 NewWindowInfo(const GURL& url, const std::string& name) :
341 // BrowserPluginGuest is a WebContentsObserver of |web_contents| and
342 // |web_contents| has to stay valid for the lifetime of BrowserPluginGuest.
343 BrowserPluginGuest(int instance_id,
344 bool has_render_view,
345 WebContentsImpl* web_contents,
346 BrowserPluginGuest* opener);
348 // Destroy unattached new windows that have been opened by this
349 // BrowserPluginGuest.
350 void DestroyUnattachedWindows();
352 void LoadURLWithParams(const GURL& url,
353 const Referrer& referrer,
354 PageTransition transition_type,
355 WebContents* web_contents);
357 // Bridge IDs correspond to a geolocation request. This method will remove
358 // the bookkeeping for a particular geolocation request associated with the
359 // provided |bridge_id|. It returns the request ID of the geolocation request.
360 int RemoveBridgeID(int bridge_id);
362 // Returns the |request_id| generated for the |request| provided.
363 int RequestPermission(
364 BrowserPluginPermissionType permission_type,
365 scoped_refptr<BrowserPluginGuest::PermissionRequest> request,
366 const base::DictionaryValue& request_info);
368 // Creates a new guest window, and BrowserPluginGuest that is owned by this
369 // BrowserPluginGuest.
370 BrowserPluginGuest* CreateNewGuestWindow(const OpenURLParams& params);
372 base::SharedMemory* damage_buffer() const { return damage_buffer_.get(); }
373 const gfx::Size& damage_view_size() const { return damage_view_size_; }
374 float damage_buffer_scale_factor() const {
375 return damage_buffer_scale_factor_;
377 // Returns the damage buffer corresponding to the handle in resize |params|.
378 base::SharedMemory* GetDamageBufferFromEmbedder(
379 const BrowserPluginHostMsg_ResizeGuest_Params& params);
381 bool InAutoSizeBounds(const gfx::Size& size) const;
383 void RequestNewWindowPermission(WindowOpenDisposition disposition,
384 const gfx::Rect& initial_bounds,
386 WebContentsImpl* new_contents);
388 // Message handlers for messages from embedder.
390 void OnCompositorFrameSwappedACK(
392 const FrameHostMsg_CompositorFrameSwappedACK_Params& params);
393 void OnCopyFromCompositingSurfaceAck(int instance_id,
395 const SkBitmap& bitmap);
396 // Handles drag events from the embedder.
397 // When dragging, the drag events go to the embedder first, and if the drag
398 // happens on the browser plugin, then the plugin sends a corresponding
399 // drag-message to the guest. This routes the drag-message to the guest
401 void OnDragStatusUpdate(int instance_id,
402 blink::WebDragStatus drag_status,
403 const DropData& drop_data,
404 blink::WebDragOperationsMask drag_mask,
405 const gfx::Point& location);
406 // Instructs the guest to execute an edit command decoded in the embedder.
407 void OnExecuteEditCommand(int instance_id,
408 const std::string& command);
410 // Returns compositor resources reclaimed in the embedder to the guest.
411 void OnReclaimCompositorResources(
413 const FrameHostMsg_ReclaimCompositorResources_Params& params);
415 // Overriden in tests.
416 virtual void OnHandleInputEvent(int instance_id,
417 const gfx::Rect& guest_window_rect,
418 const blink::WebInputEvent* event);
419 void OnLockMouse(bool user_gesture,
420 bool last_unlocked_by_target,
422 void OnLockMouseAck(int instance_id, bool succeeded);
423 void OnNavigateGuest(int instance_id, const std::string& src);
424 void OnPluginDestroyed(int instance_id);
425 // Grab the new damage buffer from the embedder, and resize the guest's
427 void OnResizeGuest(int instance_id,
428 const BrowserPluginHostMsg_ResizeGuest_Params& params);
429 // Overriden in tests.
430 virtual void OnSetFocus(int instance_id, bool focused);
431 // Sets the name of the guest so that other guests in the same partition can
433 void OnSetName(int instance_id, const std::string& name);
434 // Updates the size state of the guest.
437 const BrowserPluginHostMsg_AutoSize_Params& auto_size_params,
438 const BrowserPluginHostMsg_ResizeGuest_Params& resize_guest_params);
439 void OnSetEditCommandsForNextKeyEvent(
441 const std::vector<EditCommand>& edit_commands);
442 void OnSetContentsOpaque(int instance_id, bool opaque);
443 // The guest WebContents is visible if both its embedder is visible and
444 // the browser plugin element is visible. If either one is not then the
445 // WebContents is marked as hidden. A hidden WebContents will consume
446 // fewer GPU and CPU resources.
448 // When every WebContents in a RenderProcessHost is hidden, it will lower
449 // the priority of the process (see RenderProcessHostImpl::WidgetHidden).
451 // It will also send a message to the guest renderer process to cleanup
452 // resources such as dropping back buffers and adjusting memory limits (if in
453 // compositing mode, see CCLayerTreeHost::setVisible).
455 // Additionally, it will slow down Javascript execution and garbage
456 // collection. See RenderThreadImpl::IdleHandler (executed when hidden) and
457 // RenderThreadImpl::IdleHandlerInForegroundTab (executed when visible).
458 void OnSetVisibility(int instance_id, bool visible);
459 // Message from embedder acknowledging last HW buffer.
460 void OnSwapBuffersACK(int instance_id,
461 const FrameHostMsg_BuffersSwappedACK_Params& params);
462 void OnUnlockMouse();
463 void OnUnlockMouseAck(int instance_id);
464 void OnUpdateGeometry(int instance_id, const gfx::Rect& view_rect);
465 void OnUpdateRectACK(
468 const BrowserPluginHostMsg_AutoSize_Params& auto_size_params,
469 const BrowserPluginHostMsg_ResizeGuest_Params& resize_guest_params);
471 void OnTextInputTypeChanged(ui::TextInputType type,
472 ui::TextInputMode input_mode,
473 bool can_compose_inline);
474 void OnImeSetComposition(
476 const std::string& text,
477 const std::vector<blink::WebCompositionUnderline>& underlines,
480 void OnImeConfirmComposition(
482 const std::string& text,
483 bool keep_selection);
484 void OnExtendSelectionAndDelete(int instance_id, int before, int after);
485 // Overridden in tests.
486 virtual void OnImeCancelComposition();
487 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
488 void OnImeCompositionRangeChanged(
489 const gfx::Range& range,
490 const std::vector<gfx::Rect>& character_bounds);
493 // Message handlers for messages from guest.
495 void OnDragStopped();
496 void OnHandleInputEventAck(
497 blink::WebInputEvent::Type event_type,
498 InputEventAckState ack_result);
499 void OnHasTouchEventHandlers(bool accept);
500 void OnSetCursor(const WebCursor& cursor);
501 // On MacOSX popups are painted by the browser process. We handle them here
502 // so that they are positioned correctly.
503 #if defined(OS_MACOSX)
504 void OnShowPopup(const ViewHostMsg_ShowPopup_Params& params);
506 void OnShowWidget(int route_id, const gfx::Rect& initial_pos);
507 // Overriden in tests.
508 virtual void OnTakeFocus(bool reverse);
509 void OnUpdateFrameName(int frame_id,
511 const std::string& name);
512 void OnUpdateRect(const ViewHostMsg_UpdateRect_Params& params);
514 // Requests download permission through embedder JavaScript API after
515 // retrieving url information from IO thread.
516 void DidRetrieveDownloadURLFromRequestId(
517 const std::string& request_method,
518 const base::Callback<void(bool)>& callback,
519 const std::string& url);
521 // Embedder sets permission to allow or deny geolocation request.
522 void SetGeolocationPermission(
523 GeolocationCallback callback, int bridge_id, bool allowed);
525 // Forwards all messages from the |pending_messages_| queue to the embedder.
526 void SendQueuedMessages();
528 // Static factory instance (always NULL for non-test).
529 static BrowserPluginHostFactory* factory_;
531 scoped_ptr<EmbedderWebContentsObserver> embedder_web_contents_observer_;
532 WebContentsImpl* embedder_web_contents_;
534 std::map<int, int> bridge_id_to_request_id_map_;
536 // An identifier that uniquely identifies a browser plugin guest within an
539 scoped_ptr<base::SharedMemory> damage_buffer_;
540 // An identifier that uniquely identifies a damage buffer.
541 uint32 damage_buffer_sequence_id_;
542 size_t damage_buffer_size_;
543 gfx::Size damage_view_size_;
544 float damage_buffer_scale_factor_;
545 float guest_device_scale_factor_;
546 gfx::Rect guest_window_rect_;
547 gfx::Rect guest_screen_rect_;
548 base::TimeDelta guest_hang_timeout_;
551 bool pending_lock_request_;
554 bool embedder_visible_;
556 bool auto_size_enabled_;
557 gfx::Size max_auto_size_;
558 gfx::Size min_auto_size_;
560 // Each copy-request is identified by a unique number. The unique number is
561 // used to keep track of the right callback.
562 int copy_request_id_;
563 typedef base::Callback<void(bool, const SkBitmap&)> CopyRequestCallback;
564 typedef std::map<int, const CopyRequestCallback> CopyRequestMap;
565 CopyRequestMap copy_request_callbacks_;
567 typedef std::map<BrowserPluginGuest*, NewWindowInfo> PendingWindowMap;
568 PendingWindowMap pending_new_windows_;
569 base::WeakPtr<BrowserPluginGuest> opener_;
570 // A counter to generate a unique request id for a permission request.
571 // We only need the ids to be unique for a given BrowserPluginGuest.
572 int next_permission_request_id_;
574 // A map to store relevant info for a request keyed by the request's id.
575 typedef std::map<int, scoped_refptr<PermissionRequest> > RequestMap;
576 RequestMap permission_request_map_;
578 // Indicates that this BrowserPluginGuest has associated renderer-side state.
579 // This is used to determine whether or not to create a new RenderView when
580 // this guest is attached.
581 bool has_render_view_;
583 // Last seen size of guest contents (by OnUpdateRect).
584 gfx::Size last_seen_view_size_;
585 // Last seen autosize attribute state (by OnUpdateRect).
586 bool last_seen_auto_size_enabled_;
588 bool is_in_destruction_;
590 // This is a queue of messages that are destined to be sent to the embedder
591 // once the guest is attached to a particular embedder.
592 std::queue<IPC::Message*> pending_messages_;
594 scoped_ptr<BrowserPluginGuestDelegate> delegate_;
596 // These are parameters passed from JavaScript on attachment to the content
598 scoped_ptr<base::DictionaryValue> extra_attach_params_;
600 // Weak pointer used to ask GeolocationPermissionContext about geolocation
602 base::WeakPtrFactory<BrowserPluginGuest> weak_ptr_factory_;
604 DISALLOW_COPY_AND_ASSIGN(BrowserPluginGuest);
607 } // namespace content
609 #endif // CONTENT_BROWSER_BROWSER_PLUGIN_BROWSER_PLUGIN_GUEST_H_