guest_view_base.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. // Copyright 2014 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.
  4. #ifndef COMPONENTS_GUEST_VIEW_BROWSER_GUEST_VIEW_BASE_H_
  5. #define COMPONENTS_GUEST_VIEW_BROWSER_GUEST_VIEW_BASE_H_
  6. #include <memory>
  7. #include "base/containers/circular_deque.h"
  8. #include "base/memory/raw_ptr.h"
  9. #include "base/memory/weak_ptr.h"
  10. #include "base/values.h"
  11. #include "components/guest_view/browser/guest_view_message_handler.h"
  12. #include "components/guest_view/common/guest_view_constants.h"
  13. #include "components/zoom/zoom_observer.h"
  14. #include "content/public/browser/browser_plugin_guest_delegate.h"
  15. #include "content/public/browser/guest_host.h"
  16. #include "content/public/browser/web_contents.h"
  17. #include "content/public/browser/web_contents_delegate.h"
  18. #include "content/public/browser/web_contents_observer.h"
  19. namespace content {
  20. class RenderFrameHost;
  21. }
  22. namespace guest_view {
  23. class GuestViewEvent;
  24. class GuestViewManager;
  25. // A struct of parameters for SetSize(). The parameters are all declared as
  26. // scoped pointers since they are all optional. Null pointers indicate that the
  27. // parameter has not been provided, and the last used value should be used. Note
  28. // that when |enable_auto_size| is true, providing |normal_size| is not
  29. // meaningful. This is because the normal size of the guestview is overridden
  30. // whenever autosizing occurs.
  31. struct SetSizeParams {
  32. SetSizeParams();
  33. ~SetSizeParams();
  34. std::unique_ptr<bool> enable_auto_size;
  35. std::unique_ptr<gfx::Size> min_size;
  36. std::unique_ptr<gfx::Size> max_size;
  37. std::unique_ptr<gfx::Size> normal_size;
  38. };
  39. // A GuestViewBase is the base class browser-side API implementation for a
  40. // <*view> tag. GuestViewBase maintains an association between a guest
  41. // WebContents and an owner WebContents. It receives events issued from
  42. // the guest and relays them to the owner. GuestViewBase tracks the lifetime
  43. // of its owner. A GuestViewBase's owner is referred to as an embedder if
  44. // it is attached to a container within the owner's WebContents.
  45. class GuestViewBase : public content::BrowserPluginGuestDelegate,
  46. public content::WebContentsDelegate,
  47. public content::WebContentsObserver,
  48. public zoom::ZoomObserver {
  49. public:
  50. static GuestViewBase* FromWebContents(
  51. const content::WebContents* web_contents);
  52. static GuestViewBase* From(int owner_process_id, int instance_id);
  53. GuestViewBase(const GuestViewBase&) = delete;
  54. GuestViewBase& operator=(const GuestViewBase&) = delete;
  55. // Given a |web_contents|, returns the top level owner WebContents. If
  56. // |web_contents| does not belong to a GuestView, it will be returned
  57. // unchanged.
  58. static content::WebContents* GetTopLevelWebContents(
  59. content::WebContents* web_contents);
  60. static bool IsGuest(content::WebContents* web_contents);
  61. // Returns the name of the derived type of this GuestView.
  62. virtual const char* GetViewType() const = 0;
  63. // This method queries whether autosize is supported for this particular view.
  64. // By default, autosize is not supported. Derived classes can override this
  65. // behavior to support autosize.
  66. virtual bool IsAutoSizeSupported() const;
  67. // This method queries whether preferred size events are enabled for this
  68. // view. By default, preferred size events are disabled, since they add a
  69. // small amount of overhead.
  70. virtual bool IsPreferredSizeModeEnabled() const;
  71. // This indicates whether zoom should propagate from the embedder to the guest
  72. // content.
  73. virtual bool ZoomPropagatesFromEmbedderToGuest() const;
  74. // Access to guest views are determined by the availability of the internal
  75. // extension API used to implement the guest view.
  76. //
  77. // This should be the name of the API as it appears in the _api_features.json
  78. // file.
  79. virtual const char* GetAPINamespace() const = 0;
  80. // This method is the task prefix to show for a task produced by this
  81. // GuestViewBase's derived type.
  82. virtual int GetTaskPrefix() const = 0;
  83. // Dispatches an event to the guest proxy.
  84. void DispatchEventToGuestProxy(std::unique_ptr<GuestViewEvent> event);
  85. // Dispatches an event to the view.
  86. void DispatchEventToView(std::unique_ptr<GuestViewEvent> event);
  87. // This creates a WebContents and initializes |this| GuestViewBase to use the
  88. // newly created WebContents.
  89. using WebContentsCreatedCallback =
  90. base::OnceCallback<void(content::WebContents*)>;
  91. void Init(const base::Value::Dict& create_params,
  92. WebContentsCreatedCallback callback);
  93. void InitWithWebContents(const base::Value::Dict& create_params,
  94. content::WebContents* guest_web_contents);
  95. // Used to toggle autosize mode for this GuestView, and set both the automatic
  96. // and normal sizes.
  97. void SetSize(const SetSizeParams& params);
  98. bool initialized() const { return initialized_; }
  99. content::WebContents* embedder_web_contents() const {
  100. return attached() ? owner_web_contents_.get() : nullptr;
  101. }
  102. content::WebContents* owner_web_contents() const {
  103. return owner_web_contents_;
  104. }
  105. // Returns the parameters associated with the element hosting this GuestView
  106. // passed in from JavaScript.
  107. const base::Value::Dict& attach_params() const { return attach_params_; }
  108. // Returns whether this guest has an associated embedder.
  109. bool attached() const {
  110. return !(element_instance_id_ == kInstanceIDNone || attach_in_progress_ ||
  111. is_being_destroyed_);
  112. }
  113. // Returns the instance ID of the <*view> element.
  114. int view_instance_id() const { return view_instance_id_; }
  115. // Returns the instance ID of this GuestViewBase.
  116. int guest_instance_id() const { return guest_instance_id_; }
  117. // Returns the instance ID of the GuestViewBase's element (unique within an
  118. // embedder process). Note: this value is set once after attach is complete.
  119. // It will maintain its value during the lifetime of GuestViewBase, even after
  120. // |attach()| is false due to |is_being_destroyed_|.
  121. int element_instance_id() const { return element_instance_id_; }
  122. bool can_owner_receive_events() const { return !!view_instance_id_; }
  123. gfx::Size size() const { return guest_size_; }
  124. // Returns the user browser context of the embedder.
  125. content::BrowserContext* browser_context() const { return browser_context_; }
  126. // Returns the URL of the owner WebContents' SiteInstance.
  127. // WARNING: Be careful using this with GuestViews where
  128. // `CanBeEmbeddedInsideCrossProcessFrames` is true. This returns the site of
  129. // the WebContents, not the embedding frame.
  130. const GURL& GetOwnerSiteURL() const;
  131. // Returns the host of the owner WebContents. For extensions, this is the
  132. // extension ID.
  133. std::string owner_host() const { return owner_host_; }
  134. // Whether the guest view is inside a plugin document.
  135. bool is_full_page_plugin() const { return is_full_page_plugin_; }
  136. // Destroy this guest.
  137. void Destroy(bool also_delete);
  138. // Saves the attach state of the custom element hosting this GuestView.
  139. void SetAttachParams(const base::Value::Dict& params);
  140. // Returns the RenderWidgetHost corresponding to the owner frame.
  141. virtual content::RenderWidgetHost* GetOwnerRenderWidgetHost();
  142. // The SiteInstance of the owner frame.
  143. virtual content::SiteInstance* GetOwnerSiteInstance();
  144. // Starts the attaching process for a (frame-based) GuestView.
  145. // |embedder_frame| is a frame in the embedder WebContents (owned by a
  146. // HTMLFrameOwnerElement associated with the GuestView's element in the
  147. // embedder process) which will be used for attaching.
  148. void AttachToOuterWebContentsFrame(
  149. content::RenderFrameHost* embedder_frame,
  150. int32_t element_instance_id,
  151. bool is_full_page_plugin,
  152. GuestViewMessageHandler::AttachToEmbedderFrameCallback
  153. attachment_callback);
  154. // Returns true if the corresponding guest is allowed to be embedded inside an
  155. // <iframe> which is cross process.
  156. virtual bool CanBeEmbeddedInsideCrossProcessFrames() const;
  157. content::RenderFrameHost* GetGuestMainFrame() const;
  158. protected:
  159. explicit GuestViewBase(content::WebContents* owner_web_contents);
  160. ~GuestViewBase() override;
  161. GuestViewBase* GetOpener() const { return opener_.get(); }
  162. void SetOpener(GuestViewBase* opener);
  163. // TODO(ekaramad): If a guest is based on BrowserPlugin and is embedded inside
  164. // a cross-process frame, we need to notify the destruction of the frame so
  165. // that the clean-up on the browser side is done appropriately. Remove this
  166. // method when BrowserPlugin is removed (https://crbug.com/535197).
  167. virtual void OnRenderFrameHostDeleted(int process_id, int routing_id);
  168. // WebContentsDelegate implementation.
  169. bool HandleKeyboardEvent(
  170. content::WebContents* source,
  171. const content::NativeWebKeyboardEvent& event) override;
  172. bool PreHandleGestureEvent(content::WebContents* source,
  173. const blink::WebGestureEvent& event) override;
  174. content::WebContents* GetResponsibleWebContents(
  175. content::WebContents* web_contents) override;
  176. // WebContentsObserver implementation.
  177. void DidFinishNavigation(
  178. content::NavigationHandle* navigation_handle) override;
  179. // Given a set of initialization parameters, a concrete subclass of
  180. // GuestViewBase can create a specialized WebContents that it returns back to
  181. // GuestViewBase.
  182. virtual void CreateWebContents(const base::Value::Dict& create_params,
  183. WebContentsCreatedCallback callback) = 0;
  184. // This method is called after the guest has been attached to an embedder and
  185. // suspended resource loads have been resumed.
  186. //
  187. // This method can be overriden by subclasses. This gives the derived class
  188. // an opportunity to perform setup actions after attachment.
  189. virtual void DidAttachToEmbedder() {}
  190. // This method is called after this GuestViewBase has been initiated.
  191. //
  192. // This gives the derived class an opportunity to perform additional
  193. // initialization.
  194. virtual void DidInitialize(const base::Value::Dict& create_params) {}
  195. // This method is called when embedder WebContents's fullscreen is toggled.
  196. //
  197. // If the guest asked the embedder to enter fullscreen, the guest uses this
  198. // signal to exit fullscreen state.
  199. virtual void EmbedderFullscreenToggled(bool entered_fullscreen) {}
  200. // This method is called when the initial set of frames within the page have
  201. // completed loading.
  202. virtual void GuestViewDidStopLoading() {}
  203. // This method is called when the guest WebContents has been destroyed. This
  204. // object will be destroyed after this call returns.
  205. //
  206. // This gives the derived class an opportunity to perform some cleanup.
  207. virtual void GuestDestroyed() {}
  208. // This method is invoked when the guest RenderView is ready, e.g. because we
  209. // recreated it after a crash or after reattachment.
  210. //
  211. // This gives the derived class an opportunity to perform some initialization
  212. // work.
  213. virtual void GuestReady() {}
  214. // This method is called when the guest's zoom changes.
  215. virtual void GuestZoomChanged(double old_zoom_level, double new_zoom_level) {}
  216. // This method is invoked when the contents auto-resized to give the container
  217. // an opportunity to match it if it wishes.
  218. //
  219. // This gives the derived class an opportunity to inform its container element
  220. // or perform other actions.
  221. virtual void GuestSizeChangedDueToAutoSize(const gfx::Size& old_size,
  222. const gfx::Size& new_size) {}
  223. // This method is invoked when the contents preferred size changes. This will
  224. // only ever fire if IsPreferredSizeSupported returns true.
  225. virtual void OnPreferredSizeChanged(const gfx::Size& pref_size) {}
  226. // Signals that the guest view is ready. The default implementation signals
  227. // immediately, but derived class can override this if they need to do
  228. // asynchronous setup.
  229. virtual void SignalWhenReady(base::OnceClosure callback);
  230. // This method is called immediately before suspended resource loads have been
  231. // resumed on attachment to an embedder.
  232. //
  233. // This method can be overriden by subclasses. This gives the derived class
  234. // an opportunity to perform setup actions before attachment.
  235. virtual void WillAttachToEmbedder() {}
  236. // This method is called when the guest WebContents is about to be destroyed.
  237. //
  238. // This gives the derived class an opportunity to perform some cleanup prior
  239. // to destruction.
  240. virtual void WillDestroy() {}
  241. // Convert sizes in pixels from logical to physical numbers of pixels.
  242. // Note that a size can consist of a fractional number of logical pixels
  243. // (hence |logical_pixels| is represented as a double), but will always
  244. // consist of an integral number of physical pixels (hence the return value
  245. // is represented as an int).
  246. int LogicalPixelsToPhysicalPixels(double logical_pixels) const;
  247. // Convert sizes in pixels from physical to logical numbers of pixels.
  248. // Note that a size can consist of a fractional number of logical pixels
  249. // (hence the return value is represented as a double), but will always
  250. // consist of an integral number of physical pixels (hence |physical_pixels|
  251. // is represented as an int).
  252. double PhysicalPixelsToLogicalPixels(int physical_pixels) const;
  253. void SetGuestZoomLevelToMatchEmbedder();
  254. private:
  255. class OwnerContentsObserver;
  256. class OpenerLifetimeObserver;
  257. // TODO(533069): Remove since BrowserPlugin has been removed.
  258. void DidAttach();
  259. void WillAttach(content::WebContents* embedder_web_contents,
  260. int browser_plugin_instance_id,
  261. bool is_full_page_plugin,
  262. base::OnceClosure completion_callback);
  263. // BrowserPluginGuestDelegate implementation.
  264. content::WebContents* CreateNewGuestWindow(
  265. const content::WebContents::CreateParams& create_params) final;
  266. content::WebContents* GetOwnerWebContents() final;
  267. void SetGuestHost(content::GuestHost* guest_host) final;
  268. // WebContentsDelegate implementation.
  269. void ActivateContents(content::WebContents* contents) final;
  270. void ContentsMouseEvent(content::WebContents* source,
  271. bool motion,
  272. bool exited) final;
  273. void ContentsZoomChange(bool zoom_in) final;
  274. void LoadingStateChanged(content::WebContents* source,
  275. bool should_show_loading_ui) final;
  276. void ResizeDueToAutoResize(content::WebContents* web_contents,
  277. const gfx::Size& new_size) final;
  278. void RunFileChooser(content::RenderFrameHost* render_frame_host,
  279. scoped_refptr<content::FileSelectListener> listener,
  280. const blink::mojom::FileChooserParams& params) final;
  281. bool ShouldFocusPageAfterCrash() final;
  282. void UpdatePreferredSize(content::WebContents* web_contents,
  283. const gfx::Size& pref_size) final;
  284. void UpdateTargetURL(content::WebContents* source, const GURL& url) final;
  285. bool ShouldResumeRequestsForCreatedWindow() final;
  286. // WebContentsObserver implementation.
  287. void DidStopLoading() final;
  288. void RenderViewReady() final;
  289. void WebContentsDestroyed() final;
  290. // ui_zoom::ZoomObserver implementation.
  291. void OnZoomChanged(
  292. const zoom::ZoomController::ZoomChangedEventData& data) final;
  293. void SendQueuedEvents();
  294. void CompleteInit(base::Value::Dict create_params,
  295. WebContentsCreatedCallback callback,
  296. content::WebContents* guest_web_contents);
  297. // Dispatches the onResize event to the embedder.
  298. void DispatchOnResizeEvent(const gfx::Size& old_size,
  299. const gfx::Size& new_size);
  300. // Returns the default size of the guestview.
  301. gfx::Size GetDefaultSize() const;
  302. // Get the zoom factor for the embedder's web contents.
  303. double GetEmbedderZoomFactor() const;
  304. void SetUpSizing(const base::Value::Dict& params);
  305. void StartTrackingEmbedderZoomLevel();
  306. void StopTrackingEmbedderZoomLevel();
  307. void UpdateGuestSize(const gfx::Size& new_size, bool due_to_auto_resize);
  308. GuestViewManager* GetGuestViewManager();
  309. void SetOwnerHost();
  310. // TODO(ekaramad): Revisit this once MimeHandlerViewGuest is frame-based
  311. // (https://crbug.com/659750); either remove or unify with
  312. // BrowserPluginGuestDelegate::WillAttach.
  313. void WillAttach(content::WebContents* embedder_web_contents,
  314. content::RenderFrameHost* outer_contents_frame,
  315. int browser_plugin_instance_id,
  316. bool is_full_page_plugin,
  317. base::OnceClosure completion_callback,
  318. GuestViewMessageHandler::AttachToEmbedderFrameCallback
  319. attachment_callback);
  320. // This guest tracks the lifetime of the WebContents specified by
  321. // |owner_web_contents_|. If |owner_web_contents_| is destroyed then this
  322. // guest will also self-destruct.
  323. raw_ptr<content::WebContents> owner_web_contents_;
  324. std::string owner_host_;
  325. const raw_ptr<content::BrowserContext> browser_context_;
  326. // |guest_instance_id_| is a profile-wide unique identifier for a guest
  327. // WebContents.
  328. const int guest_instance_id_;
  329. // |view_instance_id_| is an identifier that's unique within a particular
  330. // embedder RenderViewHost for a particular <*view> instance.
  331. int view_instance_id_;
  332. // |element_instance_id_| is an identifer that's unique to a particular
  333. // GuestViewContainer element.
  334. int element_instance_id_;
  335. // |attach_in_progress_| is used to make sure that attached() doesn't return
  336. // true until after DidAttach() is called, since that's when we are guaranteed
  337. // that the contentWindow for cross-process-iframe based guests will become
  338. // valid.
  339. bool attach_in_progress_;
  340. // |initialized_| indicates whether GuestViewBase::Init has been called for
  341. // this object.
  342. bool initialized_;
  343. // Indicates that this guest is in the process of being destroyed.
  344. bool is_being_destroyed_;
  345. // This is a queue of Events that are destined to be sent to the embedder once
  346. // the guest is attached to a particular embedder.
  347. base::circular_deque<std::unique_ptr<GuestViewEvent>> pending_events_;
  348. // The opener guest view.
  349. base::WeakPtr<GuestViewBase> opener_;
  350. // The parameters associated with the element hosting this GuestView that
  351. // are passed in from JavaScript. This will typically be the view instance ID,
  352. // and element-specific parameters. These parameters are passed along to new
  353. // guests that are created from this guest.
  354. base::Value::Dict attach_params_;
  355. // This observer ensures that this guest self-destructs if the embedder goes
  356. // away. It also tracks when the embedder's fullscreen is toggled so the guest
  357. // can change itself accordingly.
  358. std::unique_ptr<OwnerContentsObserver> owner_contents_observer_;
  359. // This observer ensures that if the guest is unattached and its opener goes
  360. // away then this guest also self-destructs.
  361. std::unique_ptr<OpenerLifetimeObserver> opener_lifetime_observer_;
  362. // The size of the guest content. Note: In autosize mode, the container
  363. // element may not match the size of the guest.
  364. gfx::Size guest_size_;
  365. // A pointer to the guest_host.
  366. raw_ptr<content::GuestHost> guest_host_;
  367. // Indicates whether autosize mode is enabled or not.
  368. bool auto_size_enabled_;
  369. // The maximum size constraints of the container element in autosize mode.
  370. gfx::Size max_auto_size_;
  371. // The minimum size constraints of the container element in autosize mode.
  372. gfx::Size min_auto_size_;
  373. // The size that will be used when autosize mode is disabled.
  374. gfx::Size normal_size_;
  375. // Whether the guest view is inside a plugin document.
  376. bool is_full_page_plugin_;
  377. // This is used to ensure pending tasks will not fire after this object is
  378. // destroyed.
  379. base::WeakPtrFactory<GuestViewBase> weak_ptr_factory_{this};
  380. };
  381. } // namespace guest_view
  382. #endif // COMPONENTS_GUEST_VIEW_BROWSER_GUEST_VIEW_BASE_H_