blob: b921830d272e5b908eea35209a72beaa94c4ee7a [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"
Jiawei Lidf9ad18a2019-07-07 05:31:0217#include "base/strings/string_piece_forward.h"
Chad Duffin4aa9c042019-01-11 00:51:5518#include "chromecast/common/mojom/feature_manager.mojom.h"
Chih-Hsuan Kuo7b4fb102020-03-04 08:21:4919#include "content/public/common/media_playback_renderer_type.mojom.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
Jiawei Li0565a2f2019-12-07 01:26:0141class QueryableDataHost;
42
Sean Topping0e8ac572019-01-30 03:05:4343struct RendererFeature {
44 const std::string name;
45 base::Value value;
46};
47
Sean Toppinge91b0972018-10-25 20:59:1248// Simplified WebContents wrapper class for Cast platforms.
Sean Topping7414eed2019-04-10 23:04:2149//
50// Proper usage of content::WebContents relies on understanding the meaning
51// behind various WebContentsObserver methods, and then translating those
52// signals into some concrete state. CastWebContents does *not* own the
53// underlying WebContents (usually whatever class implements
54// content::WebContentsDelegate is the actual owner).
55//
56// =============================================================================
57// Lifetime
58// =============================================================================
59// CastWebContents *must* be created before WebContents begins loading any
60// content. Once content begins loading (via CWC::LoadUrl() or one of the
61// WebContents navigation APIs), CastWebContents will calculate its state based
62// on the status of the WebContents' *main* RenderFrame. Events from sub-frames
63// (e.g. iframes) are ignored, since we expect the web app to take care of
64// sub-frame errors.
65//
66// We consider the CastWebContents to be in a LOADED state when the content of
67// the main frame is fully loaded and running (all resources fetched, JS is
68// running). Iframes might still be loading in this case, but in general we
Sean Toppingeda675e2019-11-07 22:29:0469// consider the page to be in a presentable state at this stage, so it is
Sean Topping7414eed2019-04-10 23:04:2170// appropriate to display the WebContents to the user.
71//
72// During or after the page is loaded, there are multiple error conditions that
73// can occur. The following events will cause the page to enter an ERROR state:
74//
75// 1. If the main frame is served an HTTP error page (such as a 404 page), then
76// it means the desired content wasn't loaded.
77//
78// 2. If the main frame fails to load, such as when the browser blocked the URL
79// request, we treat this as an error.
80//
81// 3. The RenderProcess for the main frame could crash, so the page is not in a
82// usable state.
83//
84// The CastWebContents user can respond to these errors in a few ways: The
85// content can be reloaded, or the entire page activity can be cancelled. If we
86// totally cancel the activity, we prefer to notify the user with an error
87// screen or visible/audible error message. Otherwise, a silent retry is
88// preferred.
89//
90// CastWebContents can be used to close the underlying WebContents gracefully
91// via CWC::Close(). This initiates web page tear-down logic so that the web
92// app has a chance to perform its own finalization logic in JS. Next, we call
93// WebContents::ClosePage(), which defers the page closure logic to the
94// content::WebContentsDelegate. Usually, it will run its own finalization
95// logic and then destroy the WebContents. CastWebContents will be notified of
96// the WebContents destruction and enter the DESTROYED state. In the event
97// the page isn't destroyed, the page will enter the CLOSED state automatically
98// after a timeout. CastWebContents users should not try to reload the page, as
99// page closure is intentional.
100//
101// The web app may decide to close itself (such as via "window.close()" in JS).
102// This is similar to initiating the close flow via CWC::Close(), with the end
103// result being the same. We consider this an intentional closure, and should
104// not attempt to reload the page.
105//
106// Once CastWebContents is in the DESTROYED state, it is not really usable
107// anymore; most of the methods will simply no-op, and no more observer signals
108// will be emitted.
109//
110// CastWebContents can be deleted at any time, *except* during Observer
111// notifications. If the owner wants to destroy CastWebContents as a result of
112// an Observer event, it should post a task to destroy CastWebContents.
Sean Toppinge91b0972018-10-25 20:59:12113class CastWebContents {
114 public:
115 class Delegate {
116 public:
Sean Toppingf0a1d572019-06-17 23:03:44117 // Notify that an inner WebContents was created. |inner_contents| is created
118 // in a default-initialized state with no delegate, and can be safely
119 // initialized by the delegate.
120 virtual void InnerContentsCreated(CastWebContents* inner_contents,
121 CastWebContents* outer_contents) {}
122
123 protected:
124 virtual ~Delegate() {}
125 };
126
127 // Observer class. The Observer should *not* destroy CastWebContents during
128 // any of these events, otherwise other observers might try to use a freed
129 // pointer to |cast_web_contents|.
130 class Observer {
131 public:
132 Observer();
133
Sean Toppinge91b0972018-10-25 20:59:12134 // Advertises page state for the CastWebContents.
135 // Use CastWebContents::page_state() to get the new state.
Sean Toppingf0a1d572019-06-17 23:03:44136 virtual void OnPageStateChanged(CastWebContents* cast_web_contents) {}
Sean Toppinge91b0972018-10-25 20:59:12137
138 // Called when the page has stopped. e.g.: A 404 occurred when loading the
139 // page or if the render process for the main frame crashes. |error_code|
140 // will return a net::Error describing the failure, or net::OK if the page
Sean Topping7414eed2019-04-10 23:04:21141 // closed intentionally.
Sean Toppinge91b0972018-10-25 20:59:12142 //
143 // After this method, the page state will be one of the following:
Sean Topping7414eed2019-04-10 23:04:21144 // CLOSED: Page was closed as expected and the WebContents exists. The page
145 // should generally not be reloaded, since the page closure was
146 // triggered intentionally.
147 // ERROR: Page is in an error state. It should be reloaded or deleted.
Sean Toppinge91b0972018-10-25 20:59:12148 // DESTROYED: Page was closed due to deletion of WebContents. The
149 // CastWebContents instance is no longer usable and should be deleted.
Sean Toppinge91b0972018-10-25 20:59:12150 virtual void OnPageStopped(CastWebContents* cast_web_contents,
Sean Toppingf0a1d572019-06-17 23:03:44151 int error_code) {}
Sean Toppinge91b0972018-10-25 20:59:12152
Sean Toppingf0a1d572019-06-17 23:03:44153 // A new RenderFrame was created for the WebContents. |frame_interfaces| are
154 // provided by the new frame.
155 virtual void RenderFrameCreated(
156 int render_process_id,
157 int render_frame_id,
Sean Topping2d4e54e2019-06-25 00:04:04158 service_manager::InterfaceProvider* frame_interfaces,
159 blink::AssociatedInterfaceProvider* frame_associated_interfaces) {}
Chad Duffin4aa9c042019-01-11 00:51:55160
Jiawei Lic3354ee2019-12-13 23:48:35161 // A navigation has finished in the WebContents' main frame.
162 virtual void MainFrameFinishedNavigation() {}
163
Sean Toppingf0a1d572019-06-17 23:03:44164 // These methods are calls forwarded from WebContentsObserver.
165 virtual void MainFrameResized(const gfx::Rect& bounds) {}
166 virtual void UpdateTitle(const base::string16& title) {}
167 virtual void UpdateFaviconURL(GURL icon_url) {}
168 virtual void DidFinishBlockedNavigation(GURL url) {}
169 virtual void DidFirstVisuallyNonEmptyPaint() {}
Chad Duffin4aa9c042019-01-11 00:51:55170
Sean Topping7414eed2019-04-10 23:04:21171 // Notifies that a resource for the main frame failed to load.
172 virtual void ResourceLoadFailed(CastWebContents* cast_web_contents) {}
173
Zhaoxin2fe094a2020-02-11 23:35:45174 // Propagates the process information via observer, in particular to
175 // the underlying OnRendererProcessStarted() method.
176 virtual void OnRenderProcessReady(const base::Process& process) {}
177
Sean Toppinge8648a22020-04-29 18:41:00178 // Notify media playback state changes for the underlying WebContents.
179 virtual void MediaPlaybackChanged(bool media_playing) {}
180
Chad Duffin4aa9c042019-01-11 00:51:55181 // Adds |this| to the ObserverList in the implementation of
182 // |cast_web_contents|.
183 void Observe(CastWebContents* cast_web_contents);
184
185 // Removes |this| from the ObserverList in the implementation of
186 // |cast_web_contents_|. This is only invoked by CastWebContents and is used
187 // to ensure that once the observed CastWebContents object is destructed the
188 // CastWebContents::Observer does not invoke any additional function calls
189 // on it.
190 void ResetCastWebContents();
191
192 protected:
193 virtual ~Observer();
194
195 CastWebContents* cast_web_contents_;
196 };
197
Sean Toppingf0a1d572019-06-17 23:03:44198 enum class BackgroundColor {
199 NONE,
200 WHITE,
201 BLACK,
202 TRANSPARENT,
203 };
204
Sean Topping7414eed2019-04-10 23:04:21205 // Initialization parameters for CastWebContents.
Sean Topping0e8ac572019-01-30 03:05:43206 struct InitParams {
Sean Toppingeda675e2019-11-07 22:29:04207 // The delegate for the CastWebContents. Must be non-null. If the delegate
208 // is destroyed before CastWebContents, the WeakPtr will be invalidated on
209 // the main UI thread.
210 base::WeakPtr<Delegate> delegate = nullptr;
Jiawei Lia64a082b2019-12-06 21:17:26211 // Enable development mode for this CastWebContents. Whitelists
Sean Topping8a343862019-05-09 22:19:14212 // certain functionality for the WebContents, like remote debugging and
213 // debugging interfaces.
214 bool enabled_for_dev = false;
Sean Topping7414eed2019-04-10 23:04:21215 // Chooses a media renderer for the WebContents.
Chih-Hsuan Kuo7b4fb102020-03-04 08:21:49216 content::mojom::RendererType renderer_type =
217 content::mojom::RendererType::DEFAULT_RENDERER;
Sean Topping7414eed2019-04-10 23:04:21218 // Whether the WebContents is a root native window, or if it is embedded in
219 // another WebContents (see Delegate::InnerContentsCreated()).
Sean Topping6735aaf2019-03-20 19:20:12220 bool is_root_window = false;
Sean Topping8a343862019-05-09 22:19:14221 // Whether inner WebContents events should be handled. If this is set to
222 // true, then inner WebContents will automatically have a CastWebContents
223 // created and notify the delegate.
224 bool handle_inner_contents = false;
225 // Construct internal media blocker and enable BlockMediaLoading().
226 bool use_media_blocker = false;
Sean Toppingf0a1d572019-06-17 23:03:44227 // Background color for the WebContents view. If not provided, the color
228 // will fall back to the platform default.
229 BackgroundColor background_color = BackgroundColor::NONE;
Jiawei Lia64a082b2019-12-06 21:17:26230 // Enable WebSQL database for this CastWebContents.
231 bool enable_websql = false;
232 // Enable mixer audio support for this CastWebContents.
233 bool enable_mixer_audio = false;
Jiawei Li0565a2f2019-12-07 01:26:01234 // Whether to provide a QueryableDataHost for this CastWebContents.
235 // Clients can use it to send queryable values to the render frames.
236 // queryable_data_host() will return a nullptr if this is false.
237 bool enable_queryable_data_host = false;
Jiaqi Han9ea54f92020-02-20 23:44:59238 // Whether to provide a URL filter applied to network requests for the
239 // activity hosted by this CastWebContents.
240 // No filters implies no restrictions.
241 base::Optional<std::vector<std::string>> url_filters = base::nullopt;
Sean Toppingeda675e2019-11-07 22:29:04242
243 InitParams();
244 InitParams(const InitParams& other);
245 ~InitParams();
Sean Topping0e8ac572019-01-30 03:05:43246 };
247
Sean Toppinge91b0972018-10-25 20:59:12248 // Page state for the main frame.
249 enum class PageState {
250 IDLE, // Main frame has not started yet.
251 LOADING, // Main frame is loading resources.
252 LOADED, // Main frame is loaded, but sub-frames may still be loading.
253 CLOSED, // Page is closed and should be cleaned up.
254 DESTROYED, // The WebContents is destroyed and can no longer be used.
255 ERROR, // Main frame is in an error state.
256 };
257
Sean Topping6735aaf2019-03-20 19:20:12258 static std::vector<CastWebContents*>& GetAll();
259
Jiawei Lia64a082b2019-12-06 21:17:26260 // Returns the CastWebContents that wraps the content::WebContents, or nullptr
261 // if the CastWebContents does not exist.
262 static CastWebContents* FromWebContents(content::WebContents* web_contents);
263
Sean Toppinge91b0972018-10-25 20:59:12264 CastWebContents() = default;
265 virtual ~CastWebContents() = default;
266
Sean Topping6735aaf2019-03-20 19:20:12267 // Tab identifier for the WebContents, mainly used by the tabs extension API.
268 // Tab IDs may be re-used, but no two live CastWebContents should have the
269 // same tab ID at any given time.
270 virtual int tab_id() const = 0;
271
Sean Topping0e8ac572019-01-30 03:05:43272 // TODO(seantopping): Hide this, clients shouldn't use WebContents directly.
Sean Toppinge91b0972018-10-25 20:59:12273 virtual content::WebContents* web_contents() const = 0;
274 virtual PageState page_state() const = 0;
275
Jiawei Li0565a2f2019-12-07 01:26:01276 // Returns QueryableDataHost that is used to push values to the renderer.
277 // Returns nullptr if the new queryable data bindings is enabled.
278 virtual QueryableDataHost* queryable_data_host() const = 0;
279
Jiawei Lic3354ee2019-12-13 23:48:35280 // Returns the PID of the main frame process if valid.
281 virtual base::Optional<pid_t> GetMainFrameRenderProcessPid() const = 0;
282
Sean Topping0e8ac572019-01-30 03:05:43283 // ===========================================================================
284 // Initialization and Setup
285 // ===========================================================================
286
Sean Topping0e8ac572019-01-30 03:05:43287 // Add a set of features for all renderers in the WebContents. Features are
288 // configured when `CastWebContents::RenderFrameCreated` is invoked.
289 virtual void AddRendererFeatures(std::vector<RendererFeature> features) = 0;
290
291 virtual void AllowWebAndMojoWebUiBindings() = 0;
292 virtual void ClearRenderWidgetHostView() = 0;
293
294 // ===========================================================================
295 // Page Lifetime
296 // ===========================================================================
297
Sean Toppinge91b0972018-10-25 20:59:12298 // Navigates the underlying WebContents to |url|. Delegate will be notified of
299 // page progression events via OnPageStateChanged().
300 virtual void LoadUrl(const GURL& url) = 0;
301
302 // Initiate closure of the page. This invokes the appropriate unload handlers.
303 // Eventually the delegate will be notified with OnPageStopped().
304 virtual void ClosePage() = 0;
305
306 // Stop the page immediately. This will automatically invoke
307 // Delegate::OnPageStopped(error_code), allowing the delegate to delete or
Sean Topping7414eed2019-04-10 23:04:21308 // reload the page without waiting for the WebContents owner to tear down the
309 // page.
Sean Toppinge91b0972018-10-25 20:59:12310 virtual void Stop(int error_code) = 0;
311
Sean Topping8a343862019-05-09 22:19:14312 // ===========================================================================
Sean Toppinga0a0f5e2020-03-19 00:22:30313 // Visibility
314 // ===========================================================================
315
316 // Specify if the WebContents should be treated as visible. This triggers a
317 // document "visibilitychange" change event, and will paint the WebContents
318 // quad if |visible| is true (otherwise it will be blank). Note that this does
319 // *not* guarantee the page is visible on the screen, as that depends on if
320 // the WebContents quad is present in the screen layout and isn't obscured by
321 // another window.
322 virtual void SetWebVisibilityAndPaint(bool visible) = 0;
323
324 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14325 // Media Management
326 // ===========================================================================
327
328 // Block/unblock media from loading in all RenderFrames for the WebContents.
329 virtual void BlockMediaLoading(bool blocked) = 0;
Andres Medinaa65ad1b2019-06-26 22:18:19330 // Block/unblock media from starting in all RenderFrames for the WebContents.
331 // As opposed to |BlockMediaLoading|, |BlockMediaStarting| allows media to
332 // load while in blocking state.
333 virtual void BlockMediaStarting(bool blocked) = 0;
Sean Topping8a343862019-05-09 22:19:14334 virtual void EnableBackgroundVideoPlayback(bool enabled) = 0;
335
336 // ===========================================================================
Jiawei Lidf9ad18a2019-07-07 05:31:02337 // Page Communication
338 // ===========================================================================
339
Kevin Marshall6f8f04b2020-08-05 18:48:14340 // Returns the script injector instance, which injects scripts at page load
341 // time.
Kevin Marshall3f693812020-08-07 17:45:36342 virtual on_load_script_injector::OnLoadScriptInjectorHost<base::StringPiece>*
Kevin Marshall6f8f04b2020-08-05 18:48:14343 script_injector() = 0;
Jiawei Lidf9ad18a2019-07-07 05:31:02344
Kevin Marshall6f8f04b2020-08-05 18:48:14345 // Injects on-load scripts into the WebContents' main frame.
346 virtual void InjectScriptsIntoMainFrame() = 0;
Jiawei Lidf9ad18a2019-07-07 05:31:02347
Jiawei Libba76072019-07-29 23:00:25348 // Posts a message to the frame's onMessage handler.
349 //
350 // `target_origin` restricts message delivery to the specified origin.
351 // If `target_origin` is "*", then the message will be sent to the
352 // document regardless of its origin.
353 // See html.spec.whatwg.org/multipage/web-messaging.html sect. 9.4.3
354 // for more details on how the target origin policy is applied.
355 // Should be called on UI thread.
Chris Hamilton825f2ed2020-01-30 21:46:41356 virtual void PostMessageToMainFrame(
357 const std::string& target_origin,
358 const std::string& data,
359 std::vector<blink::WebMessagePort> ports) = 0;
Jiawei Libba76072019-07-29 23:00:25360
Jiawei Li5283ad42020-03-27 21:26:05361 // Executes a string of JavaScript in the main frame's context.
362 // This is no-op if the main frame is not available.
363 // Pass in a callback to receive a result when it is available.
364 // If there is no need to receive the result, pass in a
365 // default-constructed callback. If provided, the callback
366 // will be invoked on the UI thread.
367 virtual void ExecuteJavaScript(
368 const base::string16& javascript,
369 base::OnceCallback<void(base::Value)> callback) = 0;
370
Jiawei Lidf9ad18a2019-07-07 05:31:02371 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14372 // Utility Methods
373 // ===========================================================================
374
Chad Duffin4aa9c042019-01-11 00:51:55375 // Used to add or remove |observer| to the ObserverList in the implementation.
376 // These functions should only be invoked by CastWebContents::Observer in a
377 // valid sequence, enforced via SequenceChecker.
378 virtual void AddObserver(Observer* observer) = 0;
379 virtual void RemoveObserver(Observer* observer) = 0;
380
Ryan Daum52c9f7132020-04-06 21:23:34381 // Enable or disable devtools remote debugging for this WebContents and any
382 // inner WebContents that are spawned from it.
383 virtual void SetEnabledForRemoteDebugging(bool enabled) = 0;
384
Jiawei Li830fcfd2019-02-12 20:12:17385 // Used to expose CastWebContents's |binder_registry_| to Delegate.
386 // Delegate should register its mojo interface binders via this function
387 // when it is ready.
388 virtual service_manager::BinderRegistry* binder_registry() = 0;
389
Julie Jeongeun Kim641f4752019-12-04 01:53:22390 // Used for owner to pass its |InterfaceProvider| pointers to CastWebContents.
391 // It is owner's responsibility to make sure each |InterfaceProvider| pointer
392 // has distinct mojo interface set.
Jiawei Li830fcfd2019-02-12 20:12:17393 using InterfaceSet = base::flat_set<std::string>;
394 virtual void RegisterInterfaceProvider(
395 const InterfaceSet& interface_set,
396 service_manager::InterfaceProvider* interface_provider) = 0;
397
Jiawei Lia64a082b2019-12-06 21:17:26398 // Returns true if WebSQL database is configured enabled for this
399 // CastWebContents.
400 virtual bool is_websql_enabled() = 0;
401
402 // Returns true if mixer audio is enabled.
403 virtual bool is_mixer_audio_enabled() = 0;
404
Sean Toppingabf3be592020-03-11 23:20:35405 // Returns whether or not CastWebContents binder_registry() is valid for
406 // binding interfaces.
407 virtual bool can_bind_interfaces() = 0;
408
Sean Toppinge91b0972018-10-25 20:59:12409 private:
410 DISALLOW_COPY_AND_ASSIGN(CastWebContents);
411};
412
413std::ostream& operator<<(std::ostream& os, CastWebContents::PageState state);
414
415} // namespace chromecast
416
417#endif // CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_