code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCH_DELEGATE_H_
#define WEBLAYER_PUBLIC_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCH_DELEGATE_H_
#include <set>
#include <string>
#include "base/functional/callback_forward.h"
namespace weblayer {
using OnTokenFetchedCallback =
base::OnceCallback<void(const std::string& token)>;
// An interface that allows clients to handle access token requests for Google
// accounts originating in the browser.
class GoogleAccountAccessTokenFetchDelegate {
public:
// Called when the WebLayer implementation wants to fetch an access token for
// the embedder's current GAIA account (if any) and the given scopes. The
// client should invoke |onTokenFetchedCallback| when its internal token fetch
// is complete, passing either the fetched access token or the empty string in
// the case of failure (e.g., if there is no current GAIA account or there was
// an error in the token fetch).
//
// NOTE: WebLayer will not perform any caching of the returned token but will
// instead make a new request each time that it needs to use an access token.
// The expectation is that the client will use caching internally to minimize
// latency of these requests.
virtual void FetchAccessToken(const std::set<std::string>& scopes,
OnTokenFetchedCallback callback) = 0;
// Called when a token previously obtained via a call to
// FetchAccessToken(|scopes|) is identified as invalid, so the embedder can
// take appropriate action (e.g., dropping the token from its cache and/or
// force-fetching a new token).
virtual void OnAccessTokenIdentifiedAsInvalid(
const std::set<std::string>& scopes,
const std::string& token) = 0;
protected:
virtual ~GoogleAccountAccessTokenFetchDelegate() {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCH_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/google_account_access_token_fetch_delegate.h | C++ | unknown | 2,048 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_GOOGLE_ACCOUNTS_DELEGATE_H_
#define WEBLAYER_PUBLIC_GOOGLE_ACCOUNTS_DELEGATE_H_
#include <string>
namespace signin {
struct ManageAccountsParams;
}
namespace weblayer {
// Used to intercept interaction with GAIA accounts.
class GoogleAccountsDelegate {
public:
// Called when a user wants to change the state of their GAIA account. This
// could be a signin, signout, or any other action. See
// signin::GAIAServiceType for all the possible actions.
virtual void OnGoogleAccountsRequest(
const signin::ManageAccountsParams& params) = 0;
// The current GAIA ID the user is signed in with, or empty if the user is
// signed out. This can be provided on a best effort basis if the ID is not
// available immediately.
virtual std::string GetGaiaId() = 0;
protected:
virtual ~GoogleAccountsDelegate() = default;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_GOOGLE_ACCOUNTS_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/google_accounts_delegate.h | C++ | unknown | 1,092 |
# Copyright 2021 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit tests for weblayer public API."""
import glob
import logging
import os
import shutil
import subprocess
import sys
import tempfile
USE_PYTHON3 = True
_WEBLAYER_PUBLIC_MANIFEST_PATH=os.path.join("weblayer", "public", "java",
"AndroidManifest.xml")
_MANIFEST_CHANGE_STRING = """You are changing the WebLayer public manifest.
Did you validate this change with WebLayer's internal clients?
If not, you must do so before landing it!"""
def CheckChangeOnUpload(input_api, output_api):
for f in input_api.AffectedFiles():
if _WEBLAYER_PUBLIC_MANIFEST_PATH in f.AbsoluteLocalPath():
return [output_api.PresubmitPromptWarning(
_MANIFEST_CHANGE_STRING)]
return []
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/PRESUBMIT.py | Python | unknown | 879 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.concurrent.futures.CallbackToFutureAdapter;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.webengine.interfaces.ExceptionType;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.ICookieManagerDelegate;
import org.chromium.webengine.interfaces.IStringCallback;
import java.util.HashSet;
/**
* CookieManager allows you to set/get cookies within the context of the WebFragment's
* profile.
*/
public class CookieManager {
@NonNull
private ICookieManagerDelegate mDelegate;
@NonNull
private HashSet<CallbackToFutureAdapter.Completer<Void>> mPendingSetCompleters =
new HashSet<>();
@NonNull
private HashSet<CallbackToFutureAdapter.Completer<String>> mPendingGetCompleters =
new HashSet<>();
CookieManager(@NonNull ICookieManagerDelegate delegate) {
mDelegate = delegate;
}
/**
* Sets a cookie for the given URL.
*
* @param uri the URI for which the cookie is to be set.
* @param value the cookie string, using the format of the 'Set-Cookie' HTTP response header.
*/
@NonNull
public ListenableFuture<Void> setCookie(@NonNull String uri, @NonNull String value) {
ThreadCheck.ensureOnUiThread();
if (mDelegate == null) {
return Futures.immediateFailedFuture(
new IllegalStateException("WebSandbox has been destroyed"));
}
return CallbackToFutureAdapter.getFuture(completer -> {
mPendingSetCompleters.add(completer);
try {
mDelegate.setCookie(uri, value, new IBooleanCallback.Stub() {
@Override
public void onResult(boolean set) {
if (!set) {
completer.setException(
new IllegalArgumentException("Cookie not set: " + value));
}
completer.set(null);
mPendingSetCompleters.remove(completer);
}
@Override
public void onException(@ExceptionType int type, String msg) {
completer.setException(ExceptionHelper.createException(type, msg));
mPendingSetCompleters.remove(completer);
}
});
} catch (RemoteException e) {
completer.setException(e);
mPendingSetCompleters.remove(completer);
}
// Debug string.
return "CookieManager.setCookie Future";
});
}
/**
* Gets the cookies for the given URL.
*
* @param uri the URI for which the cookie is to be set.
*/
@NonNull
public ListenableFuture<String> getCookie(@NonNull String uri) {
if (mDelegate == null) {
return Futures.immediateFailedFuture(
new IllegalStateException("WebSandbox has been destroyed"));
}
return CallbackToFutureAdapter.getFuture(completer -> {
mPendingGetCompleters.add(completer);
try {
mDelegate.getCookie(uri, new IStringCallback.Stub() {
@Override
public void onResult(String result) {
if (result != null) {
completer.set(result);
} else {
// TODO(rayankans): Improve exception reporting.
completer.setException(
new IllegalArgumentException("Failed to get cookie"));
}
mPendingGetCompleters.remove(completer);
}
@Override
public void onException(@ExceptionType int type, String msg) {
completer.setException(ExceptionHelper.createException(type, msg));
mPendingGetCompleters.remove(completer);
}
});
} catch (RemoteException e) {
completer.setException(e);
mPendingGetCompleters.remove(completer);
}
// Debug string.
return "CookieManager.getCookie Future";
});
}
void invalidate() {
mDelegate = null;
for (var completer : mPendingSetCompleters) {
completer.setCancelled();
}
for (var completer : mPendingGetCompleters) {
completer.setCancelled();
}
mPendingSetCompleters.clear();
mPendingGetCompleters.clear();
}
// TODO(rayankans): Add a Cookie Observer.
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/CookieManager.java | Java | unknown | 5,079 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import org.chromium.webengine.interfaces.ExceptionType;
class ExceptionHelper {
static Exception createException(@ExceptionType int type, String msg) {
switch (type) {
case ExceptionType.RESTRICTED_API:
return new RestrictedAPIException(msg);
case ExceptionType.INVALID_ARGUMENT:
return new IllegalArgumentException(msg);
case ExceptionType.UNKNOWN:
return new RuntimeException(msg);
}
// Should not happen.
return new RuntimeException(msg);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/ExceptionHelper.java | Java | unknown | 748 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
/**
* Fullscreen callback notifies when fullscreen mode starts and ends.
* It expects an implementation to enter and exit fullscreen mode, e.g. expand the
* FragmentContainerView to full size.
*/
public interface FullscreenCallback {
/**
/**
* Called when the page has requested to go fullscreen. The embedder is responsible for
* putting the system into fullscreen mode. The embedder can exit out of fullscreen by
* running the supplied FullscreenClient by calling fullscreenClient.exitFullscreen().
*
* NOTE: we expect the WebEngine Fragment to be covering the whole display without any other UI
elements from
* the embedder or Android on screen. Otherwise some web features (e.g. WebXR) might experience
* clipped or misaligned UI elements.
*
* @param webEngine the {@code WebEngine} associated with this event.
* @param tab the {@code Tab} associated with this Event
* @param fullscreenClient the {@code FullscreenClient} used to programmatically exit fullscreen
mode.
*/
public void onEnterFullscreen(WebEngine webEngine, Tab tab, FullscreenClient fullscreenClient);
/**
* Called when the WebEngine Tab exits fullscreen mode.
*
* @param webEngine the {@code WebEngine} associated with this event.
* @param tab the {@code Tab} associated with this Event
*/
public void onExitFullscreen(WebEngine webEngine, Tab tab);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/FullscreenCallback.java | Java | unknown | 1,621 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.Handler;
import android.os.Looper;
import org.chromium.webengine.interfaces.IFullscreenCallbackDelegate;
import org.chromium.webengine.interfaces.IFullscreenClient;
/**
* {@link FullscreenCallbackDelegate} notifies registered {@Link FullscreenCallback} of fullscreen
* events of the Tab.
*/
class FullscreenCallbackDelegate extends IFullscreenCallbackDelegate.Stub {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private FullscreenCallback mFullscreenCallback;
private WebEngine mWebEngine;
private Tab mTab;
public FullscreenCallbackDelegate(WebEngine webEngine, Tab tab) {
mWebEngine = webEngine;
mTab = tab;
}
public void setFullscreenCallback(FullscreenCallback callback) {
ThreadCheck.ensureOnUiThread();
mFullscreenCallback = callback;
}
@Override
public void onEnterFullscreen(IFullscreenClient iFullscreenClient) {
mHandler.post(() -> {
if (mFullscreenCallback != null) {
mFullscreenCallback.onEnterFullscreen(
mWebEngine, mTab, new FullscreenClient(iFullscreenClient));
}
});
}
@Override
public void onExitFullscreen() {
mHandler.post(() -> {
if (mFullscreenCallback != null) {
mFullscreenCallback.onExitFullscreen(mWebEngine, mTab);
}
});
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/FullscreenCallbackDelegate.java | Java | unknown | 1,606 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.RemoteException;
import org.chromium.webengine.interfaces.IFullscreenClient;
/**
* {@link FullscreenClient} is passed in {@link FullscreenCallback#onEnterFullscreen}
* to programmatically exit fullscreen mode.
*/
public class FullscreenClient {
private IFullscreenClient mFullscreenClient;
FullscreenClient(IFullscreenClient client) {
mFullscreenClient = client;
}
/**
* Exit fullscreen mode, will do nothing if already closed.
*/
public void exitFullscreen() {
ThreadCheck.ensureOnUiThread();
try {
mFullscreenClient.exitFullscreen();
} catch (RemoteException e) {
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/FullscreenClient.java | Java | unknown | 860 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
/**
* An interface for listening to postMessages from the web content.
*/
public interface MessageEventListener {
public abstract void onMessage(Tab source, String message);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/MessageEventListener.java | Java | unknown | 359 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.net.Uri;
import androidx.annotation.NonNull;
import org.chromium.webengine.interfaces.INavigationParams;
/**
* {@link Navigation} contains information about the current Tab Navigation.
*/
public class Navigation {
@NonNull
private INavigationParams mNavigationParams;
Navigation(@NonNull INavigationParams navigationParams) {
mNavigationParams = navigationParams;
}
/**
* The uri the main frame is navigating to. This may change during the navigation when
* encountering a server redirect.
*/
@NonNull
public Uri getUri() {
return mNavigationParams.uri;
}
/**
* Returns the status code of the navigation. Returns 0 if the navigation hasn't completed yet
* or if a response wasn't received.
*/
public int getStatusCode() {
return mNavigationParams.statusCode;
}
/**
* Whether the navigation happened without changing document. Examples of same document
* navigations are:
* - reference fragment navigations
* - pushState/replaceState
* - same page history navigation
*/
public boolean isSameDocument() {
return mNavigationParams.isSameDocument;
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/Navigation.java | Java | unknown | 1,399 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import androidx.annotation.NonNull;
/**
* An interface for observing changes to a Tab.
*/
public interface NavigationObserver {
/**
* Called when a navigation aborts in the Tab.
*
* Note that |navigation| is a snapshot of the current navigation, content might change over the
* course of the navigation.
*
* @param tab the tab associated with this event.
* @param navigation the unique object for this navigation.
*/
public default void onNavigationFailed(@NonNull Tab tab, @NonNull Navigation navigation) {}
/**
* Called when a navigation completes successfully in the Tab.
*
* The document load will still be ongoing in the Tab. Use the document loads
* events such as onFirstContentfulPaint and related methods to listen for continued events from
* this Tab.
*
* Note that this is fired by same-document navigations, such as fragment navigations or
* pushState/replaceState, which will not result in a document change. To filter these out, use
* NavigationHandle::IsSameDocument.
*
* Note that |navigation| is a snapshot of the current navigation, content might change over the
* course of the navigation.
*
* @param tab the tab associated with this event.
* @param navigation the unique object for this navigation.
*/
public default void onNavigationCompleted(@NonNull Tab tab, @NonNull Navigation navigation) {}
/**
* Called when a navigation started in the Tab. |navigation| is unique to a
* specific navigation.
*
* Note that this is only fired by navigations in the main frame.
*
* Note that this is fired by same-document navigations, such as fragment navigations or
* pushState/replaceState, which will not result in a document change. To filter these out, use
* Navigation::IsSameDocument.
*
* Note that |navigation| is a snapshot of the current navigation, content might change over the
* course of the navigation.
*
* Note that there is no guarantee that NavigationCompleted/NavigationFailed will be called for
* any particular navigation before NavigationStarted is called on the next.
*
* @param tab the tab associated with this event.
* @param navigation the unique object for this navigation.
*/
public default void onNavigationStarted(@NonNull Tab tab, @NonNull Navigation navigation) {}
/**
* Called when a navigation encountered a server redirect.
*
* @param tab the tab associated with this event.
* @param navigation the unique object for this navigation.
*/
public default void onNavigationRedirected(@NonNull Tab tab, @NonNull Navigation navigation) {}
/**
* The load state of the document has changed.
*
* @param tab the tab associated with this event.
* @param progress The loading progress.
*/
public default void onLoadProgressChanged(@NonNull Tab tab, double progress) {}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/NavigationObserver.java | Java | unknown | 3,186 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import org.chromium.base.ObserverList;
import org.chromium.webengine.interfaces.INavigationObserverDelegate;
import org.chromium.webengine.interfaces.INavigationParams;
/**
* {@link NavigationObserverDelegate} notifies registered {@Link NavigationObserver}s of navigation
* events in a Tab.
*/
class NavigationObserverDelegate extends INavigationObserverDelegate.Stub {
private final Handler mHandler = new Handler(Looper.getMainLooper());
@NonNull
private Tab mTab;
@NonNull
private ObserverList<NavigationObserver> mNavigationObservers =
new ObserverList<NavigationObserver>();
public NavigationObserverDelegate(Tab tab) {
ThreadCheck.ensureOnUiThread();
mTab = tab;
}
/**
* Registers a {@link NavigationObserver}. Call only from the UI thread.
*
* @return true if the observer was added to the list of observers.
*/
boolean registerObserver(NavigationObserver tabObserver) {
ThreadCheck.ensureOnUiThread();
return mNavigationObservers.addObserver(tabObserver);
}
/**
* Unregisters a {@link NavigationObserver}. Call only from the UI thread.
*
* @return true if the observer was removed from the list of observers.
*/
boolean unregisterObserver(NavigationObserver tabObserver) {
ThreadCheck.ensureOnUiThread();
return mNavigationObservers.removeObserver(tabObserver);
}
@Override
public void notifyNavigationStarted(@NonNull INavigationParams navigation) {
mHandler.post(() -> {
for (NavigationObserver observer : mNavigationObservers) {
observer.onNavigationStarted(mTab, new Navigation(navigation));
}
});
}
@Override
public void notifyNavigationRedirected(@NonNull INavigationParams navigation) {
mHandler.post(() -> {
for (NavigationObserver observer : mNavigationObservers) {
observer.onNavigationRedirected(mTab, new Navigation(navigation));
}
});
}
@Override
public void notifyNavigationCompleted(@NonNull INavigationParams navigation) {
mHandler.post(() -> {
for (NavigationObserver observer : mNavigationObservers) {
observer.onNavigationCompleted(mTab, new Navigation(navigation));
}
});
}
@Override
public void notifyNavigationFailed(@NonNull INavigationParams navigation) {
mHandler.post(() -> {
for (NavigationObserver observer : mNavigationObservers) {
observer.onNavigationFailed(mTab, new Navigation(navigation));
}
});
}
@Override
public void notifyLoadProgressChanged(double progress) {
mHandler.post(() -> {
for (NavigationObserver observer : mNavigationObservers) {
observer.onLoadProgressChanged(mTab, progress);
}
});
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/NavigationObserverDelegate.java | Java | unknown | 3,220 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
/**
* Error thrown for API access violations.
*/
public class RestrictedAPIException extends RuntimeException {
public RestrictedAPIException(String message) {
super(message);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/RestrictedAPIException.java | Java | unknown | 375 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.net.Uri;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.concurrent.futures.CallbackToFutureAdapter;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.base.ObserverList;
import org.chromium.webengine.interfaces.ExceptionType;
import org.chromium.webengine.interfaces.IPostMessageCallback;
import org.chromium.webengine.interfaces.IStringCallback;
import org.chromium.webengine.interfaces.ITabParams;
import org.chromium.webengine.interfaces.ITabProxy;
import java.util.List;
/**
* Tab controls the tab content and state.
*/
public class Tab {
@NonNull
private WebEngine mWebEngine;
@NonNull
private ITabProxy mTabProxy;
@NonNull
private TabNavigationController mTabNavigationController;
@NonNull
private TabObserverDelegate mTabObserverDelegate;
@NonNull
private String mGuid;
@NonNull
private Uri mUri;
@NonNull
private ObserverList<MessageEventListenerProxy> mMessageEventListenerProxies =
new ObserverList<>();
private boolean mPostMessageReady;
@NonNull
private FullscreenCallbackDelegate mFullscreenCallbackDelegate;
Tab(@NonNull WebEngine webEngine, @NonNull ITabParams tabParams) {
assert tabParams.tabProxy != null;
assert tabParams.tabGuid != null;
assert tabParams.navigationControllerProxy != null;
assert tabParams.uri != null;
mWebEngine = webEngine;
mTabProxy = tabParams.tabProxy;
mGuid = tabParams.tabGuid;
mUri = Uri.parse(tabParams.uri);
mTabObserverDelegate = new TabObserverDelegate(this);
mTabNavigationController =
new TabNavigationController(this, tabParams.navigationControllerProxy);
mFullscreenCallbackDelegate = new FullscreenCallbackDelegate(mWebEngine, this);
try {
mTabProxy.setTabObserverDelegate(mTabObserverDelegate);
mTabProxy.setFullscreenCallbackDelegate(mFullscreenCallbackDelegate);
} catch (RemoteException e) {
}
}
/**
* Returns the WebEngine instance associated with this Tab.
*/
@NonNull
public WebEngine getWebEngine() {
return mWebEngine;
}
/**
* Returns the URL of the page displayed.
*/
@NonNull
public Uri getDisplayUri() {
return mUri;
}
void setDisplayUri(Uri uri) {
mUri = uri;
}
/**
* Returns a unique identifier for the Tab.
*/
@NonNull
public String getGuid() {
return mGuid;
}
/**
* Sets this Tab to active.
*/
public void setActive() {
// TODO(rayankans): Should we make this return a ListenableFuture that resolves after the
// tab becomes active?
ThreadCheck.ensureOnUiThread();
if (mTabProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mTabProxy.setActive();
} catch (RemoteException e) {
}
}
/*
* Closes this Tab.
*/
public void close() {
// TODO(rayankans): Should we make this return a ListenableFuture that resolves after the
// tab is closed?
ThreadCheck.ensureOnUiThread();
if (mTabProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mTabProxy.close();
} catch (RemoteException e) {
}
}
/**
* Executes the script, and resolves with the result of the execution.
*
* @param useSeparateIsolate If true, runs the script in a separate v8 Isolate. This uses more
* memory, but separates the injected scrips from scripts in the page. This prevents any
* potentially malicious interaction between first-party scripts in the page, and injected
* scripts. Use with caution, only pass false for this argument if you know this isn't an issue
* or you need to interact with first-party scripts.
*/
@NonNull
public ListenableFuture<String> executeScript(
@NonNull String script, boolean useSeparateIsolate) {
ThreadCheck.ensureOnUiThread();
if (mTabProxy == null) {
return Futures.immediateFailedFuture(
new IllegalStateException("WebSandbox has been destroyed"));
}
return CallbackToFutureAdapter.getFuture(completer -> {
try {
mTabProxy.executeScript(script, useSeparateIsolate, new IStringCallback.Stub() {
@Override
public void onResult(String result) {
completer.set(result);
}
@Override
public void onException(@ExceptionType int type, String msg) {
completer.setException(ExceptionHelper.createException(type, msg));
}
});
} catch (RemoteException e) {
completer.setException(e);
}
return "Tab.executeScript Future";
});
}
/**
* Returns the navigation controller for this Tab.
*
* @return The TabNavigationController.
*/
@NonNull
public TabNavigationController getNavigationController() {
return mTabNavigationController;
}
/**
* Registers a {@link TabObserver} and returns if successful.
*
* @param tabObserver The TabObserver.
*
* @return true if observer was added to the list of observers.
*/
public boolean registerTabObserver(@NonNull TabObserver tabObserver) {
ThreadCheck.ensureOnUiThread();
return mTabObserverDelegate.registerObserver(tabObserver);
}
/**
* Unregisters a {@link Tabobserver} and returns if successful.
*
* @param tabObserver The TabObserver to remove.
*
* @return true if observer was removed from the list of observers.
*/
public boolean unregisterTabObserver(@NonNull TabObserver tabObserver) {
ThreadCheck.ensureOnUiThread();
return mTabObserverDelegate.unregisterObserver(tabObserver);
}
private class MessageEventListenerProxy {
private MessageEventListener mListener;
private List<String> mAllowedOrigins;
private MessageEventListenerProxy(
MessageEventListener listener, List<String> allowedOrigins) {
mListener = listener;
mAllowedOrigins = allowedOrigins;
}
private MessageEventListener getListener() {
return mListener;
}
private List<String> getAllowedOrigins() {
return mAllowedOrigins;
}
private void onPostMessage(String message, String origin) {
if (!mAllowedOrigins.contains("*") && !mAllowedOrigins.contains(origin)) {
return;
}
mListener.onMessage(Tab.this, message);
}
}
/**
* Add an event listener for post messages from the web content.
* @param listener Receives the message events posted for the web content.
* @param allowedOrigins The list of origins to accept messages from. "*" will match all
* origins.
*/
public void addMessageEventListener(
@NonNull MessageEventListener listener, @NonNull List<String> allowedOrigins) {
ThreadCheck.ensureOnUiThread();
if (mTabProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
// TODO(crbug.com/1408811): Validate the list of origins.
MessageEventListenerProxy proxy = new MessageEventListenerProxy(listener, allowedOrigins);
mMessageEventListenerProxies.addObserver(proxy);
if (mPostMessageReady) {
// We already created a message event listener in the sandbox. However we need to update
// the list of allowedOrigins in the sandbox. This is done so that a message (with a
// valid listener on this end) is sent over IPC once.
try {
mTabProxy.addMessageEventListener(proxy.getAllowedOrigins());
} catch (RemoteException e) {
throw new IllegalStateException("Failed to communicate with WebSandbox");
}
return;
}
IPostMessageCallback callback = new IPostMessageCallback.Stub() {
@Override
public void onPostMessage(String message, String origin) {
for (MessageEventListenerProxy p : mMessageEventListenerProxies) {
p.onPostMessage(message, origin);
}
}
};
try {
mTabProxy.createMessageEventListener(callback, proxy.getAllowedOrigins());
mPostMessageReady = true;
} catch (RemoteException e) {
throw new IllegalStateException("Failed to communicate with WebSandbox");
}
}
/**
* Removes the event listener.
*/
public void removeMessageEventListener(@NonNull MessageEventListener listener) {
ThreadCheck.ensureOnUiThread();
MessageEventListenerProxy targetProxy = null;
for (MessageEventListenerProxy proxy : mMessageEventListenerProxies) {
if (proxy.getListener().equals(listener)) {
targetProxy = proxy;
break;
}
}
if (targetProxy == null) {
return;
}
mMessageEventListenerProxies.removeObserver(targetProxy);
try {
mTabProxy.removeMessageEventListener(targetProxy.getAllowedOrigins());
} catch (RemoteException e) {
throw new IllegalStateException("Failed to communicate with WebSandbox");
}
}
/**
* Sends a post message to the web content. The targetOrigin must also be specified to ensure
* the right receiver gets the message.
*
* To receive the message in the web page, you need to add a "message" event listener to the
* window object.
*
* <pre class="prettyprint">
* // Web page (in JavaScript):
* window.addEventListener('message', e => {
* // |e.data| contains the payload.
* // |e.origin| contains the host app id, in the format of app://<package_name>.
* console.log('Received message', e.data, 'from', e.origin);
* // |e.ports[0]| can be used to communicate back with the host app.
* e.ports[0].postMessage('Received ' + e.data);
* });
* </pre>
*
* @param message The message to be sent to the web page.
* @param targetOrigin The origin of the page that should receive the message. If '*' is
* provided, the message will be accepted by a page of any origin.
*/
public void postMessage(@NonNull String message, @NonNull String targetOrigin) {
ThreadCheck.ensureOnUiThread();
if (mTabProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mTabProxy.postMessage(message, targetOrigin);
} catch (RemoteException e) {
}
}
/**
* Attaches a callback to handle fullscreen events from the web content.
*/
public void setFullscreenCallback(@NonNull FullscreenCallback callback) {
ThreadCheck.ensureOnUiThread();
mFullscreenCallbackDelegate.setFullscreenCallback(callback);
}
@Override
public int hashCode() {
return mGuid.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj instanceof Tab) {
return this == obj || mGuid.equals(((Tab) obj).getGuid());
}
return false;
}
void invalidate() {
mTabProxy = null;
mTabNavigationController.invalidate();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/Tab.java | Java | unknown | 12,113 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* An interface for observing changes to the set of Tabs in a WebFragment.
*/
public interface TabListObserver {
/**
* The active tab has changed.
*
* @param webEngine the webEngine associated with this event.
* @param activeTab The newly active tab, null if no tab is active.
*/
public default void onActiveTabChanged(@NonNull WebEngine webEngine, @Nullable Tab activeTab) {}
/**
* A tab was added to the WebFragment.
*
* @param webEngine the webEngine associated with this event.
* @param tab The tab that was added.
*/
public default void onTabAdded(@NonNull WebEngine webEngine, @NonNull Tab tab) {}
/**
* A tab was removed from the WebFragment.
*
* WARNING: this is *not* called when the WebFragment is destroyed.
*
* @param webEngine the webEngine associated with this event.
* @param tab The tab that was removed.
*/
public default void onTabRemoved(@NonNull WebEngine webEngine, @NonNull Tab tab) {}
/**
* Called when the WebFragment is about to be destroyed. After this
* call the WebFragment with all Tabs are destroyed and can not be used.
*
* @param webEngine the webEngine associated with this event.
*/
public default void onWillDestroyFragmentAndAllTabs(@NonNull WebEngine webEngine) {}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/TabListObserver.java | Java | unknown | 1,605 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.base.Callback;
import org.chromium.base.ObserverList;
import org.chromium.webengine.interfaces.ITabListObserverDelegate;
import org.chromium.webengine.interfaces.ITabParams;
/**
* {@link TabListObserverDelegate} notifies {@link TabListObserver}s of events in the Fragment.
*/
class TabListObserverDelegate extends ITabListObserverDelegate.Stub {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private WebEngine mWebEngine;
private TabRegistry mTabRegistry;
private ObserverList<TabListObserver> mTabListObservers = new ObserverList<TabListObserver>();
private Callback<Void> mInitializationFinishedCallback;
public TabListObserverDelegate(WebEngine webEngine, TabRegistry tabRegistry) {
// Assert on UI thread as ObserverList can only be accessed from one thread.
ThreadCheck.ensureOnUiThread();
mWebEngine = webEngine;
mTabRegistry = tabRegistry;
}
void setInitializationFinishedCallback(Callback<Void> initializationFinishedCallback) {
mInitializationFinishedCallback = initializationFinishedCallback;
}
/**
* Register a TabListObserver. Call only from the UI thread.
*
* @return true if the observer was added to the list of observers.
*/
boolean registerObserver(TabListObserver tabListObserver) {
ThreadCheck.ensureOnUiThread();
return mTabListObservers.addObserver(tabListObserver);
}
/**
* Unregister a TabListObserver. Call only from the UI thread.
*
* @return true if the observer was removed from the list of observers.
*/
boolean unregisterObserver(TabListObserver tabListObserver) {
ThreadCheck.ensureOnUiThread();
return mTabListObservers.removeObserver(tabListObserver);
}
@Override
public void notifyActiveTabChanged(@Nullable ITabParams tabParams) {
mHandler.post(() -> {
Tab tab = null;
if (tabParams != null) {
tab = mTabRegistry.getOrCreateTab(tabParams);
}
mTabRegistry.setActiveTab(tab);
for (TabListObserver observer : mTabListObservers) {
observer.onActiveTabChanged(mWebEngine, tab);
}
});
}
@Override
public void notifyTabAdded(@NonNull ITabParams tabParams) {
mHandler.post(() -> {
Tab tab = mTabRegistry.getOrCreateTab(tabParams);
for (TabListObserver observer : mTabListObservers) {
observer.onTabAdded(mWebEngine, tab);
}
});
}
@Override
public void notifyTabRemoved(@NonNull ITabParams tabParams) {
mHandler.post(() -> {
Tab tab = mTabRegistry.getOrCreateTab(tabParams);
mTabRegistry.removeTab(tab);
for (TabListObserver observer : mTabListObservers) {
observer.onTabRemoved(mWebEngine, tab);
}
});
}
@Override
public void notifyWillDestroyBrowserAndAllTabs() {
mHandler.post(() -> {
for (TabListObserver observer : mTabListObservers) {
observer.onWillDestroyFragmentAndAllTabs(mWebEngine);
}
});
}
@Override
public void onFinishedTabInitialization() {
mHandler.post(() -> {
if (mInitializationFinishedCallback != null) {
mInitializationFinishedCallback.onResult(null);
mInitializationFinishedCallback = null;
}
});
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/TabListObserverDelegate.java | Java | unknown | 3,838 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.concurrent.futures.CallbackToFutureAdapter;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.base.Callback;
import org.chromium.webengine.interfaces.ITabCallback;
import org.chromium.webengine.interfaces.ITabManagerDelegate;
import org.chromium.webengine.interfaces.ITabParams;
import java.util.Set;
/**
* Class for interaction with WebEngine Tabs.
* Calls into WebEngineDelegate which runs on the Binder thread, and requires
* finished initialization from onCreate on UIThread.
* Access only via ListenableFuture through WebEngine.
*/
public class TabManager {
@NonNull
private ITabManagerDelegate mDelegate;
@NonNull
private WebEngine mWebEngine;
@NonNull
private TabRegistry mTabRegistry;
@NonNull
private final TabListObserverDelegate mTabListObserverDelegate;
@NonNull
private Callback mInitializedTabsCallback;
private final class TabCallback extends ITabCallback.Stub {
private CallbackToFutureAdapter.Completer<Tab> mCompleter;
TabCallback(CallbackToFutureAdapter.Completer<Tab> completer) {
mCompleter = completer;
}
@Override
public void onResult(@Nullable ITabParams tabParams) {
if (tabParams != null) {
new Handler(Looper.getMainLooper()).post(() -> {
mCompleter.set(mTabRegistry.getOrCreateTab(tabParams));
});
return;
}
mCompleter.set(null);
}
};
TabManager(ITabManagerDelegate delegate, WebEngine webEngine) {
mDelegate = delegate;
mWebEngine = webEngine;
mTabRegistry = new TabRegistry(mWebEngine);
mTabListObserverDelegate = new TabListObserverDelegate(mWebEngine, mTabRegistry);
try {
mDelegate.setTabListObserverDelegate(mTabListObserverDelegate);
} catch (RemoteException e) {
}
}
void initialize(Callback<Void> initializedCallback) {
mTabListObserverDelegate.setInitializationFinishedCallback(initializedCallback);
try {
mDelegate.notifyInitialTabs();
} catch (RemoteException e) {
}
}
/**
* Registers a tab observer and returns if successful.
*
* @param tabListObserver The TabListObserver.
*/
public boolean registerTabListObserver(@NonNull TabListObserver tabListObserver) {
ThreadCheck.ensureOnUiThread();
return mTabListObserverDelegate.registerObserver(tabListObserver);
}
/**
* Unregisters a tab observer and returns if successful.
*
* @param tabListObserver The TabListObserver to remove.
*/
public boolean unregisterTabListObserver(@NonNull TabListObserver tabListObserver) {
ThreadCheck.ensureOnUiThread();
return mTabListObserverDelegate.unregisterObserver(tabListObserver);
}
/**
* Returns the currently active Tab or null if no Tab is active.
*/
@Nullable
public Tab getActiveTab() {
return mTabRegistry.getActiveTab();
}
/**
* Creates a new Tab and returns it in a ListenableFuture.
*/
@NonNull
public ListenableFuture<Tab> createTab() {
ThreadCheck.ensureOnUiThread();
if (mDelegate == null) {
return Futures.immediateFailedFuture(
new IllegalStateException("WebSandbox has been destroyed"));
}
return CallbackToFutureAdapter.getFuture(completer -> {
try {
mDelegate.createTab(new TabCallback(completer));
} catch (RemoteException e) {
completer.setException(e);
}
// Debug string.
return "Create Tab Future";
});
}
/**
* Returns a set of all the tabs.
*/
@NonNull
public Set<Tab> getAllTabs() {
return mTabRegistry.getTabs();
}
void invalidate() {
mDelegate = null;
mTabRegistry.invalidate();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/TabManager.java | Java | unknown | 4,412 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.concurrent.futures.CallbackToFutureAdapter;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.webengine.interfaces.ExceptionType;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.ITabNavigationControllerProxy;
/**
* TabNavigationController controls the navigation in a Tab.
*/
public class TabNavigationController {
@NonNull
private ITabNavigationControllerProxy mTabNavigationControllerProxy;
@NonNull
private NavigationObserverDelegate mNavigationObserverDelegate;
private final class RequestNavigationCallback extends IBooleanCallback.Stub {
private CallbackToFutureAdapter.Completer<Boolean> mCompleter;
RequestNavigationCallback(CallbackToFutureAdapter.Completer<Boolean> completer) {
mCompleter = completer;
}
@Override
public void onResult(boolean possible) {
mCompleter.set(possible);
}
@Override
public void onException(@ExceptionType int type, String msg) {
mCompleter.setException(ExceptionHelper.createException(type, msg));
}
};
TabNavigationController(Tab tab, ITabNavigationControllerProxy tabNavigationControllerProxy) {
mTabNavigationControllerProxy = tabNavigationControllerProxy;
mNavigationObserverDelegate = new NavigationObserverDelegate(tab);
try {
mTabNavigationControllerProxy.setNavigationObserverDelegate(
mNavigationObserverDelegate);
} catch (RemoteException e) {
}
}
/**
* Navigates this Tab to the given URI.
*
* @param uri The destination URI.
*/
public void navigate(@NonNull String uri) {
ThreadCheck.ensureOnUiThread();
if (mTabNavigationControllerProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mTabNavigationControllerProxy.navigate(uri);
} catch (RemoteException e) {
}
}
/**
* Navigates to the previous navigation.
*/
public void goBack() {
ThreadCheck.ensureOnUiThread();
if (mTabNavigationControllerProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mTabNavigationControllerProxy.goBack();
} catch (RemoteException e) {
}
}
/**
* Navigates to the next navigation.
*/
public void goForward() {
ThreadCheck.ensureOnUiThread();
if (mTabNavigationControllerProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mTabNavigationControllerProxy.goForward();
} catch (RemoteException e) {
}
}
/**
* Reloads this Tab. Does nothing if there are no navigations.
*/
public void reload() {
ThreadCheck.ensureOnUiThread();
if (mTabNavigationControllerProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mTabNavigationControllerProxy.reload();
} catch (RemoteException e) {
}
}
/**
* Stops in progress loading. Does nothing if not in the process of loading.
*/
public void stop() {
ThreadCheck.ensureOnUiThread();
if (mTabNavigationControllerProxy == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mTabNavigationControllerProxy.stop();
} catch (RemoteException e) {
}
}
/**
* Returns a ListenablePromise that resolves to true if there is a navigation before the current
* one.
*/
@NonNull
public ListenableFuture<Boolean> canGoBack() {
ThreadCheck.ensureOnUiThread();
if (mTabNavigationControllerProxy == null) {
return Futures.immediateFailedFuture(
new IllegalStateException("WebSandbox has been destroyed"));
}
return CallbackToFutureAdapter.getFuture(completer -> {
mTabNavigationControllerProxy.canGoBack(new RequestNavigationCallback(completer));
// Debug string.
return "Can navigate back Future";
});
}
/**
* Returns a ListenablePromise that resolves to true if there is a navigation after the current
* one.
*/
@NonNull
public ListenableFuture<Boolean> canGoForward() {
ThreadCheck.ensureOnUiThread();
if (mTabNavigationControllerProxy == null) {
return Futures.immediateFailedFuture(
new IllegalStateException("WebSandbox has been destroyed"));
}
return CallbackToFutureAdapter.getFuture(completer -> {
mTabNavigationControllerProxy.canGoForward(new RequestNavigationCallback(completer));
// Debug string.
return "Can navigate forward Future";
});
}
/**
* Registers a {@link NavigationObserver} and returns if successful.
*
* @param navigationObserver The {@link NavigationObserver}.
*/
public boolean registerNavigationObserver(@NonNull NavigationObserver navigationObserver) {
ThreadCheck.ensureOnUiThread();
return mNavigationObserverDelegate.registerObserver(navigationObserver);
}
/**
* Unregisters a {@link NavigationObserver} and returns if successful.
*
* @param navigationObserver The TabObserver to remove.
*
* @return true if observer was removed from the list of observers.
*/
public boolean unregisterNavigationObserver(@NonNull NavigationObserver navigationObserver) {
ThreadCheck.ensureOnUiThread();
return mNavigationObserverDelegate.unregisterObserver(navigationObserver);
}
void invalidate() {
mTabNavigationControllerProxy = null;
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/TabNavigationController.java | Java | unknown | 6,291 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* An interface for observing changes to a Tab.
*/
public interface TabObserver {
/**
* The Uri that can be displayed in the location-bar has updated.
*
* @param tab the tab associated with this event.
* @param uri The new user-visible uri.
*/
public default void onVisibleUriChanged(@NonNull Tab tab, @NonNull String uri) {}
/**
* Called when the title of this tab changes. Note before the page sets a title, the title may
* be a portion of the Uri.
*
* @param tab the tab associated with this event.
* @param title New title of this tab.
*/
public default void onTitleUpdated(@NonNull Tab tab, @NonNull String title) {}
/**
* Called when the favicon of the tab has changed.
*
* @param tab the tab associated with this event.
* @param favicon The favicon associated with the Tab. null if there is no favicon.
*/
public default void onFaviconChanged(@NonNull Tab tab, @Nullable Bitmap favicon) {}
/**
* Triggered when the render process dies, either due to crash or killed by the system to
* reclaim memory.
*
* @param tab the tab associated with this event.
*/
public default void onRenderProcessGone(@NonNull Tab tab) {}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/TabObserver.java | Java | unknown | 1,553 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import org.chromium.base.ObserverList;
import org.chromium.webengine.interfaces.ITabObserverDelegate;
/**
* {@link TabObserverDelegate} notifies registered {@Link TabObserver}s of events in the Tab.
*/
class TabObserverDelegate extends ITabObserverDelegate.Stub {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private Tab mTab;
private ObserverList<TabObserver> mTabObservers = new ObserverList<TabObserver>();
public TabObserverDelegate(Tab tab) {
// Assert on UI thread as ObserverList can only be accessed from one thread.
ThreadCheck.ensureOnUiThread();
mTab = tab;
}
/**
* Registers a {@link TabObserver}. Call only from the UI thread.
*
* @return true if the observer was added to the list of observers.
*/
boolean registerObserver(TabObserver tabObserver) {
ThreadCheck.ensureOnUiThread();
return mTabObservers.addObserver(tabObserver);
}
/**
* Unregisters a {@link TabObserver}. Call only from the UI thread.
*
* @return true if the observer was removed from the list of observers.
*/
boolean unregisterObserver(TabObserver tabObserver) {
ThreadCheck.ensureOnUiThread();
return mTabObservers.removeObserver(tabObserver);
}
@Override
public void notifyVisibleUriChanged(@NonNull String uri) {
mHandler.post(() -> {
mTab.setDisplayUri(Uri.parse(uri));
for (TabObserver observer : mTabObservers) {
observer.onVisibleUriChanged(mTab, uri);
}
});
}
@Override
public void notifyTitleUpdated(@NonNull String title) {
mHandler.post(() -> {
for (TabObserver observer : mTabObservers) {
observer.onTitleUpdated(mTab, title);
}
});
}
@Override
public void notifyRenderProcessGone() {
mHandler.post(() -> {
for (TabObserver observer : mTabObservers) {
observer.onRenderProcessGone(mTab);
}
});
}
@Override
public void notifyFaviconChanged(Bitmap favicon) {
mHandler.post(() -> {
for (TabObserver observer : mTabObservers) {
observer.onFaviconChanged(mTab, favicon);
}
});
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/TabObserverDelegate.java | Java | unknown | 2,654 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import androidx.annotation.Nullable;
import org.chromium.webengine.interfaces.ITabParams;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Tab registry for storing open {@link Tab}s per WebEngine on the webengine side.
*
* For internal use only.
*/
class TabRegistry {
private WebEngine mWebEngine;
private Map<String, Tab> mGuidToTab = new HashMap<String, Tab>();
@Nullable
private Tab mActiveTab;
TabRegistry(WebEngine webEngine) {
mWebEngine = webEngine;
}
Tab getOrCreateTab(ITabParams tabParams) {
Tab tab = mGuidToTab.get(tabParams.tabGuid);
if (tab == null) {
tab = new Tab(mWebEngine, tabParams);
mGuidToTab.put(tabParams.tabGuid, tab);
}
return tab;
}
void removeTab(Tab tab) {
mGuidToTab.remove(tab.getGuid());
}
void invalidate() {
for (Tab tab : mGuidToTab.values()) {
tab.invalidate();
}
mGuidToTab.clear();
}
Set<Tab> getTabs() {
return new HashSet(mGuidToTab.values());
}
void setActiveTab(Tab tab) {
mActiveTab = tab;
}
Tab getActiveTab() {
return mActiveTab;
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/TabRegistry.java | Java | unknown | 1,428 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.Looper;
import android.util.AndroidRuntimeException;
class ThreadCheck {
static void ensureOnUiThread() {
if (Looper.getMainLooper() != Looper.myLooper()) {
throw new AndroidRuntimeException("This method needs to be called on the main thread");
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/ThreadCheck.java | Java | unknown | 483 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.concurrent.futures.CallbackToFutureAdapter;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.base.Callback;
import org.chromium.webengine.interfaces.ExceptionType;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.ICookieManagerDelegate;
import org.chromium.webengine.interfaces.ITabManagerDelegate;
import org.chromium.webengine.interfaces.IWebEngineDelegate;
import org.chromium.webengine.interfaces.IWebFragmentEventsDelegate;
/**
* WebEngine is created via the WebSandbox and is used to interact with its content as well as to
* obtain its Fragment.
*/
public class WebEngine {
@NonNull
private WebSandbox mWebSandbox;
@NonNull
private String mTag;
@NonNull
private IWebEngineDelegate mDelegate;
@NonNull
private WebFragment mFragment;
@NonNull
private TabManager mTabManager;
@NonNull
private CookieManager mCookieManager;
private WebEngine(WebSandbox webSandbox, IWebEngineDelegate delegate,
IWebFragmentEventsDelegate fragmentEventsDelegate,
ITabManagerDelegate tabManagerDelegate, ICookieManagerDelegate cookieManagerDelegate,
String tag) {
ThreadCheck.ensureOnUiThread();
mWebSandbox = webSandbox;
mTag = tag;
mDelegate = delegate;
mFragment = new WebFragment();
try {
mFragment.initialize(webSandbox, this, fragmentEventsDelegate);
} catch (RemoteException e) {
}
mTabManager = new TabManager(tabManagerDelegate, this);
mCookieManager = new CookieManager(cookieManagerDelegate);
}
static WebEngine create(WebSandbox webSandbox, IWebEngineDelegate delegate,
IWebFragmentEventsDelegate fragmentEventsDelegate,
ITabManagerDelegate tabManagerDelegate, ICookieManagerDelegate cookieManagerDelegate,
String tag) {
return new WebEngine(webSandbox, delegate, fragmentEventsDelegate, tabManagerDelegate,
cookieManagerDelegate, tag);
}
void initializeTabManager(Callback<Void> initializationFinishedCallback) {
mTabManager.initialize(initializationFinishedCallback);
}
/**
* Returns the TabManager.
*/
@NonNull
public TabManager getTabManager() {
return mTabManager;
}
/**
* Returns the CookieManager.
*/
@NonNull
public CookieManager getCookieManager() {
return mCookieManager;
}
void updateFragment(WebFragment fragment) {
mFragment = fragment;
}
private final class RequestNavigationCallback extends IBooleanCallback.Stub {
private CallbackToFutureAdapter.Completer<Boolean> mCompleter;
RequestNavigationCallback(CallbackToFutureAdapter.Completer<Boolean> completer) {
mCompleter = completer;
}
@Override
public void onResult(boolean didNavigate) {
mCompleter.set(didNavigate);
}
@Override
public void onException(@ExceptionType int type, String msg) {
mCompleter.setException(ExceptionHelper.createException(type, msg));
}
}
/**
* Tries to navigate back inside the WebEngine session and returns a Future with a Boolean
* which is true if the back navigation was successful.
*
* Only recommended to use if no switching of Tabs is used.
*
* Navigates back inside the currently active tab if possible. If that is not possible,
* checks if any Tab was added to the WebEngine before the currently active Tab,
* if so, the currently active Tab is closed and this Tab is set to active.
*/
@NonNull
public ListenableFuture<Boolean> tryNavigateBack() {
ThreadCheck.ensureOnUiThread();
if (mDelegate == null) {
return Futures.immediateFailedFuture(
new IllegalStateException("WebSandbox has been destroyed"));
}
return CallbackToFutureAdapter.getFuture(completer -> {
mDelegate.tryNavigateBack(new RequestNavigationCallback(completer));
// Debug string.
return "Did navigate back Future";
});
}
/**
* Returns the WebFragment.
*/
@NonNull
public WebFragment getFragment() {
return mFragment;
}
/**
* Returns the tag associated with this WebEngine instance.
*/
@NonNull
public String getTag() {
return mTag;
}
void invalidate() {
ThreadCheck.ensureOnUiThread();
if (mTabManager != null) {
mTabManager.invalidate();
mTabManager = null;
}
if (mCookieManager != null) {
mCookieManager.invalidate();
mCookieManager = null;
}
if (mFragment != null) {
mFragment.invalidate();
mFragment = null;
}
if (mDelegate != null) {
try {
mDelegate.shutdown();
} catch (RemoteException e) {
}
mDelegate = null;
}
if (mWebSandbox != null && !mWebSandbox.isShutdown()) {
mWebSandbox.removeWebEngine(mTag, this);
}
mWebSandbox = null;
}
/**
* Close this WebEngine.
*/
public void close() {
invalidate();
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/WebEngine.java | Java | unknown | 5,689 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.webengine.interfaces.IWebEngineParams;
import java.util.ArrayList;
/**
* Parameters for {@link WebSandbox#createFragment}.
*/
public class WebEngineParams {
@Nullable
private String mProfileName;
@Nullable
private String mPersistenceId;
private boolean mIsIncognito;
private boolean mIsExternalIntentsEnabled = true;
@Nullable
private ArrayList<String> mAllowedOrigins;
IWebEngineParams getParcelable() {
IWebEngineParams params = new IWebEngineParams();
params.profileName = mProfileName;
params.persistenceId = mPersistenceId;
params.isIncognito = mIsIncognito;
params.isExternalIntentsEnabled = mIsExternalIntentsEnabled;
params.allowedOrigins = mAllowedOrigins;
return params;
}
/**
* A Builder class to help create WebEngineParams.
*/
public static final class Builder {
private WebEngineParams mParams = new WebEngineParams();
/**
* Returns the WebEngineParam instance asscoaiated with this Builder.
*/
@NonNull
public WebEngineParams build() {
return mParams;
}
/**
* Sets the name of the profile. Null or empty string implicitly creates an incognito
* profile. If {@code profile} must only contain alphanumeric and underscore characters
* since it will be used as a directory name in the file system.
*
* @param profileName The name of the profile.
*/
@NonNull
public Builder setProfileName(@Nullable String profileName) {
mParams.mProfileName = profileName;
return this;
}
/**
* Sets the persistence id, which uniquely identifies the Fragment for saving the set of
* tabs and navigations. A value of null does not save/restore any state. A non-null value
* results in asynchronously restoring the tabs and navigations. Supplying a non-null value
* means the Fragment initially has no tabs (until restore is complete).
*
* @param persistenceId The id for persistence.
*/
@NonNull
public Builder setPersistenceId(@Nullable String persistenceId) {
mParams.mPersistenceId = persistenceId;
return this;
}
/**
* Sets whether the profile is incognito.
* @param isIncognito Whether the profile should be incognito.
*/
@NonNull
public Builder setIsIncognito(boolean isIncognito) {
mParams.mIsIncognito = isIncognito;
return this;
}
/**
* Sets whether pages will be able to open native intents.
* @param isExternalIntentsEnabled Whether all pages will have the ability to open intent
* urls.
*/
@NonNull
public Builder setIsExternalIntentsEnabled(boolean isExternalIntentsEnabled) {
mParams.mIsExternalIntentsEnabled = isExternalIntentsEnabled;
return this;
}
/**
* Sets whether a list of origins are allowed to be navigated to. If this is not set all
* origins will be allowed.
* @param allowedOrigins An ArrayList of origins the WebEngine can navigate to.
* This does not support wild cards; full host strings must be provided.
*
* <pre>
* {@code
* ArrayList<String> allowList = new ArrayList<>();
* allowList.add("https://www.example.com");
* allowList.add("http://foo.com");
*
* new WebEngineParams.Builder()
* .setAllowedOrigins(allowList)
* .build();
* }
* </pre>
*/
@NonNull
public Builder setAllowedOrigins(@Nullable ArrayList<String> allowedOrigins) {
mParams.mAllowedOrigins = allowedOrigins;
return this;
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/WebEngineParams.java | Java | unknown | 4,225 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.SurfaceControlViewHost.SurfacePackage;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import org.chromium.webengine.interfaces.IWebFragmentEventsDelegate;
import org.chromium.webengine.interfaces.IWebFragmentEventsDelegateClient;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* Fragment for rendering web content. This is obtained through WebEngine.
*/
public class WebFragment extends Fragment {
@Nullable
private WebSandbox mWebSandbox;
@Nullable
private WebEngine mWebEngine;
@Nullable
private IWebFragmentEventsDelegate mDelegate;
private final IWebFragmentEventsDelegateClient mClient =
new IWebFragmentEventsDelegateClient.Stub() {
@Override
public void onSurfacePackageReady(SurfacePackage surfacePackage) {
SurfaceView surfaceView = (SurfaceView) WebFragment.super.getView();
surfaceView.setChildSurfacePackage(surfacePackage);
}
@Override
public void onContentViewRenderViewReady(
IObjectWrapper wrappedContentViewRenderView) {
LinearLayout layout = (LinearLayout) WebFragment.super.getView();
layout.addView(ObjectWrapper.unwrap(wrappedContentViewRenderView, View.class));
}
};
private SurfaceHolder.Callback mSurfaceHolderCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
IBinder hostToken = ((SurfaceView) getView()).getHostToken();
assert hostToken != null;
try {
mDelegate.attachViewHierarchy(hostToken);
} catch (RemoteException e) {
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
resizeSurfaceView(width, height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {}
};
/**
* This constructor is for the system FragmentManager only. Please use
* {@link WebSandbox#createFragment}.
*/
public WebFragment() {}
void initialize(WebSandbox webSandbox, WebEngine webEngine, IWebFragmentEventsDelegate delegate)
throws RemoteException {
mWebSandbox = webSandbox;
mWebEngine = webEngine;
mDelegate = delegate;
}
/**
* Returns the {@link WebEngine} associated with this Fragment.
*/
@NonNull
public WebEngine getWebEngine() {
return mWebEngine;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
WebViewModel model = getViewModel();
if (model.hasSavedState()) {
// Load from view model.
assert mWebSandbox == null;
mWebSandbox = model.mWebSandbox;
mWebEngine = model.mWebEngine;
mDelegate = model.mDelegate;
// Recreating a WebFragment e.g. after rotating the device creates a new WebFragment
// based on the data from the ViewModel. The WebFragment in the WebEngine needs to be
// updated as it needs to have the current instance.
mWebEngine.updateFragment(this);
} else {
// Save to View model.
assert mWebSandbox != null;
model.mWebSandbox = mWebSandbox;
model.mWebEngine = mWebEngine;
model.mDelegate = mDelegate;
}
if (mWebSandbox.isShutdown()) {
// This is likely due to an inactive fragment being attached after the Web Sandbox
// has been killed.
invalidate();
return;
}
AppCompatDelegate.create(getActivity(), null);
try {
mDelegate.setClient(mClient);
if (WebSandbox.isInProcessMode(context)) {
// Pass the activity context for the in-process mode.
// This is because the Autofill Manager is only available with activity contexts.
// This will be cleaned up when the fragment is detached.
mDelegate.onAttachWithContext(
ObjectWrapper.wrap(context), ObjectWrapper.wrap((Fragment) this));
} else {
mDelegate.onAttach();
}
} catch (RemoteException e) {
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mDelegate.onCreate();
} catch (RemoteException e) {
}
}
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (WebSandbox.isInProcessMode(getActivity())) {
LinearLayout layout = new LinearLayout(getActivity());
try {
mDelegate.retrieveContentViewRenderView();
} catch (RemoteException e) {
}
return layout;
} else {
return new WebSurfaceView(getActivity(), mSurfaceHolderCallback);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
mDelegate.onActivityResult(requestCode, resultCode, ObjectWrapper.wrap(data));
} catch (RemoteException e) {
}
}
@Override
public void onDestroy() {
super.onDestroy();
try {
mDelegate.onDestroy();
} catch (RemoteException e) {
}
}
@Override
public void onDetach() {
super.onDetach();
try {
mDelegate.onDetach();
} catch (RemoteException e) {
}
}
@Override
public void onStart() {
super.onStart();
try {
mDelegate.onStart();
} catch (RemoteException e) {
}
}
@Override
public void onStop() {
super.onStop();
try {
mDelegate.onStop();
} catch (RemoteException e) {
}
}
@Override
public void onResume() {
super.onResume();
try {
mDelegate.onResume();
} catch (RemoteException e) {
}
}
@Override
public void onPause() {
super.onPause();
try {
mDelegate.onPause();
} catch (RemoteException e) {
}
}
/**
* Returns the Sandbox that created this WebFragment.
*/
@NonNull
public WebSandbox getWebSandbox() {
return mWebSandbox;
}
private void resizeSurfaceView(int width, int height) {
try {
mDelegate.resizeView(width, height);
} catch (RemoteException e) {
}
}
private WebViewModel getViewModel() {
return new ViewModelProvider(this).get(WebViewModel.class);
}
void invalidate() {
try {
// The fragment is synchronously removed so that the shutdown steps can complete.
getParentFragmentManager().beginTransaction().remove(this).commitNow();
} catch (IllegalStateException e) {
// Fragment already removed from FragmentManager.
return;
} finally {
mDelegate = null;
mWebEngine = null;
mWebSandbox = null;
}
}
/**
* A custom SurfaceView that registers a SurfaceHolder.Callback.
*/
private class WebSurfaceView extends SurfaceView {
private SurfaceHolder.Callback mSurfaceHolderCallback;
WebSurfaceView(Context context, SurfaceHolder.Callback surfaceHolderCallback) {
super(context);
mSurfaceHolderCallback = surfaceHolderCallback;
setZOrderOnTop(true);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
getHolder().addCallback(mSurfaceHolderCallback);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
getHolder().removeCallback(mSurfaceHolderCallback);
}
}
/**
* This class is an implementation detail and not intended for public use. It may change at any
* time in incompatible ways, including being removed.
*
* This class stores WebFragment specific state to a ViewModel so that it can reused if a
* new Fragment is created that should share the same state.
*/
public static final class WebViewModel extends ViewModel {
@Nullable
private WebSandbox mWebSandbox;
@Nullable
private WebEngine mWebEngine;
@Nullable
private IWebFragmentEventsDelegate mDelegate;
boolean hasSavedState() {
return mWebSandbox != null;
}
@Override
public void onCleared() {
mWebSandbox = null;
mWebEngine = null;
mDelegate = null;
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/WebFragment.java | Java | unknown | 9,825 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.concurrent.futures.CallbackToFutureAdapter;
import androidx.core.content.ContextCompat;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.ICookieManagerDelegate;
import org.chromium.webengine.interfaces.IStringCallback;
import org.chromium.webengine.interfaces.ITabManagerDelegate;
import org.chromium.webengine.interfaces.IWebEngineDelegate;
import org.chromium.webengine.interfaces.IWebEngineDelegateClient;
import org.chromium.webengine.interfaces.IWebFragmentEventsDelegate;
import org.chromium.webengine.interfaces.IWebSandboxCallback;
import org.chromium.webengine.interfaces.IWebSandboxService;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Handle to the browsing sandbox. Must be created asynchronously.
*/
public class WebSandbox {
private final Handler mHandler = new Handler(Looper.getMainLooper());
// TODO(swestphal): Remove this and its function args and detect which service should be used
// based on android version.
private static final String BROWSER_PROCESS_MODE =
"org.chromium.webengine.shell.BrowserProcessMode";
// Use another APK as a placeholder for an actual sandbox, since they are conceptually the
// same thing.
private static final String SANDBOX_BROWSER_SANDBOX_PACKAGE = "org.chromium.webengine.sandbox";
private static final String BROWSER_SANDBOX_ACTION =
"org.chromium.weblayer.intent.action.BROWSERSANDBOX";
private static final String BROWSER_INPROCESS_ACTION =
"org.chromium.weblayer.intent.action.BROWSERINPROCESS";
private static final String DEFAULT_PROFILE_NAME = "DefaultProfile";
@Nullable
private static WebSandbox sInstance;
@NonNull
private IWebSandboxService mWebSandboxService;
@NonNull
private SandboxConnection mConnection;
@NonNull
private Map<String, WebEngine> mActiveWebEngines = new HashMap<String, WebEngine>();
private static class SandboxConnection implements ServiceConnection {
private static ListenableFuture<SandboxConnection> sSandboxConnectionFuture;
private static SandboxConnection sSandboxConnectionInstance;
private CallbackToFutureAdapter.Completer<SandboxConnection> mSandboxConnectionCompleter;
private IWebSandboxService mWebSandboxService;
private Context mContext;
private static boolean sPendingBrowserProcessInitialization;
private SandboxConnection(
Context context, CallbackToFutureAdapter.Completer<SandboxConnection> completer) {
mContext = context;
mSandboxConnectionCompleter = completer;
Intent intent = new Intent(
isInProcessMode(mContext) ? BROWSER_INPROCESS_ACTION : BROWSER_SANDBOX_ACTION);
intent.setPackage(isInProcessMode(mContext) ? mContext.getPackageName()
: SANDBOX_BROWSER_SANDBOX_PACKAGE);
mContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
}
static ListenableFuture<SandboxConnection> getInstance(Context context) {
if (sSandboxConnectionInstance != null) {
return Futures.immediateFuture(sSandboxConnectionInstance);
}
if (sSandboxConnectionFuture == null) {
sSandboxConnectionFuture = CallbackToFutureAdapter.getFuture(completer -> {
new SandboxConnection(context, completer);
return "SandboxConnection Future";
});
}
return sSandboxConnectionFuture;
}
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
mWebSandboxService = IWebSandboxService.Stub.asInterface(service);
sSandboxConnectionInstance = this;
sSandboxConnectionFuture = null;
mSandboxConnectionCompleter.set(sSandboxConnectionInstance);
mSandboxConnectionCompleter = null;
}
private CallbackToFutureAdapter.Completer<WebSandbox> mCompleter;
void initializeBrowserProcess(CallbackToFutureAdapter.Completer<WebSandbox> completer) {
assert !sPendingBrowserProcessInitialization
: "SandboxInitialization already in progress";
mCompleter = completer;
sPendingBrowserProcessInitialization = true;
try {
mWebSandboxService.initializeBrowserProcess(new IWebSandboxCallback.Stub() {
@Override
public void onBrowserProcessInitialized() {
sInstance = new WebSandbox(SandboxConnection.this, mWebSandboxService);
mCompleter.set(sInstance);
mCompleter = null;
sPendingBrowserProcessInitialization = false;
}
@Override
public void onBrowserProcessInitializationFailure() {
mCompleter.setException(
new IllegalStateException("Failed to initialize WebSandbox"));
mCompleter = null;
sPendingBrowserProcessInitialization = false;
}
});
} catch (RemoteException e) {
mCompleter.setException(e);
mCompleter = null;
}
}
void isAvailable(CallbackToFutureAdapter.Completer<Boolean> completer)
throws RemoteException {
mWebSandboxService.isAvailable(new IBooleanCallback.Stub() {
@Override
public void onResult(boolean isAvailable) {
completer.set(isAvailable);
}
@Override
public void onException(int type, String msg) {
completer.setException(ExceptionHelper.createException(type, msg));
}
});
}
void getVersion(CallbackToFutureAdapter.Completer<String> completer)
throws RemoteException {
mWebSandboxService.getVersion(new IStringCallback.Stub() {
@Override
public void onResult(String version) {
completer.set(version);
}
@Override
public void onException(int type, String msg) {
completer.setException(ExceptionHelper.createException(type, msg));
}
});
}
void getProviderPackageName(CallbackToFutureAdapter.Completer<String> completer)
throws RemoteException {
mWebSandboxService.getProviderPackageName(new IStringCallback.Stub() {
@Override
public void onResult(String providerPackageName) {
completer.set(providerPackageName);
}
@Override
public void onException(int type, String msg) {
completer.setException(ExceptionHelper.createException(type, msg));
}
});
}
void unbind() {
mContext.unbindService(this);
sSandboxConnectionInstance = null;
sInstance = null;
}
// TODO(rayankans): Actually handle failure / disconnection events.
@Override
public void onServiceDisconnected(ComponentName name) {}
}
private WebSandbox(SandboxConnection connection, IWebSandboxService service) {
mConnection = connection;
mWebSandboxService = service;
}
/**
* Asynchronously creates a handle to the web sandbox after initializing the
* browser process.
* @param context The Android Context.
*/
@NonNull
public static ListenableFuture<WebSandbox> create(@NonNull Context context) {
ThreadCheck.ensureOnUiThread();
if (sInstance != null) {
return Futures.immediateFuture(sInstance);
}
if (SandboxConnection.sPendingBrowserProcessInitialization) {
return Futures.immediateFailedFuture(
new IllegalStateException("WebSandbox is already being created"));
}
Context applicationContext = context.getApplicationContext();
ListenableFuture<SandboxConnection> sandboxConnectionFuture =
SandboxConnection.getInstance(applicationContext);
AsyncFunction<SandboxConnection, WebSandbox> initializeBrowserProcessTask =
sandboxConnection -> {
return CallbackToFutureAdapter.getFuture(completer -> {
sandboxConnection.initializeBrowserProcess(completer);
// Debug string.
return "WebSandbox Sandbox Future";
});
};
return Futures.transformAsync(sandboxConnectionFuture, initializeBrowserProcessTask,
ContextCompat.getMainExecutor(applicationContext));
}
/**
* Returns a ListenableFuture that resolves to whether a WebSandbox is available.
* @param context The Android Context.
*/
@NonNull
public static ListenableFuture<Boolean> isAvailable(@NonNull Context context) {
ThreadCheck.ensureOnUiThread();
Context applicationContext = context.getApplicationContext();
ListenableFuture<SandboxConnection> sandboxConnectionFuture =
SandboxConnection.getInstance(applicationContext);
AsyncFunction<SandboxConnection, Boolean> isAvailableTask = sandboxConnection -> {
return CallbackToFutureAdapter.getFuture(completer -> {
sandboxConnection.isAvailable(completer);
// Debug string.
return "Sandbox Available Future";
});
};
return Futures.transformAsync(sandboxConnectionFuture, isAvailableTask,
ContextCompat.getMainExecutor(applicationContext));
}
/**
* Returns a ListenableFuture that resolves to the version of the provider.
* @param context The Android Context.
*/
@NonNull
public static ListenableFuture<String> getVersion(@NonNull Context context) {
ThreadCheck.ensureOnUiThread();
Context applicationContext = context.getApplicationContext();
ListenableFuture<SandboxConnection> sandboxConnectionFuture =
SandboxConnection.getInstance(applicationContext);
AsyncFunction<SandboxConnection, String> getVersionTask = sandboxConnection -> {
return CallbackToFutureAdapter.getFuture(completer -> {
sandboxConnection.getVersion(completer);
// Debug string.
return "Sandbox Version Future";
});
};
return Futures.transformAsync(sandboxConnectionFuture, getVersionTask,
ContextCompat.getMainExecutor(applicationContext));
}
/**
* Returns a ListenableFuture that resolves to the package name of the provider.
* @param context The Android Context.
*/
@NonNull
public static ListenableFuture<String> getProviderPackageName(@NonNull Context context) {
ThreadCheck.ensureOnUiThread();
Context applicationContext = context.getApplicationContext();
ListenableFuture<SandboxConnection> sandboxConnectionFuture =
SandboxConnection.getInstance(applicationContext);
AsyncFunction<SandboxConnection, String> getProviderPackageNameTask = sandboxConnection -> {
return CallbackToFutureAdapter.getFuture(completer -> {
sandboxConnection.getProviderPackageName(completer);
// Debug string.
return "Sandbox Provider Package Future";
});
};
return Futures.transformAsync(sandboxConnectionFuture, getProviderPackageNameTask,
ContextCompat.getMainExecutor(applicationContext));
}
private class WebEngineDelegateClient extends IWebEngineDelegateClient.Stub {
private CallbackToFutureAdapter.Completer<WebEngine> mWebEngineCompleter;
private String mTag;
WebEngineDelegateClient(
CallbackToFutureAdapter.Completer<WebEngine> completer, String tag) {
mWebEngineCompleter = completer;
mTag = tag;
}
@Override
public void onDelegatesReady(IWebEngineDelegate delegate,
IWebFragmentEventsDelegate fragmentEventsDelegate,
ITabManagerDelegate tabManagerDelegate,
ICookieManagerDelegate cookieManagerDelegate) {
mHandler.post(() -> {
WebEngine engine = WebEngine.create(WebSandbox.this, delegate,
fragmentEventsDelegate, tabManagerDelegate, cookieManagerDelegate, mTag);
engine.initializeTabManager((v) -> {
addWebEngine(mTag, engine);
mWebEngineCompleter.set(engine);
});
});
}
}
private String createNewTag() {
int webEngineIndex = mActiveWebEngines.size();
String tag = String.format("webengine_%d", webEngineIndex);
while (mActiveWebEngines.containsKey(tag)) {
++webEngineIndex;
tag = String.format("webengine_%d", webEngineIndex);
}
return tag;
}
/**
* Asynchronously creates a new WebEngine with default Profile.
*/
@NonNull
public ListenableFuture<WebEngine> createWebEngine() {
ThreadCheck.ensureOnUiThread();
return createWebEngine(createNewTag());
}
/**
* Asynchronously creates a new WebEngine with default Profile and gives it a {@code tag}.
*
* @param tag The tag to be associated with the WebEngine instance.
*/
@NonNull
public ListenableFuture<WebEngine> createWebEngine(@NonNull String tag) {
ThreadCheck.ensureOnUiThread();
if (mActiveWebEngines.containsKey(tag)) {
throw new IllegalArgumentException("Tag already associated with a WebEngine");
}
if (mWebSandboxService == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
WebEngineParams params =
(new WebEngineParams.Builder()).setProfileName(DEFAULT_PROFILE_NAME).build();
return createWebEngine(params, tag);
}
/**
* Asynchronously creates a new WebEngine based on {@code params}.
* @param params The configuration parameters for the WebEngine instance.
*/
@NonNull
public ListenableFuture<WebEngine> createWebEngine(@NonNull WebEngineParams params) {
ThreadCheck.ensureOnUiThread();
return createWebEngine(params, createNewTag());
}
/**
* Asynchronously creates a new WebEngine based on {@code params} and gives it a {@code tag}.
*
* @param params The configuration parameters for the WebEngine instance.
* @param tag The tag to be associated with the WebEngine instance.
*/
@NonNull
public ListenableFuture<WebEngine> createWebEngine(
@NonNull WebEngineParams params, @NonNull String tag) {
ThreadCheck.ensureOnUiThread();
if (mActiveWebEngines.containsKey(tag)) {
throw new IllegalArgumentException("Tag already associated with a WebEngine");
}
if (mWebSandboxService == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
ListenableFuture<WebEngine> futureWebEngine =
CallbackToFutureAdapter.getFuture(completer -> {
mWebSandboxService.createWebEngineDelegate(
params.getParcelable(), new WebEngineDelegateClient(completer, tag));
return "WebEngineClient Future";
});
return futureWebEngine;
}
/**
* Enables or disables DevTools remote debugging.
*
* @param enabled Whether remote debugging should be enabled or not.
*/
public void setRemoteDebuggingEnabled(boolean enabled) {
ThreadCheck.ensureOnUiThread();
if (mWebSandboxService == null) {
throw new IllegalStateException("WebSandbox has been destroyed");
}
try {
mWebSandboxService.setRemoteDebuggingEnabled(enabled);
} catch (RemoteException e) {
}
}
// TODO(swestphal): Remove this again.
static boolean isInProcessMode(Context appContext) {
try {
Bundle metaData = appContext.getPackageManager()
.getApplicationInfo(appContext.getPackageName(),
PackageManager.GET_META_DATA)
.metaData;
if (metaData != null) return metaData.getString(BROWSER_PROCESS_MODE).equals("local");
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
void addWebEngine(String tag, WebEngine webEngine) {
assert !mActiveWebEngines.containsKey(tag) : "Key already associated with a WebEngine";
mActiveWebEngines.put(tag, webEngine);
}
void removeWebEngine(String tag, WebEngine webEngine) {
assert webEngine == mActiveWebEngines.get(tag);
mActiveWebEngines.remove(tag);
}
/**
* Returns the WebEngine with the given tag, or null if no WebEngine exists with this tag.
*
* @param tag the name of the WebEngine.
*/
@Nullable
public WebEngine getWebEngine(String tag) {
return mActiveWebEngines.get(tag);
}
/**
* Returns all active {@link WebEngine}.
*/
@NonNull
public Collection<WebEngine> getWebEngines() {
return mActiveWebEngines.values();
}
boolean isShutdown() {
return mWebSandboxService == null;
}
/**
* Shuts down the WebEngine and closes the sandbox connection.
*/
public void shutdown() {
if (isShutdown()) {
// WebSandbox was already shut down.
return;
}
mWebSandboxService = null;
for (WebEngine engine : mActiveWebEngines.values()) {
// This will shut down the WebEngine, its fragment, and remove {@code engine} from
// {@code mActiveWebEngines}.
engine.invalidate();
}
mActiveWebEngines.clear();
mConnection.unbind();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/WebSandbox.java | Java | unknown | 19,311 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@IntDef({ExceptionType.RESTRICTED_API, ExceptionType.INVALID_ARGUMENT, ExceptionType.UNKNOWN})
@Retention(RetentionPolicy.SOURCE)
public @interface ExceptionType {
int RESTRICTED_API = 0;
int INVALID_ARGUMENT = 1;
int UNKNOWN = 2;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ExceptionType.java | Java | unknown | 554 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
oneway interface IBooleanCallback {
void onResult(in boolean result) = 1;
// TODO(swestphal): Replace parameters with actual Exception when supported to also propagate stacktrace.
void onException(in int type, in String msg) = 2;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IBooleanCallback.aidl | AIDL | unknown | 432 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.IStringCallback;
oneway interface ICookieManagerDelegate {
void setCookie(String uri, String value, IBooleanCallback callback) = 1;
void getCookie(String uri, IStringCallback callback) = 2;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ICookieManagerDelegate.aidl | AIDL | unknown | 489 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.IFullscreenClient;
oneway interface IFullscreenCallbackDelegate {
void onEnterFullscreen(IFullscreenClient client) = 0;
void onExitFullscreen() = 1;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IFullscreenCallbackDelegate.aidl | AIDL | unknown | 389 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
// A FullscreenClient that is passed to the webengine to exit fullscreen
// mode programmatically.
oneway interface IFullscreenClient {
void exitFullscreen() = 0;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IFullscreenClient.aidl | AIDL | unknown | 357 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.INavigationParams;
oneway interface INavigationObserverDelegate {
void notifyNavigationStarted(in INavigationParams navigation) = 1;
void notifyNavigationCompleted(in INavigationParams navigation) = 2;
void notifyNavigationFailed(in INavigationParams navigation) = 3;
void notifyLoadProgressChanged(double progress) = 4;
void notifyNavigationRedirected(in INavigationParams navigation) = 5;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/INavigationObserverDelegate.aidl | AIDL | unknown | 643 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import android.net.Uri;
import org.chromium.webengine.interfaces.ITabProxy;
import org.chromium.webengine.interfaces.ITabNavigationControllerProxy;
parcelable INavigationParams {
Uri uri;
int statusCode;
boolean isSameDocument;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/INavigationParams.aidl | AIDL | unknown | 431 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
oneway interface IPostMessageCallback {
void onPostMessage(in String result, in String origin) = 1;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IPostMessageCallback.aidl | AIDL | unknown | 293 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
oneway interface IStringCallback {
void onResult(in String result) = 1;
// TODO(swestphal): Replace parameters with actual Exception when supported to also propagate stacktrace.
void onException(in int type, in String msg) = 2;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IStringCallback.aidl | AIDL | unknown | 430 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.ITabParams;
oneway interface ITabCallback {
void onResult(in ITabParams tabParams) = 1;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ITabCallback.aidl | AIDL | unknown | 324 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.ITabParams;
oneway interface ITabListObserverDelegate {
void notifyActiveTabChanged(in ITabParams tabParams) = 1;
void notifyTabAdded(in ITabParams tabParams) = 2;
void notifyTabRemoved(in ITabParams tabParams) = 3;
void notifyWillDestroyBrowserAndAllTabs() = 4;
void onFinishedTabInitialization() = 5;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ITabListObserverDelegate.aidl | AIDL | unknown | 555 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.ITabProxy;
import org.chromium.webengine.interfaces.ITabCallback;
import org.chromium.webengine.interfaces.ITabListObserverDelegate;
oneway interface ITabManagerDelegate {
void setTabListObserverDelegate(ITabListObserverDelegate tabListObserverDelegate) = 1;
void notifyInitialTabs() = 2;
void getActiveTab(ITabCallback callback) = 3;
void createTab(ITabCallback callback) = 4;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ITabManagerDelegate.aidl | AIDL | unknown | 627 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.INavigationObserverDelegate;
oneway interface ITabNavigationControllerProxy {
void navigate(in String uri) = 1;
void goBack() = 2;
void goForward() = 3;
void canGoBack(IBooleanCallback callback) = 4;
void canGoForward(IBooleanCallback callback) = 5;
void reload() = 7;
void stop() = 8;
void setNavigationObserverDelegate(INavigationObserverDelegate tabNavigationDelegate) = 6;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ITabNavigationControllerProxy.aidl | AIDL | unknown | 700 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import android.graphics.Bitmap;
import org.chromium.webengine.interfaces.ITabParams;
oneway interface ITabObserverDelegate {
void notifyTitleUpdated(in String title) = 1;
void notifyVisibleUriChanged(in String uri) = 2;
void notifyRenderProcessGone() = 3;
void notifyFaviconChanged(in Bitmap favicon) = 4;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ITabObserverDelegate.aidl | AIDL | unknown | 513 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.ITabProxy;
import org.chromium.webengine.interfaces.ITabNavigationControllerProxy;
parcelable ITabParams {
ITabProxy tabProxy;
String tabGuid;
String uri;
ITabNavigationControllerProxy navigationControllerProxy;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ITabParams.aidl | AIDL | unknown | 459 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.IFullscreenCallbackDelegate;
import org.chromium.webengine.interfaces.IPostMessageCallback;
import org.chromium.webengine.interfaces.IStringCallback;
import org.chromium.webengine.interfaces.ITabObserverDelegate;
import java.util.List;
oneway interface ITabProxy {
void setActive() = 1;
void close() = 2;
void executeScript(in String script, in boolean useSeparateIsolate, in IStringCallback callback) = 3;
void setTabObserverDelegate(ITabObserverDelegate tabObserverDelegate) = 6;
// PostMessage:
void postMessage(in String message, in String targetOrigin) = 7;
void createMessageEventListener(in IPostMessageCallback callback, in List<String> allowedOrigins) = 8;
void addMessageEventListener(in List<String> allowedOrigins) = 9;
void removeMessageEventListener(in List<String> allowedOrigins) = 10;
// Fullscreen mode:
void setFullscreenCallbackDelegate(in IFullscreenCallbackDelegate fullscreenCallbackDelegate) = 11;
// Reserved Tags: 4, 5
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/ITabProxy.aidl | AIDL | unknown | 1,206 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.ITabListObserverDelegate;
oneway interface IWebEngineDelegate {
void shutdown() = 1;
void tryNavigateBack(IBooleanCallback callback) = 2;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IWebEngineDelegate.aidl | AIDL | unknown | 437 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.ICookieManagerDelegate;
import org.chromium.webengine.interfaces.ITabManagerDelegate;
import org.chromium.webengine.interfaces.IWebEngineDelegate;
import org.chromium.webengine.interfaces.IWebFragmentEventsDelegate;
oneway interface IWebEngineDelegateClient {
void onDelegatesReady(
IWebEngineDelegate delegate,
IWebFragmentEventsDelegate fragmentEventsDelegate,
ITabManagerDelegate tabManagerDelegate,
ICookieManagerDelegate cookieManagerDelegate) = 1;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IWebEngineDelegateClient.aidl | AIDL | unknown | 738 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
parcelable IWebEngineParams {
String profileName;
String persistenceId;
boolean isIncognito;
boolean isExternalIntentsEnabled;
@nullable List<String> allowedOrigins;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IWebEngineParams.aidl | AIDL | unknown | 376 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import android.os.Bundle;
import org.chromium.webengine.interfaces.IWebFragmentEventsDelegateClient;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
// Next value: 16
oneway interface IWebFragmentEventsDelegate {
void setClient(in IWebFragmentEventsDelegateClient client) = 1;
// Fragment events.
void onCreate() = 2;
void onStart() = 3;
void onAttach() = 4;
void onDetach() = 5;
void onPause() = 6;
void onStop() = 7;
void onResume() = 8;
void onDestroy() = 9;
// Fragment operations.
void resizeView(in int width, in int height) = 10;
void setMinimumSurfaceSize(int width, int height) = 11;
// Out of process operations.
void attachViewHierarchy(in IBinder hostToken) = 12;
// In process operations.
void onAttachWithContext(IObjectWrapper context, IObjectWrapper fragment) = 13;
void retrieveContentViewRenderView() = 14;
void onActivityResult(int requestCode, int resultCode, IObjectWrapper intent) = 15;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IWebFragmentEventsDelegate.aidl | AIDL | unknown | 1,197 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import android.view.SurfaceControlViewHost.SurfacePackage;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
oneway interface IWebFragmentEventsDelegateClient {
void onSurfacePackageReady(in SurfacePackage surfacePackage) = 1;
// Pre-U/T -devices cannot create an out-of-process Service with privileges needed
// to run the Browser process.
// On those devices we run BrowserFragment in-process but with the same API.
// The ObjectWrapper is only needed to pass the View-object (ContentViewRenderView)
// to the connecting client as the SurfaceControlViewHost is also not available on
// older versions.
void onContentViewRenderViewReady(in IObjectWrapper contentViewRenderView) = 2;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IWebFragmentEventsDelegateClient.aidl | AIDL | unknown | 923 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import android.view.SurfaceControlViewHost.SurfacePackage;
oneway interface IWebSandboxCallback {
void onBrowserProcessInitialized() = 1;
void onBrowserProcessInitializationFailure() = 2;
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IWebSandboxCallback.aidl | AIDL | unknown | 386 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.interfaces;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.IStringCallback;
import org.chromium.webengine.interfaces.IWebEngineParams;
import org.chromium.webengine.interfaces.IWebEngineDelegateClient;
import org.chromium.webengine.interfaces.IWebSandboxCallback;
oneway interface IWebSandboxService {
void isAvailable(IBooleanCallback callback) = 1;
void getVersion(IStringCallback callback) = 2;
void getProviderPackageName(IStringCallback callback) = 3;
void initializeBrowserProcess(in IWebSandboxCallback callback) = 4;
void createWebEngineDelegate(in IWebEngineParams params, IWebEngineDelegateClient fragmentClient) = 5;
void setRemoteDebuggingEnabled(in boolean enabled) = 6;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/webengine/interfaces/IWebSandboxService.aidl | AIDL | unknown | 942 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
/**
* Used to override floating some action mode menu items.
*
* @since 88
*/
abstract class ActionModeCallback {
/**
* Called when an overridden item type is clicked. The action mode is closed after this returns.
* @param selectedText the raw selected text. Client is responsible for trimming it to fit into
* some use cases as the text can be very large.
*/
public void onActionItemClicked(@ActionModeItemType int item, String selectedText) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ActionModeCallback.java | Java | unknown | 676 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@IntDef({ActionModeItemType.SHARE, ActionModeItemType.WEB_SEARCH})
@Retention(RetentionPolicy.SOURCE)
@interface ActionModeItemType {
int SHARE = org.chromium.weblayer_private.interfaces.ActionModeItemType.SHARE;
int WEB_SEARCH = org.chromium.weblayer_private.interfaces.ActionModeItemType.WEB_SEARCH;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ActionModeItemType.java | Java | unknown | 609 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* Listens to events from WebLayer-spawned notifications.
*/
public class BroadcastReceiver extends android.content.BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
WebLayer.loadAsync(context, webLayer -> {
try {
webLayer.getImpl().onReceivedBroadcast(ObjectWrapper.wrap(context), intent);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
});
} catch (UnsupportedVersionException e) {
throw new RuntimeException(e);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/BroadcastReceiver.java | Java | unknown | 983 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IBrowser;
import org.chromium.weblayer_private.interfaces.IBrowserClient;
import org.chromium.weblayer_private.interfaces.IMediaRouteDialogFragment;
import org.chromium.weblayer_private.interfaces.IRemoteFragment;
import org.chromium.weblayer_private.interfaces.ITab;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.util.Set;
/**
* Browser contains any number of Tabs, with one active Tab. The active Tab is visible to the user,
* all other Tabs are hidden.
*
* Newly created Browsers have a single active Tab.
*
* Browser provides for two distinct ways to save state, which impacts the state of the Browser at
* various points in the lifecycle.
*
* Asynchronously to the file system. This is used if a {@link persistenceId} was supplied when the
* Browser was created. The {@link persistenceId} uniquely identifies the Browser for saving the
* set of tabs and navigations. This is intended for long term persistence.
*
* For Browsers created with a {@link persistenceId}, restore happens asynchronously. As a result,
* the Browser will not have any tabs until restore completes (which may be after the Fragment has
* started).
*
* If a {@link persistenceId} is not supplied, then a minimal amount of state is saved to the
* fragment (instance state). During recreation, if instance state is available, the state is
* restored in {@link onStart}. Restore happens during start so that callbacks can be attached. As
* a result of this, the Browser has no tabs until the Fragment is started.
*/
class Browser {
// Set to null once destroyed (or for tests).
private IBrowser mImpl;
private final ObserverList<TabListCallback> mTabListCallbacks;
private final ObserverList<TabInitializationCallback> mTabInitializationCallbacks;
private static int sMaxNavigationsPerTabForInstanceState;
/**
* Sets the maximum number of navigations saved when persisting a Browsers instance state. The
* max applies to each Tab in the Browser. For example, if a value of 6 is supplied and the
* Browser has 4 tabs, then up to 24 navigation entries may be saved. The supplied value is
* a recommendation, for various reasons it may not be honored. A value of 0 results in
* using the default.
*
* @param value The maximum number of navigations to persist.
*
* @throws IllegalArgumentException If {@code value} is less than 0.
*
* @since 98
*/
public static void setMaxNavigationsPerTabForInstanceState(int value) {
ThreadCheck.ensureOnUiThread();
if (value < 0) throw new IllegalArgumentException("Max must be >= 0");
sMaxNavigationsPerTabForInstanceState = value;
}
static int getMaxNavigationsPerTabForInstanceState() {
return sMaxNavigationsPerTabForInstanceState;
}
// Constructor for test mocking.
protected Browser() {
mImpl = null;
mTabListCallbacks = null;
mTabInitializationCallbacks = null;
}
// Constructor for browserfragment to inject the {@code tabListCallback} on startup.
Browser(IBrowser impl) {
mImpl = impl;
mTabListCallbacks = new ObserverList<TabListCallback>();
mTabInitializationCallbacks = new ObserverList<TabInitializationCallback>();
}
void initializeState() {
try {
mImpl.setClient(new BrowserClientImpl());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
private void throwIfDestroyed() {
if (mImpl == null) {
throw new IllegalStateException("Browser can not be used once destroyed");
}
}
IBrowser getIBrowser() {
return mImpl;
}
/**
* Returns remote counterpart for the BrowserFragment: an {@link IRemoteFragment}.
*/
IRemoteFragment connectFragment() {
try {
return mImpl.createBrowserFragmentImpl();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the remote counterpart of MediaRouteDialogFragment.
*/
/* package */ IMediaRouteDialogFragment createMediaRouteDialogFragment() {
try {
return mImpl.createMediaRouteDialogFragmentImpl();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns true if this Browser has been destroyed.
*/
public boolean isDestroyed() {
ThreadCheck.ensureOnUiThread();
return mImpl == null;
}
// Called prior to notifying IBrowser of destroy().
void prepareForDestroy() {
for (TabListCallback callback : mTabListCallbacks) {
callback.onWillDestroyBrowserAndAllTabs();
}
}
// Called after the browser was destroyed.
void onDestroyed() {
mImpl = null;
}
/**
* Sets the active (visible) Tab. Only one Tab is visible at a time.
*
* @param tab The Tab to make active.
*
* @throws IllegalStateException if {@link tab} was not added to this
* Browser.
*
* @see #addTab()
*/
public void setActiveTab(@NonNull Tab tab) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
if (getActiveTab() != tab && !mImpl.setActiveTab(tab.getITab())) {
throw new IllegalStateException("attachTab() must be called before "
+ "setActiveTab");
}
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Adds a tab to this Browser. If {link tab} is the active Tab of another Browser, then the
* other Browser's active tab is set to null. This does nothing if {@link tab} is already
* contained in this Browser.
*
* @param tab The Tab to add.
*/
public void addTab(@NonNull Tab tab) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
if (tab.getBrowser() == this) return;
try {
mImpl.addTab(tab.getITab());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the active (visible) Tab associated with this
* Browser.
*
* @return The Tab.
*/
@Nullable
public Tab getActiveTab() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
Tab tab = Tab.getTabById(mImpl.getActiveTabId());
assert tab == null || tab.getBrowser() == this;
return tab;
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the set of Tabs contained in this Browser.
*
* @return The Tabs
*/
@NonNull
public Set<Tab> getTabs() {
ThreadCheck.ensureOnUiThread();
return Tab.getTabsInBrowser(this);
}
/**
* Returns a List of Tabs as saved in the native Browser.
*
* @return The Tabs.
*/
@NonNull
private int[] getTabIds() {
ThreadCheck.ensureOnUiThread();
try {
return mImpl.getTabIds();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Disposes a Tab. If {@link tab} is the active Tab, no Tab is made active. After this call
* {@link tab} should not be used.
*
* Note this will skip any beforeunload handlers. To run those first, use
* {@link Tab#dispatchBeforeUnloadAndClose} instead.
*
* @param tab The Tab to dispose.
*
* @throws IllegalStateException is {@link tab} is not in this Browser.
*/
public void destroyTab(@NonNull Tab tab) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
if (tab.getBrowser() != this) {
throw new IllegalStateException("destroyTab() must be called on a Tab in the Browser");
}
try {
mImpl.destroyTab(tab.getITab());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Navigates to the previous navigation across all tabs according to tabs in native Browser.
*/
void tryNavigateBack(@NonNull Callback<Boolean> callback) {
Tab activeTab = getActiveTab();
if (activeTab == null) {
callback.onResult(false);
return;
}
if (activeTab.dismissTransientUi()) {
callback.onResult(true);
return;
}
NavigationController controller = activeTab.getNavigationController();
if (controller.canGoBack()) {
controller.goBack();
callback.onResult(true);
return;
}
int[] tabIds = getTabIds();
if (tabIds.length > 1) {
Tab previousTab = null;
int activeTabId = activeTab.getId();
int prevId = -1;
for (int id : tabIds) {
if (id == activeTabId) {
previousTab = Tab.getTabById(prevId);
break;
}
prevId = id;
}
if (previousTab != null) {
activeTab.dispatchBeforeUnloadAndClose();
setActiveTab(previousTab);
callback.onResult(true);
return;
}
}
callback.onResult(false);
}
/**
* Adds a TabListCallback.
*
* @param callback The TabListCallback.
*/
public void registerTabListCallback(@NonNull TabListCallback callback) {
ThreadCheck.ensureOnUiThread();
mTabListCallbacks.addObserver(callback);
}
/**
* Removes a TabListCallback.
*
* @param callback The TabListCallback.
*/
public void unregisterTabListCallback(@NonNull TabListCallback callback) {
ThreadCheck.ensureOnUiThread();
mTabListCallbacks.removeObserver(callback);
}
/**
* Returns true if this Browser is in the process of restoring the previous state.
*
* @param True if restoring previous state.
*/
public boolean isRestoringPreviousState() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
return mImpl.isRestoringPreviousState();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Adds a TabInitializationCallback.
*
* @param callback The TabInitializationCallback.
*/
public void registerTabInitializationCallback(@NonNull TabInitializationCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
mTabInitializationCallbacks.addObserver(callback);
}
/**
* Removes a TabInitializationCallback.
*
* @param callback The TabInitializationCallback.
*/
public void unregisterTabInitializationCallback(@NonNull TabInitializationCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
mTabInitializationCallbacks.removeObserver(callback);
}
/**
* Creates a new tab attached to this browser. This will call {@link TabListCallback#onTabAdded}
* with the new tab.
*/
public @NonNull Tab createTab() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
ITab iTab = mImpl.createTab();
Tab tab = Tab.getTabById(iTab.getId());
assert tab != null;
return tab;
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Controls how sites are themed when WebLayer is in dark mode. WebLayer considers itself to be
* in dark mode if the UI_MODE_NIGHT_YES flag of its Resources' Configuration's uiMode field is
* set, which is typically controlled with AppCompatDelegate#setDefaultNightMode. By default
* pages will only be rendered in dark mode if WebLayer is in dark mode and they provide a dark
* theme in CSS. See DarkModeStrategy for other possible configurations.
*
* @see DarkModeStrategy
* @param strategy See {@link DarkModeStrategy}.
*
* @since 90
*/
public void setDarkModeStrategy(@DarkModeStrategy int strategy) {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 89) {
throw new UnsupportedOperationException();
}
throwIfDestroyed();
try {
mImpl.setDarkModeStrategy(strategy);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns {@link Profile} associated with this Browser Fragment. Multiple fragments can share
* the same Profile.
*/
@NonNull
public Profile getProfile() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
return Profile.of(mImpl.getProfile());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public void shutdown() {
try {
mImpl.shutdown();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
private final class BrowserClientImpl extends IBrowserClient.Stub {
@Override
public void onActiveTabChanged(int activeTabId) {
StrictModeWorkaround.apply();
Tab tab = Tab.getTabById(activeTabId);
for (TabListCallback callback : mTabListCallbacks) {
callback.onActiveTabChanged(tab);
}
}
@Override
public void onTabAdded(ITab iTab) {
StrictModeWorkaround.apply();
int id = 0;
try {
id = iTab.getId();
} catch (RemoteException e) {
throw new APICallException(e);
}
Tab tab = Tab.getTabById(id);
if (tab == null) {
tab = new Tab(iTab, Browser.this);
} else {
tab.setBrowser(Browser.this);
}
for (TabListCallback callback : mTabListCallbacks) {
callback.onTabAdded(tab);
}
}
@Override
public void onTabRemoved(int tabId) {
StrictModeWorkaround.apply();
Tab tab = Tab.getTabById(tabId);
// This should only be called with a previously created tab.
assert tab != null;
// And this should only be called for tabs attached to this browser.
assert tab.getBrowser() == Browser.this;
tab.setBrowser(null);
for (TabListCallback callback : mTabListCallbacks) {
callback.onTabRemoved(tab);
}
}
@Override
public IRemoteFragment createMediaRouteDialogFragment() {
StrictModeWorkaround.apply();
return new MediaRouteDialogFragmentEventHandler().getRemoteFragment();
}
@Override
public void onTabInitializationCompleted() {
for (TabInitializationCallback callback : mTabInitializationCallbacks) {
callback.onTabInitializationCompleted();
}
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/Browser.java | Java | unknown | 15,698 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* Service running the browser process for a BrowserFragment inside the hosting
* application's process.
*/
public class BrowserInProcessService extends Service {
private final IBinder mBinder = new BrowserProcessBinder(this);
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/BrowserInProcessService.java | Java | unknown | 589 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.IStringCallback;
import org.chromium.webengine.interfaces.IWebEngineDelegateClient;
import org.chromium.webengine.interfaces.IWebEngineParams;
import org.chromium.webengine.interfaces.IWebSandboxCallback;
import org.chromium.webengine.interfaces.IWebSandboxService;
/**
* Implementation of IWebSandboxService.Stub to be used in in-process and out-of-process
* browser process services.
*/
class BrowserProcessBinder extends IWebSandboxService.Stub {
private final Context mContext;
private WebLayer mWebLayer;
BrowserProcessBinder(Context context) {
mContext = context;
}
@Override
public void isAvailable(IBooleanCallback callback) {
new Handler(Looper.getMainLooper()).post(() -> {
try {
callback.onResult(WebLayer.isAvailable(mContext));
} catch (RemoteException e) {
}
});
}
@Override
public void getVersion(IStringCallback callback) {
new Handler(Looper.getMainLooper()).post(() -> {
try {
callback.onResult(WebLayer.getSupportedFullVersion(mContext));
} catch (RemoteException e) {
}
});
}
@Override
public void getProviderPackageName(IStringCallback callback) {
new Handler(Looper.getMainLooper()).post(() -> {
try {
callback.onResult(WebLayer.getProviderPackageName(mContext));
} catch (RemoteException e) {
}
});
}
@Override
public void initializeBrowserProcess(IWebSandboxCallback callback) {
new Handler(Looper.getMainLooper()).post(() -> {
try {
WebLayer.loadAsync(mContext, (webLayer) -> onWebLayerReady(webLayer, callback));
} catch (Exception e) {
try {
callback.onBrowserProcessInitializationFailure();
} catch (RemoteException re) {
}
}
});
}
private void onWebLayerReady(WebLayer webLayer, IWebSandboxCallback callback) {
mWebLayer = webLayer;
try {
callback.onBrowserProcessInitialized();
} catch (RemoteException e) {
}
}
@Override
public void createWebEngineDelegate(
IWebEngineParams params, IWebEngineDelegateClient webEngineClient) {
assert mWebLayer != null;
WebEngineDelegate.create(mContext, mWebLayer, params, webEngineClient);
}
@Override
public void setRemoteDebuggingEnabled(boolean enabled) {
assert mWebLayer != null;
mWebLayer.setRemoteDebuggingEnabled(enabled);
}
}; | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/BrowserProcessBinder.java | Java | unknown | 3,043 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* Service running the browser process for a BrowserFragment outside of the hosting
* application's process.
*/
public class BrowserSandboxService extends Service {
private IBinder mBinder = new BrowserProcessBinder(this);
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/BrowserSandboxService.java | Java | unknown | 586 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @hide
*/
@IntDef({BrowsingDataType.COOKIES_AND_SITE_DATA, BrowsingDataType.CACHE,
BrowsingDataType.SITE_SETTINGS})
@Retention(RetentionPolicy.SOURCE)
@interface BrowsingDataType {
int COOKIES_AND_SITE_DATA =
org.chromium.weblayer_private.interfaces.BrowsingDataType.COOKIES_AND_SITE_DATA;
int CACHE = org.chromium.weblayer_private.interfaces.BrowsingDataType.CACHE;
int SITE_SETTINGS = org.chromium.weblayer_private.interfaces.BrowsingDataType.SITE_SETTINGS;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/BrowsingDataType.java | Java | unknown | 798 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
/**
* Simple callback that takes a generic value.
* @param <T> The type of value passed into the callback.
*/
interface Callback<T> {
void onResult(T result);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/Callback.java | Java | unknown | 344 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.graphics.Bitmap;
import androidx.annotation.Nullable;
/**
* Callback for capturing screenshots.
*/
interface CaptureScreenShotCallback {
/**
* @param bitmap The result bitmap. May be null on failure
* @param errorCode An opaque error code value for debugging. 0 indicates success.
*/
void onScreenShotCaptured(@Nullable Bitmap bitmap, int errorCode);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/CaptureScreenShotCallback.java | Java | unknown | 571 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IChildProcessService;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* Delegates service calls to the chrome service implementation.
*/
@SuppressWarnings("JavadocType")
public abstract class ChildProcessService extends Service {
private IChildProcessService mImpl;
public ChildProcessService() {}
@Override
public void onCreate() {
super.onCreate();
try {
WebLayer.disableWebViewCompatibilityMode();
Context appContext = getApplicationContext();
Context remoteContext = WebLayer.getOrCreateRemoteContext(appContext);
mImpl = IChildProcessService.Stub.asInterface(
(IBinder) WebLayer
.loadRemoteClass(appContext,
"org.chromium.weblayer_private.ChildProcessServiceImpl")
.getMethod("create", Service.class, Context.class, Context.class)
.invoke(null, this, appContext, remoteContext));
mImpl.onCreate();
} catch (Exception e) {
throw new APICallException(e);
}
}
@Override
public void onDestroy() {
super.onDestroy();
try {
mImpl.onDestroy();
mImpl = null;
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@Override
public IBinder onBind(Intent intent) {
try {
return ObjectWrapper.unwrap(mImpl.onBind(ObjectWrapper.wrap(intent)), IBinder.class);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static class Privileged extends ChildProcessService {}
public static final class Privileged0 extends Privileged {}
public static final class Privileged1 extends Privileged {}
public static final class Privileged2 extends Privileged {}
public static final class Privileged3 extends Privileged {}
public static final class Privileged4 extends Privileged {}
public static class Sandboxed extends ChildProcessService {}
public static final class Sandboxed0 extends Sandboxed {}
public static final class Sandboxed1 extends Sandboxed {}
public static final class Sandboxed2 extends Sandboxed {}
public static final class Sandboxed3 extends Sandboxed {}
public static final class Sandboxed4 extends Sandboxed {}
public static final class Sandboxed5 extends Sandboxed {}
public static final class Sandboxed6 extends Sandboxed {}
public static final class Sandboxed7 extends Sandboxed {}
public static final class Sandboxed8 extends Sandboxed {}
public static final class Sandboxed9 extends Sandboxed {}
public static final class Sandboxed10 extends Sandboxed {}
public static final class Sandboxed11 extends Sandboxed {}
public static final class Sandboxed12 extends Sandboxed {}
public static final class Sandboxed13 extends Sandboxed {}
public static final class Sandboxed14 extends Sandboxed {}
public static final class Sandboxed15 extends Sandboxed {}
public static final class Sandboxed16 extends Sandboxed {}
public static final class Sandboxed17 extends Sandboxed {}
public static final class Sandboxed18 extends Sandboxed {}
public static final class Sandboxed19 extends Sandboxed {}
public static final class Sandboxed20 extends Sandboxed {}
public static final class Sandboxed21 extends Sandboxed {}
public static final class Sandboxed22 extends Sandboxed {}
public static final class Sandboxed23 extends Sandboxed {}
public static final class Sandboxed24 extends Sandboxed {}
public static final class Sandboxed25 extends Sandboxed {}
public static final class Sandboxed26 extends Sandboxed {}
public static final class Sandboxed27 extends Sandboxed {}
public static final class Sandboxed28 extends Sandboxed {}
public static final class Sandboxed29 extends Sandboxed {}
public static final class Sandboxed30 extends Sandboxed {}
public static final class Sandboxed31 extends Sandboxed {}
public static final class Sandboxed32 extends Sandboxed {}
public static final class Sandboxed33 extends Sandboxed {}
public static final class Sandboxed34 extends Sandboxed {}
public static final class Sandboxed35 extends Sandboxed {}
public static final class Sandboxed36 extends Sandboxed {}
public static final class Sandboxed37 extends Sandboxed {}
public static final class Sandboxed38 extends Sandboxed {}
public static final class Sandboxed39 extends Sandboxed {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ChildProcessService.java | Java | unknown | 5,066 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.IContextMenuParams;
/**
* Parameters for constructing context menu.
*/
class ContextMenuParams {
/**
* The Uri associated with the main frame of the page that triggered the context menu.
*/
@NonNull
public final Uri pageUri;
/**
* The link Uri, if any.
*/
@Nullable
public final Uri linkUri;
/**
* The link text, if any.
*/
@Nullable
public final String linkText;
/**
* The title or alt attribute (if title is not available).
*/
@Nullable
public final String titleOrAltText;
/**
* This is the source Uri for the element that the context menu was
* invoked on. Example of elements with source URLs are img, audio, and
* video.
*/
@Nullable
public final Uri srcUri;
/**
* Whether srcUri points to an image.
*
* @since 88
*/
public final boolean isImage;
/**
* Whether srcUri points to a video.
*
* @since 88
*/
public final boolean isVideo;
/**
* Whether this link or image/video can be downloaded. Only if this is true can
* {@link Tab.download} be called.
*
* @since 88
*/
public final boolean canDownload;
final IContextMenuParams mContextMenuParams;
protected ContextMenuParams(
Uri pageUri, Uri linkUri, String linkText, String titleOrAltText, Uri srcUri) {
this(pageUri, linkUri, linkText, titleOrAltText, srcUri, false, false, false, null);
}
protected ContextMenuParams(Uri pageUri, Uri linkUri, String linkText, String titleOrAltText,
Uri srcUri, boolean isImage, boolean isVideo, boolean canDownload,
IContextMenuParams contextMenuParams) {
this.pageUri = pageUri;
this.linkUri = linkUri;
this.linkText = linkText;
this.titleOrAltText = titleOrAltText;
this.srcUri = srcUri;
this.isImage = isImage;
this.isVideo = isVideo;
this.canDownload = canDownload;
this.mContextMenuParams = contextMenuParams;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ContextMenuParams.java | Java | unknown | 2,394 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @hide
*/
@IntDef({CookieChangeCause.INSERTED, CookieChangeCause.EXPLICIT, CookieChangeCause.UNKNOWN_DELETION,
CookieChangeCause.OVERWRITE, CookieChangeCause.EXPIRED, CookieChangeCause.EVICTED,
CookieChangeCause.EXPIRED_OVERWRITE})
@Retention(RetentionPolicy.SOURCE)
@interface CookieChangeCause {
/** The cookie was inserted. */
int INSERTED = org.chromium.weblayer_private.interfaces.CookieChangeCause.INSERTED;
/** The cookie was changed directly by a consumer's action. */
int EXPLICIT = org.chromium.weblayer_private.interfaces.CookieChangeCause.EXPLICIT;
/** The cookie was deleted, but no more details are known. */
int UNKNOWN_DELETION =
org.chromium.weblayer_private.interfaces.CookieChangeCause.UNKNOWN_DELETION;
/** The cookie was automatically removed due to an insert operation that overwrote it. */
int OVERWRITE = org.chromium.weblayer_private.interfaces.CookieChangeCause.OVERWRITE;
/** The cookie was automatically removed as it expired. */
int EXPIRED = org.chromium.weblayer_private.interfaces.CookieChangeCause.EXPIRED;
/** The cookie was automatically evicted during garbage collection. */
int EVICTED = org.chromium.weblayer_private.interfaces.CookieChangeCause.EVICTED;
/** The cookie was overwritten with an already-expired expiration date. */
int EXPIRED_OVERWRITE =
org.chromium.weblayer_private.interfaces.CookieChangeCause.EXPIRED_OVERWRITE;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/CookieChangeCause.java | Java | unknown | 1,772 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.NonNull;
/**
* Callback used to listen for cookie changes.
*/
abstract class CookieChangedCallback {
public abstract void onCookieChanged(@NonNull String cookie, @CookieChangeCause int cause);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/CookieChangedCallback.java | Java | unknown | 405 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.net.Uri;
import android.os.RemoteException;
import android.webkit.ValueCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IBooleanCallback;
import org.chromium.weblayer_private.interfaces.ICookieChangedCallbackClient;
import org.chromium.weblayer_private.interfaces.ICookieManager;
import org.chromium.weblayer_private.interfaces.IProfile;
import org.chromium.weblayer_private.interfaces.IStringCallback;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.util.List;
/**
* Manages cookies for a WebLayer profile.
*/
class CookieManager {
private final ICookieManager mImpl;
static CookieManager create(IProfile profile) {
try {
return new CookieManager(profile.getCookieManager());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
// Constructor for test mocking.
protected CookieManager() {
mImpl = null;
}
private CookieManager(ICookieManager impl) {
mImpl = impl;
}
/**
* Sets a cookie for the given URL.
*
* @param uri the URI for which the cookie is to be set.
* @param value the cookie string, using the format of the 'Set-Cookie' HTTP response header.
* @param callback a callback to be executed when the cookie has been set, or on failure. Called
* with true if the cookie is set successfully, and false if the cookie is not set for
* security reasons.
*
* @throws IllegalArgumentException if the cookie is invalid.
*/
public void setCookie(
@NonNull Uri uri, @NonNull String value, @NonNull IBooleanCallback callback) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.setCookie(uri.toString(), value, callback);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Gets the cookies for the given URL.
*
* @param uri the URI to get cookies for.
* @param callback a callback to be executed with the cookie value in the format of the 'Cookie'
* HTTP request header. If there is no cookie, this will be called with an empty string.
*/
public void getCookie(@NonNull Uri uri, @NonNull IStringCallback callback) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.getCookie(uri.toString(), callback);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Gets the cookies for the given URL in the form of the 'Set-Cookie' HTTP response header.
*
* @param uri the URI to get cookies for.
* @param callback a callback to be executed with a list of cookie strings in the format of the
* 'Set-Cookie' HTTP response header.
* @since 101
*/
public void getResponseCookies(@NonNull Uri uri, @NonNull Callback<List<String>> callback) {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 101) {
throw new UnsupportedOperationException();
}
try {
ValueCallback<List<String>> valueCallback = (List<String> result) -> {
callback.onResult(result);
};
mImpl.getResponseCookies(uri.toString(), ObjectWrapper.wrap(valueCallback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Adds a callback to listen for changes to cookies for the given URI.
*
* @param uri the URI to listen to cookie changes on.
* @param name the name of the cookie to listen for changes on. Can be null to listen for
* changes on all cookies.
* @param callback a callback that will be notified on cookie changes.
* @return a Runnable which will unregister the callback from listening to cookie changes.
* @throws IllegalArgumentException if the cookie name is an empty string.
*/
@NonNull
public Runnable addCookieChangedCallback(
@NonNull Uri uri, @Nullable String name, @NonNull CookieChangedCallback callback) {
ThreadCheck.ensureOnUiThread();
if (name != null && name.isEmpty()) {
throw new IllegalArgumentException(
"Name cannot be empty, use null to listen for all cookie changes.");
}
try {
return ObjectWrapper.unwrap(mImpl.addCookieChangedCallback(uri.toString(), name,
new CookieChangedCallbackClientImpl(callback)),
Runnable.class);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
private static final class CookieChangedCallbackClientImpl
extends ICookieChangedCallbackClient.Stub {
private final CookieChangedCallback mCallback;
CookieChangedCallbackClientImpl(CookieChangedCallback callback) {
mCallback = callback;
}
@Override
public void onCookieChanged(String cookie, @CookieChangeCause int cause) {
StrictModeWorkaround.apply();
mCallback.onCookieChanged(cookie, cause);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/CookieManager.java | Java | unknown | 5,579 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import org.chromium.webengine.interfaces.ExceptionType;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.ICookieManagerDelegate;
import org.chromium.webengine.interfaces.IStringCallback;
import org.chromium.weblayer_private.interfaces.APICallException;
/**
* This class acts as a proxy between the embedding app's WebFragment and
* the WebLayer implementation.
*/
class CookieManagerDelegate extends ICookieManagerDelegate.Stub {
private CookieManager mCookieManager;
private Handler mHandler = new Handler(Looper.getMainLooper());
CookieManagerDelegate(CookieManager cookieManager) {
mCookieManager = cookieManager;
}
@Override
public void setCookie(String uri, String value, IBooleanCallback callback) {
mHandler.post(() -> {
try {
mCookieManager.setCookie(Uri.parse(uri), value,
new org.chromium.weblayer_private.interfaces.IBooleanCallback.Stub() {
@Override
public void onResult(boolean result) {
try {
callback.onResult(result);
} catch (RemoteException e) {
}
}
@Override
public void onException(@ExceptionType int type, String msg) {
try {
callback.onException(ExceptionHelper.convertType(type), msg);
} catch (RemoteException e) {
}
}
});
} catch (APICallException e) {
try {
callback.onException(ExceptionType.UNKNOWN, e.getMessage());
} catch (RemoteException re) {
}
}
});
}
@Override
public void getCookie(String uri, IStringCallback callback) {
mHandler.post(() -> {
try {
mCookieManager.getCookie(Uri.parse(uri),
new org.chromium.weblayer_private.interfaces.IStringCallback.Stub() {
@Override
public void onResult(String result) {
try {
callback.onResult(result);
} catch (RemoteException e) {
}
}
@Override
public void onException(@ExceptionType int type, String msg) {
try {
callback.onException(ExceptionHelper.convertType(type), msg);
} catch (RemoteException e) {
}
}
});
} catch (APICallException e) {
try {
callback.onException(ExceptionType.UNKNOWN, e.getMessage());
} catch (RemoteException re) {
}
}
});
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/CookieManagerDelegate.java | Java | unknown | 3,560 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.NonNull;
/**
* Callback object for results of asynchronous {@link CrashReporterController} operations.
*/
abstract class CrashReporterCallback {
/**
* Called as a result of a new crash being detected, or with the result of {@link
* CrashReporterController#getPendingCrashes}
*
* @param localIds an array of crash report IDs available to be uploaded.
*/
public void onPendingCrashReports(@NonNull String[] localIds) {}
/**
* Called when a crash has been deleted.
*
* @param localId the local identifier of the crash that was deleted.
*/
public void onCrashDeleted(@NonNull String localId) {}
/**
* Called when a crash has been uploaded.
*
* @param localId the local identifier of the crash that was uploaded.
* @param reportId the remote identifier for the uploaded crash.
*/
public void onCrashUploadSucceeded(@NonNull String localId, @NonNull String reportId) {}
/**
* Called when a crash failed to upload.
*
* @param localId the local identifier of the crash that failed to upload.
* @param failureReason a free text string giving the failure reason.
*/
public void onCrashUploadFailed(@NonNull String localId, @NonNull String failureReason) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/CrashReporterCallback.java | Java | unknown | 1,485 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.ICrashReporterController;
import org.chromium.weblayer_private.interfaces.ICrashReporterControllerClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
/**
* Provides an API to allow WebLayer embedders to control the handling of crash reports.
*
* Creation of the CrashReporterController singleton bootstraps WebLayer code loading (but not full
* initialization) so that it can be used in a lightweight fashion from a scheduled task.
*
* Crash reports are identified by a unique string, with which is associated an opaque blob of data
* for upload, and a key: value dictionary of crash metadata. Given an identifier, callers can
* either trigger an upload attempt, or delete the crash report.
*
* After successful upload, local crash data is deleted and the crash can be referenced by the
* returned remote identifier string.
*
* An embedder should register a CrashReporterCallback to be alerted to the presence of crash
* reports via {@link CrashReporterCallback#onPendingCrashReports}. When a crash report is
* available, the embedder should decide whether the crash should be uploaded or deleted based on
* user preference. Knowing that a crash is available can be used as a signal to schedule upload
* work for a later point in time (or favourable power/network conditions).
*/
class CrashReporterController {
private ICrashReporterController mImpl;
private final ObserverList<CrashReporterCallback> mCallbacks;
private static final class Holder {
static CrashReporterController sInstance = new CrashReporterController();
}
// Protected so it's available for test mocking.
protected CrashReporterController() {
mCallbacks = new ObserverList<CrashReporterCallback>();
}
/** Retrieve the singleton CrashReporterController instance. */
public static CrashReporterController getInstance(@NonNull Context appContext) {
ThreadCheck.ensureOnUiThread();
return Holder.sInstance.connect(appContext.getApplicationContext());
}
/**
* Asynchronously fetch the set of crash reports ready to be uploaded.
*
* Results are returned via {@link CrashReporterCallback#onPendingCrashReports}.
*/
public void checkForPendingCrashReports() {
try {
mImpl.checkForPendingCrashReports();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Get the crash keys for a crash.
*
* Performs IO on this thread, so should not be called on the UI thread.
*
* @param localId a crash identifier.
* @return a Bundle containing crash information as key: value pairs.
*/
public @Nullable Bundle getCrashKeys(String localId) {
try {
return mImpl.getCrashKeys(localId);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Asynchronously delete a crash.
*
* Deletion is notified via {@link CrashReporterCallback#onCrashDeleted}
*
* @param localId a crash identifier.
*/
public void deleteCrash(@NonNull String localId) {
try {
mImpl.deleteCrash(localId);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Asynchronously upload a crash.
*
* Success is notified via {@link CrashReporterCallback#onCrashUploadSucceeded},
* and the crash report is purged. On upload failure,
* {@link CrashReporterCallback#onCrashUploadFailed} is called. The crash report
* will be kept until it is deemed too old, or too many upload attempts have
* failed.
*
* @param localId a crash identifier.
*/
public void uploadCrash(@NonNull String localId) {
try {
mImpl.uploadCrash(localId);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/** Register a {@link CrashReporterCallback} callback object. */
public void registerCallback(@NonNull CrashReporterCallback callback) {
ThreadCheck.ensureOnUiThread();
mCallbacks.addObserver(callback);
}
/** Unregister a previously registered {@link CrashReporterCallback} callback object. */
public void unregisterCallback(@NonNull CrashReporterCallback callback) {
ThreadCheck.ensureOnUiThread();
mCallbacks.removeObserver(callback);
}
private CrashReporterController connect(@NonNull Context appContext) {
if (mImpl != null) {
return this;
}
try {
mImpl = WebLayer.getIWebLayer(appContext)
.getCrashReporterController(ObjectWrapper.wrap(appContext),
ObjectWrapper.wrap(
WebLayer.getOrCreateRemoteContext(appContext)));
mImpl.setClient(new CrashReporterControllerClientImpl());
} catch (Exception e) {
throw new APICallException(e);
}
return this;
}
private final class CrashReporterControllerClientImpl
extends ICrashReporterControllerClient.Stub {
@Override
public void onPendingCrashReports(String[] localIds) {
StrictModeWorkaround.apply();
for (CrashReporterCallback callback : mCallbacks) {
callback.onPendingCrashReports(localIds);
}
}
@Override
public void onCrashDeleted(String localId) {
StrictModeWorkaround.apply();
for (CrashReporterCallback callback : mCallbacks) {
callback.onCrashDeleted(localId);
}
}
@Override
public void onCrashUploadSucceeded(String localId, String reportId) {
StrictModeWorkaround.apply();
for (CrashReporterCallback callback : mCallbacks) {
callback.onCrashUploadSucceeded(localId, reportId);
}
}
@Override
public void onCrashUploadFailed(String localId, String failureReason) {
StrictModeWorkaround.apply();
for (CrashReporterCallback callback : mCallbacks) {
callback.onCrashUploadFailed(localId, failureReason);
}
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/CrashReporterController.java | Java | unknown | 6,832 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @hide
*/
@IntDef({DarkModeStrategy.PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING,
DarkModeStrategy.WEB_THEME_DARKENING_ONLY, DarkModeStrategy.USER_AGENT_DARKENING_ONLY})
@Retention(RetentionPolicy.SOURCE)
@interface DarkModeStrategy {
/**
* Only render pages in dark mode if they provide a dark theme in their CSS. If no theme is
* provided, the page will render with its default styling, which could be a light theme.
*/
int WEB_THEME_DARKENING_ONLY =
org.chromium.weblayer_private.interfaces.DarkModeStrategy.WEB_THEME_DARKENING_ONLY;
/**
* Always apply automatic user-agent darkening to pages, ignoring any dark theme that the
* site provides. All pages will appear dark in this mode.
*/
int USER_AGENT_DARKENING_ONLY =
org.chromium.weblayer_private.interfaces.DarkModeStrategy.USER_AGENT_DARKENING_ONLY;
/**
* Render pages using their specified dark theme if available, otherwise fall back on automatic
* user-agent darkening. All pages will appear dark in this mode.
*/
int PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING =
org.chromium.weblayer_private.interfaces.DarkModeStrategy
.PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/DarkModeStrategy.java | Java | unknown | 1,566 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IClientDownload;
import org.chromium.weblayer_private.interfaces.IDownload;
import java.io.File;
/**
* Contains information about a single download that's in progress.
*/
class Download extends IClientDownload.Stub {
private final IDownload mDownloadImpl;
// Constructor for test mocking.
protected Download() {
mDownloadImpl = null;
}
Download(IDownload impl) {
mDownloadImpl = impl;
}
/**
* By default downloads will show a system notification. Call this to disable it.
*/
public void disableNotification() {
ThreadCheck.ensureOnUiThread();
try {
mDownloadImpl.disableNotification();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@DownloadState
public int getState() {
ThreadCheck.ensureOnUiThread();
try {
return mDownloadImpl.getState();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the total number of expected bytes. Returns -1 if the total size is not known.
*/
public long getTotalBytes() {
ThreadCheck.ensureOnUiThread();
try {
return mDownloadImpl.getTotalBytes();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Total number of bytes that have been received and written to the download file.
*/
public long getReceivedBytes() {
ThreadCheck.ensureOnUiThread();
try {
return mDownloadImpl.getReceivedBytes();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Pauses the download.
*/
public void pause() {
ThreadCheck.ensureOnUiThread();
try {
mDownloadImpl.pause();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Resumes the download.
*/
public void resume() {
ThreadCheck.ensureOnUiThread();
try {
mDownloadImpl.resume();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Cancels the download.
*/
public void cancel() {
ThreadCheck.ensureOnUiThread();
try {
mDownloadImpl.cancel();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the location of the downloaded file. This may be empty if the target path hasn't been
* determined yet. The file it points to won't be available until the download completes
* successfully.
*/
@NonNull
public File getLocation() {
ThreadCheck.ensureOnUiThread();
try {
return new File(mDownloadImpl.getLocation());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the file name for the download that should be displayed to the user.
*/
@NonNull
public File getFileNameToReportToUser() {
ThreadCheck.ensureOnUiThread();
try {
return new File(mDownloadImpl.getFileNameToReportToUser());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the effective MIME type of downloaded content.
*/
@NonNull
public String getMimeType() {
ThreadCheck.ensureOnUiThread();
try {
return mDownloadImpl.getMimeType();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Return information about the error, if any, that was encountered during the download.
*/
@DownloadError
public int getError() {
ThreadCheck.ensureOnUiThread();
try {
return mDownloadImpl.getError();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/Download.java | Java | unknown | 4,400 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.net.Uri;
import android.webkit.ValueCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* An interface that allows clients to handle download requests originating in the browser.
*/
abstract class DownloadCallback {
/**
* A download of has been requested with the specified details. If it returns true the download
* will be considered intercepted and WebLayer won't proceed with it. Note that there are many
* corner cases where the embedder downloading it won't work (e.g. POSTs, one-time URLs,
* requests that depend on cookies or auth state). This is called after AllowDownload.
*
* @param uri the target that should be downloaded
* @param userAgent the user agent to be used for the download
* @param contentDisposition content-disposition http header, if present
* @param mimetype the mimetype of the content reported by the server
* @param contentLength the file size reported by the server
*/
public abstract boolean onInterceptDownload(@NonNull Uri uri, @NonNull String userAgent,
@NonNull String contentDisposition, @NonNull String mimetype, long contentLength);
/**
* Gives the embedder the opportunity to asynchronously allow or disallow the
* given download. It's safe to run |callback| synchronously.
*
* @param uri the target that is being downloaded
* @param requestMethod the method (GET/POST etc...) of the download
* @param requestInitiator the initiating Uri, if present
* @param callback a callback to allow or disallow the download. Must be called to avoid leaks,
* and must be called on the UI thread.
*/
public abstract void allowDownload(@NonNull Uri uri, @NonNull String requestMethod,
@Nullable Uri requestInitiator, @NonNull ValueCallback<Boolean> callback);
/**
* A download has started. There will be 0..n calls to DownloadProgressChanged, then either a
* call to DownloadCompleted or DownloadFailed. The same |download| will be provided on
* subsequent calls to those methods when related to this download. Observers should clear any
* references to |download| in onDownloadCompleted or onDownloadFailed, just before it is
* destroyed.
*
* @param download the unique object for this download.
*/
public void onDownloadStarted(@NonNull Download download) {}
/**
* The download progress has changed.
*
* @param download the unique object for this download.
*/
public void onDownloadProgressChanged(@NonNull Download download) {}
/**
* The download has completed successfully.
*
* Note that |download| will be destroyed at the end of this call, so do not keep a reference
* to it afterward.
*
* @param download the unique object for this download.
*/
public void onDownloadCompleted(@NonNull Download download) {}
/**
* The download has failed because the user cancelled it or because of a server or network
* error.
*
* Note that |download| will be destroyed at the end of this call, so do not keep a reference
* to it afterward.
*
* @param download the unique object for this download.
*/
public void onDownloadFailed(@NonNull Download download) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/DownloadCallback.java | Java | unknown | 3,531 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @hide
*/
@IntDef({DownloadError.NO_ERROR, DownloadError.SERVER_ERROR, DownloadError.SSL_ERROR,
DownloadError.CONNECTIVITY_ERROR, DownloadError.NO_SPACE, DownloadError.FILE_ERROR,
DownloadError.CANCELLED, DownloadError.OTHER_ERROR})
@Retention(RetentionPolicy.SOURCE)
@interface DownloadError {
int NO_ERROR = org.chromium.weblayer_private.interfaces.DownloadError.NO_ERROR;
int SERVER_ERROR = org.chromium.weblayer_private.interfaces.DownloadError.SERVER_ERROR;
int SSL_ERROR = org.chromium.weblayer_private.interfaces.DownloadError.SSL_ERROR;
int CONNECTIVITY_ERROR =
org.chromium.weblayer_private.interfaces.DownloadError.CONNECTIVITY_ERROR;
int NO_SPACE = org.chromium.weblayer_private.interfaces.DownloadError.NO_SPACE;
int FILE_ERROR = org.chromium.weblayer_private.interfaces.DownloadError.FILE_ERROR;
int CANCELLED = org.chromium.weblayer_private.interfaces.DownloadError.CANCELLED;
int OTHER_ERROR = org.chromium.weblayer_private.interfaces.DownloadError.OTHER_ERROR;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/DownloadError.java | Java | unknown | 1,343 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @hide
*/
@IntDef({DownloadState.IN_PROGRESS, DownloadState.COMPLETE, DownloadState.PAUSED,
DownloadState.CANCELLED, DownloadState.FAILED})
@Retention(RetentionPolicy.SOURCE)
@interface DownloadState {
int IN_PROGRESS = org.chromium.weblayer_private.interfaces.DownloadState.IN_PROGRESS;
int COMPLETE = org.chromium.weblayer_private.interfaces.DownloadState.COMPLETE;
int PAUSED = org.chromium.weblayer_private.interfaces.DownloadState.PAUSED;
int CANCELLED = org.chromium.weblayer_private.interfaces.DownloadState.CANCELLED;
int FAILED = org.chromium.weblayer_private.interfaces.DownloadState.FAILED;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/DownloadState.java | Java | unknown | 936 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.NonNull;
/**
* ErrorPage contains the html to show when an error is encountered.
*/
class ErrorPage {
public final String htmlContent;
/**
* Creates an ErrorPage.
*
* @param htmlContent The html to show.
*
*/
public ErrorPage(@NonNull String htmlContent) {
this.htmlContent = htmlContent;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ErrorPage.java | Java | unknown | 549 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* An interface that allows clients to handle error page interactions.
*/
abstract class ErrorPageCallback {
/**
* The user has attempted to back out of an error page, such as one warning of an SSL error.
*
* @return true if the action was overridden and WebLayer should skip default handling.
*/
public abstract boolean onBackToSafety();
/**
* Called when an error is encountered. A null return value results in a default error page
* being shown, a non-null return value results in showing the content of the returned
* {@link ErrorPage}.
*
* @param navigation The navigation that encountered the error.
*
* @return The error page.
*/
public @Nullable ErrorPage getErrorPage(@NonNull Navigation navigation) {
return null;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ErrorPageCallback.java | Java | unknown | 1,072 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import org.chromium.weblayer_private.interfaces.ExceptionType;
class ExceptionHelper {
static @ExceptionType int convertType(@ExceptionType int type) {
switch (type) {
case ExceptionType.RESTRICTED_API:
return org.chromium.webengine.interfaces.ExceptionType.RESTRICTED_API;
case ExceptionType.UNKNOWN:
return org.chromium.webengine.interfaces.ExceptionType.UNKNOWN;
}
assert false : "Unexpected ExceptionType: " + String.valueOf(type);
return org.chromium.webengine.interfaces.ExceptionType.UNKNOWN;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ExceptionHelper.java | Java | unknown | 777 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.NonNull;
/**
* Allows the embedder to present a custom warning dialog gating external intent launch in
* incognito mode rather than WebLayer's default dialog being used.
* See {@link Tab#setExternalIntentInIncognitoCallback()}.
* @since 93
*/
abstract class ExternalIntentInIncognitoCallback {
/* Invoked when the user initiates a launch of an intent in incognito mode. The embedder's
* implementation should present a modal dialog warning the user that they are leaving
* incognito and asking if they wish to continue; it should then invoke onUserDecision() with
* the user's decision once obtained (passing the value as an Integer wrapping an
* @ExternalIntentInIncognitoUserDecision).
* NOTE: The dialog presented *must* be modal, as confusion of state can otherwise occur. */
public abstract void onExternalIntentInIncognito(
@NonNull Callback<Integer> onUserDecisionCallback);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ExternalIntentInIncognitoCallback.java | Java | unknown | 1,138 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@IntDef({ExternalIntentInIncognitoUserDecision.ALLOW, ExternalIntentInIncognitoUserDecision.DENY})
@Retention(RetentionPolicy.SOURCE)
@interface ExternalIntentInIncognitoUserDecision {
int ALLOW =
org.chromium.weblayer_private.interfaces.ExternalIntentInIncognitoUserDecision.ALLOW;
int DENY = org.chromium.weblayer_private.interfaces.ExternalIntentInIncognitoUserDecision.DENY;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ExternalIntentInIncognitoUserDecision.java | Java | unknown | 698 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.graphics.Bitmap;
import androidx.annotation.Nullable;
/**
* Informed of changes to the favicon of the current navigation.
*/
abstract class FaviconCallback {
/**
* Called when the favicon of the current navigation has changed. This is called with null when
* a navigation is started.
*
* @param favicon The favicon.
*/
public void onFaviconChanged(@Nullable Bitmap favicon) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/FaviconCallback.java | Java | unknown | 607 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.graphics.Bitmap;
import android.os.RemoteException;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IFaviconFetcher;
import org.chromium.weblayer_private.interfaces.IFaviconFetcherClient;
import org.chromium.weblayer_private.interfaces.ITab;
/**
* {@link FaviconFetcher} is responsible for downloading a favicon for the current navigation.
* {@link FaviconFetcher} maintains an on disk cache of favicons downloading favicons as necessary.
*/
class FaviconFetcher {
private final FaviconCallback mCallback;
private IFaviconFetcher mImpl;
private @Nullable Bitmap mBitmap;
// Constructor for test mocking.
protected FaviconFetcher() {
mCallback = null;
}
FaviconFetcher(ITab iTab, FaviconCallback callback) {
mCallback = callback;
try {
mImpl = iTab.createFaviconFetcher(new FaviconFetcherClientImpl());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Destroys this FaviconFetcher. The callback will no longer be notified. This is implicitly
* called when the Tab is destroyed.
*/
public void destroy() {
ThreadCheck.ensureOnUiThread();
// As the implementation may implicitly destroy this, allow destroy() to be called multiple
// times.
if (mImpl == null) return;
try {
mImpl.destroy();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the favicon for the current navigation. This returns a null Bitmap if the favicon
* isn't available yet (which includes no navigation).
*
* @return The favicon.
*/
public @Nullable Bitmap getFaviconForCurrentNavigation() {
ThreadCheck.ensureOnUiThread();
return mBitmap;
}
private final class FaviconFetcherClientImpl extends IFaviconFetcherClient.Stub {
@Override
public void onDestroyed() {
mImpl = null;
}
@Override
public void onFaviconChanged(Bitmap bitmap) {
mBitmap = bitmap;
mCallback.onFaviconChanged(bitmap);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/FaviconFetcher.java | Java | unknown | 2,468 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
/**
* Informed of find in page results.
*/
abstract class FindInPageCallback {
/**
* Called when incremental results from a find operation are ready.
*
* @param numberOfMatches The total number of matches found thus far.
* @param activeMatchIndex The index of the currently highlighted match.
* @param finalUpdate Whether this is the last find result that can be expected for the current
* find operation.
*/
public void onFindResult(int numberOfMatches, int activeMatchIndex, boolean finalUpdate) {}
/**
* Called when WebLayer has ended the find session, for example due to the Tab losing active
* status. This will not be invoked when the client ends a find session via {@link
* FindInPageController#setFindInPageCallback} with a {@code null} value.
*/
public void onFindEnded() {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/FindInPageCallback.java | Java | unknown | 1,044 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IFindInPageCallbackClient;
import org.chromium.weblayer_private.interfaces.ITab;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
/**
* Initiates find-in-page operations.
*
* There is one FindInPageController per {@link Tab}, and only the active tab may have an active
* find session.
*/
class FindInPageController {
private final ITab mTab;
protected FindInPageController() {
mTab = null;
}
FindInPageController(ITab tab) {
mTab = tab;
}
/**
* Starts or ends a find session.
*
* When called with a non-null parameter, this starts a find session and displays a find result
* bar over the affected web page. When called with a null parameter, the find session will end
* and the result bar will be removed.
*
* @param callback The object that will be notified of find results, or null to end the find
* session.
* @return True if the operation succeeded. Ending a find session will always succeed, but
* starting one may fail, for example if the tab is not active or a find session is
* already started.
*/
public boolean setFindInPageCallback(@Nullable FindInPageCallback callback) {
ThreadCheck.ensureOnUiThread();
try {
FindInPageCallbackClientImpl callbackClient = null;
if (callback != null) {
callbackClient = new FindInPageCallbackClientImpl(callback);
}
return mTab.setFindInPageCallbackClient(callbackClient);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Called to initiate an in-page text search for the given string.
*
* Results will be highlighted in context, with additional attention drawn to the "active"
* result. The position of results will also be displayed on the find result bar.
* This has no effect if there is no active find session.
*
* @param searchText The {@link String} to search for. Any pre-existing search results will be
* cleared.
* @param forward The direction to move the "active" result. This only applies when the search
* text matches that of the last search.
*/
public void find(@NonNull String searchText, boolean forward) {
ThreadCheck.ensureOnUiThread();
try {
mTab.findInPage(searchText, forward);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
private static final class FindInPageCallbackClientImpl extends IFindInPageCallbackClient.Stub {
private final FindInPageCallback mCallback;
FindInPageCallbackClientImpl(FindInPageCallback callback) {
mCallback = callback;
}
public FindInPageCallback getCallback() {
return mCallback;
}
@Override
public void onFindResult(int numberOfMatches, int activeMatchOrdinal, boolean finalUpdate) {
StrictModeWorkaround.apply();
mCallback.onFindResult(numberOfMatches, activeMatchOrdinal, finalUpdate);
}
@Override
public void onFindEnded() {
StrictModeWorkaround.apply();
mCallback.onFindEnded();
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/FindInPageController.java | Java | unknown | 3,710 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.NonNull;
/**
* Used to configure fullscreen related state. HTML fullscreen support is only enabled if a
* FullscreenCallback is set.
*/
abstract class FullscreenCallback {
/**
* Called when the page has requested to go fullscreen. The delegate is responsible for
* putting the system into fullscreen mode. The delegate can exit out of fullscreen by
* running the supplied Runnable (calling exitFullscreenRunner.Run() results in calling
* exitFullscreen()).
*
* NOTE: we expect WebLayer to be covering the whole display without any other UI elements from
* the embedder or Android on screen. Otherwise some web features (e.g. WebXR) might experience
* clipped or misaligned UI elements.
*
* NOTE: the Runnable must not be used synchronously, and must be run on the UI thread.
*/
public abstract void onEnterFullscreen(@NonNull Runnable exitFullscreenRunner);
/**
* The page has exited fullscreen mode and the system should be moved out of fullscreen mode.
*/
public abstract void onExitFullscreen();
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/FullscreenCallback.java | Java | unknown | 1,290 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import org.chromium.webengine.interfaces.IFullscreenCallbackDelegate;
import org.chromium.webengine.interfaces.IFullscreenClient;
/**
* This class acts as a proxy between the Fullscreen events happening in
* weblayer and the FullscreenCallbackDelegate in webengine.
*/
class FullscreenCallbackDelegate extends FullscreenCallback {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private IFullscreenCallbackDelegate mFullscreenCallbackDelegate;
void setDelegate(IFullscreenCallbackDelegate delegate) {
mFullscreenCallbackDelegate = delegate;
}
@Override
public void onEnterFullscreen(@NonNull Runnable exitFullscreenRunner) {
if (mFullscreenCallbackDelegate != null) {
try {
mFullscreenCallbackDelegate.onEnterFullscreen(new IFullscreenClient.Stub() {
@Override
public void exitFullscreen() {
mHandler.post(() -> { exitFullscreenRunner.run(); });
}
});
} catch (RemoteException e) {
}
}
}
@Override
public void onExitFullscreen() {
if (mFullscreenCallbackDelegate != null) {
try {
mFullscreenCallbackDelegate.onExitFullscreen();
} catch (RemoteException e) {
}
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/FullscreenCallbackDelegate.java | Java | unknown | 1,682 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.NonNull;
import java.util.Set;
/**
* Used to fetch OAuth2 access tokens for the user's current GAIA account.
* @since 89
*/
abstract class GoogleAccountAccessTokenFetcher {
/**
* Called when the WebLayer implementation wants to fetch an access token for the embedder's
* current GAIA account (if any) and the given scopes. The client should invoke
* |onTokenFetchedCallback| when its internal token fetch is complete, passing either the
* fetched access token or the empty string in the case of failure (e.g., if there is no current
* GAIA account or there was an error in the token fetch).
*
* NOTE: WebLayer will not perform any caching of the returned token but will instead make a new
* request each time that it needs to use an access token. The expectation is that the client
* will use caching internally to minimize latency of these requests.
*/
public abstract void fetchAccessToken(
@NonNull Set<String> scopes, @NonNull Callback<String> onTokenFetchedCallback);
/**
* Called when a token previously obtained via a call to fetchAccessToken(|scopes|) is
* identified as invalid, so the embedder can take appropriate action (e.g., dropping the token
* from its cache and/or force-fetching a new token).
*/
public abstract void onAccessTokenIdentifiedAsInvalid(
@NonNull Set<String> scopes, @NonNull String token);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/GoogleAccountAccessTokenFetcher.java | Java | unknown | 1,643 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @hide
*/
@IntDef({GoogleAccountServiceType.SIGNOUT, GoogleAccountServiceType.ADD_SESSION,
GoogleAccountServiceType.DEFAULT})
@Retention(RetentionPolicy.SOURCE)
@interface GoogleAccountServiceType {
/**
* Logout all existing sessions.
*/
int SIGNOUT = org.chromium.weblayer_private.interfaces.GoogleAccountServiceType.SIGNOUT;
/**
* Add or re-authenticate an account.
*/
int ADD_SESSION = org.chromium.weblayer_private.interfaces.GoogleAccountServiceType.ADD_SESSION;
/**
* All other cases.
*/
int DEFAULT = org.chromium.weblayer_private.interfaces.GoogleAccountServiceType.DEFAULT;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/GoogleAccountServiceType.java | Java | unknown | 953 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.NonNull;
/**
* Used to intercept interaction with GAIA accounts.
*/
abstract class GoogleAccountsCallback {
/**
* Called when a user wants to change the state of their GAIA account. This could be a signin,
* signout, or any other action. See {@link GoogleAccountServiceType} for all the possible
* actions.
*/
public abstract void onGoogleAccountsRequest(@NonNull GoogleAccountsParams params);
/**
* The current GAIA ID the user is signed in with, or empty if the user is signed out. This can
* be provided on a best effort basis if the ID is not available immediately.
*/
public abstract @NonNull String getGaiaId();
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/GoogleAccountsCallback.java | Java | unknown | 878 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.net.Uri;
import androidx.annotation.NonNull;
/**
* Params passed to {@link GoogleAccountsCallback#onGoogleAccountsRequest}.
*/
class GoogleAccountsParams {
/**
* The requested service type such as "ADD_SESSION".
*/
public final @GoogleAccountServiceType int serviceType;
/**
* The prefilled email. May be empty.
*/
public final @NonNull String email;
/**
* The continue URL after the requested service is completed successfully. May be empty.
*/
public final @NonNull Uri continueUri;
/**
* Whether the continue URL should be loaded in the same tab.
*/
public final boolean isSameTab;
public GoogleAccountsParams(@GoogleAccountServiceType int serviceType, String email,
Uri continueUri, boolean isSameTab) {
this.serviceType = serviceType;
this.email = email;
this.continueUri = continueUri;
this.isSameTab = isSameTab;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/GoogleAccountsParams.java | Java | unknown | 1,147 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IWebLayer;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* A wrapper service of GooglePayDataCallbacksService. The wrapping is necessary because
* WebLayer's internal parts are not allowed to interact with the external apps directly.
*
* @since 90
*/
class GooglePayDataCallbacksServiceWrapper extends Service {
@Nullable
private Service mService;
@Override
public void onCreate() {
ThreadCheck.ensureOnUiThread();
Service service = createService();
if (service == null) {
stopSelf();
return;
}
mService = service;
mService.onCreate();
}
@Nullable
private Service createService() {
if (WebLayer.getSupportedMajorVersionInternal() < 90) return null;
if (!WebLayer.hasWebLayerInitializationStarted()) return null;
WebLayer webLayer = WebLayer.getLoadedWebLayer(this);
if (webLayer == null) return null;
IWebLayer iWebLayer = webLayer.getImpl();
if (iWebLayer == null) return null;
IObjectWrapper objectWrapper;
try {
objectWrapper = iWebLayer.createGooglePayDataCallbacksService();
} catch (RemoteException e) {
throw new APICallException(e);
}
if (objectWrapper == null) return null;
return ObjectWrapper.unwrap(objectWrapper, Service.class);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
if (mService == null) return null;
try {
return mService.onBind(intent);
} catch (Exception e) {
throw new APICallException(e);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/GooglePayDataCallbacksServiceWrapper.java | Java | unknown | 2,177 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* A service used internally by WebLayer for decoding images on the local device.
*/
class ImageDecoderService extends Service {
private IBinder mImageDecoder;
@Override
public void onCreate() {
try {
mImageDecoder =
WebLayer.getIWebLayer(this).initializeImageDecoder(ObjectWrapper.wrap(this),
ObjectWrapper.wrap(WebLayer.getOrCreateRemoteContext(this)));
} catch (Exception e) {
throw new APICallException(e);
}
}
@Override
public IBinder onBind(Intent intent) {
return mImageDecoder;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ImageDecoderService.java | Java | unknown | 1,022 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @hide
*/
@IntDef({LoadError.NO_ERROR, LoadError.HTTP_CLIENT_ERROR, LoadError.HTTP_SERVER_ERROR,
LoadError.SSL_ERROR, LoadError.CONNECTIVITY_ERROR, LoadError.OTHER_ERROR})
@Retention(RetentionPolicy.SOURCE)
@interface LoadError {
/**
* Navigation completed successfully.
*/
int NO_ERROR = org.chromium.weblayer_private.interfaces.LoadError.NO_ERROR;
/**
* Server responded with 4xx status code.
*/
int HTTP_CLIENT_ERROR = org.chromium.weblayer_private.interfaces.LoadError.HTTP_CLIENT_ERROR;
/**
* Server responded with 5xx status code.
*/
int HTTP_SERVER_ERROR = org.chromium.weblayer_private.interfaces.LoadError.HTTP_SERVER_ERROR;
/**
* Certificate error.
*/
int SSL_ERROR = org.chromium.weblayer_private.interfaces.LoadError.SSL_ERROR;
/**
* Problem connecting to server.
*/
int CONNECTIVITY_ERROR = org.chromium.weblayer_private.interfaces.LoadError.CONNECTIVITY_ERROR;
/**
* An error not listed above or below occurred.
*/
int OTHER_ERROR = org.chromium.weblayer_private.interfaces.LoadError.OTHER_ERROR;
/**
* Safe browsing error.
*
* @since 88
*/
int SAFE_BROWSING_ERROR =
org.chromium.weblayer_private.interfaces.LoadError.SAFE_BROWSING_ERROR;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/LoadError.java | Java | unknown | 1,620 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.webkit.ValueCallback;
/**
* Used along with {@link MediaCaptureController} to control and observe Media Capture and Streams
* usage.
*/
abstract class MediaCaptureCallback {
/**
* Called when a site in a Tab requests to start capturing media from the user's device.
*
* This will be called only if the app already has the requisite permissions and the user has
* granted permissions to the site that is making the request.
*
* At least one of the two boolean parameters will be true. Note that a single tab can have more
* than one concurrent active stream, and these parameters only represent the state of the new
* stream.
*
* @param audio if true, the new stream includes audio from a microphone.
* @param video if true, the new stream includes video from a camera.
* @param requestResult a callback to be run with true if and when the stream can start, or
* false if the stream should not start. Must be run on the UI thread.
*/
public void onMediaCaptureRequested(
boolean audio, boolean video, ValueCallback<Boolean> requestResult) {}
/**
* Called when media streaming state will change in the Tab.
*
* A site will receive audio/video from the device’s hardware. This
* may be called with both parameters false to indicate all streaming
* has stopped, or multiple times in a row with different parameter
* values as streaming state changes to include or exclude hardware.
*
* @param audio if true, the stream includes audio from a microphone.
* @param video if true, the stream includes video from a camera.
*/
public void onMediaCaptureStateChanged(boolean audio, boolean video) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/MediaCaptureCallback.java | Java | unknown | 1,945 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.os.RemoteException;
import android.webkit.ValueCallback;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IMediaCaptureCallbackClient;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.ITab;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
/**
* Used to control Media Capture and Streams Web API operations.
*
* The Web API is used by sites to record video and audio from the user's device, e.g. for voice
* recognition or video conferencing. There is one MediaCaptureController per {@link Tab}.
*/
class MediaCaptureController {
private final ITab mTab;
protected MediaCaptureController() {
mTab = null;
}
MediaCaptureController(ITab tab) {
mTab = tab;
}
/**
* Sets the callback for the tab.
* @param MediaCaptureCallback the callback to use, or null. If null, capture requests will be
* allowed (assuming the system and user granted permission).
*/
public void setMediaCaptureCallback(@Nullable MediaCaptureCallback callback) {
ThreadCheck.ensureOnUiThread();
try {
MediaCaptureCallbackClientImpl callbackClient = null;
if (callback != null) {
callbackClient = new MediaCaptureCallbackClientImpl(callback);
}
mTab.setMediaCaptureCallbackClient(callbackClient);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Called to stop the active media stream(s) in a tab.
*/
public void stopMediaCapturing() {
ThreadCheck.ensureOnUiThread();
try {
mTab.stopMediaCapturing();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
private static final class MediaCaptureCallbackClientImpl
extends IMediaCaptureCallbackClient.Stub {
private final MediaCaptureCallback mCallback;
MediaCaptureCallbackClientImpl(MediaCaptureCallback callback) {
mCallback = callback;
}
public MediaCaptureCallback getCallback() {
return mCallback;
}
@Override
public void onMediaCaptureRequested(
boolean audio, boolean video, IObjectWrapper callbackWrapper) {
StrictModeWorkaround.apply();
ValueCallback<Boolean> requestResultCallback =
(ValueCallback<Boolean>) ObjectWrapper.unwrap(
callbackWrapper, ValueCallback.class);
mCallback.onMediaCaptureRequested(audio, video, requestResultCallback);
}
@Override
public void onMediaCaptureStateChanged(boolean audio, boolean video) {
StrictModeWorkaround.apply();
mCallback.onMediaCaptureStateChanged(audio, video);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/MediaCaptureController.java | Java | unknown | 3,244 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* Base class that provides common functionality for media playback services that are associated
* with an active media session and Android notification.
*/
abstract class MediaPlaybackBaseService extends Service {
// True when the start command has been forwarded to the impl.
boolean mStarted;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
if (!WebLayer.hasWebLayerInitializationStarted()) {
stopSelf();
return;
}
init();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
WebLayer webLayer = getWebLayer();
if (webLayer == null) {
stopSelf();
} else {
try {
forwardStartCommandToImpl(webLayer, intent);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
mStarted = true;
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (!mStarted) return;
try {
forwardDestroyToImpl();
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
/** Called to do initialization when the service is created. */
void init() {}
/**
* Called to forward {@link onStartCommand()} to the WebLayer implementation.
*
* @param webLayer the implementation.
* @param intent the intent that started the service.
*/
abstract void forwardStartCommandToImpl(@NonNull WebLayer webLayer, Intent intent)
throws RemoteException;
/**
* Called to forward {@link onDestroy()} to the WebLayer implementation.
*
* This will only be called if {@link forwardStartCommandToImpl()} was previously called, and
* there should always be a loaded {@link WebLayer} available via {@link getWebLayer()}.
*/
abstract void forwardDestroyToImpl() throws RemoteException;
/** Returns the loaded {@link WebLayer}, or null if none is loaded. */
@Nullable
WebLayer getWebLayer() {
WebLayer webLayer;
try {
webLayer = WebLayer.getLoadedWebLayer(getApplication());
} catch (UnsupportedVersionException e) {
throw new RuntimeException(e);
}
return webLayer;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/MediaPlaybackBaseService.java | Java | unknown | 2,830 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
/**
* This class handles dialog fragments for casting, such as a {@link
* MediaRouteChooserDialogFragment} or a {@link MediaRouteControllerDialogFragment}.
*
* TODO(rayankans): Expose MediaRouteDialog to the client side.
*/
class MediaRouteDialogFragmentEventHandler extends RemoteFragmentEventHandler {
MediaRouteDialogFragmentEventHandler() {
super(null /* args */);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/MediaRouteDialogFragmentEventHandler.java | Java | unknown | 570 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import org.chromium.base.ContextUtils;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* A foreground {@link Service} for the Web MediaSession API.
* This class is a thin wrapper that forwards lifecycle events to the WebLayer implementation, which
* in turn manages a system notification and {@link MediaSession}. This service will be in the
* foreground when the MediaSession is active.
*/
public class MediaSessionService extends MediaPlaybackBaseService {
// A helper to automatically pause the media session when a user removes headphones.
private BroadcastReceiver mAudioBecomingNoisyReceiver;
@Override
public void onDestroy() {
super.onDestroy();
if (mAudioBecomingNoisyReceiver != null) {
unregisterReceiver(mAudioBecomingNoisyReceiver);
}
}
@Override
void init() {
mAudioBecomingNoisyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
return;
}
Intent i = new Intent(getApplication(), MediaSessionService.class);
i.setAction(intent.getAction());
getApplication().startService(i);
}
};
IntentFilter filter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
ContextUtils.registerProtectedBroadcastReceiver(this, mAudioBecomingNoisyReceiver, filter);
}
@Override
void forwardStartCommandToImpl(@NonNull WebLayer webLayer, Intent intent)
throws RemoteException {
webLayer.getImpl().onMediaSessionServiceStarted(ObjectWrapper.wrap(this), intent);
}
@Override
void forwardDestroyToImpl() throws RemoteException {
getWebLayer().getImpl().onMediaSessionServiceDestroyed();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/MediaSessionService.java | Java | unknown | 2,348 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.webkit.WebResourceResponse;
import androidx.annotation.NonNull;
/**
* Parameters for {@link NavigationController#navigate}.
*/
class NavigateParams {
private boolean mShouldReplaceCurrentEntry;
private boolean mIntentProcessingDisabled;
private boolean mIntentLaunchesAllowedInBackground;
private boolean mNetworkErrorAutoReloadDisabled;
private boolean mAutoPlayEnabled;
private WebResourceResponse mResponse;
/**
* A Builder class to help create NavigateParams.
*/
public static final class Builder {
private NavigateParams mParams;
/**
* Constructs a new Builder.
*/
public Builder() {
mParams = new NavigateParams();
}
/**
* Builds the NavigateParams.
*/
@NonNull
public NavigateParams build() {
return mParams;
}
/**
* @param replace Indicates whether the navigation should replace the current navigation
* entry in the history stack. False by default.
*/
@NonNull
public Builder setShouldReplaceCurrentEntry(boolean replace) {
mParams.mShouldReplaceCurrentEntry = replace;
return this;
}
/**
* Disables lookup and launching of an Intent that matches the uri being navigated to. If
* this is not called, WebLayer may look for a matching intent-filter, and if one is found,
* create and launch an Intent. The exact heuristics of when Intent matching is performed
* depends upon a wide range of state (such as the uri being navigated to, navigation
* stack...).
*/
@NonNull
public Builder disableIntentProcessing() {
mParams.mIntentProcessingDisabled = true;
return this;
}
/**
* Enables intent launching to occur for this navigation even if it is being executed in a
* background (i.e., non-visible) tab (by default, intent launches are disallowed in
* background tabs).
*
* @since 89
*/
@NonNull
public Builder allowIntentLaunchesInBackground() {
if (WebLayer.shouldPerformVersionChecks()
&& WebLayer.getSupportedMajorVersionInternal() < 89) {
throw new UnsupportedOperationException();
}
mParams.mIntentLaunchesAllowedInBackground = true;
return this;
}
/**
* Disables auto-reload for this navigation if the network is down and comes back later.
* Auto-reload is enabled by default. This is deprecated as of 88, instead use
* {@link Navigation#disableNetworkErrorAutoReload} which works for both embedder-initiated
* navigations and also user-initiated navigations (such as back or forward). Auto-reload
* is disabled if either method is called.
*/
@NonNull
public Builder disableNetworkErrorAutoReload() {
mParams.mNetworkErrorAutoReloadDisabled = true;
return this;
}
/**
* Enable auto-play for videos in this navigation. Auto-play is disabled by default.
*/
@NonNull
public Builder enableAutoPlay() {
mParams.mAutoPlayEnabled = true;
return this;
}
/**
* @param response If the embedder has already fetched the data for a navigation it can
* supply it via a WebResourceResponse. The navigation will be committed at the
* Uri given to NavigationController.navigate().
* Caveats:
* -ensure proper cache headers are set if you don't want it to be reloaded.
* Depending on the device available memory a back navigation might hit
* the network if the headers don't indicate it's cacheable and the
* page wasn't in the back-forward cache. An example to cache for 1 minute:
* Cache-Control: private, max-age=60
* -since this isn't fetched by WebLayer it won't have the necessary certificate
* information to show the security padlock or certificate data.
*/
@NonNull
public Builder setResponse(@NonNull WebResourceResponse response) {
mParams.mResponse = response;
return this;
}
}
/**
* Returns true if the current navigation will be replaced, false otherwise.
*/
public boolean getShouldReplaceCurrentEntry() {
return mShouldReplaceCurrentEntry;
}
/**
* Returns true if intent processing is disabled.
*
* @return Whether intent processing is disabled.
*/
public boolean isIntentProcessingDisabled() {
return mIntentProcessingDisabled;
}
/**
* Returns true if intent launches are allowed in the background.
*
* @return Whether intent launches are allowed in the background.
*
* @since 89
*/
public boolean areIntentLaunchesAllowedInBackground() {
if (WebLayer.shouldPerformVersionChecks()
&& WebLayer.getSupportedMajorVersionInternal() < 89) {
throw new UnsupportedOperationException();
}
return mIntentLaunchesAllowedInBackground;
}
/**
* Returns true if auto reload for network errors is disabled.
*
* @return Whether auto reload for network errors is disabled.
*/
public boolean isNetworkErrorAutoReloadDisabled() {
return mNetworkErrorAutoReloadDisabled;
}
/**
* Returns true if auto play for videos is enabled.
*
* @return Whether auto play for videos is enabled.
*/
public boolean isAutoPlayEnabled() {
return mAutoPlayEnabled;
}
/**
* Returns a response of the html to use.
*
* @return WebResourceResponse of html to use.
*/
public WebResourceResponse getResponse() {
return mResponse;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/NavigateParams.java | Java | unknown | 6,322 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.net.Uri;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IClientNavigation;
import org.chromium.weblayer_private.interfaces.INavigation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Information about a navigation. Each time there is a new navigation, a new
* Navigation object will be created and that same object will be used in all
* of the NavigationCallback methods.
*/
class Navigation extends IClientNavigation.Stub {
private final INavigation mNavigationImpl;
// Constructor for test mocking.
protected Navigation() {
mNavigationImpl = null;
}
Navigation(INavigation impl) {
mNavigationImpl = impl;
}
@NavigationState
public int getState() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.getState();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* The uri the main frame is navigating to. This may change during the navigation when
* encountering a server redirect.
*/
@NonNull
public Uri getUri() {
ThreadCheck.ensureOnUiThread();
try {
return Uri.parse(mNavigationImpl.getUri());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the redirects that occurred on the way to the current page. The current page is the
* last one in the list (so even when there's no redirect, there will be one entry in the list).
*/
@NonNull
public List<Uri> getRedirectChain() {
ThreadCheck.ensureOnUiThread();
try {
List<Uri> redirects = new ArrayList<Uri>();
for (String r : mNavigationImpl.getRedirectChain()) redirects.add(Uri.parse(r));
return redirects;
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the status code of the navigation. Returns 0 if the navigation hasn't completed yet
* or if a response wasn't received.
*/
public int getHttpStatusCode() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.getHttpStatusCode();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/*
* Returns the HTTP response headers. Returns an empty map if the navigation hasn't completed
* yet or if a response wasn't received.
*
* @since 91
*/
public Map<String, String> getResponseHeaders() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 91) {
throw new UnsupportedOperationException();
}
try {
Map<String, String> headers = new HashMap<String, String>();
List<String> array = mNavigationImpl.getResponseHeaders();
for (int i = 0; i < array.size(); i += 2) {
headers.put(array.get(i), array.get(i + 1));
}
return headers;
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether the navigation happened without changing document. Examples of same document
* navigations are:
* - reference fragment navigations
* - pushState/replaceState
* - same page history navigation
*/
public boolean isSameDocument() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.isSameDocument();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether the navigation resulted in an error page (e.g. interstitial). Note that if an error
* page reloads, this will return true even though GetNetErrorCode will be kNoError.
*/
public boolean isErrorPage() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.isErrorPage();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Return information about the error, if any, that was encountered while loading the page.
*/
@LoadError
public int getLoadError() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.getLoadError();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether this navigation resulted in a download. Returns false if this navigation did not
* result in a download, or if download status is not yet known for this navigation. Download
* status is determined for a navigation when processing final (post redirect) HTTP response
* headers. This means the only time the embedder can know if it's a download is in
* NavigationCallback.onNavigationFailed.
*/
public boolean isDownload() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.isDownload();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether the target URL can be handled by the browser's internal protocol handlers, i.e., has
* a scheme that the browser knows how to process internally. Examples of such URLs are
* http(s) URLs, data URLs, and file URLs. A typical example of a URL for which there is no
* internal protocol handler (and for which this method would return also) is an intent:// URL.
*
* @return Whether the target URL of the navigation has a known protocol.
*
* @since 89
*/
public boolean isKnownProtocol() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 89) {
throw new UnsupportedOperationException();
}
try {
return mNavigationImpl.isKnownProtocol();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether this navigation resulted in an external intent being launched. Returns false if this
* navigation did not do so, or if that status is not yet known for this navigation. This
* status is determined for a navigation when processing final (post redirect) HTTP response
* headers. This means the only time the embedder can know if the navigation resulted in an
* external intent being launched is in NavigationCallback.onNavigationFailed.
*
* @return Whether an intent was launched for the navigation.
*
* @since 89
*/
public boolean wasIntentLaunched() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 89) {
throw new UnsupportedOperationException();
}
try {
return mNavigationImpl.wasIntentLaunched();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether this navigation resulted in the user deciding whether an external intent should be
* launched (e.g., via a dialog). Returns false if this navigation did not resolve to such a
* user decision, or if that status is not yet known for this navigation. This status is
* determined for a navigation when processing final (post redirect) HTTP response headers. This
* means the only time the embedder can know this status definitively is in
* NavigationCallback.onNavigationFailed.
*
* @return Whether this navigation resulted in a user decision guarding external intent launch.
*
* @since 89
*/
public boolean isUserDecidingIntentLaunch() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 89) {
throw new UnsupportedOperationException();
}
try {
return mNavigationImpl.isUserDecidingIntentLaunch();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether this navigation was stopped before it could complete because
* NavigationController.stop() was called.
*/
public boolean wasStopCalled() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.wasStopCalled();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Sets a header for a network request. If a header with the specified name exists it is
* overwritten. This method can only be called at two times, from
* {@link NavigationCallback.onNavigationStarted} and {@link
* NavigationCallback.onNavigationRedirected}. When called during start, the header applies to
* both the initial network request as well as redirects.
*
* This method may be used to set the referer. If the referer is set in navigation start, it is
* reset during the redirect. In other words, if you need to set a referer that applies to
* redirects, then this must be called from {@link onNavigationRedirected}.
*
* Note that any headers that are set here won't be sent again if the frame html is fetched
* again due to a user reloading the page, navigating back and forth etc... when this fetch
* couldn't be cached (either in the disk cache or in the back-forward cache).
*
* @param name The name of the header. The name must be rfc 2616 compliant.
* @param value The value of the header. The value must not contain '\0', '\n' or '\r'.
*
* @throws IllegalArgumentException If supplied invalid values.
* @throws IllegalStateException If not called during start or a redirect.
*/
public void setRequestHeader(@NonNull String name, @NonNull String value) {
ThreadCheck.ensureOnUiThread();
try {
mNavigationImpl.setRequestHeader(name, value);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Disables auto-reload for this navigation if the network is down and comes back later.
* Auto-reload is enabled by default. This method may only be called from
* {@link NavigationCallback.onNavigationStarted}.
*
* @throws IllegalStateException If not called during start.
*
* @since 88
*/
public void disableNetworkErrorAutoReload() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.shouldPerformVersionChecks()
&& WebLayer.getSupportedMajorVersionInternal() < 88) {
throw new UnsupportedOperationException();
}
try {
mNavigationImpl.disableNetworkErrorAutoReload();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Disables intent processing for the lifetime of this navigation (including following
* redirects). This method may only be called from
* {@link NavigationCallback.onNavigationStarted}.
*
* @throws IllegalStateException If not called during start.
*
* @since 97
*/
public void disableIntentProcessing() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.shouldPerformVersionChecks()
&& WebLayer.getSupportedMajorVersionInternal() < 97) {
throw new UnsupportedOperationException();
}
try {
mNavigationImpl.disableIntentProcessing();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Sets the user-agent string that applies to the current navigation. This user-agent is not
* sticky, it applies to this navigation only (and any redirects or resources that are loaded).
* This method may only be called from {@link NavigationCallback.onNavigationStarted}. Setting
* this to a non empty string will cause will cause the User-Agent Client Hint header values and
* the values returned by `navigator.userAgentData` to be empty for requests this override is
* applied to.
*
* Note that this user agent won't be sent again if the frame html is fetched again due to a
* user reloading the page, navigating back and forth etc... when this fetch couldn't be cached
* (either in the disk cache or in the back-forward cache).
*
* @param value The user-agent string. The value must not contain '\0', '\n' or '\r'. An empty
* string results in the default user-agent string.
*
* @throws IllegalArgumentException If supplied an invalid value.
* @throws IllegalStateException If not called during start or if {@link
* Tab.setDesktopUserAgent} was called with a value of true.
*/
public void setUserAgentString(@NonNull String value) {
ThreadCheck.ensureOnUiThread();
try {
mNavigationImpl.setUserAgentString(value);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns whether the navigation was initiated by the page. Examples of page-initiated
* navigations:
* * Clicking <a> links.
* * changing window.location.href
* * redirect via the <meta http-equiv="refresh"> tag
* * using window.history.pushState
* * window.history.forward() or window.history.back()
*
* This method returns false for navigations initiated by the WebLayer API.
*
* @return Whether the navigation was initiated by the page.
*/
public boolean isPageInitiated() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.isPageInitiated();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether the navigation is a reload. Examples of reloads include:
* * embedder-specified through NavigationController::Reload
* * page-initiated reloads, e.g. location.reload()
* * reloads when the network interface is reconnected
*/
public boolean isReload() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationImpl.isReload();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Whether the navigation is restoring a page from back-forward cache (see
* https://web.dev/bfcache/). Since a previously loaded page is being reused, there are some
* things embedders have to keep in mind such as:
* * there will be no NavigationObserver::onFirstContentfulPaint callbacks
* * if an embedder injects code using Tab::ExecuteScript there is no need to reinject scripts
*
* @since 89
*/
public boolean isServedFromBackForwardCache() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 89) {
throw new UnsupportedOperationException();
}
try {
return mNavigationImpl.isServedFromBackForwardCache();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns true if this navigation was initiated by a form submission.
*
* @since 89
*/
public boolean isFormSubmission() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 89
|| WebLayer.getVersion().equals("89.0.4389.69")
|| WebLayer.getVersion().equals("89.0.4389.72")) {
throw new UnsupportedOperationException();
}
try {
return mNavigationImpl.isFormSubmission();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the referrer for this request.
*
* @since 89
*/
@NonNull
public Uri getReferrer() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 89
|| WebLayer.getVersion().equals("89.0.4389.69")
|| WebLayer.getVersion().equals("89.0.4389.72")) {
throw new UnsupportedOperationException();
}
try {
return Uri.parse(mNavigationImpl.getReferrer());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the Page object this navigation is occurring for.
* This method may only be called in (1) {@link NavigationCallback.onNavigationCompleted} or
* (2) {@link NavigationCallback.onNavigationFailed} when {@link Navigation#isErrorPage}
* returns true. It will return a non-null object in these cases.
*
* @throws IllegalStateException if called outside the above circumstances.
*
* @since 90
*/
@NonNull
public Page getPage() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 90) {
throw new UnsupportedOperationException();
}
try {
return (Page) mNavigationImpl.getPage();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the offset between the indices of the previous last committed and the newly committed
* navigation entries, for example -1 for back navigations, 0 for reloads, 1 for forward
* navigations or new navigations. Note that the return value can be less than -1 or greater
* than 1 if the navigation goes back/forward multiple entries. This may not cover all corner
* cases, and can be incorrect in cases like main frame client redirects.
*
* @since 92
*/
public int getNavigationEntryOffset() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 92) {
throw new UnsupportedOperationException();
}
try {
return mNavigationImpl.getNavigationEntryOffset();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns true if the navigation response was fetched from the cache.
*
* @since 102
*/
public boolean wasFetchedFromCache() {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 102) {
throw new UnsupportedOperationException();
}
try {
return mNavigationImpl.wasFetchedFromCache();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/Navigation.java | Java | unknown | 18,902 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.net.Uri;
import androidx.annotation.NonNull;
/**
* Informed of interesting events that happen during the lifetime of NavigationController. This
* interface is only notified of main frame navigations.
*
* The lifecycle of a navigation:
* 1) navigationStarted()
* 2) 0 or more navigationRedirected()
* 3) navigationCompleted() or navigationFailed()
* 4) onFirstContentfulPaint().
*/
abstract class NavigationCallback {
/**
* Called when a navigation started in the Tab. |navigation| is unique to a
* specific navigation. The same |navigation| will be provided on subsequent calls to
* NavigationRedirected, NavigationCommitted, NavigationCompleted and NavigationFailed when
* related to this navigation. Observers should clear any references to |navigation| in
* NavigationCompleted or NavigationFailed, just before it is destroyed.
*
* Note that this is only fired by navigations in the main frame.
*
* Note that this is fired by same-document navigations, such as fragment navigations or
* pushState/replaceState, which will not result in a document change. To filter these out, use
* Navigation::IsSameDocument.
*
* Note that more than one navigation can be ongoing in the Tab at the same time.
* Each will get its own Navigation object.
*
* Note that there is no guarantee that NavigationCompleted/NavigationFailed will be called for
* any particular navigation before NavigationStarted is called on the next.
*
* @param navigation the unique object for this navigation.
*/
public void onNavigationStarted(@NonNull Navigation navigation) {}
/**
* Called when a navigation encountered a server redirect.
*
* @param navigation the unique object for this navigation.
*/
public void onNavigationRedirected(@NonNull Navigation navigation) {}
/**
* Called when a navigation completes successfully in the Tab.
*
* The document load will still be ongoing in the Tab. Use the document loads
* events such as onFirstContentfulPaint and related methods to listen for continued events from
* this Tab.
*
* Note that this is fired by same-document navigations, such as fragment navigations or
* pushState/replaceState, which will not result in a document change. To filter these out, use
* NavigationHandle::IsSameDocument.
*
* Note that |navigation| will be destroyed at the end of this call, so do not keep a reference
* to it afterward.
*
* @param navigation the unique object for this navigation.
*/
public void onNavigationCompleted(@NonNull Navigation navigation) {}
/**
* Called when a navigation aborts in the Tab.
*
* Note that |navigation| will be destroyed at the end of this call, so do not keep a reference
* to it afterward.
*
* @param navigation the unique object for this navigation.
*/
public void onNavigationFailed(@NonNull Navigation navigation) {}
/**
* The load state of the document has changed.
*
* @param isLoading Whether any resource is loading.
* @param shouldShowLoadingUi True if the navigation is expected to show navigation-in-progress
* UI (if any exists). Only valid when |isLoading| is true.
*/
public void onLoadStateChanged(boolean isLoading, boolean shouldShowLoadingUi) {}
/**
* The progress of loading the main frame in the document has changed.
*
* @param progress A value in the range of 0.0-1.0.
*/
public void onLoadProgressChanged(double progress) {}
/**
* This is fired after each navigation has completed to indicate that the first paint after a
* non-empty layout has finished. This is *not* called for same-document navigations or when the
* page is loaded from the back-forward cache; see {@link
* Navigation#isServedFromBackForwardCache}.
*/
public void onFirstContentfulPaint() {}
/**
* Similar to onFirstContentfulPaint but contains timing information from the renderer process
* to better align with the Navigation Timing API.
*
* @param navigationStartMs the absolute navigation start time in milliseconds since boot,
* not counting time spent in deep sleep. This comes from SystemClock.uptimeMillis().
* @param firstContentfulPaintDurationMs the number of milliseconds to first contentful paint
* from navigation start.
* @since 88
*/
public void onFirstContentfulPaint(
long navigationStartMs, long firstContentfulPaintDurationMs) {}
/**
* This is fired when the largest contentful paint metric is available.
*
* @param navigationStartMs the absolute navigation start time in milliseconds since boot,
* not counting time spent in deep sleep. This comes from SystemClock.uptimeMillis().
* @param largestContentfulPaintDurationMs the number of milliseconds to largest contentful
* paint
* from navigation start.
* @since 88
*/
public void onLargestContentfulPaint(
long navigationStartMs, long largestContentfulPaintDurationMs) {}
/**
* Called after each navigation to indicate that the old page is no longer
* being rendered. Note this is not ordered with respect to onFirstContentfulPaint.
* @param newNavigationUri Uri of the new navigation.
*/
public void onOldPageNoLongerRendered(@NonNull Uri newNavigationUri) {}
/* Called when a Page is destroyed. For the common case, this is called when the user navigates
* away from a page to a new one or when the Tab is destroyed. However there are situations when
* a page is alive when it's not visible, e.g. when it goes into the back-forward cache. In that
* case this method will either be called when the back-forward cache entry is evicted or if it
* is used then this cycle repeats.
* @since 90
*/
public void onPageDestroyed(@NonNull Page page) {}
/*
* Called when the source language for |page| has been determined to be |language|.
* Note: |language| is an ISO 639 language code (two letters, except for Chinese where a
* localization is necessary).
* @since 93
*/
public void onPageLanguageDetermined(@NonNull Page page, @NonNull String language) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/NavigationCallback.java | Java | unknown | 6,602 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import android.net.Uri;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IClientNavigation;
import org.chromium.weblayer_private.interfaces.IClientPage;
import org.chromium.weblayer_private.interfaces.INavigateParams;
import org.chromium.weblayer_private.interfaces.INavigation;
import org.chromium.weblayer_private.interfaces.INavigationController;
import org.chromium.weblayer_private.interfaces.INavigationControllerClient;
import org.chromium.weblayer_private.interfaces.ITab;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
/**
* Provides methods to control navigation, along with maintaining the current list of navigations.
*/
class NavigationController {
private INavigationController mNavigationController;
private final ObserverList<NavigationCallback> mCallbacks;
static NavigationController create(ITab tab) {
NavigationController navigationController = new NavigationController();
try {
navigationController.mNavigationController = tab.createNavigationController(
navigationController.new NavigationControllerClientImpl());
} catch (RemoteException e) {
throw new APICallException(e);
}
return navigationController;
}
// Constructor protected for test mocking.
protected NavigationController() {
mCallbacks = new ObserverList<NavigationCallback>();
}
public void navigate(@NonNull Uri uri) {
navigate(uri, null);
}
/**
* Navigates to the given URI, with optional settings.
*
* @param uri the destination URI.
* @param params extra parameters for the navigation.
*
*/
public void navigate(@NonNull Uri uri, @Nullable NavigateParams params) {
ThreadCheck.ensureOnUiThread();
try {
INavigateParams iparams = mNavigationController.createNavigateParams();
if (params != null) {
if (params.getShouldReplaceCurrentEntry()) iparams.replaceCurrentEntry();
if (params.isIntentProcessingDisabled()) iparams.disableIntentProcessing();
if (WebLayer.getSupportedMajorVersionInternal() >= 89
&& params.areIntentLaunchesAllowedInBackground()) {
iparams.allowIntentLaunchesInBackground();
}
if (params.isNetworkErrorAutoReloadDisabled()) {
iparams.disableNetworkErrorAutoReload();
}
if (params.isAutoPlayEnabled()) iparams.enableAutoPlay();
if (params.getResponse() != null) {
iparams.setResponse(ObjectWrapper.wrap(params.getResponse()));
}
}
mNavigationController.navigate3(uri.toString(), iparams);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Navigates to the previous navigation.
*
* Note: this may go back more than a single navigation entry, see {@link
* isNavigationEntrySkippable} for more details.
*
* @throws IndexOutOfBoundsException If {@link #canGoBack} returns false.
*/
public void goBack() throws IndexOutOfBoundsException {
ThreadCheck.ensureOnUiThread();
if (!canGoBack()) {
throw new IndexOutOfBoundsException();
}
try {
mNavigationController.goBack();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Navigates to the next navigation.
*
* @throws IndexOutOfBoundsException If {@link #canGoForward} returns false.
*/
public void goForward() throws IndexOutOfBoundsException {
ThreadCheck.ensureOnUiThread();
if (!canGoForward()) {
throw new IndexOutOfBoundsException();
}
try {
mNavigationController.goForward();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns true if there is a navigation before the current one.
*
* Note: this may return false even if the current index is not 0, see {@link
* isNavigationEntrySkippable} for more details.
*
* @return Whether there is a navigation before the current one.
*/
public boolean canGoBack() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationController.canGoBack();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns true if there is a navigation after the current one.
*
* @return Whether there is a navigation after the current one.
*/
public boolean canGoForward() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationController.canGoForward();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Navigates to the entry at {@link index}.
*
* @throws IndexOutOfBoundsException If index is negative or is not less than {@link
* getNavigationListSize}.
*/
public void goToIndex(int index) throws IndexOutOfBoundsException {
ThreadCheck.ensureOnUiThread();
checkNavigationIndex(index);
try {
mNavigationController.goToIndex(index);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Reloads the current entry. Does nothing if there are no navigations.
*/
public void reload() {
ThreadCheck.ensureOnUiThread();
try {
mNavigationController.reload();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Stops in progress loading. Does nothing if not in the process of loading.
*/
public void stop() {
ThreadCheck.ensureOnUiThread();
try {
mNavigationController.stop();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the number of navigations entries.
*
* @return The number of navigation entries, 0 if empty.
*/
public int getNavigationListSize() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationController.getNavigationListSize();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the index of the current navigation, -1 if there are no navigations.
*
* @return The index of the current navigation.
*/
public int getNavigationListCurrentIndex() {
ThreadCheck.ensureOnUiThread();
try {
return mNavigationController.getNavigationListCurrentIndex();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the uri to display for the navigation at index.
*
* @param index The index of the navigation.
* @throws IndexOutOfBoundsException If index is negative or is not less than {@link
* getNavigationListSize}.
*/
@NonNull
public Uri getNavigationEntryDisplayUri(int index) throws IndexOutOfBoundsException {
ThreadCheck.ensureOnUiThread();
checkNavigationIndex(index);
try {
return Uri.parse(mNavigationController.getNavigationEntryDisplayUri(index));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the title of the navigation entry at the supplied index.
*
* @throws IndexOutOfBoundsException If index is negative or is not less than {@link
* getNavigationListSize}.
*/
@NonNull
public String getNavigationEntryTitle(int index) throws IndexOutOfBoundsException {
ThreadCheck.ensureOnUiThread();
checkNavigationIndex(index);
try {
return mNavigationController.getNavigationEntryTitle(index);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns whether this entry will be skipped on a call to {@link goBack} or {@link goForward}.
* This will be true for certain navigations, such as certain client side redirects and
* history.pushState navigations done without user interaction.
*
* @throws IndexOutOfBoundsException If index is negative or is not less than {@link
* getNavigationListSize}.
*/
public boolean isNavigationEntrySkippable(int index) throws IndexOutOfBoundsException {
ThreadCheck.ensureOnUiThread();
checkNavigationIndex(index);
try {
return mNavigationController.isNavigationEntrySkippable(index);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public void registerNavigationCallback(@NonNull NavigationCallback callback) {
ThreadCheck.ensureOnUiThread();
mCallbacks.addObserver(callback);
}
public void unregisterNavigationCallback(@NonNull NavigationCallback callback) {
ThreadCheck.ensureOnUiThread();
mCallbacks.removeObserver(callback);
}
private void checkNavigationIndex(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= getNavigationListSize()) {
throw new IndexOutOfBoundsException();
}
}
private final class NavigationControllerClientImpl extends INavigationControllerClient.Stub {
@Override
public IClientNavigation createClientNavigation(INavigation navigationImpl) {
StrictModeWorkaround.apply();
return new Navigation(navigationImpl);
}
@Override
public void navigationStarted(IClientNavigation navigation) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onNavigationStarted((Navigation) navigation);
}
}
@Override
public void navigationRedirected(IClientNavigation navigation) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onNavigationRedirected((Navigation) navigation);
}
}
@Override
public void readyToCommitNavigation(IClientNavigation navigation) {
StrictModeWorkaround.apply();
// Functionality removed from NavigationCallback in M90. See crbug.com/1174193
}
@Override
public void navigationCompleted(IClientNavigation navigation) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onNavigationCompleted((Navigation) navigation);
}
}
@Override
public void navigationFailed(IClientNavigation navigation) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onNavigationFailed((Navigation) navigation);
}
}
@Override
public void loadStateChanged(boolean isLoading, boolean shouldShowLoadingUi) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onLoadStateChanged(isLoading, shouldShowLoadingUi);
}
}
@Override
public void loadProgressChanged(double progress) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onLoadProgressChanged(progress);
}
}
@Override
public void onFirstContentfulPaint() {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onFirstContentfulPaint();
}
}
@Override
public void onFirstContentfulPaint2(
long navigationStartMs, long firstContentfulPaintDurationMs) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onFirstContentfulPaint(navigationStartMs, firstContentfulPaintDurationMs);
}
}
@Override
public void onLargestContentfulPaint(
long navigationStartMs, long largestContentfulPaintDurationMs) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onLargestContentfulPaint(
navigationStartMs, largestContentfulPaintDurationMs);
}
}
@Override
public void onOldPageNoLongerRendered(String uri) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onOldPageNoLongerRendered(Uri.parse(uri));
}
}
@Override
public IClientPage createClientPage() {
StrictModeWorkaround.apply();
return new Page();
}
@Override
public void onPageDestroyed(IClientPage page) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onPageDestroyed((Page) page);
}
}
@Override
public void onPageLanguageDetermined(IClientPage page, String language) {
StrictModeWorkaround.apply();
for (NavigationCallback callback : mCallbacks) {
callback.onPageLanguageDetermined((Page) page, language);
}
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/NavigationController.java | Java | unknown | 14,188 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @hide
*/
@IntDef({NavigationState.WAITING_RESPONSE, NavigationState.RECEIVING_BYTES,
NavigationState.COMPLETE, NavigationState.FAILED})
@Retention(RetentionPolicy.SOURCE)
@interface NavigationState {
int WAITING_RESPONSE =
org.chromium.weblayer_private.interfaces.NavigationState.WAITING_RESPONSE;
int RECEIVING_BYTES = org.chromium.weblayer_private.interfaces.NavigationState.RECEIVING_BYTES;
int COMPLETE = org.chromium.weblayer_private.interfaces.NavigationState.COMPLETE;
int FAILED = org.chromium.weblayer_private.interfaces.NavigationState.FAILED;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/NavigationState.java | Java | unknown | 897 |