blob: a4df057ab568b6825e124189c1c7a3b07af81322 [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"
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
33namespace chromecast {
34
Jiawei Li0565a2f2019-12-07 01:26:0135class QueryableDataHost;
36
Sean Topping0e8ac572019-01-30 03:05:4337struct RendererFeature {
38 const std::string name;
39 base::Value value;
40};
41
Sean Toppinge91b0972018-10-25 20:59:1242// Simplified WebContents wrapper class for Cast platforms.
Sean Topping7414eed2019-04-10 23:04:2143//
44// Proper usage of content::WebContents relies on understanding the meaning
45// behind various WebContentsObserver methods, and then translating those
46// signals into some concrete state. CastWebContents does *not* own the
47// underlying WebContents (usually whatever class implements
48// content::WebContentsDelegate is the actual owner).
49//
50// =============================================================================
51// Lifetime
52// =============================================================================
53// CastWebContents *must* be created before WebContents begins loading any
54// content. Once content begins loading (via CWC::LoadUrl() or one of the
55// WebContents navigation APIs), CastWebContents will calculate its state based
56// on the status of the WebContents' *main* RenderFrame. Events from sub-frames
57// (e.g. iframes) are ignored, since we expect the web app to take care of
58// sub-frame errors.
59//
60// We consider the CastWebContents to be in a LOADED state when the content of
61// the main frame is fully loaded and running (all resources fetched, JS is
62// running). Iframes might still be loading in this case, but in general we
Sean Toppingeda675e2019-11-07 22:29:0463// consider the page to be in a presentable state at this stage, so it is
Sean Topping7414eed2019-04-10 23:04:2164// appropriate to display the WebContents to the user.
65//
66// During or after the page is loaded, there are multiple error conditions that
67// can occur. The following events will cause the page to enter an ERROR state:
68//
69// 1. If the main frame is served an HTTP error page (such as a 404 page), then
70// it means the desired content wasn't loaded.
71//
72// 2. If the main frame fails to load, such as when the browser blocked the URL
73// request, we treat this as an error.
74//
75// 3. The RenderProcess for the main frame could crash, so the page is not in a
76// usable state.
77//
78// The CastWebContents user can respond to these errors in a few ways: The
79// content can be reloaded, or the entire page activity can be cancelled. If we
80// totally cancel the activity, we prefer to notify the user with an error
81// screen or visible/audible error message. Otherwise, a silent retry is
82// preferred.
83//
84// CastWebContents can be used to close the underlying WebContents gracefully
85// via CWC::Close(). This initiates web page tear-down logic so that the web
86// app has a chance to perform its own finalization logic in JS. Next, we call
87// WebContents::ClosePage(), which defers the page closure logic to the
88// content::WebContentsDelegate. Usually, it will run its own finalization
89// logic and then destroy the WebContents. CastWebContents will be notified of
90// the WebContents destruction and enter the DESTROYED state. In the event
91// the page isn't destroyed, the page will enter the CLOSED state automatically
92// after a timeout. CastWebContents users should not try to reload the page, as
93// page closure is intentional.
94//
95// The web app may decide to close itself (such as via "window.close()" in JS).
96// This is similar to initiating the close flow via CWC::Close(), with the end
97// result being the same. We consider this an intentional closure, and should
98// not attempt to reload the page.
99//
100// Once CastWebContents is in the DESTROYED state, it is not really usable
101// anymore; most of the methods will simply no-op, and no more observer signals
102// will be emitted.
103//
104// CastWebContents can be deleted at any time, *except* during Observer
105// notifications. If the owner wants to destroy CastWebContents as a result of
106// an Observer event, it should post a task to destroy CastWebContents.
Sean Toppinge91b0972018-10-25 20:59:12107class CastWebContents {
108 public:
109 class Delegate {
110 public:
Sean Toppingf0a1d572019-06-17 23:03:44111 // Notify that an inner WebContents was created. |inner_contents| is created
112 // in a default-initialized state with no delegate, and can be safely
113 // initialized by the delegate.
114 virtual void InnerContentsCreated(CastWebContents* inner_contents,
115 CastWebContents* outer_contents) {}
116
117 protected:
118 virtual ~Delegate() {}
119 };
120
121 // Observer class. The Observer should *not* destroy CastWebContents during
122 // any of these events, otherwise other observers might try to use a freed
123 // pointer to |cast_web_contents|.
124 class Observer {
125 public:
126 Observer();
127
Sean Toppinge91b0972018-10-25 20:59:12128 // Advertises page state for the CastWebContents.
129 // Use CastWebContents::page_state() to get the new state.
Sean Toppingf0a1d572019-06-17 23:03:44130 virtual void OnPageStateChanged(CastWebContents* cast_web_contents) {}
Sean Toppinge91b0972018-10-25 20:59:12131
132 // Called when the page has stopped. e.g.: A 404 occurred when loading the
133 // page or if the render process for the main frame crashes. |error_code|
134 // will return a net::Error describing the failure, or net::OK if the page
Sean Topping7414eed2019-04-10 23:04:21135 // closed intentionally.
Sean Toppinge91b0972018-10-25 20:59:12136 //
137 // After this method, the page state will be one of the following:
Sean Topping7414eed2019-04-10 23:04:21138 // CLOSED: Page was closed as expected and the WebContents exists. The page
139 // should generally not be reloaded, since the page closure was
140 // triggered intentionally.
141 // ERROR: Page is in an error state. It should be reloaded or deleted.
Sean Toppinge91b0972018-10-25 20:59:12142 // DESTROYED: Page was closed due to deletion of WebContents. The
143 // CastWebContents instance is no longer usable and should be deleted.
Sean Toppinge91b0972018-10-25 20:59:12144 virtual void OnPageStopped(CastWebContents* cast_web_contents,
Sean Toppingf0a1d572019-06-17 23:03:44145 int error_code) {}
Sean Toppinge91b0972018-10-25 20:59:12146
Sean Toppingf0a1d572019-06-17 23:03:44147 // A new RenderFrame was created for the WebContents. |frame_interfaces| are
148 // provided by the new frame.
149 virtual void RenderFrameCreated(
150 int render_process_id,
151 int render_frame_id,
Sean Topping2d4e54e2019-06-25 00:04:04152 service_manager::InterfaceProvider* frame_interfaces,
153 blink::AssociatedInterfaceProvider* frame_associated_interfaces) {}
Chad Duffin4aa9c042019-01-11 00:51:55154
Jiawei Lic3354ee2019-12-13 23:48:35155 // A navigation has finished in the WebContents' main frame.
156 virtual void MainFrameFinishedNavigation() {}
157
Sean Toppingf0a1d572019-06-17 23:03:44158 // These methods are calls forwarded from WebContentsObserver.
159 virtual void MainFrameResized(const gfx::Rect& bounds) {}
160 virtual void UpdateTitle(const base::string16& title) {}
161 virtual void UpdateFaviconURL(GURL icon_url) {}
162 virtual void DidFinishBlockedNavigation(GURL url) {}
163 virtual void DidFirstVisuallyNonEmptyPaint() {}
Chad Duffin4aa9c042019-01-11 00:51:55164
Sean Topping7414eed2019-04-10 23:04:21165 // Notifies that a resource for the main frame failed to load.
166 virtual void ResourceLoadFailed(CastWebContents* cast_web_contents) {}
167
Zhaoxin2fe094a2020-02-11 23:35:45168 // Propagates the process information via observer, in particular to
169 // the underlying OnRendererProcessStarted() method.
170 virtual void OnRenderProcessReady(const base::Process& process) {}
171
Chad Duffin4aa9c042019-01-11 00:51:55172 // Adds |this| to the ObserverList in the implementation of
173 // |cast_web_contents|.
174 void Observe(CastWebContents* cast_web_contents);
175
176 // Removes |this| from the ObserverList in the implementation of
177 // |cast_web_contents_|. This is only invoked by CastWebContents and is used
178 // to ensure that once the observed CastWebContents object is destructed the
179 // CastWebContents::Observer does not invoke any additional function calls
180 // on it.
181 void ResetCastWebContents();
182
183 protected:
184 virtual ~Observer();
185
186 CastWebContents* cast_web_contents_;
187 };
188
Sean Toppingf0a1d572019-06-17 23:03:44189 enum class BackgroundColor {
190 NONE,
191 WHITE,
192 BLACK,
193 TRANSPARENT,
194 };
195
Sean Topping7414eed2019-04-10 23:04:21196 // Initialization parameters for CastWebContents.
Sean Topping0e8ac572019-01-30 03:05:43197 struct InitParams {
Sean Toppingeda675e2019-11-07 22:29:04198 // The delegate for the CastWebContents. Must be non-null. If the delegate
199 // is destroyed before CastWebContents, the WeakPtr will be invalidated on
200 // the main UI thread.
201 base::WeakPtr<Delegate> delegate = nullptr;
Jiawei Lia64a082b2019-12-06 21:17:26202 // Enable development mode for this CastWebContents. Whitelists
Sean Topping8a343862019-05-09 22:19:14203 // certain functionality for the WebContents, like remote debugging and
204 // debugging interfaces.
205 bool enabled_for_dev = false;
Sean Topping7414eed2019-04-10 23:04:21206 // Chooses a media renderer for the WebContents.
Sean Topping8a343862019-05-09 22:19:14207 bool use_cma_renderer = false;
Sean Topping7414eed2019-04-10 23:04:21208 // Whether the WebContents is a root native window, or if it is embedded in
209 // another WebContents (see Delegate::InnerContentsCreated()).
Sean Topping6735aaf2019-03-20 19:20:12210 bool is_root_window = false;
Sean Topping8a343862019-05-09 22:19:14211 // Whether inner WebContents events should be handled. If this is set to
212 // true, then inner WebContents will automatically have a CastWebContents
213 // created and notify the delegate.
214 bool handle_inner_contents = false;
215 // Construct internal media blocker and enable BlockMediaLoading().
216 bool use_media_blocker = false;
Sean Toppingf0a1d572019-06-17 23:03:44217 // Background color for the WebContents view. If not provided, the color
218 // will fall back to the platform default.
219 BackgroundColor background_color = BackgroundColor::NONE;
Jiawei Lia64a082b2019-12-06 21:17:26220 // Enable WebSQL database for this CastWebContents.
221 bool enable_websql = false;
222 // Enable mixer audio support for this CastWebContents.
223 bool enable_mixer_audio = false;
Jiawei Li0565a2f2019-12-07 01:26:01224 // Whether to provide a QueryableDataHost for this CastWebContents.
225 // Clients can use it to send queryable values to the render frames.
226 // queryable_data_host() will return a nullptr if this is false.
227 bool enable_queryable_data_host = false;
Sean Toppingeda675e2019-11-07 22:29:04228
229 InitParams();
230 InitParams(const InitParams& other);
231 ~InitParams();
Sean Topping0e8ac572019-01-30 03:05:43232 };
233
Sean Toppinge91b0972018-10-25 20:59:12234 // Page state for the main frame.
235 enum class PageState {
236 IDLE, // Main frame has not started yet.
237 LOADING, // Main frame is loading resources.
238 LOADED, // Main frame is loaded, but sub-frames may still be loading.
239 CLOSED, // Page is closed and should be cleaned up.
240 DESTROYED, // The WebContents is destroyed and can no longer be used.
241 ERROR, // Main frame is in an error state.
242 };
243
Sean Topping6735aaf2019-03-20 19:20:12244 static std::vector<CastWebContents*>& GetAll();
245
Jiawei Lia64a082b2019-12-06 21:17:26246 // Returns the CastWebContents that wraps the content::WebContents, or nullptr
247 // if the CastWebContents does not exist.
248 static CastWebContents* FromWebContents(content::WebContents* web_contents);
249
Sean Toppinge91b0972018-10-25 20:59:12250 CastWebContents() = default;
251 virtual ~CastWebContents() = default;
252
Sean Topping6735aaf2019-03-20 19:20:12253 // Tab identifier for the WebContents, mainly used by the tabs extension API.
254 // Tab IDs may be re-used, but no two live CastWebContents should have the
255 // same tab ID at any given time.
256 virtual int tab_id() const = 0;
257
Sean Topping0e8ac572019-01-30 03:05:43258 // TODO(seantopping): Hide this, clients shouldn't use WebContents directly.
Sean Toppinge91b0972018-10-25 20:59:12259 virtual content::WebContents* web_contents() const = 0;
260 virtual PageState page_state() const = 0;
261
Jiawei Li0565a2f2019-12-07 01:26:01262 // Returns QueryableDataHost that is used to push values to the renderer.
263 // Returns nullptr if the new queryable data bindings is enabled.
264 virtual QueryableDataHost* queryable_data_host() const = 0;
265
Jiawei Lic3354ee2019-12-13 23:48:35266 // Returns the PID of the main frame process if valid.
267 virtual base::Optional<pid_t> GetMainFrameRenderProcessPid() const = 0;
268
Sean Topping0e8ac572019-01-30 03:05:43269 // ===========================================================================
270 // Initialization and Setup
271 // ===========================================================================
272
Sean Topping0e8ac572019-01-30 03:05:43273 // Add a set of features for all renderers in the WebContents. Features are
274 // configured when `CastWebContents::RenderFrameCreated` is invoked.
275 virtual void AddRendererFeatures(std::vector<RendererFeature> features) = 0;
276
277 virtual void AllowWebAndMojoWebUiBindings() = 0;
278 virtual void ClearRenderWidgetHostView() = 0;
279
280 // ===========================================================================
281 // Page Lifetime
282 // ===========================================================================
283
Sean Toppinge91b0972018-10-25 20:59:12284 // Navigates the underlying WebContents to |url|. Delegate will be notified of
285 // page progression events via OnPageStateChanged().
286 virtual void LoadUrl(const GURL& url) = 0;
287
288 // Initiate closure of the page. This invokes the appropriate unload handlers.
289 // Eventually the delegate will be notified with OnPageStopped().
290 virtual void ClosePage() = 0;
291
292 // Stop the page immediately. This will automatically invoke
293 // Delegate::OnPageStopped(error_code), allowing the delegate to delete or
Sean Topping7414eed2019-04-10 23:04:21294 // reload the page without waiting for the WebContents owner to tear down the
295 // page.
Sean Toppinge91b0972018-10-25 20:59:12296 virtual void Stop(int error_code) = 0;
297
Sean Topping8a343862019-05-09 22:19:14298 // ===========================================================================
Sean Topping6d514082020-02-11 03:10:33299 // Visibility
300 // ===========================================================================
301
302 // Specify if the WebContents should be treated as visible. This triggers a
303 // document "visibilitychange" change event, and will paint the WebContents
304 // quad if |visible| is true (otherwise it will be blank). Note that this does
305 // *not* guarantee the page is visible on the screen, as that depends on if
306 // the WebContents quad is present in the screen layout and isn't obscured by
307 // another window.
308 virtual void SetWebVisibilityAndPaint(bool visible) = 0;
309
310 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14311 // Media Management
312 // ===========================================================================
313
314 // Block/unblock media from loading in all RenderFrames for the WebContents.
315 virtual void BlockMediaLoading(bool blocked) = 0;
Andres Medinaa65ad1b2019-06-26 22:18:19316 // Block/unblock media from starting in all RenderFrames for the WebContents.
317 // As opposed to |BlockMediaLoading|, |BlockMediaStarting| allows media to
318 // load while in blocking state.
319 virtual void BlockMediaStarting(bool blocked) = 0;
Sean Topping8a343862019-05-09 22:19:14320 virtual void EnableBackgroundVideoPlayback(bool enabled) = 0;
321
322 // ===========================================================================
Jiawei Lidf9ad18a2019-07-07 05:31:02323 // Page Communication
324 // ===========================================================================
325
326 // Executes a UTF-8 encoded |script| for every subsequent page load where
327 // the frame's URL has an origin reflected in |origins|. The script is
328 // executed early, prior to the execution of the document's scripts.
329 //
330 // Scripts are identified by a string-based client-managed |id|. Any
331 // script previously injected using the same |id| will be replaced.
332 //
333 // The order in which multiple bindings are executed is the same as the
334 // order in which the bindings were Added. If a script is added which
335 // clobbers an existing script of the same |id|, the previous script's
336 // precedence in the injection order will be preserved.
337 // |script| and |id| must be non-empty string.
338 //
339 // At least one |origins| entry must be specified.
340 // If a wildcard "*" is specified in |origins|, then the script will be
341 // evaluated for all documents.
342 virtual void AddBeforeLoadJavaScript(base::StringPiece id,
343 const std::vector<std::string>& origins,
344 base::StringPiece script) = 0;
345
346 // Removes a previously added JavaScript snippet identified by |id|.
347 // This is a no-op if there is no JavaScript snippet identified by |id|.
348 virtual void RemoveBeforeLoadJavaScript(base::StringPiece id) = 0;
349
Jiawei Libba76072019-07-29 23:00:25350 // Posts a message to the frame's onMessage handler.
351 //
352 // `target_origin` restricts message delivery to the specified origin.
353 // If `target_origin` is "*", then the message will be sent to the
354 // document regardless of its origin.
355 // See html.spec.whatwg.org/multipage/web-messaging.html sect. 9.4.3
356 // for more details on how the target origin policy is applied.
357 // Should be called on UI thread.
Chris Hamilton825f2ed2020-01-30 21:46:41358 // TODO(crbug.com/803242): Deprecated and will be shortly removed.
Jiawei Libba76072019-07-29 23:00:25359 virtual void PostMessageToMainFrame(
360 const std::string& target_origin,
361 const std::string& data,
362 std::vector<mojo::ScopedMessagePipeHandle> channels) = 0;
Chris Hamilton825f2ed2020-01-30 21:46:41363 virtual void PostMessageToMainFrame(
364 const std::string& target_origin,
365 const std::string& data,
366 std::vector<blink::WebMessagePort> ports) = 0;
Jiawei Libba76072019-07-29 23:00:25367
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
Jiawei Li830fcfd2019-02-12 20:12:17378 // Used to expose CastWebContents's |binder_registry_| to Delegate.
379 // Delegate should register its mojo interface binders via this function
380 // when it is ready.
381 virtual service_manager::BinderRegistry* binder_registry() = 0;
382
Julie Jeongeun Kim641f4752019-12-04 01:53:22383 // Used for owner to pass its |InterfaceProvider| pointers to CastWebContents.
384 // It is owner's responsibility to make sure each |InterfaceProvider| pointer
385 // has distinct mojo interface set.
Jiawei Li830fcfd2019-02-12 20:12:17386 using InterfaceSet = base::flat_set<std::string>;
387 virtual void RegisterInterfaceProvider(
388 const InterfaceSet& interface_set,
389 service_manager::InterfaceProvider* interface_provider) = 0;
390
Jiawei Lia64a082b2019-12-06 21:17:26391 // Returns true if WebSQL database is configured enabled for this
392 // CastWebContents.
393 virtual bool is_websql_enabled() = 0;
394
395 // Returns true if mixer audio is enabled.
396 virtual bool is_mixer_audio_enabled() = 0;
397
Sean Toppinge91b0972018-10-25 20:59:12398 private:
399 DISALLOW_COPY_AND_ASSIGN(CastWebContents);
400};
401
402std::ostream& operator<<(std::ostream& os, CastWebContents::PageState state);
403
404} // namespace chromecast
405
406#endif // CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_