blob: 7376fa7337b50d664ec6040d9a7513e48502f141 [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
34namespace chromecast {
35
Jiawei Li0565a2f2019-12-07 01:26:0136class QueryableDataHost;
37
Sean Topping0e8ac572019-01-30 03:05:4338struct RendererFeature {
39 const std::string name;
40 base::Value value;
41};
42
Sean Toppinge91b0972018-10-25 20:59:1243// Simplified WebContents wrapper class for Cast platforms.
Sean Topping7414eed2019-04-10 23:04:2144//
45// Proper usage of content::WebContents relies on understanding the meaning
46// behind various WebContentsObserver methods, and then translating those
47// signals into some concrete state. CastWebContents does *not* own the
48// underlying WebContents (usually whatever class implements
49// content::WebContentsDelegate is the actual owner).
50//
51// =============================================================================
52// Lifetime
53// =============================================================================
54// CastWebContents *must* be created before WebContents begins loading any
55// content. Once content begins loading (via CWC::LoadUrl() or one of the
56// WebContents navigation APIs), CastWebContents will calculate its state based
57// on the status of the WebContents' *main* RenderFrame. Events from sub-frames
58// (e.g. iframes) are ignored, since we expect the web app to take care of
59// sub-frame errors.
60//
61// We consider the CastWebContents to be in a LOADED state when the content of
62// the main frame is fully loaded and running (all resources fetched, JS is
63// running). Iframes might still be loading in this case, but in general we
Sean Toppingeda675e2019-11-07 22:29:0464// consider the page to be in a presentable state at this stage, so it is
Sean Topping7414eed2019-04-10 23:04:2165// appropriate to display the WebContents to the user.
66//
67// During or after the page is loaded, there are multiple error conditions that
68// can occur. The following events will cause the page to enter an ERROR state:
69//
70// 1. If the main frame is served an HTTP error page (such as a 404 page), then
71// it means the desired content wasn't loaded.
72//
73// 2. If the main frame fails to load, such as when the browser blocked the URL
74// request, we treat this as an error.
75//
76// 3. The RenderProcess for the main frame could crash, so the page is not in a
77// usable state.
78//
79// The CastWebContents user can respond to these errors in a few ways: The
80// content can be reloaded, or the entire page activity can be cancelled. If we
81// totally cancel the activity, we prefer to notify the user with an error
82// screen or visible/audible error message. Otherwise, a silent retry is
83// preferred.
84//
85// CastWebContents can be used to close the underlying WebContents gracefully
86// via CWC::Close(). This initiates web page tear-down logic so that the web
87// app has a chance to perform its own finalization logic in JS. Next, we call
88// WebContents::ClosePage(), which defers the page closure logic to the
89// content::WebContentsDelegate. Usually, it will run its own finalization
90// logic and then destroy the WebContents. CastWebContents will be notified of
91// the WebContents destruction and enter the DESTROYED state. In the event
92// the page isn't destroyed, the page will enter the CLOSED state automatically
93// after a timeout. CastWebContents users should not try to reload the page, as
94// page closure is intentional.
95//
96// The web app may decide to close itself (such as via "window.close()" in JS).
97// This is similar to initiating the close flow via CWC::Close(), with the end
98// result being the same. We consider this an intentional closure, and should
99// not attempt to reload the page.
100//
101// Once CastWebContents is in the DESTROYED state, it is not really usable
102// anymore; most of the methods will simply no-op, and no more observer signals
103// will be emitted.
104//
105// CastWebContents can be deleted at any time, *except* during Observer
106// notifications. If the owner wants to destroy CastWebContents as a result of
107// an Observer event, it should post a task to destroy CastWebContents.
Sean Toppinge91b0972018-10-25 20:59:12108class CastWebContents {
109 public:
110 class Delegate {
111 public:
Sean Toppingf0a1d572019-06-17 23:03:44112 // Notify that an inner WebContents was created. |inner_contents| is created
113 // in a default-initialized state with no delegate, and can be safely
114 // initialized by the delegate.
115 virtual void InnerContentsCreated(CastWebContents* inner_contents,
116 CastWebContents* outer_contents) {}
117
118 protected:
119 virtual ~Delegate() {}
120 };
121
122 // Observer class. The Observer should *not* destroy CastWebContents during
123 // any of these events, otherwise other observers might try to use a freed
124 // pointer to |cast_web_contents|.
125 class Observer {
126 public:
127 Observer();
128
Sean Toppinge91b0972018-10-25 20:59:12129 // Advertises page state for the CastWebContents.
130 // Use CastWebContents::page_state() to get the new state.
Sean Toppingf0a1d572019-06-17 23:03:44131 virtual void OnPageStateChanged(CastWebContents* cast_web_contents) {}
Sean Toppinge91b0972018-10-25 20:59:12132
133 // Called when the page has stopped. e.g.: A 404 occurred when loading the
134 // page or if the render process for the main frame crashes. |error_code|
135 // will return a net::Error describing the failure, or net::OK if the page
Sean Topping7414eed2019-04-10 23:04:21136 // closed intentionally.
Sean Toppinge91b0972018-10-25 20:59:12137 //
138 // After this method, the page state will be one of the following:
Sean Topping7414eed2019-04-10 23:04:21139 // CLOSED: Page was closed as expected and the WebContents exists. The page
140 // should generally not be reloaded, since the page closure was
141 // triggered intentionally.
142 // ERROR: Page is in an error state. It should be reloaded or deleted.
Sean Toppinge91b0972018-10-25 20:59:12143 // DESTROYED: Page was closed due to deletion of WebContents. The
144 // CastWebContents instance is no longer usable and should be deleted.
Sean Toppinge91b0972018-10-25 20:59:12145 virtual void OnPageStopped(CastWebContents* cast_web_contents,
Sean Toppingf0a1d572019-06-17 23:03:44146 int error_code) {}
Sean Toppinge91b0972018-10-25 20:59:12147
Sean Toppingf0a1d572019-06-17 23:03:44148 // A new RenderFrame was created for the WebContents. |frame_interfaces| are
149 // provided by the new frame.
150 virtual void RenderFrameCreated(
151 int render_process_id,
152 int render_frame_id,
Sean Topping2d4e54e2019-06-25 00:04:04153 service_manager::InterfaceProvider* frame_interfaces,
154 blink::AssociatedInterfaceProvider* frame_associated_interfaces) {}
Chad Duffin4aa9c042019-01-11 00:51:55155
Jiawei Lic3354ee2019-12-13 23:48:35156 // A navigation has finished in the WebContents' main frame.
157 virtual void MainFrameFinishedNavigation() {}
158
Sean Toppingf0a1d572019-06-17 23:03:44159 // These methods are calls forwarded from WebContentsObserver.
160 virtual void MainFrameResized(const gfx::Rect& bounds) {}
161 virtual void UpdateTitle(const base::string16& title) {}
162 virtual void UpdateFaviconURL(GURL icon_url) {}
163 virtual void DidFinishBlockedNavigation(GURL url) {}
164 virtual void DidFirstVisuallyNonEmptyPaint() {}
Chad Duffin4aa9c042019-01-11 00:51:55165
Sean Topping7414eed2019-04-10 23:04:21166 // Notifies that a resource for the main frame failed to load.
167 virtual void ResourceLoadFailed(CastWebContents* cast_web_contents) {}
168
Zhaoxin2fe094a2020-02-11 23:35:45169 // Propagates the process information via observer, in particular to
170 // the underlying OnRendererProcessStarted() method.
171 virtual void OnRenderProcessReady(const base::Process& process) {}
172
Chad Duffin4aa9c042019-01-11 00:51:55173 // Adds |this| to the ObserverList in the implementation of
174 // |cast_web_contents|.
175 void Observe(CastWebContents* cast_web_contents);
176
177 // Removes |this| from the ObserverList in the implementation of
178 // |cast_web_contents_|. This is only invoked by CastWebContents and is used
179 // to ensure that once the observed CastWebContents object is destructed the
180 // CastWebContents::Observer does not invoke any additional function calls
181 // on it.
182 void ResetCastWebContents();
183
184 protected:
185 virtual ~Observer();
186
187 CastWebContents* cast_web_contents_;
188 };
189
Sean Toppingf0a1d572019-06-17 23:03:44190 enum class BackgroundColor {
191 NONE,
192 WHITE,
193 BLACK,
194 TRANSPARENT,
195 };
196
Sean Topping7414eed2019-04-10 23:04:21197 // Initialization parameters for CastWebContents.
Sean Topping0e8ac572019-01-30 03:05:43198 struct InitParams {
Sean Toppingeda675e2019-11-07 22:29:04199 // The delegate for the CastWebContents. Must be non-null. If the delegate
200 // is destroyed before CastWebContents, the WeakPtr will be invalidated on
201 // the main UI thread.
202 base::WeakPtr<Delegate> delegate = nullptr;
Jiawei Lia64a082b2019-12-06 21:17:26203 // Enable development mode for this CastWebContents. Whitelists
Sean Topping8a343862019-05-09 22:19:14204 // certain functionality for the WebContents, like remote debugging and
205 // debugging interfaces.
206 bool enabled_for_dev = false;
Sean Topping7414eed2019-04-10 23:04:21207 // Chooses a media renderer for the WebContents.
Chih-Hsuan Kuo7b4fb102020-03-04 08:21:49208 content::mojom::RendererType renderer_type =
209 content::mojom::RendererType::DEFAULT_RENDERER;
Sean Topping7414eed2019-04-10 23:04:21210 // Whether the WebContents is a root native window, or if it is embedded in
211 // another WebContents (see Delegate::InnerContentsCreated()).
Sean Topping6735aaf2019-03-20 19:20:12212 bool is_root_window = false;
Sean Topping8a343862019-05-09 22:19:14213 // Whether inner WebContents events should be handled. If this is set to
214 // true, then inner WebContents will automatically have a CastWebContents
215 // created and notify the delegate.
216 bool handle_inner_contents = false;
217 // Construct internal media blocker and enable BlockMediaLoading().
218 bool use_media_blocker = false;
Sean Toppingf0a1d572019-06-17 23:03:44219 // Background color for the WebContents view. If not provided, the color
220 // will fall back to the platform default.
221 BackgroundColor background_color = BackgroundColor::NONE;
Jiawei Lia64a082b2019-12-06 21:17:26222 // Enable WebSQL database for this CastWebContents.
223 bool enable_websql = false;
224 // Enable mixer audio support for this CastWebContents.
225 bool enable_mixer_audio = false;
Jiawei Li0565a2f2019-12-07 01:26:01226 // Whether to provide a QueryableDataHost for this CastWebContents.
227 // Clients can use it to send queryable values to the render frames.
228 // queryable_data_host() will return a nullptr if this is false.
229 bool enable_queryable_data_host = 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;
Sean Toppingeda675e2019-11-07 22:29:04234
235 InitParams();
236 InitParams(const InitParams& other);
237 ~InitParams();
Sean Topping0e8ac572019-01-30 03:05:43238 };
239
Sean Toppinge91b0972018-10-25 20:59:12240 // Page state for the main frame.
241 enum class PageState {
242 IDLE, // Main frame has not started yet.
243 LOADING, // Main frame is loading resources.
244 LOADED, // Main frame is loaded, but sub-frames may still be loading.
245 CLOSED, // Page is closed and should be cleaned up.
246 DESTROYED, // The WebContents is destroyed and can no longer be used.
247 ERROR, // Main frame is in an error state.
248 };
249
Sean Topping6735aaf2019-03-20 19:20:12250 static std::vector<CastWebContents*>& GetAll();
251
Jiawei Lia64a082b2019-12-06 21:17:26252 // Returns the CastWebContents that wraps the content::WebContents, or nullptr
253 // if the CastWebContents does not exist.
254 static CastWebContents* FromWebContents(content::WebContents* web_contents);
255
Sean Toppinge91b0972018-10-25 20:59:12256 CastWebContents() = default;
257 virtual ~CastWebContents() = default;
258
Sean Topping6735aaf2019-03-20 19:20:12259 // Tab identifier for the WebContents, mainly used by the tabs extension API.
260 // Tab IDs may be re-used, but no two live CastWebContents should have the
261 // same tab ID at any given time.
262 virtual int tab_id() const = 0;
263
Sean Topping0e8ac572019-01-30 03:05:43264 // TODO(seantopping): Hide this, clients shouldn't use WebContents directly.
Sean Toppinge91b0972018-10-25 20:59:12265 virtual content::WebContents* web_contents() const = 0;
266 virtual PageState page_state() const = 0;
267
Jiawei Li0565a2f2019-12-07 01:26:01268 // Returns QueryableDataHost that is used to push values to the renderer.
269 // Returns nullptr if the new queryable data bindings is enabled.
270 virtual QueryableDataHost* queryable_data_host() const = 0;
271
Jiawei Lic3354ee2019-12-13 23:48:35272 // Returns the PID of the main frame process if valid.
273 virtual base::Optional<pid_t> GetMainFrameRenderProcessPid() const = 0;
274
Sean Topping0e8ac572019-01-30 03:05:43275 // ===========================================================================
276 // Initialization and Setup
277 // ===========================================================================
278
Sean Topping0e8ac572019-01-30 03:05:43279 // Add a set of features for all renderers in the WebContents. Features are
280 // configured when `CastWebContents::RenderFrameCreated` is invoked.
281 virtual void AddRendererFeatures(std::vector<RendererFeature> features) = 0;
282
283 virtual void AllowWebAndMojoWebUiBindings() = 0;
284 virtual void ClearRenderWidgetHostView() = 0;
285
286 // ===========================================================================
287 // Page Lifetime
288 // ===========================================================================
289
Sean Toppinge91b0972018-10-25 20:59:12290 // Navigates the underlying WebContents to |url|. Delegate will be notified of
291 // page progression events via OnPageStateChanged().
292 virtual void LoadUrl(const GURL& url) = 0;
293
294 // Initiate closure of the page. This invokes the appropriate unload handlers.
295 // Eventually the delegate will be notified with OnPageStopped().
296 virtual void ClosePage() = 0;
297
298 // Stop the page immediately. This will automatically invoke
299 // Delegate::OnPageStopped(error_code), allowing the delegate to delete or
Sean Topping7414eed2019-04-10 23:04:21300 // reload the page without waiting for the WebContents owner to tear down the
301 // page.
Sean Toppinge91b0972018-10-25 20:59:12302 virtual void Stop(int error_code) = 0;
303
Sean Topping8a343862019-05-09 22:19:14304 // ===========================================================================
305 // Media Management
306 // ===========================================================================
307
308 // Block/unblock media from loading in all RenderFrames for the WebContents.
309 virtual void BlockMediaLoading(bool blocked) = 0;
Andres Medinaa65ad1b2019-06-26 22:18:19310 // Block/unblock media from starting in all RenderFrames for the WebContents.
311 // As opposed to |BlockMediaLoading|, |BlockMediaStarting| allows media to
312 // load while in blocking state.
313 virtual void BlockMediaStarting(bool blocked) = 0;
Sean Topping8a343862019-05-09 22:19:14314 virtual void EnableBackgroundVideoPlayback(bool enabled) = 0;
315
316 // ===========================================================================
Jiawei Lidf9ad18a2019-07-07 05:31:02317 // Page Communication
318 // ===========================================================================
319
320 // Executes a UTF-8 encoded |script| for every subsequent page load where
321 // the frame's URL has an origin reflected in |origins|. The script is
322 // executed early, prior to the execution of the document's scripts.
323 //
324 // Scripts are identified by a string-based client-managed |id|. Any
325 // script previously injected using the same |id| will be replaced.
326 //
327 // The order in which multiple bindings are executed is the same as the
328 // order in which the bindings were Added. If a script is added which
329 // clobbers an existing script of the same |id|, the previous script's
330 // precedence in the injection order will be preserved.
331 // |script| and |id| must be non-empty string.
332 //
333 // At least one |origins| entry must be specified.
334 // If a wildcard "*" is specified in |origins|, then the script will be
335 // evaluated for all documents.
336 virtual void AddBeforeLoadJavaScript(base::StringPiece id,
337 const std::vector<std::string>& origins,
338 base::StringPiece script) = 0;
339
340 // Removes a previously added JavaScript snippet identified by |id|.
341 // This is a no-op if there is no JavaScript snippet identified by |id|.
342 virtual void RemoveBeforeLoadJavaScript(base::StringPiece id) = 0;
343
Jiawei Libba76072019-07-29 23:00:25344 // Posts a message to the frame's onMessage handler.
345 //
346 // `target_origin` restricts message delivery to the specified origin.
347 // If `target_origin` is "*", then the message will be sent to the
348 // document regardless of its origin.
349 // See html.spec.whatwg.org/multipage/web-messaging.html sect. 9.4.3
350 // for more details on how the target origin policy is applied.
351 // Should be called on UI thread.
Chris Hamilton825f2ed2020-01-30 21:46:41352 // TODO(crbug.com/803242): Deprecated and will be shortly removed.
Jiawei Libba76072019-07-29 23:00:25353 virtual void PostMessageToMainFrame(
354 const std::string& target_origin,
355 const std::string& data,
356 std::vector<mojo::ScopedMessagePipeHandle> channels) = 0;
Chris Hamilton825f2ed2020-01-30 21:46:41357 virtual void PostMessageToMainFrame(
358 const std::string& target_origin,
359 const std::string& data,
360 std::vector<blink::WebMessagePort> ports) = 0;
Jiawei Libba76072019-07-29 23:00:25361
Jiawei Lidf9ad18a2019-07-07 05:31:02362 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14363 // Utility Methods
364 // ===========================================================================
365
Chad Duffin4aa9c042019-01-11 00:51:55366 // Used to add or remove |observer| to the ObserverList in the implementation.
367 // These functions should only be invoked by CastWebContents::Observer in a
368 // valid sequence, enforced via SequenceChecker.
369 virtual void AddObserver(Observer* observer) = 0;
370 virtual void RemoveObserver(Observer* observer) = 0;
371
Jiawei Li830fcfd2019-02-12 20:12:17372 // Used to expose CastWebContents's |binder_registry_| to Delegate.
373 // Delegate should register its mojo interface binders via this function
374 // when it is ready.
375 virtual service_manager::BinderRegistry* binder_registry() = 0;
376
Julie Jeongeun Kim641f4752019-12-04 01:53:22377 // Used for owner to pass its |InterfaceProvider| pointers to CastWebContents.
378 // It is owner's responsibility to make sure each |InterfaceProvider| pointer
379 // has distinct mojo interface set.
Jiawei Li830fcfd2019-02-12 20:12:17380 using InterfaceSet = base::flat_set<std::string>;
381 virtual void RegisterInterfaceProvider(
382 const InterfaceSet& interface_set,
383 service_manager::InterfaceProvider* interface_provider) = 0;
384
Jiawei Lia64a082b2019-12-06 21:17:26385 // Returns true if WebSQL database is configured enabled for this
386 // CastWebContents.
387 virtual bool is_websql_enabled() = 0;
388
389 // Returns true if mixer audio is enabled.
390 virtual bool is_mixer_audio_enabled() = 0;
391
Sean Toppinge91b0972018-10-25 20:59:12392 private:
393 DISALLOW_COPY_AND_ASSIGN(CastWebContents);
394};
395
396std::ostream& operator<<(std::ostream& os, CastWebContents::PageState state);
397
398} // namespace chromecast
399
400#endif // CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_