blob: 437613ddb607aa60830494a84a12ff0fc1d4bbd8 [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"
Sean Toppingf0a1d572019-06-17 23:03:4416#include "base/strings/string16.h"
Chad Duffin4aa9c042019-01-11 00:51:5517#include "chromecast/common/mojom/feature_manager.mojom.h"
Chih-Hsuan Kuo7b4fb102020-03-04 08:21:4918#include "content/public/common/media_playback_renderer_type.mojom.h"
Ken Rockot48c7b502020-11-20 23:33:5919#include "mojo/public/cpp/bindings/generic_pending_receiver.h"
Jiawei Li830fcfd2019-02-12 20:12:1720#include "services/service_manager/public/cpp/binder_registry.h"
21#include "services/service_manager/public/cpp/interface_provider.h"
Chris Hamilton825f2ed2020-01-30 21:46:4122#include "third_party/blink/public/common/messaging/web_message_port.h"
Sean Toppingf0a1d572019-06-17 23:03:4423#include "ui/gfx/geometry/rect.h"
Sean Toppinge91b0972018-10-25 20:59:1224#include "url/gurl.h"
25
Sean Topping2d4e54e2019-06-25 00:04:0426namespace blink {
27class AssociatedInterfaceProvider;
28} // namespace blink
29
Sean Toppinge91b0972018-10-25 20:59:1230namespace content {
31class WebContents;
32} // namespace content
33
Kevin Marshall3f693812020-08-07 17:45:3634namespace on_load_script_injector {
35template <typename>
36class OnLoadScriptInjectorHost;
37} // namespace on_load_script_injector
38
Sean Toppinge91b0972018-10-25 20:59:1239namespace chromecast {
40
Sean Topping0e8ac572019-01-30 03:05:4341struct RendererFeature {
42 const std::string name;
43 base::Value value;
44};
45
Sean Toppinge91b0972018-10-25 20:59:1246// Simplified WebContents wrapper class for Cast platforms.
Sean Topping7414eed2019-04-10 23:04:2147//
48// Proper usage of content::WebContents relies on understanding the meaning
49// behind various WebContentsObserver methods, and then translating those
50// signals into some concrete state. CastWebContents does *not* own the
51// underlying WebContents (usually whatever class implements
52// content::WebContentsDelegate is the actual owner).
53//
54// =============================================================================
55// Lifetime
56// =============================================================================
57// CastWebContents *must* be created before WebContents begins loading any
58// content. Once content begins loading (via CWC::LoadUrl() or one of the
59// WebContents navigation APIs), CastWebContents will calculate its state based
60// on the status of the WebContents' *main* RenderFrame. Events from sub-frames
61// (e.g. iframes) are ignored, since we expect the web app to take care of
62// sub-frame errors.
63//
64// We consider the CastWebContents to be in a LOADED state when the content of
65// the main frame is fully loaded and running (all resources fetched, JS is
66// running). Iframes might still be loading in this case, but in general we
Sean Toppingeda675e2019-11-07 22:29:0467// consider the page to be in a presentable state at this stage, so it is
Sean Topping7414eed2019-04-10 23:04:2168// appropriate to display the WebContents to the user.
69//
70// During or after the page is loaded, there are multiple error conditions that
71// can occur. The following events will cause the page to enter an ERROR state:
72//
73// 1. If the main frame is served an HTTP error page (such as a 404 page), then
74// it means the desired content wasn't loaded.
75//
76// 2. If the main frame fails to load, such as when the browser blocked the URL
77// request, we treat this as an error.
78//
79// 3. The RenderProcess for the main frame could crash, so the page is not in a
80// usable state.
81//
82// The CastWebContents user can respond to these errors in a few ways: The
83// content can be reloaded, or the entire page activity can be cancelled. If we
84// totally cancel the activity, we prefer to notify the user with an error
85// screen or visible/audible error message. Otherwise, a silent retry is
86// preferred.
87//
88// CastWebContents can be used to close the underlying WebContents gracefully
89// via CWC::Close(). This initiates web page tear-down logic so that the web
90// app has a chance to perform its own finalization logic in JS. Next, we call
91// WebContents::ClosePage(), which defers the page closure logic to the
92// content::WebContentsDelegate. Usually, it will run its own finalization
93// logic and then destroy the WebContents. CastWebContents will be notified of
94// the WebContents destruction and enter the DESTROYED state. In the event
95// the page isn't destroyed, the page will enter the CLOSED state automatically
96// after a timeout. CastWebContents users should not try to reload the page, as
97// page closure is intentional.
98//
99// The web app may decide to close itself (such as via "window.close()" in JS).
100// This is similar to initiating the close flow via CWC::Close(), with the end
101// result being the same. We consider this an intentional closure, and should
102// not attempt to reload the page.
103//
104// Once CastWebContents is in the DESTROYED state, it is not really usable
105// anymore; most of the methods will simply no-op, and no more observer signals
106// will be emitted.
107//
108// CastWebContents can be deleted at any time, *except* during Observer
109// notifications. If the owner wants to destroy CastWebContents as a result of
110// an Observer event, it should post a task to destroy CastWebContents.
Sean Toppinge91b0972018-10-25 20:59:12111class CastWebContents {
112 public:
113 class Delegate {
114 public:
Sean Toppingf0a1d572019-06-17 23:03:44115 // Notify that an inner WebContents was created. |inner_contents| is created
116 // in a default-initialized state with no delegate, and can be safely
117 // initialized by the delegate.
118 virtual void InnerContentsCreated(CastWebContents* inner_contents,
119 CastWebContents* outer_contents) {}
120
121 protected:
122 virtual ~Delegate() {}
123 };
124
125 // Observer class. The Observer should *not* destroy CastWebContents during
126 // any of these events, otherwise other observers might try to use a freed
127 // pointer to |cast_web_contents|.
128 class Observer {
129 public:
130 Observer();
131
Sean Toppinge91b0972018-10-25 20:59:12132 // Advertises page state for the CastWebContents.
133 // Use CastWebContents::page_state() to get the new state.
Sean Toppingf0a1d572019-06-17 23:03:44134 virtual void OnPageStateChanged(CastWebContents* cast_web_contents) {}
Sean Toppinge91b0972018-10-25 20:59:12135
136 // Called when the page has stopped. e.g.: A 404 occurred when loading the
137 // page or if the render process for the main frame crashes. |error_code|
138 // will return a net::Error describing the failure, or net::OK if the page
Sean Topping7414eed2019-04-10 23:04:21139 // closed intentionally.
Sean Toppinge91b0972018-10-25 20:59:12140 //
141 // After this method, the page state will be one of the following:
Sean Topping7414eed2019-04-10 23:04:21142 // CLOSED: Page was closed as expected and the WebContents exists. The page
143 // should generally not be reloaded, since the page closure was
144 // triggered intentionally.
145 // ERROR: Page is in an error state. It should be reloaded or deleted.
Sean Toppinge91b0972018-10-25 20:59:12146 // DESTROYED: Page was closed due to deletion of WebContents. The
147 // CastWebContents instance is no longer usable and should be deleted.
Sean Toppinge91b0972018-10-25 20:59:12148 virtual void OnPageStopped(CastWebContents* cast_web_contents,
Sean Toppingf0a1d572019-06-17 23:03:44149 int error_code) {}
Sean Toppinge91b0972018-10-25 20:59:12150
Sean Toppingf0a1d572019-06-17 23:03:44151 // A new RenderFrame was created for the WebContents. |frame_interfaces| are
152 // provided by the new frame.
153 virtual void RenderFrameCreated(
154 int render_process_id,
155 int render_frame_id,
Sean Topping2d4e54e2019-06-25 00:04:04156 service_manager::InterfaceProvider* frame_interfaces,
157 blink::AssociatedInterfaceProvider* frame_associated_interfaces) {}
Chad Duffin4aa9c042019-01-11 00:51:55158
Jiawei Lic3354ee2019-12-13 23:48:35159 // A navigation has finished in the WebContents' main frame.
160 virtual void MainFrameFinishedNavigation() {}
161
Sean Toppingf0a1d572019-06-17 23:03:44162 // These methods are calls forwarded from WebContentsObserver.
163 virtual void MainFrameResized(const gfx::Rect& bounds) {}
164 virtual void UpdateTitle(const base::string16& title) {}
165 virtual void UpdateFaviconURL(GURL icon_url) {}
166 virtual void DidFinishBlockedNavigation(GURL url) {}
167 virtual void DidFirstVisuallyNonEmptyPaint() {}
Chad Duffin4aa9c042019-01-11 00:51:55168
Sean Topping7414eed2019-04-10 23:04:21169 // Notifies that a resource for the main frame failed to load.
170 virtual void ResourceLoadFailed(CastWebContents* cast_web_contents) {}
171
Zhaoxin2fe094a2020-02-11 23:35:45172 // Propagates the process information via observer, in particular to
173 // the underlying OnRendererProcessStarted() method.
174 virtual void OnRenderProcessReady(const base::Process& process) {}
175
Sean Toppinge8648a22020-04-29 18:41:00176 // Notify media playback state changes for the underlying WebContents.
177 virtual void MediaPlaybackChanged(bool media_playing) {}
178
Chad Duffin4aa9c042019-01-11 00:51:55179 // Adds |this| to the ObserverList in the implementation of
180 // |cast_web_contents|.
181 void Observe(CastWebContents* cast_web_contents);
182
183 // Removes |this| from the ObserverList in the implementation of
184 // |cast_web_contents_|. This is only invoked by CastWebContents and is used
185 // to ensure that once the observed CastWebContents object is destructed the
186 // CastWebContents::Observer does not invoke any additional function calls
187 // on it.
188 void ResetCastWebContents();
189
190 protected:
191 virtual ~Observer();
192
193 CastWebContents* cast_web_contents_;
194 };
195
Sean Toppingf0a1d572019-06-17 23:03:44196 enum class BackgroundColor {
197 NONE,
198 WHITE,
199 BLACK,
200 TRANSPARENT,
201 };
202
Sean Topping7414eed2019-04-10 23:04:21203 // Initialization parameters for CastWebContents.
Sean Topping0e8ac572019-01-30 03:05:43204 struct InitParams {
Sean Toppingeda675e2019-11-07 22:29:04205 // The delegate for the CastWebContents. Must be non-null. If the delegate
206 // is destroyed before CastWebContents, the WeakPtr will be invalidated on
207 // the main UI thread.
208 base::WeakPtr<Delegate> delegate = nullptr;
Jiawei Lia64a082b2019-12-06 21:17:26209 // Enable development mode for this CastWebContents. Whitelists
Sean Topping8a343862019-05-09 22:19:14210 // certain functionality for the WebContents, like remote debugging and
211 // debugging interfaces.
212 bool enabled_for_dev = false;
Sean Topping7414eed2019-04-10 23:04:21213 // Chooses a media renderer for the WebContents.
Chih-Hsuan Kuo7b4fb102020-03-04 08:21:49214 content::mojom::RendererType renderer_type =
215 content::mojom::RendererType::DEFAULT_RENDERER;
Sean Topping7414eed2019-04-10 23:04:21216 // Whether the WebContents is a root native window, or if it is embedded in
217 // another WebContents (see Delegate::InnerContentsCreated()).
Sean Topping6735aaf2019-03-20 19:20:12218 bool is_root_window = false;
Sean Topping8a343862019-05-09 22:19:14219 // Whether inner WebContents events should be handled. If this is set to
220 // true, then inner WebContents will automatically have a CastWebContents
221 // created and notify the delegate.
222 bool handle_inner_contents = false;
223 // Construct internal media blocker and enable BlockMediaLoading().
224 bool use_media_blocker = false;
Sean Toppingf0a1d572019-06-17 23:03:44225 // Background color for the WebContents view. If not provided, the color
226 // will fall back to the platform default.
227 BackgroundColor background_color = BackgroundColor::NONE;
Jiawei Lia64a082b2019-12-06 21:17:26228 // Enable WebSQL database for this CastWebContents.
229 bool enable_websql = false;
230 // Enable mixer audio support for this CastWebContents.
231 bool enable_mixer_audio = false;
Jiaqi Han9ea54f92020-02-20 23:44:59232 // Whether to provide a URL filter applied to network requests for the
233 // activity hosted by this CastWebContents.
234 // No filters implies no restrictions.
235 base::Optional<std::vector<std::string>> url_filters = base::nullopt;
Peter Qiu90dfc9a2021-02-10 18:39:23236 // Whether WebRTC peer connections are allowed to use legacy versions of the
237 // TLS/DTLS protocols.
238 bool webrtc_allow_legacy_tls_protocols = false;
Sean Toppingeda675e2019-11-07 22:29:04239
240 InitParams();
241 InitParams(const InitParams& other);
242 ~InitParams();
Sean Topping0e8ac572019-01-30 03:05:43243 };
244
Sean Toppinge91b0972018-10-25 20:59:12245 // Page state for the main frame.
246 enum class PageState {
247 IDLE, // Main frame has not started yet.
248 LOADING, // Main frame is loading resources.
249 LOADED, // Main frame is loaded, but sub-frames may still be loading.
250 CLOSED, // Page is closed and should be cleaned up.
251 DESTROYED, // The WebContents is destroyed and can no longer be used.
252 ERROR, // Main frame is in an error state.
253 };
254
Sean Topping6735aaf2019-03-20 19:20:12255 static std::vector<CastWebContents*>& GetAll();
256
Jiawei Lia64a082b2019-12-06 21:17:26257 // Returns the CastWebContents that wraps the content::WebContents, or nullptr
258 // if the CastWebContents does not exist.
259 static CastWebContents* FromWebContents(content::WebContents* web_contents);
260
Sean Toppinge91b0972018-10-25 20:59:12261 CastWebContents() = default;
262 virtual ~CastWebContents() = default;
263
Sean Topping6735aaf2019-03-20 19:20:12264 // Tab identifier for the WebContents, mainly used by the tabs extension API.
265 // Tab IDs may be re-used, but no two live CastWebContents should have the
266 // same tab ID at any given time.
267 virtual int tab_id() const = 0;
268
Randy Rossic6bb3ab2020-08-11 18:02:52269 // An identifier for the WebContents, mainly used by platform views service.
270 // IDs may be re-used but are unique among all live CastWebContents.
271 virtual int id() const = 0;
272
Sean Topping0e8ac572019-01-30 03:05:43273 // TODO(seantopping): Hide this, clients shouldn't use WebContents directly.
Sean Toppinge91b0972018-10-25 20:59:12274 virtual content::WebContents* web_contents() const = 0;
275 virtual PageState page_state() const = 0;
276
Jiawei Lic3354ee2019-12-13 23:48:35277 // Returns the PID of the main frame process if valid.
278 virtual base::Optional<pid_t> GetMainFrameRenderProcessPid() const = 0;
279
Sean Topping0e8ac572019-01-30 03:05:43280 // ===========================================================================
281 // Initialization and Setup
282 // ===========================================================================
283
Sean Topping0e8ac572019-01-30 03:05:43284 // Add a set of features for all renderers in the WebContents. Features are
285 // configured when `CastWebContents::RenderFrameCreated` is invoked.
286 virtual void AddRendererFeatures(std::vector<RendererFeature> features) = 0;
287
288 virtual void AllowWebAndMojoWebUiBindings() = 0;
289 virtual void ClearRenderWidgetHostView() = 0;
290
291 // ===========================================================================
292 // Page Lifetime
293 // ===========================================================================
294
Sean Toppinge91b0972018-10-25 20:59:12295 // Navigates the underlying WebContents to |url|. Delegate will be notified of
296 // page progression events via OnPageStateChanged().
297 virtual void LoadUrl(const GURL& url) = 0;
298
299 // Initiate closure of the page. This invokes the appropriate unload handlers.
300 // Eventually the delegate will be notified with OnPageStopped().
301 virtual void ClosePage() = 0;
302
303 // Stop the page immediately. This will automatically invoke
304 // Delegate::OnPageStopped(error_code), allowing the delegate to delete or
Sean Topping7414eed2019-04-10 23:04:21305 // reload the page without waiting for the WebContents owner to tear down the
306 // page.
Sean Toppinge91b0972018-10-25 20:59:12307 virtual void Stop(int error_code) = 0;
308
Sean Topping8a343862019-05-09 22:19:14309 // ===========================================================================
Sean Toppinga0a0f5e2020-03-19 00:22:30310 // Visibility
311 // ===========================================================================
312
313 // Specify if the WebContents should be treated as visible. This triggers a
314 // document "visibilitychange" change event, and will paint the WebContents
315 // quad if |visible| is true (otherwise it will be blank). Note that this does
316 // *not* guarantee the page is visible on the screen, as that depends on if
317 // the WebContents quad is present in the screen layout and isn't obscured by
318 // another window.
319 virtual void SetWebVisibilityAndPaint(bool visible) = 0;
320
321 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14322 // Media Management
323 // ===========================================================================
324
325 // Block/unblock media from loading in all RenderFrames for the WebContents.
326 virtual void BlockMediaLoading(bool blocked) = 0;
Andres Medinaa65ad1b2019-06-26 22:18:19327 // Block/unblock media from starting in all RenderFrames for the WebContents.
328 // As opposed to |BlockMediaLoading|, |BlockMediaStarting| allows media to
329 // load while in blocking state.
330 virtual void BlockMediaStarting(bool blocked) = 0;
Sean Topping8a343862019-05-09 22:19:14331 virtual void EnableBackgroundVideoPlayback(bool enabled) = 0;
332
333 // ===========================================================================
Jiawei Lidf9ad18a2019-07-07 05:31:02334 // Page Communication
335 // ===========================================================================
336
Kevin Marshall6f8f04b2020-08-05 18:48:14337 // Returns the script injector instance, which injects scripts at page load
338 // time.
Jiawei Li0b1efea2020-08-12 03:30:57339 virtual on_load_script_injector::OnLoadScriptInjectorHost<std::string>*
Kevin Marshall6f8f04b2020-08-05 18:48:14340 script_injector() = 0;
Jiawei Lidf9ad18a2019-07-07 05:31:02341
Kevin Marshall6f8f04b2020-08-05 18:48:14342 // Injects on-load scripts into the WebContents' main frame.
343 virtual void InjectScriptsIntoMainFrame() = 0;
Jiawei Lidf9ad18a2019-07-07 05:31:02344
Jiawei Libba76072019-07-29 23:00:25345 // Posts a message to the frame's onMessage handler.
346 //
347 // `target_origin` restricts message delivery to the specified origin.
348 // If `target_origin` is "*", then the message will be sent to the
349 // document regardless of its origin.
350 // See html.spec.whatwg.org/multipage/web-messaging.html sect. 9.4.3
351 // for more details on how the target origin policy is applied.
352 // Should be called on UI thread.
Chris Hamilton825f2ed2020-01-30 21:46:41353 virtual void PostMessageToMainFrame(
354 const std::string& target_origin,
355 const std::string& data,
356 std::vector<blink::WebMessagePort> ports) = 0;
Jiawei Libba76072019-07-29 23:00:25357
Jiawei Li5283ad42020-03-27 21:26:05358 // Executes a string of JavaScript in the main frame's context.
359 // This is no-op if the main frame is not available.
360 // Pass in a callback to receive a result when it is available.
361 // If there is no need to receive the result, pass in a
362 // default-constructed callback. If provided, the callback
363 // will be invoked on the UI thread.
364 virtual void ExecuteJavaScript(
365 const base::string16& javascript,
366 base::OnceCallback<void(base::Value)> callback) = 0;
367
Jiawei Lidf9ad18a2019-07-07 05:31:02368 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14369 // Utility Methods
370 // ===========================================================================
371
Chad Duffin4aa9c042019-01-11 00:51:55372 // Used to add or remove |observer| to the ObserverList in the implementation.
373 // These functions should only be invoked by CastWebContents::Observer in a
374 // valid sequence, enforced via SequenceChecker.
375 virtual void AddObserver(Observer* observer) = 0;
376 virtual void RemoveObserver(Observer* observer) = 0;
377
Ryan Daum52c9f7132020-04-06 21:23:34378 // Enable or disable devtools remote debugging for this WebContents and any
379 // inner WebContents that are spawned from it.
380 virtual void SetEnabledForRemoteDebugging(bool enabled) = 0;
381
Jiawei Li830fcfd2019-02-12 20:12:17382 // Used to expose CastWebContents's |binder_registry_| to Delegate.
383 // Delegate should register its mojo interface binders via this function
384 // when it is ready.
385 virtual service_manager::BinderRegistry* binder_registry() = 0;
386
Ken Rockot48c7b502020-11-20 23:33:59387 // Asks the CastWebContents to bind an interface receiver using either its
388 // registry or any registered InterfaceProvider.
389 virtual bool TryBindReceiver(mojo::GenericPendingReceiver& receiver) = 0;
390
Julie Jeongeun Kim641f4752019-12-04 01:53:22391 // Used for owner to pass its |InterfaceProvider| pointers to CastWebContents.
392 // It is owner's responsibility to make sure each |InterfaceProvider| pointer
393 // has distinct mojo interface set.
Jiawei Li830fcfd2019-02-12 20:12:17394 using InterfaceSet = base::flat_set<std::string>;
395 virtual void RegisterInterfaceProvider(
396 const InterfaceSet& interface_set,
397 service_manager::InterfaceProvider* interface_provider) = 0;
398
Jiawei Lia64a082b2019-12-06 21:17:26399 // Returns true if WebSQL database is configured enabled for this
400 // CastWebContents.
401 virtual bool is_websql_enabled() = 0;
402
403 // Returns true if mixer audio is enabled.
404 virtual bool is_mixer_audio_enabled() = 0;
405
Sean Toppingabf3be592020-03-11 23:20:35406 // Returns whether or not CastWebContents binder_registry() is valid for
407 // binding interfaces.
408 virtual bool can_bind_interfaces() = 0;
409
Sean Toppinge91b0972018-10-25 20:59:12410 private:
411 DISALLOW_COPY_AND_ASSIGN(CastWebContents);
412};
413
414std::ostream& operator<<(std::ostream& os, CastWebContents::PageState state);
415
416} // namespace chromecast
417
418#endif // CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_