blob: 0e1d43c5be37ca88f5936ba8373c7ab101e154c3 [file] [log] [blame]
Sean Toppinge91b0972018-10-25 20:59:121// Copyright 2018 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
5#ifndef CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_
6#define CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_
7
Chad Duffin4aa9c042019-01-11 00:51:558#include <string>
9#include <vector>
10
Jiawei Lidf9ad18a2019-07-07 05:31:0211#include "base/callback.h"
Jiawei Li830fcfd2019-02-12 20:12:1712#include "base/containers/flat_set.h"
Chad Duffin4aa9c042019-01-11 00:51:5513#include "base/observer_list.h"
Sean Topping0e8ac572019-01-30 03:05:4314#include "base/optional.h"
Zhaoxin2fe094a2020-02-11 23:35:4515#include "base/process/process.h"
Chad Duffin4aa9c042019-01-11 00:51:5516#include "chromecast/common/mojom/feature_manager.mojom.h"
Chih-Hsuan Kuo7b4fb102020-03-04 08:21:4917#include "content/public/common/media_playback_renderer_type.mojom.h"
Ken Rockot48c7b502020-11-20 23:33:5918#include "mojo/public/cpp/bindings/generic_pending_receiver.h"
Jiawei Li830fcfd2019-02-12 20:12:1719#include "services/service_manager/public/cpp/binder_registry.h"
20#include "services/service_manager/public/cpp/interface_provider.h"
Chris Hamilton825f2ed2020-01-30 21:46:4121#include "third_party/blink/public/common/messaging/web_message_port.h"
Sean Toppingf0a1d572019-06-17 23:03:4422#include "ui/gfx/geometry/rect.h"
Sean Toppinge91b0972018-10-25 20:59:1223#include "url/gurl.h"
24
Sean Topping2d4e54e2019-06-25 00:04:0425namespace blink {
26class AssociatedInterfaceProvider;
27} // namespace blink
28
Sean Toppinge91b0972018-10-25 20:59:1229namespace content {
30class WebContents;
31} // namespace content
32
Kevin Marshall3f693812020-08-07 17:45:3633namespace on_load_script_injector {
34template <typename>
35class OnLoadScriptInjectorHost;
36} // namespace on_load_script_injector
37
Sean Toppinge91b0972018-10-25 20:59:1238namespace chromecast {
39
Sean Topping0e8ac572019-01-30 03:05:4340struct RendererFeature {
41 const std::string name;
42 base::Value value;
43};
44
Sean Toppinge91b0972018-10-25 20:59:1245// Simplified WebContents wrapper class for Cast platforms.
Sean Topping7414eed2019-04-10 23:04:2146//
47// Proper usage of content::WebContents relies on understanding the meaning
48// behind various WebContentsObserver methods, and then translating those
49// signals into some concrete state. CastWebContents does *not* own the
50// underlying WebContents (usually whatever class implements
51// content::WebContentsDelegate is the actual owner).
52//
53// =============================================================================
54// Lifetime
55// =============================================================================
56// CastWebContents *must* be created before WebContents begins loading any
57// content. Once content begins loading (via CWC::LoadUrl() or one of the
58// WebContents navigation APIs), CastWebContents will calculate its state based
59// on the status of the WebContents' *main* RenderFrame. Events from sub-frames
60// (e.g. iframes) are ignored, since we expect the web app to take care of
61// sub-frame errors.
62//
63// We consider the CastWebContents to be in a LOADED state when the content of
Jiawei Li042aaca2021-03-30 00:15:5364// the main frame is fully loaded and running (all resources fetched,
65// redirection finished, JS is running). Iframes might still be loading in this
66// case, but in general we consider the page to be in a presentable state at
67// this stage, so it is appropriate to display the WebContents to the user.
Sean Topping7414eed2019-04-10 23:04:2168//
69// During or after the page is loaded, there are multiple error conditions that
70// can occur. The following events will cause the page to enter an ERROR state:
71//
72// 1. If the main frame is served an HTTP error page (such as a 404 page), then
73// it means the desired content wasn't loaded.
74//
75// 2. If the main frame fails to load, such as when the browser blocked the URL
76// request, we treat this as an error.
77//
78// 3. The RenderProcess for the main frame could crash, so the page is not in a
79// usable state.
80//
81// The CastWebContents user can respond to these errors in a few ways: The
82// content can be reloaded, or the entire page activity can be cancelled. If we
83// totally cancel the activity, we prefer to notify the user with an error
84// screen or visible/audible error message. Otherwise, a silent retry is
85// preferred.
86//
87// CastWebContents can be used to close the underlying WebContents gracefully
88// via CWC::Close(). This initiates web page tear-down logic so that the web
89// app has a chance to perform its own finalization logic in JS. Next, we call
90// WebContents::ClosePage(), which defers the page closure logic to the
91// content::WebContentsDelegate. Usually, it will run its own finalization
92// logic and then destroy the WebContents. CastWebContents will be notified of
93// the WebContents destruction and enter the DESTROYED state. In the event
94// the page isn't destroyed, the page will enter the CLOSED state automatically
95// after a timeout. CastWebContents users should not try to reload the page, as
96// page closure is intentional.
97//
98// The web app may decide to close itself (such as via "window.close()" in JS).
99// This is similar to initiating the close flow via CWC::Close(), with the end
100// result being the same. We consider this an intentional closure, and should
101// not attempt to reload the page.
102//
103// Once CastWebContents is in the DESTROYED state, it is not really usable
104// anymore; most of the methods will simply no-op, and no more observer signals
105// will be emitted.
106//
107// CastWebContents can be deleted at any time, *except* during Observer
108// notifications. If the owner wants to destroy CastWebContents as a result of
109// an Observer event, it should post a task to destroy CastWebContents.
Sean Toppinge91b0972018-10-25 20:59:12110class CastWebContents {
111 public:
112 class Delegate {
113 public:
Sean Toppingf0a1d572019-06-17 23:03:44114 // Notify that an inner WebContents was created. |inner_contents| is created
115 // in a default-initialized state with no delegate, and can be safely
116 // initialized by the delegate.
117 virtual void InnerContentsCreated(CastWebContents* inner_contents,
118 CastWebContents* outer_contents) {}
119
120 protected:
121 virtual ~Delegate() {}
122 };
123
124 // Observer class. The Observer should *not* destroy CastWebContents during
125 // any of these events, otherwise other observers might try to use a freed
126 // pointer to |cast_web_contents|.
127 class Observer {
128 public:
129 Observer();
130
Sean Toppinge91b0972018-10-25 20:59:12131 // Advertises page state for the CastWebContents.
132 // Use CastWebContents::page_state() to get the new state.
Sean Toppingf0a1d572019-06-17 23:03:44133 virtual void OnPageStateChanged(CastWebContents* cast_web_contents) {}
Sean Toppinge91b0972018-10-25 20:59:12134
135 // Called when the page has stopped. e.g.: A 404 occurred when loading the
136 // page or if the render process for the main frame crashes. |error_code|
137 // will return a net::Error describing the failure, or net::OK if the page
Sean Topping7414eed2019-04-10 23:04:21138 // closed intentionally.
Sean Toppinge91b0972018-10-25 20:59:12139 //
140 // After this method, the page state will be one of the following:
Sean Topping7414eed2019-04-10 23:04:21141 // CLOSED: Page was closed as expected and the WebContents exists. The page
142 // should generally not be reloaded, since the page closure was
143 // triggered intentionally.
144 // ERROR: Page is in an error state. It should be reloaded or deleted.
Sean Toppinge91b0972018-10-25 20:59:12145 // DESTROYED: Page was closed due to deletion of WebContents. The
146 // CastWebContents instance is no longer usable and should be deleted.
Sean Toppinge91b0972018-10-25 20:59:12147 virtual void OnPageStopped(CastWebContents* cast_web_contents,
Sean Toppingf0a1d572019-06-17 23:03:44148 int error_code) {}
Sean Toppinge91b0972018-10-25 20:59:12149
Sean Toppingf0a1d572019-06-17 23:03:44150 // A new RenderFrame was created for the WebContents. |frame_interfaces| are
151 // provided by the new frame.
152 virtual void RenderFrameCreated(
153 int render_process_id,
154 int render_frame_id,
Sean Topping2d4e54e2019-06-25 00:04:04155 service_manager::InterfaceProvider* frame_interfaces,
156 blink::AssociatedInterfaceProvider* frame_associated_interfaces) {}
Chad Duffin4aa9c042019-01-11 00:51:55157
Jiawei Lic3354ee2019-12-13 23:48:35158 // A navigation has finished in the WebContents' main frame.
159 virtual void MainFrameFinishedNavigation() {}
160
Sean Toppingf0a1d572019-06-17 23:03:44161 // These methods are calls forwarded from WebContentsObserver.
162 virtual void MainFrameResized(const gfx::Rect& bounds) {}
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:58163 virtual void UpdateTitle(const std::u16string& title) {}
Sean Toppingf0a1d572019-06-17 23:03:44164 virtual void UpdateFaviconURL(GURL icon_url) {}
Sean Toppingf0a1d572019-06-17 23:03:44165 virtual void DidFirstVisuallyNonEmptyPaint() {}
Chad Duffin4aa9c042019-01-11 00:51:55166
Sean Topping7414eed2019-04-10 23:04:21167 // Notifies that a resource for the main frame failed to load.
168 virtual void ResourceLoadFailed(CastWebContents* cast_web_contents) {}
169
Zhaoxin2fe094a2020-02-11 23:35:45170 // Propagates the process information via observer, in particular to
171 // the underlying OnRendererProcessStarted() method.
172 virtual void OnRenderProcessReady(const base::Process& process) {}
173
Sean Toppinge8648a22020-04-29 18:41:00174 // Notify media playback state changes for the underlying WebContents.
175 virtual void MediaPlaybackChanged(bool media_playing) {}
176
Chad Duffin4aa9c042019-01-11 00:51:55177 // Adds |this| to the ObserverList in the implementation of
178 // |cast_web_contents|.
179 void Observe(CastWebContents* cast_web_contents);
180
181 // Removes |this| from the ObserverList in the implementation of
182 // |cast_web_contents_|. This is only invoked by CastWebContents and is used
183 // to ensure that once the observed CastWebContents object is destructed the
184 // CastWebContents::Observer does not invoke any additional function calls
185 // on it.
186 void ResetCastWebContents();
187
188 protected:
189 virtual ~Observer();
190
191 CastWebContents* cast_web_contents_;
192 };
193
Sean Toppingf0a1d572019-06-17 23:03:44194 enum class BackgroundColor {
195 NONE,
196 WHITE,
197 BLACK,
198 TRANSPARENT,
199 };
200
Sean Topping7414eed2019-04-10 23:04:21201 // Initialization parameters for CastWebContents.
Sean Topping0e8ac572019-01-30 03:05:43202 struct InitParams {
Sean Toppingeda675e2019-11-07 22:29:04203 // The delegate for the CastWebContents. Must be non-null. If the delegate
204 // is destroyed before CastWebContents, the WeakPtr will be invalidated on
205 // the main UI thread.
206 base::WeakPtr<Delegate> delegate = nullptr;
Jiawei Lia64a082b2019-12-06 21:17:26207 // Enable development mode for this CastWebContents. Whitelists
Sean Topping8a343862019-05-09 22:19:14208 // certain functionality for the WebContents, like remote debugging and
209 // debugging interfaces.
210 bool enabled_for_dev = false;
Sean Topping7414eed2019-04-10 23:04:21211 // Chooses a media renderer for the WebContents.
Chih-Hsuan Kuo7b4fb102020-03-04 08:21:49212 content::mojom::RendererType renderer_type =
213 content::mojom::RendererType::DEFAULT_RENDERER;
Sean Topping7414eed2019-04-10 23:04:21214 // Whether the WebContents is a root native window, or if it is embedded in
215 // another WebContents (see Delegate::InnerContentsCreated()).
Sean Topping6735aaf2019-03-20 19:20:12216 bool is_root_window = false;
Sean Topping8a343862019-05-09 22:19:14217 // Whether inner WebContents events should be handled. If this is set to
218 // true, then inner WebContents will automatically have a CastWebContents
219 // created and notify the delegate.
220 bool handle_inner_contents = false;
221 // Construct internal media blocker and enable BlockMediaLoading().
222 bool use_media_blocker = false;
Sean Toppingf0a1d572019-06-17 23:03:44223 // Background color for the WebContents view. If not provided, the color
224 // will fall back to the platform default.
225 BackgroundColor background_color = BackgroundColor::NONE;
Jiawei Lia64a082b2019-12-06 21:17:26226 // Enable WebSQL database for this CastWebContents.
227 bool enable_websql = false;
228 // Enable mixer audio support for this CastWebContents.
229 bool enable_mixer_audio = false;
Jiaqi Han9ea54f92020-02-20 23:44:59230 // Whether to provide a URL filter applied to network requests for the
231 // activity hosted by this CastWebContents.
232 // No filters implies no restrictions.
233 base::Optional<std::vector<std::string>> url_filters = base::nullopt;
Peter Qiu90dfc9a2021-02-10 18:39:23234 // Whether WebRTC peer connections are allowed to use legacy versions of the
235 // TLS/DTLS protocols.
236 bool webrtc_allow_legacy_tls_protocols = false;
Sean Toppingeda675e2019-11-07 22:29:04237
238 InitParams();
239 InitParams(const InitParams& other);
240 ~InitParams();
Sean Topping0e8ac572019-01-30 03:05:43241 };
242
Sean Toppinge91b0972018-10-25 20:59:12243 // Page state for the main frame.
244 enum class PageState {
245 IDLE, // Main frame has not started yet.
246 LOADING, // Main frame is loading resources.
247 LOADED, // Main frame is loaded, but sub-frames may still be loading.
248 CLOSED, // Page is closed and should be cleaned up.
249 DESTROYED, // The WebContents is destroyed and can no longer be used.
250 ERROR, // Main frame is in an error state.
251 };
252
Sean Topping6735aaf2019-03-20 19:20:12253 static std::vector<CastWebContents*>& GetAll();
254
Jiawei Lia64a082b2019-12-06 21:17:26255 // Returns the CastWebContents that wraps the content::WebContents, or nullptr
256 // if the CastWebContents does not exist.
257 static CastWebContents* FromWebContents(content::WebContents* web_contents);
258
Sean Toppinge91b0972018-10-25 20:59:12259 CastWebContents() = default;
260 virtual ~CastWebContents() = default;
261
Sean Topping6735aaf2019-03-20 19:20:12262 // Tab identifier for the WebContents, mainly used by the tabs extension API.
263 // Tab IDs may be re-used, but no two live CastWebContents should have the
264 // same tab ID at any given time.
265 virtual int tab_id() const = 0;
266
Randy Rossic6bb3ab2020-08-11 18:02:52267 // An identifier for the WebContents, mainly used by platform views service.
268 // IDs may be re-used but are unique among all live CastWebContents.
269 virtual int id() const = 0;
270
Sean Topping0e8ac572019-01-30 03:05:43271 // TODO(seantopping): Hide this, clients shouldn't use WebContents directly.
Sean Toppinge91b0972018-10-25 20:59:12272 virtual content::WebContents* web_contents() const = 0;
273 virtual PageState page_state() const = 0;
274
Jiawei Lic3354ee2019-12-13 23:48:35275 // Returns the PID of the main frame process if valid.
276 virtual base::Optional<pid_t> GetMainFrameRenderProcessPid() const = 0;
277
Sean Topping0e8ac572019-01-30 03:05:43278 // ===========================================================================
279 // Initialization and Setup
280 // ===========================================================================
281
Sean Topping0e8ac572019-01-30 03:05:43282 // Add a set of features for all renderers in the WebContents. Features are
283 // configured when `CastWebContents::RenderFrameCreated` is invoked.
284 virtual void AddRendererFeatures(std::vector<RendererFeature> features) = 0;
285
286 virtual void AllowWebAndMojoWebUiBindings() = 0;
287 virtual void ClearRenderWidgetHostView() = 0;
288
289 // ===========================================================================
290 // Page Lifetime
291 // ===========================================================================
292
Sean Toppinge91b0972018-10-25 20:59:12293 // Navigates the underlying WebContents to |url|. Delegate will be notified of
294 // page progression events via OnPageStateChanged().
295 virtual void LoadUrl(const GURL& url) = 0;
296
297 // Initiate closure of the page. This invokes the appropriate unload handlers.
298 // Eventually the delegate will be notified with OnPageStopped().
299 virtual void ClosePage() = 0;
300
301 // Stop the page immediately. This will automatically invoke
302 // Delegate::OnPageStopped(error_code), allowing the delegate to delete or
Sean Topping7414eed2019-04-10 23:04:21303 // reload the page without waiting for the WebContents owner to tear down the
304 // page.
Sean Toppinge91b0972018-10-25 20:59:12305 virtual void Stop(int error_code) = 0;
306
Sean Topping8a343862019-05-09 22:19:14307 // ===========================================================================
Sean Toppinga0a0f5e2020-03-19 00:22:30308 // Visibility
309 // ===========================================================================
310
311 // Specify if the WebContents should be treated as visible. This triggers a
312 // document "visibilitychange" change event, and will paint the WebContents
313 // quad if |visible| is true (otherwise it will be blank). Note that this does
314 // *not* guarantee the page is visible on the screen, as that depends on if
315 // the WebContents quad is present in the screen layout and isn't obscured by
316 // another window.
317 virtual void SetWebVisibilityAndPaint(bool visible) = 0;
318
319 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14320 // Media Management
321 // ===========================================================================
322
323 // Block/unblock media from loading in all RenderFrames for the WebContents.
324 virtual void BlockMediaLoading(bool blocked) = 0;
Andres Medinaa65ad1b2019-06-26 22:18:19325 // Block/unblock media from starting in all RenderFrames for the WebContents.
326 // As opposed to |BlockMediaLoading|, |BlockMediaStarting| allows media to
327 // load while in blocking state.
328 virtual void BlockMediaStarting(bool blocked) = 0;
Sean Topping8a343862019-05-09 22:19:14329 virtual void EnableBackgroundVideoPlayback(bool enabled) = 0;
330
331 // ===========================================================================
Jiawei Lidf9ad18a2019-07-07 05:31:02332 // Page Communication
333 // ===========================================================================
334
Kevin Marshall6f8f04b2020-08-05 18:48:14335 // Returns the script injector instance, which injects scripts at page load
336 // time.
Jiawei Li0b1efea2020-08-12 03:30:57337 virtual on_load_script_injector::OnLoadScriptInjectorHost<std::string>*
Kevin Marshall6f8f04b2020-08-05 18:48:14338 script_injector() = 0;
Jiawei Lidf9ad18a2019-07-07 05:31:02339
Jiawei Libba76072019-07-29 23:00:25340 // Posts a message to the frame's onMessage handler.
341 //
342 // `target_origin` restricts message delivery to the specified origin.
343 // If `target_origin` is "*", then the message will be sent to the
344 // document regardless of its origin.
345 // See html.spec.whatwg.org/multipage/web-messaging.html sect. 9.4.3
346 // for more details on how the target origin policy is applied.
347 // Should be called on UI thread.
Chris Hamilton825f2ed2020-01-30 21:46:41348 virtual void PostMessageToMainFrame(
349 const std::string& target_origin,
350 const std::string& data,
351 std::vector<blink::WebMessagePort> ports) = 0;
Jiawei Libba76072019-07-29 23:00:25352
Jiawei Li5283ad42020-03-27 21:26:05353 // Executes a string of JavaScript in the main frame's context.
354 // This is no-op if the main frame is not available.
355 // Pass in a callback to receive a result when it is available.
356 // If there is no need to receive the result, pass in a
357 // default-constructed callback. If provided, the callback
358 // will be invoked on the UI thread.
359 virtual void ExecuteJavaScript(
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:58360 const std::u16string& javascript,
Jiawei Li5283ad42020-03-27 21:26:05361 base::OnceCallback<void(base::Value)> callback) = 0;
362
Jiawei Lidf9ad18a2019-07-07 05:31:02363 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14364 // Utility Methods
365 // ===========================================================================
366
Chad Duffin4aa9c042019-01-11 00:51:55367 // Used to add or remove |observer| to the ObserverList in the implementation.
368 // These functions should only be invoked by CastWebContents::Observer in a
369 // valid sequence, enforced via SequenceChecker.
370 virtual void AddObserver(Observer* observer) = 0;
371 virtual void RemoveObserver(Observer* observer) = 0;
372
Ryan Daum52c9f7132020-04-06 21:23:34373 // Enable or disable devtools remote debugging for this WebContents and any
374 // inner WebContents that are spawned from it.
375 virtual void SetEnabledForRemoteDebugging(bool enabled) = 0;
376
Jiawei Li830fcfd2019-02-12 20:12:17377 // Used to expose CastWebContents's |binder_registry_| to Delegate.
378 // Delegate should register its mojo interface binders via this function
379 // when it is ready.
380 virtual service_manager::BinderRegistry* binder_registry() = 0;
381
Ken Rockot48c7b502020-11-20 23:33:59382 // Asks the CastWebContents to bind an interface receiver using either its
383 // registry or any registered InterfaceProvider.
384 virtual bool TryBindReceiver(mojo::GenericPendingReceiver& receiver) = 0;
385
Julie Jeongeun Kim641f4752019-12-04 01:53:22386 // Used for owner to pass its |InterfaceProvider| pointers to CastWebContents.
387 // It is owner's responsibility to make sure each |InterfaceProvider| pointer
388 // has distinct mojo interface set.
Jiawei Li830fcfd2019-02-12 20:12:17389 using InterfaceSet = base::flat_set<std::string>;
390 virtual void RegisterInterfaceProvider(
391 const InterfaceSet& interface_set,
392 service_manager::InterfaceProvider* interface_provider) = 0;
393
Jiawei Lia64a082b2019-12-06 21:17:26394 // Returns true if WebSQL database is configured enabled for this
395 // CastWebContents.
396 virtual bool is_websql_enabled() = 0;
397
398 // Returns true if mixer audio is enabled.
399 virtual bool is_mixer_audio_enabled() = 0;
400
Sean Toppingabf3be592020-03-11 23:20:35401 // Returns whether or not CastWebContents binder_registry() is valid for
402 // binding interfaces.
403 virtual bool can_bind_interfaces() = 0;
404
Sean Toppinge91b0972018-10-25 20:59:12405 private:
406 DISALLOW_COPY_AND_ASSIGN(CastWebContents);
407};
408
409std::ostream& operator<<(std::ostream& os, CastWebContents::PageState state);
410
411} // namespace chromecast
412
413#endif // CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_