blob: 352044df6bbf059edefb17e2f5b993a7ea8dee58 [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"
Sean Toppingf0a1d572019-06-17 23:03:4420#include "ui/gfx/geometry/rect.h"
Sean Toppinge91b0972018-10-25 20:59:1221#include "url/gurl.h"
22
Sean Topping2d4e54e2019-06-25 00:04:0423namespace blink {
24class AssociatedInterfaceProvider;
25} // namespace blink
26
Sean Toppinge91b0972018-10-25 20:59:1227namespace content {
28class WebContents;
29} // namespace content
30
31namespace chromecast {
32
Jiawei Li0565a2f2019-12-07 01:26:0133class QueryableDataHost;
34
Sean Topping0e8ac572019-01-30 03:05:4335struct RendererFeature {
36 const std::string name;
37 base::Value value;
38};
39
Sean Toppinge91b0972018-10-25 20:59:1240// Simplified WebContents wrapper class for Cast platforms.
Sean Topping7414eed2019-04-10 23:04:2141//
42// Proper usage of content::WebContents relies on understanding the meaning
43// behind various WebContentsObserver methods, and then translating those
44// signals into some concrete state. CastWebContents does *not* own the
45// underlying WebContents (usually whatever class implements
46// content::WebContentsDelegate is the actual owner).
47//
48// =============================================================================
49// Lifetime
50// =============================================================================
51// CastWebContents *must* be created before WebContents begins loading any
52// content. Once content begins loading (via CWC::LoadUrl() or one of the
53// WebContents navigation APIs), CastWebContents will calculate its state based
54// on the status of the WebContents' *main* RenderFrame. Events from sub-frames
55// (e.g. iframes) are ignored, since we expect the web app to take care of
56// sub-frame errors.
57//
58// We consider the CastWebContents to be in a LOADED state when the content of
59// the main frame is fully loaded and running (all resources fetched, JS is
60// running). Iframes might still be loading in this case, but in general we
Sean Toppingeda675e2019-11-07 22:29:0461// consider the page to be in a presentable state at this stage, so it is
Sean Topping7414eed2019-04-10 23:04:2162// appropriate to display the WebContents to the user.
63//
64// During or after the page is loaded, there are multiple error conditions that
65// can occur. The following events will cause the page to enter an ERROR state:
66//
67// 1. If the main frame is served an HTTP error page (such as a 404 page), then
68// it means the desired content wasn't loaded.
69//
70// 2. If the main frame fails to load, such as when the browser blocked the URL
71// request, we treat this as an error.
72//
73// 3. The RenderProcess for the main frame could crash, so the page is not in a
74// usable state.
75//
76// The CastWebContents user can respond to these errors in a few ways: The
77// content can be reloaded, or the entire page activity can be cancelled. If we
78// totally cancel the activity, we prefer to notify the user with an error
79// screen or visible/audible error message. Otherwise, a silent retry is
80// preferred.
81//
82// CastWebContents can be used to close the underlying WebContents gracefully
83// via CWC::Close(). This initiates web page tear-down logic so that the web
84// app has a chance to perform its own finalization logic in JS. Next, we call
85// WebContents::ClosePage(), which defers the page closure logic to the
86// content::WebContentsDelegate. Usually, it will run its own finalization
87// logic and then destroy the WebContents. CastWebContents will be notified of
88// the WebContents destruction and enter the DESTROYED state. In the event
89// the page isn't destroyed, the page will enter the CLOSED state automatically
90// after a timeout. CastWebContents users should not try to reload the page, as
91// page closure is intentional.
92//
93// The web app may decide to close itself (such as via "window.close()" in JS).
94// This is similar to initiating the close flow via CWC::Close(), with the end
95// result being the same. We consider this an intentional closure, and should
96// not attempt to reload the page.
97//
98// Once CastWebContents is in the DESTROYED state, it is not really usable
99// anymore; most of the methods will simply no-op, and no more observer signals
100// will be emitted.
101//
102// CastWebContents can be deleted at any time, *except* during Observer
103// notifications. If the owner wants to destroy CastWebContents as a result of
104// an Observer event, it should post a task to destroy CastWebContents.
Sean Toppinge91b0972018-10-25 20:59:12105class CastWebContents {
106 public:
107 class Delegate {
108 public:
Sean Toppingf0a1d572019-06-17 23:03:44109 // Notify that an inner WebContents was created. |inner_contents| is created
110 // in a default-initialized state with no delegate, and can be safely
111 // initialized by the delegate.
112 virtual void InnerContentsCreated(CastWebContents* inner_contents,
113 CastWebContents* outer_contents) {}
114
115 protected:
116 virtual ~Delegate() {}
117 };
118
119 // Observer class. The Observer should *not* destroy CastWebContents during
120 // any of these events, otherwise other observers might try to use a freed
121 // pointer to |cast_web_contents|.
122 class Observer {
123 public:
124 Observer();
125
Sean Toppinge91b0972018-10-25 20:59:12126 // Advertises page state for the CastWebContents.
127 // Use CastWebContents::page_state() to get the new state.
Sean Toppingf0a1d572019-06-17 23:03:44128 virtual void OnPageStateChanged(CastWebContents* cast_web_contents) {}
Sean Toppinge91b0972018-10-25 20:59:12129
130 // Called when the page has stopped. e.g.: A 404 occurred when loading the
131 // page or if the render process for the main frame crashes. |error_code|
132 // will return a net::Error describing the failure, or net::OK if the page
Sean Topping7414eed2019-04-10 23:04:21133 // closed intentionally.
Sean Toppinge91b0972018-10-25 20:59:12134 //
135 // After this method, the page state will be one of the following:
Sean Topping7414eed2019-04-10 23:04:21136 // CLOSED: Page was closed as expected and the WebContents exists. The page
137 // should generally not be reloaded, since the page closure was
138 // triggered intentionally.
139 // ERROR: Page is in an error state. It should be reloaded or deleted.
Sean Toppinge91b0972018-10-25 20:59:12140 // DESTROYED: Page was closed due to deletion of WebContents. The
141 // CastWebContents instance is no longer usable and should be deleted.
Sean Toppinge91b0972018-10-25 20:59:12142 virtual void OnPageStopped(CastWebContents* cast_web_contents,
Sean Toppingf0a1d572019-06-17 23:03:44143 int error_code) {}
Sean Toppinge91b0972018-10-25 20:59:12144
Sean Toppingf0a1d572019-06-17 23:03:44145 // A new RenderFrame was created for the WebContents. |frame_interfaces| are
146 // provided by the new frame.
147 virtual void RenderFrameCreated(
148 int render_process_id,
149 int render_frame_id,
Sean Topping2d4e54e2019-06-25 00:04:04150 service_manager::InterfaceProvider* frame_interfaces,
151 blink::AssociatedInterfaceProvider* frame_associated_interfaces) {}
Chad Duffin4aa9c042019-01-11 00:51:55152
Sean Toppingf0a1d572019-06-17 23:03:44153 // These methods are calls forwarded from WebContentsObserver.
154 virtual void MainFrameResized(const gfx::Rect& bounds) {}
155 virtual void UpdateTitle(const base::string16& title) {}
156 virtual void UpdateFaviconURL(GURL icon_url) {}
157 virtual void DidFinishBlockedNavigation(GURL url) {}
158 virtual void DidFirstVisuallyNonEmptyPaint() {}
Chad Duffin4aa9c042019-01-11 00:51:55159
Sean Topping7414eed2019-04-10 23:04:21160 // Notifies that a resource for the main frame failed to load.
161 virtual void ResourceLoadFailed(CastWebContents* cast_web_contents) {}
162
Chad Duffin4aa9c042019-01-11 00:51:55163 // Adds |this| to the ObserverList in the implementation of
164 // |cast_web_contents|.
165 void Observe(CastWebContents* cast_web_contents);
166
167 // Removes |this| from the ObserverList in the implementation of
168 // |cast_web_contents_|. This is only invoked by CastWebContents and is used
169 // to ensure that once the observed CastWebContents object is destructed the
170 // CastWebContents::Observer does not invoke any additional function calls
171 // on it.
172 void ResetCastWebContents();
173
174 protected:
175 virtual ~Observer();
176
177 CastWebContents* cast_web_contents_;
178 };
179
Sean Toppingf0a1d572019-06-17 23:03:44180 enum class BackgroundColor {
181 NONE,
182 WHITE,
183 BLACK,
184 TRANSPARENT,
185 };
186
Sean Topping7414eed2019-04-10 23:04:21187 // Initialization parameters for CastWebContents.
Sean Topping0e8ac572019-01-30 03:05:43188 struct InitParams {
Sean Toppingeda675e2019-11-07 22:29:04189 // The delegate for the CastWebContents. Must be non-null. If the delegate
190 // is destroyed before CastWebContents, the WeakPtr will be invalidated on
191 // the main UI thread.
192 base::WeakPtr<Delegate> delegate = nullptr;
Jiawei Lia64a082b2019-12-06 21:17:26193 // Enable development mode for this CastWebContents. Whitelists
Sean Topping8a343862019-05-09 22:19:14194 // certain functionality for the WebContents, like remote debugging and
195 // debugging interfaces.
196 bool enabled_for_dev = false;
Sean Topping7414eed2019-04-10 23:04:21197 // Chooses a media renderer for the WebContents.
Sean Topping8a343862019-05-09 22:19:14198 bool use_cma_renderer = false;
Sean Topping7414eed2019-04-10 23:04:21199 // Whether the WebContents is a root native window, or if it is embedded in
200 // another WebContents (see Delegate::InnerContentsCreated()).
Sean Topping6735aaf2019-03-20 19:20:12201 bool is_root_window = false;
Sean Topping8a343862019-05-09 22:19:14202 // Whether inner WebContents events should be handled. If this is set to
203 // true, then inner WebContents will automatically have a CastWebContents
204 // created and notify the delegate.
205 bool handle_inner_contents = false;
206 // Construct internal media blocker and enable BlockMediaLoading().
207 bool use_media_blocker = false;
Sean Toppingf0a1d572019-06-17 23:03:44208 // Background color for the WebContents view. If not provided, the color
209 // will fall back to the platform default.
210 BackgroundColor background_color = BackgroundColor::NONE;
Jiawei Lia64a082b2019-12-06 21:17:26211 // Enable WebSQL database for this CastWebContents.
212 bool enable_websql = false;
213 // Enable mixer audio support for this CastWebContents.
214 bool enable_mixer_audio = false;
Jiawei Li0565a2f2019-12-07 01:26:01215 // Whether to provide a QueryableDataHost for this CastWebContents.
216 // Clients can use it to send queryable values to the render frames.
217 // queryable_data_host() will return a nullptr if this is false.
218 bool enable_queryable_data_host = false;
Sean Toppingeda675e2019-11-07 22:29:04219
220 InitParams();
221 InitParams(const InitParams& other);
222 ~InitParams();
Sean Topping0e8ac572019-01-30 03:05:43223 };
224
Sean Toppinge91b0972018-10-25 20:59:12225 // Page state for the main frame.
226 enum class PageState {
227 IDLE, // Main frame has not started yet.
228 LOADING, // Main frame is loading resources.
229 LOADED, // Main frame is loaded, but sub-frames may still be loading.
230 CLOSED, // Page is closed and should be cleaned up.
231 DESTROYED, // The WebContents is destroyed and can no longer be used.
232 ERROR, // Main frame is in an error state.
233 };
234
Sean Topping6735aaf2019-03-20 19:20:12235 static std::vector<CastWebContents*>& GetAll();
236
Jiawei Lia64a082b2019-12-06 21:17:26237 // Returns the CastWebContents that wraps the content::WebContents, or nullptr
238 // if the CastWebContents does not exist.
239 static CastWebContents* FromWebContents(content::WebContents* web_contents);
240
Sean Toppinge91b0972018-10-25 20:59:12241 CastWebContents() = default;
242 virtual ~CastWebContents() = default;
243
Sean Topping6735aaf2019-03-20 19:20:12244 // Tab identifier for the WebContents, mainly used by the tabs extension API.
245 // Tab IDs may be re-used, but no two live CastWebContents should have the
246 // same tab ID at any given time.
247 virtual int tab_id() const = 0;
248
Sean Topping0e8ac572019-01-30 03:05:43249 // TODO(seantopping): Hide this, clients shouldn't use WebContents directly.
Sean Toppinge91b0972018-10-25 20:59:12250 virtual content::WebContents* web_contents() const = 0;
251 virtual PageState page_state() const = 0;
252
Jiawei Li0565a2f2019-12-07 01:26:01253 // Returns QueryableDataHost that is used to push values to the renderer.
254 // Returns nullptr if the new queryable data bindings is enabled.
255 virtual QueryableDataHost* queryable_data_host() const = 0;
256
Sean Topping0e8ac572019-01-30 03:05:43257 // ===========================================================================
258 // Initialization and Setup
259 // ===========================================================================
260
Sean Topping0e8ac572019-01-30 03:05:43261 // Add a set of features for all renderers in the WebContents. Features are
262 // configured when `CastWebContents::RenderFrameCreated` is invoked.
263 virtual void AddRendererFeatures(std::vector<RendererFeature> features) = 0;
264
265 virtual void AllowWebAndMojoWebUiBindings() = 0;
266 virtual void ClearRenderWidgetHostView() = 0;
267
268 // ===========================================================================
269 // Page Lifetime
270 // ===========================================================================
271
Sean Toppinge91b0972018-10-25 20:59:12272 // Navigates the underlying WebContents to |url|. Delegate will be notified of
273 // page progression events via OnPageStateChanged().
274 virtual void LoadUrl(const GURL& url) = 0;
275
276 // Initiate closure of the page. This invokes the appropriate unload handlers.
277 // Eventually the delegate will be notified with OnPageStopped().
278 virtual void ClosePage() = 0;
279
280 // Stop the page immediately. This will automatically invoke
281 // Delegate::OnPageStopped(error_code), allowing the delegate to delete or
Sean Topping7414eed2019-04-10 23:04:21282 // reload the page without waiting for the WebContents owner to tear down the
283 // page.
Sean Toppinge91b0972018-10-25 20:59:12284 virtual void Stop(int error_code) = 0;
285
Sean Topping8a343862019-05-09 22:19:14286 // ===========================================================================
287 // Media Management
288 // ===========================================================================
289
290 // Block/unblock media from loading in all RenderFrames for the WebContents.
291 virtual void BlockMediaLoading(bool blocked) = 0;
Andres Medinaa65ad1b2019-06-26 22:18:19292 // Block/unblock media from starting in all RenderFrames for the WebContents.
293 // As opposed to |BlockMediaLoading|, |BlockMediaStarting| allows media to
294 // load while in blocking state.
295 virtual void BlockMediaStarting(bool blocked) = 0;
Sean Topping8a343862019-05-09 22:19:14296 virtual void EnableBackgroundVideoPlayback(bool enabled) = 0;
297
298 // ===========================================================================
Jiawei Lidf9ad18a2019-07-07 05:31:02299 // Page Communication
300 // ===========================================================================
301
302 // Executes a UTF-8 encoded |script| for every subsequent page load where
303 // the frame's URL has an origin reflected in |origins|. The script is
304 // executed early, prior to the execution of the document's scripts.
305 //
306 // Scripts are identified by a string-based client-managed |id|. Any
307 // script previously injected using the same |id| will be replaced.
308 //
309 // The order in which multiple bindings are executed is the same as the
310 // order in which the bindings were Added. If a script is added which
311 // clobbers an existing script of the same |id|, the previous script's
312 // precedence in the injection order will be preserved.
313 // |script| and |id| must be non-empty string.
314 //
315 // At least one |origins| entry must be specified.
316 // If a wildcard "*" is specified in |origins|, then the script will be
317 // evaluated for all documents.
318 virtual void AddBeforeLoadJavaScript(base::StringPiece id,
319 const std::vector<std::string>& origins,
320 base::StringPiece script) = 0;
321
322 // Removes a previously added JavaScript snippet identified by |id|.
323 // This is a no-op if there is no JavaScript snippet identified by |id|.
324 virtual void RemoveBeforeLoadJavaScript(base::StringPiece id) = 0;
325
Jiawei Libba76072019-07-29 23:00:25326 // Posts a message to the frame's onMessage handler.
327 //
328 // `target_origin` restricts message delivery to the specified origin.
329 // If `target_origin` is "*", then the message will be sent to the
330 // document regardless of its origin.
331 // See html.spec.whatwg.org/multipage/web-messaging.html sect. 9.4.3
332 // for more details on how the target origin policy is applied.
333 // Should be called on UI thread.
334 virtual void PostMessageToMainFrame(
335 const std::string& target_origin,
336 const std::string& data,
337 std::vector<mojo::ScopedMessagePipeHandle> channels) = 0;
338
Jiawei Lidf9ad18a2019-07-07 05:31:02339 // ===========================================================================
Sean Topping8a343862019-05-09 22:19:14340 // Utility Methods
341 // ===========================================================================
342
Chad Duffin4aa9c042019-01-11 00:51:55343 // Used to add or remove |observer| to the ObserverList in the implementation.
344 // These functions should only be invoked by CastWebContents::Observer in a
345 // valid sequence, enforced via SequenceChecker.
346 virtual void AddObserver(Observer* observer) = 0;
347 virtual void RemoveObserver(Observer* observer) = 0;
348
Jiawei Li830fcfd2019-02-12 20:12:17349 // Used to expose CastWebContents's |binder_registry_| to Delegate.
350 // Delegate should register its mojo interface binders via this function
351 // when it is ready.
352 virtual service_manager::BinderRegistry* binder_registry() = 0;
353
Julie Jeongeun Kim641f4752019-12-04 01:53:22354 // Used for owner to pass its |InterfaceProvider| pointers to CastWebContents.
355 // It is owner's responsibility to make sure each |InterfaceProvider| pointer
356 // has distinct mojo interface set.
Jiawei Li830fcfd2019-02-12 20:12:17357 using InterfaceSet = base::flat_set<std::string>;
358 virtual void RegisterInterfaceProvider(
359 const InterfaceSet& interface_set,
360 service_manager::InterfaceProvider* interface_provider) = 0;
361
Jiawei Lia64a082b2019-12-06 21:17:26362 // Returns true if WebSQL database is configured enabled for this
363 // CastWebContents.
364 virtual bool is_websql_enabled() = 0;
365
366 // Returns true if mixer audio is enabled.
367 virtual bool is_mixer_audio_enabled() = 0;
368
Sean Toppinge91b0972018-10-25 20:59:12369 private:
370 DISALLOW_COPY_AND_ASSIGN(CastWebContents);
371};
372
373std::ostream& operator<<(std::ostream& os, CastWebContents::PageState state);
374
375} // namespace chromecast
376
377#endif // CHROMECAST_BROWSER_CAST_WEB_CONTENTS_H_