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 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 for handling new tabs (such as occurs when window.open() is called). If this is not
* set, popups are disabled.
*/
abstract class NewTabCallback {
/**
* Called when a new tab has been created.
*
* @param tab The new tab.
* @param type How the tab should be shown.
*/
public abstract void onNewTab(@NonNull Tab tab, @NewTabType int type);
/**
* Called when a tab previously opened via onNewTab() was asked to close. Generally this should
* destroy the Tab and/or Browser.
* NOTE: This callback was deprecated in 84; WebLayer now internally closes tabs in this case
* and the embedder will be notified via TabListCallback#onTabRemoved().
*
* @see Browser#destroyTab
*/
@Deprecated
public void onCloseTab() {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/NewTabCallback.java | Java | unknown | 1,017 |
// 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({NewTabType.FOREGROUND_TAB, NewTabType.BACKGROUND_TAB, NewTabType.NEW_POPUP,
NewTabType.NEW_WINDOW})
@Retention(RetentionPolicy.SOURCE)
@interface NewTabType {
/**
* The page requested a new tab to be shown active.
*/
int FOREGROUND_TAB = org.chromium.weblayer_private.interfaces.NewTabType.FOREGROUND_TAB;
/**
* The page requested a new tab in the background. Generally, this is only encountered when
* keyboard modifiers are used.
*/
int BACKGROUND_TAB = org.chromium.weblayer_private.interfaces.NewTabType.BACKGROUND_TAB;
/**
* The page requested the tab to open a new popup. A popup generally shows minimal ui
* affordances, such as no tabstrip. On a phone, this is generally the same as
* NEW_TAB_MODE_FOREGROUND_TAB.
*/
int NEW_POPUP = org.chromium.weblayer_private.interfaces.NewTabType.NEW_POPUP;
/**
* The page requested the tab to open in a new window. On a phone, this is generally the
* same as NEW_TAB_MODE_FOREGROUND_TAB.
*/
int NEW_WINDOW = org.chromium.weblayer_private.interfaces.NewTabType.NEW_WINDOW;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/NewTabType.java | Java | unknown | 1,446 |
// Copyright 2013 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 java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* A container for a list of observers.
* <p/>
* This container can be modified during iteration without invalidating the iterator.
* So, it safely handles the case of an observer removing itself or other observers from the list
* while observers are being notified.
* <p/>
* The implementation (and the interface) is heavily influenced by the C++ ObserverList.
* Notable differences:
* - The iterator implements NOTIFY_EXISTING_ONLY.
* - The range-based for loop is left to the clients to implement in terms of iterator().
* <p/>
* This class is not threadsafe. Observers MUST be added, removed and will be notified on the same
* thread this is created.
*
* @param <E> The type of observers that this list should hold.
*/
class ObserverList<E> implements Iterable<E> {
/**
* Extended iterator interface that provides rewind functionality.
*/
public interface RewindableIterator<E> extends Iterator<E> {
/**
* Rewind the iterator back to the beginning.
*
* If we need to iterate multiple times, we can avoid iterator object reallocation by using
* this method.
*/
public void rewind();
}
public final List<E> mObservers = new ArrayList<E>();
private int mIterationDepth;
private int mCount;
private boolean mNeedsCompact;
public ObserverList() {}
/**
* Add an observer to the list.
* <p/>
* An observer should not be added to the same list more than once. If an iteration is already
* in progress, this observer will be not be visible during that iteration.
*
* @return true if the observer list changed as a result of the call.
*/
public boolean addObserver(E obs) {
// Avoid adding null elements to the list as they may be removed on a compaction.
if (obs == null || mObservers.contains(obs)) {
return false;
}
// Structurally modifying the underlying list here. This means we
// cannot use the underlying list's iterator to iterate over the list.
boolean result = mObservers.add(obs);
assert result;
++mCount;
return true;
}
/**
* Remove an observer from the list if it is in the list.
*
* @return true if an element was removed as a result of this call.
*/
public boolean removeObserver(E obs) {
if (obs == null) {
return false;
}
int index = mObservers.indexOf(obs);
if (index == -1) {
return false;
}
if (mIterationDepth == 0) {
// No one is iterating over the list.
mObservers.remove(index);
} else {
mNeedsCompact = true;
mObservers.set(index, null);
}
--mCount;
assert mCount >= 0;
return true;
}
public boolean hasObserver(E obs) {
return mObservers.contains(obs);
}
public void clear() {
mCount = 0;
if (mIterationDepth == 0) {
mObservers.clear();
return;
}
int size = mObservers.size();
mNeedsCompact |= size != 0;
for (int i = 0; i < size; i++) {
mObservers.set(i, null);
}
}
@Override
public Iterator<E> iterator() {
return new ObserverListIterator();
}
/**
* It's the same as {@link ObserverList#iterator()} but the return type is
* {@link RewindableIterator}. Use this iterator type if you need to use
* {@link RewindableIterator#rewind()}.
*/
public RewindableIterator<E> rewindableIterator() {
return new ObserverListIterator();
}
/**
* Returns the number of observers currently registered in the ObserverList.
* This is equivalent to the number of non-empty spaces in |mObservers|.
*/
public int size() {
return mCount;
}
/**
* Returns true if the ObserverList contains no observers.
*/
public boolean isEmpty() {
return mCount == 0;
}
/**
* Compact the underlying list be removing null elements.
* <p/>
* Should only be called when mIterationDepth is zero.
*/
private void compact() {
assert mIterationDepth == 0;
for (int i = mObservers.size() - 1; i >= 0; i--) {
if (mObservers.get(i) == null) {
mObservers.remove(i);
}
}
}
private void incrementIterationDepth() {
mIterationDepth++;
}
private void decrementIterationDepthAndCompactIfNeeded() {
mIterationDepth--;
assert mIterationDepth >= 0;
if (mIterationDepth > 0) return;
if (!mNeedsCompact) return;
mNeedsCompact = false;
compact();
}
/**
* Returns the size of the underlying storage of the ObserverList.
* It will take into account the empty spaces inside |mObservers|.
*/
private int capacity() {
return mObservers.size();
}
private E getObserverAt(int index) {
return mObservers.get(index);
}
private class ObserverListIterator implements RewindableIterator<E> {
private int mListEndMarker;
private int mIndex;
private boolean mIsExhausted;
private ObserverListIterator() {
ObserverList.this.incrementIterationDepth();
mListEndMarker = ObserverList.this.capacity();
}
@Override
public void rewind() {
compactListIfNeeded();
ObserverList.this.incrementIterationDepth();
mListEndMarker = ObserverList.this.capacity();
mIsExhausted = false;
mIndex = 0;
}
@Override
public boolean hasNext() {
int lookupIndex = mIndex;
while (lookupIndex < mListEndMarker
&& ObserverList.this.getObserverAt(lookupIndex) == null) {
lookupIndex++;
}
if (lookupIndex < mListEndMarker) return true;
// We have reached the end of the list, allow for compaction.
compactListIfNeeded();
return false;
}
@Override
public E next() {
// Advance if the current element is null.
while (mIndex < mListEndMarker && ObserverList.this.getObserverAt(mIndex) == null) {
mIndex++;
}
if (mIndex < mListEndMarker) return ObserverList.this.getObserverAt(mIndex++);
// We have reached the end of the list, allow for compaction.
compactListIfNeeded();
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private void compactListIfNeeded() {
if (!mIsExhausted) {
mIsExhausted = true;
ObserverList.this.decrementIterationDepthAndCompactIfNeeded();
}
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ObserverList.java | Java | unknown | 7,321 |
// 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 androidx.annotation.Nullable;
/**
* Used for handling requests to open new tabs that are not associated with any existing tab.
*
* This will be used in cases where a service worker tries to open a document, e.g. via the Web API
* clients.openWindow.
*
* @since 91
*/
abstract class OpenUrlCallback {
/**
* Called to get the {@link Browser} in which to create a new tab for a requested navigation.
*
* @return The {@link Browser} to host the new tab in, or null if the request should be
* rejected.
*/
public abstract @Nullable Browser getBrowserForNewTab();
/**
* Called when a new tab has been created and added to the browser given by {@link
* getBrowserForNewTab()}.
*
* It's expected this tab will be set to active.
*
* @param tab The new tab.
*/
public abstract void onTabAdded(@NonNull Tab tab);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/OpenUrlCallback.java | Java | unknown | 1,116 |
// 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 org.chromium.weblayer_private.interfaces.IClientPage;
/**
* This objects tracks the lifetime of a loaded web page. Most of the time there is only one Page
* object per tab at a time. However features like back-forward cache, prerendering etc... sometime
* involve the creation of additional Page object. {@link Navigation.getPage} will return the Page
* for a given navigation. Similarly it'll the same Page object that's passed in
* {@link NavigationCallback.onPageDestroyed}.
*
* @since 90
*/
class Page extends IClientPage.Stub {}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/Page.java | Java | unknown | 726 |
// 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 client-side service that wraps the impl-side PaymentDetailsUpdateService. WebLayer embedders
* export this service via //weblayer/public/java/AndroidManifest.xml so external payment apps can
* notify WebLayer of any updates to the selected payment details.
*
* @since 92
*/
public class PaymentDetailsUpdateServiceWrapper extends Service {
/** The impl-side of PaymentDetailsUpdateService. Can be null if WebLayer wasn't loaded yet. */
@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() < 92) {
throw new UnsupportedOperationException();
}
// WebLayer started the calling app so we assume WebLayer is still running. This service is
// not supposed to be started when WebLayer isn't running so we can safely ignore requests
// in that case.
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.createPaymentDetailsUpdateService();
} 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/PaymentDetailsUpdateServiceWrapper.java | Java | unknown | 2,645 |
// 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 androidx.annotation.NonNull;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IPrerenderController;
import org.chromium.weblayer_private.interfaces.IProfile;
/**
* PrerenderController enables prerendering of urls.
*
* Prerendering has the same effect as adding a link rel="prerender" resource hint to a web page. It
* is implemented using NoStatePrefetch and fetches resources needed for a url in advance, but does
* not execute Javascript or render any part of the page in advance. For more information on
* NoStatePrefetch, see https://developers.google.com/web/updates/2018/07/nostate-prefetch.
*/
class PrerenderController {
private final IPrerenderController mImpl;
static PrerenderController create(IProfile profile) {
try {
return new PrerenderController(profile.getPrerenderController());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
// Constructor for test mocking.
protected PrerenderController() {
mImpl = null;
}
PrerenderController(IPrerenderController prerenderController) {
mImpl = prerenderController;
}
/*
* Creates a prerender for the url provided.
* Prerendering here is implemented using NoStatePrefetch. We fetch resources and save them
* to the HTTP cache. All resources are cached according to their cache headers. For details,
* see https://developers.google.com/web/updates/2018/07/nostate-prefetch#implementation.
*
* On low end devices or when the device has too many renderers running and prerender is
* considered expensive, we do preconnect instead. Preconnect involves creating connections with
* the server without actually fetching any resources. For more information on preconnect, see
* https://www.chromium.org/developers/design-documents/network-stack/preconnect.
* @param uri The uri to prerender.
*/
public void schedulePrerender(@NonNull Uri uri) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.prerender(uri.toString());
} catch (RemoteException exception) {
throw new APICallException(exception);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/PrerenderController.java | Java | unknown | 2,503 |
// 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.graphics.Bitmap;
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.IBrowser;
import org.chromium.weblayer_private.interfaces.IClientDownload;
import org.chromium.weblayer_private.interfaces.IDownload;
import org.chromium.weblayer_private.interfaces.IDownloadCallbackClient;
import org.chromium.weblayer_private.interfaces.IGoogleAccountAccessTokenFetcherClient;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IOpenUrlCallbackClient;
import org.chromium.weblayer_private.interfaces.IProfile;
import org.chromium.weblayer_private.interfaces.IProfileClient;
import org.chromium.weblayer_private.interfaces.IUserIdentityCallbackClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Profile holds state (typically on disk) needed for browsing. Create a
* Profile via WebLayer.
*/
class Profile {
private static final Map<String, Profile> sProfiles = new HashMap<>();
private static final Map<String, Profile> sIncognitoProfiles = new HashMap<>();
/* package */ static Profile of(IProfile impl) {
ThreadCheck.ensureOnUiThread();
String name;
try {
name = impl.getName();
} catch (RemoteException e) {
throw new APICallException(e);
}
boolean isIncognito;
try {
isIncognito = impl.isIncognito();
} catch (RemoteException e) {
throw new APICallException(e);
}
Profile profile;
if (isIncognito) {
profile = sIncognitoProfiles.get(name);
} else {
profile = sProfiles.get(name);
}
if (profile != null) {
return profile;
}
return new Profile(name, impl, isIncognito);
}
/**
* Return all profiles that have been created and not yet called destroyed.
*/
@NonNull
public static Collection<Profile> getAllProfiles() {
ThreadCheck.ensureOnUiThread();
Set<Profile> profiles = new HashSet<Profile>();
profiles.addAll(sProfiles.values());
profiles.addAll(sIncognitoProfiles.values());
return profiles;
}
static String sanitizeProfileName(String profileName) {
if ("".equals(profileName)) {
throw new IllegalArgumentException("Profile path cannot be empty");
}
return profileName == null ? "" : profileName;
}
private final String mName;
private final boolean mIsIncognito;
private IProfile mImpl;
private DownloadCallbackClientImpl mDownloadCallbackClient;
private final CookieManager mCookieManager;
private final PrerenderController mPrerenderController;
// Constructor for test mocking.
protected Profile() {
mName = null;
mIsIncognito = false;
mImpl = null;
mCookieManager = null;
mPrerenderController = null;
}
private Profile(String name, IProfile impl, boolean isIncognito) {
mName = name;
mImpl = impl;
mIsIncognito = isIncognito;
mCookieManager = CookieManager.create(impl);
mPrerenderController = PrerenderController.create(impl);
if (isIncognito) {
sIncognitoProfiles.put(name, this);
} else {
sProfiles.put(name, this);
}
try {
mImpl.setClient(new ProfileClientImpl());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
IProfile getIProfile() {
return mImpl;
}
/**
* Returns the name of the profile. While added in 87, this can be used with any version.
*
* @return The name of the profile.
*/
@NonNull
public String getName() {
return mName;
}
/**
* Returns true if the profile is incognito. While added in 87, this can be used with any
* version.
*
* @return True if the profile is incognito.
*/
public boolean isIncognito() {
return mIsIncognito;
}
/**
* Clears the data associated with the Profile.
* The clearing is asynchronous, and new data may be generated during clearing. It is safe to
* call this method repeatedly without waiting for callback.
*
* @param dataTypes See {@link BrowsingDataType}.
* @param fromMillis Defines the start (in milliseconds since epoch) of the time range to clear.
* @param toMillis Defines the end (in milliseconds since epoch) of the time range to clear.
* For clearing all data prefer using {@link Long#MAX_VALUE} to
* {@link System.currentTimeMillis()} to take into account possible system clock changes.
* @param callback {@link Runnable} which is run when clearing is finished.
*/
public void clearBrowsingData(@NonNull @BrowsingDataType int[] dataTypes, long fromMillis,
long toMillis, @NonNull Runnable callback) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.clearBrowsingData(dataTypes, fromMillis, toMillis, ObjectWrapper.wrap(callback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Clears the data associated with the Profile.
* Same as {@link #clearBrowsingData(int[], long, long, Runnable)} with unbounded time range.
*/
public void clearBrowsingData(
@NonNull @BrowsingDataType int[] dataTypes, @NonNull Runnable callback) {
ThreadCheck.ensureOnUiThread();
clearBrowsingData(dataTypes, 0, Long.MAX_VALUE, callback);
}
/**
* Delete all profile data stored on disk. There are a number of edge cases with deleting
* profile data:
* * This method will throw an exception if there are any existing usage of this Profile. For
* example, all BrowserFragment belonging to this profile must be destroyed.
* * This object is considered destroyed after this method returns. Calling any other method
* after will throw exceptions.
* * Creating a new profile of the same name before doneCallback runs will throw an exception.
*
* After calling this function, {@link #getAllProfiles()} will not return the Profile, and
* {@link #enumerateAllProfileNames} will not return the profile name.
*
* @param completionCallback Callback that is notified when destruction and deletion of data is
* complete.
*/
public void destroyAndDeleteDataFromDisk(@Nullable Runnable completionCallback) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.destroyAndDeleteDataFromDisk(ObjectWrapper.wrap(completionCallback));
} catch (RemoteException e) {
throw new APICallException(e);
}
onDestroyed();
}
/**
* This method provides the same functionality as {@link destroyAndDeleteDataFromDisk}, but
* delays until there is no usage of the Profile. If there is no usage of the profile,
* destruction and deletion of data on disk is immediate. If there is usage, then destruction
* and deletion of data happens when there is no usage of the Profile. If the process is killed
* before deletion of data on disk occurs, then deletion of data happens when WebLayer is
* restarted.
*
* While destruction may be delayed, once this function is called, the profile name will not be
* returned from {@link WebLayer#enumerateAllProfileNames}. OTOH, {@link #getAllProfiles()}
* returns this profile until there are no more usages.
*
* If this function is called multiple times before the Profile is destroyed, then every
* callback supplied is run once destruction and deletion of data is complete.
*
* @param completionCallback Callback that is notified when destruction and deletion of data is
* complete. If the process is killed before all references are removed, the callback is never
* called.
*
* @throws IllegalStateException If the Profile has already been destroyed. You can check for
* that by looking for the profile in {@link #getAllProfiles()}.
*/
public void destroyAndDeleteDataFromDiskSoon(@Nullable Runnable completionCallback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
mImpl.destroyAndDeleteDataFromDiskSoon(ObjectWrapper.wrap(completionCallback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
private void throwIfDestroyed() {
if (mImpl == null) {
throw new IllegalStateException("Profile can not be used once destroyed");
}
}
@Deprecated
public void destroy() {
ThreadCheck.ensureOnUiThread();
try {
mImpl.destroy();
} catch (RemoteException e) {
throw new APICallException(e);
}
onDestroyed();
}
private void onDestroyed() {
if (mIsIncognito) {
sIncognitoProfiles.remove(mName);
} else {
sProfiles.remove(mName);
}
mImpl = null;
}
/**
* Allows embedders to override the default download directory. By default this is the system
* download directory.
*
* @param directory the directory to place downloads in.
*/
public void setDownloadDirectory(@NonNull File directory) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.setDownloadDirectory(directory.toString());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Allows embedders to control how downloads function.
*
* @param callback the callback interface implemented by the embedder.
*/
public void setDownloadCallback(@Nullable DownloadCallback callback) {
ThreadCheck.ensureOnUiThread();
try {
if (callback != null) {
mDownloadCallbackClient = new DownloadCallbackClientImpl(callback);
mImpl.setDownloadCallbackClient(mDownloadCallbackClient);
} else {
mDownloadCallbackClient = null;
mImpl.setDownloadCallbackClient(null);
}
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Gets the cookie manager for this profile.
*/
@NonNull
public CookieManager getCookieManager() {
ThreadCheck.ensureOnUiThread();
return mCookieManager;
}
/**
* Gets the prerender controller for this profile.
*/
@NonNull
public PrerenderController getPrerenderController() {
ThreadCheck.ensureOnUiThread();
return mPrerenderController;
}
/**
* Allows the embedder to set a boolean value for a specific setting, see {@link SettingType}
* for more details and the possible options.
*
* @param type See {@link SettingType}.
* @param value The value to set for the setting.
*/
public void setBooleanSetting(@SettingType int type, boolean value) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.setBooleanSetting(type, value);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the current value for the given setting type, see {@link SettingType} for more
* details and the possible options.
*/
public boolean getBooleanSetting(@SettingType int type) {
ThreadCheck.ensureOnUiThread();
try {
return mImpl.getBooleanSetting(type);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Asynchronously fetches the set of known Browser persistence-ids. See
* {@link WebLayer#createBrowserFragment} for details on the persistence-id.
*
* @param callback The callback that is supplied the set of ids.
*
* @throws IllegalStateException If called on an in memory profile.
*/
public void getBrowserPersistenceIds(@NonNull Callback<Set<String>> callback) {
ThreadCheck.ensureOnUiThread();
if (mName.isEmpty()) {
throw new IllegalStateException(
"getBrowserPersistenceIds() is not applicable to in-memory profiles");
}
try {
mImpl.getBrowserPersistenceIds(
ObjectWrapper.wrap((ValueCallback<Set<String>>) callback::onResult));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Asynchronously removes the storage associated with the set of Browser persistence-ids. This
* ignores ids actively in use. {@link doneCallback} is supplied the result of the operation. A
* value of true means all files were removed. A value of false indicates at least one of the
* files could not be removed.
*
* @param callback The callback that is supplied the result of the operation.
*
* @throws IllegalStateException If called on an in memory profile.
* @throws IllegalArgumentException if {@link ids} contains an empty/null string.
*/
public void removeBrowserPersistenceStorage(
@NonNull Set<String> ids, @NonNull Callback<Boolean> callback) {
ThreadCheck.ensureOnUiThread();
if (mName.isEmpty()) {
throw new IllegalStateException(
"removetBrowserPersistenceStorage() is not applicable to in-memory profiles");
}
try {
mImpl.removeBrowserPersistenceStorage(ids.toArray(new String[ids.size()]),
ObjectWrapper.wrap((ValueCallback<Boolean>) callback::onResult));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* For cross-origin navigations, the implementation may leverage a separate OS process for
* stronger isolation. If an embedder knows that a cross-origin navigation is likely starting
* soon, they can call this method as a hint to the implementation to start a fresh OS process.
* A subsequent navigation may use this preinitialized process, improving performance. It is
* safe to call this multiple times or when it is not certain that the spare renderer will be
* used, although calling this too eagerly may reduce performance as unnecessary processes are
* created.
*/
public void prepareForPossibleCrossOriginNavigation() {
ThreadCheck.ensureOnUiThread();
try {
mImpl.prepareForPossibleCrossOriginNavigation();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the previously downloaded favicon for {@link uri}.
*
* @param uri The uri to get the favicon for.
* @param callback The callback that is notified of the bitmap. The bitmap passed to the
* callback will be null if one is not available.
*/
public void getCachedFaviconForPageUri(@NonNull Uri uri, @NonNull Callback<Bitmap> callback) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.getCachedFaviconForPageUri(
uri.toString(), ObjectWrapper.wrap((ValueCallback<Bitmap>) callback::onResult));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* See {@link UserIdentityCallback}.
*/
public void setUserIdentityCallback(@Nullable UserIdentityCallback callback) {
ThreadCheck.ensureOnUiThread();
try {
mImpl.setUserIdentityCallbackClient(
callback == null ? null : new UserIdentityCallbackClientImpl(callback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* See {@link GoogleAccountAccessTokenFetcher}.
* @since 89
*/
public void setGoogleAccountAccessTokenFetcher(
@Nullable GoogleAccountAccessTokenFetcher fetcher) {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 89) {
throw new UnsupportedOperationException();
}
try {
mImpl.setGoogleAccountAccessTokenFetcherClient(fetcher == null
? null
: new GoogleAccountAccessTokenFetcherClientImpl(fetcher));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Sets a callback which is invoked to open a new tab that is not associated with any open tab.
*
* This will be called in cases where a service worker tries to open a tab, e.g. via the Web API
* clients.openWindow. If set to null, all such navigation requests will be rejected.
*
* @since 91
*/
public void setTablessOpenUrlCallback(@Nullable OpenUrlCallback callback) {
ThreadCheck.ensureOnUiThread();
if (WebLayer.getSupportedMajorVersionInternal() < 91) {
throw new UnsupportedOperationException();
}
try {
mImpl.setTablessOpenUrlCallbackClient(
callback == null ? null : new OpenUrlCallbackClientImpl(callback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
static final class DownloadCallbackClientImpl extends IDownloadCallbackClient.Stub {
private final DownloadCallback mCallback;
DownloadCallbackClientImpl(DownloadCallback callback) {
mCallback = callback;
}
@Override
public boolean interceptDownload(String uriString, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
StrictModeWorkaround.apply();
return mCallback.onInterceptDownload(
Uri.parse(uriString), userAgent, contentDisposition, mimetype, contentLength);
}
@Override
public void allowDownload(String uriString, String requestMethod,
String requestInitiatorString, IObjectWrapper valueCallback) {
StrictModeWorkaround.apply();
Uri requestInitiator;
if (requestInitiatorString != null) {
requestInitiator = Uri.parse(requestInitiatorString);
} else {
requestInitiator = Uri.EMPTY;
}
mCallback.allowDownload(Uri.parse(uriString), requestMethod, requestInitiator,
(ValueCallback<Boolean>) ObjectWrapper.unwrap(
valueCallback, ValueCallback.class));
}
@Override
public IClientDownload createClientDownload(IDownload downloadImpl) {
StrictModeWorkaround.apply();
return new Download(downloadImpl);
}
@Override
public void downloadStarted(IClientDownload download) {
StrictModeWorkaround.apply();
mCallback.onDownloadStarted((Download) download);
}
@Override
public void downloadProgressChanged(IClientDownload download) {
StrictModeWorkaround.apply();
mCallback.onDownloadProgressChanged((Download) download);
}
@Override
public void downloadCompleted(IClientDownload download) {
StrictModeWorkaround.apply();
mCallback.onDownloadCompleted((Download) download);
}
@Override
public void downloadFailed(IClientDownload download) {
StrictModeWorkaround.apply();
mCallback.onDownloadFailed((Download) download);
}
}
private static final class UserIdentityCallbackClientImpl
extends IUserIdentityCallbackClient.Stub {
private UserIdentityCallback mCallback;
UserIdentityCallbackClientImpl(UserIdentityCallback callback) {
mCallback = callback;
}
@Override
public String getEmail() {
StrictModeWorkaround.apply();
return mCallback.getEmail();
}
@Override
public String getFullName() {
StrictModeWorkaround.apply();
return mCallback.getFullName();
}
@Override
public void getAvatar(int desiredSize, IObjectWrapper avatarLoadedWrapper) {
StrictModeWorkaround.apply();
ValueCallback<Bitmap> avatarLoadedCallback =
(ValueCallback<Bitmap>) ObjectWrapper.unwrap(
avatarLoadedWrapper, ValueCallback.class);
mCallback.getAvatar(desiredSize, avatarLoadedCallback);
}
}
private static final class GoogleAccountAccessTokenFetcherClientImpl
extends IGoogleAccountAccessTokenFetcherClient.Stub {
private GoogleAccountAccessTokenFetcher mFetcher;
GoogleAccountAccessTokenFetcherClientImpl(GoogleAccountAccessTokenFetcher fetcher) {
mFetcher = fetcher;
}
@Override
public void fetchAccessToken(
IObjectWrapper scopesWrapper, IObjectWrapper onTokenFetchedWrapper) {
StrictModeWorkaround.apply();
Set<String> scopes = ObjectWrapper.unwrap(scopesWrapper, Set.class);
ValueCallback<String> valueCallback =
ObjectWrapper.unwrap(onTokenFetchedWrapper, ValueCallback.class);
mFetcher.fetchAccessToken(scopes, (token) -> valueCallback.onReceiveValue(token));
}
@Override
public void onAccessTokenIdentifiedAsInvalid(
IObjectWrapper scopesWrapper, IObjectWrapper tokenWrapper) {
StrictModeWorkaround.apply();
Set<String> scopes = ObjectWrapper.unwrap(scopesWrapper, Set.class);
String token = ObjectWrapper.unwrap(tokenWrapper, String.class);
mFetcher.onAccessTokenIdentifiedAsInvalid(scopes, token);
}
}
private static final class OpenUrlCallbackClientImpl extends IOpenUrlCallbackClient.Stub {
private final OpenUrlCallback mCallback;
OpenUrlCallbackClientImpl(OpenUrlCallback callback) {
mCallback = callback;
}
@Override
public IBrowser getBrowserForNewTab() {
StrictModeWorkaround.apply();
Browser browser = mCallback.getBrowserForNewTab();
return browser == null ? null : browser.getIBrowser();
}
@Override
public void onTabAdded(int tabId) {
StrictModeWorkaround.apply();
Tab tab = Tab.getTabById(tabId);
// Tab should have already been created by way of BrowserClient.
assert tab != null;
mCallback.onTabAdded(tab);
}
}
private final class ProfileClientImpl extends IProfileClient.Stub {
@Override
public void onProfileDestroyed() {
onDestroyed();
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/Profile.java | Java | unknown | 23,571 |
// 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.Bundle;
import android.os.RemoteException;
import android.view.SurfaceControlViewHost;
import android.view.View;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IRemoteFragment;
import org.chromium.weblayer_private.interfaces.IRemoteFragmentClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* A base class for different types of Fragments being rendered remotely.
*
* This class acts as a bridge for all the of the Fragment events received from the client side and
* the weblayer private implementation.
*/
abstract class RemoteFragmentEventHandler {
@Nullable
private IRemoteFragment mRemoteFragment;
private RemoteFragmentClientImpl mRemoteFragmentClient;
RemoteFragmentEventHandler(IRemoteFragment remoteFragment) {
ThreadCheck.ensureOnUiThread();
mRemoteFragment = remoteFragment;
mRemoteFragmentClient = new RemoteFragmentClientImpl();
try {
mRemoteFragment.setClient(mRemoteFragmentClient);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onAttach(Context context, @Nullable Fragment fragment) {
ThreadCheck.ensureOnUiThread();
mRemoteFragmentClient.setFragment(fragment);
try {
mRemoteFragment.handleOnAttach(ObjectWrapper.wrap(context));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onCreate() {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleOnCreate();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onStart() {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleOnStart();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onResume() {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleOnResume();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onPause() {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleOnPause();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onStop() {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleOnStop();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onDestroy() {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleOnDestroy();
// The other side does the clean up automatically in handleOnDestroy()
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onDetach() {
ThreadCheck.ensureOnUiThread();
mRemoteFragmentClient.setFragment(null);
try {
mRemoteFragment.handleOnDetach();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleOnActivityResult(
requestCode, resultCode, ObjectWrapper.wrap(intent));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected View getContentViewRenderView() {
ThreadCheck.ensureOnUiThread();
try {
return ObjectWrapper.unwrap(
mRemoteFragment.handleGetContentViewRenderView(), View.class);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void setSurfaceControlViewHost(SurfaceControlViewHost host) {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleSetSurfaceControlViewHost(ObjectWrapper.wrap(host));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@CallSuper
protected void setMinimumSurfaceSize(int width, int height) {
ThreadCheck.ensureOnUiThread();
try {
mRemoteFragment.handleSetMinimumSurfaceSize(width, height);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
protected IRemoteFragment getRemoteFragment() {
return mRemoteFragment;
}
final class RemoteFragmentClientImpl extends IRemoteFragmentClient.Stub {
// The WebFragment. Only available for in-process mode.
@Nullable
private Fragment mFragment;
void setFragment(@Nullable Fragment fragment) {
mFragment = fragment;
}
@Override
public boolean startActivityForResult(
IObjectWrapper intent, int requestCode, IObjectWrapper options) {
if (mFragment != null) {
mFragment.startActivityForResult(ObjectWrapper.unwrap(intent, Intent.class),
requestCode, ObjectWrapper.unwrap(options, Bundle.class));
return true;
}
return false;
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/RemoteFragmentEventHandler.java | Java | unknown | 5,992 |
// 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.Intent;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.RemoteMediaServiceConstants;
/**
* A foreground {@link Service} for Presentation API and Remote Playback API.
*
* Like {@link MediaSessionService}, this class is associated with a notification for an ongoing
* media session. The difference is that the media for this service is played back on a remote
* device, i.e. casting. This class can be considered an implementation detail of WebLayer.
*
* In order to set the Cast application (optional but recommended), the client should add the
* following to its manifest:
*
* <meta-data
* android:name="org.chromium.content.browser.REMOTE_PLAYBACK_APP_ID"
* android:value="$APP_ID"/>
*
* Where $APP_ID is the value assigned to your app by the Google Cast SDK Developer Console. If
* the cast application ID is not set, the app will appear as "Default Media Receiver" in the
* notification, device selection dialog, etc.
*
* @since 88
*/
class RemoteMediaService extends MediaPlaybackBaseService {
private int mId;
@Override
void forwardStartCommandToImpl(@NonNull WebLayer webLayer, Intent intent)
throws RemoteException {
mId = intent.getIntExtra(RemoteMediaServiceConstants.NOTIFICATION_ID_KEY, 0);
if (mId == 0) throw new RuntimeException("Invalid RemoteMediaService notification id");
webLayer.getImpl().onRemoteMediaServiceStarted(ObjectWrapper.wrap(this), intent);
}
@Override
void forwardDestroyToImpl() throws RemoteException {
getWebLayer().getImpl().onRemoteMediaServiceDestroyed(mId);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/RemoteMediaService.java | Java | unknown | 1,948 |
// 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({ScrollNotificationType.DIRECTION_CHANGED_UP,
ScrollNotificationType.DIRECTION_CHANGED_DOWN})
@Retention(RetentionPolicy.SOURCE)
@interface ScrollNotificationType {
/**
* This is the direction toward vertical scroll offset 0. Note direction change notification
* is sent on direction change. If there are two consecutive scrolls in the same direction,
* the second scroll will not generate a direction change notification. Also the notification
* is sent as a result of scroll change; this means for touch scrolls, this is sent (if there
* is a direction change) on the first touch move, not touch down.
*/
int DIRECTION_CHANGED_UP =
org.chromium.weblayer_private.interfaces.ScrollNotificationType.DIRECTION_CHANGED_UP;
/**
* This is the direction away from vertical scroll offset 0. See notes on DIRECTION_CHANGED_UP.
*/
int DIRECTION_CHANGED_DOWN =
org.chromium.weblayer_private.interfaces.ScrollNotificationType.DIRECTION_CHANGED_DOWN;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ScrollNotificationType.java | Java | unknown | 1,352 |
// 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;
/**
* Callback notified when the vertical location of the content of a Tab changes. The value reported
* by the callback corresponds to the 'scrollTop' html property.
*
* WARNING: use of this API necessitates additional cross process ipc that impacts overall
* performance. Only use when absolutely necessary.
*
* Because of WebLayer's multi-process architecture, this function can not be used to reliably
* synchronize the painting of other Views with WebLayer's Views. It's entirely possible one will
* render before or after the other.
*/
abstract class ScrollOffsetCallback {
/**
* Called when the vertical scroll location of the content of a Tab changes.
*
* @param scrollLocation The new vertical location. More specifically, the 'scrollTop' html
* property.
*/
public abstract void onVerticalScrollOffsetChanged(int scrollLocation);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/ScrollOffsetCallback.java | Java | unknown | 1,061 |
// 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({SettingType.BASIC_SAFE_BROWSING_ENABLED, SettingType.UKM_ENABLED,
SettingType.EXTENDED_REPORTING_SAFE_BROWSING_ENABLED,
SettingType.REAL_TIME_SAFE_BROWSING_ENABLED})
@Retention(RetentionPolicy.SOURCE)
@interface SettingType {
/**
* Allows the embedder to set whether it wants to disable/enable the Safe Browsing functionality
* (which checks that the loaded URLs are safe). Safe Browsing is enabled by default.
*/
int BASIC_SAFE_BROWSING_ENABLED =
org.chromium.weblayer_private.interfaces.SettingType.BASIC_SAFE_BROWSING_ENABLED;
/**
* Allows the embedder to enable URL-Keyed Metrics. Disabled by default.
*/
int UKM_ENABLED = org.chromium.weblayer_private.interfaces.SettingType.UKM_ENABLED;
/**
* Allows the embedder to set whether it wants to enable/disable the Extended Reporting
* functionality for Safe Browsing (SBER). This functionality helps improve security on the web
* for everyone. It sends URLs of some pages you visit, limited system information, and some
* page content to Google, to help discover new threats and protect everyone on the web.
*
* This setting is disabled by default, but can also be enabled by the user by checking a
* checkbox in the Safe Browsing interstitial which is displayed when the user encounters a
* dangerous web page. The setting persists on disk.
*
* Note: this setting applies when Safe Browsing is enabled (i.e. BASIC_SAFE_BROWSING_ENABLED
* is true).
*/
int EXTENDED_REPORTING_SAFE_BROWSING_ENABLED =
org.chromium.weblayer_private.interfaces.SettingType
.EXTENDED_REPORTING_SAFE_BROWSING_ENABLED;
/**
* Allows the embedder to set whether it wants to enable/disable the Safe Browsing Real-time URL
* checks. This functionality is disabled by default.
*
* Note: this setting applies when Safe Browsing is enabled (i.e. BASIC_SAFE_BROWSING_ENABLED
* is true).
*/
int REAL_TIME_SAFE_BROWSING_ENABLED =
org.chromium.weblayer_private.interfaces.SettingType.REAL_TIME_SAFE_BROWSING_ENABLED;
/**
* Allows the embedder to enable/disable NoStatePrefetch. Enabled by default.
*/
int NETWORK_PREDICTION_ENABLED =
org.chromium.weblayer_private.interfaces.SettingType.NETWORK_PREDICTION_ENABLED;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/SettingType.java | Java | unknown | 2,708 |
// 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.graphics.Bitmap;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Pair;
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.IClientNavigation;
import org.chromium.weblayer_private.interfaces.IContextMenuParams;
import org.chromium.weblayer_private.interfaces.IErrorPageCallbackClient;
import org.chromium.weblayer_private.interfaces.IExternalIntentInIncognitoCallbackClient;
import org.chromium.weblayer_private.interfaces.IFullscreenCallbackClient;
import org.chromium.weblayer_private.interfaces.IGoogleAccountsCallbackClient;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IStringCallback;
import org.chromium.weblayer_private.interfaces.ITab;
import org.chromium.weblayer_private.interfaces.ITabClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Represents a single tab in a browser. More specifically, owns a NavigationController, and allows
* configuring state of the tab, such as delegates and callbacks.
*/
class Tab {
// Maps from id (as returned from ITab.getId()) to Tab.
private static final Map<Integer, Tab> sTabMap = new HashMap<Integer, Tab>();
private ITab mImpl;
// Remember the stack of Tab destruction.
private Throwable mDestroyStack;
private final NavigationController mNavigationController;
private final FindInPageController mFindInPageController;
private final MediaCaptureController mMediaCaptureController;
private final ObserverList<TabCallback> mCallbacks;
private Browser mBrowser;
private FullscreenCallbackClientImpl mFullscreenCallbackClient;
private NewTabCallback mNewTabCallback;
private final ObserverList<ScrollOffsetCallback> mScrollOffsetCallbacks;
private @Nullable ActionModeCallback mActionModeCallback;
private TabProxy mTabProxy;
private TabNavigationControllerProxy mTabNavigationControllerProxy;
// Id from the remote side.
private final int mId;
// Guid from the remote side.
private final String mGuid;
// Constructor for test mocking.
protected Tab() {
mImpl = null;
mNavigationController = null;
mFindInPageController = null;
mMediaCaptureController = null;
mCallbacks = null;
mScrollOffsetCallbacks = null;
mId = 0;
mGuid = "";
mTabProxy = null;
mTabNavigationControllerProxy = null;
}
Tab(ITab impl, Browser browser) {
mImpl = impl;
mBrowser = browser;
try {
mId = impl.getId();
mGuid = impl.getGuid();
mImpl.setClient(new TabClientImpl());
} catch (RemoteException e) {
throw new APICallException(e);
}
mCallbacks = new ObserverList<TabCallback>();
mScrollOffsetCallbacks = new ObserverList<ScrollOffsetCallback>();
mNavigationController = NavigationController.create(mImpl);
mFindInPageController = new FindInPageController(mImpl);
mMediaCaptureController = new MediaCaptureController(mImpl);
mTabProxy = new TabProxy(this);
mTabNavigationControllerProxy = new TabNavigationControllerProxy(mNavigationController);
registerTab(this);
}
static void registerTab(Tab tab) {
assert getTabById(tab.getId()) == null;
sTabMap.put(tab.getId(), tab);
}
static void unregisterTab(Tab tab) {
assert getTabById(tab.getId()) != null;
sTabMap.remove(tab.getId());
}
static Tab getTabById(int id) {
return sTabMap.get(id);
}
static Set<Tab> getTabsInBrowser(Browser browser) {
Set<Tab> tabs = new HashSet<Tab>();
for (Tab tab : sTabMap.values()) {
if (tab.getBrowser() == browser) tabs.add(tab);
}
return tabs;
}
private void throwIfDestroyed() {
if (mImpl == null) {
throw new IllegalStateException("Tab can not be used once destroyed", mDestroyStack);
}
}
int getId() {
return mId;
}
String getUri() {
try {
return mImpl.getUri();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
void setBrowser(Browser browser) {
mBrowser = browser;
}
/**
* Returns true if this Tab has been destroyed.
*/
public boolean isDestroyed() {
ThreadCheck.ensureOnUiThread();
return mImpl == null;
}
/**
* Returns whether the tab will automatically reload after its renderer process is lost.
*
* This returns true if the tab is known not to be visible, specifically if the tab is not
* active in its browser or its Fragment is not started. When a tab in this state loses its
* renderer process to a crash (or due to system memory reclamation), it will automatically
* reload next the time it becomes possibly visible.
*/
public boolean willAutomaticallyReloadAfterCrash() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
return mImpl.willAutomaticallyReloadAfterCrash();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@NonNull
public Browser getBrowser() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
return mBrowser;
}
public void setErrorPageCallback(@Nullable ErrorPageCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
mImpl.setErrorPageCallbackClient(
callback == null ? null : new ErrorPageCallbackClientImpl(callback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public void setFullscreenCallback(@Nullable FullscreenCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
if (callback != null) {
mFullscreenCallbackClient = new FullscreenCallbackClientImpl(callback);
mImpl.setFullscreenCallbackClient(mFullscreenCallbackClient);
} else {
mImpl.setFullscreenCallbackClient(null);
mFullscreenCallbackClient = null;
}
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Creates a {@link FaviconFetcher} that notifies a {@link FaviconCallback} when the favicon
* changes.
*
* When the fetcher is no longer necessary, call {@link destroy}. Destroying the Tab implicitly
* destroys any fetchers that were created.
*
* A page may provide any number of favicons. This favors a largish favicon. If a previously
* cached icon is available, it is used, otherwise the icon is downloaded.
*
* {@link callback} may be called multiple times for the same navigation. This happens if the
* page dynamically updates the favicon.
*
* @param callback The callback to notify of changes.
*/
public @NonNull FaviconFetcher createFaviconFetcher(@NonNull FaviconCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
return new FaviconFetcher(mImpl, callback);
}
/**
* Sets the target language for translation such that whenever the translate UI shows in this
* Tab, the target language will be |targetLanguage|. Notes:
* - |targetLanguage| should be specified as the language code (e.g., "de" for German).
* - Passing an empty string causes behavior to revert to default.
* - Specifying a non-empty target language will also result in the following behaviors (all of
* which are intentional as part of the semantics of having a target language):
* - Translation is initiated automatically (note that the infobar UI is present)
* - Translation occurs even for languages/sites that the user has blocklisted
* - Translation occurs even for pages in the user's default locale
* - Translation does *not* occur nor is the infobar UI shown for pages in the specified
* target language
*/
public void setTranslateTargetLanguage(@NonNull String targetLanguage) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
mImpl.setTranslateTargetLanguage(targetLanguage);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Executes the script, and returns the result to the callback if provided.
* @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.
*/
public void executeScript(
@NonNull String script, boolean useSeparateIsolate, IStringCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
mImpl.executeScript(script, useSeparateIsolate, callback);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Runs the beforeunload handler for the main frame or any sub frame, if necessary; otherwise,
* asynchronously closes the tab.
*
* If there is a beforeunload handler a dialog is shown to the user which will allow them to
* choose whether to proceed with closing the tab. WebLayer closes the tab internally and the
* embedder will be notified via TabListCallback#onTabRemoved(). The tab will not close if the
* user chooses to cancel the action. If there is no beforeunload handler, the tab closure will
* be asynchronous (but immediate) and will be notified in the same way.
*
* To close the tab synchronously without running beforeunload, use {@link Browser#destroyTab}.
*/
public void dispatchBeforeUnloadAndClose() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
mImpl.dispatchBeforeUnloadAndClose();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Dismisses one active transient UI, if any.
*
* This is useful, for example, to handle presses on the system back button. UI such as tab
* modal dialogs, text selection popups and fullscreen will be dismissed. At most one piece of
* UI will be dismissed, but this distinction isn't very meaningful in practice since only one
* such kind of UI would tend to be active at a time.
*
* @return true if some piece of UI was dismissed, or false if nothing happened.
*/
public boolean dismissTransientUi() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
return mImpl.dismissTransientUi();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public void setNewTabCallback(@Nullable NewTabCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
mNewTabCallback = callback;
try {
mImpl.setNewTabsEnabled(mNewTabCallback != null);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@Nullable
public FullscreenCallback getFullscreenCallback() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
return mFullscreenCallbackClient != null ? mFullscreenCallbackClient.getCallback() : null;
}
@NonNull
public NavigationController getNavigationController() {
throwIfDestroyed();
return mNavigationController;
}
@NonNull
public FindInPageController getFindInPageController() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
return mFindInPageController;
}
@NonNull
public MediaCaptureController getMediaCaptureController() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
return mMediaCaptureController;
}
public void registerTabCallback(@NonNull TabCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
mCallbacks.addObserver(callback);
}
public void unregisterTabCallback(@NonNull TabCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
mCallbacks.removeObserver(callback);
}
/**
* Registers {@link callback} to be notified when the scroll offset changes. <b>WARNING:</b>
* adding a {@link ScrollOffsetCallback} impacts performance, ensure
* {@link ScrollOffsetCallback} are only installed when needed. See {@link ScrollOffsetCallback}
* for more details.
*
* @param callback The ScrollOffsetCallback to notify
*/
public void registerScrollOffsetCallback(@NonNull ScrollOffsetCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
if (mScrollOffsetCallbacks.isEmpty()) {
try {
mImpl.setScrollOffsetsEnabled(true);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
mScrollOffsetCallbacks.addObserver(callback);
}
public void unregisterScrollOffsetCallback(@NonNull ScrollOffsetCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
mScrollOffsetCallbacks.removeObserver(callback);
if (mScrollOffsetCallbacks.isEmpty()) {
try {
mImpl.setScrollOffsetsEnabled(false);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
}
/**
* Take a screenshot of this tab and return it as a Bitmap.
* This API captures only the web content, not any Java Views, including the
* view in Browser.setTopView. The browser top view shrinks the height of
* the screenshot if it is not completely hidden.
* This method will fail if
* * the Fragment of this Tab is not started during the operation
* * this tab is not the active tab in its Browser
* * if scale is not in the range (0, 1]
* * Bitmap allocation fails
* The API is asynchronous when successful, but can be synchronous on
* failure. So embedder must take care when implementing resultCallback to
* allow reentrancy.
* @param scale Scale applied to the Bitmap.
* @param resultCallback Called when operation is complete.
*/
public void captureScreenShot(float scale, @NonNull CaptureScreenShotCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
mImpl.captureScreenShot(scale,
ObjectWrapper.wrap(
(ValueCallback<Pair<Bitmap, Integer>>) (Pair<Bitmap, Integer> pair) -> {
callback.onScreenShotCaptured(pair.first, pair.second);
}));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
ITab getITab() {
return mImpl;
}
/**
* Returns a unique id that persists across restarts.
*
* @return the unique id.
*/
@NonNull
public String getGuid() {
return mGuid;
}
@NonNull
TabNavigationControllerProxy getTabNavigationControllerProxy() {
return mTabNavigationControllerProxy;
}
@NonNull
TabProxy getTabProxy() {
return mTabProxy;
}
/**
* Set arbitrary data on the tab. This will be saved and restored with the browser, so it is
* important to keep this data as small as possible.
*
* @param data The data to set, must be smaller than 4K when serialized. A snapshot of this data
* is taken, so any changes to the passed in object after this call will not be reflected.
*
* @throws IllegalArgumentException if the serialzed size of the data exceeds 4K.
*/
public void setData(@NonNull Map<String, String> data) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
if (!mImpl.setData(data)) {
throw new IllegalArgumentException("Data given to Tab.setData() was too large.");
}
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Get arbitrary data set on the tab with setData().
*
* @return the data or an empty map if no data was set.
*/
@NonNull
public Map<String, String> getData() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
return (Map<String, String>) mImpl.getData();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Sets a callback to intercept interaction with GAIA accounts. If this callback is set, any
* link that would result in a change to a user's GAIA account state will trigger a call to
* {@link GoogleAccountsCallback#onGoogleAccountsRequest}.
*/
public void setGoogleAccountsCallback(@Nullable GoogleAccountsCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
mImpl.setGoogleAccountsCallbackClient(
callback == null ? null : new GoogleAccountsCallbackClientImpl(callback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Sets a callback to present warning dialogs gating external intent launches in incognito mode.
* If this callback is set, any such pending intent launch will trigger a call to {@link
* ExternalIntentInIncognitoCallback#onExternalIntentInIncognito}.
* @since 93
*/
public void setExternalIntentInIncognitoCallback(
@Nullable ExternalIntentInIncognitoCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
if (WebLayer.getSupportedMajorVersionInternal() < 93) {
throw new UnsupportedOperationException();
}
try {
mImpl.setExternalIntentInIncognitoCallbackClient(callback == null
? null
: new ExternalIntentInIncognitoCallbackClientImpl(callback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
void postMessage(String message, String targetOrigin) {
try {
mImpl.postMessage(message, targetOrigin);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns true if the content displayed in this tab can be translated.
*/
public boolean canTranslate() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
return mImpl.canTranslate();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Shows the UI which allows the user to translate the content displayed in this tab.
*/
public void showTranslateUi() {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
try {
mImpl.showTranslateUi();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Allow controlling and overriding custom items in the floating seleciton menu.
* Note floating action mode is available on M and up.
* @param actionModeItemTypes a bit field of values in ActionModeItemType.
* @param callback can be null if actionModeItemTypes is 0.
*
* @since 88
*/
public void setFloatingActionModeOverride(
int actionModeItemTypes, @Nullable ActionModeCallback callback) {
ThreadCheck.ensureOnUiThread();
throwIfDestroyed();
if (WebLayer.getSupportedMajorVersionInternal() < 88) {
throw new UnsupportedOperationException();
}
mActionModeCallback = callback;
try {
mImpl.setFloatingActionModeOverride(actionModeItemTypes);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Turns on desktop user agent if enable is true, otherwise reverts back to mobile user agent.
* The selected user agent will be used for future navigations until this method is called
* again. Each navigation saves the user agent mode it was navigated with and will reuse that on
* back/forward navigations. The tab will be reloaded with the new user agent.
* @param enable if true requests desktop site, otherwise mobile site.
*
* @since 88
*/
public void setDesktopUserAgentEnabled(boolean enable) {
if (WebLayer.getSupportedMajorVersionInternal() < 88) {
throw new UnsupportedOperationException();
}
try {
mImpl.setDesktopUserAgentEnabled(enable);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns true if the currently loaded page used a desktop user agent.
*
* @since 88
*/
public boolean isDesktopUserAgentEnabled() {
if (WebLayer.getSupportedMajorVersionInternal() < 88) {
throw new UnsupportedOperationException();
}
try {
return mImpl.isDesktopUserAgentEnabled();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Downloads the item linked to from the context menu. This could be an image/video or link.
* This will request the WRITE_EXTERNAL_STORAGE permission if it's not granted to the app.
*
* @throws IllegalArgumentException if {@link ContextMenuParams.canDownload} is false or if
* the ContextMenuParams object parameter wasn't constructed by WebLayer.
*
* @since 88
*/
public void download(ContextMenuParams contextMenuParams) {
if (WebLayer.getSupportedMajorVersionInternal() < 88) {
throw new UnsupportedOperationException();
}
if (!contextMenuParams.canDownload) {
throw new IllegalArgumentException("ContextMenuParams not downloadable.");
}
if (contextMenuParams.mContextMenuParams == null) {
throw new IllegalArgumentException("ContextMenuParams not constructed by WebLayer.");
}
try {
mImpl.download(contextMenuParams.mContextMenuParams);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Experimental (for now) API to trigger the AddToHomescreen dialog for the page in the tab.
* This adds a homescreen shortcut for it, or installs as a PWA or WebAPK.
*
* @since 90
*/
private void addToHomescreen() {
if (WebLayer.getSupportedMajorVersionInternal() < 90) {
throw new UnsupportedOperationException();
}
try {
mImpl.addToHomescreen();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
private final class TabClientImpl extends ITabClient.Stub {
@Override
public void visibleUriChanged(String uriString) {
StrictModeWorkaround.apply();
Uri uri = Uri.parse(uriString);
for (TabCallback callback : mCallbacks) {
callback.onVisibleUriChanged(uri);
}
}
@Override
public void onNewTab(int tabId, int mode) {
StrictModeWorkaround.apply();
// This should only be hit if setNewTabCallback() has been called with a non-null
// value.
assert mNewTabCallback != null;
Tab tab = getTabById(tabId);
// Tab should have already been created by way of BrowserClient.
assert tab != null;
assert tab.getBrowser() == getBrowser();
mNewTabCallback.onNewTab(tab, mode);
}
@Override
public void onTabDestroyed() {
unregisterTab(Tab.this);
// Ensure that the app will fail fast if the embedder mistakenly tries to call back
// into the implementation via this Tab.
mImpl = null;
mDestroyStack = new RuntimeException("onTabDestroyed");
}
@Override
public void onRenderProcessGone() {
StrictModeWorkaround.apply();
for (TabCallback callback : mCallbacks) {
callback.onRenderProcessGone();
}
}
@Override
public void showContextMenu(IObjectWrapper pageUrl, IObjectWrapper linkUrl,
IObjectWrapper linkText, IObjectWrapper titleOrAltText, IObjectWrapper srcUrl) {
showContextMenu2(
pageUrl, linkUrl, linkText, titleOrAltText, srcUrl, false, false, false, null);
}
@Override
public void showContextMenu2(IObjectWrapper pageUrl, IObjectWrapper linkUrl,
IObjectWrapper linkText, IObjectWrapper titleOrAltText, IObjectWrapper srcUrl,
boolean isImage, boolean isVideo, boolean canDownload,
IContextMenuParams contextMenuParams) {
StrictModeWorkaround.apply();
String pageUrlString = ObjectWrapper.unwrap(pageUrl, String.class);
String linkUrlString = ObjectWrapper.unwrap(linkUrl, String.class);
String srcUrlString = ObjectWrapper.unwrap(srcUrl, String.class);
ContextMenuParams params = new ContextMenuParams(Uri.parse(pageUrlString),
linkUrlString != null ? Uri.parse(linkUrlString) : null,
ObjectWrapper.unwrap(linkText, String.class),
ObjectWrapper.unwrap(titleOrAltText, String.class),
srcUrlString != null ? Uri.parse(srcUrlString) : null, isImage, isVideo,
canDownload, contextMenuParams);
for (TabCallback callback : mCallbacks) {
callback.showContextMenu(params);
}
}
@Override
public void onTabModalStateChanged(boolean isTabModalShowing) {
StrictModeWorkaround.apply();
for (TabCallback callback : mCallbacks) {
callback.onTabModalStateChanged(isTabModalShowing);
}
}
@Override
public void onTitleUpdated(IObjectWrapper title) {
StrictModeWorkaround.apply();
String titleString = ObjectWrapper.unwrap(title, String.class);
for (TabCallback callback : mCallbacks) {
callback.onTitleUpdated(titleString);
}
}
@Override
public void bringTabToFront() {
StrictModeWorkaround.apply();
for (TabCallback callback : mCallbacks) {
callback.bringTabToFront();
}
}
@Override
public void onBackgroundColorChanged(int color) {
StrictModeWorkaround.apply();
for (TabCallback callback : mCallbacks) {
callback.onBackgroundColorChanged(color);
}
}
@Override
public void onScrollNotification(
@ScrollNotificationType int notificationType, float currentScrollRatio) {
StrictModeWorkaround.apply();
for (TabCallback callback : mCallbacks) {
callback.onScrollNotification(notificationType, currentScrollRatio);
}
}
@Override
public void onVerticalScrollOffsetChanged(int value) {
StrictModeWorkaround.apply();
for (ScrollOffsetCallback callback : mScrollOffsetCallbacks) {
callback.onVerticalScrollOffsetChanged(value);
}
}
@Override
public void onActionItemClicked(
int actionModeItemType, IObjectWrapper selectedStringWrapper) {
StrictModeWorkaround.apply();
String selectedString = ObjectWrapper.unwrap(selectedStringWrapper, String.class);
if (mActionModeCallback != null) {
mActionModeCallback.onActionItemClicked(actionModeItemType, selectedString);
}
}
@Override
public void onVerticalOverscroll(float accumulatedOverscrollY) {
StrictModeWorkaround.apply();
for (TabCallback callback : mCallbacks) {
callback.onVerticalOverscroll(accumulatedOverscrollY);
}
}
@Override
public void onPostMessage(String message, String origin) {
StrictModeWorkaround.apply();
mTabProxy.onPostMessage(message, origin);
}
}
private static final class ErrorPageCallbackClientImpl extends IErrorPageCallbackClient.Stub {
private final ErrorPageCallback mCallback;
ErrorPageCallbackClientImpl(ErrorPageCallback callback) {
mCallback = callback;
}
public ErrorPageCallback getCallback() {
return mCallback;
}
@Override
public boolean onBackToSafety() {
StrictModeWorkaround.apply();
return mCallback.onBackToSafety();
}
@Override
public String getErrorPageContent(IClientNavigation navigation) {
StrictModeWorkaround.apply();
ErrorPage errorPage = mCallback.getErrorPage((Navigation) navigation);
return errorPage == null ? null : errorPage.htmlContent;
}
}
private static final class FullscreenCallbackClientImpl extends IFullscreenCallbackClient.Stub {
private FullscreenCallback mCallback;
/* package */ FullscreenCallbackClientImpl(FullscreenCallback callback) {
mCallback = callback;
}
public FullscreenCallback getCallback() {
return mCallback;
}
@Override
public void enterFullscreen(IObjectWrapper exitFullscreenWrapper) {
StrictModeWorkaround.apply();
ValueCallback<Void> exitFullscreenCallback = (ValueCallback<Void>) ObjectWrapper.unwrap(
exitFullscreenWrapper, ValueCallback.class);
mCallback.onEnterFullscreen(() -> exitFullscreenCallback.onReceiveValue(null));
}
@Override
public void exitFullscreen() {
StrictModeWorkaround.apply();
mCallback.onExitFullscreen();
}
}
private static final class GoogleAccountsCallbackClientImpl
extends IGoogleAccountsCallbackClient.Stub {
private GoogleAccountsCallback mCallback;
GoogleAccountsCallbackClientImpl(GoogleAccountsCallback callback) {
mCallback = callback;
}
@Override
public void onGoogleAccountsRequest(
int serviceType, String email, String continueUrl, boolean isSameTab) {
StrictModeWorkaround.apply();
mCallback.onGoogleAccountsRequest(new GoogleAccountsParams(
serviceType, email, Uri.parse(continueUrl), isSameTab));
}
@Override
public String getGaiaId() {
StrictModeWorkaround.apply();
return mCallback.getGaiaId();
}
}
private static final class ExternalIntentInIncognitoCallbackClientImpl
extends IExternalIntentInIncognitoCallbackClient.Stub {
private ExternalIntentInIncognitoCallback mCallback;
ExternalIntentInIncognitoCallbackClientImpl(ExternalIntentInIncognitoCallback callback) {
mCallback = callback;
}
@Override
public void onExternalIntentInIncognito(IObjectWrapper onUserDecisionWrapper) {
StrictModeWorkaround.apply();
ValueCallback<Integer> valueCallback =
ObjectWrapper.unwrap(onUserDecisionWrapper, ValueCallback.class);
mCallback.onExternalIntentInIncognito(
(userDecision) -> valueCallback.onReceiveValue(userDecision));
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/Tab.java | Java | unknown | 33,003 |
// 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 a Tab.
*/
abstract class TabCallback {
/**
* The Uri that should be displayed in the location-bar has updated.
*
* @param uri The new user-visible uri.
*/
public void onVisibleUriChanged(@NonNull Uri uri) {}
/**
* Triggered when the render process dies, either due to crash or killed by the system to
* reclaim memory.
*/
public void onRenderProcessGone() {}
/**
* Triggered when a context menu should be displayed.
*/
public void showContextMenu(@NonNull ContextMenuParams params) {}
/**
* Triggered when a tab's contents have been rendered inactive due to a modal overlay, or active
* due to the dismissal of a modal overlay (dialog/bubble/popup).
*
* @param isTabModalShowing true when a dialog is blocking interaction with the web contents.
*/
public void onTabModalStateChanged(boolean isTabModalShowing) {}
/**
* 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 title New title of this tab.
*/
public void onTitleUpdated(@NonNull String title) {}
/**
* Called when user attention should be brought to this tab. This should cause the tab, its
* containing Activity, and the task to be foregrounded.
*/
public void bringTabToFront() {}
/**
* Called when then background color of the page changes. The background color typically comes
* from css background-color, but heuristics and blending may be used depending upon the page.
* This is mostly useful for filling in gaps around the web page during resize, but it will
* not necessarily match the full background of the page.
* @param color The new ARGB color of the page background.
*/
public void onBackgroundColorChanged(int color) {}
/**
* Notification for scroll of the root of the web page. This is generally sent as a result of
* displaying web page. See ScrollNotificationType for more details. ScrollNotificationType is
* meant to be extensible and new types may be added in the future. Embedder should take care
* to allow unknown values.
* @param notificationType type of notification. See ScrollNotificationType for more details.
* @param currentScrollRatio value in [0, 1] indicating the current scroll ratio. For example
* a web page that is 200 pixels, has a viewport of height 50 pixels
* and a scroll offset of 50 pixels will have a ratio of 0.5.
*/
public void onScrollNotification(
@ScrollNotificationType int notificationType, float currentScrollRatio) {}
/**
* Notification for vertical overscroll. This happens when user tries to touch scroll beyond
* the scroll bounds, or when a fling animation hits scroll bounds.
* A few caveats when using this callback:
* * This should be considered independent and unordered with respect to other scroll callbacks
* such as `onScrollNotification` or `ScrollOffsetCallback.onVerticalScrollOffsetChanged`.
* Client should not assume a certain order between this and other scroll notifications.
* * The value is accumulated scroll, so the magnitude of the value only goes up for a single
* overscroll gesture. However this is not enough to distinguish between two overscroll
* gestures and client must listen to touch events to make such distinction. Similarly there
* is no "end overscroll" event, and client is expected to listen to touch events as well.
* Added in M101.
* @param accumulatedOverscrollY negative for when trying to scroll beyond offset 0, positive
* for when trying to scroll beyond bottom scroll bounds.
*/
public void onVerticalOverscroll(float accumulatedOverscrollY) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/TabCallback.java | Java | unknown | 4,235 |
// 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;
/**
* An interface for observing events related to tab initialization on startup, either a new tab or
* restoring previous tabs basedon on a persistence ID.
*/
abstract class TabInitializationCallback {
/**
* Called when WebLayer has finished the tab initialization.
*/
public void onTabInitializationCompleted() {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/TabInitializationCallback.java | Java | unknown | 515 |
// 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 for observing changes to the set of tabs in a browser.
*/
abstract class TabListCallback {
/**
* The active tab has changed.
*
* @param activeTab The newly active tab, null if no tab is active.
*/
public void onActiveTabChanged(@Nullable Tab activeTab) {}
/**
* A tab was added to the Browser.
*
* @param tab The tab that was added.
*/
public void onTabAdded(@NonNull Tab tab) {}
/**
* A tab was removed from the Browser.
*
* WARNING: this is *not* called when the Browser is destroyed. See {@link
* #onWillDestroyBrowserAndAllTabs} for more.
*
* @param tab The tab that was removed.
*/
public void onTabRemoved(@NonNull Tab tab) {}
/**
* Called when the Fragment the Browser is associated with is about to be destroyed. After this
* call the Browser and all Tabs are destroyed and can not be used.
*/
public void onWillDestroyBrowserAndAllTabs() {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/TabListCallback.java | Java | unknown | 1,248 |
// 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.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import org.chromium.webengine.interfaces.ITabCallback;
import org.chromium.webengine.interfaces.ITabListObserverDelegate;
import org.chromium.webengine.interfaces.ITabManagerDelegate;
import org.chromium.webengine.interfaces.ITabParams;
class TabManagerDelegate extends ITabManagerDelegate.Stub {
private Handler mHandler = new Handler(Looper.getMainLooper());
private Browser mBrowser;
private WebFragmentTabListDelegate mTabListDelegate = new WebFragmentTabListDelegate();
TabManagerDelegate(Browser browser) {
mBrowser = browser;
browser.registerTabListCallback(mTabListDelegate);
}
@Override
public void setTabListObserverDelegate(ITabListObserverDelegate tabListObserverDelegate) {
mTabListDelegate.setObserver(tabListObserverDelegate);
}
@Override
public void notifyInitialTabs() {
mHandler.post(() -> {
mTabListDelegate.notifyInitialTabs(mBrowser.getTabs(), mBrowser.getActiveTab());
});
}
@Override
public void getActiveTab(ITabCallback tabCallback) {
mHandler.post(() -> {
Tab activeTab = mBrowser.getActiveTab();
try {
if (activeTab != null) {
ITabParams tabParams = TabParams.buildParcelable(activeTab);
tabCallback.onResult(tabParams);
} else {
tabCallback.onResult(null);
}
} catch (RemoteException e) {
}
});
}
@Override
public void createTab(ITabCallback callback) {
mHandler.post(() -> {
Tab newTab = mBrowser.createTab();
try {
callback.onResult(TabParams.buildParcelable(newTab));
} catch (RemoteException e) {
}
});
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/TabManagerDelegate.java | Java | unknown | 2,084 |
// 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.IBooleanCallback;
import org.chromium.webengine.interfaces.INavigationObserverDelegate;
import org.chromium.webengine.interfaces.ITabNavigationControllerProxy;
class TabNavigationControllerProxy extends ITabNavigationControllerProxy.Stub {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private WebFragmentNavigationDelegate mNavigationObserverDelegate =
new WebFragmentNavigationDelegate();
private final NavigationController mNavigationController;
TabNavigationControllerProxy(NavigationController navigationController) {
mNavigationController = navigationController;
mNavigationController.registerNavigationCallback(mNavigationObserverDelegate);
}
@Override
public void navigate(String uri) {
mHandler.post(() -> {
NavigateParams.Builder navigateParamsBuilder =
new NavigateParams.Builder().disableIntentProcessing();
mNavigationController.navigate(Uri.parse(uri), navigateParamsBuilder.build());
});
}
@Override
public void goBack() {
mHandler.post(() -> { mNavigationController.goBack(); });
}
@Override
public void goForward() {
mHandler.post(() -> { mNavigationController.goForward(); });
}
@Override
public void canGoBack(IBooleanCallback callback) {
mHandler.post(() -> {
try {
callback.onResult(mNavigationController.canGoBack());
} catch (RemoteException e) {
}
});
}
@Override
public void canGoForward(IBooleanCallback callback) {
mHandler.post(() -> {
try {
callback.onResult(mNavigationController.canGoForward());
} catch (RemoteException e) {
}
});
}
@Override
public void reload() {
mHandler.post(() -> { mNavigationController.reload(); });
}
@Override
public void stop() {
mHandler.post(() -> { mNavigationController.stop(); });
}
@Override
public void setNavigationObserverDelegate(INavigationObserverDelegate navigationDelegate) {
mNavigationObserverDelegate.setObserver(navigationDelegate);
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/TabNavigationControllerProxy.java | Java | unknown | 2,559 |
// 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 androidx.annotation.NonNull;
import org.chromium.webengine.interfaces.ITabParams;
/**
* Parameters for {@link Tab}.
*/
class TabParams {
static ITabParams buildParcelable(@NonNull Tab tab) {
ITabParams parcel = new ITabParams();
parcel.tabProxy = tab.getTabProxy();
parcel.tabGuid = tab.getGuid();
parcel.uri = tab.getUri();
parcel.navigationControllerProxy = tab.getTabNavigationControllerProxy();
return parcel;
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/TabParams.java | Java | unknown | 661 |
// 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.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import org.chromium.webengine.interfaces.ExceptionType;
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 org.chromium.webengine.interfaces.ITabProxy;
import java.util.ArrayList;
import java.util.List;
/**
* This class acts as a proxy between a Tab object in the embedding app
* and the Tab implementation in WebLayer.
* A (@link TabProxy} is owned by the {@link Tab}.
*/
class TabProxy extends ITabProxy.Stub {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private int mTabId;
private String mGuid;
private WebFragmentTabDelegate mTabObserverDelegate = new WebFragmentTabDelegate();
private WebFragmentNavigationDelegate mNavigationObserverDelegate =
new WebFragmentNavigationDelegate();
private FullscreenCallbackDelegate mFullscreenCallbackDelegate =
new FullscreenCallbackDelegate();
private FaviconFetcher mFaviconFetcher;
// Only use one callback for all the message event listeners. This is to avoid sending the same
// message over multiple times. The message can then be proxied to all valid listeners.
private IPostMessageCallback mMessageEventListenerCallback;
// The union of origins allowed by all the listeners. It may contain duplicates.
private ArrayList<String> mAllowedOriginsForPostMessage = new ArrayList<>();
TabProxy(Tab tab) {
mTabId = tab.getId();
mGuid = tab.getGuid();
tab.registerTabCallback(mTabObserverDelegate);
tab.setFullscreenCallback(mFullscreenCallbackDelegate);
mFaviconFetcher = tab.createFaviconFetcher(new FaviconCallback() {
@Override
public void onFaviconChanged(Bitmap favicon) {
mTabObserverDelegate.notifyFaviconChanged(favicon);
}
});
}
void invalidate() {
mTabId = -1;
mGuid = null;
mTabObserverDelegate = null;
mNavigationObserverDelegate = null;
mFaviconFetcher.destroy();
mFaviconFetcher = null;
}
boolean isValid() {
return mGuid != null;
}
private Tab getTab() {
Tab tab = Tab.getTabById(mTabId);
if (tab == null) {
// TODO(swestphal): Raise exception.
}
return tab;
}
@Override
public void setActive() {
mHandler.post(() -> {
Tab tab = getTab();
tab.getBrowser().setActiveTab(tab);
});
}
@Override
public void close() {
mHandler.post(() -> {
getTab().dispatchBeforeUnloadAndClose();
invalidate();
});
}
@Override
public void executeScript(String script, boolean useSeparateIsolate, IStringCallback callback) {
mHandler.post(() -> {
try {
getTab().executeScript(script, useSeparateIsolate,
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 (RuntimeException e) {
try {
callback.onException(ExceptionType.UNKNOWN, e.getMessage());
} catch (RemoteException re) {
}
}
});
}
@Override
public void setTabObserverDelegate(ITabObserverDelegate tabObserverDelegate) {
mTabObserverDelegate.setObserver(tabObserverDelegate);
}
@Override
public void postMessage(String message, String targetOrigin) {
mHandler.post(() -> { getTab().postMessage(message, targetOrigin); });
}
@Override
public void createMessageEventListener(
IPostMessageCallback callback, List<String> allowedOrigins) {
assert mMessageEventListenerCallback == null;
mMessageEventListenerCallback = callback;
mAllowedOriginsForPostMessage.addAll(allowedOrigins);
}
@Override
public void addMessageEventListener(List<String> allowedOrigins) {
mAllowedOriginsForPostMessage.addAll(allowedOrigins);
}
@Override
public void removeMessageEventListener(List<String> allowedOrigins) {
for (String origin : allowedOrigins) {
// Remove one instance of |origin|. Other listeners may have registered with the same
// |origin| and needs to be left in |mAllowedOriginsForPostMessage|.
boolean didRemove = mAllowedOriginsForPostMessage.remove(origin);
assert didRemove;
}
}
void onPostMessage(String message, String origin) {
if (mMessageEventListenerCallback == null) {
return;
}
if (!mAllowedOriginsForPostMessage.contains("*")
&& !mAllowedOriginsForPostMessage.contains(origin)) {
// No listener was attached to receive this message. Drop it.
return;
}
try {
mMessageEventListenerCallback.onPostMessage(message, origin);
} catch (RemoteException e) {
}
}
@Override
public void setFullscreenCallbackDelegate(
IFullscreenCallbackDelegate fullscreenCallbackDelegate) {
mFullscreenCallbackDelegate.setDelegate(fullscreenCallbackDelegate);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/TabProxy.java | Java | unknown | 6,395 |
// 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.Looper;
import android.util.AndroidRuntimeException;
/* package */ class ThreadCheck {
/* package */ 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/weblayer/ThreadCheck.java | Java | unknown | 510 |
// 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;
/**
* Error thrown if client and implementation versions are not compatible.
*/
class UnsupportedVersionException extends RuntimeException {
/**
* Constructs a new exception with the specified version.
*/
public UnsupportedVersionException(String implementationVersion) {
super("Unsupported WebLayer version, client version "
+ WebLayerClientVersionConstants.PRODUCT_VERSION
+ " is not supported by implementation version " + implementationVersion);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/UnsupportedVersionException.java | Java | unknown | 694 |
// 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.webkit.ValueCallback;
import androidx.annotation.NonNull;
/**
* Used to provide details about the current user's identity.
*
* If this callback is implemented and set on {@link Profile}, the information is used to better
* organize contact details in the navigator.contacts UI as well as by Autofill Assistant.
*/
abstract class UserIdentityCallback {
/**
* The current user's email address. If no user is signed in or the email is currently
* unavailable, this should return an empty string.
*/
public @NonNull String getEmail() {
return new String();
}
/**
* Returns the full name of the current user, or empty if the user is signed out. This can
* be provided on a best effort basis if the name is not available immediately.
*/
public @NonNull String getFullName() {
return new String();
}
/**
* Called to retrieve the signed-in user's avatar.
* @param desiredSize the size the avatar will be displayed at, in raw pixels. If a different
* size avatar is returned, WebLayer will scale the returned image.
* @param avatarLoadedCallback to be called with the avatar when it is available (synchronously
* or asynchronously). Until such time that it's called, WebLayer will fall back to a
* monogram based on {@link getFullName()}, e.g. encircled "JD" for "Jill Doe". This
* will no-op if the associated {@link Profile} object is destroyed before this is
* called.
*/
public void getAvatar(int desiredSize, @NonNull ValueCallback<Bitmap> avatarLoadedCallback) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/UserIdentityCallback.java | Java | unknown | 1,858 |
// 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 java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The annotated method or class verifies on O, but not below.
*
* The annotated method (or methods on the annotated class) are guaranteed to not be inlined by R8
* on builds targeted below O. This prevents class verification errors (which results in a very slow
* retry-verification-at-runtime) from spreading into other classes on these lower versions.
*
* Note: this is the WebLayer client library version of the annotation from
* org.chromium.base.annotations.
*/
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
/* package */ @interface VerifiesOnO {}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/VerifiesOnO.java | Java | unknown | 965 |
// 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 java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The annotated method or class verifies on R, but not below.
*
* The annotated method (or methods on the annotated class) are guaranteed to not be inlined by R8
* on builds targeted below R. This prevents class verification errors (which results in a very slow
* retry-verification-at-runtime) from spreading into other classes on these lower versions.
*
* Note: this is the WebLayer client library version of the annotation from
* org.chromium.base.annotations.
*/
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
/* package */ @interface VerifiesOnR {}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/VerifiesOnR.java | Java | unknown | 965 |
// 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.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import org.chromium.webengine.interfaces.IBooleanCallback;
import org.chromium.webengine.interfaces.IWebEngineDelegate;
import org.chromium.webengine.interfaces.IWebEngineDelegateClient;
import org.chromium.webengine.interfaces.IWebEngineParams;
import org.chromium.weblayer_private.interfaces.BrowserFragmentArgs;
import java.util.ArrayList;
/**
* Class to delegate between a webengine.WebEngine and its weblayer.Browser counter part.
*/
class WebEngineDelegate extends IWebEngineDelegate.Stub {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private Browser mBrowser;
WebEngineDelegate(Browser browser) {
mBrowser = browser;
}
static void create(Context context, WebLayer webLayer, IWebEngineParams params,
IWebEngineDelegateClient client) {
new Handler(Looper.getMainLooper()).post(() -> {
Browser browser = new Browser(webLayer.createBrowser(context, bundleParams(params)));
WebFragmentEventsDelegate fragmentEventsDelegate =
new WebFragmentEventsDelegate(context, browser.connectFragment());
CookieManagerDelegate cookieManagerDelegate =
new CookieManagerDelegate(browser.getProfile().getCookieManager());
TabManagerDelegate tabManagerDelegate = new TabManagerDelegate(browser);
WebEngineDelegate webEngineDelegate = new WebEngineDelegate(browser);
browser.registerTabInitializationCallback(new TabInitializationCallback() {
@Override
public void onTabInitializationCompleted() {
new Handler(Looper.getMainLooper()).post(() -> {
try {
client.onDelegatesReady(webEngineDelegate, fragmentEventsDelegate,
tabManagerDelegate, cookieManagerDelegate);
} catch (RemoteException e) {
throw new RuntimeException("Failed to initialize WebEngineDelegate", e);
}
});
}
});
browser.initializeState();
});
}
private static Bundle bundleParams(IWebEngineParams params) {
String profileName = Profile.sanitizeProfileName(params.profileName);
boolean isIncognito = params.isIncognito || "".equals(profileName);
boolean isExternalIntentsEnabled = params.isExternalIntentsEnabled;
// Support for named incognito profiles was added in 87. Checking is done in
// WebFragment, as this code should not trigger loading WebLayer.
Bundle args = new Bundle();
args.putString(BrowserFragmentArgs.PROFILE_NAME, profileName);
if (params.persistenceId != null) {
args.putString(BrowserFragmentArgs.PERSISTENCE_ID, params.persistenceId);
}
if (params.allowedOrigins != null) {
args.putStringArrayList(
BrowserFragmentArgs.ALLOWED_ORIGINS, (ArrayList<String>) params.allowedOrigins);
}
args.putBoolean(BrowserFragmentArgs.IS_INCOGNITO, isIncognito);
args.putBoolean(BrowserFragmentArgs.IS_EXTERNAL_INTENTS_ENABLED, isExternalIntentsEnabled);
args.putBoolean(BrowserFragmentArgs.USE_VIEW_MODEL, false);
return args;
}
@Override
public void tryNavigateBack(IBooleanCallback callback) {
mHandler.post(() -> {
mBrowser.tryNavigateBack(didNavigate -> {
try {
callback.onResult(didNavigate);
} catch (RemoteException e) {
}
});
});
}
@Override
public void shutdown() {
mHandler.post(() -> {
// This is for the weblayer.Browser / weblayer_private.BrowserImpl which has a lifetime
// that exceeds the Fragment, onDestroy only destroys the Fragment UI.
// TODO(swestphal): Check order.
mBrowser.prepareForDestroy();
mBrowser.shutdown();
mBrowser.onDestroyed();
mBrowser = null;
});
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebEngineDelegate.java | Java | unknown | 4,462 |
// 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 androidx.annotation.Nullable;
class WebFragmentCreateParams {
private boolean mIncognito;
@Nullable
private String mProfileName;
@Nullable
private String mPersistenceId;
private boolean mUseViewModel;
/**
* A Builder class to help create WebFragmentCreateParams.
*/
public static final class Builder {
@NonNull
private WebFragmentCreateParams mParams;
/**
* Constructs a new Builder.
*/
public Builder() {
mParams = new WebFragmentCreateParams();
}
/**
* Builds the WebFragmentCreateParams.
*/
@NonNull
public WebFragmentCreateParams build() {
return mParams;
}
/**
* Sets whether the profile is incognito.
*
* Support for incognito fragments with a non-null and non-empty profile name was added
* in 88. Attempting to use a fragment with a non-null and non-empty profile name earlier
* than 88 will result in an exception.
*
* @param incognito Whether the profile should be incognito.
*/
@NonNull
public Builder setIsIncognito(boolean incognito) {
mParams.mIncognito = incognito;
return this;
}
/**
*
* 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 The name of the profile.
*/
@NonNull
public Builder setProfileName(@Nullable String name) {
mParams.mProfileName = name;
return this;
}
/**
* Sets the persistence id, which uniquely identifies the Browser 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 Browser initially has no tabs (until restore is complete).
*
* @param id The id for persistence.
*/
@NonNull
public Builder setPersistenceId(@Nullable String id) {
mParams.mPersistenceId = id;
return this;
}
/**
* Sets whether the Browser should be stored in a ViewModel owned by the Fragment. A value
* of true results in the Browser not being recreated during configuration changes. This is
* a replacement for {@code Fragment#setRetainInstance()}.
*
* @param useViewModel Whether a ViewModel should be used.
*/
@NonNull
public Builder setUseViewModel(boolean useViewModel) {
mParams.mUseViewModel = useViewModel;
return this;
}
}
/**
* Returns whether the Browser is incognito.
*
* @return True if the profile is incognito.
*/
public boolean isIncognito() {
return mIncognito;
}
/**
* Returns the name of a profile. Null or empty is implicitly mapped to incognito.
*
* @return The profile name.
*/
@Nullable
public String getProfileName() {
return mProfileName;
}
/**
* Returns the persisted id for the browser.
*
* @return The persistence id.
*/
@Nullable
public String getPersistenceId() {
return mPersistenceId;
}
/**
* Whether ViewModel should be used.
*/
public boolean getUseViewModel() {
return mUseViewModel;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebFragmentCreateParams.java | Java | unknown | 3,936 |
// 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 org.chromium.weblayer_private.interfaces.IRemoteFragment;
/**
* Class to handle events forwarded by WebFragmentEventDelegate.
*/
final class WebFragmentEventHandler extends RemoteFragmentEventHandler {
public WebFragmentEventHandler(IRemoteFragment remoteFragment) {
super(remoteFragment);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebFragmentEventHandler.java | Java | unknown | 496 |
// 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.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.view.SurfaceControlViewHost;
import android.view.WindowManager;
import androidx.fragment.app.Fragment;
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.IRemoteFragment;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* This class proxies Fragment Lifecycle events from the WebFragment to
* the WebLayer implementation.
*/
class WebFragmentEventsDelegate extends IWebFragmentEventsDelegate.Stub {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private Context mContext;
private WebFragmentEventHandler mEventHandler;
private WebFragmentTabListDelegate mTabListDelegate;
private IWebFragmentEventsDelegateClient mClient;
private SurfaceControlViewHost mSurfaceControlViewHost;
WebFragmentEventsDelegate(Context context, IRemoteFragment remoteFragment) {
ThreadCheck.ensureOnUiThread();
mContext = context;
mEventHandler = new WebFragmentEventHandler(remoteFragment);
}
@Override
public void setClient(IWebFragmentEventsDelegateClient client) {
mClient = client;
}
@Override
public void attachViewHierarchy(IBinder hostToken) {
mHandler.post(() -> attachViewHierarchyOnUi(hostToken));
}
private void attachViewHierarchyOnUi(IBinder hostToken) {
WindowManager window = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
assert mSurfaceControlViewHost == null;
mSurfaceControlViewHost =
new SurfaceControlViewHost(mContext, window.getDefaultDisplay(), hostToken);
mEventHandler.setSurfaceControlViewHost(mSurfaceControlViewHost);
try {
mClient.onSurfacePackageReady(mSurfaceControlViewHost.getSurfacePackage());
} catch (RemoteException e) {
}
}
@Override
public void retrieveContentViewRenderView() {
mHandler.post(() -> {
try {
mClient.onContentViewRenderViewReady(
ObjectWrapper.wrap(mEventHandler.getContentViewRenderView()));
} catch (RemoteException e) {
}
});
}
@Override
public void resizeView(int width, int height) {
mHandler.post(() -> {
if (mSurfaceControlViewHost != null) {
mSurfaceControlViewHost.relayout(width, height);
}
});
}
@Override
public void onAttach() {
mHandler.post(() -> mEventHandler.onAttach(mContext, null));
}
@Override
public void onAttachWithContext(IObjectWrapper context, IObjectWrapper fragment) {
mHandler.post(() -> mEventHandler.onAttach(ObjectWrapper.unwrap(context, Context.class),
ObjectWrapper.unwrap(fragment, Fragment.class)));
}
@Override
public void onCreate() {
mHandler.post(() -> { mEventHandler.onCreate(); });
}
@Override
public void onDestroy() {
mHandler.post(() -> mEventHandler.onDestroy());
}
@Override
public void onDetach() {
mHandler.post(() -> {
mEventHandler.onDetach();
if (mSurfaceControlViewHost != null) {
mSurfaceControlViewHost.release();
mSurfaceControlViewHost = null;
}
});
}
@Override
public void onStart() {
mHandler.post(() -> { mEventHandler.onStart(); });
}
@Override
public void onStop() {
mHandler.post(() -> mEventHandler.onStop());
}
@Override
public void onResume() {
mHandler.post(() -> mEventHandler.onResume());
}
@Override
public void onPause() {
mHandler.post(() -> mEventHandler.onPause());
}
@Override
public void onActivityResult(int requestCode, int resultCode, IObjectWrapper intent) {
mHandler.post(() -> mEventHandler.onActivityResult(requestCode, resultCode,
ObjectWrapper.unwrap(intent, Intent.class)));
}
/**
* Set the minimum surface size of this BrowserFragment instance.
* Setting this avoids expensive surface resize for a fragment view resize that is within the
* minimum size. The trade off is the additional memory and power needed for the larger
* surface. For example, for a browser use case, it's likely worthwhile to set the minimum
* surface size to the screen size to avoid surface resize when entering and exiting fullscreen.
* It is safe to call this before Views are initialized.
* Note Android does have a max size limit on Surfaces which applies here as well; this
* generally should not be larger than the device screen size.
* Note the surface size is increased to the layout size only if both the width and height are
* no larger than the minimum surface size. No adjustment is made if the surface size is larger
* than the minimum size in one dimension and smaller in the other dimension.
*/
@Override
public void setMinimumSurfaceSize(int width, int height) {
mHandler.post(() -> mEventHandler.setMinimumSurfaceSize(width, height));
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebFragmentEventsDelegate.java | Java | unknown | 5,699 |
// 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.os.RemoteException;
import androidx.annotation.NonNull;
import org.chromium.webengine.interfaces.INavigationObserverDelegate;
/**
* This class acts as a proxy between the Tab navigation events happening in
* weblayer and the NavigationObserverDelegate in webengine.
*/
class WebFragmentNavigationDelegate extends NavigationCallback {
private INavigationObserverDelegate mNavigationObserver;
void setObserver(INavigationObserverDelegate observer) {
mNavigationObserver = observer;
}
@Override
public void onNavigationStarted(@NonNull Navigation navigation) {
maybeRunOnNavigationObserver(observer -> {
observer.notifyNavigationStarted(WebFragmentNavigationParams.create(navigation));
});
}
@Override
public void onNavigationRedirected(@NonNull Navigation navigation) {
maybeRunOnNavigationObserver(observer -> {
observer.notifyNavigationRedirected(WebFragmentNavigationParams.create(navigation));
});
}
@Override
public void onNavigationCompleted(@NonNull Navigation navigation) {
maybeRunOnNavigationObserver(observer -> {
observer.notifyNavigationCompleted(WebFragmentNavigationParams.create(navigation));
});
}
@Override
public void onNavigationFailed(@NonNull Navigation navigation) {
maybeRunOnNavigationObserver(observer -> {
observer.notifyNavigationFailed(WebFragmentNavigationParams.create(navigation));
});
}
@Override
public void onLoadProgressChanged(double progress) {
maybeRunOnNavigationObserver(observer -> observer.notifyLoadProgressChanged(progress));
}
private interface OnNavigationObserverCallback {
void run(INavigationObserverDelegate navigationObserver) throws RemoteException;
}
private void maybeRunOnNavigationObserver(OnNavigationObserverCallback callback) {
if (mNavigationObserver != null) {
try {
callback.run(mNavigationObserver);
} catch (RemoteException e) {
}
}
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebFragmentNavigationDelegate.java | Java | unknown | 2,296 |
// 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.webengine.interfaces.INavigationParams;
/**
* This class is a helper class to create {@link INavigationParams}-parcelable.
*/
class WebFragmentNavigationParams {
private WebFragmentNavigationParams() {}
public static INavigationParams create(Navigation navigation) {
INavigationParams params = new INavigationParams();
params.uri = navigation.getUri();
params.statusCode = navigation.getHttpStatusCode();
params.isSameDocument = navigation.isSameDocument();
return params;
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebFragmentNavigationParams.java | Java | unknown | 728 |
// 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.graphics.Bitmap;
import android.net.Uri;
import android.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.webengine.interfaces.ITabObserverDelegate;
/**
* This class acts as a proxy between the Tab events happening in
* weblayer and the TabObserverDelegate in webengine.
*/
class WebFragmentTabDelegate extends TabCallback {
private ITabObserverDelegate mTabObserver;
void setObserver(ITabObserverDelegate observer) {
mTabObserver = observer;
}
@Override
public void onVisibleUriChanged(@NonNull Uri uri) {
maybeRunOnTabObserver(observer -> { observer.notifyVisibleUriChanged(uri.toString()); });
}
@Override
public void onRenderProcessGone() {
maybeRunOnTabObserver(observer -> { observer.notifyRenderProcessGone(); });
}
@Override
public void onTitleUpdated(@NonNull String title) {
maybeRunOnTabObserver(observer -> { observer.notifyTitleUpdated(title); });
}
void notifyFaviconChanged(@Nullable Bitmap favicon) {
maybeRunOnTabObserver(observer -> { observer.notifyFaviconChanged(favicon); });
}
private interface OnTabObserverCallback {
void run(ITabObserverDelegate tabObserver) throws RemoteException;
}
private void maybeRunOnTabObserver(OnTabObserverCallback callback) {
if (mTabObserver != null) {
try {
callback.run(mTabObserver);
} catch (RemoteException e) {
}
}
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebFragmentTabDelegate.java | Java | unknown | 1,733 |
// 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.os.RemoteException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.webengine.interfaces.ITabListObserverDelegate;
import org.chromium.webengine.interfaces.ITabParams;
import java.util.Set;
/**
* This class acts as a proxy between the TabList events happening in
* weblayer and the TabListObserverDelegate in webengine.
*/
class WebFragmentTabListDelegate extends TabListCallback {
private ITabListObserverDelegate mTabListObserver;
private final NewTabCallback mNewTabCallback = new NewTabCallback() {
@Override
public void onNewTab(@NonNull Tab tab, @NewTabType int type) {
// Set foreground tabs and tabs in new windows by default to active.
switch (type) {
case NewTabType.FOREGROUND_TAB:
case NewTabType.NEW_WINDOW:
tab.getBrowser().setActiveTab(tab);
break;
}
}
};
void setObserver(ITabListObserverDelegate observer) {
mTabListObserver = observer;
}
void notifyInitialTabs(Set<Tab> allTabs, Tab activeTab) {
for (Tab tab : allTabs) {
onTabAdded(tab);
}
onActiveTabChanged(activeTab);
onFinishedTabInitialization();
}
@Override
public void onActiveTabChanged(@Nullable Tab tab) {
maybeRunOnTabListObserver(observer -> {
ITabParams tabParams = null;
if (tab != null) {
tabParams = TabParams.buildParcelable(tab);
}
observer.notifyActiveTabChanged(tabParams);
});
}
@Override
public void onTabAdded(@NonNull Tab tab) {
// This is a requirement to open new tabs.
tab.setNewTabCallback(mNewTabCallback);
maybeRunOnTabListObserver(observer -> {
ITabParams tabParams = TabParams.buildParcelable(tab);
observer.notifyTabAdded(tabParams);
});
}
@Override
public void onTabRemoved(@NonNull Tab tab) {
maybeRunOnTabListObserver(observer -> {
ITabParams tabParams = TabParams.buildParcelable(tab);
observer.notifyTabRemoved(tabParams);
});
}
@Override
public void onWillDestroyBrowserAndAllTabs() {
maybeRunOnTabListObserver(observer -> observer.notifyWillDestroyBrowserAndAllTabs());
}
public void onFinishedTabInitialization() {
maybeRunOnTabListObserver(observer -> { observer.onFinishedTabInitialization(); });
}
private interface OnTabListObserverCallback {
void run(ITabListObserverDelegate tabObserver) throws RemoteException;
}
private void maybeRunOnTabListObserver(OnTabListObserverCallback callback) {
if (mTabListObserver != null) {
try {
callback.run(mTabListObserver);
} catch (RemoteException e) {
}
}
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebFragmentTabListDelegate.java | Java | unknown | 3,120 |
// 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.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.StrictMode;
import android.os.SystemClock;
import android.util.AndroidRuntimeException;
import android.util.Log;
import android.webkit.ValueCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IBrowser;
import org.chromium.weblayer_private.interfaces.IProfile;
import org.chromium.weblayer_private.interfaces.IWebLayer;
import org.chromium.weblayer_private.interfaces.IWebLayerClient;
import org.chromium.weblayer_private.interfaces.IWebLayerFactory;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import org.chromium.weblayer_private.interfaces.WebLayerVersionConstants;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* WebLayer is responsible for initializing state necessary to use any of the classes in web layer.
*/
@VisibleForTesting
public class WebLayer {
private static final String TAG = "WebLayer";
// This metadata key, if defined, overrides the default behaviour of loading WebLayer from the
// current WebView implementation. This is only intended for testing, and does not enforce any
// signature requirements on the implementation, nor does it use the production code path to
// load the code. Do not set this in production APKs!
private static final String PACKAGE_MANIFEST_KEY = "org.chromium.weblayer.WebLayerPackage";
@SuppressWarnings("StaticFieldLeak")
@Nullable
private static Context sRemoteContext;
@Nullable
private static ClassLoader sRemoteClassLoader;
@Nullable
private static Context sAppContext;
@Nullable
private static WebLayerLoader sLoader;
private static boolean sDisableWebViewCompatibilityMode;
@NonNull
private final IWebLayer mImpl;
// Times used for logging UMA histograms.
private static long sClassLoaderCreationTime;
private static long sContextCreationTime;
private static long sWebLayerLoaderCreationTime;
/**
* Returns true if WebLayer is available. This tries to load WebLayer, but does no
* initialization. This function may be called by code that uses WebView.
* <p>
* NOTE: it's possible for this to return true, yet loading to still fail. This happens if there
* is an error during loading.
*
* @return true Returns true if WebLayer is available.
*/
static boolean isAvailable(Context context) {
ThreadCheck.ensureOnUiThread();
return getWebLayerLoader(context).isAvailable();
}
private static void checkAvailable(Context context) {
if (!isAvailable(context)) {
throw new UnsupportedVersionException(sLoader.getVersion());
}
}
/**
* Asynchronously creates and initializes WebLayer. Calling this more than once returns the same
* object. Both this method and {@link #loadSync} yield the same instance of {@link WebLayer}.
* <p>
* {@link callback} is supplied null if unable to load WebLayer. In general, the only time null
* is supplied is if there is an unexpected error.
*
* @param appContext The hosting application's Context.
* @param callback {@link Callback} which will receive the WebLayer instance.
* @throws UnsupportedVersionException If {@link #isAvailable} returns false. See
* {@link #isAvailable} for details.
*/
static void loadAsync(@NonNull Context appContext, @NonNull Callback<WebLayer> callback)
throws UnsupportedVersionException {
ThreadCheck.ensureOnUiThread();
checkAvailable(appContext);
getWebLayerLoader(appContext).loadAsync(callback);
}
/**
* Synchronously creates and initializes WebLayer.
* Both this method and {@link #loadAsync} yield the same instance of {@link WebLayer}.
* It is safe to call this method after {@link #loadAsync} to block until the ongoing load
* finishes (or immediately return its result if already finished).
* <p>
* This returns null if unable to load WebLayer. In general, the only time null
* is returns is if there is an unexpected error loading.
*
* @param appContext The hosting application's Context.
* @return a {@link WebLayer} instance, or null if unable to load WebLayer.
*
* @throws UnsupportedVersionException If {@link #isAvailable} returns false. See
* {@link #isAvailable} for details.
*/
@Nullable
static WebLayer loadSync(@NonNull Context appContext) throws UnsupportedVersionException {
ThreadCheck.ensureOnUiThread();
checkAvailable(appContext);
return getWebLayerLoader(appContext).loadSync();
}
private static WebLayerLoader getWebLayerLoader(Context context) {
if (sLoader == null) sLoader = new WebLayerLoader(context);
return sLoader;
}
/** Returns whether WebLayer loading has at least started. */
static boolean hasWebLayerInitializationStarted() {
return sLoader != null;
}
IWebLayer getImpl() {
return mImpl;
}
static WebLayer getLoadedWebLayer(@NonNull Context appContext)
throws UnsupportedVersionException {
ThreadCheck.ensureOnUiThread();
checkAvailable(appContext);
return getWebLayerLoader(appContext).getLoadedWebLayer();
}
/**
* Returns the supported version. Using any functions defined in a newer version than
* returned by {@link getSupportedMajorVersion} result in throwing an
* UnsupportedOperationException.
* <p> For example, consider the function {@link setBottomBar}, and further assume
* {@link setBottomBar} was added in version 11. If {@link getSupportedMajorVersion}
* returns 10, then calling {@link setBottomBar} returns in an UnsupportedOperationException.
* OTOH, if {@link getSupportedMajorVersion} returns 12, then {@link setBottomBar} works as
* expected
*
* @return the supported version, or -1 if WebLayer is not available.
*/
static int getSupportedMajorVersion(@NonNull Context context) {
ThreadCheck.ensureOnUiThread();
return getWebLayerLoader(context).getMajorVersion();
}
// Returns true if version checks should be done. This is provided solely for testing, and
// specifically testing that does not run on device and load the implementation. It is only
// necessary to check this in code paths that don't require WebLayer to load the implementation
// and need to be callable in tests.
static boolean shouldPerformVersionChecks() {
return !"robolectric".equals(Build.FINGERPRINT);
}
// Internal version of getSupportedMajorVersion(). This should only be used when you know
// WebLayer has been initialized. Generally that means calling this from any non-static method.
static int getSupportedMajorVersionInternal() {
if (sLoader == null) {
throw new IllegalStateException(
"This should only be called once WebLayer is initialized");
}
return sLoader.getMajorVersion();
}
// Internal getter for the app Context. This should only be used when you know WebLayer has
// been initialized.
static Context getAppContext() {
return sAppContext;
}
/**
* Returns the Chrome version of the WebLayer implementation. This will return a full version
* string such as "79.0.3945.0", while {@link getSupportedMajorVersion} will only return the
* major version integer (79 in the example).
*/
@NonNull
static String getSupportedFullVersion(@NonNull Context context) {
ThreadCheck.ensureOnUiThread();
return getWebLayerLoader(context).getVersion();
}
/**
* Returns the Chrome version this client was built at. This will return a full version string
* such as "79.0.3945.0".
*/
@NonNull
static String getVersion() {
ThreadCheck.ensureOnUiThread();
return WebLayerClientVersionConstants.PRODUCT_VERSION;
}
@NonNull
static String getProviderPackageName(@NonNull Context context) {
ThreadCheck.ensureOnUiThread();
return getWebLayerLoader(context).getProviderPackageName();
}
/**
* Encapsulates the state of WebLayer loading and initialization.
*/
private static final class WebLayerLoader {
@NonNull
private final List<Callback<WebLayer>> mCallbacks = new ArrayList<>();
@Nullable
private IWebLayerFactory mFactory;
@Nullable
private IWebLayer mIWebLayer;
@Nullable
private WebLayer mWebLayer;
// True if WebLayer is available and compatible with this client.
private final boolean mAvailable;
private final int mMajorVersion;
private final String mVersion;
private boolean mIsLoadingAsync;
private Context mContext;
/**
* Creates WebLayerLoader. This does a minimal amount of loading
*/
public WebLayerLoader(@NonNull Context context) {
boolean available = false;
int majorVersion = -1;
String version = "<unavailable>";
// Use the application context as the supplied context may have a shorter lifetime.
mContext = context.getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
&& ApiHelperForR.getAttributionTag(context) != null) {
// Getting the application context means we lose any attribution. Use the
// attribution tag from the supplied context so that embedders have a way to set an
// attribution tag.
mContext = ApiHelperForR.createAttributionContext(
mContext, ApiHelperForR.getAttributionTag(context));
}
try {
Class factoryClass = loadRemoteClass(
mContext, "org.chromium.weblayer_private.WebLayerFactoryImpl");
long start = SystemClock.elapsedRealtime();
mFactory = IWebLayerFactory.Stub.asInterface(
(IBinder) factoryClass
.getMethod("create", String.class, int.class, int.class)
.invoke(null, WebLayerClientVersionConstants.PRODUCT_VERSION,
WebLayerClientVersionConstants.PRODUCT_MAJOR_VERSION, -1));
sWebLayerLoaderCreationTime = SystemClock.elapsedRealtime() - start;
available = mFactory.isClientSupported();
majorVersion = mFactory.getImplementationMajorVersion();
version = mFactory.getImplementationVersion();
if (available) {
available = majorVersion >= WebLayerVersionConstants.MIN_VERSION;
}
// See comment in WebLayerFactoryImpl.isClientSupported() for details on this.
if (available
&& WebLayerClientVersionConstants.PRODUCT_MAJOR_VERSION > majorVersion) {
available = WebLayerClientVersionConstants.PRODUCT_MAJOR_VERSION - majorVersion
<= WebLayerVersionConstants.MAX_SKEW;
}
} catch (Exception e) {
Log.e(TAG, "Unable to create WebLayerFactory", e);
}
mAvailable = available;
mMajorVersion = majorVersion;
mVersion = version;
}
public String getProviderPackageName() {
try {
return getOrCreateRemoteContext(mContext).getPackageName();
} catch (Exception e) {
throw new APICallException(e);
}
}
public boolean isAvailable() {
return mAvailable;
}
public int getMajorVersion() {
return mMajorVersion;
}
public String getVersion() {
return mVersion;
}
public void loadAsync(@NonNull Callback<WebLayer> callback) {
if (mWebLayer != null) {
callback.onResult(mWebLayer);
return;
}
mCallbacks.add(callback);
if (mIsLoadingAsync) {
return; // Already loading.
}
mIsLoadingAsync = true;
if (getIWebLayer() == null) {
// Unable to create WebLayer. This generally shouldn't happen.
onWebLayerReady();
return;
}
try {
getIWebLayer().loadAsync(ObjectWrapper.wrap(mContext),
ObjectWrapper.wrap(getOrCreateRemoteContext(mContext)),
ObjectWrapper.wrap(
(ValueCallback<Boolean>) result -> { onWebLayerReady(); }));
} catch (Exception e) {
throw new APICallException(e);
}
}
public WebLayer loadSync() {
if (mWebLayer != null) {
return mWebLayer;
}
if (getIWebLayer() == null) {
// Error in creating WebLayer. This generally shouldn't happen.
onWebLayerReady();
return null;
}
try {
getIWebLayer().loadSync(ObjectWrapper.wrap(mContext),
ObjectWrapper.wrap(getOrCreateRemoteContext(mContext)));
onWebLayerReady();
return mWebLayer;
} catch (Exception e) {
throw new APICallException(e);
}
}
WebLayer getLoadedWebLayer() {
return mWebLayer;
}
@Nullable
private IWebLayer getIWebLayer() {
if (mIWebLayer != null) return mIWebLayer;
if (!mAvailable) return null;
try {
mIWebLayer = mFactory.createWebLayer();
} catch (RemoteException e) {
// If |mAvailable| returns true, then create() should always succeed.
throw new AndroidRuntimeException(e);
}
return mIWebLayer;
}
private void onWebLayerReady() {
if (mWebLayer != null) {
return;
}
if (mIWebLayer != null) mWebLayer = new WebLayer(mIWebLayer);
for (Callback<WebLayer> callback : mCallbacks) {
callback.onResult(mWebLayer);
}
mCallbacks.clear();
}
}
// Constructor for test mocking.
protected WebLayer() {
mImpl = null;
}
private WebLayer(IWebLayer iWebLayer) {
mImpl = iWebLayer;
try {
mImpl.setClient(new WebLayerClientImpl());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Get or create the profile for profileName.
* @param profileName Null to indicate in-memory profile. Otherwise, name cannot be empty
* and should contain only alphanumeric and underscore characters since it will be used as
* a directory name in the file system.
*/
@NonNull
public Profile getProfile(@Nullable String profileName) {
ThreadCheck.ensureOnUiThread();
IProfile iprofile;
try {
iprofile = mImpl.getProfile(Profile.sanitizeProfileName(profileName));
} catch (RemoteException e) {
throw new APICallException(e);
}
return Profile.of(iprofile);
}
/**
* Get or create the incognito profile with the name {@link profileName}.
*
* @param profileName The name of the profile. Null is mapped to an empty string.
*/
@NonNull
public Profile getIncognitoProfile(@Nullable String profileName) {
ThreadCheck.ensureOnUiThread();
IProfile iprofile;
try {
iprofile = mImpl.getIncognitoProfile(Profile.sanitizeProfileName(profileName));
} catch (RemoteException e) {
throw new APICallException(e);
}
return Profile.of(iprofile);
}
/**
* Return a list of Profile names currently on disk. This does not include incognito
* profiles. This will not include profiles that are being deleted from disk.
* WebLayer must be initialized before calling this.
*/
public void enumerateAllProfileNames(@NonNull Callback<String[]> callback) {
ThreadCheck.ensureOnUiThread();
try {
ValueCallback<String[]> valueCallback = (String[] value) -> callback.onResult(value);
mImpl.enumerateAllProfileNames(ObjectWrapper.wrap(valueCallback));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the user agent string used by WebLayer.
*
* @return The user-agent string.
*/
public String getUserAgentString() {
ThreadCheck.ensureOnUiThread();
try {
return mImpl.getUserAgentString();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* To enable or disable DevTools remote debugging.
*/
public void setRemoteDebuggingEnabled(boolean enabled) {
try {
mImpl.setRemoteDebuggingEnabled(enabled);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* @return Whether or not DevTools remote debugging is enabled.
*/
public boolean isRemoteDebuggingEnabled() {
try {
return mImpl.isRemoteDebuggingEnabled();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Provide WebLayer with a set of active external experiment IDs.
*
* These experiment IDs are to be incorporated into metrics collection performed by WebLayer
* to aid in interpretation of data and elimination of confounding factors.
*
* This method may be called multiple times to update experient IDs if they change.
*
* @param experimentIds An array of integer active experiment IDs relevant to WebLayer.
*/
public void registerExternalExperimentIDs(@NonNull int[] experimentIds) {
ThreadCheck.ensureOnUiThread();
try {
// First param no longer used. First param was not used in the backend as of 85, and
// always supplied as empty as of 89 client.
mImpl.registerExternalExperimentIDs("", experimentIds);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Returns the value of X-Client-Data header.
* @since 101
*/
public String getXClientDataHeader() {
ThreadCheck.ensureOnUiThread();
if (getSupportedMajorVersionInternal() < 101) {
throw new UnsupportedOperationException();
}
try {
return mImpl.getXClientDataHeader();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
IBrowser createBrowser(Context serviceContext, Bundle fragmentArgs) {
try {
return mImpl.createBrowser(
ObjectWrapper.wrap(serviceContext), ObjectWrapper.wrap(fragmentArgs));
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/* package */ static IWebLayer getIWebLayer(Context context) {
return getWebLayerLoader(context).getIWebLayer();
}
@VisibleForTesting
/* package */ static Context getApplicationContextForTesting(Context appContext) {
try {
return (Context) ObjectWrapper.unwrap(
getIWebLayer(appContext).getApplicationContext(), Context.class);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
/**
* Creates a ClassLoader for the remote (weblayer implementation) side.
*/
static Class<?> loadRemoteClass(Context appContext, String className)
throws PackageManager.NameNotFoundException, ReflectiveOperationException {
if (sRemoteClassLoader != null) {
return sRemoteClassLoader.loadClass(className);
}
long start = SystemClock.elapsedRealtime();
// Child processes do not need WebView compatibility since there is no chance
// WebView will run in the same process.
if (sDisableWebViewCompatibilityMode) {
Context context = getOrCreateRemoteContext(appContext);
// Android versions before O do not support isolated splits, so WebLayer will be loaded
// as a normal split which is already available from the base class loader.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Attempt to find the class in the base ClassLoader, if it doesn't exist then load
// the weblayer ClassLoader.
try {
Class.forName(className, false, context.getClassLoader());
} catch (ClassNotFoundException e) {
try {
// If the implementation APK does not support isolated splits, this will
// just return the original context.
context = ApiHelperForO.createContextForSplit(context, "weblayer");
} catch (PackageManager.NameNotFoundException e2) {
// WebLayer not in split, proceed with the base context.
}
}
}
sRemoteClassLoader = context.getClassLoader();
} else {
sRemoteClassLoader = WebViewCompatibilityHelper.initialize(appContext);
}
sClassLoaderCreationTime = SystemClock.elapsedRealtime() - start;
return sRemoteClassLoader.loadClass(className);
}
/**
* Creates a Context for the remote (weblayer implementation) side.
*/
static Context getOrCreateRemoteContext(Context appContext)
throws PackageManager.NameNotFoundException, ReflectiveOperationException {
if (sRemoteContext != null) {
return sRemoteContext;
}
long start = SystemClock.elapsedRealtime();
Class<?> webViewFactoryClass = Class.forName("android.webkit.WebViewFactory");
String implPackageName = getImplPackageName(appContext);
sAppContext = appContext;
if (implPackageName != null) {
sRemoteContext = createRemoteContextFromPackageName(appContext, implPackageName);
} else {
Method getContext =
webViewFactoryClass.getDeclaredMethod("getWebViewContextAndSetProvider");
getContext.setAccessible(true);
sRemoteContext = (Context) getContext.invoke(null);
}
sContextCreationTime = SystemClock.elapsedRealtime() - start;
return sRemoteContext;
}
/* package */ static void disableWebViewCompatibilityMode() {
sDisableWebViewCompatibilityMode = true;
}
/**
* Creates a Context for the remote (weblayer implementation) side
* using a specified package name as the implementation. This is only
* intended for testing, not production use.
*/
private static Context createRemoteContextFromPackageName(
Context appContext, String implPackageName)
throws PackageManager.NameNotFoundException, ReflectiveOperationException {
// Load the code for the target package.
Context remoteContext = appContext.createPackageContext(
implPackageName, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
// Get the package info for the target package.
PackageInfo implPackageInfo = appContext.getPackageManager().getPackageInfo(implPackageName,
PackageManager.GET_SHARED_LIBRARY_FILES | PackageManager.GET_META_DATA);
// Store this package info in WebViewFactory as if it had been loaded as WebView,
// because other parts of the implementation need to be able to fetch it from there.
Class<?> webViewFactory = Class.forName("android.webkit.WebViewFactory");
Field sPackageInfo = webViewFactory.getDeclaredField("sPackageInfo");
sPackageInfo.setAccessible(true);
sPackageInfo.set(null, implPackageInfo);
return remoteContext;
}
private static String getImplPackageName(Context appContext)
throws PackageManager.NameNotFoundException {
Bundle metaData = appContext.getPackageManager()
.getApplicationInfo(
appContext.getPackageName(), PackageManager.GET_META_DATA)
.metaData;
if (metaData != null) return metaData.getString(PACKAGE_MANIFEST_KEY);
return null;
}
private final class WebLayerClientImpl extends IWebLayerClient.Stub {
@Override
public Intent createIntent() {
StrictModeWorkaround.apply();
// Intent objects need to be created in the client library so they can refer to the
// broadcast receiver that will handle them. The broadcast receiver needs to be in the
// client library because it's referenced in the manifest.
return new Intent(WebLayer.getAppContext(), BroadcastReceiver.class);
}
@Override
public Intent createMediaSessionServiceIntent() {
StrictModeWorkaround.apply();
return new Intent(WebLayer.getAppContext(), MediaSessionService.class);
}
@Override
public Intent createImageDecoderServiceIntent() {
StrictModeWorkaround.apply();
return new Intent(WebLayer.getAppContext(), ImageDecoderService.class);
}
@Override
public int getMediaSessionNotificationId() {
StrictModeWorkaround.apply();
// The id is part of the public library to avoid conflicts.
return R.id.weblayer_media_session_notification;
}
@Override
public long getClassLoaderCreationTime() {
return sClassLoaderCreationTime;
}
@Override
public long getContextCreationTime() {
return sContextCreationTime;
}
@Override
public long getWebLayerLoaderCreationTime() {
return sWebLayerLoaderCreationTime;
}
@Override
public Intent createRemoteMediaServiceIntent() {
StrictModeWorkaround.apply();
return new Intent(WebLayer.getAppContext(), RemoteMediaService.class);
}
@Override
public int getPresentationApiNotificationId() {
StrictModeWorkaround.apply();
// The id is part of the public library to avoid conflicts.
return R.id.weblayer_presentation_api_notification;
}
@Override
public int getRemotePlaybackApiNotificationId() {
StrictModeWorkaround.apply();
// The id is part of the public library to avoid conflicts.
return R.id.weblayer_remote_playback_api_notification;
}
@Override
public int getMaxNavigationsPerTabForInstanceState() {
return Browser.getMaxNavigationsPerTabForInstanceState();
}
}
/** Utility class to use new APIs that were added in O (API level 26). */
@VerifiesOnO
@RequiresApi(Build.VERSION_CODES.O)
/* package */ static final class ApiHelperForO {
/** See {@link Context.createContextForSplit(String) }. */
public static Context createContextForSplit(Context context, String name)
throws PackageManager.NameNotFoundException {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
return context.createContextForSplit(name);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
/** See {@link ApplicationInfo#splitNames}. */
public static String[] getSplitNames(ApplicationInfo info) {
return info.splitNames;
}
}
@VerifiesOnR
@RequiresApi(Build.VERSION_CODES.R)
private static final class ApiHelperForR {
/** See {@link Context.getAttributionTag() }. */
public static String getAttributionTag(Context context) {
return context.getAttributionTag();
}
/** See {@link Context.createAttributionContext(String) }. */
public static Context createAttributionContext(Context context, String tag) {
return context.createAttributionContext(tag);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebLayer.java | Java | unknown | 29,573 |
// 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.core.content.FileProvider;
/**
* Subclass of FileProvider which prevents conflicts with the embedding application manifest.
*/
public class WebLayerFileProvider extends FileProvider {}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebLayerFileProvider.java | Java | unknown | 380 |
// 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 when sending and receiving messages to a page.
*/
class WebMessage {
private final String mContents;
/**
* Creates a message with the specified contents.
*
* @param message Contents of the message.
*/
public WebMessage(@NonNull String message) {
mContents = message;
}
/**
* Returns the contents of the message.
*
* @return The contents of the message.
*/
public @NonNull String getContents() {
return mContents;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebMessage.java | Java | unknown | 729 |
// 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.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import dalvik.system.BaseDexClassLoader;
import dalvik.system.PathClassLoader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/** Helper class which performs initialization needed for WebView compatibility. */
final class WebViewCompatibilityHelper {
/** Creates a the ClassLoader to use for WebView compatibility. */
static ClassLoader initialize(Context appContext)
throws PackageManager.NameNotFoundException, ReflectiveOperationException {
Context remoteContext = WebLayer.getOrCreateRemoteContext(appContext);
PackageInfo info =
appContext.getPackageManager().getPackageInfo(remoteContext.getPackageName(),
PackageManager.GET_SHARED_LIBRARY_FILES
| PackageManager.MATCH_UNINSTALLED_PACKAGES);
String[] libraryPaths = getLibraryPaths(remoteContext.getClassLoader());
// Prepend "/." to all library paths. This changes the library path while still pointing to
// the same directory, allowing us to get around a check in the JVM. This is only necessary
// for N+, where we rely on linker namespaces.
for (int i = 0; i < libraryPaths.length; i++) {
assert libraryPaths[i].startsWith("/");
libraryPaths[i] = "/." + libraryPaths[i];
}
String dexPath = getAllApkPaths(info.applicationInfo);
String librarySearchPath = TextUtils.join(File.pathSeparator, libraryPaths);
// TODO(cduvall): PathClassLoader may call stat on the library paths, consider moving
// this to a background thread.
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
// Use the system class loader's parent here, since it is much more efficient. This
// matches what Android does when constructing class loaders, see
// android.app.ApplicationLoaders.
return new PathClassLoader(
dexPath, librarySearchPath, ClassLoader.getSystemClassLoader().getParent());
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
/** Returns the library paths the given class loader will search. */
static String[] getLibraryPaths(ClassLoader classLoader) throws ReflectiveOperationException {
// This seems to be the best way to reliably get both the native lib directory and the path
// within the APK where libs might be stored.
return ((String) BaseDexClassLoader.class.getDeclaredMethod("getLdLibraryPath")
.invoke((BaseDexClassLoader) classLoader))
.split(":");
}
/** This is mostly taken from ApplicationInfo.getAllApkPaths(). */
private static String getAllApkPaths(ApplicationInfo info) {
// The OS version of this method also includes resourceDirs, but this is not available in
// the SDK.
final List<String> output = new ArrayList<>(10);
// First add the base APK path, since this is always needed.
if (info.sourceDir != null) {
output.add(info.sourceDir);
}
// Next add split paths that are used by WebLayer.
if (info.splitSourceDirs != null) {
String[] splitNames = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
splitNames = WebLayer.ApiHelperForO.getSplitNames(info);
}
for (int i = 0; i < info.splitSourceDirs.length; i++) {
// WebLayer only uses the "chrome" and "weblayer" splits.
if (splitNames != null && !splitNames[i].equals("chrome")
&& !splitNames[i].equals("weblayer")) {
continue;
}
output.add(info.splitSourceDirs[i]);
}
}
// Last, add shared library paths.
if (info.sharedLibraryFiles != null) {
for (String input : info.sharedLibraryFiles) {
output.add(input);
}
}
return TextUtils.join(File.pathSeparator, output);
}
private WebViewCompatibilityHelper() {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/java/org/chromium/weblayer/WebViewCompatibilityHelper.java | Java | unknown | 4,588 |
// 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.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Tests for (@link ObserverList}.
*/
@RunWith(BaseJUnit4ClassRunner.class)
public class ObserverListTest {
interface Observer {
void observe(int x);
}
private static class Foo implements Observer {
private final int mScalar;
private int mTotal;
Foo(int scalar) {
mScalar = scalar;
}
@Override
public void observe(int x) {
mTotal += x * mScalar;
}
}
/**
* An observer which add a given Observer object to the list when observe is called.
*/
private static class FooAdder implements Observer {
private final ObserverList<Observer> mList;
private final Observer mLucky;
FooAdder(ObserverList<Observer> list, Observer oblivious) {
mList = list;
mLucky = oblivious;
}
@Override
public void observe(int x) {
mList.addObserver(mLucky);
}
}
/**
* An observer which removes a given Observer object from the list when observe is called.
*/
private static class FooRemover implements Observer {
private final ObserverList<Observer> mList;
private final Observer mDoomed;
FooRemover(ObserverList<Observer> list, Observer innocent) {
mList = list;
mDoomed = innocent;
}
@Override
public void observe(int x) {
mList.removeObserver(mDoomed);
}
}
private static <T> int getSizeOfIterable(Iterable<T> iterable) {
if (iterable instanceof Collection<?>) return ((Collection<?>) iterable).size();
int num = 0;
for (T el : iterable) num++;
return num;
}
@Test
@SmallTest
public void testRemoveWhileIteration() {
ObserverList<Observer> observerList = new ObserverList<Observer>();
Foo a = new Foo(1);
Foo b = new Foo(-1);
Foo c = new Foo(1);
Foo d = new Foo(-1);
Foo e = new Foo(-1);
FooRemover evil = new FooRemover(observerList, c);
observerList.addObserver(a);
observerList.addObserver(b);
for (Observer obs : observerList) obs.observe(10);
// Removing an observer not in the list should do nothing.
observerList.removeObserver(e);
observerList.addObserver(evil);
observerList.addObserver(c);
observerList.addObserver(d);
for (Observer obs : observerList) obs.observe(10);
// observe should be called twice on a.
Assert.assertEquals(20, a.mTotal);
// observe should be called twice on b.
Assert.assertEquals(-20, b.mTotal);
// evil removed c from the observerList before it got any callbacks.
Assert.assertEquals(0, c.mTotal);
// observe should be called once on d.
Assert.assertEquals(-10, d.mTotal);
// e was never added to the list, observe should not be called.
Assert.assertEquals(0, e.mTotal);
}
@Test
@SmallTest
public void testAddWhileIteration() {
ObserverList<Observer> observerList = new ObserverList<Observer>();
Foo a = new Foo(1);
Foo b = new Foo(-1);
Foo c = new Foo(1);
FooAdder evil = new FooAdder(observerList, c);
observerList.addObserver(evil);
observerList.addObserver(a);
observerList.addObserver(b);
for (Observer obs : observerList) obs.observe(10);
Assert.assertTrue(observerList.hasObserver(c));
Assert.assertEquals(10, a.mTotal);
Assert.assertEquals(-10, b.mTotal);
Assert.assertEquals(0, c.mTotal);
}
@Test
@SmallTest
public void testIterator() {
ObserverList<Integer> observerList = new ObserverList<Integer>();
observerList.addObserver(5);
observerList.addObserver(10);
observerList.addObserver(15);
Assert.assertEquals(3, getSizeOfIterable(observerList));
observerList.removeObserver(10);
Assert.assertEquals(2, getSizeOfIterable(observerList));
Iterator<Integer> it = observerList.iterator();
Assert.assertTrue(it.hasNext());
Assert.assertTrue(5 == it.next());
Assert.assertTrue(it.hasNext());
Assert.assertTrue(15 == it.next());
Assert.assertFalse(it.hasNext());
boolean removeExceptionThrown = false;
try {
it.remove();
Assert.fail("Expecting UnsupportedOperationException to be thrown here.");
} catch (UnsupportedOperationException e) {
removeExceptionThrown = true;
}
Assert.assertTrue(removeExceptionThrown);
Assert.assertEquals(2, getSizeOfIterable(observerList));
boolean noElementExceptionThrown = false;
try {
it.next();
Assert.fail("Expecting NoSuchElementException to be thrown here.");
} catch (NoSuchElementException e) {
noElementExceptionThrown = true;
}
Assert.assertTrue(noElementExceptionThrown);
}
@Test
@SmallTest
public void testRewindableIterator() {
ObserverList<Integer> observerList = new ObserverList<Integer>();
observerList.addObserver(5);
observerList.addObserver(10);
observerList.addObserver(15);
Assert.assertEquals(3, getSizeOfIterable(observerList));
ObserverList.RewindableIterator<Integer> it = observerList.rewindableIterator();
Assert.assertTrue(it.hasNext());
Assert.assertTrue(5 == it.next());
Assert.assertTrue(it.hasNext());
Assert.assertTrue(10 == it.next());
Assert.assertTrue(it.hasNext());
Assert.assertTrue(15 == it.next());
Assert.assertFalse(it.hasNext());
it.rewind();
Assert.assertTrue(it.hasNext());
Assert.assertTrue(5 == it.next());
Assert.assertTrue(it.hasNext());
Assert.assertTrue(10 == it.next());
Assert.assertTrue(it.hasNext());
Assert.assertTrue(15 == it.next());
Assert.assertEquals(5, (int) observerList.mObservers.get(0));
observerList.removeObserver(5);
Assert.assertEquals(null, observerList.mObservers.get(0));
it.rewind();
Assert.assertEquals(10, (int) observerList.mObservers.get(0));
Assert.assertTrue(it.hasNext());
Assert.assertTrue(10 == it.next());
Assert.assertTrue(it.hasNext());
Assert.assertTrue(15 == it.next());
}
@Test
@SmallTest
public void testAddObserverReturnValue() {
ObserverList<Object> observerList = new ObserverList<Object>();
Object a = new Object();
Assert.assertTrue(observerList.addObserver(a));
Assert.assertFalse(observerList.addObserver(a));
Object b = new Object();
Assert.assertTrue(observerList.addObserver(b));
Assert.assertFalse(observerList.addObserver(null));
}
@Test
@SmallTest
public void testRemoveObserverReturnValue() {
ObserverList<Object> observerList = new ObserverList<Object>();
Object a = new Object();
Object b = new Object();
observerList.addObserver(a);
observerList.addObserver(b);
Assert.assertTrue(observerList.removeObserver(a));
Assert.assertFalse(observerList.removeObserver(a));
Assert.assertFalse(observerList.removeObserver(new Object()));
Assert.assertTrue(observerList.removeObserver(b));
Assert.assertFalse(observerList.removeObserver(null));
// If we remove an object while iterating, it will be replaced by 'null'.
observerList.addObserver(a);
Assert.assertTrue(observerList.removeObserver(a));
Assert.assertFalse(observerList.removeObserver(null));
}
@Test
@SmallTest
public void testSize() {
ObserverList<Object> observerList = new ObserverList<Object>();
Assert.assertEquals(0, observerList.size());
Assert.assertTrue(observerList.isEmpty());
observerList.addObserver(null);
Assert.assertEquals(0, observerList.size());
Assert.assertTrue(observerList.isEmpty());
Object a = new Object();
observerList.addObserver(a);
Assert.assertEquals(1, observerList.size());
Assert.assertFalse(observerList.isEmpty());
observerList.addObserver(a);
Assert.assertEquals(1, observerList.size());
Assert.assertFalse(observerList.isEmpty());
observerList.addObserver(null);
Assert.assertEquals(1, observerList.size());
Assert.assertFalse(observerList.isEmpty());
Object b = new Object();
observerList.addObserver(b);
Assert.assertEquals(2, observerList.size());
Assert.assertFalse(observerList.isEmpty());
observerList.removeObserver(null);
Assert.assertEquals(2, observerList.size());
Assert.assertFalse(observerList.isEmpty());
observerList.removeObserver(new Object());
Assert.assertEquals(2, observerList.size());
Assert.assertFalse(observerList.isEmpty());
observerList.removeObserver(b);
Assert.assertEquals(1, observerList.size());
Assert.assertFalse(observerList.isEmpty());
observerList.removeObserver(b);
Assert.assertEquals(1, observerList.size());
Assert.assertFalse(observerList.isEmpty());
observerList.removeObserver(a);
Assert.assertEquals(0, observerList.size());
Assert.assertTrue(observerList.isEmpty());
observerList.removeObserver(a);
observerList.removeObserver(b);
observerList.removeObserver(null);
observerList.removeObserver(new Object());
Assert.assertEquals(0, observerList.size());
Assert.assertTrue(observerList.isEmpty());
observerList.addObserver(new Object());
observerList.addObserver(new Object());
observerList.addObserver(new Object());
observerList.addObserver(a);
Assert.assertEquals(4, observerList.size());
Assert.assertFalse(observerList.isEmpty());
observerList.clear();
Assert.assertEquals(0, observerList.size());
Assert.assertTrue(observerList.isEmpty());
observerList.removeObserver(a);
observerList.removeObserver(b);
observerList.removeObserver(null);
observerList.removeObserver(new Object());
Assert.assertEquals(0, observerList.size());
Assert.assertTrue(observerList.isEmpty());
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/javatests/org/chromium/weblayer/ObserverListTest.java | Java | unknown | 10,988 |
// 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 androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.BaseJUnit4ClassRunner;
/**
* Tests for (@link WebViewCompatibilityHelper}.
*/
@RunWith(BaseJUnit4ClassRunner.class)
public class WebViewCompatibilityHelperTest {
@Test
@SmallTest
public void testLibraryPaths() throws Exception {
Context appContext = InstrumentationRegistry.getTargetContext();
ClassLoader classLoader = WebViewCompatibilityHelper.initialize(appContext);
String[] libraryPaths = WebViewCompatibilityHelper.getLibraryPaths(classLoader);
for (String path : libraryPaths) {
Assert.assertTrue(path.startsWith("/./"));
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/javatests/org/chromium/weblayer/WebViewCompatibilityHelperTest.java | Java | unknown | 1,015 |
// 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 org.chromium.weblayer_private.interfaces.SettingsIntentHelper;
/**
* Helpers for writing tests for the Settings UI.
*/
public final class SettingsTestUtils {
// This can be removed if/when we move this into SettingsActivity. Currently no embedders
// need to launch the single site settings UI directly.
public static Intent createIntentForSiteSettingsSingleWebsite(
Context context, String profileName, boolean isIncognito, String url) {
return SettingsIntentHelper.createIntentForSiteSettingsSingleWebsite(
context, profileName, isIncognito, url);
}
// This can be removed if/when we move this into SettingsActivity. Currently no embedders
// need to launch the single category settings UI directly.
public static Intent createIntentForSiteSettingsSingleCategory(Context context,
String profileName, boolean isIncognito, String categoryType, String categoryTitle) {
return SettingsIntentHelper.createIntentForSiteSettingsSingleCategory(
context, profileName, isIncognito, categoryType, categoryTitle);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/javatestutil/org/chromium/weblayer/SettingsTestUtils.java | Java | unknown | 1,363 |
// 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;
/**
* TestProfile is responsible for forwarding function calls to Profile.
*/
public final class TestProfile {
public static void destroy(Profile profile) {
profile.destroy();
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/public/javatestutil/org/chromium/weblayer/TestProfile.java | Java | unknown | 373 |
// 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.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.AndroidRuntimeException;
import android.view.View;
import android.webkit.ValueCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.base.Callback;
import org.chromium.weblayer_private.interfaces.BrowserFragmentArgs;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.test_interfaces.ITestWebLayer;
import java.util.ArrayList;
import java.util.Set;
/**
* TestWebLayer is responsible for passing messages over a test only AIDL to the
* WebLayer implementation.
*/
public final class TestWebLayer {
@Nullable
private ITestWebLayer mITestWebLayer;
@Nullable
private static TestWebLayer sInstance;
public static TestWebLayer getTestWebLayer(@NonNull Context appContext) {
if (sInstance == null) sInstance = new TestWebLayer(appContext);
return sInstance;
}
private TestWebLayer(@NonNull Context appContext) {
try {
Class TestWebLayerClass = WebLayer.loadRemoteClass(
appContext, "org.chromium.weblayer_private.test.TestWebLayerImpl");
mITestWebLayer = ITestWebLayer.Stub.asInterface(
(IBinder) TestWebLayerClass.getMethod("create").invoke(null));
} catch (PackageManager.NameNotFoundException | ReflectiveOperationException e) {
throw new AndroidRuntimeException(e);
}
}
public static WebLayer loadSync(Context context) {
return WebLayer.loadSync(context);
}
public boolean isNetworkChangeAutoDetectOn() throws RemoteException {
return mITestWebLayer.isNetworkChangeAutoDetectOn();
}
/**
* Gets the processed context which is returned by ContextUtils.getApplicationContext() on the
* remote side.
*/
public static Context getRemoteContext(@NonNull Context appContext) {
return WebLayer.getApplicationContextForTesting(appContext);
}
/** Gets the context for the WebLayer implementation package. */
public static Context getWebLayerContext(@NonNull Context appContext) {
try {
return WebLayer.getOrCreateRemoteContext(appContext);
} catch (PackageManager.NameNotFoundException | ReflectiveOperationException e) {
throw new AndroidRuntimeException(e);
}
}
public void setMockLocationProvider(boolean enabled) throws RemoteException {
mITestWebLayer.setMockLocationProvider(enabled);
}
public boolean isMockLocationProviderRunning() throws RemoteException {
return mITestWebLayer.isMockLocationProviderRunning();
}
public boolean isPermissionDialogShown() throws RemoteException {
return mITestWebLayer.isPermissionDialogShown();
}
public void clickPermissionDialogButton(boolean allow) throws RemoteException {
mITestWebLayer.clickPermissionDialogButton(allow);
}
public void setSystemLocationSettingEnabled(boolean enabled) throws RemoteException {
mITestWebLayer.setSystemLocationSettingEnabled(enabled);
}
// Runs |runnable| when cc::RenderFrameMetadata's |top_controls_height| and
// |bottom_controls_height| matches the supplied values. |runnable| may be run synchronously.
public void waitForBrowserControlsMetadataState(Tab tab, int top, int bottom, Runnable runnable)
throws RemoteException {
mITestWebLayer.waitForBrowserControlsMetadataState(
tab.getITab(), top, bottom, ObjectWrapper.wrap(runnable));
}
public void setAccessibilityEnabled(boolean enabled) throws RemoteException {
mITestWebLayer.setAccessibilityEnabled(enabled);
}
public void addInfoBar(Tab tab, Runnable runnable) throws RemoteException {
mITestWebLayer.addInfoBar(tab.getITab(), ObjectWrapper.wrap(runnable));
}
public View getInfoBarContainerView(Tab tab) throws RemoteException {
return (View) ObjectWrapper.unwrap(
mITestWebLayer.getInfoBarContainerView(tab.getITab()), View.class);
}
public void setIgnoreMissingKeyForTranslateManager(boolean ignore) throws RemoteException {
mITestWebLayer.setIgnoreMissingKeyForTranslateManager(ignore);
}
public void forceNetworkConnectivityState(boolean networkAvailable) throws RemoteException {
mITestWebLayer.forceNetworkConnectivityState(networkAvailable);
}
public boolean canInfoBarContainerScroll(Tab tab) throws RemoteException {
return mITestWebLayer.canInfoBarContainerScroll(tab.getITab());
}
public String getTranslateInfoBarTargetLanguage(Tab tab) throws RemoteException {
return mITestWebLayer.getTranslateInfoBarTargetLanguage(tab.getITab());
}
public static void disableWebViewCompatibilityMode() {
WebLayer.disableWebViewCompatibilityMode();
}
public static void setupWeblayerForBrowserTest(Context application, Callback<View> callback) {
WebLayer.loadAsync(application, webLayer -> {
Bundle args = new Bundle();
args.putString(BrowserFragmentArgs.PROFILE_NAME, "browsertest");
args.putBoolean(BrowserFragmentArgs.IS_INCOGNITO, false);
Browser browser = new Browser(webLayer.createBrowser(application, args));
WebFragmentEventHandler eventHandler =
new WebFragmentEventHandler(browser.connectFragment());
browser.initializeState();
eventHandler.onAttach(application, null);
eventHandler.onCreate();
eventHandler.onStart();
eventHandler.onResume();
callback.onResult(eventHandler.getContentViewRenderView());
});
}
public boolean didShowFullscreenToast(Tab tab) throws RemoteException {
return mITestWebLayer.didShowFullscreenToast(tab.getITab());
}
public void initializeMockMediaRouteProvider(boolean closeRouteWithErrorOnSend,
boolean disableIsSupportsSource, @Nullable String createRouteErrorMessage,
@Nullable String joinRouteErrorMessage) throws RemoteException {
mITestWebLayer.initializeMockMediaRouteProvider(closeRouteWithErrorOnSend,
disableIsSupportsSource, createRouteErrorMessage, joinRouteErrorMessage);
}
public View getMediaRouteButton(String name) throws RemoteException {
return (View) ObjectWrapper.unwrap(mITestWebLayer.getMediaRouteButton(name), View.class);
}
public void crashTab(Tab tab) throws RemoteException {
mITestWebLayer.crashTab(tab.getITab());
}
public boolean isWindowOnSmallDevice(Browser browser) throws RemoteException {
return mITestWebLayer.isWindowOnSmallDevice(browser.getIBrowser());
}
public void fetchAccessToken(Profile profile, Set<String> scopes,
Callback<String> onTokenFetched) throws RemoteException {
ValueCallback<String> valueCallback = (String token) -> {
onTokenFetched.onResult(token);
};
mITestWebLayer.fetchAccessToken(profile.getIProfile(), ObjectWrapper.wrap(scopes),
ObjectWrapper.wrap(valueCallback));
}
public void addContentCaptureConsumer(Browser browser, Runnable runnable,
ArrayList<Integer> callbacks) throws RemoteException {
mITestWebLayer.addContentCaptureConsumer(
browser.getIBrowser(), ObjectWrapper.wrap(runnable), ObjectWrapper.wrap(callbacks));
}
public void notifyOfAutofillEvents(Browser browser, Runnable onNewEvent,
ArrayList<Integer> eventsObserved) throws RemoteException {
mITestWebLayer.notifyOfAutofillEvents(browser.getIBrowser(), ObjectWrapper.wrap(onNewEvent),
ObjectWrapper.wrap(eventsObserved));
}
public void activateBackgroundFetchNotification(int id) throws RemoteException {
mITestWebLayer.activateBackgroundFetchNotification(id);
}
public void expediteDownloadService() throws RemoteException {
mITestWebLayer.expediteDownloadService();
}
public void setMockWebAuthnEnabled(boolean enabled) throws RemoteException {
mITestWebLayer.setMockWebAuthnEnabled(enabled);
}
public void fireOnAccessTokenIdentifiedAsInvalid(
Profile profile, Set<String> scopes, String token) throws RemoteException {
mITestWebLayer.fireOnAccessTokenIdentifiedAsInvalid(
profile.getIProfile(), ObjectWrapper.wrap(scopes), ObjectWrapper.wrap(token));
}
public void grantLocationPermission(String url) throws RemoteException {
mITestWebLayer.grantLocationPermission(url);
}
public void setTextScaling(Profile profile, float value) throws RemoteException {
mITestWebLayer.setTextScaling(profile.getIProfile(), value);
}
public boolean getForceEnableZoom(Profile profile) throws RemoteException {
return mITestWebLayer.getForceEnableZoom(profile.getIProfile());
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/public/javatestutil/org/chromium/weblayer/TestWebLayer.java | Java | unknown | 9,314 |
// 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.
#ifndef WEBLAYER_PUBLIC_MAIN_H_
#define WEBLAYER_PUBLIC_MAIN_H_
#include <string>
#include "base/files/file.h"
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#endif
namespace weblayer {
class MainDelegate {
public:
virtual void PreMainMessageLoopRun() = 0;
virtual void PostMainMessageLoopRun() = 0;
virtual void SetMainMessageLoopQuitClosure(
base::OnceClosure quit_closure) = 0;
};
struct MainParams {
MainParams();
MainParams(const MainParams& other);
~MainParams();
raw_ptr<MainDelegate> delegate;
// If set, logging will redirect to this file.
base::FilePath log_filename;
// The name of the file that has the PAK data.
std::string pak_name;
};
int Main(MainParams params
#if BUILDFLAG(IS_WIN)
#if !defined(WIN_CONSOLE_APP)
,
HINSTANCE instance
#endif
#else
,
int argc,
const char** argv
#endif
);
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_MAIN_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/main.h | C++ | unknown | 1,200 |
// 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.
#ifndef WEBLAYER_PUBLIC_NAVIGATION_H_
#define WEBLAYER_PUBLIC_NAVIGATION_H_
#include <string>
#include <vector>
class GURL;
namespace net {
class HttpResponseHeaders;
}
namespace weblayer {
class Page;
// These types are sent over IPC and across different versions. Never remove
// or change the order.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.weblayer_private
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: ImplNavigationState
enum class NavigationState {
// Waiting to receive initial response data.
kWaitingResponse = 0,
// Processing the response.
kReceivingBytes = 1,
// The navigation succeeded. Any NavigationObservers would have had
// NavigationCompleted() called.
kComplete = 2,
// The navigation failed. This could be because of an error (in which case
// IsErrorPage() will return true) or the navigation got turned into a
// download (in which case IsDownload() will return true).
// NavigationObservers would have had NavigationFailed() called.
kFailed = 3,
};
class Navigation {
public:
virtual ~Navigation() {}
// The URL the frame is navigating to. This may change during the navigation
// when encountering a server redirect.
virtual GURL GetURL() = 0;
// 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).
virtual const std::vector<GURL>& GetRedirectChain() = 0;
virtual NavigationState GetState() = 0;
// Returns the status code of the navigation. Returns 0 if the navigation
// hasn't completed yet or if a response wasn't received.
virtual int GetHttpStatusCode() = 0;
// Returns the HTTP response headers. Returns nullptr if the navigation
// hasn't completed yet or if a response wasn't received.
virtual const net::HttpResponseHeaders* GetResponseHeaders() = 0;
// Whether the navigation happened without changing document. Examples of
// same document navigations are:
// * reference fragment navigations
// * pushState/replaceState
// * same page history navigation
virtual bool IsSameDocument() = 0;
// 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.
virtual bool IsErrorPage() = 0;
// Returns true if 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
// NavigationObserver::NavigationFailed.
virtual bool IsDownload() = 0;
// 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 false) is an intent:// URL.
// Added in 89.
virtual bool IsKnownProtocol() = 0;
// Returns true if the navigation was stopped before it could complete because
// NavigationController::Stop() was called.
virtual bool WasStopCalled() = 0;
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.weblayer_private
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: ImplLoadError
enum LoadError {
kNoError = 0, // Navigation completed successfully.
kHttpClientError = 1, // Server responded with 4xx status code.
kHttpServerError = 2, // Server responded with 5xx status code.
kSSLError = 3, // Certificate error.
kConnectivityError = 4, // Problem connecting to server.
kOtherError = 5, // An error not listed above or below occurred.
kSafeBrowsingError = 6, // Safe browsing error.
};
// Return information about the error, if any, that was encountered while
// loading the page.
virtual LoadError GetLoadError() = 0;
// Set a request's header. If the header is already present, its value is
// overwritten. This function can only be called at two times, during start
// and redirect. When called during start, the header applies to both the
// start and redirect. |name| must be rfc 2616 compliant and |value| must
// not contain '\0', '\n' or '\r'.
//
// This function 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 NavigationRedirected().
virtual void SetRequestHeader(const std::string& name,
const std::string& value) = 0;
// Sets the user-agent string used for this navigation. The user-agent is
// not sticky, it applies to this navigation only (and any redirects). This
// function may only be called from NavigationObserver::NavigationStarted().
// Any value specified during start carries through to a redirect. |value|
// must not contain any illegal characters as documented in
// SetRequestHeader(). Setting this to a non empty string 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.
virtual void SetUserAgentString(const std::string& value) = 0;
// Disables auto-reload for this navigation if the network is down and comes
// back later. Auto-reload is enabled by default. This function may only be
// called from NavigationObserver::NavigationStarted().
virtual void DisableNetworkErrorAutoReload() = 0;
// Whether the navigation was initiated by the page. Examples of
// page-initiated navigations include:
// * <a> link click
// * 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.
virtual bool IsPageInitiated() = 0;
// 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
virtual bool IsReload() = 0;
// 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
virtual bool IsServedFromBackForwardCache() = 0;
// Returns true if this navigation was initiated by a form submission.
virtual bool IsFormSubmission() = 0;
// Returns the referrer for this request.
virtual GURL GetReferrer() = 0;
// Returns the Page object this navigation is occurring for. This method may
// only be called in or after NavigationObserver::NavigationCompleted() or
// NavigationObserve::NavigationFailed(). It can return null if the navigation
// didn't commit (e.g. 204/205 or download).
virtual Page* GetPage() = 0;
// Returns the offset between the indices of the previous last committed and
// the newly committed navigation entries (e.g. -1 for back navigations, 0
// for reloads, 1 for forward navigations). This may not cover all corner
// cases, and can be incorrect in cases like main frame client redirects.
virtual int GetNavigationEntryOffset() = 0;
// Returns true if the navigation response was fetched from the cache.
virtual bool WasFetchedFromCache() = 0;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_NAVIGATION_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/navigation.h | C++ | unknown | 8,229 |
// 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.
#ifndef WEBLAYER_PUBLIC_NAVIGATION_CONTROLLER_H_
#define WEBLAYER_PUBLIC_NAVIGATION_CONTROLLER_H_
#include <algorithm>
#include <string>
class GURL;
namespace weblayer {
class NavigationObserver;
class NavigationController {
public:
// The members of this struct and their defaults should be kept in sync with
// |NavigationController::LoadURLParams|.
struct NavigateParams {
bool should_replace_current_entry = false;
bool enable_auto_play = false;
};
virtual ~NavigationController() = default;
virtual void AddObserver(NavigationObserver* observer) = 0;
virtual void RemoveObserver(NavigationObserver* observer) = 0;
virtual void Navigate(const GURL& url) = 0;
virtual void Navigate(const GURL& url, const NavigateParams& params) = 0;
virtual void GoBack() = 0;
virtual void GoForward() = 0;
virtual bool CanGoBack() = 0;
virtual bool CanGoForward() = 0;
// Navigates to the specified absolute index.
virtual void GoToIndex(int index) = 0;
virtual void Reload() = 0;
virtual void Stop() = 0;
// Gets the number of entries in the back/forward list.
virtual int GetNavigationListSize() = 0;
// Gets the index of the current entry in the back/forward list, or -1 if
// there are no entries.
virtual int GetNavigationListCurrentIndex() = 0;
// Gets the URL of the given entry in the back/forward list, or an empty GURL
// if there is no navigation entry at that index.
virtual GURL GetNavigationEntryDisplayURL(int index) = 0;
// Gets the page title of the given entry in the back/forward list, or an
// empty string if there is no navigation entry at that index.
virtual std::string GetNavigationEntryTitle(int index) = 0;
// Returns whether this entry will be skipped on a call to GoBack() or
// GoForward(). This will be true for navigations that were done without a
// user gesture, including both client side redirects and history.pushState.
virtual bool IsNavigationEntrySkippable(int index) = 0;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_NAVIGATION_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/navigation_controller.h | C++ | unknown | 2,221 |
// 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.
#ifndef WEBLAYER_PUBLIC_NAVIGATION_OBSERVER_H_
#define WEBLAYER_PUBLIC_NAVIGATION_OBSERVER_H_
class GURL;
namespace base {
class TimeDelta;
class TimeTicks;
} // namespace base
namespace weblayer {
class Navigation;
class Page;
// An interface for a WebLayer embedder to get notified about navigations. For
// now this only notifies for the main frame.
//
// The lifecycle of a navigation:
// 1) A navigation is initiated, such as by NavigationController::Navigate()
// or within the page
// 2) LoadStateChanged() first invoked
// 3) NavigationStarted
// 4) 0 or more NavigationRedirected
// 5) NavigationCompleted or NavigationFailed
// 6) Main frame completes loading, LoadStateChanged() last invoked
class NavigationObserver {
public:
virtual ~NavigationObserver() {}
// 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.
virtual void NavigationStarted(Navigation* navigation) {}
// Called when a navigation encountered a server redirect.
virtual void NavigationRedirected(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.
virtual void NavigationCompleted(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.
virtual void NavigationFailed(Navigation* navigation) {}
// Indicates that loading has started (|is_loading| is true) or is done
// (|is_loading| is false). |should_show_loading_ui| will be true unless the
// load is a fragment navigation, or triggered by
// history.pushState/replaceState.
virtual void LoadStateChanged(bool is_loading, bool should_show_loading_ui) {}
// Indicates that the load progress of the page has changed. |progress|
// ranges from 0.0 to 1.0.
virtual void LoadProgressChanged(double progress) {}
// This is fired after each navigation has completed to indicate that the
// first paint after a non-empty layout has finished.
virtual void OnFirstContentfulPaint() {}
// Similar to OnFirstContentfulPaint but contains timing information from the
// renderer process to better align with the Navigation Timing API.
// |navigation_start| is the navigation start time.
// |first_contentful_paint| is the duration to first contentful paint from
// navigation start.
virtual void OnFirstContentfulPaint(
const base::TimeTicks& navigation_start,
const base::TimeDelta& first_contentful_paint) {}
// This is fired when the largest contentful paint page load metric is
// available. |navigation_start| is the navigation start time.
// |largest_contentful_paint| is the duration to largest contentful paint from
// navigation start.
virtual void OnLargestContentfulPaint(
const base::TimeTicks& navigation_start,
const base::TimeDelta& largest_contentful_paint) {}
// Called after each navigation to indicate that the old page is no longer
// being rendered. Note this is not ordered with respect to
// OnFirstContentfulPaint.
virtual void OnOldPageNoLongerRendered(const GURL& url) {}
// 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.
virtual void OnPageDestroyed(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).
virtual void OnPageLanguageDetermined(Page* page,
const std::string& language) {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_NAVIGATION_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/navigation_observer.h | C++ | unknown | 5,713 |
// 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.
#ifndef WEBLAYER_PUBLIC_NEW_TAB_DELEGATE_H_
#define WEBLAYER_PUBLIC_NEW_TAB_DELEGATE_H_
namespace weblayer {
class Tab;
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.weblayer_private
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: ImplNewTabType
// Corresponds to type of browser the page requested.
enum class NewTabType {
// The new browser should be opened in the foreground.
kForeground = 0,
// The new browser should be opened in the foreground.
kBackground,
// The page requested the browser be shown in a new window with minimal
// browser UI. For example, no tabstrip.
kNewPopup,
// The page requested the browser be shown in a new window.
kNewWindow,
};
// An interface that allows clients to handle requests for new browsers, or
// in web terms, a new popup/window (and random other things).
class NewTabDelegate {
public:
// Called when a new tab is created by the browser. |new_tab| is owned by the
// browser.
virtual void OnNewTab(Tab* new_tab, NewTabType type) = 0;
protected:
virtual ~NewTabDelegate() {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_NEW_TAB_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/new_tab_delegate.h | C++ | unknown | 1,268 |
// 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_PAGE_H_
#define WEBLAYER_PUBLIC_PAGE_H_
namespace weblayer {
// This objects tracks the lifetime of a loaded web page. Most of the time there
// is only one Page object per tab. However features like back-forward cache,
// prerendering etc... sometime involve the creation of additional Page objects.
// Navigation::getPage() will return the Page for a given navigation. Similarly
// it'll be the same Page object that's passed in
// NavigationObserver::OnPageDestroyed().
class Page {
protected:
virtual ~Page() = default;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_PAGE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/page.h | C++ | unknown | 762 |
// 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_PRERENDER_CONTROLLER_H_
#define WEBLAYER_PUBLIC_PRERENDER_CONTROLLER_H_
class GURL;
namespace weblayer {
// PrerenderController enables prerendering of urls.
// Prerendering has the same effect as adding a link rel="prerender" resource
// hint to a web page. It is implemented using NoStatePrefetch and fetches
// resources needed for a url in advance, but does not execute Javascript or
// render any part of the page in advance. For more information on
// NoStatePrefetch, see
// https://developers.google.com/web/updates/2018/07/nostate-prefetch.
class PrerenderController {
public:
virtual void Prerender(const GURL& url) = 0;
virtual void DestroyAllContents() = 0;
protected:
virtual ~PrerenderController() = default;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_PRERENDER_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/prerender_controller.h | C++ | unknown | 984 |
// 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.
#ifndef WEBLAYER_PUBLIC_PROFILE_H_
#define WEBLAYER_PUBLIC_PROFILE_H_
#include <memory>
#include <string>
#include "base/containers/flat_set.h"
#include "base/functional/callback_forward.h"
#include "base/time/time.h"
namespace base {
class FilePath;
}
namespace gfx {
class Image;
}
class GURL;
namespace weblayer {
class CookieManager;
class DownloadDelegate;
class GoogleAccountAccessTokenFetchDelegate;
class PrerenderController;
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.weblayer_private
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: ImplBrowsingDataType
enum class BrowsingDataType {
COOKIES_AND_SITE_DATA = 0,
CACHE = 1,
SITE_SETTINGS = 2,
};
// Used for setting/getting profile related settings.
enum class SettingType {
BASIC_SAFE_BROWSING_ENABLED = 0,
UKM_ENABLED = 1,
EXTENDED_REPORTING_SAFE_BROWSING_ENABLED = 2,
REAL_TIME_SAFE_BROWSING_ENABLED = 3,
NETWORK_PREDICTION_ENABLED = 4,
};
class Profile {
public:
// Creates a new profile.
static std::unique_ptr<Profile> Create(const std::string& name,
bool is_incognito);
// Delete all profile's data from disk. If there are any existing usage
// of this profile, return |profile| immediately and |done_callback| will not
// be called. Otherwise return nullptr and |done_callback| is called when
// deletion is complete.
static std::unique_ptr<Profile> DestroyAndDeleteDataFromDisk(
std::unique_ptr<Profile> profile,
base::OnceClosure done_callback);
virtual ~Profile() {}
virtual void ClearBrowsingData(
const std::vector<BrowsingDataType>& data_types,
base::Time from_time,
base::Time to_time,
base::OnceClosure callback) = 0;
// Allows embedders to override the default download directory, which is the
// system download directory on Android and on other platforms it's in the
// home directory.
virtual void SetDownloadDirectory(const base::FilePath& directory) = 0;
// Sets the DownloadDelegate. If none is set, downloads will be dropped.
virtual void SetDownloadDelegate(DownloadDelegate* delegate) = 0;
// Sets the delegate for access token fetches. If none is set, the browser
// will not be able to fetch access tokens.
virtual void SetGoogleAccountAccessTokenFetchDelegate(
GoogleAccountAccessTokenFetchDelegate* delegate) = 0;
// Gets the cookie manager for this profile.
virtual CookieManager* GetCookieManager() = 0;
// Gets the prerender controller for this profile.
virtual PrerenderController* GetPrerenderController() = 0;
// Asynchronously fetches the set of known Browser persistence-ids. See
// Browser::PersistenceInfo for more details on persistence-ids.
virtual void GetBrowserPersistenceIds(
base::OnceCallback<void(base::flat_set<std::string>)> callback) = 0;
// Asynchronously removes the storage associated with the set of
// Browser persistence-ids. This ignores ids actively in use. |done_callback|
// is run with the result of the operation (on the main thread). A value of
// true means all files were removed. A value of false indicates at least one
// of the files could not be removed.
virtual void RemoveBrowserPersistenceStorage(
base::OnceCallback<void(bool)> done_callback,
base::flat_set<std::string> ids) = 0;
// Set the boolean value of the given setting type.
virtual void SetBooleanSetting(SettingType type, bool value) = 0;
// Get the boolean value of the given setting type.
virtual bool GetBooleanSetting(SettingType type) = 0;
// Returns the cached favicon for the specified url. Off the record profiles
// do not cache favicons. If this is called on an off-the-record profile
// the callback is run with an empty image synchronously. The returned image
// matches that returned by FaviconFetcher.
virtual void GetCachedFaviconForPageUrl(
const GURL& page_url,
base::OnceCallback<void(gfx::Image)> callback) = 0;
// For cross-origin navigations, the implementation may leverage a separate OS
// process for stronger isolation. If an embedder knows that a cross-origin
// navigation is likely starting soon, they can call this method as a hint to
// the implementation to start a fresh OS process. A subsequent navigation may
// use this preinitialized process, improving performance. It is safe to call
// this multiple times or when it is not certain that the spare renderer will
// be used, although calling this too eagerly may reduce performance as
// unnecessary processes are created.
virtual void PrepareForPossibleCrossOriginNavigation() = 0;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_PROFILE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/profile.h | C++ | unknown | 4,817 |
// 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.
#ifndef WEBLAYER_PUBLIC_TAB_H_
#define WEBLAYER_PUBLIC_TAB_H_
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "base/functional/callback_forward.h"
#include "build/build_config.h"
namespace base {
class Value;
}
#if !BUILDFLAG(IS_ANDROID)
namespace views {
class WebView;
}
#endif
namespace weblayer {
class Browser;
class ErrorPageDelegate;
class FaviconFetcher;
class FaviconFetcherDelegate;
class FullscreenDelegate;
class GoogleAccountsDelegate;
class NavigationController;
class NewTabDelegate;
class TabObserver;
// Represents a tab that is navigable.
class Tab {
public:
virtual ~Tab() = default;
// Returns the Browser that owns this.
virtual Browser* GetBrowser() = 0;
// Sets the ErrorPageDelegate. If none is set, a default action will be taken
// for any given interaction with an error page.
virtual void SetErrorPageDelegate(ErrorPageDelegate* delegate) = 0;
// Sets the FullscreenDelegate. Setting a non-null value implicitly enables
// fullscreen.
virtual void SetFullscreenDelegate(FullscreenDelegate* delegate) = 0;
// Sets the NewBrowserDelegate. Setting a null value implicitly disables
// popups.
virtual void SetNewTabDelegate(NewTabDelegate* delegate) = 0;
virtual void SetGoogleAccountsDelegate(GoogleAccountsDelegate* delegate) = 0;
virtual void AddObserver(TabObserver* observer) = 0;
virtual void RemoveObserver(TabObserver* observer) = 0;
virtual NavigationController* GetNavigationController() = 0;
using JavaScriptResultCallback = base::OnceCallback<void(base::Value)>;
// Executes the script, and returns the result to the callback if provided. If
// |use_separate_isolate| is 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.
virtual void ExecuteScript(const std::u16string& script,
bool use_separate_isolate,
JavaScriptResultCallback callback) = 0;
// Returns the tab's guid.
virtual const std::string& GetGuid() = 0;
// Allows the embedder to get and set arbitrary data on the tab. This will be
// saved and restored with the browser, so it is important to keep this data
// as small as possible.
virtual void SetData(const std::map<std::string, std::string>& data) = 0;
virtual const std::map<std::string, std::string>& GetData() = 0;
// Creates a FaviconFetcher that notifies a FaviconFetcherDelegate when
// the favicon changes.
// A page may provide any number of favicons. The preferred image size
// used depends upon the platform. If a previously cached icon is available,
// it is used, otherwise the icon is downloaded.
// |delegate| may be called multiple times for the same navigation. This
// happens when the page dynamically updates the favicon, but may also happen
// if a cached icon is determined to be out of date.
virtual std::unique_ptr<FaviconFetcher> CreateFaviconFetcher(
FaviconFetcherDelegate* delegate) = 0;
// Sets the target language for translation such that whenever the translate
// UI shows in this Tab, the target language will be |targetLanguage|. Notes:
// - |targetLanguage| should be specified as the language code (e.g., "de" for
// German).
// - Passing an empty string causes behavior to revert to default.
// - Specifying a non-empty target language will also result in the following
// behaviors (all of which are intentional as part of the semantics of
// having a target language):
// - Translation is initiated automatically (note that the infobar UI is
// present)
// - Translation occurs even for languages/sites that the user has
// blocklisted
// - Translation occurs even for pages in the user's default locale
// - Translation does *not* occur nor is the infobar UI shown for pages in
// the specified target language
virtual void SetTranslateTargetLanguage(
const std::string& translate_target_lang) = 0;
#if !BUILDFLAG(IS_ANDROID)
// TODO: this isn't a stable API, so use it now for expediency in the C++ API,
// but if we ever want to have backward or forward compatibility in C++ this
// will have to be something else.
virtual void AttachToView(views::WebView* web_view) = 0;
#endif
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_TAB_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/tab.h | C++ | unknown | 4,799 |
// 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.
#ifndef WEBLAYER_PUBLIC_TAB_OBSERVER_H_
#define WEBLAYER_PUBLIC_TAB_OBSERVER_H_
#include <string>
class GURL;
namespace weblayer {
class TabObserver {
public:
// The URL bar should be updated to |url|.
virtual void DisplayedUrlChanged(const GURL& url) {}
// Triggered when the render process dies, either due to crash or killed by
// the system to reclaim memory.
virtual void OnRenderProcessGone() {}
// Called when the title of this tab changes. Note before the page sets a
// title, the title may be a portion of the Uri.
virtual void OnTitleUpdated(const std::u16string& title) {}
protected:
virtual ~TabObserver() {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_TAB_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/tab_observer.h | C++ | unknown | 867 |
include_rules = [
"+components/android_system_error_page",
"+components/autofill/content/renderer",
"+components/cdm/renderer",
"+components/content_capture/common",
"+components/content_capture/renderer",
"+components/content_settings/common",
"+components/content_settings/renderer",
"+components/error_page/common",
"+components/grit",
"+components/page_load_metrics/renderer",
"+components/no_state_prefetch/common",
"+components/no_state_prefetch/renderer",
"+components/safe_browsing/buildflags.h",
"+components/safe_browsing/content/common",
"+components/safe_browsing/content/renderer",
"+components/safe_browsing/core/common",
"+components/security_interstitials/content/renderer",
"+components/security_interstitials/core/common",
"+components/spellcheck/renderer",
"+components/subresource_filter/content/renderer",
"+components/subresource_filter/core/common",
"+components/translate/content/renderer",
"+components/translate/core/common",
"+components/webapps/renderer",
"+content/public/common",
"+content/public/renderer",
# needed for safebrowsing
"+mojo/public/cpp/bindings",
"+net/base",
"+services/service_manager/public/cpp",
"+third_party/blink/public/common",
"+third_party/blink/public/platform",
"+third_party/blink/public/web",
"+ui/base",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/DEPS | Python | unknown | 1,335 |
// 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.
#include "weblayer/renderer/content_renderer_client_impl.h"
#include "base/feature_list.h"
#include "build/build_config.h"
#include "components/autofill/content/renderer/autofill_agent.h"
#include "components/autofill/content/renderer/password_autofill_agent.h"
#include "components/content_capture/common/content_capture_features.h"
#include "components/content_capture/renderer/content_capture_sender.h"
#include "components/content_settings/renderer/content_settings_agent_impl.h"
#include "components/error_page/common/error.h"
#include "components/grit/components_scaled_resources.h"
#include "components/no_state_prefetch/common/prerender_url_loader_throttle.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_client.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_helper.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_utils.h"
#include "components/no_state_prefetch/renderer/prerender_render_frame_observer.h"
#include "components/page_load_metrics/renderer/metrics_render_frame_observer.h"
#include "components/subresource_filter/content/renderer/ad_resource_tracker.h"
#include "components/subresource_filter/content/renderer/subresource_filter_agent.h"
#include "components/subresource_filter/content/renderer/unverified_ruleset_dealer.h"
#include "components/subresource_filter/core/common/common_features.h"
#include "components/webapps/renderer/web_page_metadata_agent.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_runtime_features.h"
#include "ui/base/resource/resource_bundle.h"
#include "weblayer/common/features.h"
#include "weblayer/renderer/error_page_helper.h"
#include "weblayer/renderer/url_loader_throttle_provider.h"
#include "weblayer/renderer/weblayer_render_frame_observer.h"
#include "weblayer/renderer/weblayer_render_thread_observer.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/android_system_error_page/error_page_populator.h"
#include "components/cdm/renderer/android_key_systems.h"
#include "components/spellcheck/renderer/spellcheck.h" // nogncheck
#include "components/spellcheck/renderer/spellcheck_provider.h" // nogncheck
#include "content/public/common/url_constants.h"
#include "content/public/renderer/render_thread.h"
#include "services/service_manager/public/cpp/local_interface_provider.h"
#include "third_party/blink/public/platform/web_runtime_features.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_security_policy.h"
#endif
namespace weblayer {
namespace {
#if BUILDFLAG(IS_ANDROID)
class SpellcheckInterfaceProvider
: public service_manager::LocalInterfaceProvider {
public:
SpellcheckInterfaceProvider() = default;
SpellcheckInterfaceProvider(const SpellcheckInterfaceProvider&) = delete;
SpellcheckInterfaceProvider& operator=(const SpellcheckInterfaceProvider&) =
delete;
~SpellcheckInterfaceProvider() override = default;
// service_manager::LocalInterfaceProvider:
void GetInterface(const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) override {
// A dirty hack to make SpellCheckHost requests work on WebLayer.
// TODO(crbug.com/806394): Use a WebView-specific service for SpellCheckHost
// and SafeBrowsing, instead of |content_browser|.
content::RenderThread::Get()->BindHostReceiver(mojo::GenericPendingReceiver(
interface_name, std::move(interface_pipe)));
}
};
#endif // BUILDFLAG(IS_ANDROID)
} // namespace
ContentRendererClientImpl::ContentRendererClientImpl() = default;
ContentRendererClientImpl::~ContentRendererClientImpl() = default;
void ContentRendererClientImpl::RenderThreadStarted() {
#if BUILDFLAG(IS_ANDROID)
if (!spellcheck_) {
local_interface_provider_ = std::make_unique<SpellcheckInterfaceProvider>();
spellcheck_ = std::make_unique<SpellCheck>(local_interface_provider_.get());
}
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowedForReferrer(
blink::WebString::FromUTF8(content::kAndroidAppScheme));
#endif
content::RenderThread* thread = content::RenderThread::Get();
weblayer_observer_ = std::make_unique<WebLayerRenderThreadObserver>();
thread->AddObserver(weblayer_observer_.get());
browser_interface_broker_ =
blink::Platform::Current()->GetBrowserInterfaceBroker();
subresource_filter_ruleset_dealer_ =
std::make_unique<subresource_filter::UnverifiedRulesetDealer>();
thread->AddObserver(subresource_filter_ruleset_dealer_.get());
}
void ContentRendererClientImpl::RenderFrameCreated(
content::RenderFrame* render_frame) {
auto* render_frame_observer = new WebLayerRenderFrameObserver(render_frame);
new prerender::PrerenderRenderFrameObserver(render_frame);
ErrorPageHelper::Create(render_frame);
autofill::PasswordAutofillAgent* password_autofill_agent =
new autofill::PasswordAutofillAgent(
render_frame, render_frame_observer->associated_interfaces());
new autofill::AutofillAgent(render_frame, password_autofill_agent, nullptr,
render_frame_observer->associated_interfaces());
auto* agent = new content_settings::ContentSettingsAgentImpl(
render_frame, false /* should_whitelist */,
std::make_unique<content_settings::ContentSettingsAgentImpl::Delegate>());
if (weblayer_observer_) {
if (weblayer_observer_->content_settings_manager()) {
mojo::Remote<content_settings::mojom::ContentSettingsManager> manager;
weblayer_observer_->content_settings_manager()->Clone(
manager.BindNewPipeAndPassReceiver());
agent->SetContentSettingsManager(std::move(manager));
}
}
auto* metrics_render_frame_observer =
new page_load_metrics::MetricsRenderFrameObserver(render_frame);
auto ad_resource_tracker =
std::make_unique<subresource_filter::AdResourceTracker>();
metrics_render_frame_observer->SetAdResourceTracker(
ad_resource_tracker.get());
auto* subresource_filter_agent =
new subresource_filter::SubresourceFilterAgent(
render_frame, subresource_filter_ruleset_dealer_.get(),
std::move(ad_resource_tracker));
subresource_filter_agent->Initialize();
#if BUILDFLAG(IS_ANDROID)
// |SpellCheckProvider| manages its own lifetime (and destroys itself when the
// RenderFrame is destroyed).
new SpellCheckProvider(render_frame, spellcheck_.get(),
local_interface_provider_.get());
#endif
if (render_frame->IsMainFrame())
new webapps::WebPageMetadataAgent(render_frame);
if (content_capture::features::IsContentCaptureEnabledInWebLayer()) {
new content_capture::ContentCaptureSender(
render_frame, render_frame_observer->associated_interfaces());
}
if (!render_frame->IsMainFrame()) {
auto* main_frame_no_state_prefetch_helper =
prerender::NoStatePrefetchHelper::Get(
render_frame->GetMainRenderFrame());
if (main_frame_no_state_prefetch_helper) {
// Avoid any race conditions from having the browser tell subframes that
// they're no-state prefetching.
new prerender::NoStatePrefetchHelper(
render_frame,
main_frame_no_state_prefetch_helper->histogram_prefix());
}
}
}
void ContentRendererClientImpl::WebViewCreated(
blink::WebView* web_view,
bool was_created_by_renderer,
const url::Origin* outermost_origin) {
new prerender::NoStatePrefetchClient(web_view);
}
SkBitmap* ContentRendererClientImpl::GetSadPluginBitmap() {
return const_cast<SkBitmap*>(ui::ResourceBundle::GetSharedInstance()
.GetImageNamed(IDR_SAD_PLUGIN)
.ToSkBitmap());
}
SkBitmap* ContentRendererClientImpl::GetSadWebViewBitmap() {
return const_cast<SkBitmap*>(ui::ResourceBundle::GetSharedInstance()
.GetImageNamed(IDR_SAD_WEBVIEW)
.ToSkBitmap());
}
void ContentRendererClientImpl::PrepareErrorPage(
content::RenderFrame* render_frame,
const blink::WebURLError& error,
const std::string& http_method,
content::mojom::AlternativeErrorPageOverrideInfoPtr
alternative_error_page_info,
std::string* error_html) {
auto* error_page_helper = ErrorPageHelper::GetForFrame(render_frame);
if (error_page_helper)
error_page_helper->PrepareErrorPage();
#if BUILDFLAG(IS_ANDROID)
// This does nothing if |error_html| is non-null (which happens if the
// embedder injects an error page).
android_system_error_page::PopulateErrorPageHtml(error, error_html);
#endif
}
std::unique_ptr<blink::URLLoaderThrottleProvider>
ContentRendererClientImpl::CreateURLLoaderThrottleProvider(
blink::URLLoaderThrottleProviderType provider_type) {
return std::make_unique<URLLoaderThrottleProvider>(
browser_interface_broker_.get(), provider_type);
}
void ContentRendererClientImpl::GetSupportedKeySystems(
media::GetSupportedKeySystemsCB cb) {
media::KeySystemInfos key_systems;
#if BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(ENABLE_WIDEVINE)
cdm::AddAndroidWidevine(&key_systems);
#endif // BUILDFLAG(ENABLE_WIDEVINE)
cdm::AddAndroidPlatformKeySystems(&key_systems);
#endif // BUILDFLAG(IS_ANDROID)
std::move(cb).Run(std::move(key_systems));
}
void ContentRendererClientImpl::
SetRuntimeFeaturesDefaultsBeforeBlinkInitialization() {
blink::WebRuntimeFeatures::EnablePerformanceManagerInstrumentation(true);
#if BUILDFLAG(IS_ANDROID)
// Web Share is experimental by default, and explicitly enabled on Android
// (for both Chrome and WebLayer).
blink::WebRuntimeFeatures::EnableWebShare(true);
#endif
if (base::FeatureList::IsEnabled(subresource_filter::kAdTagging)) {
blink::WebRuntimeFeatures::EnableAdTagging(true);
}
}
bool ContentRendererClientImpl::IsPrefetchOnly(
content::RenderFrame* render_frame) {
return prerender::NoStatePrefetchHelper::IsPrefetching(render_frame);
}
bool ContentRendererClientImpl::DeferMediaLoad(
content::RenderFrame* render_frame,
bool has_played_media_before,
base::OnceClosure closure) {
return prerender::DeferMediaLoad(render_frame, has_played_media_before,
std::move(closure));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/content_renderer_client_impl.cc | C++ | unknown | 10,567 |
// 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.
#ifndef WEBLAYER_RENDERER_CONTENT_RENDERER_CLIENT_IMPL_H_
#define WEBLAYER_RENDERER_CONTENT_RENDERER_CLIENT_IMPL_H_
#include "build/build_config.h"
#include "content/public/common/alternative_error_page_override_info.mojom.h"
#include "content/public/renderer/content_renderer_client.h"
#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
class SpellCheck;
namespace service_manager {
class LocalInterfaceProvider;
} // namespace service_manager
namespace subresource_filter {
class UnverifiedRulesetDealer;
}
namespace weblayer {
class WebLayerRenderThreadObserver;
class ContentRendererClientImpl : public content::ContentRendererClient {
public:
ContentRendererClientImpl();
ContentRendererClientImpl(const ContentRendererClientImpl&) = delete;
ContentRendererClientImpl& operator=(const ContentRendererClientImpl&) =
delete;
~ContentRendererClientImpl() override;
// content::ContentRendererClient:
void RenderThreadStarted() override;
void RenderFrameCreated(content::RenderFrame* render_frame) override;
void WebViewCreated(blink::WebView* web_view,
bool was_created_by_renderer,
const url::Origin* outermost_origin) override;
SkBitmap* GetSadPluginBitmap() override;
SkBitmap* GetSadWebViewBitmap() override;
void PrepareErrorPage(content::RenderFrame* render_frame,
const blink::WebURLError& error,
const std::string& http_method,
content::mojom::AlternativeErrorPageOverrideInfoPtr
alternative_error_page_info,
std::string* error_html) override;
std::unique_ptr<blink::URLLoaderThrottleProvider>
CreateURLLoaderThrottleProvider(
blink::URLLoaderThrottleProviderType provider_type) override;
void GetSupportedKeySystems(media::GetSupportedKeySystemsCB cb) override;
void SetRuntimeFeaturesDefaultsBeforeBlinkInitialization() override;
bool IsPrefetchOnly(content::RenderFrame* render_frame) override;
bool DeferMediaLoad(content::RenderFrame* render_frame,
bool has_played_media_before,
base::OnceClosure closure) override;
private:
#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<service_manager::LocalInterfaceProvider>
local_interface_provider_;
std::unique_ptr<SpellCheck> spellcheck_;
#endif
std::unique_ptr<subresource_filter::UnverifiedRulesetDealer>
subresource_filter_ruleset_dealer_;
std::unique_ptr<WebLayerRenderThreadObserver> weblayer_observer_;
scoped_refptr<blink::ThreadSafeBrowserInterfaceBrokerProxy>
browser_interface_broker_;
};
} // namespace weblayer
#endif // WEBLAYER_RENDERER_CONTENT_RENDERER_CLIENT_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/content_renderer_client_impl.h | C++ | unknown | 2,922 |
// 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.
#include "weblayer/renderer/error_page_helper.h"
#include "base/command_line.h"
#include "components/security_interstitials/content/renderer/security_interstitial_page_controller.h"
#include "content/public/renderer/render_frame.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "weblayer/common/features.h"
namespace weblayer {
// static
void ErrorPageHelper::Create(content::RenderFrame* render_frame) {
if (render_frame->IsMainFrame())
new ErrorPageHelper(render_frame);
}
// static
ErrorPageHelper* ErrorPageHelper::GetForFrame(
content::RenderFrame* render_frame) {
return render_frame->IsMainFrame() ? Get(render_frame) : nullptr;
}
void ErrorPageHelper::PrepareErrorPage() {
if (is_disabled_for_next_error_) {
is_disabled_for_next_error_ = false;
return;
}
is_preparing_for_error_page_ = true;
}
void ErrorPageHelper::DidCommitProvisionalLoad(ui::PageTransition transition) {
show_error_page_in_finish_load_ = is_preparing_for_error_page_;
is_preparing_for_error_page_ = false;
}
void ErrorPageHelper::DidFinishLoad() {
if (!show_error_page_in_finish_load_)
return;
security_interstitials::SecurityInterstitialPageController::Install(
render_frame());
}
void ErrorPageHelper::OnDestruct() {
delete this;
}
void ErrorPageHelper::DisableErrorPageHelperForNextError() {
is_disabled_for_next_error_ = true;
}
ErrorPageHelper::ErrorPageHelper(content::RenderFrame* render_frame)
: RenderFrameObserver(render_frame),
RenderFrameObserverTracker<ErrorPageHelper>(render_frame) {
render_frame->GetAssociatedInterfaceRegistry()
->AddInterface<mojom::ErrorPageHelper>(base::BindRepeating(
&ErrorPageHelper::BindErrorPageHelper, weak_factory_.GetWeakPtr()));
}
ErrorPageHelper::~ErrorPageHelper() = default;
void ErrorPageHelper::BindErrorPageHelper(
mojo::PendingAssociatedReceiver<mojom::ErrorPageHelper> receiver) {
// There is only a need for a single receiver to be bound at a time.
error_page_helper_receiver_.reset();
error_page_helper_receiver_.Bind(std::move(receiver));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/error_page_helper.cc | C++ | unknown | 2,363 |
// 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.
#ifndef WEBLAYER_RENDERER_ERROR_PAGE_HELPER_H_
#define WEBLAYER_RENDERER_ERROR_PAGE_HELPER_H_
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_observer_tracker.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "weblayer/common/error_page_helper.mojom.h"
namespace weblayer {
// A class that allows error pages to handle user interaction by handling their
// javascript commands. Currently only SSL and safebrowsing related
// interstitials are supported.
// This is a stripped down version of Chrome's NetErrorHelper.
// TODO(crbug.com/1073624): Share this logic with NetErrorHelper.
class ErrorPageHelper
: public content::RenderFrameObserver,
public content::RenderFrameObserverTracker<ErrorPageHelper>,
public mojom::ErrorPageHelper {
public:
ErrorPageHelper(const ErrorPageHelper&) = delete;
ErrorPageHelper& operator=(const ErrorPageHelper&) = delete;
// Creates an ErrorPageHelper which will observe and tie its lifetime to
// |render_frame|, if it's a main frame. ErrorPageHelpers will not be created
// for sub frames.
static void Create(content::RenderFrame* render_frame);
// Returns the ErrorPageHelper for the frame, if it exists.
static ErrorPageHelper* GetForFrame(content::RenderFrame* render_frame);
// Called when the current navigation results in an error.
void PrepareErrorPage();
// content::RenderFrameObserver:
void DidCommitProvisionalLoad(ui::PageTransition transition) override;
void DidFinishLoad() override;
void OnDestruct() override;
// mojom::ErrorPageHelper:
void DisableErrorPageHelperForNextError() override;
private:
explicit ErrorPageHelper(content::RenderFrame* render_frame);
~ErrorPageHelper() override;
void BindErrorPageHelper(
mojo::PendingAssociatedReceiver<mojom::ErrorPageHelper> receiver);
// Set to true in PrepareErrorPage().
bool is_preparing_for_error_page_ = false;
// Set to the value of |is_preparing_for_error_page_| in
// DidCommitProvisionalLoad(). Used to determine if the security interstitial
// should be shown when the load finishes.
bool show_error_page_in_finish_load_ = false;
// Set to true when the embedder injects its own error page. When the
// embedder injects its own error page the support here is not needed and
// disabled.
bool is_disabled_for_next_error_ = false;
mojo::AssociatedReceiver<mojom::ErrorPageHelper> error_page_helper_receiver_{
this};
base::WeakPtrFactory<ErrorPageHelper> weak_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_RENDERER_ERROR_PAGE_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/error_page_helper.h | C++ | unknown | 2,857 |
// 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.
#include "weblayer/renderer/url_loader_throttle_provider.h"
#include <memory>
#include "base/memory/ptr_util.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_helper.h"
#include "components/safe_browsing/content/renderer/renderer_url_loader_throttle.h"
#include "content/public/renderer/render_thread.h"
#include "third_party/blink/public/common/loader/resource_type_util.h"
namespace weblayer {
URLLoaderThrottleProvider::URLLoaderThrottleProvider(
blink::ThreadSafeBrowserInterfaceBrokerProxy* broker,
blink::URLLoaderThrottleProviderType type)
: type_(type) {
DETACH_FROM_THREAD(thread_checker_);
broker->GetInterface(safe_browsing_remote_.InitWithNewPipeAndPassReceiver());
}
URLLoaderThrottleProvider::URLLoaderThrottleProvider(
const URLLoaderThrottleProvider& other)
: type_(other.type_) {
DETACH_FROM_THREAD(thread_checker_);
if (other.safe_browsing_) {
other.safe_browsing_->Clone(
safe_browsing_remote_.InitWithNewPipeAndPassReceiver());
}
}
std::unique_ptr<blink::URLLoaderThrottleProvider>
URLLoaderThrottleProvider::Clone() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (safe_browsing_remote_)
safe_browsing_.Bind(std::move(safe_browsing_remote_));
return base::WrapUnique(new URLLoaderThrottleProvider(*this));
}
URLLoaderThrottleProvider::~URLLoaderThrottleProvider() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
}
blink::WebVector<std::unique_ptr<blink::URLLoaderThrottle>>
URLLoaderThrottleProvider::CreateThrottles(
int render_frame_id,
const blink::WebURLRequest& request) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
blink::WebVector<std::unique_ptr<blink::URLLoaderThrottle>> throttles;
bool is_frame_resource =
blink::IsRequestDestinationFrame(request.GetRequestDestination());
DCHECK(!is_frame_resource ||
type_ == blink::URLLoaderThrottleProviderType::kFrame);
if (!is_frame_resource) {
if (safe_browsing_remote_)
safe_browsing_.Bind(std::move(safe_browsing_remote_));
throttles.emplace_back(
std::make_unique<safe_browsing::RendererURLLoaderThrottle>(
safe_browsing_.get(), render_frame_id));
}
if (type_ == blink::URLLoaderThrottleProviderType::kFrame &&
!is_frame_resource) {
auto throttle =
prerender::NoStatePrefetchHelper::MaybeCreateThrottle(render_frame_id);
if (throttle)
throttles.emplace_back(std::move(throttle));
}
return throttles;
}
void URLLoaderThrottleProvider::SetOnline(bool is_online) {}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/url_loader_throttle_provider.cc | C++ | unknown | 2,711 |
// 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.
#ifndef WEBLAYER_RENDERER_URL_LOADER_THROTTLE_PROVIDER_H_
#define WEBLAYER_RENDERER_URL_LOADER_THROTTLE_PROVIDER_H_
#include "base/threading/thread_checker.h"
#include "components/safe_browsing/content/common/safe_browsing.mojom.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/url_loader_throttle_provider.h"
namespace weblayer {
// Instances must be constructed on the render thread, and then used and
// destructed on a single thread, which can be different from the render thread.
class URLLoaderThrottleProvider : public blink::URLLoaderThrottleProvider {
public:
URLLoaderThrottleProvider(
blink::ThreadSafeBrowserInterfaceBrokerProxy* broker,
blink::URLLoaderThrottleProviderType type);
URLLoaderThrottleProvider& operator=(const URLLoaderThrottleProvider&) =
delete;
~URLLoaderThrottleProvider() override;
// blink::URLLoaderThrottleProvider implementation.
std::unique_ptr<blink::URLLoaderThrottleProvider> Clone() override;
blink::WebVector<std::unique_ptr<blink::URLLoaderThrottle>> CreateThrottles(
int render_frame_id,
const blink::WebURLRequest& request) override;
void SetOnline(bool is_online) override;
private:
// This copy constructor works in conjunction with Clone(), not intended for
// general use.
URLLoaderThrottleProvider(const URLLoaderThrottleProvider& other);
blink::URLLoaderThrottleProviderType type_;
mojo::PendingRemote<safe_browsing::mojom::SafeBrowsing> safe_browsing_remote_;
mojo::Remote<safe_browsing::mojom::SafeBrowsing> safe_browsing_;
THREAD_CHECKER(thread_checker_);
};
} // namespace weblayer
#endif // WEBLAYER_RENDERER_URL_LOADER_THROTTLE_PROVIDER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/url_loader_throttle_provider.h | C++ | unknown | 1,999 |
// 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.
#include "weblayer/renderer/weblayer_render_frame_observer.h"
#include "content/public/renderer/render_frame.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_helper.h"
#include "components/translate/content/renderer/translate_agent.h"
#include "components/translate/core/common/translate_util.h"
#include "third_party/blink/public/web/web_document_loader.h"
#include "third_party/blink/public/web/web_frame_content_dumper.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "weblayer/common/features.h"
#include "weblayer/common/isolated_world_ids.h"
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
#include "components/safe_browsing/content/renderer/phishing_classifier/phishing_classifier_delegate.h"
#endif
namespace weblayer {
namespace {
// Maximum number of characters in the document to index.
// Any text beyond this point will be clipped.
static const size_t kMaxIndexChars = 65535;
// Constants for UMA statistic collection.
static const char kTranslateCaptureText[] = "Translate.CaptureText";
// For a page that auto-refreshes, we still show the bubble, if
// the refresh delay is less than this value (in seconds).
static constexpr base::TimeDelta kLocationChangeInterval = base::Seconds(10);
} // namespace
WebLayerRenderFrameObserver::WebLayerRenderFrameObserver(
content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame), translate_agent_(nullptr) {
// Don't do anything for subframes.
if (!render_frame->IsMainFrame())
return;
if (base::FeatureList::IsEnabled(
features::kWebLayerClientSidePhishingDetection))
SetClientSidePhishingDetection();
// TODO(crbug.com/1073370): Handle case where subframe translation is enabled.
DCHECK(!translate::IsSubFrameTranslationEnabled());
translate_agent_ =
new translate::TranslateAgent(render_frame, ISOLATED_WORLD_ID_TRANSLATE);
}
WebLayerRenderFrameObserver::~WebLayerRenderFrameObserver() = default;
bool WebLayerRenderFrameObserver::OnAssociatedInterfaceRequestForFrame(
const std::string& interface_name,
mojo::ScopedInterfaceEndpointHandle* handle) {
return associated_interfaces_.TryBindInterface(interface_name, handle);
}
void WebLayerRenderFrameObserver::ReadyToCommitNavigation(
blink::WebDocumentLoader* document_loader) {
// Let translate_agent do any preparatory work for loading a URL.
if (!translate_agent_)
return;
translate_agent_->PrepareForUrl(
render_frame()->GetWebFrame()->GetDocument().Url());
}
void WebLayerRenderFrameObserver::DidMeaningfulLayout(
blink::WebMeaningfulLayout layout_type) {
// Don't do any work for subframes.
if (!render_frame()->IsMainFrame())
return;
switch (layout_type) {
case blink::WebMeaningfulLayout::kFinishedParsing:
CapturePageText(PRELIMINARY_CAPTURE);
break;
case blink::WebMeaningfulLayout::kFinishedLoading:
CapturePageText(FINAL_CAPTURE);
break;
default:
break;
}
}
// NOTE: This is a simplified version of
// ChromeRenderFrameObserver::CapturePageText(), which is more complex as it is
// used for embedder-level purposes beyond translation. This code is expected to
// be eliminated when WebLayer adopts Chrome's upcoming per-frame translate
// architecture (crbug.com/1063520).
void WebLayerRenderFrameObserver::CapturePageText(
TextCaptureType capture_type) {
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
if (!frame)
return;
// Don't capture pages that have pending redirect or location change.
if (frame->IsNavigationScheduledWithin(kLocationChangeInterval))
return;
// Don't index/capture pages that are in view source mode.
if (frame->IsViewSourceModeEnabled())
return;
// Don't capture text of the error pages.
blink::WebDocumentLoader* document_loader = frame->GetDocumentLoader();
if (document_loader && document_loader->HasUnreachableURL())
return;
// Don't index/capture pages that are being no-state prefetched.
if (prerender::NoStatePrefetchHelper::IsPrefetching(render_frame()))
return;
// Don't capture contents unless there is either a translate agent or a
// phishing classifier to consume them.
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
if (!translate_agent_ && !phishing_classifier_)
return;
#else
if (!translate_agent_)
return;
#endif
base::TimeTicks capture_begin_time = base::TimeTicks::Now();
// Retrieve the frame's full text (up to kMaxIndexChars), and pass it to the
// translate helper for language detection and possible translation.
// TODO(http://crbug.com/1163244): Update this when the corresponding usage of
// this function in //chrome is updated.
std::u16string contents =
blink::WebFrameContentDumper::DumpFrameTreeAsText(frame, kMaxIndexChars)
.Utf16();
UMA_HISTOGRAM_TIMES(kTranslateCaptureText,
base::TimeTicks::Now() - capture_begin_time);
// We should run language detection only once. Parsing finishes before
// the page loads, so let's pick that timing (as in chrome).
if (translate_agent_ && capture_type == PRELIMINARY_CAPTURE) {
translate_agent_->PageCaptured(contents);
}
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
if (phishing_classifier_)
phishing_classifier_->PageCaptured(&contents,
capture_type == PRELIMINARY_CAPTURE);
#endif
}
void WebLayerRenderFrameObserver::OnDestruct() {
delete this;
}
void WebLayerRenderFrameObserver::SetClientSidePhishingDetection() {
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
phishing_classifier_ = safe_browsing::PhishingClassifierDelegate::Create(
render_frame(), nullptr);
#endif
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/weblayer_render_frame_observer.cc | C++ | unknown | 5,926 |
// 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.
#ifndef WEBLAYER_RENDERER_WEBLAYER_RENDER_FRAME_OBSERVER_H_
#define WEBLAYER_RENDERER_WEBLAYER_RENDER_FRAME_OBSERVER_H_
#include "components/safe_browsing/buildflags.h"
#include "content/public/renderer/render_frame_observer.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
namespace safe_browsing {
class PhishingClassifierDelegate;
}
namespace translate {
class TranslateAgent;
}
namespace weblayer {
// This class holds the WebLayer-specific parts of RenderFrame, and has the
// same lifetime. It is analogous to //chrome's ChromeRenderFrameObserver.
class WebLayerRenderFrameObserver : public content::RenderFrameObserver {
public:
explicit WebLayerRenderFrameObserver(content::RenderFrame* render_frame);
WebLayerRenderFrameObserver(const WebLayerRenderFrameObserver&) = delete;
WebLayerRenderFrameObserver& operator=(const WebLayerRenderFrameObserver&) =
delete;
blink::AssociatedInterfaceRegistry* associated_interfaces() {
return &associated_interfaces_;
}
private:
enum TextCaptureType { PRELIMINARY_CAPTURE, FINAL_CAPTURE };
~WebLayerRenderFrameObserver() override;
// RenderFrameObserver:
bool OnAssociatedInterfaceRequestForFrame(
const std::string& interface_name,
mojo::ScopedInterfaceEndpointHandle* handle) override;
void ReadyToCommitNavigation(
blink::WebDocumentLoader* document_loader) override;
void DidMeaningfulLayout(blink::WebMeaningfulLayout layout_type) override;
void OnDestruct() override;
void CapturePageText(TextCaptureType capture_type);
// Initializes a |phishing_classifier_delegate_|.
void SetClientSidePhishingDetection();
blink::AssociatedInterfaceRegistry associated_interfaces_;
// Has the same lifetime as this object.
translate::TranslateAgent* translate_agent_;
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
safe_browsing::PhishingClassifierDelegate* phishing_classifier_ = nullptr;
#endif
};
} // namespace weblayer
#endif // WEBLAYER_RENDERER_WEBLAYER_RENDER_FRAME_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/weblayer_render_frame_observer.h | C++ | unknown | 2,196 |
// 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.
#include "weblayer/renderer/weblayer_render_thread_observer.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
namespace weblayer {
WebLayerRenderThreadObserver::WebLayerRenderThreadObserver() = default;
WebLayerRenderThreadObserver::~WebLayerRenderThreadObserver() = default;
void WebLayerRenderThreadObserver::RegisterMojoInterfaces(
blink::AssociatedInterfaceRegistry* associated_interfaces) {
associated_interfaces->AddInterface<
mojom::RendererConfiguration>(base::BindRepeating(
&WebLayerRenderThreadObserver::OnRendererConfigurationAssociatedRequest,
base::Unretained(this)));
}
void WebLayerRenderThreadObserver::UnregisterMojoInterfaces(
blink::AssociatedInterfaceRegistry* associated_interfaces) {
associated_interfaces->RemoveInterface(mojom::RendererConfiguration::Name_);
}
// weblayer::mojom::RendererConfiguration:
void WebLayerRenderThreadObserver::SetInitialConfiguration(
mojo::PendingRemote<content_settings::mojom::ContentSettingsManager>
content_settings_manager) {
if (content_settings_manager)
content_settings_manager_.Bind(std::move(content_settings_manager));
}
void WebLayerRenderThreadObserver::OnRendererConfigurationAssociatedRequest(
mojo::PendingAssociatedReceiver<mojom::RendererConfiguration> receiver) {
renderer_configuration_receivers_.Add(this, std::move(receiver));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/weblayer_render_thread_observer.cc | C++ | unknown | 1,588 |
// 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_RENDERER_WEBLAYER_RENDER_THREAD_OBSERVER_H_
#define WEBLAYER_RENDERER_WEBLAYER_RENDER_THREAD_OBSERVER_H_
#include "components/content_settings/common/content_settings_manager.mojom.h"
#include "content/public/renderer/render_thread_observer.h"
#include "mojo/public/cpp/bindings/associated_receiver_set.h"
#include "weblayer/common/renderer_configuration.mojom.h"
namespace weblayer {
// Listens for WebLayer-specific messages from the browser.
class WebLayerRenderThreadObserver : public content::RenderThreadObserver,
public mojom::RendererConfiguration {
public:
WebLayerRenderThreadObserver();
~WebLayerRenderThreadObserver() override;
content_settings::mojom::ContentSettingsManager* content_settings_manager() {
if (content_settings_manager_)
return content_settings_manager_.get();
return nullptr;
}
private:
// content::RenderThreadObserver:
void RegisterMojoInterfaces(
blink::AssociatedInterfaceRegistry* associated_interfaces) override;
void UnregisterMojoInterfaces(
blink::AssociatedInterfaceRegistry* associated_interfaces) override;
// weblayer::mojom::RendererConfiguration:
void SetInitialConfiguration(
mojo::PendingRemote<content_settings::mojom::ContentSettingsManager>
content_settings_manager) override;
void OnRendererConfigurationAssociatedRequest(
mojo::PendingAssociatedReceiver<mojom::RendererConfiguration> receiver);
mojo::Remote<content_settings::mojom::ContentSettingsManager>
content_settings_manager_;
mojo::AssociatedReceiverSet<mojom::RendererConfiguration>
renderer_configuration_receivers_;
};
} // namespace weblayer
#endif // WEBLAYER_RENDERER_WEBLAYER_RENDER_THREAD_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/renderer/weblayer_render_thread_observer.h | C++ | unknown | 1,915 |
include_rules = [
"+net",
"+ui/aura",
"+ui/base",
"+ui/color",
"+ui/display",
"+ui/events",
"+ui/gfx",
"+ui/native_theme",
"+ui/views",
"+ui/wm",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/DEPS | Python | unknown | 168 |
include_rules = [
"+components/embedder_support",
"+components/metrics",
"+components/translate/content/android",
"+content/public/android",
"+content/public/app",
"+content/public/test",
"+ui/android",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/DEPS | Python | unknown | 219 |
// 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_browsertests_apk;
import android.view.View;
import android.widget.LinearLayout;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.content_public.browser.BrowserStartupController;
import org.chromium.native_test.NativeBrowserTest;
import org.chromium.native_test.NativeBrowserTestActivity;
import org.chromium.weblayer.TestWebLayer;
import java.io.File;
/** An Activity base class for running browser tests against WebLayerShell. */
public class WebLayerBrowserTestsActivity extends NativeBrowserTestActivity {
private static final String TAG = "native_test";
@Override
protected void initializeBrowserProcess() {
BrowserStartupController.getInstance().setContentMainCallbackForTests(() -> {
// This jumps into C++ to set up and run the test harness. The test harness runs
// ContentMain()-equivalent code, and then waits for javaStartupTasksComplete()
// to be called.
runTests();
});
try {
// Browser tests cannot be run in WebView compatibility mode since the class loader
// WebLayer uses needs to match the class loader used for setup.
TestWebLayer.disableWebViewCompatibilityMode();
TestWebLayer.setupWeblayerForBrowserTest(getApplication(), (contentView) -> {
LinearLayout mainView = new LinearLayout(this);
int viewId = View.generateViewId();
mainView.setId(viewId);
setContentView(mainView);
mainView.addView(contentView);
NativeBrowserTest.javaStartupTasksComplete();
});
} catch (Exception e) {
throw new RuntimeException("failed loading WebLayer", e);
}
}
@Override
protected File getPrivateDataDirectory() {
return new File(UrlUtils.getIsolatedTestRoot(),
WebLayerBrowserTestsApplication.PRIVATE_DATA_DIRECTORY_SUFFIX);
}
@Override
/**
* Ensure that the user data directory gets overridden to getPrivateDataDirectory() (which is
* cleared at the start of every run); the directory that ANDROID_APP_DATA_DIR is set to in the
* context of Java browsertests is not cleared as it also holds persistent state, which
* causes test failures due to state bleedthrough. See crbug.com/617734 for details.
*/
protected String getUserDataDirectoryCommandLineSwitch() {
return "webengine-user-data-dir";
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/src/org/chromium/weblayer_browsertests_apk/WebLayerBrowserTestsActivity.java | Java | unknown | 2,662 |
// 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_browsertests_apk;
import android.content.Context;
import org.chromium.base.ContextUtils;
import org.chromium.base.PathUtils;
import org.chromium.components.embedder_support.application.ClassLoaderContextWrapperFactory;
import org.chromium.native_test.NativeBrowserTestApplication;
/**
* A basic weblayer_public.browser.tests {@link android.app.Application}.
*/
public class WebLayerBrowserTestsApplication extends NativeBrowserTestApplication {
static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "weblayer_shell";
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
if (isBrowserProcess()) {
// Test-only stuff, see also NativeUnitTest.java.
PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX);
}
}
@Override
protected void setLibraryProcessType() {}
@Override
protected void initApplicationContext() {
// Matches the initApplicationContext call in WebLayerImpl.minimalInitForContext.
ContextUtils.initApplicationContext(ClassLoaderContextWrapperFactory.get(this));
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/src/org/chromium/weblayer_browsertests_apk/WebLayerBrowserTestsApplication.java | Java | unknown | 1,311 |
// 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_private;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* Bridge for setup of AccessTokenFetch browsertests from native.
*/
@JNINamespace("weblayer")
public class AccessTokenFetchTestBridge {
AccessTokenFetchTestBridge() {}
// Installs a GoogleAccountAccessTokenFetcherTestStub on |profile|. Returns the instance for
// use by the test invoking this method.
@CalledByNative
private static GoogleAccountAccessTokenFetcherTestStub
installGoogleAccountAccessTokenFetcherTestStub(ProfileImpl profile) {
GoogleAccountAccessTokenFetcherTestStub testClient =
new GoogleAccountAccessTokenFetcherTestStub();
profile.setGoogleAccountAccessTokenFetcherClient(testClient);
return testClient;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/src/org/chromium/weblayer_private/AccessTokenFetchTestBridge.java | Java | unknown | 993 |
// 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_private;
import android.webkit.ValueCallback;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.weblayer_private.interfaces.IGoogleAccountAccessTokenFetcherClient;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Implementation of IGoogleAccountAccessTokenFetcherClient that saves requests made from the
* WebLayer implementation for introspection by tests and/or responses directed by tests.
*/
@JNINamespace("weblayer")
public class GoogleAccountAccessTokenFetcherTestStub
extends IGoogleAccountAccessTokenFetcherClient.Stub {
private HashMap<Integer, ValueCallback<String>> mOutstandingRequests =
new HashMap<Integer, ValueCallback<String>>();
private int mMostRecentRequestId;
private Set<String> mMostRecentScopes;
private Set<String> mScopesForMostRecentInvalidToken = new HashSet<String>();
private String mMostRecentInvalidToken = "";
@Override
public void fetchAccessToken(
IObjectWrapper scopesWrapper, IObjectWrapper onTokenFetchedWrapper) {
Set<String> scopes = ObjectWrapper.unwrap(scopesWrapper, Set.class);
ValueCallback<String> valueCallback =
ObjectWrapper.unwrap(onTokenFetchedWrapper, ValueCallback.class);
mMostRecentScopes = scopes;
mMostRecentRequestId++;
mOutstandingRequests.put(mMostRecentRequestId, valueCallback);
}
@Override
public void onAccessTokenIdentifiedAsInvalid(
IObjectWrapper scopesWrapper, IObjectWrapper tokenWrapper) {
Set<String> scopes = ObjectWrapper.unwrap(scopesWrapper, Set.class);
String token = ObjectWrapper.unwrap(tokenWrapper, String.class);
mScopesForMostRecentInvalidToken = scopes;
mMostRecentInvalidToken = token;
}
@CalledByNative
int getMostRecentRequestId() {
return mMostRecentRequestId;
}
@CalledByNative
String[] getMostRecentRequestScopes() {
return mMostRecentScopes.toArray(new String[0]);
}
@CalledByNative
int getNumOutstandingRequests() {
return mOutstandingRequests.size();
}
@CalledByNative
String[] getScopesForMostRecentInvalidToken() {
return mScopesForMostRecentInvalidToken.toArray(new String[0]);
}
@CalledByNative
String getMostRecentInvalidToken() {
return mMostRecentInvalidToken;
}
@CalledByNative
public void respondWithTokenForRequest(int requestId, String token) {
ValueCallback<String> callback = mOutstandingRequests.get(requestId);
assert callback != null;
mOutstandingRequests.remove(requestId);
callback.onReceiveValue(token);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/src/org/chromium/weblayer_private/GoogleAccountAccessTokenFetcherTestStub.java | Java | unknown | 3,063 |
// 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_private;
import android.content.Context;
import android.text.TextUtils;
import org.chromium.base.Callback;
import org.chromium.base.ContextUtils;
import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer.TestProfile;
import org.chromium.weblayer.TestWebLayer;
import org.chromium.weblayer.WebLayer;
/**
* Helper for metrics_browsertest.cc
*/
@JNINamespace("weblayer")
class MetricsTestHelper {
private static class TestGmsBridge extends GmsBridge {
private final @ConsentType int mConsentType;
private Callback<Boolean> mConsentCallback;
public static TestGmsBridge sInstance;
public TestGmsBridge(@ConsentType int consentType) {
sInstance = this;
mConsentType = consentType;
}
@Override
public boolean canUseGms() {
return true;
}
@Override
public void setSafeBrowsingHandler() {
// We don't have this specialized service here.
}
@Override
public void queryMetricsSetting(Callback<Boolean> callback) {
ThreadUtils.assertOnUiThread();
if (mConsentType == ConsentType.DELAY_CONSENT) {
mConsentCallback = callback;
} else {
callback.onResult(mConsentType == ConsentType.CONSENT);
}
}
@Override
public void logMetrics(byte[] data) {
MetricsTestHelperJni.get().onLogMetrics(data);
}
}
@CalledByNative
private static void installTestGmsBridge(@ConsentType int consentType) {
GmsBridge.injectInstance(new TestGmsBridge(consentType));
}
@CalledByNative
private static void runConsentCallback(boolean hasConsent) {
assert TestGmsBridge.sInstance != null;
assert TestGmsBridge.sInstance.mConsentCallback != null;
TestGmsBridge.sInstance.mConsentCallback.onResult(hasConsent);
}
@CalledByNative
private static void createProfile(String name, boolean incognito) {
Context appContext = ContextUtils.getApplicationContext();
WebLayer weblayer = TestWebLayer.loadSync(appContext);
if (incognito) {
String nameOrNull = null;
if (!TextUtils.isEmpty(name)) nameOrNull = name;
weblayer.getIncognitoProfile(nameOrNull);
} else {
weblayer.getProfile(name);
}
}
@CalledByNative
private static void destroyProfile(String name, boolean incognito) {
Context appContext = ContextUtils.getApplicationContext();
WebLayer weblayer = TestWebLayer.loadSync(appContext);
if (incognito) {
String nameOrNull = null;
if (!TextUtils.isEmpty(name)) nameOrNull = name;
TestProfile.destroy(weblayer.getIncognitoProfile(nameOrNull));
} else {
TestProfile.destroy(weblayer.getProfile(name));
}
}
@CalledByNative
private static void removeTestGmsBridge() {
GmsBridge.injectInstance(null);
}
@NativeMethods
interface Natives {
void onLogMetrics(byte[] data);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/src/org/chromium/weblayer_private/MetricsTestHelper.java | Java | unknown | 3,458 |
// 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_private;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.components.translate.TranslateMenu;
/**
* Bridge for TranslateCompactInfoBar test methods invoked from native.
*/
@JNINamespace("weblayer")
public class TranslateTestBridge {
TranslateTestBridge() {}
// Selects the tab corresponding to |actionType| to simulate the user pressing on this tab.
@CalledByNative
private static void selectTab(TranslateCompactInfoBar infobar, int actionType) {
infobar.selectTabForTesting(actionType);
}
@CalledByNative
// Simulates a click of the overflow menu item for "never translate this language."
private static void clickNeverTranslateLanguageMenuItem(TranslateCompactInfoBar infobar) {
infobar.onOverflowMenuItemClicked(TranslateMenu.ID_OVERFLOW_NEVER_LANGUAGE);
}
@CalledByNative
// Simulates a click of the overflow menu item for "never translate this site."
private static void clickNeverTranslateSiteMenuItem(TranslateCompactInfoBar infobar) {
infobar.onOverflowMenuItemClicked(TranslateMenu.ID_OVERFLOW_NEVER_SITE);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/src/org/chromium/weblayer_private/TranslateTestBridge.java | Java | unknown | 1,352 |
// 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.
#include "weblayer/shell/android/browsertests_apk/translate_test_bridge.h"
#include "base/android/jni_android.h"
#include "weblayer/test/weblayer_browsertests_jni/TranslateTestBridge_jni.h"
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
// static
void TranslateTestBridge::SelectButton(
TranslateCompactInfoBar* infobar,
TranslateCompactInfoBar::ActionType action_type) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_TranslateTestBridge_selectTab(env, infobar->GetJavaInfoBar(),
action_type);
}
// static
void TranslateTestBridge::ClickOverflowMenuItem(
TranslateCompactInfoBar* infobar,
OverflowMenuItemId item_id) {
JNIEnv* env = base::android::AttachCurrentThread();
switch (item_id) {
case OverflowMenuItemId::NEVER_TRANSLATE_LANGUAGE:
Java_TranslateTestBridge_clickNeverTranslateLanguageMenuItem(
env, infobar->GetJavaInfoBar());
return;
case OverflowMenuItemId::NEVER_TRANSLATE_SITE:
Java_TranslateTestBridge_clickNeverTranslateSiteMenuItem(
env, infobar->GetJavaInfoBar());
return;
}
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/translate_test_bridge.cc | C++ | unknown | 1,345 |
// 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_SHELL_ANDROID_BROWSERTESTS_APK_TRANSLATE_TEST_BRIDGE_H_
#define WEBLAYER_SHELL_ANDROID_BROWSERTESTS_APK_TRANSLATE_TEST_BRIDGE_H_
#include "weblayer/browser/translate_compact_infobar.h"
namespace weblayer {
// Bridge to support translate_browsertest.cc to calling into Java.
class TranslateTestBridge {
public:
TranslateTestBridge();
~TranslateTestBridge();
TranslateTestBridge(const TranslateTestBridge&) = delete;
TranslateTestBridge& operator=(const TranslateTestBridge&) = delete;
enum class OverflowMenuItemId {
NEVER_TRANSLATE_LANGUAGE = 0,
NEVER_TRANSLATE_SITE = 1,
};
// Instructs the Java infobar to select the button corresponding to
// |action_type|.
static void SelectButton(TranslateCompactInfoBar* infobar,
TranslateCompactInfoBar::ActionType action_type);
// Instructs the Java infobar to click the specified overflow menu item.
static void ClickOverflowMenuItem(TranslateCompactInfoBar* infobar,
OverflowMenuItemId item_id);
};
} // namespace weblayer
#endif // WEBLAYER_SHELL_ANDROID_BROWSERTESTS_APK_TRANSLATE_TEST_BRIDGE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/translate_test_bridge.h | C++ | unknown | 1,308 |
// 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.
#include <memory>
#include "base/android/jni_android.h"
#include "base/android/library_loader/library_loader_hooks.h"
#include "base/functional/bind.h"
#include "base/message_loop/message_pump.h"
#include "content/public/app/content_jni_onload.h"
#include "content/public/app/content_main.h"
#include "content/public/test/nested_message_pump_android.h"
#include "testing/android/native_test/native_test_launcher.h"
#include "weblayer/app/content_main_delegate_impl.h"
#include "weblayer/shell/app/shell_main_params.h"
// This is called by the VM when the shared library is first loaded.
JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
base::android::InitVM(vm);
if (!content::android::OnJNIOnLoadInit())
return -1;
// This needs to be done before base::TestSuite::Initialize() is called,
// as it also tries to set MessagePumpForUIFactory.
base::MessagePump::OverrideMessagePumpForUIFactory(
[]() -> std::unique_ptr<base::MessagePump> {
return std::make_unique<content::NestedMessagePumpAndroid>();
});
content::SetContentMainDelegate(
new weblayer::ContentMainDelegateImpl(weblayer::CreateMainParams()));
return JNI_VERSION_1_4;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/browsertests_apk/weblayer_browser_tests_jni_onload.cc | C++ | unknown | 1,333 |
// 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.shell;
import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.base.Log;
import org.chromium.webengine.Navigation;
import org.chromium.webengine.NavigationObserver;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabListObserver;
import org.chromium.webengine.TabObserver;
import org.chromium.webengine.WebEngine;
/**
* Default observers for Test Activities.
*/
public class DefaultObservers implements TabListObserver, TabObserver, NavigationObserver {
private static final String TAG = "WEDefaultObservers";
// TabObserver implementation.
@Override
public void onVisibleUriChanged(@NonNull Tab tab, @NonNull String uri) {
Log.i(TAG, this + "received Tab Event: 'onVisibleUriChanged(" + uri + ")'");
}
@Override
public void onTitleUpdated(@NonNull Tab tab, @NonNull String title) {
Log.i(TAG, this + "received Tab Event: 'onTitleUpdated(" + title + ")'");
}
@Override
public void onRenderProcessGone(@NonNull Tab tab) {
Log.i(TAG, this + "received Tab Event: 'onRenderProcessGone()'");
}
@Override
public void onFaviconChanged(@NonNull Tab tab, @Nullable Bitmap favicon) {
Log.i(TAG,
this + "received Tab Event: 'onFaviconChanged("
+ (favicon == null ? "null" : favicon.toString()) + ")'");
}
// NavigationObserver implementation.
@Override
public void onNavigationFailed(@NonNull Tab tab, @NonNull Navigation navigation) {
Log.i(TAG, this + "received NavigationEvent: 'onNavigationFailed()';");
Log.i(TAG,
this + "Navigation: url:" + navigation.getUri()
+ ", HTTP-StatusCode: " + navigation.getStatusCode()
+ ", samePage: " + navigation.isSameDocument());
}
@Override
public void onNavigationCompleted(@NonNull Tab tab, @NonNull Navigation navigation) {
Log.i(TAG, this + "received NavigationEvent: 'onNavigationCompleted()';");
Log.i(TAG,
this + "Navigation: url:" + navigation.getUri()
+ ", HTTP-StatusCode: " + navigation.getStatusCode()
+ ", samePage: " + navigation.isSameDocument());
}
@Override
public void onNavigationStarted(@NonNull Tab tab, @NonNull Navigation navigation) {
Log.i(TAG, this + "received NavigationEvent: 'onNavigationStarted()';");
}
@Override
public void onNavigationRedirected(@NonNull Tab tab, @NonNull Navigation navigation) {
Log.i(TAG, this + "received NavigationEvent: 'onNavigationRedirected()';");
}
@Override
public void onLoadProgressChanged(@NonNull Tab tab, double progress) {
Log.i(TAG, this + "received NavigationEvent: 'onLoadProgressChanged()';");
}
// TabListObserver implementation.
@Override
public void onActiveTabChanged(@NonNull WebEngine webEngine, @Nullable Tab activeTab) {
Log.i(TAG, this + "received TabList Event: 'onActiveTabChanged'-event");
}
@Override
public void onTabAdded(@NonNull WebEngine webEngine, @NonNull Tab tab) {
Log.i(TAG, this + "received TabList Event: 'onTabAdded'-event");
// Recursively add tab and navigation observers to any new tab.
tab.registerTabObserver(this);
tab.getNavigationController().registerNavigationObserver(this);
}
@Override
public void onTabRemoved(@NonNull WebEngine webEngine, @NonNull Tab tab) {
Log.i(TAG, this + "received TabList Event: 'onTabRemoved'-event");
}
@Override
public void onWillDestroyFragmentAndAllTabs(@NonNull WebEngine webEngine) {
Log.i(TAG, this + "received TabList Event: 'onWillDestroyFragmentAndAllTabs'-event");
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/webengine_shell_apk/src/org/chromium/webengine/shell/DefaultObservers.java | Java | unknown | 4,010 |
// 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.shell;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.Spinner;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabManager;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
/**
* Activity for testing navigations and state resumption.
*/
public class WebEngineNavigationTestActivity extends AppCompatActivity {
private static final String TAG = "WebEngineShell";
private static final String WEB_ENGINE_TAG = "WEB_ENGINE_TAG";
private Context mContext;
private WebSandbox mWebSandbox;
private DefaultObservers mDefaultObservers = new DefaultObservers();
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_test);
mContext = getApplicationContext();
WebEngineShellActivity.setupActivitySpinner(
(Spinner) findViewById(R.id.activity_nav), this, 2);
ListenableFuture<WebSandbox> webSandboxFuture = WebSandbox.create(mContext);
Futures.addCallback(webSandboxFuture, new FutureCallback<WebSandbox>() {
@Override
public void onSuccess(WebSandbox webSandbox) {
onWebSandboxReady(webSandbox, savedInstanceState);
}
@Override
public void onFailure(Throwable thrown) {}
}, ContextCompat.getMainExecutor(mContext));
Button openActivityButton = (Button) findViewById(R.id.open_activity);
openActivityButton.setOnClickListener(
(View v) -> { super.startActivity(new Intent(this, EmptyActivity.class)); });
Button replaceFragmentButton = (Button) findViewById(R.id.replace_fragment);
replaceFragmentButton.setOnClickListener((View v) -> {
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragment_container_view, new EmptyFragment())
.addToBackStack(null)
.commit();
});
}
@Override
public void startActivity(Intent intent) {
if (mWebSandbox != null) {
// Shutdown sandbox before another activity is opened.
mWebSandbox.shutdown();
mWebSandbox = null;
}
super.startActivity(intent);
}
private void onWebSandboxReady(WebSandbox webSandbox, Bundle savedInstanceState) {
mWebSandbox = webSandbox;
webSandbox.setRemoteDebuggingEnabled(true);
WebEngine webEngine = webSandbox.getWebEngine(WEB_ENGINE_TAG);
if (webEngine != null) {
assert webSandbox.getWebEngines().size() == 1;
return;
}
ListenableFuture<WebEngine> webEngineFuture = webSandbox.createWebEngine(WEB_ENGINE_TAG);
Futures.addCallback(webEngineFuture, new FutureCallback<WebEngine>() {
@Override
public void onSuccess(WebEngine webEngine) {
onWebEngineReady(webEngine);
}
@Override
public void onFailure(Throwable thrown) {}
}, ContextCompat.getMainExecutor(mContext));
}
private void onWebEngineReady(WebEngine webEngine) {
TabManager tabManager = webEngine.getTabManager();
Tab activeTab = tabManager.getActiveTab();
activeTab.getNavigationController().navigate("https://google.com");
activeTab.registerTabObserver(mDefaultObservers);
activeTab.getNavigationController().registerNavigationObserver(mDefaultObservers);
tabManager.registerTabListObserver(mDefaultObservers);
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragment_container_view, webEngine.getFragment())
.commit();
}
/**
* Empty Activity used to test back navigation to an Activity containing a WebFragment.
*/
public static class EmptyActivity extends AppCompatActivity {}
/**
* Empty Fragment used to test back navigation to a WebFragment.
*/
public static class EmptyFragment extends Fragment {
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = new View(getActivity());
v.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
v.setBackgroundColor(Color.parseColor("#f1f1f1"));
return v;
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/webengine_shell_apk/src/org/chromium/webengine/shell/WebEngineNavigationTestActivity.java | Java | unknown | 5,335 |
// 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.shell;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.base.Log;
import org.chromium.webengine.CookieManager;
import org.chromium.webengine.FullscreenCallback;
import org.chromium.webengine.FullscreenClient;
import org.chromium.webengine.Navigation;
import org.chromium.webengine.NavigationObserver;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabListObserver;
import org.chromium.webengine.TabManager;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebFragment;
import org.chromium.webengine.WebSandbox;
import org.chromium.webengine.shell.topbar.CustomSpinner;
import org.chromium.webengine.shell.topbar.TabEventsDelegate;
import org.chromium.webengine.shell.topbar.TabEventsObserver;
import java.util.Arrays;
/**
* Activity for managing the Demo Shell.
*
* TODO(swestphal):
* - UI to add/remove tabs
* - Expose some tab/navigation events in the UI
* - Move cookie test to manual-test activity
* - Move registerWebMessageCallback to manual-test activity
*/
public class WebEngineShellActivity
extends AppCompatActivity implements FullscreenCallback, TabEventsObserver {
private static final String TAG = "WebEngineShell";
private static final String WEB_FRAGMENT_TAG = "WEB_FRAGMENT_TAG";
private WebEngineShellApplication mApplication;
private Context mContext;
private TabManager mTabManager;
private TabEventsDelegate mTabEventsDelegate;
private ProgressBar mProgressBar;
private EditText mUrlBar;
private Button mTabCountButton;
private CustomSpinner mTabListSpinner;
private ArrayAdapter<TabWrapper> mTabListAdapter;
private ImageButton mReloadButton;
private Drawable mRefreshDrawable;
private Drawable mStopDrawable;
private DefaultObservers mDefaultObservers;
private int mSystemVisibilityToRestore;
private boolean mIsTabListOpen;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mIsTabListOpen = savedInstanceState.getBoolean("isTabListOpen");
}
setContentView(R.layout.main);
mApplication = (WebEngineShellApplication) getApplication();
mContext = getApplicationContext();
mDefaultObservers = new DefaultObservers();
setupActivitySpinner((Spinner) findViewById(R.id.activity_nav), this, 0);
mProgressBar = findViewById(R.id.progress_bar);
mUrlBar = findViewById(R.id.url_bar);
mTabCountButton = findViewById(R.id.tab_count);
mTabListSpinner = findViewById(R.id.tab_list);
mReloadButton = findViewById(R.id.reload_button);
mRefreshDrawable = getDrawable(R.drawable.ic_refresh);
mStopDrawable = getDrawable(R.drawable.ic_stop);
setProgress(1.0);
mUrlBar.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Uri query = Uri.parse(v.getText().toString());
if (query.isAbsolute()) {
mTabManager.getActiveTab().getNavigationController().navigate(
query.normalizeScheme().toString());
} else if (Patterns.DOMAIN_NAME.matcher(query.toString()).matches()) {
mTabManager.getActiveTab().getNavigationController().navigate(
"https://" + query);
} else {
mTabManager.getActiveTab().getNavigationController().navigate(
"https://www.google.com/search?q="
+ Uri.encode(v.getText().toString()));
}
// Hides keyboard on Enter key pressed
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return true;
}
});
mReloadButton.setOnClickListener(v -> {
if (mReloadButton.getDrawable().equals(mRefreshDrawable)) {
mTabManager.getActiveTab().getNavigationController().reload();
} else if (mReloadButton.getDrawable().equals(mStopDrawable)) {
mTabManager.getActiveTab().getNavigationController().stop();
}
});
mTabCountButton.setOnClickListener(v -> mTabListSpinner.performClick());
mTabListSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
mTabListAdapter.getItem(pos).getTab().setActive();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
ListenableFuture<String> sandboxVersionFuture = WebSandbox.getVersion(mContext);
Futures.addCallback(sandboxVersionFuture, new FutureCallback<String>() {
@Override
public void onSuccess(String version) {
((TextView) findViewById(R.id.version)).setText(version);
}
@Override
public void onFailure(Throwable thrown) {}
}, ContextCompat.getMainExecutor(mContext));
Futures.addCallback(mApplication.getWebEngine(), new FutureCallback<WebEngine>() {
@Override
public void onSuccess(WebEngine webEngine) {
onWebEngineReady(webEngine);
}
@Override
public void onFailure(Throwable thrown) {
Toast.makeText(mContext, "Failed to start WebEngine.", Toast.LENGTH_LONG).show();
}
}, ContextCompat.getMainExecutor(mContext));
Futures.addCallback(
mApplication.getTabEventsDelegate(), new FutureCallback<TabEventsDelegate>() {
@Override
public void onSuccess(TabEventsDelegate tabEventsDelegate) {
mTabEventsDelegate = tabEventsDelegate;
tabEventsDelegate.registerObserver(WebEngineShellActivity.this);
}
@Override
public void onFailure(Throwable thrown) {}
}, ContextCompat.getMainExecutor(mContext));
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isTabListOpen", mTabListSpinner.isOpen());
super.onSaveInstanceState(outState);
}
@Override
public void onDestroy() {
super.onDestroy();
if (mTabManager == null) return;
for (Tab tab : mTabManager.getAllTabs()) {
tab.setFullscreenCallback(null);
}
if (mTabEventsDelegate != null) mTabEventsDelegate.unregisterObserver();
}
@Override
public void onBackPressed() {
WebFragment fragment =
(WebFragment) getSupportFragmentManager().findFragmentByTag(WEB_FRAGMENT_TAG);
if (fragment == null) {
super.onBackPressed();
return;
}
ListenableFuture<Boolean> tryNavigateBackFuture = fragment.getWebEngine().tryNavigateBack();
Futures.addCallback(tryNavigateBackFuture, new FutureCallback<Boolean>() {
@Override
public void onSuccess(Boolean didNavigate) {
if (!didNavigate) {
WebEngineShellActivity.super.onBackPressed();
}
}
@Override
public void onFailure(Throwable thrown) {
WebEngineShellActivity.super.onBackPressed();
}
}, ContextCompat.getMainExecutor(mContext));
}
// TODO(swestphal): Move this to a helper class.
static void setupActivitySpinner(Spinner spinner, Activity activity, int index) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity,
R.array.activities_drop_down, android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(index, false);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
final Intent intent;
switch (pos) {
case 0:
intent = new Intent(activity, WebEngineShellActivity.class);
break;
case 1:
intent = new Intent(activity, WebEngineStateTestActivity.class);
break;
case 2:
intent = new Intent(activity, WebEngineNavigationTestActivity.class);
break;
default:
assert false : "Unhandled item: " + String.valueOf(pos);
intent = null;
}
activity.startActivity(intent);
activity.finish();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
}
@Override
public void onEnterFullscreen(WebEngine webEngine, Tab tab, FullscreenClient fullscreenClient) {
final WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
getWindow().setAttributes(attrs);
findViewById(R.id.activity_nav).setVisibility(View.GONE);
findViewById(R.id.version).setVisibility(View.GONE);
findViewById(R.id.app_bar).setVisibility(View.GONE);
findViewById(R.id.progress_bar).setVisibility(View.GONE);
View decorView = getWindow().getDecorView();
mSystemVisibilityToRestore = decorView.getSystemUiVisibility();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
| View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
@Override
public void onExitFullscreen(WebEngine webEngine, Tab tab) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(mSystemVisibilityToRestore);
findViewById(R.id.activity_nav).setVisibility(View.VISIBLE);
findViewById(R.id.version).setVisibility(View.VISIBLE);
findViewById(R.id.app_bar).setVisibility(View.VISIBLE);
findViewById(R.id.progress_bar).setVisibility(View.VISIBLE);
final WindowManager.LayoutParams attrs = getWindow().getAttributes();
if ((attrs.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) {
attrs.flags &= ~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
getWindow().setAttributes(attrs);
}
}
private void onWebEngineReady(WebEngine webEngine) {
mTabManager = webEngine.getTabManager();
CookieManager cookieManager = webEngine.getCookieManager();
Tab activeTab = mTabManager.getActiveTab();
mTabCountButton.setText(String.valueOf(getTabsCount()));
mTabListAdapter = new ArrayAdapter<TabWrapper>(
mContext, android.R.layout.simple_spinner_dropdown_item);
mTabListSpinner.setAdapter(mTabListAdapter);
for (Tab t : mTabManager.getAllTabs()) {
TabWrapper tabWrapper = new TabWrapper(t);
mTabListAdapter.add(tabWrapper);
if (t.equals(mTabManager.getActiveTab())) {
mTabListSpinner.setSelection(mTabListAdapter.getPosition(tabWrapper));
}
}
if (mIsTabListOpen) {
mTabListSpinner.performClick();
}
for (Tab tab : mTabManager.getAllTabs()) {
tab.setFullscreenCallback(WebEngineShellActivity.this);
}
if (activeTab.getDisplayUri().toString().equals("")) {
mTabManager.registerTabListObserver(new TabListObserver() {
@Override
public void onTabAdded(@NonNull WebEngine webEngine, @NonNull Tab tab) {
tab.setFullscreenCallback(WebEngineShellActivity.this);
}
});
activeTab.registerTabObserver(mDefaultObservers);
activeTab.getNavigationController().registerNavigationObserver(mDefaultObservers);
activeTab.getNavigationController().registerNavigationObserver(
new NavigationObserver() {
@Override
public void onNavigationCompleted(
@NonNull Tab tab, @NonNull Navigation navigation) {
ListenableFuture<String> scriptResultFuture =
activeTab.executeScript("1+1", true);
Futures.addCallback(scriptResultFuture, new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
Log.w(TAG, "executeScript result: " + result);
}
@Override
public void onFailure(Throwable thrown) {
Log.w(TAG, "executeScript failed: " + thrown);
}
}, ContextCompat.getMainExecutor(mContext));
}
});
activeTab.getNavigationController().navigate("https://google.com");
activeTab.addMessageEventListener((Tab source, String message) -> {
Log.w(TAG, "Received post message from web content: " + message);
}, Arrays.asList("*"));
activeTab.postMessage("Hello!", "*");
ListenableFuture<Void> setCookieFuture =
cookieManager.setCookie("https://sadchonks.com", "foo=bar123");
Futures.addCallback(setCookieFuture, new FutureCallback<Void>() {
@Override
public void onSuccess(Void v) {
ListenableFuture<String> cookieFuture =
cookieManager.getCookie("https://sadchonks.com");
Futures.addCallback(cookieFuture, new FutureCallback<String>() {
@Override
public void onSuccess(String value) {
Log.w(TAG, "cookie: " + value);
}
@Override
public void onFailure(Throwable thrown) {}
}, ContextCompat.getMainExecutor(mContext));
}
@Override
public void onFailure(Throwable thrown) {
Log.w(TAG, "setCookie failed: " + thrown);
}
}, ContextCompat.getMainExecutor(mContext));
}
if (getSupportFragmentManager().findFragmentByTag(WEB_FRAGMENT_TAG) == null) {
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragment_container_view, webEngine.getFragment(), WEB_FRAGMENT_TAG)
.commit();
}
}
int getTabsCount() {
if (mTabManager == null) {
return 0;
}
return mTabManager.getAllTabs().size();
}
void setProgress(double progress) {
int progressValue = (int) Math.rint(progress * 100);
if (progressValue != mProgressBar.getMax()) {
mReloadButton.setImageDrawable(mStopDrawable);
mProgressBar.setVisibility(View.VISIBLE);
} else {
mReloadButton.setImageDrawable(mRefreshDrawable);
mProgressBar.setVisibility(View.INVISIBLE);
}
mProgressBar.setProgress(progressValue);
}
@Override
public void onVisibleUriChanged(String uri) {
mUrlBar.setText(uri);
}
@Override
public void onActiveTabChanged(Tab activeTab) {
mUrlBar.setText(activeTab.getDisplayUri().toString());
for (int position = 0; position < mTabListAdapter.getCount(); ++position) {
TabWrapper tabWrapper = mTabListAdapter.getItem(position);
if (tabWrapper.getTab().equals(activeTab)) {
mTabListSpinner.setSelection(position);
return;
}
}
}
@Override
public void onTabAdded(Tab tab) {
mTabCountButton.setText(String.valueOf(getTabsCount()));
mTabListAdapter.add(new TabWrapper(tab));
}
@Override
public void onTabRemoved(Tab tab) {
mTabCountButton.setText(String.valueOf(getTabsCount()));
for (int position = 0; position < mTabListAdapter.getCount(); ++position) {
TabWrapper tabAdapter = mTabListAdapter.getItem(position);
if (tabAdapter.getTab().equals(tab)) {
mTabListAdapter.remove(tabAdapter);
return;
}
}
}
@Override
public void onLoadProgressChanged(double progress) {
setProgress(progress);
}
static class TabWrapper {
final Tab mTab;
public TabWrapper(Tab tab) {
mTab = tab;
}
public Tab getTab() {
return mTab;
}
@NonNull
@Override
public String toString() {
return mTab.getDisplayUri().getAuthority() + mTab.getDisplayUri().getPath();
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/webengine_shell_apk/src/org/chromium/webengine/shell/WebEngineShellActivity.java | Java | unknown | 19,051 |
// 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.shell;
import android.app.Application;
import androidx.core.content.ContextCompat;
import com.google.common.base.Function;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import org.chromium.webengine.shell.topbar.TabEventsDelegate;
/**
* Application for managing WebSandbox and WebEngine in the Demo Shell.
*/
public class WebEngineShellApplication extends Application {
private ListenableFuture<WebEngine> mWebEngineFuture;
private ListenableFuture<TabEventsDelegate> mTabEventsDelegateFuture;
private TabEventsDelegate mTabEventsDelegate;
public ListenableFuture<WebEngine> getWebEngine() {
return mWebEngineFuture;
}
public ListenableFuture<TabEventsDelegate> getTabEventsDelegate() {
if (mTabEventsDelegate != null) {
return Futures.immediateFuture(mTabEventsDelegate);
}
if (mTabEventsDelegateFuture != null) {
return mTabEventsDelegateFuture;
}
Function<WebEngine, TabEventsDelegate> getTabEventsDelegateTask =
webEngine -> new TabEventsDelegate(webEngine.getTabManager());
mTabEventsDelegateFuture = Futures.transform(
getWebEngine(), getTabEventsDelegateTask, ContextCompat.getMainExecutor(this));
return mTabEventsDelegateFuture;
}
@Override
public void onCreate() {
super.onCreate();
AsyncFunction<WebSandbox, WebEngine> getWebEngineTask =
webSandbox -> webSandbox.createWebEngine("shell-engine");
mWebEngineFuture = Futures.transformAsync(
WebSandbox.create(this), getWebEngineTask, ContextCompat.getMainExecutor(this));
Futures.addCallback(mWebEngineFuture, new FutureCallback<WebEngine>() {
@Override
public void onSuccess(WebEngine webEngine) {
mTabEventsDelegate = new TabEventsDelegate(webEngine.getTabManager());
}
@Override
public void onFailure(Throwable thrown) {}
}, ContextCompat.getMainExecutor(this));
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/webengine_shell_apk/src/org/chromium/webengine/shell/WebEngineShellApplication.java | Java | unknown | 2,487 |
// 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.shell;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.base.Log;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabListObserver;
import org.chromium.webengine.TabManager;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import java.util.List;
import java.util.Set;
/**
* Activity for managing the Demo Shell.
*/
public class WebEngineStateTestActivity extends AppCompatActivity {
private static final String TAG = "WebEngineShell";
private static final String WEB_ENGINE_TAG = "WEB_ENGINE_TAG";
private Context mContext;
private WebSandbox mWebSandbox;
private DefaultObservers mDefaultObservers = new DefaultObservers();
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.state_test);
mContext = getApplicationContext();
setSandboxStateText(false);
setEngineStateText(false);
setNumberOfTabsText(0);
setVisibilityText(false);
WebEngineShellActivity.setupActivitySpinner(
(Spinner) findViewById(R.id.activity_nav), this, 1);
final Button startSandboxButton = findViewById(R.id.start_sandbox);
startSandboxButton.setOnClickListener((View v) -> { startupSandbox(); });
final Button shutdownSandboxButton = findViewById(R.id.shutdown_sandbox);
shutdownSandboxButton.setOnClickListener((View v) -> {
boolean shutdown = shutdownSandbox();
Log.i(TAG, "Sandbox shutdown successful: " + shutdown);
});
final Button startEngineButton = findViewById(R.id.start_engine);
startEngineButton.setOnClickListener((View v) -> { startupWebEngine(); });
final Button shutdownEngineButton = findViewById(R.id.shutdown_engine);
shutdownEngineButton.setOnClickListener((View v) -> {
boolean closed = closeWebEngine();
Log.i(TAG, "WenEngine closed successfully: " + closed);
});
final Button openTabButton = findViewById(R.id.open_tab);
openTabButton.setOnClickListener(
(View v) -> { openNewTabAndNavigate("https://google.com"); });
final Button closeTabButton = findViewById(R.id.close_tab);
closeTabButton.setOnClickListener((View v) -> {
boolean closed = closeTab();
Log.i(TAG, "Closed tab successfully: " + closed);
});
final Button inflateFragmentButton = findViewById(R.id.inflate_fragment);
inflateFragmentButton.setOnClickListener((View v) -> {
boolean inflated = inflateFragment();
Log.i(TAG, "Fragment inflation successful: " + inflated);
});
final Button removeFragmentButton = findViewById(R.id.remove_fragment);
removeFragmentButton.setOnClickListener((View v) -> {
boolean removed = removeFragment();
Log.i(TAG, "Fragment removal successful: " + removed);
});
}
@Override
public void startActivity(Intent intent) {
if (mWebSandbox != null) {
// Shutdown sandbox before another activity is opened.
mWebSandbox.shutdown();
}
super.startActivity(intent);
}
@Override
public void onBackPressed() {
if (mWebSandbox != null) {
mWebSandbox.shutdown();
}
super.onBackPressed();
}
private void setNumberOfTabsText(int num) {
((TextView) findViewById(R.id.num_open_tabs)).setText("Tabs: (" + num + ")");
}
private void setSandboxStateText(boolean on) {
((TextView) findViewById(R.id.sandbox_state))
.setText("Sandbox: (" + (on ? "on" : "off") + ")");
}
private void setEngineStateText(boolean on) {
((TextView) findViewById(R.id.engine_state))
.setText("Engine: (" + (on ? "started" : "closed") + ")");
}
private void setVisibilityText(boolean visible) {
((TextView) findViewById(R.id.fragment_state))
.setText("Fragment: (" + (visible ? "visible" : "gone") + ")");
}
private void startupSandbox() {
ListenableFuture<WebSandbox> webSandboxFuture = WebSandbox.create(mContext);
Futures.addCallback(webSandboxFuture, new FutureCallback<WebSandbox>() {
@Override
public void onSuccess(WebSandbox webSandbox) {
onWebSandboxReady(webSandbox);
}
@Override
public void onFailure(Throwable thrown) {}
}, ContextCompat.getMainExecutor(mContext));
}
private void onWebSandboxReady(WebSandbox webSandbox) {
setSandboxStateText(true);
mWebSandbox = webSandbox;
webSandbox.setRemoteDebuggingEnabled(true);
WebEngine currentWebEngine = getCurrentWebEngine();
if (currentWebEngine != null) {
Log.i(TAG, "Sandbox and WebEngine already created");
return;
}
Log.i(TAG, "Sandbox ready");
startupWebEngine();
}
private void startupWebEngine() {
if (mWebSandbox == null) {
Log.w(TAG, "WebSandbox not started");
return;
}
WebEngine webEngine = getCurrentWebEngine();
if (webEngine != null) {
Log.w(TAG, "WebEngine already created");
return;
}
ListenableFuture<WebEngine> webEngineFuture = mWebSandbox.createWebEngine(WEB_ENGINE_TAG);
Futures.addCallback(webEngineFuture, new FutureCallback<WebEngine>() {
@Override
public void onSuccess(WebEngine webEngine) {
Log.i(TAG, "WebEngine started");
onWebEngineReady(webEngine);
}
@Override
public void onFailure(Throwable thrown) {}
}, ContextCompat.getMainExecutor(mContext));
}
private void onWebEngineReady(WebEngine webEngine) {
setEngineStateText(true);
TabManager tabManager = webEngine.getTabManager();
setNumberOfTabsText(tabManager.getAllTabs().size());
tabManager.registerTabListObserver(new TabListObserver() {
@Override
public void onTabAdded(@NonNull WebEngine webEngine, @NonNull Tab tab) {
setNumberOfTabsText(tabManager.getAllTabs().size());
// Recursively add tab and navigation observers to any new tab.
tab.registerTabObserver(mDefaultObservers);
tab.getNavigationController().registerNavigationObserver(mDefaultObservers);
}
@Override
public void onTabRemoved(@NonNull WebEngine webEngine, @NonNull Tab tab) {
setNumberOfTabsText(tabManager.getAllTabs().size());
}
@Override
public void onWillDestroyFragmentAndAllTabs(@NonNull WebEngine webEngine) {
setNumberOfTabsText(tabManager.getAllTabs().size());
}
});
Tab activeTab = tabManager.getActiveTab();
activeTab.registerTabObserver(mDefaultObservers);
activeTab.getNavigationController().registerNavigationObserver(mDefaultObservers);
tabManager.registerTabListObserver(mDefaultObservers);
activeTab.getNavigationController().navigate("https://www.google.com");
}
/**
* Tries to shutdown WebEngine and returns if succeeded.
*/
private boolean closeWebEngine() {
setEngineStateText(false);
setVisibilityText(false);
WebEngine webEngine = getCurrentWebEngine();
if (webEngine != null) {
webEngine.close();
return true;
}
return false;
}
/**
* Tries to shutdown the Sandbox and returns if succeeded.
*/
private boolean shutdownSandbox() {
if (mWebSandbox == null) return false;
mWebSandbox.shutdown();
setEngineStateText(false);
setSandboxStateText(false);
setVisibilityText(false);
return true;
}
private void openNewTabAndNavigate(String url) {
WebEngine webEngine = getCurrentWebEngine();
if (webEngine == null) {
Log.w(TAG, "No WebEngine created");
return;
}
ListenableFuture<Tab> newTabFuture = webEngine.getTabManager().createTab();
Futures.addCallback(newTabFuture, new FutureCallback<Tab>() {
@Override
public void onSuccess(Tab newTab) {
newTab.setActive();
newTab.getNavigationController().navigate(url);
Log.i(TAG, "Tab opened");
}
@Override
public void onFailure(Throwable thrown) {
Log.i(TAG, "Opening Tab failed");
}
}, ContextCompat.getMainExecutor(mContext));
}
private boolean closeTab() {
WebEngine webEngine = getCurrentWebEngine();
if (webEngine == null) return false;
Tab activeTab = webEngine.getTabManager().getActiveTab();
if (activeTab == null) return false;
activeTab.close();
Set<Tab> allTabs = webEngine.getTabManager().getAllTabs();
allTabs.remove(activeTab);
if (allTabs.size() > 0) {
allTabs.iterator().next().setActive();
}
return true;
}
// There could be more but we only have one in this test activity.
private WebEngine getCurrentWebEngine() {
if (mWebSandbox == null) return null;
WebEngine webEngine = mWebSandbox.getWebEngine(WEB_ENGINE_TAG);
if (webEngine != null) {
assert mWebSandbox.getWebEngines().size() == 1;
return webEngine;
}
return null;
}
/**
* Tries to inflate the fragment and returns if succeeded.
*/
private boolean inflateFragment() {
WebEngine webEngine = getCurrentWebEngine();
if (webEngine == null) {
Log.w(TAG, "no WebEngine created");
return false;
}
FragmentManager fragmentManager = getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if (fragments.size() > 1) {
throw new IllegalStateException("More than one fragment added, shouldn't happen");
}
if (fragments.size() == 1) {
// Fragment already inflated.
return false;
}
setVisibilityText(true);
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragment_container_view, webEngine.getFragment())
.commit();
return true;
}
/**
* Tries to remove the WebFragment and returns if succeeded.
*/
private boolean removeFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if (fragments.size() > 1) {
throw new IllegalStateException("More than one fragment added, shouldn't happen");
}
if (fragments.size() == 0) return false; // Fragment not inflated.
setVisibilityText(false);
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.remove(fragments.get(0))
.commit();
return true;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/webengine_shell_apk/src/org/chromium/webengine/shell/WebEngineStateTestActivity.java | Java | unknown | 12,165 |
// 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.shell.topbar;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Spinner;
/**
* A Spinner wrapper monitoring whether the dialog is open or closed.
*/
public class CustomSpinner extends Spinner {
private boolean mIsOpen;
public CustomSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean performClick() {
mIsOpen = true;
return super.performClick();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (isOpen() && hasFocus) {
performClose();
}
}
private void performClose() {
mIsOpen = false;
}
public boolean isOpen() {
return mIsOpen;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/webengine_shell_apk/src/org/chromium/webengine/shell/topbar/CustomSpinner.java | Java | unknown | 941 |
// 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.shell.topbar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.webengine.Navigation;
import org.chromium.webengine.NavigationObserver;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabListObserver;
import org.chromium.webengine.TabManager;
import org.chromium.webengine.TabObserver;
import org.chromium.webengine.WebEngine;
/**
* Delegate for Tab Events.
*/
public class TabEventsDelegate implements TabObserver, NavigationObserver, TabListObserver {
private TabEventsObserver mTabEventsObserver;
private final TabManager mTabManager;
public TabEventsDelegate(TabManager tabManager) {
mTabManager = tabManager;
mTabManager.registerTabListObserver(this);
for (Tab t : mTabManager.getAllTabs()) {
t.getNavigationController().registerNavigationObserver(this);
t.registerTabObserver(this);
}
}
public void registerObserver(TabEventsObserver tabEventsObserver) {
mTabEventsObserver = tabEventsObserver;
}
public void unregisterObserver() {
mTabEventsObserver = null;
}
// TabObserver implementation.
@Override
public void onVisibleUriChanged(@NonNull Tab tab, @NonNull String uri) {
if (mTabEventsObserver == null) {
return;
}
if (!isTabActive(tab)) {
return;
}
mTabEventsObserver.onVisibleUriChanged(uri);
}
@Override
public void onTitleUpdated(Tab tab, @NonNull String title) {}
@Override
public void onRenderProcessGone(Tab tab) {}
// TabListObserver implementation.
@Override
public void onActiveTabChanged(@NonNull WebEngine webEngine, @Nullable Tab activeTab) {
if (mTabEventsObserver == null) {
return;
}
if (activeTab == null) {
return;
}
mTabEventsObserver.onActiveTabChanged(activeTab);
}
@Override
public void onTabAdded(@NonNull WebEngine webEngine, @NonNull Tab tab) {
if (mTabEventsObserver == null) {
return;
}
mTabEventsObserver.onTabAdded(tab);
tab.registerTabObserver(this);
tab.getNavigationController().registerNavigationObserver(this);
}
@Override
public void onTabRemoved(@NonNull WebEngine webEngine, @NonNull Tab tab) {
if (mTabEventsObserver == null) {
return;
}
mTabEventsObserver.onTabRemoved(tab);
}
@Override
public void onWillDestroyFragmentAndAllTabs(@NonNull WebEngine webEngine) {}
// NavigationObserver implementation.
@Override
public void onNavigationFailed(@NonNull Tab tab, @NonNull Navigation navigation) {}
@Override
public void onNavigationCompleted(@NonNull Tab tab, @NonNull Navigation navigation) {}
@Override
public void onNavigationStarted(@NonNull Tab tab, @NonNull Navigation navigation) {}
@Override
public void onNavigationRedirected(@NonNull Tab tab, @NonNull Navigation navigation) {}
@Override
public void onLoadProgressChanged(@NonNull Tab tab, double progress) {
if (mTabEventsObserver == null) {
return;
}
if (!isTabActive(tab)) {
return;
}
mTabEventsObserver.onLoadProgressChanged(progress);
}
boolean isTabActive(Tab tab) {
return mTabManager.getActiveTab() != null && mTabManager.getActiveTab().equals(tab);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/webengine_shell_apk/src/org/chromium/webengine/shell/topbar/TabEventsDelegate.java | Java | unknown | 3,656 |
// 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.shell.topbar;
import org.chromium.webengine.Tab;
/**
* An interface for setting values in the Top Bar.
*/
public interface TabEventsObserver {
void onVisibleUriChanged(String uri);
void onActiveTabChanged(Tab activeTab);
void onTabAdded(Tab tab);
void onTabRemoved(Tab tab);
void onLoadProgressChanged(double progress);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/android/webengine_shell_apk/src/org/chromium/webengine/shell/topbar/TabEventsObserver.java | Java | unknown | 525 |
// 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.
#ifndef WEBLAYER_SHELL_APP_RESOURCE_H_
#define WEBLAYER_SHELL_APP_RESOURCE_H_
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by shell.rc
//
#define IDR_MAINFRAME 128
#define IDM_EXIT 105
#define IDM_CLOSE_WINDOW 106
#define IDM_NEW_WINDOW 107
#define IDC_WEBLAYERSHELL 109
#define IDD_ALERT 130
#define IDD_CONFIRM 131
#define IDD_PROMPT 132
#define IDC_NAV_BACK 1001
#define IDC_NAV_FORWARD 1002
#define IDC_NAV_RELOAD 1003
#define IDC_NAV_STOP 1004
#define IDC_PROMPTEDIT 1005
#define IDC_DIALOGTEXT 1006
#ifndef IDC_STATIC
#define IDC_STATIC -1
#endif
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 130
#define _APS_NEXT_RESOURCE_VALUE 129
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 117
#endif
#endif
#endif // WEBLAYER_SHELL_APP_RESOURCE_H_ | Zhao-PengFei35/chromium_src_4 | weblayer/shell/app/resource.h | C | unknown | 1,060 |
// 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.
#include "build/build_config.h"
#include "weblayer/public/main.h"
#include "weblayer/shell/app/shell_main_params.h"
#if BUILDFLAG(IS_WIN)
#if defined(WIN_CONSOLE_APP)
int main() {
return weblayer::Main(weblayer::CreateMainParams());
#else
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) {
return weblayer::Main(weblayer::CreateMainParams(), instance);
#endif
}
#else
int main(int argc, const char** argv) {
return weblayer::Main(weblayer::CreateMainParams(), argc, argv);
}
#endif // BUILDFLAG(IS_WIN)
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/app/shell_main.cc | C++ | unknown | 678 |
// 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.
#include "weblayer/shell/app/shell_main_params.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/callback.h"
#include "base/path_service.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "net/base/filename_util.h"
#include "url/gurl.h"
#include "weblayer/public/main.h"
#include "weblayer/public/profile.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/shell/common/shell_switches.h"
namespace weblayer {
namespace {
GURL GetStartupURL() {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kNoInitialNavigation))
return GURL();
#if BUILDFLAG(IS_ANDROID)
// Delay renderer creation on Android until surface is ready.
return GURL();
#else
const base::CommandLine::StringVector& args = command_line->GetArgs();
if (args.empty())
return GURL("https://www.google.com/");
#if BUILDFLAG(IS_WIN)
GURL url(base::WideToUTF16(args[0]));
#else
GURL url(args[0]);
#endif
if (url.is_valid() && url.has_scheme())
return url;
return net::FilePathToFileURL(
base::MakeAbsoluteFilePath(base::FilePath(args[0])));
#endif
}
class MainDelegateImpl : public MainDelegate {
public:
void PreMainMessageLoopRun() override {
// On Android the Profile is created and owned in Java via an
// embedder-specific call to WebLayer.createBrowserFragment().
#if !BUILDFLAG(IS_ANDROID)
InitializeProfile();
#endif
Shell::Initialize();
#if BUILDFLAG(IS_ANDROID)
Shell::CreateNewWindow(GetStartupURL(), gfx::Size());
#else
Shell::CreateNewWindow(profile_.get(), GetStartupURL(), gfx::Size());
#endif
}
void PostMainMessageLoopRun() override {
#if !BUILDFLAG(IS_ANDROID)
DestroyProfile();
#endif
}
void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure) override {
Shell::SetMainMessageLoopQuitClosure(std::move(quit_closure));
}
private:
#if !BUILDFLAG(IS_ANDROID)
void InitializeProfile() {
auto* command_line = base::CommandLine::ForCurrentProcess();
const bool is_incognito =
command_line->HasSwitch(switches::kStartInIncognito);
std::string profile_name = is_incognito ? "" : "web_shell";
profile_ = Profile::Create(profile_name, is_incognito);
}
void DestroyProfile() { profile_.reset(); }
std::unique_ptr<Profile> profile_;
#endif
};
} // namespace
MainParams CreateMainParams() {
static MainDelegateImpl weblayer_delegate;
MainParams params;
params.delegate = &weblayer_delegate;
base::PathService::Get(base::DIR_EXE, ¶ms.log_filename);
params.log_filename = params.log_filename.AppendASCII("weblayer_shell.log");
params.pak_name = "weblayer.pak";
return params;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/app/shell_main_params.cc | C++ | unknown | 3,002 |
// 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.
#ifndef WEBLAYER_SHELL_APP_SHELL_MAIN_PARAMS_H_
#define WEBLAYER_SHELL_APP_SHELL_MAIN_PARAMS_H_
namespace weblayer {
struct MainParams;
MainParams CreateMainParams();
} // namespace weblayer
#endif // WEBLAYER_SHELL_APP_SHELL_MAIN_PARAMS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/app/shell_main_params.h | C++ | unknown | 391 |
// 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.
#include "weblayer/shell/browser/shell.h"
#include <stddef.h>
#include <string>
#include <utility>
#include "base/command_line.h"
#include "base/no_destructor.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "url/gurl.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/browser_list.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/prerender_controller.h"
namespace weblayer {
// Null until/unless the default main message loop is running.
base::NoDestructor<base::OnceClosure> g_quit_main_message_loop;
const int kDefaultTestWindowWidthDip = 1000;
const int kDefaultTestWindowHeightDip = 700;
std::vector<Shell*> Shell::windows_;
Shell::Shell(std::unique_ptr<Browser> browser)
: browser_(std::move(browser)), window_(nullptr) {
windows_.push_back(this);
if (tab()) {
tab()->AddObserver(this);
tab()->GetNavigationController()->AddObserver(this);
#if !BUILDFLAG(IS_ANDROID) // Android does this in Java.
static_cast<TabImpl*>(tab())->profile()->SetDownloadDelegate(this);
#endif
}
}
Shell::~Shell() {
if (tab()) {
tab()->GetNavigationController()->RemoveObserver(this);
tab()->RemoveObserver(this);
#if !BUILDFLAG(IS_ANDROID) // Android does this in Java.
static_cast<TabImpl*>(tab())->profile()->SetDownloadDelegate(nullptr);
#endif
}
PlatformCleanUp();
for (size_t i = 0; i < windows_.size(); ++i) {
if (windows_[i] == this) {
windows_.erase(windows_.begin() + i);
break;
}
}
// Always destroy WebContents before calling PlatformExit(). WebContents
// destruction sequence may depend on the resources destroyed in
// PlatformExit() (e.g. the display::Screen singleton).
if (tab()) {
auto* const profile = static_cast<TabImpl*>(tab())->profile();
profile->GetPrerenderController()->DestroyAllContents();
}
browser_.reset();
if (windows_.empty()) {
PlatformExit();
if (*g_quit_main_message_loop)
std::move(*g_quit_main_message_loop).Run();
}
}
Shell* Shell::CreateShell(std::unique_ptr<Browser> browser,
const gfx::Size& initial_size) {
Shell* shell = new Shell(std::move(browser));
shell->PlatformCreateWindow(initial_size.width(), initial_size.height());
shell->PlatformSetContents();
shell->PlatformResizeSubViews();
return shell;
}
void Shell::CloseAllWindows() {
std::vector<Shell*> open_windows(windows_);
for (size_t i = 0; i < open_windows.size(); ++i)
open_windows[i]->Close();
// Pump the message loop to allow window teardown tasks to run.
base::RunLoop().RunUntilIdle();
}
void Shell::SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure) {
*g_quit_main_message_loop = std::move(quit_closure);
}
Tab* Shell::tab() {
if (!browser())
return nullptr;
if (browser()->GetTabs().empty())
return nullptr;
return browser()->GetTabs()[0];
}
Browser* Shell::browser() {
#if BUILDFLAG(IS_ANDROID)
// TODO(jam): this won't work if we need more than one Shell in a test.
const auto& browsers = BrowserList::GetInstance()->browsers();
if (browsers.empty())
return nullptr;
return *(browsers.begin());
#else
return browser_.get();
#endif
}
void Shell::Initialize() {
PlatformInitialize(GetShellDefaultSize());
}
void Shell::DisplayedUrlChanged(const GURL& url) {
PlatformSetAddressBarURL(url);
}
void Shell::LoadStateChanged(bool is_loading, bool should_show_loading_ui) {
NavigationController* navigation_controller =
tab()->GetNavigationController();
PlatformEnableUIControl(STOP_BUTTON, is_loading && should_show_loading_ui);
// TODO(estade): These should be updated in callbacks that correspond to the
// back/forward list changing, such as NavigationEntriesDeleted.
PlatformEnableUIControl(BACK_BUTTON, navigation_controller->CanGoBack());
PlatformEnableUIControl(FORWARD_BUTTON,
navigation_controller->CanGoForward());
}
void Shell::LoadProgressChanged(double progress) {
PlatformSetLoadProgress(progress);
}
bool Shell::InterceptDownload(const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
int64_t content_length) {
return false;
}
void Shell::AllowDownload(Tab* tab,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
AllowDownloadCallback callback) {
std::move(callback).Run(true);
}
gfx::Size Shell::AdjustWindowSize(const gfx::Size& initial_size) {
if (!initial_size.IsEmpty())
return initial_size;
return GetShellDefaultSize();
}
#if BUILDFLAG(IS_ANDROID)
Shell* Shell::CreateNewWindow(const GURL& url, const gfx::Size& initial_size) {
// On Android, the browser is owned by the Java side.
return CreateNewWindowWithBrowser(nullptr, url, initial_size);
}
#else
Shell* Shell::CreateNewWindow(Profile* web_profile,
const GURL& url,
const gfx::Size& initial_size) {
auto browser = Browser::Create(web_profile, nullptr);
browser->CreateTab();
return CreateNewWindowWithBrowser(std::move(browser), url, initial_size);
}
#endif
Shell* Shell::CreateNewWindowWithBrowser(std::unique_ptr<Browser> browser,
const GURL& url,
const gfx::Size& initial_size) {
Shell* shell =
CreateShell(std::move(browser), AdjustWindowSize(initial_size));
if (!url.is_empty())
shell->LoadURL(url);
return shell;
}
void Shell::LoadURL(const GURL& url) {
tab()->GetNavigationController()->Navigate(url);
}
void Shell::GoBackOrForward(int offset) {
if (offset == -1)
tab()->GetNavigationController()->GoBack();
else if (offset == 1)
tab()->GetNavigationController()->GoForward();
}
void Shell::Reload() {
tab()->GetNavigationController()->Reload();
}
void Shell::ReloadBypassingCache() {}
void Shell::Stop() {
tab()->GetNavigationController()->Stop();
}
gfx::Size Shell::GetShellDefaultSize() {
static gfx::Size default_shell_size;
if (!default_shell_size.IsEmpty())
return default_shell_size;
default_shell_size =
gfx::Size(kDefaultTestWindowWidthDip, kDefaultTestWindowHeightDip);
return default_shell_size;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/browser/shell.cc | C++ | unknown | 6,786 |
// 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.
#ifndef WEBLAYER_SHELL_BROWSER_SHELL_H_
#define WEBLAYER_SHELL_BROWSER_SHELL_H_
#include <stdint.h>
#include <memory>
#include <string>
#include <vector>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/native_widget_types.h"
#include "weblayer/public/download_delegate.h"
#include "weblayer/public/navigation_observer.h"
#include "weblayer/public/tab_observer.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/scoped_java_ref.h"
#elif defined(USE_AURA)
namespace views {
class Widget;
class ViewsDelegate;
} // namespace views
#if !BUILDFLAG(IS_CHROMEOS)
namespace display {
class Screen;
}
namespace wm {
class WMState;
}
#endif
#endif // defined(USE_AURA)
class GURL;
namespace weblayer {
class Browser;
class Profile;
class Tab;
// This represents one window of the Web Shell, i.e. all the UI including
// buttons and url bar, as well as the web content area.
class Shell : public TabObserver,
public NavigationObserver,
public DownloadDelegate {
public:
~Shell() override;
void LoadURL(const GURL& url);
void GoBackOrForward(int offset);
void Reload();
void ReloadBypassingCache();
void Stop();
void Close();
// Do one time initialization at application startup.
static void Initialize();
#if BUILDFLAG(IS_ANDROID)
static Shell* CreateNewWindow(const GURL& url, const gfx::Size& initial_size);
#else
static Shell* CreateNewWindow(Profile* web_profile,
const GURL& url,
const gfx::Size& initial_size);
#endif
// Returns the currently open windows.
static std::vector<Shell*>& windows() { return windows_; }
// Closes all windows, pumps teardown tasks, then returns. The main message
// loop will be signalled to quit, before the call returns.
static void CloseAllWindows();
// Stores the supplied |quit_closure|, to be run when the last Shell
// instance is destroyed.
static void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure);
Tab* tab();
Browser* browser();
gfx::NativeWindow window() { return window_; }
static gfx::Size GetShellDefaultSize();
private:
enum UIControl { BACK_BUTTON, FORWARD_BUTTON, STOP_BUTTON };
static Shell* CreateNewWindowWithBrowser(std::unique_ptr<Browser> browser,
const GURL& url,
const gfx::Size& initial_size);
explicit Shell(std::unique_ptr<Browser> browser);
// TabObserver implementation:
void DisplayedUrlChanged(const GURL& url) override;
// NavigationObserver implementation:
void LoadStateChanged(bool is_loading, bool should_show_loading_ui) override;
void LoadProgressChanged(double progress) override;
// DownloadDelegate implementation:
bool InterceptDownload(const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
int64_t content_length) override;
void AllowDownload(Tab* tab,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
AllowDownloadCallback callback) override;
// Helper to create a new Shell.
static Shell* CreateShell(std::unique_ptr<Browser> browser,
const gfx::Size& initial_size);
// Helper for one time initialization of application
static void PlatformInitialize(const gfx::Size& default_window_size);
// Helper for one time deinitialization of platform specific state.
static void PlatformExit();
// Adjust the size when Blink sends 0 for width and/or height.
// This happens when Blink requests a default-sized window.
static gfx::Size AdjustWindowSize(const gfx::Size& initial_size);
// All the methods that begin with Platform need to be implemented by the
// platform specific Shell implementation.
// Called from the destructor to let each platform do any necessary cleanup.
void PlatformCleanUp();
// Creates the main window GUI.
void PlatformCreateWindow(int width, int height);
// Links the WebContents into the newly created window.
void PlatformSetContents();
// Resize the content area and GUI.
void PlatformResizeSubViews();
// Enable/disable a button.
void PlatformEnableUIControl(UIControl control, bool is_enabled);
// Updates the url in the url bar.
void PlatformSetAddressBarURL(const GURL& url);
// Sets the load progress indicator in the UI.
void PlatformSetLoadProgress(double progress);
// Set the title of shell window
void PlatformSetTitle(const std::u16string& title);
std::unique_ptr<Browser> browser_;
gfx::NativeWindow window_;
gfx::Size content_size_;
#if BUILDFLAG(IS_ANDROID)
base::android::ScopedJavaGlobalRef<jobject> java_object_;
#elif defined(USE_AURA)
static wm::WMState* wm_state_;
static display::Screen* screen_;
#if defined(TOOLKIT_VIEWS)
static views::ViewsDelegate* views_delegate_;
raw_ptr<views::Widget> window_widget_;
#endif // defined(TOOLKIT_VIEWS)
#endif // defined(USE_AURA)
// A container of all the open windows. We use a vector so we can keep track
// of ordering.
static std::vector<Shell*> windows_;
};
} // namespace weblayer
#endif // WEBLAYER_SHELL_BROWSER_SHELL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/browser/shell.h | C++ | unknown | 5,657 |
// 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.
#include "weblayer/shell/browser/shell.h"
namespace weblayer {
// Shell is only used on Android for weblayer_browsertests. So no need to
// implement these methods.
void Shell::PlatformInitialize(const gfx::Size& default_window_size) {}
void Shell::PlatformExit() {}
void Shell::PlatformCleanUp() {}
void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {}
void Shell::PlatformSetAddressBarURL(const GURL& url) {}
void Shell::PlatformSetLoadProgress(double progress) {}
void Shell::PlatformCreateWindow(int width, int height) {}
void Shell::PlatformSetContents() {}
void Shell::PlatformResizeSubViews() {}
void Shell::Close() {}
void Shell::PlatformSetTitle(const std::u16string& title) {}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/browser/shell_android.cc | C++ | unknown | 890 |
// 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.
#include <stddef.h>
#include <memory>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/color/color_id.h"
#include "ui/events/event.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/flex_layout_view.h"
#include "ui/views/test/desktop_test_views_delegate.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/browser/shell.h"
#if defined(USE_AURA) && !BUILDFLAG(IS_CHROMEOS)
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if BUILDFLAG(IS_WIN)
#include <fcntl.h>
#include <io.h>
#endif
namespace weblayer {
namespace {
// Maintain the UI controls and web view for web shell
class ShellWindowDelegateView : public views::WidgetDelegateView,
public views::TextfieldController {
public:
METADATA_HEADER(ShellWindowDelegateView);
enum UIControl { BACK_BUTTON, FORWARD_BUTTON, STOP_BUTTON };
explicit ShellWindowDelegateView(Shell* shell) : shell_(shell) {
SetHasWindowSizeControls(true);
InitShellWindow();
}
ShellWindowDelegateView(const ShellWindowDelegateView&) = delete;
ShellWindowDelegateView& operator=(const ShellWindowDelegateView&) = delete;
~ShellWindowDelegateView() override = default;
// Update the state of UI controls
void SetAddressBarURL(const GURL& url) {
url_entry_->SetText(base::ASCIIToUTF16(url.spec()));
}
void AttachTab(Tab* tab, const gfx::Size& size) {
contents_view_->SetUseDefaultFillLayout(true);
// If there was a previous WebView in this Shell it should be removed and
// deleted.
if (web_view_)
contents_view_->RemoveChildViewT(web_view_.get());
views::Builder<views::View>(contents_view_.get())
.AddChild(views::Builder<views::WebView>()
.CopyAddressTo(&web_view_)
.SetPreferredSize(size))
.BuildChildren();
tab->AttachToView(web_view_);
web_view_->SizeToPreferredSize();
// Resize the widget, keeping the same origin.
gfx::Rect bounds = GetWidget()->GetWindowBoundsInScreen();
bounds.set_size(GetWidget()->GetRootView()->GetPreferredSize());
GetWidget()->SetBounds(bounds);
}
void SetWindowTitle(const std::u16string& title) { title_ = title; }
void EnableUIControl(UIControl control, bool is_enabled) {
if (control == BACK_BUTTON) {
back_button_->SetState(is_enabled ? views::Button::STATE_NORMAL
: views::Button::STATE_DISABLED);
} else if (control == FORWARD_BUTTON) {
forward_button_->SetState(is_enabled ? views::Button::STATE_NORMAL
: views::Button::STATE_DISABLED);
} else if (control == STOP_BUTTON) {
stop_button_->SetState(is_enabled ? views::Button::STATE_NORMAL
: views::Button::STATE_DISABLED);
if (!is_enabled)
UpdateLoadProgress();
}
}
void UpdateLoadProgress(double progress = 0.) {
std::string stop_text("Stop");
if (stop_button_->GetState() == views::Button::STATE_NORMAL)
stop_text = base::StringPrintf("Stop (%.0f%%)", progress * 100);
stop_button_->SetText(base::ASCIIToUTF16(stop_text));
}
private:
// Initialize the UI control contained in shell window
void InitShellWindow() {
auto toolbar_button_rule = [](const views::View* view,
const views::SizeBounds& size_bounds) {
gfx::Size preferred_size = view->GetPreferredSize();
if (size_bounds != views::SizeBounds() &&
size_bounds.width().is_bounded()) {
preferred_size.set_width(std::max(
std::min(size_bounds.width().value(), preferred_size.width()),
preferred_size.width() / 2));
}
return preferred_size;
};
auto* box_layout = SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical));
views::Builder<views::WidgetDelegateView>(this)
.SetBackground(
views::CreateThemedSolidBackground(ui::kColorWindowBackground))
.AddChildren(
views::Builder<views::FlexLayoutView>()
.CopyAddressTo(&toolbar_view_)
.SetOrientation(views::LayoutOrientation::kHorizontal)
// Top/Left/Right padding = 2, Bottom padding = 5
.SetProperty(views::kMarginsKey, gfx::Insets::TLBR(2, 2, 5, 2))
.AddChildren(
views::Builder<views::MdTextButton>()
.CopyAddressTo(&back_button_)
.SetText(u"Back")
.SetCallback(base::BindRepeating(
&Shell::GoBackOrForward,
base::Unretained(shell_.get()), -1))
.SetProperty(
views::kFlexBehaviorKey,
views::FlexSpecification(
base::BindRepeating(toolbar_button_rule))),
views::Builder<views::MdTextButton>()
.CopyAddressTo(&forward_button_)
.SetText(u"Forward")
.SetCallback(base::BindRepeating(
&Shell::GoBackOrForward,
base::Unretained(shell_.get()), 1))
.SetProperty(
views::kFlexBehaviorKey,
views::FlexSpecification(
base::BindRepeating(toolbar_button_rule))),
views::Builder<views::MdTextButton>()
.CopyAddressTo(&refresh_button_)
.SetText(u"Refresh")
.SetCallback(base::BindRepeating(
&Shell::Reload, base::Unretained(shell_.get())))
.SetProperty(
views::kFlexBehaviorKey,
views::FlexSpecification(
base::BindRepeating(toolbar_button_rule))),
views::Builder<views::MdTextButton>()
.CopyAddressTo(&stop_button_)
.SetText(u"Stop (100%)")
.SetCallback(base::BindRepeating(
&Shell::Stop, base::Unretained(shell_.get())))
.SetProperty(
views::kFlexBehaviorKey,
views::FlexSpecification(
base::BindRepeating(toolbar_button_rule))),
views::Builder<views::Textfield>()
.CopyAddressTo(&url_entry_)
.SetAccessibleName(u"Enter URL")
.SetController(this)
.SetTextInputType(
ui::TextInputType::TEXT_INPUT_TYPE_URL)
.SetProperty(
views::kFlexBehaviorKey,
views::FlexSpecification(
views::MinimumFlexSizeRule::kScaleToMinimum,
views::MaximumFlexSizeRule::kUnbounded))
// Left padding = 2, Right padding = 2
.SetProperty(views::kMarginsKey,
gfx::Insets::TLBR(0, 2, 0, 2))),
views::Builder<views::View>()
.CopyAddressTo(&contents_view_)
.SetUseDefaultFillLayout(true)
.SetProperty(views::kMarginsKey, gfx::Insets::TLBR(0, 2, 0, 2)),
views::Builder<views::View>().SetProperty(
views::kMarginsKey, gfx::Insets::TLBR(0, 0, 5, 0)))
.BuildChildren();
box_layout->SetFlexForView(contents_view_, 1);
}
void InitAccelerators() {
// This function must be called when part of the widget hierarchy.
DCHECK(GetWidget());
static const ui::KeyboardCode keys[] = {ui::VKEY_F5, ui::VKEY_BROWSER_BACK,
ui::VKEY_BROWSER_FORWARD};
for (size_t i = 0; i < std::size(keys); ++i) {
GetFocusManager()->RegisterAccelerator(
ui::Accelerator(keys[i], ui::EF_NONE),
ui::AcceleratorManager::kNormalPriority, this);
}
}
// Overridden from TextfieldController
void ContentsChanged(views::Textfield* sender,
const std::u16string& new_contents) override {}
bool HandleKeyEvent(views::Textfield* sender,
const ui::KeyEvent& key_event) override {
if (key_event.type() == ui::ET_KEY_PRESSED && sender == url_entry_ &&
key_event.key_code() == ui::VKEY_RETURN) {
std::string text = base::UTF16ToUTF8(url_entry_->GetText());
GURL url(text);
if (!url.has_scheme()) {
url = GURL(std::string("http://") + std::string(text));
url_entry_->SetText(base::ASCIIToUTF16(url.spec()));
}
shell_->LoadURL(url);
return true;
}
return false;
}
// Overridden from WidgetDelegateView
std::u16string GetWindowTitle() const override { return title_; }
// Overridden from View
gfx::Size GetMinimumSize() const override {
// We want to be able to make the window smaller than its initial
// (preferred) size.
return gfx::Size();
}
void AddedToWidget() override { InitAccelerators(); }
// Overridden from AcceleratorTarget:
bool AcceleratorPressed(const ui::Accelerator& accelerator) override {
switch (accelerator.key_code()) {
case ui::VKEY_F5:
shell_->Reload();
return true;
case ui::VKEY_BROWSER_BACK:
shell_->GoBackOrForward(-1);
return true;
case ui::VKEY_BROWSER_FORWARD:
shell_->GoBackOrForward(1);
return true;
default:
return views::WidgetDelegateView::AcceleratorPressed(accelerator);
}
}
private:
std::unique_ptr<Shell> shell_;
// Window title
std::u16string title_;
// Toolbar view contains forward/backward/reload button and URL entry
raw_ptr<views::View> toolbar_view_ = nullptr;
raw_ptr<views::Button> back_button_ = nullptr;
raw_ptr<views::Button> forward_button_ = nullptr;
raw_ptr<views::Button> refresh_button_ = nullptr;
raw_ptr<views::MdTextButton> stop_button_ = nullptr;
raw_ptr<views::Textfield> url_entry_ = nullptr;
// Contents view contains the WebBrowser view
raw_ptr<views::View> contents_view_ = nullptr;
raw_ptr<views::WebView> web_view_ = nullptr;
};
BEGIN_METADATA(ShellWindowDelegateView, views::WidgetDelegateView)
END_METADATA
} // namespace
#if defined(USE_AURA) && !BUILDFLAG(IS_CHROMEOS)
// static
wm::WMState* Shell::wm_state_ = nullptr;
display::Screen* Shell::screen_ = nullptr;
#endif
// static
views::ViewsDelegate* Shell::views_delegate_ = nullptr;
// static
void Shell::PlatformInitialize(const gfx::Size& default_window_size) {
#if BUILDFLAG(IS_WIN)
_setmode(_fileno(stdout), _O_BINARY);
_setmode(_fileno(stderr), _O_BINARY);
#endif
#if defined(USE_AURA) && !BUILDFLAG(IS_CHROMEOS)
wm_state_ = new wm::WMState;
CHECK(!display::Screen::GetScreen());
screen_ = views::CreateDesktopScreen().release();
#endif
views_delegate_ = new views::DesktopTestViewsDelegate();
}
void Shell::PlatformExit() {
delete views_delegate_;
views_delegate_ = nullptr;
// delete platform_;
// platform_ = nullptr;
#if defined(USE_AURA)
delete screen_;
screen_ = nullptr;
delete wm_state_;
wm_state_ = nullptr;
#endif
}
void Shell::PlatformCleanUp() {}
void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {
ShellWindowDelegateView* delegate_view =
static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
if (control == BACK_BUTTON) {
delegate_view->EnableUIControl(ShellWindowDelegateView::BACK_BUTTON,
is_enabled);
} else if (control == FORWARD_BUTTON) {
delegate_view->EnableUIControl(ShellWindowDelegateView::FORWARD_BUTTON,
is_enabled);
} else if (control == STOP_BUTTON) {
delegate_view->EnableUIControl(ShellWindowDelegateView::STOP_BUTTON,
is_enabled);
}
}
void Shell::PlatformSetAddressBarURL(const GURL& url) {
ShellWindowDelegateView* delegate_view =
static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
delegate_view->SetAddressBarURL(url);
}
void Shell::PlatformSetLoadProgress(double progress) {
ShellWindowDelegateView* delegate_view =
static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
delegate_view->UpdateLoadProgress(progress);
}
void Shell::PlatformCreateWindow(int width, int height) {
window_widget_ = new views::Widget;
views::Widget::InitParams params;
params.bounds = gfx::Rect(0, 0, width, height);
params.delegate = new ShellWindowDelegateView(this);
params.wm_class_class = "chromium-web_shell";
params.wm_class_name = params.wm_class_class;
window_widget_->Init(std::move(params));
content_size_ = gfx::Size(width, height);
// |window_widget_| is made visible in PlatformSetContents(), so that the
// platform-window size does not need to change due to layout again.
window_ = window_widget_->GetNativeWindow();
}
void Shell::PlatformSetContents() {
views::WidgetDelegate* widget_delegate = window_widget_->widget_delegate();
ShellWindowDelegateView* delegate_view =
static_cast<ShellWindowDelegateView*>(widget_delegate);
delegate_view->AttachTab(tab(), content_size_);
window_->GetHost()->Show();
window_widget_->Show();
}
void Shell::PlatformResizeSubViews() {}
void Shell::Close() {
window_widget_->CloseNow();
}
void Shell::PlatformSetTitle(const std::u16string& title) {
ShellWindowDelegateView* delegate_view =
static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
delegate_view->SetWindowTitle(title);
window_widget_->UpdateWindowTitle();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/browser/shell_views.cc | C++ | unknown | 15,049 |
// 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.
#include "weblayer/shell/common/shell_switches.h"
namespace weblayer {
namespace switches {
// Stops new Shell objects from navigating to a default url.
const char kNoInitialNavigation[] = "no-initial-navigation";
// Starts the shell with the profile in incognito mode.
const char kStartInIncognito[] = "start-in-incognito";
} // namespace switches
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/common/shell_switches.cc | C++ | unknown | 524 |
// 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.
#ifndef WEBLAYER_SHELL_COMMON_SHELL_SWITCHES_H_
#define WEBLAYER_SHELL_COMMON_SHELL_SWITCHES_H_
namespace weblayer {
namespace switches {
extern const char kNoInitialNavigation[];
extern const char kStartInIncognito[];
} // namespace switches
} // namespace weblayer
#endif // WEBLAYER_SHELL_COMMON_SHELL_SWITCHES_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/shell/common/shell_switches.h | C++ | unknown | 470 |
include_rules = [
"+components/android_autofill/browser",
"+components/autofill/core/browser",
"+components/browsing_data/content",
"+components/embedder_support",
"+components/heavy_ad_intervention",
"+components/security_interstitials",
"+components/subresource_filter/content/browser",
"+components/subresource_filter/core/browser",
"+components/subresource_filter/core/common",
"+components/url_pattern_index/proto",
"+content/public/common",
"+content/public/browser",
"+content/public/test",
"+net/dns/mock_host_resolver.h",
"+net/test",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/test/DEPS | Python | unknown | 576 |
// 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.
#include "base/command_line.h"
#include "base/test/launcher/test_launcher.h"
#include "build/build_config.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/network_service_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "weblayer/test/test_launcher_delegate_impl.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/win_util.h"
#endif // BUILDFLAG(IS_WIN)
int main(int argc, char** argv) {
base::CommandLine::Init(argc, argv);
size_t parallel_jobs = base::NumParallelJobs(/*cores_per_job=*/1);
if (parallel_jobs == 0U)
return 1;
#if BUILDFLAG(IS_WIN)
// Load and pin user32.dll to avoid having to load it once tests start while
// on the main thread loop where blocking calls are disallowed.
base::win::PinUser32();
#endif // BUILDFLAG(IS_WIN)
// Set up a working test environment for the network service in case it's
// used. Only create this object in the utility process, so that its members
// don't interfere with other test objects in the browser process.
std::unique_ptr<content::NetworkServiceTestHelper>
network_service_test_helper = content::NetworkServiceTestHelper::Create();
weblayer::TestLauncherDelegateImpl launcher_delegate;
return content::LaunchTests(&launcher_delegate, parallel_jobs, argc, argv);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/test/browsertests_main.cc | C++ | unknown | 1,454 |
<html>
<body onclick="window.alert('tab modal overlay');">
<p id='x'>XXXX</p>
</body>
</html>
| Zhao-PengFei35/chromium_src_4 | weblayer/test/data/alert.html | HTML | unknown | 102 |
<html>
<body>
<video id="vid" controls autoplay>
<source src="bear.webm" type="video/mp4">
</video>
</body>
</html>
| Zhao-PengFei35/chromium_src_4 | weblayer/test/data/autoplay.html | HTML | unknown | 118 |
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>A page</title>
<script src="main.js"></script>
</head>
<body>
Hello world.
</body>
</html>
| Zhao-PengFei35/chromium_src_4 | weblayer/test/data/background_fetch/index.html | HTML | unknown | 177 |
// 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.
const kBackgroundFetchId = 'bg-fetch-id';
const kBackgroundFetchResource =
['/weblayer/test/data/background_fetch/types_of_cheese.txt'];
function RegisterServiceWorker() {
navigator.serviceWorker.register('sw.js').then(() => {
console.log('service worker registered');
});
}
// Starts a Background Fetch request for a single to-be-downloaded file.
function StartSingleFileDownload() {
navigator.serviceWorker.ready
.then(swRegistration => {
const options = {title: 'Single-file Background Fetch'};
return swRegistration.backgroundFetch.fetch(
kBackgroundFetchId, kBackgroundFetchResource, options);
})
.then(bgFetchRegistration => {
console.log('bg fetch started');
})
.catch(error => {
console.log(error);
});
}
document.addEventListener('touchend', function(e) {
RegisterServiceWorker();
StartSingleFileDownload();
}, false);
| Zhao-PengFei35/chromium_src_4 | weblayer/test/data/background_fetch/main.js | JavaScript | unknown | 1,074 |
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Another page</title>
</head>
</html>
| Zhao-PengFei35/chromium_src_4 | weblayer/test/data/background_fetch/new_page.html | HTML | unknown | 111 |