blob: 323007c187a4b914d5f7bfc1c304f7e1c22bc502 [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"
Sean Toppingf0a1d572019-06-17 23:03:4415#include "base/strings/string16.h"
Jiawei Lidf9ad18a2019-07-07 05:31:0216#include "base/strings/string_piece_forward.h"
Chad Duffin4aa9c042019-01-11 00:51:5517#include "chromecast/common/mojom/feature_manager.mojom.h"
Jiawei Li830fcfd2019-02-12 20:12:1718#include "services/service_manager/public/cpp/binder_registry.h"
19#include "services/service_manager/public/cpp/interface_provider.h"
Chris Hamilton825f2ed2020-01-30 21:46:4120#include "third_party/blink/public/common/messaging/web_message_port.h"
Sean Toppingf0a1d572019-06-17 23:03:4421#include "ui/gfx/geometry/rect.h"
Sean Toppinge91b0972018-10-25 20:59:1222#include "url/gurl.h"
23
Sean Topping2d4e54e2019-06-25 00:04:0424namespace blink {
25class AssociatedInterfaceProvider;
26} // namespace blink
27
Sean Toppinge91b0972018-10-25 20:59:1228namespace content {
29class WebContents;
30} // namespace content
31
32namespace chromecast {
33
Jiawei Li0565a2f2019-12-07 01:26:0134class QueryableDataHost;
35
Sean Topping0e8ac572019-01-30 03:05:4336struct RendererFeature {
37 const std::string name;
38 base::Value value;
39};
40
Sean Toppinge91b0972018-10-25 20:59:1241// Simplified WebContents wrapper class for Cast platforms.
Sean Topping7414eed2019-04-10 23:04:2142//
43// Proper usage of content::WebContents relies on understanding the meaning
44// behind various WebContentsObserver methods, and then translating those
45// signals into some concrete state. CastWebContents does *not* own the
46// underlying WebContents (usually whatever class implements
47// content::WebContentsDelegate is the actual owner).
48//
49// =============================================================================
50// Lifetime
51// =============================================================================
52// CastWebContents *must* be created before WebContents begins loading any
53// content. Once content begins loading (via CWC::LoadUrl() or one of the
54// WebContents navigation APIs), CastWebContents will calculate its state based
55// on the status of the WebContents' *main* RenderFrame. Events from sub-frames
56// (e.g. iframes) are ignored, since we expect the web app to take care of
57// sub-frame errors.
58//
59// We consider the CastWebContents to be in a LOADED state when the content of
60// the main frame is fully loaded and running (all resources fetched, JS is
61// running). Iframes might still be loading in this case, but in general we
Sean Toppingeda675e2019-11-07 22:29:0462// consider the page to be in a presentable state at this stage, so it is
Sean Topping7414eed2019-04-10 23:04:2163// appropriate to display the WebContents to the user.
64//
65// During or after the page is loaded, there are multiple error conditions that
66// can occur. The following events will cause the page to enter an ERROR state:
67//
68// 1. If the main frame is served an HTTP error page (such as a 404 page), then
69// it means the desired content wasn't loaded.
70//
71// 2. If the main frame fails to load, such as when the browser blocked the URL
72// request, we treat this as an error.
73//
74// 3. The RenderProcess for the main frame could crash, so the page is not in a
75// usable state.
76//
77// The CastWebContents user can respond to these errors in a few ways: The
78// content can be reloaded, or the entire page activity can be cancelled. If we
79// totally cancel the activity, we prefer to notify the user with an error
80// screen or visible/audible error message. Otherwise, a silent retry is
81// preferred.
82//
83// CastWebContents can be used to close the underlying WebContents gracefully
84// via CWC::Close(). This initiates web page tear-down logic so that the web
85// app has a chance to perform its own finalization logic in JS. Next, we call
86// WebContents::ClosePage(), which defers the page closure logic to the
87// content::WebContentsDelegate. Usually, it will run its own finalization
88// logic and then destroy the WebContents. CastWebContents will be notified of
89// the WebContents destruction and enter the DESTROYED state. In the event
90// the page isn't destroyed, the page will enter the CLOSED state automatically
91// after a timeout. CastWebContents users should not try to reload the page, as
92// page closure is intentional.
93//
94// The web app may decide to close itself (such as via "window.close()" in JS).
95// This is similar to initiating the close flow via CWC::Close(), with the end
96// result being the same. We consider this an intentional closure, and should
97// not attempt to reload the page.
98//
99// Once CastWebContents is in the DESTROYED state, it is not really usable
100// anymore; most of the methods will simply no-op, and no more observer signals
101// will be emitted.
102//
103// CastWebContents can be deleted at any time, *except* during Observer
104// notifications. If the owner wants to destroy CastWebContents as a result of
105// an Observer event, it should post a task to destroy CastWebContents.
Sean Toppinge91b0972018-10-25 20:59:12106class CastWebContents {
107 public:
108 class Delegate {
109 public:
Sean Toppingf0a1d572019-06-17 23:03:44110 // Notify that an inner WebContents was created. |inner_contents| is created
111 // in a default-initialized state with no delegate, and can be safely
112 // initialized by the delegate.
113 virtual void InnerContentsCreated(CastWebContents* inner_contents,
114 CastWebContents* outer_contents) {}
115
116 protected:
117 virtual ~Delegate() {}
118 };
119
120 // Observer class. The Observer should *not* destroy CastWebContents during
121 // any of these events, otherwise other observers might try to use a freed
122 // pointer to |cast_web_contents|.
123 class Observer {
124 public:
125 Observer();
126
Sean Toppinge91b0972018-10-25 20:59:12127 // Advertises page state for the CastWebContents.
128 // Use CastWebContents::page_state() to get the new state.
Sean Toppingf0a1d572019-06-17 23:03:44129 virtual void OnPageStateChanged(CastWebContents* cast_web_contents) {}
Sean Toppinge91b0972018-10-25 20:59:12130
131 // Called when the page has stopped. e.g.: A 404 occurred when loading the
132 // page or if the render process for the main frame crashes. |error_code|
133 // will return a net::Error describing the failure, or net::OK if the page
Sean Topping7414eed2019-04-10 23:04:21134 // closed intentionally.
Sean Toppinge91b0972018-10-25 20:59:12135 //
136 // After this method, the page state will be one of the following:
Sean Topping7414eed2019-04-10 23:04:21137 // CLOSED: Page was closed as expected and the WebContents exists. The page
138 // should generally not be reloaded, since the page closure was
139 // triggered intentionally.
140 // ERROR: Page is in an error state. It should be reloaded or deleted.
Sean Toppinge91b0972018-10-25 20:59:12141 // DESTROYED: Page was closed due to deletion of WebContents. The
142 // CastWebContents instance is no longer usable and should be deleted.
Sean Toppinge91b0972018-10-25 20:59:12143 virtual void OnPageStopped(CastWebContents* cast_web_contents,
Sean Toppingf0a1d572019-06-17 23:03:44144 int error_code) {}
Sean Toppinge91b0972018-10-25 20:59:12145
Sean Toppingf0a1d572019-06-17 23:03:44146 // A new RenderFrame was created for the WebContents. |frame_interfaces| are
147 // provided by the new frame.
148 virtual void RenderFrameCreated(
149 int render_process_id,
150 int render_frame_id,
Sean Topping2d4e54e2019-06-25 00:04:04151 service_manager::InterfaceProvider* frame_interfaces,
152 blink::AssociatedInterfaceProvider* frame_associated_interfaces) {}
Chad Duffin4aa9c042019-01-11 00:51:55153
Jiawei Lic3354ee2019-12-13 23:48:35154 // A navigation has finished in the WebContents' main frame.
155 virtual void MainFrameFinishedNavigation() {}
156
Sean Toppingf0a1d572019-06-17 23:03:44157 // These methods are calls forwarded from WebContentsObserver.
158 virtual void MainFrameResized(const gfx::Rect& bounds) {}
159 virtual void UpdateTitle(const base::string16& title) {}
160 virtual void UpdateFaviconURL(GURL icon_url) {}
161 virtual void DidFinishBlockedNavigation(GURL url) {}
162 virtual void DidFirstVisuallyNonEmptyPaint() {}
Chad Duffin4aa9c042019-01-11 00:51:55163
Sean Topping7414eed2019-04-10 23:04:21164 // Notifies that a resource for the main frame failed to load.
165 virtual void ResourceLoadFailed(CastWebContents* cast_web_contents) {}
166
Chad Duffin4aa9c042019-01-11 00:51:55167 // Adds |this| to the ObserverList in the implementation of
168 // |cast_web_contents|.
169 void Observe(CastWebContents* cast_web_contents);
170
171 // Removes |this| from the ObserverList in the implementation of
172 // |cast_web_contents_|. This is only invoked by CastWebContents and is used
173 // to ensure that once the observed CastWebContents object is destructed the
174 // CastWebContents::Observer does not invoke any additional function calls
175 // on it.
176 void ResetCastWebContents();
177
178 protected:
179 virtual ~Observer();
180
181 CastWebContents* cast_web_contents_;
182 };
183
Sean Toppingf0a1d572019-06-17 23:03:44184 enum class BackgroundColor {
185 NONE,
186 WHITE,
187 BLACK,
188 TRANSPARENT,
189 };
190
Sean Topping7414eed2019-04-10 23:04:21191 // Initialization parameters for CastWebContents.
Sean Topping0e8ac572019-01-30 03:05:43192 struct InitParams {
Sean Toppingeda675e2019-11-07 22:29:04193 // The delegate for the CastWebContents. Must be non-null. If the delegate
194 // is destroyed before CastWebContents, the WeakPtr will be invalidated on
195 // the main UI thread.
196 base::WeakPtr<Delegate> delegate = nullptr;
Jiawei Lia64a082b2019-12-06 21:17:26197 // Enable development mode for this CastWebContents. Whitelists
Sean Topping8a343862019-05-09 22:19:14198 // certain functionality for the WebContents, like remote debugging and
199 // debugging interfaces.
200 bool enabled_for_dev = false;
Sean Topping7414eed2019-04-10 23:04:21201 // Chooses a media renderer for the WebContents.
Sean Topping8a343862019-05-09 22:19:14202 bool use_cma_renderer = false;
Sean Topping7414eed2019-04-10 23:04:21203 // Whether the WebContents is a root native window, or if it is embedded in
204 // another WebContents (see Delegate::InnerContentsCreated()).
Sean Topping6735aaf2019-03-20 19:20:12205 bool is_root_window = false;
Sean Topping8a343862019-05-09 22:19:14206 // Whether inner WebContents events should be handled. If this is set to
207 // true, then inner WebContents will automatically have a CastWebContents
208 // created and notify the delegate.
209 bool handle_inner_contents = false;
210 // Construct internal media blocker and enable BlockMediaLoading().
211 bool use_media_blocker = false;
Sean Toppingf0a1d572019-06-17 23:03:44212 // Background color for the WebContents view. If not provided, the color
213 // will fall back to the platform default.
214 BackgroundColor background_color = BackgroundColor::NONE;
Jiawei Lia64a082b2019-12-06 21:17:26215 // Enable WebSQL database for this CastWebContents.
216 bool enable_websql = false;
217 // Enable mixer audio support for this CastWebContents.
218 bool enable_mixer_audio = false;
Jiawei Li0565a2f2019-12-07 01:26:01219 // Whether to provide a QueryableDataHost for this CastWebContents.
220 // Clients can use it to send queryable values to the render frames.
221 // queryable_data_host() will return a nullptr if this is false.
222 bool enable_queryable_data_host = false;
Sean Toppingeda675e2019-11-07 22:29:04223
224 InitParams();
225 InitParams(const InitParams& other);
226 ~InitParams();
Sean Topping0e8ac572019-01-30 03:05:43227 };
228
Sean Toppinge91b0972018-10-25 20:59:12229 // Page state for the main frame.
230 enum class PageState {
231 IDLE, // Main frame has not started yet.
232 LOADING, // Main frame is loading resources.
233 LOADED, // Main frame is loaded, but sub-frames may still be loading.
234 CLOSED, // Page is closed and should be cleaned up.
235 DESTROYED, // The WebContents is destroyed and can no longer be used.
236 ERROR, // Main frame is in an error state.
237 };
238
Sean Topping6735aaf2019-03-20 19:20:12239 static std::vector<CastWebContents*>& GetAll();
240
Jiawei Lia64a082b2019-12-06 21:17:26241 // Returns the CastWebContents that wraps the content::WebContents, or nullptr
242 // if the CastWebContents does not exist.
243 static CastWebContents* FromWebContents(content::WebContents* web_contents);
244
Sean Toppinge91b0972018-10-25 20:59:12245 CastWebContents() = default;
246 virtual ~CastWebContents() = default;
247
Sean Topping6735aaf2019-03-20 19:20:12248 // Tab identifier for the WebContents, mainly used by the tabs extension API.
249 // Tab IDs may be re-used, but no two live CastWebContents should have the
250 // same tab ID at any given time.
251 virtual int tab_id() const = 0;
252
Sean Topping0e8ac572019-01-30 03:05:43253 // TODO(seantopping): Hide this, clients shouldn't use WebContents directly.
Sean Toppinge91b0972018-10-25 20:59:12254 virtual content::WebContents* web_contents() const = 0;
255 virtual PageState page_state() const = 0;
256
Jiawei Li0565a2f2019-12-07 01:26:01257 // Returns QueryableDataHost that is used to push values to the renderer.
258 // Returns nullptr if the new queryable data bindings is enabled.
259 virtual QueryableDataHost* queryable_data_host() const = 0;
260
Jiawei Lic3354ee2019-12-13 23:48:35261 // Returns the PID of the main frame process if valid.
262 virtual base::Optional<pid_t> GetMainFrameRenderProcessPid() const = 0;
263
Sean Topping0e8ac572019-01-30 03:05:43264 // ===========================================================================
265 // Initialization and Setup
266 // ===========================================================================
267
Sean Topping0e8ac572019-01-30 03:05:43268 // Add a set of features for all renderers in the WebContents. Features are
269 // configured when `CastWebContents::RenderFrameCreated` is invoked.
270 virtual void AddRendererFeatures(std::vector<RendererFeature> features) = 0;
271
272 virtual void AllowWebAndMojoWebUiBindings() = 0;
273 virtual void ClearRenderWidgetHostView() = 0;
274
275 // ===========================================================================
276 // Page Lifetime
277 // ===========================================================================
278
Sean Toppinge91b0972018-10-25 20:59:12279 // Navigates the underlying WebContents to |url|. Delegate will be notified of
280 // page progression events via OnPageStateChanged().
281 virtual void LoadUrl(const GURL& url) = 0;
282
283 // Initiate closure of the page. This invokes the appropriate unload handlers.
284 // Eventually the delegate will be notified with OnPageStopped().
285 virtual void ClosePage() = 0;
286
287 // Stop the page immediately. This will automatically invoke
288 // Delegate::OnPageStopped(error_code), allowing the delegate to delete or
Sean Topping7414eed2019-04-10 23:04:21289 // reload the page without waiting for the WebContents owner to tear down the
290 // page.
Sean Toppinge91b0972018-10-25 20:59:12291 virtual void Stop(int error_code) = 0;
292
Sean Topping8a343862019-05-09 22:19:14293 // ===========================================================================
Sean Topping6d514082020-02-11 03:10:33294 // Visibility
295 // ===========================================================================
296
297 // Specify if the WebContents should be treated as visible. This triggers a
298 // document "visibilitychange" change event, and will paint the WebContents
299 // quad if |visible| is true (otherwise it will be blank). Note that this does
300 // *not* guarantee the page is visible on the screen, as that depends on if
301 // the WebContents quad is present in the screen layout and isn't obscured by
302 // another window.
303 virtual void SetWebVisibilityAndPaint(bool visible) = 0;
304
305 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14306 // Media Management
307 // ===========================================================================
308
309 // Block/unblock media from loading in all RenderFrames for the WebContents.
310 virtual void BlockMediaLoading(bool blocked) = 0;
Andres Medinaa65ad1b2019-06-26 22:18:19311 // Block/unblock media from starting in all RenderFrames for the WebContents.
312 // As opposed to |BlockMediaLoading|, |BlockMediaStarting| allows media to
313 // load while in blocking state.
314 virtual void BlockMediaStarting(bool blocked) = 0;
Sean Topping8a343862019-05-09 22:19:14315 virtual void EnableBackgroundVideoPlayback(bool enabled) = 0;
316
317 // ===========================================================================
Jiawei Lidf9ad18a2019-07-07 05:31:02318 // Page Communication
319 // ===========================================================================
320
321 // Executes a UTF-8 encoded |script| for every subsequent page load where
322 // the frame's URL has an origin reflected in |origins|. The script is
323 // executed early, prior to the execution of the document's scripts.
324 //
325 // Scripts are identified by a string-based client-managed |id|. Any
326 // script previously injected using the same |id| will be replaced.
327 //
328 // The order in which multiple bindings are executed is the same as the
329 // order in which the bindings were Added. If a script is added which
330 // clobbers an existing script of the same |id|, the previous script's
331 // precedence in the injection order will be preserved.
332 // |script| and |id| must be non-empty string.
333 //
334 // At least one |origins| entry must be specified.
335 // If a wildcard "*" is specified in |origins|, then the script will be
336 // evaluated for all documents.
337 virtual void AddBeforeLoadJavaScript(base::StringPiece id,
338 const std::vector<std::string>& origins,
339 base::StringPiece script) = 0;
340
341 // Removes a previously added JavaScript snippet identified by |id|.
342 // This is a no-op if there is no JavaScript snippet identified by |id|.
343 virtual void RemoveBeforeLoadJavaScript(base::StringPiece id) = 0;
344
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 // TODO(crbug.com/803242): Deprecated and will be shortly removed.
Jiawei Libba76072019-07-29 23:00:25354 virtual void PostMessageToMainFrame(
355 const std::string& target_origin,
356 const std::string& data,
357 std::vector<mojo::ScopedMessagePipeHandle> channels) = 0;
Chris Hamilton825f2ed2020-01-30 21:46:41358 virtual void PostMessageToMainFrame(
359 const std::string& target_origin,
360 const std::string& data,
361 std::vector<blink::WebMessagePort> ports) = 0;
Jiawei Libba76072019-07-29 23:00:25362
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
Jiawei Li830fcfd2019-02-12 20:12:17373 // Used to expose CastWebContents's |binder_registry_| to Delegate.
374 // Delegate should register its mojo interface binders via this function
375 // when it is ready.
376 virtual service_manager::BinderRegistry* binder_registry() = 0;
377
Julie Jeongeun Kim641f4752019-12-04 01:53:22378 // Used for owner to pass its |InterfaceProvider| pointers to CastWebContents.
379 // It is owner's responsibility to make sure each |InterfaceProvider| pointer
380 // has distinct mojo interface set.
Jiawei Li830fcfd2019-02-12 20:12:17381 using InterfaceSet = base::flat_set<std::string>;
382 virtual void RegisterInterfaceProvider(
383 const InterfaceSet& interface_set,
384 service_manager::InterfaceProvider* interface_provider) = 0;
385
Jiawei Lia64a082b2019-12-06 21:17:26386 // Returns true if WebSQL database is configured enabled for this
387 // CastWebContents.
388 virtual bool is_websql_enabled() = 0;
389
390 // Returns true if mixer audio is enabled.
391 virtual bool is_mixer_audio_enabled() = 0;
392
Sean Toppinge91b0972018-10-25 20:59:12393 private:
394 DISALLOW_COPY_AND_ASSIGN(CastWebContents);
395};
396
397std::ostream& operator<<(std::ostream& os, CastWebContents::PageState state);
398
399} // namespace chromecast
400
401#endif // CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_