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 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.interfaces; import org.chromium.weblayer_private.interfaces.IBooleanCallback; import org.chromium.weblayer_private.interfaces.ICookieChangedCallbackClient; import org.chromium.weblayer_private.interfaces.IObjectWrapper; import org.chromium.weblayer_private.interfaces.IStringCallback; interface ICookieManager { void setCookie(in String url, in String value, in IBooleanCallback callback) = 0; void getCookie(in String url, in IStringCallback callback) = 1; IObjectWrapper addCookieChangedCallback(in String url, in String name, ICookieChangedCallbackClient callback) = 2; // Added in 101. void getResponseCookies(in String url, in IObjectWrapper callback) = 3; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/ICookieManager.aidl
AIDL
unknown
862
// 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.interfaces; import android.os.Bundle; import org.chromium.weblayer_private.interfaces.ICrashReporterControllerClient; import org.chromium.weblayer_private.interfaces.IObjectWrapper; interface ICrashReporterController { void setClient(in ICrashReporterControllerClient client) = 0; void checkForPendingCrashReports() = 1; Bundle getCrashKeys(in String localId) = 2; void deleteCrash(in String localId) = 3; void uploadCrash(in String localId) = 4; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/ICrashReporterController.aidl
AIDL
unknown
654
// 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.interfaces; import android.os.Bundle; import org.chromium.weblayer_private.interfaces.IObjectWrapper; interface ICrashReporterControllerClient { void onPendingCrashReports(in String[] localIds) = 0; void onCrashDeleted(in String localId) = 1; void onCrashUploadSucceeded(in String localId, in String reportId) = 2; void onCrashUploadFailed(in String localId, in String failureMessage) = 3; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/ICrashReporterControllerClient.aidl
AIDL
unknown
593
// 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.interfaces; /** * Contains information about a single download that's in progress. */ interface IDownload { int getState() = 0; long getTotalBytes() = 1; long getReceivedBytes() = 2; void pause() = 3; void resume() = 4; void cancel() = 5; String getLocation() = 6; int getError() = 7; String getMimeType() = 8; void disableNotification() = 9; String getFileNameToReportToUser() = 10; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IDownload.aidl
AIDL
unknown
593
// 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.interfaces; import android.content.Intent; import org.chromium.weblayer_private.interfaces.IClientDownload; import org.chromium.weblayer_private.interfaces.IDownload; import org.chromium.weblayer_private.interfaces.IObjectWrapper; /** * Used to forward download requests to the client. */ interface IDownloadCallbackClient { boolean interceptDownload(in String uriString, in String userAgent, in String contentDisposition, in String mimetype, long contentLength) = 0; void allowDownload(in String uriString, in String requestMethod, in String requestInitiatorString, in IObjectWrapper valueCallback) = 1; IClientDownload createClientDownload(in IDownload impl) = 2; void downloadStarted(IClientDownload download) = 3; void downloadProgressChanged(IClientDownload download) = 4; void downloadCompleted(IClientDownload download) = 5; void downloadFailed(IClientDownload download) = 6; // ID 7 was createIntent and was removed in M87. }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IDownloadCallbackClient.aidl
AIDL
unknown
1,136
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IClientNavigation; /** * Allows the client to override the default way of handling user interactions * with error pages (such as SSL interstitials). */ interface IErrorPageCallbackClient { boolean onBackToSafety() = 0; String getErrorPageContent(IClientNavigation navigation) = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IErrorPageCallbackClient.aidl
AIDL
unknown
534
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; interface IExternalIntentInIncognitoCallbackClient { // onUserDecisionWrapper is a ValueCallback<Integer>. void onExternalIntentInIncognito(in IObjectWrapper onUserDecisionWrapper) = 0; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IExternalIntentInIncognitoCallbackClient.aidl
AIDL
unknown
452
// 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.interfaces; interface IFaviconFetcher { void destroy() = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IFaviconFetcher.aidl
AIDL
unknown
247
// 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.interfaces; interface IFaviconFetcherClient { void onDestroyed() = 1; void onFaviconChanged(in Bitmap bitmap) = 2; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IFaviconFetcherClient.aidl
AIDL
unknown
304
// 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.interfaces; /** * Used to forward find in page results to the client. */ interface IFindInPageCallbackClient { void onFindResult(in int numberOfMatches, in int activeMatchOrdinal, in boolean finalUpdate) = 0; void onFindEnded() = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IFindInPageCallbackClient.aidl
AIDL
unknown
424
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; /** * Used to forward FullscreenCallback calls to the client. */ interface IFullscreenCallbackClient { // exitFullscreenWrapper is a ValueCallback<Void> that when run exits // fullscreen. void enterFullscreen(in IObjectWrapper exitFullscreenWrapper) = 0; void exitFullscreen() = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IFullscreenCallbackClient.aidl
AIDL
unknown
554
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; interface IGoogleAccountAccessTokenFetcherClient { // scopesWrapper is a Set<String>, and onTokenFetchedWrapper is a ValueCallback<String>. void fetchAccessToken(in IObjectWrapper scopesWrapper, in IObjectWrapper onTokenFetchedWrapper) = 0; // scopesWrapper is a Set<String>, and tokenWrapper is a String. // Added in 93. void onAccessTokenIdentifiedAsInvalid(in IObjectWrapper scopesWrapper, in IObjectWrapper tokenWrapper) = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IGoogleAccountAccessTokenFetcherClient.aidl
AIDL
unknown
703
// 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.interfaces; interface IGoogleAccountsCallbackClient { void onGoogleAccountsRequest(int serviceType, in String email, in String continueUrl, boolean isSameTab) = 0; String getGaiaId() = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IGoogleAccountsCallbackClient.aidl
AIDL
unknown
377
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; interface IMediaCaptureCallbackClient { void onMediaCaptureRequested(boolean audio, boolean video, in IObjectWrapper requestResult) = 0; void onMediaCaptureStateChanged(boolean audio, boolean video) = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IMediaCaptureCallbackClient.aidl
AIDL
unknown
470
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IRemoteFragment; interface IMediaRouteDialogFragment { IRemoteFragment asRemoteFragment() = 0; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IMediaRouteDialogFragment.aidl
AIDL
unknown
343
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.weblayer_private.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; /** * Provides parameters for NavigationController.navigate. */ interface INavigateParams { void replaceCurrentEntry() = 0; void disableIntentProcessing() = 1; void disableNetworkErrorAutoReload() = 2; void enableAutoPlay() = 3; void setResponse(in IObjectWrapper response) = 4; // @since 89 void allowIntentLaunchesInBackground() = 5; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/INavigateParams.aidl
AIDL
unknown
615
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IClientPage; /** * Provides information about a navigation. */ interface INavigation { int getState() = 0; String getUri() = 1; List<String> getRedirectChain() = 2; int getHttpStatusCode() = 3; boolean isSameDocument() = 4; boolean isErrorPage() = 5; int getLoadError() = 6; void setRequestHeader(in String name, in String value) = 7; void setUserAgentString(in String value) = 8; boolean isDownload() = 9; boolean wasStopCalled() = 10; boolean isPageInitiated() = 11; boolean isReload() = 12; // @since 89 boolean wasIntentLaunched() = 13; boolean isUserDecidingIntentLaunch() = 14; boolean isKnownProtocol() = 15; boolean isServedFromBackForwardCache() = 16; boolean isFormSubmission() = 19; String getReferrer() = 20; // @since 88 void disableNetworkErrorAutoReload() = 17; // @since 90 IClientPage getPage() = 18; // @since 91 List<String> getResponseHeaders() = 21; // @since 92 int getNavigationEntryOffset() = 22; // @since 97 void disableIntentProcessing() = 23; // @since 102 boolean wasFetchedFromCache() = 24; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/INavigation.aidl
AIDL
unknown
1,351
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; import org.chromium.weblayer_private.interfaces.INavigateParams; import org.chromium.weblayer_private.interfaces.NavigateParams; interface INavigationController { // Deprecated in M89. void navigate(in String uri, in NavigateParams params) = 0; void goBack() = 1; void goForward() = 2; void reload() = 3; void stop() = 4; int getNavigationListSize() = 5; int getNavigationListCurrentIndex() = 6; String getNavigationEntryDisplayUri(in int index) = 7; boolean canGoBack() = 8; boolean canGoForward() = 9; void goToIndex(in int index) = 10; String getNavigationEntryTitle(in int index) = 11; // ID 12 was replace and was removed in M83. boolean isNavigationEntrySkippable(int index) = 13; // Deprecated in M89. void navigate2(in String uri, in boolean shouldReplaceEntry, in boolean disableIntentProcessing, in boolean disableNetworkErrorAutoReload, in boolean enableAutoPlay) = 14; INavigateParams createNavigateParams() = 15; void navigate3(in String uri, in INavigateParams params) = 16; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/INavigationController.aidl
AIDL
unknown
1,389
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IClientNavigation; import org.chromium.weblayer_private.interfaces.IClientPage; import org.chromium.weblayer_private.interfaces.INavigation; import org.chromium.weblayer_private.interfaces.IObjectWrapper; /** * Interface used by NavigationController to inform the client of changes. This largely duplicates * the NavigationCallback interface, but is a singleton to avoid unnecessary IPC. */ interface INavigationControllerClient { IClientNavigation createClientNavigation(in INavigation impl) = 0; void navigationStarted(IClientNavigation navigation) = 1; void navigationRedirected(IClientNavigation navigation) = 2; void readyToCommitNavigation(IClientNavigation navigation) = 3; void navigationCompleted(IClientNavigation navigation) = 4; void navigationFailed(IClientNavigation navigation) = 5; void loadStateChanged(boolean isLoading, boolean shouldShowLoadingUi) = 6; void loadProgressChanged(double progress) = 7; void onFirstContentfulPaint() = 8; void onOldPageNoLongerRendered(in String uri) = 9; // Added in M88. void onFirstContentfulPaint2(long navigationStartMs, long firstContentfulPaintDurationMs) = 10; void onLargestContentfulPaint(long navigationStartMs, long largestContentfulPaintDurationMs) = 11; // Added in M90. IClientPage createClientPage() = 12; void onPageDestroyed(IClientPage page) = 13; // Added in M93. void onPageLanguageDetermined(IClientPage page, in String language) = 14; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/INavigationControllerClient.aidl
AIDL
unknown
1,705
// 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.interfaces; /** * This interface intentionally has no methods, and instances of this should * be created from class ObjectWrapper only. This is used as a way of passing * objects that descend from the system classes via AIDL across classloaders * without serializing them. */ interface IObjectWrapper { }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IObjectWrapper.aidl
AIDL
unknown
494
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IBrowser; // Since 91. interface IOpenUrlCallbackClient { IBrowser getBrowserForNewTab() = 0; void onTabAdded(in int tabId) = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IOpenUrlCallbackClient.aidl
AIDL
unknown
379
// 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.interfaces; interface IPrerenderController { void prerender(in String url) = 0; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IPrerenderController.aidl
AIDL
unknown
267
// 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.interfaces; import org.chromium.weblayer_private.interfaces.ICookieManager; import org.chromium.weblayer_private.interfaces.IDownloadCallbackClient; import org.chromium.weblayer_private.interfaces.IUserIdentityCallbackClient; 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.IPrerenderController; import org.chromium.weblayer_private.interfaces.IProfileClient; interface IProfile { void destroy() = 0; void clearBrowsingData(in int[] dataTypes, long fromMillis, long toMillis, in IObjectWrapper completionCallback) = 1; String getName() = 2; void setDownloadDirectory(String directory) = 3; void destroyAndDeleteDataFromDisk(in IObjectWrapper completionCallback) = 4; void setDownloadCallbackClient(IDownloadCallbackClient client) = 5; ICookieManager getCookieManager() = 6; void setBooleanSetting(int type, boolean value) = 7; boolean getBooleanSetting(int type) = 8; void getBrowserPersistenceIds(in IObjectWrapper resultCallback) = 9; void removeBrowserPersistenceStorage(in String[] ids, in IObjectWrapper resultCallback) = 10; void prepareForPossibleCrossOriginNavigation() = 11; void getCachedFaviconForPageUri(in String uri, in IObjectWrapper resultCallback) = 12; void setUserIdentityCallbackClient(IUserIdentityCallbackClient client) = 13; IPrerenderController getPrerenderController() = 15; boolean isIncognito() = 16; void setClient(in IProfileClient client) = 17; void destroyAndDeleteDataFromDiskSoon(in IObjectWrapper completeCallback) = 18; // Added in 89. void setGoogleAccountAccessTokenFetcherClient(IGoogleAccountAccessTokenFetcherClient client) = 19; // Added in 91. void setTablessOpenUrlCallbackClient(IOpenUrlCallbackClient client) = 20; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IProfile.aidl
AIDL
unknown
2,209
// 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.interfaces; // Added in Version 88. interface IProfileClient { void onProfileDestroyed() = 0; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IProfileClient.aidl
AIDL
unknown
281
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; import org.chromium.weblayer_private.interfaces.IRemoteFragmentClient; // Next value: 16 interface IRemoteFragment { void setClient(in IRemoteFragmentClient client) = 15; // Fragment events. void handleOnCreate() = 0; void handleOnAttach(in IObjectWrapper context) = 1; void handleOnStart() = 2; void handleOnResume() = 3; void handleOnPause() = 4; void handleOnStop() = 5; void handleOnDestroyView() = 6; void handleOnDetach() = 7; void handleOnDestroy() = 8; // |data| is an Intent with the result returned from the activity. void handleOnActivityResult(int requestCode, int resultCode, in IObjectWrapper data) = 9; void handleOnRequestPermissionsResult(int requestCode, in String[] permissions, in int[] grantResults) = 10; // Out of process operations. void handleSetSurfaceControlViewHost(in IObjectWrapper /* SurfaceControlViewHost */ host) = 12; // In process operations. IObjectWrapper /* View */ handleGetContentViewRenderView() = 13; // Fragment operations. void handleSetMinimumSurfaceSize(in int width, in int height) = 14; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IRemoteFragment.aidl
AIDL
unknown
1,486
// 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_private.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; // Next value: 1 interface IRemoteFragmentClient { boolean startActivityForResult(in IObjectWrapper intent, in int requestCode, in IObjectWrapper options) = 0; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IRemoteFragmentClient.aidl
AIDL
unknown
425
// 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_private.interfaces; oneway interface IStringCallback { void onResult(in String result) = 1; // TODO(swestphal): Replace parameters with actual Exception when supported to also propagate stacktrace. void onException(in int type, in String msg) = 2; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IStringCallback.aidl
AIDL
unknown
437
// 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.interfaces; import java.util.List; import org.chromium.weblayer_private.interfaces.IContextMenuParams; import org.chromium.weblayer_private.interfaces.IDownloadCallbackClient; import org.chromium.weblayer_private.interfaces.IErrorPageCallbackClient; import org.chromium.weblayer_private.interfaces.IExternalIntentInIncognitoCallbackClient; import org.chromium.weblayer_private.interfaces.IFaviconFetcher; import org.chromium.weblayer_private.interfaces.IFaviconFetcherClient; import org.chromium.weblayer_private.interfaces.IFindInPageCallbackClient; import org.chromium.weblayer_private.interfaces.IFullscreenCallbackClient; import org.chromium.weblayer_private.interfaces.IGoogleAccountsCallbackClient; import org.chromium.weblayer_private.interfaces.IMediaCaptureCallbackClient; import org.chromium.weblayer_private.interfaces.INavigationController; import org.chromium.weblayer_private.interfaces.INavigationControllerClient; import org.chromium.weblayer_private.interfaces.IObjectWrapper; import org.chromium.weblayer_private.interfaces.IStringCallback; import org.chromium.weblayer_private.interfaces.ITabClient; interface ITab { void setClient(in ITabClient client) = 0; INavigationController createNavigationController(in INavigationControllerClient client) = 1; // ID 2 was setDownloadCallbackClient and was removed in M89. void setErrorPageCallbackClient(IErrorPageCallbackClient client) = 3; void setFullscreenCallbackClient(in IFullscreenCallbackClient client) = 4; void executeScript(in String script, boolean useSeparateIsolate, in IStringCallback callback) = 5; void setNewTabsEnabled(in boolean enabled) = 6; // Returns a unique identifier for this Tab. The id is *not* unique across // restores. The id is intended for the client library to avoid creating duplicate client objects // for the same ITab. int getId() = 7; boolean setFindInPageCallbackClient(IFindInPageCallbackClient client) = 8; void findInPage(in String searchText, boolean forward) = 9; // And and removed in 82; superseded by dismissTransientUi(). // void dismissTabModalOverlay() = 10; void dispatchBeforeUnloadAndClose() = 11; boolean dismissTransientUi() = 12; String getGuid() = 13; void setMediaCaptureCallbackClient(in IMediaCaptureCallbackClient client) = 14; void stopMediaCapturing() = 15; void captureScreenShot(in float scale, in IObjectWrapper resultCallback) = 16; boolean setData(in Map data) = 17; Map getData() = 18; // IDs 19 and 20 were registerWebMessageCallback & unregisterWebMessageCallback. boolean canTranslate() = 21; void showTranslateUi() = 22; void setGoogleAccountsCallbackClient(IGoogleAccountsCallbackClient client) = 23; IFaviconFetcher createFaviconFetcher(IFaviconFetcherClient client) = 24; void setTranslateTargetLanguage(in String targetLanguage) = 25; void setScrollOffsetsEnabled(in boolean enabled) = 26; // Added in 88 void setFloatingActionModeOverride(in int actionModeItemTypes) = 27; boolean willAutomaticallyReloadAfterCrash() = 28; void setDesktopUserAgentEnabled(in boolean enable) = 29; boolean isDesktopUserAgentEnabled() = 30; void download(in IContextMenuParams contextMenuParams) = 31; // Added in 90 void addToHomescreen() = 32; // Added in 93 void setExternalIntentInIncognitoCallbackClient(IExternalIntentInIncognitoCallbackClient client) = 33; String getUri() = 34; void postMessage(in String message, in String targetOrigin) = 35; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/ITab.aidl
AIDL
unknown
3,669
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IContextMenuParams; import org.chromium.weblayer_private.interfaces.IObjectWrapper; /** * Interface used by Tab to inform the client of changes. This largely duplicates the * TabCallback interface, but is a singleton to avoid unnecessary IPC. */ interface ITabClient { void visibleUriChanged(in String uriString) = 0; void onNewTab(in int tabId, in int mode) = 1; void onRenderProcessGone() = 2; // ID 3 was onCloseTab and was removed in M87. // Deprecated in M88. void showContextMenu(in IObjectWrapper pageUrl, in IObjectWrapper linkUrl, in IObjectWrapper linkText, in IObjectWrapper titleOrAltText, in IObjectWrapper srcUrl) = 4; void onTabModalStateChanged(in boolean isTabModalShowing) = 5; void onTitleUpdated(in IObjectWrapper title) = 6; void bringTabToFront() = 7; void onTabDestroyed() = 8; void onBackgroundColorChanged(in int color) = 9; void onScrollNotification( in int notificationType, in float currentScrollRatio) = 10; void onVerticalScrollOffsetChanged(in int offset) = 11; // Added in M88 void onActionItemClicked( in int actionModeItemType, in IObjectWrapper selectedString) = 12; void showContextMenu2(in IObjectWrapper pageUrl, in IObjectWrapper linkUrl, in IObjectWrapper linkText, in IObjectWrapper titleOrAltText, in IObjectWrapper srcUrl, in boolean isImage, in boolean isVideo, in boolean canDownload, in IContextMenuParams contextMenuParams) = 13; // Added in M101. void onVerticalOverscroll(float accumulatedOverscrollY) = 14; // Added in M111. void onPostMessage(in String message, in String origin) = 15; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/ITabClient.aidl
AIDL
unknown
1,890
// 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.interfaces; import org.chromium.weblayer_private.interfaces.IObjectWrapper; interface IUserIdentityCallbackClient { String getEmail() = 0; String getFullName() = 1; // avatarLoadedWrapper is a ValueCallback<Bitmap> that updates the profile icon when run. void getAvatar(int desiredSize, in IObjectWrapper avatarLoadedWrapper) = 2; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IUserIdentityCallbackClient.aidl
AIDL
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. package org.chromium.weblayer_private.interfaces; import android.content.Intent; import android.os.Bundle; import org.chromium.weblayer_private.interfaces.IBrowser; import org.chromium.weblayer_private.interfaces.ICrashReporterController; import org.chromium.weblayer_private.interfaces.IObjectWrapper; import org.chromium.weblayer_private.interfaces.IProfile; import org.chromium.weblayer_private.interfaces.IMediaRouteDialogFragment; import org.chromium.weblayer_private.interfaces.IWebLayerClient; interface IWebLayer { // ID 1 was loadAsyncV80 and was removed in M86. // ID 2 was loadSyncV80 and was removed in M86. // Create or get the profile matching profileName. IProfile getProfile(in String profileName) = 4; // Enable or disable DevTools remote debugging server. void setRemoteDebuggingEnabled(boolean enabled) = 5; // Returns whether or not the DevTools remote debugging server is enabled. boolean isRemoteDebuggingEnabled() = 6; // ID 7 was getCrashReporterControllerV80 and was removed in M86. // Initializes WebLayer and starts loading. // // It is expected that either loadAsync or loadSync is called before anything else. // // @param appContext A Context that refers to the Application using WebLayer. // @param remoteContext A Context that refers to the WebLayer provider package. // @param loadedCallback A ValueCallback that will be called when load completes. void loadAsync(in IObjectWrapper appContext, in IObjectWrapper remoteContext, in IObjectWrapper loadedCallback) = 8; // Initializes WebLayer, starts loading and blocks until loading has completed. // // It is expected that either loadAsync or loadSync is called before anything else. // // @param appContext A Context that refers to the Application using WebLayer. // @param remoteContext A Context that refers to the WebLayer provider package. void loadSync(in IObjectWrapper appContext, in IObjectWrapper remoteContext) = 9; // Returns the singleton crash reporter controller. If WebLayer has not been // initialized, does the minimum initialization needed for the crash reporter. ICrashReporterController getCrashReporterController( in IObjectWrapper appContext, in IObjectWrapper remoteContext) = 10; // Forwards broadcast from a notification to the implementation. void onReceivedBroadcast(in IObjectWrapper appContext, in Intent intent) = 11; void enumerateAllProfileNames(in IObjectWrapper valueCallback) = 12; void setClient(in IWebLayerClient client) = 13; String getUserAgentString() = 14; void registerExternalExperimentIDs(in String trialName, in int[] experimentIds) = 15; void onMediaSessionServiceStarted(in IObjectWrapper sessionService, in Intent intent) = 17; void onMediaSessionServiceDestroyed() = 18; IBinder initializeImageDecoder(in IObjectWrapper appContext, in IObjectWrapper remoteContext) = 19; IObjectWrapper getApplicationContext() = 20; IProfile getIncognitoProfile(in String profileName) = 24; // Added in Version 88. void onRemoteMediaServiceStarted(in IObjectWrapper sessionService, in Intent intent) = 22; void onRemoteMediaServiceDestroyed(int id) = 23; // Creates an instance of GooglePayDataCallbacksService. Added in Version 92. IObjectWrapper createGooglePayDataCallbacksService() = 26; // Creates an instance of PaymentDetailsUpdateService. Added in Version 92. IObjectWrapper createPaymentDetailsUpdateService() = 27; // Added in Version 101. String getXClientDataHeader() = 28; IBrowser createBrowser(IObjectWrapper serviceContext, IObjectWrapper fragmentArgs) = 29; // WARNING: when choosing next value make sure you look back for the max, as // merges may mean the last function does not have the max value. }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IWebLayer.aidl
AIDL
unknown
4,007
// 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.interfaces; import android.content.Intent; interface IWebLayerClient { Intent createIntent() = 0; Intent createMediaSessionServiceIntent() = 1; int getMediaSessionNotificationId() = 2; Intent createImageDecoderServiceIntent() = 3; // Since Version 88. long getClassLoaderCreationTime() = 4; long getContextCreationTime() = 5; long getWebLayerLoaderCreationTime() = 6; Intent createRemoteMediaServiceIntent() = 7; int getPresentationApiNotificationId() = 8; int getRemotePlaybackApiNotificationId() = 9; // Added in Version 98. int getMaxNavigationsPerTabForInstanceState() = 10; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IWebLayerClient.aidl
AIDL
unknown
793
// 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.interfaces; import android.os.Bundle; import org.chromium.weblayer_private.interfaces.IWebLayer; // Factory for creating IWebLayer as well as determining if a particular version // of a client is supported. interface IWebLayerFactory { // Returns true if a client with the specified version is supported. boolean isClientSupported() = 0; // Creates a new IWebLayer. It is expected that a client has a single // IWebLayer. Further, at this time, only a single client is supported. IWebLayer createWebLayer() = 1; // Returns the full version string of the implementation. String getImplementationVersion() = 2; // Returns the major version of the implementation. int getImplementationMajorVersion() = 3; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/IWebLayerFactory.aidl
AIDL
unknown
910
// 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.interfaces; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({LoadError.NO_ERROR, LoadError.HTTP_CLIENT_ERROR, LoadError.HTTP_SERVER_ERROR, LoadError.SSL_ERROR, LoadError.CONNECTIVITY_ERROR, LoadError.OTHER_ERROR, LoadError.SAFE_BROWSING_ERROR}) @Retention(RetentionPolicy.SOURCE) public @interface LoadError { int NO_ERROR = 0; int HTTP_CLIENT_ERROR = 1; int HTTP_SERVER_ERROR = 2; int SSL_ERROR = 3; int CONNECTIVITY_ERROR = 4; int OTHER_ERROR = 5; // Sent since 88. int SAFE_BROWSING_ERROR = 6; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/LoadError.java
Java
unknown
811
// 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.interfaces; parcelable NavigateParams;
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/NavigateParams.aidl
AIDL
unknown
222
// 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.interfaces; import android.os.Parcel; import android.os.Parcelable; /** * Extra optional parameters for {@link NavigationController#navigate}. * * Default values should be kept in sync with C++ NavigationController::LoadURLParams. * * @since 83 */ public class NavigateParams implements Parcelable { public boolean mShouldReplaceCurrentEntry; public static final Parcelable.Creator<NavigateParams> CREATOR = new Parcelable.Creator<NavigateParams>() { @Override public NavigateParams createFromParcel(Parcel in) { return new NavigateParams(in); } @Override public NavigateParams[] newArray(int size) { return new NavigateParams[size]; } }; public NavigateParams() {} private NavigateParams(Parcel in) { readFromParcel(in); } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(mShouldReplaceCurrentEntry ? 1 : 0); } public void readFromParcel(Parcel in) { mShouldReplaceCurrentEntry = in.readInt() == 1; } @Override public int describeContents() { return 0; } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/NavigateParams.java
Java
unknown
1,424
// 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.interfaces; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({NavigationState.WAITING_RESPONSE, NavigationState.RECEIVING_BYTES, NavigationState.COMPLETE, NavigationState.FAILED}) @Retention(RetentionPolicy.SOURCE) public @interface NavigationState { int WAITING_RESPONSE = 0; int RECEIVING_BYTES = 1; int COMPLETE = 2; int FAILED = 3; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/NavigationState.java
Java
unknown
625
// 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.interfaces; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({NewTabType.FOREGROUND_TAB, NewTabType.BACKGROUND_TAB, NewTabType.NEW_POPUP, NewTabType.NEW_WINDOW}) @Retention(RetentionPolicy.SOURCE) public @interface NewTabType { int FOREGROUND_TAB = 0; int BACKGROUND_TAB = 1; int NEW_POPUP = 2; int NEW_WINDOW = 3; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/NewTabType.java
Java
unknown
604
// 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.interfaces; import android.os.IBinder; import java.lang.reflect.Field; /** * This wraps an object to be transferred across sibling classloaders in the same process via the * IObjectWrapper AIDL interface. By using reflection to retrieve the object, no serialization needs * to occur. * * @param <T> The type of the wrapped object. */ public final class ObjectWrapper<T> extends IObjectWrapper.Stub { /** * The wrapped object. You must not add another member in this class because the check for * retrieving this member variable is that this is the ONLY member variable declared in this * class and it is private. This is because ObjectWrapper can be obfuscated, so that this member * variable can have an obfuscated name. */ private final T mWrappedObject; /* DO NOT ADD NEW CLASS MEMBERS (see above) */ /** Disable creating an object wrapper. Instead, use {@link #wrap(Object)}. */ private ObjectWrapper(T object) { mWrappedObject = object; } /** * Create the wrapped object. * * @param object The object instance to wrap. * @return The wrapped object. */ public static <T> IObjectWrapper wrap(T object) { return new ObjectWrapper<T>(object); } /** * Unwrap the object within the {@link IObjectWrapper} using reflection. * * @param remote The {@link IObjectWrapper} instance to unwrap. * @param clazz The {@link Class} of the unwrapped object type. * @return The unwrapped object. */ public static <T> T unwrap(IObjectWrapper remote, Class<T> clazz) { if (remote == null) return null; // Handle the case when not getting an IObjectWrapper from a sibling classloader if (remote instanceof ObjectWrapper) { @SuppressWarnings("unchecked") ObjectWrapper<T> typedRemote = ((ObjectWrapper<T>) remote); return typedRemote.mWrappedObject; } IBinder remoteBinder = remote.asBinder(); // It is possible that ObjectWrapper was obfuscated in which case wrappedObject // would have a different name. The following checks that there is a single // declared field that is private. Class<?> remoteClazz = remoteBinder.getClass(); Field validField = null; for (Field field : remoteClazz.getDeclaredFields()) { if (field.isSynthetic()) continue; // Only one valid, non-synthetic field is allowed on the class. if (validField != null) { validField = null; break; } validField = field; } if (validField == null || validField.isAccessible()) { throw new IllegalArgumentException("The concrete class implementing IObjectWrapper" + " must have exactly *one* declared *private* field for the wrapped object. " + " Preferably, this is an instance of the ObjectWrapper<T> class."); } validField.setAccessible(true); try { Object wrappedObject = validField.get(remoteBinder); if (wrappedObject == null) return null; if (!clazz.isInstance(wrappedObject)) { throw new IllegalArgumentException("remoteBinder is the wrong class."); } return clazz.cast(wrappedObject); } catch (NullPointerException e) { throw new IllegalArgumentException("Binder object is null.", e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("remoteBinder is the wrong class.", e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access the field in remoteBinder.", e); } } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/ObjectWrapper.java
Java
unknown
3,980
# 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. """Presubmit tests for weblayer. Used to verify incompatible changes have not been done to AIDL files. """ import glob import logging import os import shutil import subprocess import sys import tempfile USE_PYTHON3 = True _INCOMPATIBLE_API_ERROR_STRING = """You have made an incompatible API change. Generally this means one of the following: A function has been removed. The arguments of a function has changed. This tool also reports renames as errors, which are generally okay. If the API you are changing was added in the current release, you can safely ignore this warning.""" class AidlFile: """Provides information about an aidl file in the repo.""" def __init__(self, f): # The AffectedFile. self.affected_file = f # Path of the aidl file in the repo, this is the full absolute path. self.path_in_repo = f.AbsoluteLocalPath() # Absolute path to where java files start. self.java_root_dir = '' # Package names of the file. self.packages = [] # Name part of the file, e.g. IBrowser.aidl. self.file_name = os.path.basename(self.path_in_repo) current_dir = self.path_in_repo packages = [] while current_dir != '': dir_name, base_name = os.path.split(current_dir) packages.append(base_name) if base_name == 'org': packages.reverse() self.java_root_dir = dir_name # Last item is the file name packages.pop() self.packages = packages break parent_dir = dir_name if current_dir == parent_dir: logging.warn('Unable to find file system root for %s', self.path_in_repo) break current_dir = parent_dir def IsValid(self): """Returns true if this is a valid aidl file.""" return len(self.packages) > 0 def GetPathRelativeTo(self, other_dir): """Returns the path of the file relative to another directory. The path is built using the java packages. """ return os.path.join(os.path.join(other_dir, *self.packages), self.file_name) def _CompareApiDumpForFiles(input_api, output_api, aidl_files): if len(aidl_files) == 0: return [] # These tests fail to run on Windows (devil_chromium needs some non-standard # Windows modules) and given the Android dependencies this is reasonable. if input_api.is_windows: return [] repo_root = input_api.change.RepositoryRoot() build_android_dir = os.path.join(repo_root, 'build', 'android') sys.path.append(build_android_dir) sys.path.append(os.path.join(repo_root, 'third_party', 'catapult', 'devil')) import devil_chromium from devil.android.sdk import build_tools devil_chromium.Initialize() try: aidl_tool_path = build_tools.GetPath('aidl') except Exception as e: if input_api.no_diffs: # If we are running presubmits with --all or --files and the 'aidl' tool # cannot be found then that probably means that target_os = 'android' is # missing from .gclient and the failure is not interesting. return [] if not os.path.exists(aidl_tool_path): return [output_api.PresubmitError( 'Android sdk does not contain aidl command ' + aidl_tool_path)] framework_aidl_path = glob.glob(os.path.join( input_api.change.RepositoryRoot(), 'third_party', 'android_sdk', 'public', 'platforms', '*', 'framework.aidl'))[0] logging.debug('Using framework.aidl at path %s', framework_aidl_path) tmp_old_contents_dir = tempfile.mkdtemp() tmp_old_aidl_dir = tempfile.mkdtemp() tmp_new_aidl_dir = tempfile.mkdtemp() aidl_src_dir = aidl_files[0].java_root_dir generate_old_api_cmd = [aidl_tool_path, '--dumpapi', '--out', tmp_old_aidl_dir, ('-p' + framework_aidl_path), ('-I' + aidl_src_dir)] generate_new_api_cmd = [aidl_tool_path, '--dumpapi', '--out', tmp_new_aidl_dir, ('-p' + framework_aidl_path), ('-I' + aidl_src_dir)] # The following generates the aidl api dump (both original and new) for any # changed file. The dumps are then compared using --checkapi. try: valid_file = False for aidl_file in aidl_files: old_contents = '\n'.join(aidl_file.affected_file.OldContents()) if len(old_contents) == 0: # When |old_contents| is empty it indicates a new file, which is # implicitly compatible. continue old_contents_file_path = aidl_file.GetPathRelativeTo(tmp_old_contents_dir) # aidl expects the directory to match the java package names. if not os.path.isdir(os.path.dirname(old_contents_file_path)): os.makedirs(os.path.dirname(old_contents_file_path)) with open(old_contents_file_path, 'w') as old_contents_file: old_contents_file.write(old_contents) generate_old_api_cmd += [old_contents_file_path] generate_new_api_cmd += [aidl_file.path_in_repo] valid_file = True if not valid_file: return [] logging.debug('Generating old api %s', generate_old_api_cmd) result = subprocess.call(generate_old_api_cmd) if result != 0: return [output_api.PresubmitError('Error generating old aidl api dump')] logging.debug('Generating new api %s', generate_new_api_cmd) result = subprocess.call(generate_new_api_cmd) if result != 0: return [output_api.PresubmitError('Error generating new aidl api')] logging.debug('Diffing api') result = subprocess.call([aidl_tool_path, '--checkapi', tmp_old_aidl_dir, tmp_new_aidl_dir]) if result != 0: return [output_api.PresubmitPromptWarning(_INCOMPATIBLE_API_ERROR_STRING)] finally: shutil.rmtree(tmp_old_contents_dir) shutil.rmtree(tmp_old_aidl_dir) shutil.rmtree(tmp_new_aidl_dir) return [] def CheckChangeOnUpload(input_api, output_api): filter_lambda = lambda x: input_api.FilterSourceFile( x, files_to_check=[r'.*\.aidl$' ]) aidl_files = [] for f in input_api.AffectedFiles(include_deletes=False, file_filter=filter_lambda): aidl_file = AidlFile(f) logging.debug('Possible aidl file %s', f.AbsoluteLocalPath()) if aidl_file.IsValid(): aidl_files.append(aidl_file) else: logging.warn('File matched aidl extension, but not valid ' + f.AbsoluteLocalPath()) if len(aidl_files) == 0: return [] return _CompareApiDumpForFiles(input_api, output_api, aidl_files)
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/PRESUBMIT.py
Python
unknown
6,651
// 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.interfaces; /** Keys for remote media service intent extras. */ public interface RemoteMediaServiceConstants { // Used as a key in the client's AndroidManifest.xml to enable remote media playback, i.e. // Presentation API, Remote Playback API, and Media Fling (automatic casting of html5 videos). // This exists because clients that already integrate with GMSCore cast framework may find WL's // integration problematic and need to turn it off. To use this, the application's // AndroidManifest.xml should have a meta-data tag with this name and value of false. The // default is true, i.e. enabled. // TODO(crbug.com/1148410): remove this. String FEATURE_ENABLED_KEY = "org.chromium.weblayer.ENABLE_REMOTE_MEDIA"; // Used internally by WebLayer as a key to the various values of remote media service // notification IDs. String NOTIFICATION_ID_KEY = "REMOTE_MEDIA_SERVICE_NOTIFICATION_ID_KEY"; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/RemoteMediaServiceConstants.java
Java
unknown
1,125
// 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.interfaces; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({ScrollNotificationType.DIRECTION_CHANGED_UP, ScrollNotificationType.DIRECTION_CHANGED_DOWN}) @Retention(RetentionPolicy.SOURCE) public @interface ScrollNotificationType { int DIRECTION_CHANGED_UP = 0; int DIRECTION_CHANGED_DOWN = 1; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/ScrollNotificationType.java
Java
unknown
576
// 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.interfaces; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({SettingType.BASIC_SAFE_BROWSING_ENABLED, SettingType.UKM_ENABLED, SettingType.EXTENDED_REPORTING_SAFE_BROWSING_ENABLED, SettingType.REAL_TIME_SAFE_BROWSING_ENABLED, SettingType.NETWORK_PREDICTION_ENABLED}) @Retention(RetentionPolicy.SOURCE) public @interface SettingType { int BASIC_SAFE_BROWSING_ENABLED = 0; int UKM_ENABLED = 1; int EXTENDED_REPORTING_SAFE_BROWSING_ENABLED = 2; int REAL_TIME_SAFE_BROWSING_ENABLED = 3; int NETWORK_PREDICTION_ENABLED = 4; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/SettingType.java
Java
unknown
821
// 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.interfaces; import android.os.Parcel; import android.os.StrictMode; import android.util.Log; import java.lang.reflect.Field; /** * Workaround to unset PENALTY_GATHER in StrictMode. * Normally the serialization code to set the PENALTY_GATHER bit in each AIDL * call and the IPC code unsets the bit. WebLayer only uses AIDL for * serialization, but not IPC; this leaves the PENALTY_GATHER bit always set, * causing any StrictMode violations to be gathered and serialized in ever AIDL * call but never reported. * StrictModeWorkaround.apply will unset the PENALTY_GATHER bit and should be * called at the beginning of the implementation of an AIDL call. */ public final class StrictModeWorkaround { private static final String TAG = "StrictModeWorkaround"; private static final int PENALTY_GATHER; private static final Field sThreadPolicyMaskField; static { Field field; int mask; try { field = StrictMode.ThreadPolicy.class.getDeclaredField("mask"); field.setAccessible(true); int currentMask = getCurrentPolicyMask(field); try { setCurrentPolicyMask(field, 0); // The value of PENALTY_GATHER has changed between Android // versions. Instead of hard coding them, try to get the value // from Parcel directly. Parcel parcel = Parcel.obtain(); // The value of the token does not matter. parcel.writeInterfaceToken(TAG); parcel.setDataPosition(0); mask = parcel.readInt(); parcel.recycle(); } finally { setCurrentPolicyMask(field, currentMask); } } catch (NoSuchFieldException | SecurityException e) { Log.w(TAG, "StrictMode reflection exception", e); field = null; mask = 0; } catch (RuntimeException e) { Log.w(TAG, "StrictMode run time exception", e); field = null; mask = 0; } sThreadPolicyMaskField = field; PENALTY_GATHER = mask; } private static int getCurrentPolicyMask(Field field) { StrictMode.ThreadPolicy policy = StrictMode.getThreadPolicy(); try { return field.getInt(policy); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private static void setCurrentPolicyMask(Field field, int newPolicyMask) { StrictMode.ThreadPolicy policy = StrictMode.getThreadPolicy(); try { field.setInt(policy, newPolicyMask); } catch (IllegalAccessException e) { throw new RuntimeException(e); } StrictMode.setThreadPolicy(policy); } public static void apply() { if (sThreadPolicyMaskField == null) return; try { int currentPolicyMask = getCurrentPolicyMask(sThreadPolicyMaskField); if ((currentPolicyMask & PENALTY_GATHER) == 0) { return; } setCurrentPolicyMask(sThreadPolicyMaskField, currentPolicyMask & ~PENALTY_GATHER); } catch (RuntimeException e) { // Ignore exceptions. } } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/StrictModeWorkaround.java
Java
unknown
3,453
// 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.interfaces; /** * Versioning related constants. */ public interface WebLayerVersionConstants { /** * Maximum allowed version skew. If the skew is greater than this, the implementation and client * are not considered compatible, and WebLayer is unusable. The skew is the absolute value of * the difference between the client major version and the implementation major version. * * @see WebLayer#isAvailable() */ int MAX_SKEW = 9; /** * Minimum version of client and implementation. */ int MIN_VERSION = 87; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/interfaces/WebLayerVersionConstants.java
Java
unknown
750
// 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.media; import android.content.Context; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import org.chromium.components.embedder_support.application.ClassLoaderContextWrapperFactory; import org.chromium.weblayer_private.FragmentHostingRemoteFragmentImpl; import org.chromium.weblayer_private.R; import org.chromium.weblayer_private.interfaces.IMediaRouteDialogFragment; import org.chromium.weblayer_private.interfaces.IRemoteFragment; import org.chromium.weblayer_private.interfaces.StrictModeWorkaround; import java.lang.ref.WeakReference; /** * WebLayer's implementation of the client library's MediaRouteDialogFragment. * * This class is the impl-side representation of a client fragment which is added to the browser * fragment, and is parent to MediaRouter-related {@link DialogFragment} instances. This class will * automatically clean up the client-side fragment when the child fragment is detached. */ public class MediaRouteDialogFragmentImpl extends FragmentHostingRemoteFragmentImpl { // The instance for the currently active dialog, if any. This is a WeakReference to get around // StaticFieldLeak warnings. private static WeakReference<MediaRouteDialogFragmentImpl> sInstanceForTest; private static class MediaRouteDialogContext extends FragmentHostingRemoteFragmentImpl.RemoteFragmentContext { public MediaRouteDialogContext(Context embedderContext) { super(ClassLoaderContextWrapperFactory.get(embedderContext)); // TODO(estade): this is necessary because MediaRouter dialogs crash if the theme has an // action bar. It's unclear why this is necessary when it's not in Chrome, and why // ContextThemeWrapper doesn't work. getTheme().applyStyle(R.style.Theme_BrowserUI_DayNight, /*force=*/true); } } public MediaRouteDialogFragmentImpl(Context context) { super(context); sInstanceForTest = new WeakReference<MediaRouteDialogFragmentImpl>(this); } @Override public void onAttach(Context context) { StrictModeWorkaround.apply(); super.onAttach(context); // Remove the host fragment as soon as the media router dialog fragment is detached. getSupportFragmentManager().registerFragmentLifecycleCallbacks( new FragmentManager.FragmentLifecycleCallbacks() { @Override public void onFragmentDetached(FragmentManager fm, Fragment f) { MediaRouteDialogFragmentImpl.this.removeFragmentFromFragmentManager(); } }, false); } @Override protected FragmentHostingRemoteFragmentImpl.RemoteFragmentContext createRemoteFragmentContext( Context embedderContext) { return new MediaRouteDialogContext(embedderContext); } public IMediaRouteDialogFragment asIMediaRouteDialogFragment() { return new IMediaRouteDialogFragment.Stub() { @Override public IRemoteFragment asRemoteFragment() { StrictModeWorkaround.apply(); return MediaRouteDialogFragmentImpl.this; } }; } public static MediaRouteDialogFragmentImpl fromRemoteFragment(IRemoteFragment remoteFragment) { return (MediaRouteDialogFragmentImpl) remoteFragment; } public static MediaRouteDialogFragmentImpl getInstanceForTest() { return sInstanceForTest.get(); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/media/MediaRouteDialogFragmentImpl.java
Java
unknown
3,711
// 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.media; import android.app.Application; import android.app.Service; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.support.v4.media.session.MediaSessionCompat; import androidx.fragment.app.FragmentManager; import androidx.mediarouter.media.MediaRouter; import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.components.browser_ui.media.MediaNotificationController; import org.chromium.components.browser_ui.media.MediaNotificationInfo; import org.chromium.components.browser_ui.media.MediaNotificationManager; import org.chromium.components.browser_ui.notifications.NotificationWrapper; import org.chromium.components.browser_ui.notifications.NotificationWrapperBuilder; import org.chromium.components.media_router.MediaRouterClient; import org.chromium.content_public.browser.WebContents; import org.chromium.weblayer_private.IntentUtils; import org.chromium.weblayer_private.TabImpl; import org.chromium.weblayer_private.WebLayerFactoryImpl; import org.chromium.weblayer_private.WebLayerImpl; import org.chromium.weblayer_private.interfaces.RemoteMediaServiceConstants; /** Provides WebLayer-specific behavior for Media Router. */ @JNINamespace("weblayer") public class MediaRouterClientImpl extends MediaRouterClient { static int sPresentationNotificationId; static int sRemotingNotificationId; private MediaRouterClientImpl() {} public static void serviceStarted(Service service, Intent intent) { int notificationId = intent.getIntExtra(RemoteMediaServiceConstants.NOTIFICATION_ID_KEY, 0); if (notificationId == 0) { throw new RuntimeException("Invalid RemoteMediaService notification id"); } MediaSessionNotificationHelper.serviceStarted(service, intent, notificationId); } public static void serviceDestroyed(int notificationId) { MediaSessionNotificationHelper.serviceDestroyed(notificationId); } @Override public Context getContextForRemoting() { return getContextForRemotingImpl(); } @Override public int getTabId(WebContents webContents) { TabImpl tab = TabImpl.fromWebContents(webContents); return tab == null ? -1 : tab.getId(); } @Override public Intent createBringTabToFrontIntent(int tabId) { return IntentUtils.createBringTabToFrontIntent(tabId); } @Override public void showNotification(MediaNotificationInfo notificationInfo) { MediaNotificationManager.show(notificationInfo, () -> { return new MediaRouterNotificationControllerDelegate(notificationInfo.id); }); } @Override public int getPresentationNotificationId() { return getPresentationNotificationIdFromClient(); } @Override public int getRemotingNotificationId() { return getRemotingNotificationIdFromClient(); } @Override public FragmentManager getSupportFragmentManager(WebContents initiator) { return null; } @Override // TODO(crbug.com/1377518): Implement addDeferredTask(). public void addDeferredTask(Runnable deferredTask) { deferredTask.run(); } @Override public boolean isCafMrpDeferredDiscoveryEnabled() { return true; } @Override public boolean isCastAnotherContentWhileCastingEnabled() { return true; } @CalledByNative public static void initialize() { if (MediaRouterClient.getInstance() != null) return; MediaRouterClient.setInstance(new MediaRouterClientImpl()); } @CalledByNative public static boolean isMediaRouterEnabled() { if (WebLayerFactoryImpl.getClientMajorVersion() < 88) return false; Context context = ContextUtils.getApplicationContext(); try { ApplicationInfo ai = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); return ai.metaData.getBoolean(RemoteMediaServiceConstants.FEATURE_ENABLED_KEY, true); } catch (NameNotFoundException e) { return true; } } private static class MediaRouterNotificationControllerDelegate implements MediaNotificationController.Delegate { // The ID distinguishes between Presentation and Remoting services/notifications. private final int mNotificationId; MediaRouterNotificationControllerDelegate(int notificationId) { mNotificationId = notificationId; } @Override public Intent createServiceIntent() { return WebLayerImpl.createRemoteMediaServiceIntent().putExtra( RemoteMediaServiceConstants.NOTIFICATION_ID_KEY, mNotificationId); } @Override public String getAppName() { return WebLayerImpl.getClientApplicationName(); } @Override public String getNotificationGroupName() { if (mNotificationId == getPresentationNotificationIdFromClient()) { return "org.chromium.weblayer.PresentationApi"; } assert mNotificationId == getRemotingNotificationIdFromClient(); return "org.chromium.weblayer.RemotePlaybackApi"; } @Override public NotificationWrapperBuilder createNotificationWrapperBuilder() { return MediaSessionNotificationHelper.createNotificationWrapperBuilder(mNotificationId); } @Override public void onMediaSessionUpdated(MediaSessionCompat session) { MediaRouter.getInstance(getContextForRemotingImpl()).setMediaSessionCompat(session); } @Override public void logNotificationShown(NotificationWrapper notification) {} } private static int getPresentationNotificationIdFromClient() { if (sPresentationNotificationId == 0) { sPresentationNotificationId = WebLayerImpl.getPresentationApiNotificationId(); } return sPresentationNotificationId; } private static int getRemotingNotificationIdFromClient() { if (sRemotingNotificationId == 0) { sRemotingNotificationId = WebLayerImpl.getRemotePlaybackApiNotificationId(); } return sRemotingNotificationId; } private static Context getContextForRemotingImpl() { Context context = ContextUtils.getApplicationContext(); // The GMS Cast framework assumes the passed {@link Context} returns an instance of {@link // Application} from {@link getApplicationContext()}, so we make sure to remove any // wrappers. while (!(context.getApplicationContext() instanceof Application)) { if (context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } else { return null; } } return context; } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/media/MediaRouterClientImpl.java
Java
unknown
7,394
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.weblayer_private.media; import android.app.Service; import android.content.Intent; import android.support.v4.media.session.MediaSessionCompat; import org.chromium.components.browser_ui.media.MediaNotificationController; import org.chromium.components.browser_ui.media.MediaNotificationInfo; import org.chromium.components.browser_ui.media.MediaNotificationManager; import org.chromium.components.browser_ui.media.MediaSessionHelper; import org.chromium.components.browser_ui.notifications.NotificationWrapper; import org.chromium.components.browser_ui.notifications.NotificationWrapperBuilder; import org.chromium.content_public.browser.BrowserContextHandle; import org.chromium.weblayer_private.IntentUtils; import org.chromium.weblayer_private.TabImpl; import org.chromium.weblayer_private.WebLayerImpl; /** * A glue class for MediaSession. * This class defines delegates that provide WebLayer-specific behavior to shared MediaSession code. * It also manages the lifetime of {@link MediaNotificationController} and the {@link Service} * associated with the notification. */ public class MediaSessionManager { private static int sNotificationId; public static void serviceStarted(Service service, Intent intent) { MediaSessionNotificationHelper.serviceStarted(service, intent, getNotificationId()); } public static void serviceDestroyed() { MediaSessionNotificationHelper.serviceDestroyed(getNotificationId()); } public static MediaSessionHelper.Delegate createMediaSessionHelperDelegate(TabImpl tab) { return new MediaSessionHelper.Delegate() { @Override public Intent createBringTabToFrontIntent() { return IntentUtils.createBringTabToFrontIntent(tab.getId()); } @Override public BrowserContextHandle getBrowserContextHandle() { return tab.getProfile(); } @Override public MediaNotificationInfo.Builder createMediaNotificationInfoBuilder() { return new MediaNotificationInfo.Builder() .setInstanceId(tab.getId()) .setId(getNotificationId()); } @Override public void showMediaNotification(MediaNotificationInfo notificationInfo) { assert notificationInfo.id == getNotificationId(); MediaNotificationManager.show(notificationInfo, () -> { return new WebLayerMediaNotificationControllerDelegate(); }); } @Override public void hideMediaNotification() { MediaNotificationManager.hide(tab.getId(), getNotificationId()); } @Override public void activateAndroidMediaSession() { MediaNotificationManager.activateAndroidMediaSession( tab.getId(), getNotificationId()); } }; } private static class WebLayerMediaNotificationControllerDelegate implements MediaNotificationController.Delegate { @Override public Intent createServiceIntent() { return WebLayerImpl.createMediaSessionServiceIntent(); } @Override public String getAppName() { return WebLayerImpl.getClientApplicationName(); } @Override public String getNotificationGroupName() { return "org.chromium.weblayer.MediaSession"; } @Override public NotificationWrapperBuilder createNotificationWrapperBuilder() { return MediaSessionNotificationHelper.createNotificationWrapperBuilder( getNotificationId()); } @Override public void onMediaSessionUpdated(MediaSessionCompat session) { // This is only relevant when casting. } @Override public void logNotificationShown(NotificationWrapper notification) {} } private static int getNotificationId() { if (sNotificationId == 0) sNotificationId = WebLayerImpl.getMediaSessionNotificationId(); return sNotificationId; } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/media/MediaSessionManager.java
Java
unknown
4,343
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.weblayer_private.media; import android.app.Service; import android.content.Intent; import org.chromium.components.browser_ui.media.MediaNotificationController; import org.chromium.components.browser_ui.media.MediaNotificationManager; import org.chromium.components.browser_ui.notifications.ForegroundServiceUtils; import org.chromium.components.browser_ui.notifications.NotificationMetadata; import org.chromium.components.browser_ui.notifications.NotificationWrapperBuilder; import org.chromium.weblayer_private.WebLayerNotificationChannels; import org.chromium.weblayer_private.WebLayerNotificationWrapperBuilder; /** * A helper class for management of MediaSession (local device), Presentation API and Remote * Playback API (casting) notifications and foreground services. */ class MediaSessionNotificationHelper { static void serviceStarted(Service service, Intent intent, int notificationId) { MediaNotificationController controller = MediaNotificationManager.getController(notificationId); if (controller != null && controller.processIntent(service, intent)) return; // The service has been started with startForegroundService() but the // notification hasn't been shown. See similar logic in {@link // ChromeMediaNotificationControllerDelegate}. MediaNotificationController.finishStartingForegroundServiceOnO(service, createNotificationWrapperBuilder(notificationId).buildNotificationWrapper()); // Call stopForeground to guarantee Android unset the foreground bit. ForegroundServiceUtils.getInstance().stopForeground( service, Service.STOP_FOREGROUND_REMOVE); service.stopSelf(); } static void serviceDestroyed(int notificationId) { MediaNotificationController controller = MediaNotificationManager.getController(notificationId); if (controller != null) controller.onServiceDestroyed(); MediaNotificationManager.clear(notificationId); } static NotificationWrapperBuilder createNotificationWrapperBuilder(int notificationId) { // Only the null tag will work as expected, because {@link Service#startForeground()} only // takes an ID and no tag. If we pass a tag here, then the notification that's used to // display a paused state (no foreground service) will not be identified as the same one // that's used with the foreground service. return WebLayerNotificationWrapperBuilder.create( WebLayerNotificationChannels.ChannelId.MEDIA_PLAYBACK, new NotificationMetadata(0, null /*notificationTag*/, notificationId)); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/media/MediaSessionNotificationHelper.java
Java
unknown
2,856
// 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.media; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.RemoteException; import android.util.AndroidRuntimeException; import android.webkit.ValueCallback; 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.components.browser_ui.notifications.NotificationManagerProxy; import org.chromium.components.browser_ui.notifications.NotificationManagerProxyImpl; import org.chromium.components.browser_ui.notifications.NotificationMetadata; import org.chromium.components.browser_ui.notifications.NotificationWrapper; import org.chromium.components.browser_ui.notifications.PendingIntentProvider; import org.chromium.components.webrtc.MediaCaptureNotificationUtil; import org.chromium.components.webrtc.MediaCaptureNotificationUtil.MediaType; import org.chromium.content_public.browser.WebContents; import org.chromium.weblayer_private.IntentUtils; import org.chromium.weblayer_private.TabImpl; import org.chromium.weblayer_private.WebLayerImpl; import org.chromium.weblayer_private.WebLayerNotificationChannels; import org.chromium.weblayer_private.WebLayerNotificationWrapperBuilder; import org.chromium.weblayer_private.interfaces.IMediaCaptureCallbackClient; import org.chromium.weblayer_private.interfaces.ObjectWrapper; import java.util.HashSet; import java.util.Set; /** * A per-tab object that manages notifications for ongoing media capture streams * (microphone/camera). This object is created by {@link TabImpl} and creates and destroys its * native equivalent. */ @JNINamespace("weblayer") public class MediaStreamManager { private static final String WEBRTC_PREFIX = "org.chromium.weblayer.webrtc"; private static final String AV_STREAM_TAG = WEBRTC_PREFIX + ".avstream"; /** * A key used in the app's shared preferences to track a set of active streaming notifications. * This is used to clear notifications that may have persisted across restarts due to a crash. * TODO(estade): remove this approach and simply iterate across all notifications via * {@link NotificationManager#getActiveNotifications} once the minimum API level is 23. */ private static final String PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS = WEBRTC_PREFIX + ".avstream_notifications"; private IMediaCaptureCallbackClient mClient; private TabImpl mTab; // The notification ID matches the tab ID, which uniquely identifies the notification when // paired with the tag. private int mNotificationId; // Pointer to the native MediaStreamManager. private long mNative; /** * To be called when WebLayer is started. Clears notifications that may have persisted from * before a crash. */ public static void onWebLayerInit() { SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); Set<String> staleNotificationIds = prefs.getStringSet(PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS, null); if (staleNotificationIds == null) return; NotificationManagerProxy manager = getNotificationManager(); if (manager == null) return; for (String id : staleNotificationIds) { manager.cancel(AV_STREAM_TAG, Integer.parseInt(id)); } prefs.edit().remove(PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS).apply(); } public MediaStreamManager(TabImpl tab) { mTab = tab; mNotificationId = tab.getId(); mNative = MediaStreamManagerJni.get().create(this, tab.getWebContents()); } public void destroy() { cancelNotification(); MediaStreamManagerJni.get().destroy(mNative); mNative = 0; mClient = null; } public void setClient(IMediaCaptureCallbackClient client) { mClient = client; } public void stopStreaming() { MediaStreamManagerJni.get().stopStreaming(mNative); } private void cancelNotification() { NotificationManagerProxy notificationManager = getNotificationManager(); if (notificationManager != null) { notificationManager.cancel(AV_STREAM_TAG, mNotificationId); } notifyClient(false, false); updateActiveNotifications(false); } private void notifyClient(boolean audio, boolean video) { if (mClient != null) { try { mClient.onMediaCaptureStateChanged(audio, video); } catch (RemoteException e) { throw new AndroidRuntimeException(e); } } } /** * Updates the list of active notifications stored in the SharedPrefences. * * @param active if true, then {@link mNotificationId} will be added to the list of active * notifications, otherwise it will be removed. */ private void updateActiveNotifications(boolean active) { SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); Set<String> activeIds = new HashSet<String>( prefs.getStringSet(PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS, new HashSet<String>())); if (active) { activeIds.add(Integer.toString(mNotificationId)); } else { activeIds.remove(Integer.toString(mNotificationId)); } prefs.edit() .putStringSet(PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS, activeIds.isEmpty() ? null : activeIds) .apply(); } @CalledByNative private void prepareToStream(boolean audio, boolean video, int requestId) throws RemoteException { if (mClient == null) { respondToStreamRequest(requestId, true); } else { mClient.onMediaCaptureRequested( audio, video, ObjectWrapper.wrap(new ValueCallback<Boolean>() { @Override public void onReceiveValue(Boolean allowed) { ThreadUtils.assertOnUiThread(); respondToStreamRequest(requestId, allowed.booleanValue()); } })); } } private void respondToStreamRequest(int requestId, boolean allow) { if (mNative == 0) return; MediaStreamManagerJni.get().onClientReadyToStream(mNative, requestId, allow); } /** * Called after the tab's media streaming state has changed. * * A notification should be shown (or updated) iff one of the parameters is true, otherwise * any existing notification will be removed. * * @param audio true if the tab is streaming audio. * @param video true if the tab is streaming video. */ @CalledByNative private void update(boolean audio, boolean video) { if (!audio && !video) { cancelNotification(); return; } Context appContext = ContextUtils.getApplicationContext(); Intent intent = IntentUtils.createBringTabToFrontIntent(mNotificationId); PendingIntentProvider contentIntent = PendingIntentProvider.getBroadcast(appContext, mNotificationId, intent, 0); int mediaType = audio && video ? MediaType.AUDIO_AND_VIDEO : audio ? MediaType.AUDIO_ONLY : MediaType.VIDEO_ONLY; NotificationWrapper notification = MediaCaptureNotificationUtil.createNotification( WebLayerNotificationWrapperBuilder.create( WebLayerNotificationChannels.ChannelId.WEBRTC_CAM_AND_MIC, new NotificationMetadata(0, AV_STREAM_TAG, mNotificationId)), mediaType, mTab.getProfile().isIncognito() ? null : mTab.getWebContents().getVisibleUrl().getSpec(), WebLayerImpl.getClientApplicationName(), contentIntent, null /*stopIntent*/); getNotificationManager().notify(notification); updateActiveNotifications(true); notifyClient(audio, video); } private static NotificationManagerProxy getNotificationManager() { return new NotificationManagerProxyImpl(ContextUtils.getApplicationContext()); } @NativeMethods interface Natives { long create(MediaStreamManager caller, WebContents webContents); void destroy(long manager); void onClientReadyToStream(long nativeMediaStreamManager, int requestId, boolean allow); void stopStreaming(long nativeMediaStreamManager); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/media/MediaStreamManager.java
Java
unknown
8,943
// 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.metrics; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.weblayer_private.GmsBridge; /** * Determines user consent and app opt-out for metrics. See metrics_service_client.h for more * explanation. * * TODO(weblayer-team): Consider compoentizing once requirements are nailed down. */ @JNINamespace("weblayer") public class MetricsServiceClient { private static final String TAG = "MetricsServiceClie-"; // Individual apps can use this meta-data tag in their manifest to opt out of metrics. private static final String AUTO_UPLOAD_METADATA_STR = "android.WebLayer.MetricsAutoUpload"; private static boolean isAppOptedOut(Context ctx) { try { ApplicationInfo info = ctx.getPackageManager().getApplicationInfo( ctx.getPackageName(), PackageManager.GET_META_DATA); if (info.metaData == null) { // null means no such tag was found which we interpret as not opting out. return false; } // getBoolean returns false if the key is not found, which is what we want. return info.metaData.getBoolean(AUTO_UPLOAD_METADATA_STR); } catch (PackageManager.NameNotFoundException e) { // This should never happen. Log.e(TAG, "App could not find itself by package name!"); // The conservative thing is to assume the app HAS opted out. return true; } } public static void init() { GmsBridge.getInstance().queryMetricsSetting(userConsent -> { MetricsServiceClientJni.get().setHaveMetricsConsent( userConsent, !isAppOptedOut(ContextUtils.getApplicationContext())); }); } @NativeMethods interface Natives { void setHaveMetricsConsent(boolean userConsent, boolean appConsent); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/metrics/MetricsServiceClient.java
Java
unknown
2,290
// 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.metrics; import android.os.SystemClock; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; /** * Utilities to support startup metrics */ @JNINamespace("weblayer") public class UmaUtils { private static long sApplicationStartTimeMs; /** * Record the time in the application lifecycle at which WebLayer code first runs. */ public static void recordMainEntryPointTime() { // We can't simply pass this down through a JNI call, since the JNI for weblayer // isn't initialized until we start the native content browser component, and we // then need the start time in the C++ side before we return to Java. As such we // save it in a static that the C++ can fetch once it has initialized the JNI. sApplicationStartTimeMs = SystemClock.uptimeMillis(); } @CalledByNative public static long getApplicationStartTime() { return sApplicationStartTimeMs; } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/metrics/UmaUtils.java
Java
unknown
1,174
// 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.payments; import androidx.annotation.Nullable; import org.chromium.components.payments.BrowserPaymentRequest; import org.chromium.components.payments.InvalidPaymentRequest; import org.chromium.components.payments.MojoPaymentRequestGateKeeper; import org.chromium.components.payments.OriginSecurityChecker; import org.chromium.components.payments.PaymentAppServiceBridge; import org.chromium.components.payments.PaymentFeatureList; import org.chromium.components.payments.PaymentRequestService; import org.chromium.components.payments.PaymentRequestServiceUtil; import org.chromium.components.payments.PrefsStrings; import org.chromium.components.payments.SslValidityChecker; import org.chromium.components.user_prefs.UserPrefs; import org.chromium.content_public.browser.BrowserContextHandle; import org.chromium.content_public.browser.PermissionsPolicyFeature; import org.chromium.content_public.browser.RenderFrameHost; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsStatics; import org.chromium.payments.mojom.PaymentRequest; import org.chromium.services.service_manager.InterfaceFactory; import org.chromium.url.GURL; import org.chromium.weblayer_private.ProfileImpl; import org.chromium.weblayer_private.TabImpl; /** Creates an instance of PaymentRequest for use in WebLayer. */ public class WebLayerPaymentRequestFactory implements InterfaceFactory<PaymentRequest> { private final RenderFrameHost mRenderFrameHost; /** * Production implementation of the WebLayerPaymentRequestService's Delegate. Gives true answers * about the system. */ private static class WebLayerPaymentRequestDelegateImpl implements PaymentRequestService.Delegate { private final RenderFrameHost mRenderFrameHost; /* package */ WebLayerPaymentRequestDelegateImpl(RenderFrameHost renderFrameHost) { mRenderFrameHost = renderFrameHost; } @Override public BrowserPaymentRequest createBrowserPaymentRequest( PaymentRequestService paymentRequestService) { return new WebLayerPaymentRequestService(paymentRequestService, this); } @Override public boolean isOffTheRecord() { ProfileImpl profile = getProfile(); if (profile == null) return true; return profile.isIncognito(); } @Override public String getInvalidSslCertificateErrorMessage() { WebContents webContents = PaymentRequestServiceUtil.getLiveWebContents(mRenderFrameHost); if (webContents == null || webContents.isDestroyed()) return null; GURL url = webContents.getLastCommittedUrl(); if (url == null || !OriginSecurityChecker.isSchemeCryptographic(url)) { return null; } return SslValidityChecker.getInvalidSslCertificateErrorMessage(webContents); } @Override public boolean prefsCanMakePayment() { BrowserContextHandle profile = getProfile(); return profile != null && UserPrefs.get(profile).getBoolean(PrefsStrings.CAN_MAKE_PAYMENT_ENABLED); } @Nullable @Override public String getTwaPackageName() { return null; } @Nullable private ProfileImpl getProfile() { WebContents webContents = PaymentRequestServiceUtil.getLiveWebContents(mRenderFrameHost); if (webContents == null) return null; TabImpl tab = TabImpl.fromWebContents(webContents); if (tab == null) return null; return tab.getProfile(); } } /** * Creates an instance of WebLayerPaymentRequestFactory. * @param renderFrameHost The frame that issues the payment request on the merchant page. */ public WebLayerPaymentRequestFactory(RenderFrameHost renderFrameHost) { mRenderFrameHost = renderFrameHost; } @Override public PaymentRequest createImpl() { if (mRenderFrameHost == null) return new InvalidPaymentRequest(); if (!mRenderFrameHost.isFeatureEnabled(PermissionsPolicyFeature.PAYMENT)) { mRenderFrameHost.terminateRendererDueToBadMessage(241 /*PAYMENTS_WITHOUT_PERMISSION*/); return null; } if (!PaymentFeatureList.isEnabled(PaymentFeatureList.WEB_PAYMENTS)) { return new InvalidPaymentRequest(); } PaymentRequestService.Delegate delegate = new WebLayerPaymentRequestDelegateImpl(mRenderFrameHost); WebContents webContents = WebContentsStatics.fromRenderFrameHost(mRenderFrameHost); if (webContents == null || webContents.isDestroyed()) return new InvalidPaymentRequest(); return new MojoPaymentRequestGateKeeper( (client, onClosed) -> new PaymentRequestService(mRenderFrameHost, client, onClosed, delegate, PaymentAppServiceBridge::new)); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/payments/WebLayerPaymentRequestFactory.java
Java
unknown
5,284
// 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.payments; import androidx.annotation.Nullable; import org.chromium.components.payments.BrowserPaymentRequest; import org.chromium.components.payments.JourneyLogger; import org.chromium.components.payments.PaymentApp; import org.chromium.components.payments.PaymentAppType; import org.chromium.components.payments.PaymentRequestService; import org.chromium.components.payments.PaymentRequestService.Delegate; import org.chromium.components.payments.PaymentRequestSpec; import org.chromium.components.payments.PaymentResponseHelper; import org.chromium.components.payments.PaymentResponseHelperInterface; import org.chromium.payments.mojom.PaymentDetails; import org.chromium.payments.mojom.PaymentErrorReason; import org.chromium.payments.mojom.PaymentItem; import org.chromium.payments.mojom.PaymentValidationErrors; import java.util.ArrayList; import java.util.List; /** The WebLayer-specific part of the payment request service. */ public class WebLayerPaymentRequestService implements BrowserPaymentRequest { private final List<PaymentApp> mAvailableApps = new ArrayList<>(); private final JourneyLogger mJourneyLogger; private PaymentRequestService mPaymentRequestService; private PaymentRequestSpec mSpec; private boolean mHasClosed; private boolean mShouldSkipAppSelector; private PaymentApp mSelectedApp; /** * Create an instance of {@link WebLayerPaymentRequestService}. * @param paymentRequestService The payment request service. * @param delegate The delegate of the payment request service. */ public WebLayerPaymentRequestService( PaymentRequestService paymentRequestService, Delegate delegate) { mPaymentRequestService = paymentRequestService; mJourneyLogger = mPaymentRequestService.getJourneyLogger(); } // Implements BrowserPaymentRequest: @Override public void onPaymentDetailsUpdated( PaymentDetails details, boolean hasNotifiedInvokedPaymentApp) {} // Implements BrowserPaymentRequest: @Override public void onPaymentDetailsNotUpdated(String selectedShippingOptionError) {} @Override public boolean onPaymentAppCreated(PaymentApp paymentApp) { // Ignores the service worker payment apps in WebLayer until - // TODO(crbug.com/1224420): WebLayer supports Service worker payment apps. return paymentApp.getPaymentAppType() != PaymentAppType.SERVICE_WORKER_APP; } // Implements BrowserPaymentRequest: @Override public void complete(int result, Runnable onCompleteHandled) { onCompleteHandled.run(); } // Implements BrowserPaymentRequest: @Override public void onRetry(PaymentValidationErrors errors) {} // Implements BrowserPaymentRequest: @Override public void close() { if (mHasClosed) return; mHasClosed = true; if (mPaymentRequestService != null) { mPaymentRequestService.close(); mPaymentRequestService = null; } } // Implements BrowserPaymentRequest: @Override public boolean hasAvailableApps() { return !mAvailableApps.isEmpty(); } // Implements BrowserPaymentRequest: @Override public void notifyPaymentUiOfPendingApps(List<PaymentApp> pendingApps) { assert mAvailableApps.isEmpty() : "notifyPaymentUiOfPendingApps() should be called at most once."; mAvailableApps.addAll(pendingApps); mSelectedApp = mAvailableApps.size() == 0 ? null : mAvailableApps.get(0); } // Implements BrowserPaymentRequest: @Override public void onSpecValidated(PaymentRequestSpec spec) { mSpec = spec; } // Implements BrowserPaymentRequest: @Override @Nullable public String showOrSkipAppSelector(boolean isShowWaitingForUpdatedDetails, PaymentItem total, boolean shouldSkipAppSelector) { mShouldSkipAppSelector = shouldSkipAppSelector; if (!mShouldSkipAppSelector) { return "This request is not supported in Web Layer. Please try in Chrome, or make sure " + "that: (1) show() is triggered by user gesture, or" + "(2) do not request any contact information."; } return null; } // Implements BrowserPaymentRequest: @Override @Nullable public String onShowCalledAndAppsQueriedAndDetailsFinalized() { assert !mAvailableApps.isEmpty() : "triggerPaymentAppUiSkipIfApplicable() should be called only when there is any " + "available app."; PaymentApp selectedPaymentApp = mAvailableApps.get(0); if (mShouldSkipAppSelector) { mJourneyLogger.setSkippedShow(); PaymentResponseHelperInterface paymentResponseHelper = new PaymentResponseHelper(selectedPaymentApp, mSpec.getPaymentOptions()); mPaymentRequestService.invokePaymentApp(selectedPaymentApp, paymentResponseHelper); } return null; } // Implements BrowserPaymentRequest: @Override public PaymentApp getSelectedPaymentApp() { return mAvailableApps.get(0); } // Implements BrowserPaymentRequest: @Override public List<PaymentApp> getPaymentApps() { return mAvailableApps; } // Implements BrowserPaymentRequest: @Override public boolean hasAnyCompleteApp() { return !mAvailableApps.isEmpty() && mAvailableApps.get(0).isComplete(); } private void disconnectFromClientWithDebugMessage(String debugMessage) { if (mPaymentRequestService != null) { mPaymentRequestService.disconnectFromClientWithDebugMessage( debugMessage, PaymentErrorReason.USER_CANCEL); } close(); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/payments/WebLayerPaymentRequestService.java
Java
unknown
5,978
// 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.payments; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; import org.robolectric.annotation.Config; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.JniMocker; import org.chromium.components.payments.ErrorMessageUtil; import org.chromium.components.payments.ErrorMessageUtilJni; import org.chromium.components.payments.PayerData; import org.chromium.components.payments.PaymentApp; import org.chromium.components.payments.PaymentApp.InstrumentDetailsCallback; import org.chromium.components.payments.PaymentAppFactoryDelegate; import org.chromium.components.payments.PaymentAppFactoryInterface; import org.chromium.components.payments.PaymentAppService; import org.chromium.components.payments.PaymentRequestService; import org.chromium.components.payments.test_support.ShadowPaymentFeatureList; import org.chromium.payments.mojom.PaymentRequest; import org.chromium.payments.mojom.PaymentRequestClient; import org.chromium.payments.mojom.PaymentResponse; import org.chromium.weblayer_private.payments.test_support.WebLayerPaymentRequestBuilder; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * A test for the integration of PaymentRequestService, MojoPaymentRequestGateKeeper, * WebLayerPaymentRequestService and PaymentAppService. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {ShadowPaymentFeatureList.class}) public class WebLayerPaymentRequestServiceTest { private static final String METHOD_NAME = "https://www.chromium.org"; private static final String STRINGIFIED_DETAILS = "test stringifiedDetails"; private final ArgumentCaptor<InstrumentDetailsCallback> mPaymentAppCallbackCaptor = ArgumentCaptor.forClass(InstrumentDetailsCallback.class); @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule().strictness(Strictness.WARN); @Rule public JniMocker mJniMocker = new JniMocker(); @Mock private ErrorMessageUtil.Natives mErrorMessageUtilMock; private PaymentRequestClient mClient; private PaymentAppFactoryInterface mFactory; private PaymentApp mPaymentApp; private boolean mWaitForUpdatedDetails; @Before public void setUp() { mJniMocker.mock(ErrorMessageUtilJni.TEST_HOOKS, mErrorMessageUtilMock); Mockito.doAnswer(args -> { String[] methods = args.getArgument(0); return "(Mock) Not supported error: " + Arrays.toString(methods); }) .when(mErrorMessageUtilMock) .getNotSupportedErrorMessage(Mockito.any()); ShadowPaymentFeatureList.setDefaultStatuses(); PaymentRequestService.resetShowingPaymentRequestForTest(); PaymentAppService.getInstance().resetForTest(); mClient = Mockito.mock(PaymentRequestClient.class); mPaymentApp = mockPaymentApp(); mFactory = Mockito.mock(PaymentAppFactoryInterface.class); Mockito.doAnswer((args) -> { PaymentAppFactoryDelegate delegate = args.getArgument(0); delegate.onCanMakePaymentCalculated(true); delegate.onPaymentAppCreated(mPaymentApp); delegate.onDoneCreatingPaymentApps(mFactory); return null; }) .when(mFactory) .create(Mockito.any()); } @After public void tearDown() { PaymentRequestService.resetShowingPaymentRequestForTest(); PaymentAppService.getInstance().resetForTest(); } private PaymentApp mockPaymentApp() { PaymentApp app = Mockito.mock(PaymentApp.class); Set<String> methodNames = new HashSet<>(); methodNames.add(METHOD_NAME); Mockito.doReturn(methodNames).when(app).getInstrumentMethodNames(); Mockito.doReturn("testPaymentApp").when(app).getIdentifier(); Mockito.doReturn(true).when(app).handlesShippingAddress(); return app; } private WebLayerPaymentRequestBuilder defaultBuilder() { WebLayerPaymentRequestBuilder builder = WebLayerPaymentRequestBuilder.defaultBuilder(mClient); PaymentAppService.getInstance().addUniqueFactory(mFactory, "testFactoryId"); return builder; } private void show(PaymentRequest request) { request.show(mWaitForUpdatedDetails); } private void assertNoError() { Mockito.verify(mClient, Mockito.never()).onError(Mockito.anyInt(), Mockito.anyString()); } private void assertResponse() { ArgumentCaptor<PaymentResponse> responseCaptor = ArgumentCaptor.forClass(PaymentResponse.class); Mockito.verify(mClient, Mockito.times(1)).onPaymentResponse(responseCaptor.capture()); PaymentResponse response = responseCaptor.getValue(); Assert.assertNotNull(response); Assert.assertEquals(METHOD_NAME, response.methodName); Assert.assertEquals(STRINGIFIED_DETAILS, response.stringifiedDetails); } private void assertInvokePaymentAppCalled() { Mockito.verify(mPaymentApp, Mockito.times(1)) .invokePaymentApp(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), mPaymentAppCallbackCaptor.capture()); } private void simulatePaymentAppRespond() { mPaymentAppCallbackCaptor.getValue().onInstrumentDetailsReady( METHOD_NAME, STRINGIFIED_DETAILS, new PayerData()); } @Test @Feature({"Payments"}) public void testPaymentIsSuccessful() { PaymentRequest request = defaultBuilder().buildAndInit(); Assert.assertNotNull(request); assertNoError(); show(request); assertNoError(); assertInvokePaymentAppCalled(); simulatePaymentAppRespond(); assertResponse(); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/payments/WebLayerPaymentRequestServiceTest.java
Java
unknown
6,569
// 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.payments.test_support; import android.content.Context; import androidx.annotation.Nullable; import org.mockito.Mockito; import org.chromium.components.payments.BrowserPaymentRequest; import org.chromium.components.payments.JourneyLogger; import org.chromium.components.payments.MojoPaymentRequestGateKeeper; import org.chromium.components.payments.PaymentAppFactoryInterface; import org.chromium.components.payments.PaymentRequestService; import org.chromium.components.payments.PaymentRequestSpec; import org.chromium.content_public.browser.RenderFrameHost; import org.chromium.content_public.browser.WebContents; import org.chromium.payments.mojom.PaymentCurrencyAmount; import org.chromium.payments.mojom.PaymentDetails; import org.chromium.payments.mojom.PaymentItem; import org.chromium.payments.mojom.PaymentMethodData; import org.chromium.payments.mojom.PaymentOptions; import org.chromium.payments.mojom.PaymentRequest; import org.chromium.payments.mojom.PaymentRequestClient; import org.chromium.ui.base.WindowAndroid; import org.chromium.url.GURL; import org.chromium.url.JUnitTestGURLs; import org.chromium.url.Origin; import org.chromium.weblayer_private.payments.WebLayerPaymentRequestService; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** The builder of PaymentRequest used in WebLayer, for testing purpose only. */ public class WebLayerPaymentRequestBuilder implements PaymentRequestService.Delegate { private final PaymentRequestClient mClient; private final PaymentRequestService.Delegate mDelegate; private final RenderFrameHost mRenderFrameHost; private final PaymentMethodData[] mMethodData; private final PaymentDetails mDetails; private final WebContents mWebContents; private final JourneyLogger mJourneyLogger; private final PaymentRequestSpec mSpec; private final PaymentOptions mOptions; private String mSupportedMethod = "https://www.chromium.org"; /** * Create a default builder. * @param client The PaymentRequestClient used for this PaymentRequest. * @return The created builder. */ public static WebLayerPaymentRequestBuilder defaultBuilder(PaymentRequestClient client) { return new WebLayerPaymentRequestBuilder(client); } private WebLayerPaymentRequestBuilder(PaymentRequestClient client) { mClient = client; mDelegate = this; mJourneyLogger = Mockito.mock(JourneyLogger.class); mWebContents = Mockito.mock(WebContents.class); Mockito.doReturn(JUnitTestGURLs.getGURL(JUnitTestGURLs.URL_1)) .when(mWebContents) .getLastCommittedUrl(); mRenderFrameHost = Mockito.mock(RenderFrameHost.class); Mockito.doReturn(JUnitTestGURLs.getGURL(JUnitTestGURLs.URL_2)) .when(mRenderFrameHost) .getLastCommittedURL(); Origin origin = Mockito.mock(Origin.class); Mockito.doReturn(origin).when(mRenderFrameHost).getLastCommittedOrigin(); mMethodData = new PaymentMethodData[1]; mDetails = new PaymentDetails(); mDetails.id = "testId"; mDetails.total = new PaymentItem(); mOptions = new PaymentOptions(); mSpec = Mockito.mock(PaymentRequestSpec.class); } /** * Build PaymentRequest and calls its init(). * @return The built and initialized PaymentRequest. */ public PaymentRequest buildAndInit() { mMethodData[0] = new PaymentMethodData(); mMethodData[0].supportedMethod = mSupportedMethod; PaymentCurrencyAmount amount = new PaymentCurrencyAmount(); amount.currency = "CNY"; amount.value = "123"; PaymentItem total = new PaymentItem(); total.amount = amount; Mockito.doReturn(total).when(mSpec).getRawTotal(); Map<String, PaymentMethodData> methodDataMap = new HashMap<>(); methodDataMap.put(mMethodData[0].supportedMethod, mMethodData[0]); Mockito.doReturn(methodDataMap).when(mSpec).getMethodData(); Mockito.doReturn(mOptions).when(mSpec).getPaymentOptions(); PaymentRequest request = new MojoPaymentRequestGateKeeper( (client, onClosed) -> new PaymentRequestService( mRenderFrameHost, client, onClosed, /*delegate=*/this, () -> null)); request.init(mClient, mMethodData, mDetails, mOptions); return request; } /** * Sets the method supported by this payment request (currently, only one method is supported). * @param supportedMethod The supported method. * @return The builder after the setting. */ public WebLayerPaymentRequestBuilder setSupportedMethod(String supportedMethod) { mSupportedMethod = supportedMethod; return this; } @Override public BrowserPaymentRequest createBrowserPaymentRequest( PaymentRequestService paymentRequestService) { return new WebLayerPaymentRequestService(paymentRequestService, mDelegate); } @Override public boolean isOffTheRecord() { return false; } @Override public String getInvalidSslCertificateErrorMessage() { return null; } @Override public boolean prefsCanMakePayment() { return false; } @Nullable @Override public String getTwaPackageName() { return null; } @Nullable @Override public WebContents getLiveWebContents(RenderFrameHost renderFrameHost) { return mWebContents; } @Override public boolean isOriginSecure(GURL url) { return true; } @Override public JourneyLogger createJourneyLogger(boolean isIncognito, WebContents webContents) { return mJourneyLogger; } @Override public String formatUrlForSecurityDisplay(GURL uri) { return uri.getSpec(); } @Override public byte[][] getCertificateChain(WebContents webContents) { return new byte[0][]; } @Override public boolean isOriginAllowedToUseWebPaymentApis(GURL url) { return true; } @Override public boolean validatePaymentDetails(PaymentDetails details) { return true; } @Override public PaymentRequestSpec createPaymentRequestSpec(PaymentOptions options, PaymentDetails details, Collection<PaymentMethodData> methodData, String appLocale) { return mSpec; } @Override public WindowAndroid getWindowAndroid(RenderFrameHost renderFrameHost) { WindowAndroid window = Mockito.mock(WindowAndroid.class); Context context = Mockito.mock(Context.class); WeakReference<Context> weakContext = Mockito.mock(WeakReference.class); Mockito.doReturn(context).when(weakContext).get(); Mockito.doReturn(weakContext).when(window).getContext(); return window; } @Override public PaymentAppFactoryInterface createAndroidPaymentAppFactory() { return null; } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/payments/test_support/WebLayerPaymentRequestBuilder.java
Java
unknown
7,246
// 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.permissions; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.components.permissions.AndroidPermissionRequester; import org.chromium.ui.base.WindowAndroid; /** Util functions to request Android permissions for a content setting. */ @JNINamespace("weblayer") public final class PermissionRequestUtils { @CalledByNative private static void requestPermission( WindowAndroid windowAndroid, long nativeCallback, int[] contentSettingsTypes) { if (!AndroidPermissionRequester.requestAndroidPermissions(windowAndroid, contentSettingsTypes, new AndroidPermissionRequester.RequestDelegate() { @Override public void onAndroidPermissionAccepted() { PermissionRequestUtilsJni.get().onResult(nativeCallback, true); } @Override public void onAndroidPermissionCanceled() { PermissionRequestUtilsJni.get().onResult(nativeCallback, false); } })) { PermissionRequestUtilsJni.get().onResult(nativeCallback, false); } } @NativeMethods interface Natives { void onResult(long callback, boolean result); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/permissions/PermissionRequestUtils.java
Java
unknown
1,609
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.weblayer_private.resources; import org.chromium.base.annotations.CalledByNative; /** * Wrapper class for ResourceId so it can be called over JNI. Since ResourceId is a generated class * `@CalledByNative` does not work on it directly. */ class ResourceMapper { @CalledByNative private static int[] getResourceIdList() { return ResourceId.getResourceIdList(); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/resources/ResourceMapper.java
Java
unknown
552
// 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.settings; import androidx.preference.PreferenceFragmentCompat; import org.chromium.components.browser_ui.accessibility.AccessibilitySettingsDelegate; import org.chromium.content_public.browser.BrowserContextHandle; import org.chromium.weblayer_private.ProfileImpl; /** The WebLayer implementation of AccessibilitySettingsDelegate. */ public class WebLayerAccessibilitySettingsDelegate implements AccessibilitySettingsDelegate { private ProfileImpl mProfile; public WebLayerAccessibilitySettingsDelegate(ProfileImpl profile) { mProfile = profile; } @Override public BrowserContextHandle getBrowserContextHandle() { return mProfile; } @Override public BooleanPreferenceDelegate getAccessibilityTabSwitcherDelegate() { return null; } @Override public BooleanPreferenceDelegate getReaderForAccessibilityDelegate() { return null; } @Override public void addExtraPreferences(PreferenceFragmentCompat fragment) {} @Override public boolean showPageZoomSettingsUI() { return false; } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/settings/WebLayerAccessibilitySettingsDelegate.java
Java
unknown
1,276
// 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.settings; import android.app.Activity; import android.graphics.drawable.Drawable; import androidx.annotation.LayoutRes; import androidx.annotation.Nullable; import androidx.preference.Preference; import org.chromium.base.Callback; import org.chromium.components.browser_ui.settings.ManagedPreferenceDelegate; import org.chromium.components.browser_ui.site_settings.SiteSettingsCategory.Type; import org.chromium.components.browser_ui.site_settings.SiteSettingsDelegate; import org.chromium.components.content_settings.ContentSettingsType; import org.chromium.components.embedder_support.util.Origin; import org.chromium.content_public.browser.BrowserContextHandle; import org.chromium.url.GURL; import org.chromium.weblayer_private.WebLayerImpl; import java.util.Collections; import java.util.Set; /** * A SiteSettingsDelegate instance that contains WebLayer-specific Site Settings logic. */ public class WebLayerSiteSettingsDelegate implements SiteSettingsDelegate, ManagedPreferenceDelegate { private final BrowserContextHandle mBrowserContextHandle; public WebLayerSiteSettingsDelegate(BrowserContextHandle browserContextHandle) { mBrowserContextHandle = browserContextHandle; } // SiteSettingsDelegate implementation: @Override public BrowserContextHandle getBrowserContextHandle() { return mBrowserContextHandle; } @Override public ManagedPreferenceDelegate getManagedPreferenceDelegate() { return this; } @Override public void getFaviconImageForURL(GURL faviconUrl, Callback<Drawable> callback) { // We don't currently support favicons on WebLayer. callback.onResult(null); } @Override public boolean isCategoryVisible(@Type int type) { return type == Type.ADS || type == Type.ALL_SITES || type == Type.AUTOMATIC_DOWNLOADS || type == Type.BACKGROUND_SYNC || type == Type.CAMERA || type == Type.COOKIES || type == Type.DEVICE_LOCATION || type == Type.JAVASCRIPT || type == Type.MICROPHONE || type == Type.POPUPS || type == Type.PROTECTED_MEDIA || type == Type.SOUND || type == Type.USE_STORAGE; } @Override public boolean isIncognitoModeEnabled() { return true; } @Override public boolean isQuietNotificationPromptsFeatureEnabled() { return false; } @Override public boolean isPrivacySandboxFirstPartySetsUIFeatureEnabled() { return false; } @Override public boolean isPrivacySandboxSettings4Enabled() { return false; } @Override public String getChannelIdForOrigin(String origin) { return null; } @Override public String getAppName() { return WebLayerImpl.getClientApplicationName(); } @Override @Nullable public String getDelegateAppNameForOrigin(Origin origin, @ContentSettingsType int type) { return null; } @Override @Nullable public String getDelegatePackageNameForOrigin(Origin origin, @ContentSettingsType int type) { return null; } // ManagedPrefrenceDelegate implementation: // A no-op because WebLayer doesn't support managed preferences. @Override public boolean isPreferenceControlledByPolicy(Preference preference) { return false; } @Override public boolean isPreferenceControlledByCustodian(Preference preference) { return false; } @Override public boolean doesProfileHaveMultipleCustodians() { return false; } @Override public @LayoutRes int defaultPreferenceLayoutResource() { // WebLayer uses Android's default Preference layout. return 0; } @Override public boolean isHelpAndFeedbackEnabled() { return false; } @Override public void launchSettingsHelpAndFeedbackActivity(Activity currentActivity) {} @Override public void launchProtectedContentHelpAndFeedbackActivity(Activity currentActivity) {} @Override public Set<String> getOriginsWithInstalledApp() { return Collections.EMPTY_SET; } @Override public Set<String> getAllDelegatedNotificationOrigins() { return Collections.EMPTY_SET; } @Override public void maybeDisplayPrivacySandboxSnackbar() {} @Override public void dismissPrivacySandboxSnackbar() {} @Override public boolean isFirstPartySetsDataAccessEnabled() { return false; } @Override public boolean isFirstPartySetsDataAccessManaged() { return false; } @Override public boolean isPartOfManagedFirstPartySet(String origin) { return false; } @Override public void setFirstPartySetsDataAccessEnabled(boolean enabled) {} @Override public String getFirstPartySetOwner(String memberOrigin) { return null; } @Override public boolean canLaunchClearBrowsingDataDialog() { return false; } @Override public void launchClearBrowsingDataDialog(Activity currentActivity) {} @Override public void notifyRequestDesktopSiteSettingsPageOpened() {} @Override public void onDestroyView() {} }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/settings/WebLayerSiteSettingsDelegate.java
Java
unknown
5,406
// 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.test; import android.content.Context; import android.graphics.Rect; import android.view.View; import android.view.autofill.AutofillValue; import org.chromium.base.Log; import org.chromium.components.autofill.AutofillManagerWrapper; import org.chromium.weblayer_private.test_interfaces.AutofillEventType; import java.util.ArrayList; /** * A test AutofillManagerWrapper for AutofillTest */ public class TestAutofillManagerWrapper extends AutofillManagerWrapper { public static final boolean DEBUG = false; public static final String TAG = "AutofillTest"; public TestAutofillManagerWrapper( Context context, Runnable onNewEvents, ArrayList<Integer> eventsObserved) { super(context); if (DEBUG) Log.i(TAG, "TestAutofillManagerWrapper"); mOnNewEvents = onNewEvents; mEventsObserved = eventsObserved; } @Override public boolean isDisabled() { return false; } @Override public boolean isAwGCurrentAutofillService() { return true; } @Override public void notifyVirtualViewEntered(View parent, int childId, Rect absBounds) { if (DEBUG) Log.i(TAG, "notifyVirtualViewEntered"); mEventsObserved.add(AutofillEventType.VIEW_ENTERED); mOnNewEvents.run(); } @Override public void notifyVirtualViewExited(View parent, int childId) { if (DEBUG) Log.i(TAG, "notifyVirtualViewExited"); mEventsObserved.add(AutofillEventType.VIEW_EXITED); mOnNewEvents.run(); } @Override public void notifyVirtualValueChanged(View parent, int childId, AutofillValue value) { if (DEBUG) Log.i(TAG, "notifyVirtualValueChanged"); mEventsObserved.add(AutofillEventType.VALUE_CHANGED); mOnNewEvents.run(); } @Override public void commit(int submissionSource) { if (DEBUG) Log.i(TAG, "commit"); mEventsObserved.add(AutofillEventType.COMMIT); mOnNewEvents.run(); } @Override public void cancel() { if (DEBUG) Log.i(TAG, "cancel"); mEventsObserved.add(AutofillEventType.CANCEL); mOnNewEvents.run(); } @Override public void notifyNewSessionStarted(boolean hasServerPrediction) { if (DEBUG) Log.i(TAG, "notifyNewSessionStarted"); mEventsObserved.add(AutofillEventType.SESSION_STARTED); mOnNewEvents.run(); } @Override public void onQueryDone(boolean success) { if (DEBUG) Log.i(TAG, "onQueryDone " + success); mEventsObserved.add(AutofillEventType.QUERY_DONE); mOnNewEvents.run(); } private ArrayList<Integer> mEventsObserved; private Runnable mOnNewEvents; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/test/TestAutofillManagerWrapper.java
Java
unknown
2,871
// 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.test; import org.chromium.components.content_capture.ContentCaptureConsumer; import org.chromium.components.content_capture.ContentCaptureFrame; import org.chromium.components.content_capture.FrameSession; import java.util.ArrayList; /** * A test ContentCaptureConsumer for ContentCaptureTest. */ public class TestContentCaptureConsumer implements ContentCaptureConsumer { public static final int CONTENT_CAPTURED = 1; public static final int CONTENT_UPDATED = 2; public static final int CONTENT_REMOVED = 3; public static final int SESSION_REMOVED = 4; public static final int TITLE_UPDATED = 5; public static final int FAVICON_UPDATED = 6; public TestContentCaptureConsumer(Runnable onNewEvents, ArrayList<Integer> eventsObserved) { mOnNewEvents = onNewEvents; mEventsObserved = eventsObserved; } @Override public void onContentCaptured( FrameSession parentFrame, ContentCaptureFrame contentCaptureData) { mEventsObserved.add(CONTENT_CAPTURED); mOnNewEvents.run(); } @Override public void onContentUpdated(FrameSession parentFrame, ContentCaptureFrame contentCaptureData) { mEventsObserved.add(CONTENT_UPDATED); mOnNewEvents.run(); } @Override public void onSessionRemoved(FrameSession session) { mEventsObserved.add(SESSION_REMOVED); mOnNewEvents.run(); } @Override public void onContentRemoved(FrameSession session, long[] removedIds) { mEventsObserved.add(CONTENT_REMOVED); mOnNewEvents.run(); } @Override public void onTitleUpdated(ContentCaptureFrame mainFrame) { mEventsObserved.add(TITLE_UPDATED); mOnNewEvents.run(); } @Override public void onFaviconUpdated(ContentCaptureFrame mainFrame) { mEventsObserved.add(FAVICON_UPDATED); mOnNewEvents.run(); } @Override public boolean shouldCapture(String[] urls) { return true; } private ArrayList<Integer> mEventsObserved; private Runnable mOnNewEvents; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/test/TestContentCaptureConsumer.java
Java
unknown
2,261
// 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.test; import androidx.annotation.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.components.infobars.InfoBar; import org.chromium.components.infobars.InfoBarCompactLayout; import org.chromium.content_public.browser.WebContents; import org.chromium.weblayer_private.TabImpl; /** * A test infobar. */ @JNINamespace("weblayer") public class TestInfoBar extends InfoBar { @VisibleForTesting public TestInfoBar() { super(0, 0, null, null); } @Override protected boolean usesCompactLayout() { return true; } @Override protected void createCompactLayoutContent(InfoBarCompactLayout layout) { new InfoBarCompactLayout.MessageBuilder(layout) .withText("I am a compact infobar") .buildAndInsert(); } @CalledByNative private static TestInfoBar create() { return new TestInfoBar(); } public static void show(TabImpl tab) { TestInfoBarJni.get().show(tab.getWebContents()); } @NativeMethods interface Natives { void show(WebContents webContents); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/test/TestInfoBar.java
Java
unknown
1,424
// 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.test; import android.os.IBinder; import android.os.RemoteException; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.build.annotations.UsedByReflection; import org.chromium.components.autofill.AutofillProviderTestHelper; import org.chromium.components.browser_ui.accessibility.FontSizePrefs; import org.chromium.components.infobars.InfoBarAnimationListener; import org.chromium.components.infobars.InfoBarUiItem; import org.chromium.components.location.LocationUtils; import org.chromium.components.media_router.BrowserMediaRouter; import org.chromium.components.media_router.MockMediaRouteProvider; import org.chromium.components.permissions.PermissionDialogController; import org.chromium.components.webauthn.AuthenticatorImpl; import org.chromium.components.webauthn.MockFido2CredentialRequest; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.content_public.browser.test.util.WebContentsUtils; import org.chromium.device.geolocation.LocationProviderOverrider; import org.chromium.device.geolocation.MockLocationProvider; import org.chromium.net.NetworkChangeNotifier; import org.chromium.ui.modaldialog.ModalDialogProperties; import org.chromium.weblayer_private.BrowserImpl; import org.chromium.weblayer_private.DownloadImpl; import org.chromium.weblayer_private.InfoBarContainer; import org.chromium.weblayer_private.ProfileImpl; import org.chromium.weblayer_private.TabImpl; import org.chromium.weblayer_private.WebLayerAccessibilityUtil; import org.chromium.weblayer_private.interfaces.IBrowser; import org.chromium.weblayer_private.interfaces.IObjectWrapper; import org.chromium.weblayer_private.interfaces.IProfile; import org.chromium.weblayer_private.interfaces.ITab; import org.chromium.weblayer_private.interfaces.ObjectWrapper; import org.chromium.weblayer_private.test_interfaces.ITestWebLayer; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; /** * Root implementation class for TestWebLayer. */ @JNINamespace("weblayer") @UsedByReflection("WebLayer") public final class TestWebLayerImpl extends ITestWebLayer.Stub { private MockLocationProvider mMockLocationProvider; @UsedByReflection("WebLayer") public static IBinder create() { return new TestWebLayerImpl(); } private TestWebLayerImpl() {} @Override public boolean isNetworkChangeAutoDetectOn() { return NetworkChangeNotifier.getAutoDetectorForTest() != null; } @Override public void setMockLocationProvider(boolean enable) { if (enable) { mMockLocationProvider = new MockLocationProvider(); LocationProviderOverrider.setLocationProviderImpl(mMockLocationProvider); } else if (mMockLocationProvider != null) { mMockLocationProvider.stop(); mMockLocationProvider.stopUpdates(); } } @Override public boolean isMockLocationProviderRunning() { return mMockLocationProvider.isRunning(); } @Override public boolean isPermissionDialogShown() { try { return TestThreadUtils.runOnUiThreadBlocking(() -> { return PermissionDialogController.getInstance().isDialogShownForTest(); }); } catch (ExecutionException e) { return false; } } @Override public void clickPermissionDialogButton(boolean allow) { TestThreadUtils.runOnUiThreadBlocking(() -> { PermissionDialogController.getInstance().clickButtonForTest(allow ? ModalDialogProperties.ButtonType.POSITIVE : ModalDialogProperties.ButtonType.NEGATIVE); }); } @Override public void setSystemLocationSettingEnabled(boolean enabled) { TestThreadUtils.runOnUiThreadBlocking(() -> { LocationUtils.setFactory(() -> { return new LocationUtils() { @Override public boolean isSystemLocationSettingEnabled() { return enabled; } }; }); }); } @Override public void waitForBrowserControlsMetadataState( ITab tab, int topHeight, int bottomHeight, IObjectWrapper runnable) { TestWebLayerImplJni.get().waitForBrowserControlsMetadataState( ((TabImpl) tab).getNativeTab(), topHeight, bottomHeight, ObjectWrapper.unwrap(runnable, Runnable.class)); } @Override public void setAccessibilityEnabled(boolean value) { WebLayerAccessibilityUtil.get().setAccessibilityEnabledForTesting(value); } @Override public void addInfoBar(ITab tab, IObjectWrapper runnable) { Runnable unwrappedRunnable = ObjectWrapper.unwrap(runnable, Runnable.class); TabImpl tabImpl = (TabImpl) tab; InfoBarContainer infoBarContainer = tabImpl.getInfoBarContainerForTesting(); infoBarContainer.addAnimationListener(new InfoBarAnimationListener() { @Override public void notifyAnimationFinished(int animationType) {} @Override public void notifyAllAnimationsFinished(InfoBarUiItem frontInfoBar) { unwrappedRunnable.run(); infoBarContainer.removeAnimationListener(this); } }); TestInfoBar.show((TabImpl) tab); } @Override public IObjectWrapper getInfoBarContainerView(ITab tab) { return ObjectWrapper.wrap( ((TabImpl) tab).getInfoBarContainerForTesting().getViewForTesting()); } @Override public void setIgnoreMissingKeyForTranslateManager(boolean ignore) { TestWebLayerImplJni.get().setIgnoreMissingKeyForTranslateManager(ignore); } @Override public void forceNetworkConnectivityState(boolean networkAvailable) { TestThreadUtils.runOnUiThreadBlocking( () -> { NetworkChangeNotifier.forceConnectivityState(true); }); } @Override public boolean canInfoBarContainerScroll(ITab tab) { return ((TabImpl) tab).canInfoBarContainerScrollForTesting(); } @Override public String getTranslateInfoBarTargetLanguage(ITab tab) { TabImpl tabImpl = (TabImpl) tab; return tabImpl.getTranslateInfoBarTargetLanguageForTesting(); } @Override public boolean didShowFullscreenToast(ITab tab) { TabImpl tabImpl = (TabImpl) tab; return tabImpl.didShowFullscreenToast(); } @Override public void initializeMockMediaRouteProvider(boolean closeRouteWithErrorOnSend, boolean disableIsSupportsSource, String createRouteErrorMessage, String joinRouteErrorMessage) { BrowserMediaRouter.setRouteProviderFactoryForTest(new MockMediaRouteProvider.Factory()); if (closeRouteWithErrorOnSend) { MockMediaRouteProvider.Factory.sProvider.setCloseRouteWithErrorOnSend(true); } if (disableIsSupportsSource) { MockMediaRouteProvider.Factory.sProvider.setIsSupportsSource(false); } if (createRouteErrorMessage != null) { MockMediaRouteProvider.Factory.sProvider.setCreateRouteErrorMessage( createRouteErrorMessage); } if (joinRouteErrorMessage != null) { MockMediaRouteProvider.Factory.sProvider.setJoinRouteErrorMessage( joinRouteErrorMessage); } } @Override public IObjectWrapper getMediaRouteButton(String name) { return null; } @Override public void crashTab(ITab tab) { try { TabImpl tabImpl = (TabImpl) tab; WebContentsUtils.crashTabAndWait(tabImpl.getWebContents()); } catch (TimeoutException e) { throw new RuntimeException(e); } } @Override public boolean isWindowOnSmallDevice(IBrowser browser) { try { return TestThreadUtils.runOnUiThreadBlocking( () -> { return ((BrowserImpl) browser).isWindowOnSmallDevice(); }); } catch (ExecutionException e) { return true; } } @Override public void fetchAccessToken(IProfile profile, IObjectWrapper /* Set<String> */ scopes, IObjectWrapper /* ValueCallback<String> */ onTokenFetched) throws RemoteException { ProfileImpl profileImpl = (ProfileImpl) profile; profileImpl.fetchAccessTokenForTesting(scopes, onTokenFetched); } @Override public void addContentCaptureConsumer(IBrowser browser, IObjectWrapper /* Runnable */ onNewEvents, IObjectWrapper /* ArrayList<Integer>*/ eventsObserved) { Runnable unwrappedOnNewEvents = ObjectWrapper.unwrap(onNewEvents, Runnable.class); ArrayList<Integer> unwrappedEventsObserved = ObjectWrapper.unwrap(eventsObserved, ArrayList.class); TestThreadUtils.runOnUiThreadBlocking(() -> { BrowserImpl browserImpl = (BrowserImpl) browser; browserImpl.getBrowserFragment() .getPossiblyNullViewController() .addContentCaptureConsumerForTesting(new TestContentCaptureConsumer( unwrappedOnNewEvents, unwrappedEventsObserved)); }); } @Override public void notifyOfAutofillEvents(IBrowser browser, IObjectWrapper /* Runnable */ onNewEvents, IObjectWrapper /* ArrayList<Integer>*/ eventsObserved) { Runnable unwrappedOnNewEvents = ObjectWrapper.unwrap(onNewEvents, Runnable.class); ArrayList<Integer> unwrappedEventsObserved = ObjectWrapper.unwrap(eventsObserved, ArrayList.class); TestThreadUtils.runOnUiThreadBlocking(() -> { AutofillProviderTestHelper.disableDownloadServerForTesting(); BrowserImpl browserImpl = (BrowserImpl) browser; TabImpl tab = browserImpl.getActiveTab(); tab.getAutofillProviderForTesting().replaceAutofillManagerWrapperForTesting( new TestAutofillManagerWrapper(browserImpl.getContext(), unwrappedOnNewEvents, unwrappedEventsObserved)); }); } @Override public void activateBackgroundFetchNotification(int id) { TestThreadUtils.runOnUiThreadBlocking( () -> DownloadImpl.activateNotificationForTesting(id)); } @Override public void expediteDownloadService() { TestWebLayerImplJni.get().expediteDownloadService(); } @Override public void setMockWebAuthnEnabled(boolean enabled) { if (enabled) { AuthenticatorImpl.overrideFido2CredentialRequestForTesting( new MockFido2CredentialRequest()); } else { AuthenticatorImpl.overrideFido2CredentialRequestForTesting(null); } } @Override public void fireOnAccessTokenIdentifiedAsInvalid(IProfile profile, IObjectWrapper /* Set<String> */ scopes, IObjectWrapper /* String */ token) throws RemoteException { ProfileImpl profileImpl = (ProfileImpl) profile; profileImpl.fireOnAccessTokenIdentifiedAsInvalidForTesting(scopes, token); } @Override public void grantLocationPermission(String url) { TestThreadUtils.runOnUiThreadBlocking( () -> { TestWebLayerImplJni.get().grantLocationPermission(url); }); } @Override public void setTextScaling(IProfile profile, float value) { ProfileImpl profileImpl = (ProfileImpl) profile; FontSizePrefs.getInstance(profileImpl).setUserFontScaleFactor(value); } @Override public boolean getForceEnableZoom(IProfile profile) { ProfileImpl profileImpl = (ProfileImpl) profile; return FontSizePrefs.getInstance(profileImpl).getForceEnableZoom(); } @NativeMethods interface Natives { void waitForBrowserControlsMetadataState( long tabImpl, int top, int bottom, Runnable runnable); void setIgnoreMissingKeyForTranslateManager(boolean ignore); void expediteDownloadService(); void grantLocationPermission(String url); } }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/test/TestWebLayerImpl.java
Java
unknown
12,511
// 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.test_interfaces; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({AutofillEventType.VIEW_ENTERED, AutofillEventType.VIEW_EXITED, AutofillEventType.VALUE_CHANGED, AutofillEventType.COMMIT, AutofillEventType.CANCEL, AutofillEventType.SESSION_STARTED, AutofillEventType.QUERY_DONE}) @Retention(RetentionPolicy.SOURCE) public @interface AutofillEventType { int VIEW_ENTERED = 1; int VIEW_EXITED = 2; int VALUE_CHANGED = 3; int COMMIT = 4; int CANCEL = 5; int SESSION_STARTED = 6; int QUERY_DONE = 7; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/test_interfaces/AutofillEventType.java
Java
unknown
806
// 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.test_interfaces; import android.os.Bundle; import org.chromium.weblayer_private.interfaces.IBrowser; import org.chromium.weblayer_private.interfaces.IProfile; import org.chromium.weblayer_private.interfaces.IObjectWrapper; import org.chromium.weblayer_private.interfaces.ITab; interface ITestWebLayer { // Force network connectivity state. boolean isNetworkChangeAutoDetectOn() = 1; // set mock location provider void setMockLocationProvider(in boolean enable) = 2; boolean isMockLocationProviderRunning() = 3; // Whether or not a permission dialog is currently showing. boolean isPermissionDialogShown() = 4; // Clicks a button on the permission dialog. void clickPermissionDialogButton(boolean allow) = 5; // Forces the system location setting to enabled. void setSystemLocationSettingEnabled(boolean enabled) = 6; // See comments in TestWebLayer for details. void waitForBrowserControlsMetadataState(in ITab tab, in int top, in int bottom, in IObjectWrapper runnable) = 7; void setAccessibilityEnabled(in boolean enabled) = 8; // Creates and shows a test infobar in |tab|, calling |runnable| when the addition (including // animations) is complete. void addInfoBar(in ITab tab, in IObjectWrapper runnable) = 10; // Gets the infobar container view associated with |tab|. IObjectWrapper /* View */ getInfoBarContainerView(in ITab tab) = 11; void setIgnoreMissingKeyForTranslateManager(in boolean ignore) = 12; void forceNetworkConnectivityState(in boolean networkAvailable) = 13; boolean canInfoBarContainerScroll(in ITab tab) = 14; // Returns the target language of the currently-showing translate infobar, or null if no translate // infobar is currently showing. String getTranslateInfoBarTargetLanguage(in ITab tab) = 16; // Returns true if a fullscreen toast was shown for |tab|. boolean didShowFullscreenToast(in ITab tab) = 17; // Does setup for MediaRouter tests, mocking out Chromecast devices. void initializeMockMediaRouteProvider( boolean closeRouteWithErrorOnSend, boolean disableIsSupportsSource, in String createRouteErrorMessage, in String joinRouteErrorMessage) = 18; // Gets a button from the currently visible media route selection dialog. The button represents a // route and contains the text |name|. Returns null if no such dialog or button exists. IObjectWrapper /* View */ getMediaRouteButton(String name) = 19; // Causes the renderer process in the tab's main frame to crash. void crashTab(in ITab tab) = 20; boolean isWindowOnSmallDevice(in IBrowser browser) = 21; void fetchAccessToken(in IProfile profile, in IObjectWrapper /* Set<String */ scopes, in IObjectWrapper /* ValueCallback<String> */ onTokenFetched) = 23; // Add a TestContentCaptureConsumer for the provided |browser|, with a Runnable |onNewEvent| to notify the // caller when the events happened, the event ID will be received through |eventsObserved| list. void addContentCaptureConsumer(in IBrowser browser, in IObjectWrapper /* Runnable */ onNewEvent, in IObjectWrapper /* ArrayList<Integer> */ eventsObserved) = 24; // Notifies the caller of autofill-related events that occur in |browser|. The caller is notified // via |onNewEvent| when a new event occurs, at which point the list of events that have occurred // since notifyOfAutofillEvents() was first invoked will be available via |eventsObserved|. // Note: Calling this method results in stubbing out the actual system-level integration with // Android Autofill. void notifyOfAutofillEvents(in IBrowser browser, in IObjectWrapper /* Runnable */ onNewEvent, in IObjectWrapper /* ArrayList<Integer> */ eventsObserved) = 25; // Simulates tapping the download notification with `id`. void activateBackgroundFetchNotification(int id) = 26; // Speeds up download service initialization. void expediteDownloadService() = 27; // Mocks the GMSCore Fido calls used by WebAuthn. void setMockWebAuthnEnabled(in boolean enabled) = 28; // Simulates the implementation-side event of an access token being // identified as invalid. void fireOnAccessTokenIdentifiedAsInvalid(in IProfile profile, in IObjectWrapper /* Set<String */ scopes, in IObjectWrapper /* String */ token) = 29; // Grants `url` location permission. void grantLocationPermission(String url) = 30; void setTextScaling(in IProfile profile, float value) = 31; boolean getForceEnableZoom(in IProfile profile) = 32; }
Zhao-PengFei35/chromium_src_4
weblayer/browser/java/org/chromium/weblayer_private/test_interfaces/ITestWebLayer.aidl
AIDL
unknown
4,906
// 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/browser/javascript_tab_modal_dialog_manager_delegate_android.h" #include "components/javascript_dialogs/android/tab_modal_dialog_view_android.h" #include "weblayer/browser/tab_impl.h" namespace weblayer { JavaScriptTabModalDialogManagerDelegateAndroid:: JavaScriptTabModalDialogManagerDelegateAndroid( content::WebContents* web_contents) : web_contents_(web_contents) {} JavaScriptTabModalDialogManagerDelegateAndroid:: ~JavaScriptTabModalDialogManagerDelegateAndroid() = default; base::WeakPtr<javascript_dialogs::TabModalDialogView> JavaScriptTabModalDialogManagerDelegateAndroid::CreateNewDialog( content::WebContents* alerting_web_contents, const std::u16string& title, content::JavaScriptDialogType dialog_type, const std::u16string& message_text, const std::u16string& default_prompt_text, content::JavaScriptDialogManager::DialogClosedCallback callback_on_button_clicked, base::OnceClosure callback_on_cancelled) { return javascript_dialogs::TabModalDialogViewAndroid::Create( web_contents_, alerting_web_contents, title, dialog_type, message_text, default_prompt_text, std::move(callback_on_button_clicked), std::move(callback_on_cancelled)); } void JavaScriptTabModalDialogManagerDelegateAndroid::WillRunDialog() {} void JavaScriptTabModalDialogManagerDelegateAndroid::DidCloseDialog() {} void JavaScriptTabModalDialogManagerDelegateAndroid::SetTabNeedsAttention( bool attention) {} bool JavaScriptTabModalDialogManagerDelegateAndroid::IsWebContentsForemost() { // TODO(estade): this should also check if the browser is active/showing. DCHECK(TabImpl::FromWebContents(web_contents_)); return TabImpl::FromWebContents(web_contents_)->IsActive(); } bool JavaScriptTabModalDialogManagerDelegateAndroid::IsApp() { return false; } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/javascript_tab_modal_dialog_manager_delegate_android.cc
C++
unknown
2,022
// 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_BROWSER_JAVASCRIPT_TAB_MODAL_DIALOG_MANAGER_DELEGATE_ANDROID_H_ #define WEBLAYER_BROWSER_JAVASCRIPT_TAB_MODAL_DIALOG_MANAGER_DELEGATE_ANDROID_H_ #include "base/memory/raw_ptr.h" #include "components/javascript_dialogs/tab_modal_dialog_manager_delegate.h" namespace content { class WebContents; } namespace weblayer { class JavaScriptTabModalDialogManagerDelegateAndroid : public javascript_dialogs::TabModalDialogManagerDelegate { public: explicit JavaScriptTabModalDialogManagerDelegateAndroid( content::WebContents* web_contents); JavaScriptTabModalDialogManagerDelegateAndroid( const JavaScriptTabModalDialogManagerDelegateAndroid& other) = delete; JavaScriptTabModalDialogManagerDelegateAndroid& operator=( const JavaScriptTabModalDialogManagerDelegateAndroid& other) = delete; ~JavaScriptTabModalDialogManagerDelegateAndroid() override; // javascript_dialogs::TabModalDialogManagerDelegate base::WeakPtr<javascript_dialogs::TabModalDialogView> CreateNewDialog( content::WebContents* alerting_web_contents, const std::u16string& title, content::JavaScriptDialogType dialog_type, const std::u16string& message_text, const std::u16string& default_prompt_text, content::JavaScriptDialogManager::DialogClosedCallback dialog_callback, base::OnceClosure dialog_closed_callback) override; void WillRunDialog() override; void DidCloseDialog() override; void SetTabNeedsAttention(bool attention) override; bool IsWebContentsForemost() override; bool IsApp() override; private: raw_ptr<content::WebContents> web_contents_; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_JAVASCRIPT_TAB_MODAL_DIALOG_MANAGER_DELEGATE_ANDROID_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/javascript_tab_modal_dialog_manager_delegate_android.h
C++
unknown
1,888
// 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. #include "base/test/scoped_feature_list.h" #include "components/page_load_metrics/browser/observers/ad_metrics/ad_intervention_browser_test_utils.h" #include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h" #include "components/subresource_filter/core/browser/subresource_filter_features.h" #include "components/subresource_filter/core/common/common_features.h" #include "components/subresource_filter/core/common/test_ruleset_utils.h" #include "components/subresource_filter/core/mojom/subresource_filter.mojom.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" #include "url/gurl.h" #include "weblayer/test/subresource_filter_browser_test_harness.h" namespace weblayer { namespace { const char kAdsInterventionRecordedHistogram[] = "SubresourceFilter.PageLoad.AdsInterventionTriggered"; } // namespace class LargeStickyAdViolationBrowserTest : public SubresourceFilterBrowserTest { public: LargeStickyAdViolationBrowserTest() = default; void SetUp() override { std::vector<base::test::FeatureRef> enabled = { subresource_filter::kAdTagging, subresource_filter::kAdsInterventionsEnforced}; std::vector<base::test::FeatureRef> disabled = { blink::features::kFrequencyCappingForLargeStickyAdDetection}; feature_list_.InitWithFeatures(enabled, disabled); SubresourceFilterBrowserTest::SetUp(); } void SetUpOnMainThread() override { SubresourceFilterBrowserTest::SetUpOnMainThread(); SetRulesetWithRules( {subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js")}); } protected: base::test::ScopedFeatureList feature_list_; }; IN_PROC_BROWSER_TEST_F(LargeStickyAdViolationBrowserTest, NoLargeStickyAd_AdInterventionNotTriggered) { base::HistogramTester histogram_tester; GURL url = embedded_test_server()->GetURL( "a.com", "/ads_observer/large_scrollable_page_with_adiframe_writer.html"); page_load_metrics::NavigateAndWaitForFirstContentfulPaint(web_contents(), url); // Reload the page. Since we haven't seen any ad violations, expect that the // ad script is loaded and that the subresource filter UI doesn't show up. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); EXPECT_TRUE( WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 0); histogram_tester.ExpectBucketCount( kAdsInterventionRecordedHistogram, subresource_filter::mojom::AdsViolation::kLargeStickyAd, 0); } IN_PROC_BROWSER_TEST_F(LargeStickyAdViolationBrowserTest, LargeStickyAd_AdInterventionTriggered) { base::HistogramTester histogram_tester; GURL url = embedded_test_server()->GetURL( "a.com", "/ads_observer/large_scrollable_page_with_adiframe_writer.html"); page_load_metrics::NavigateAndWaitForFirstContentfulPaint(web_contents(), url); page_load_metrics::TriggerAndDetectLargeStickyAd(web_contents()); // Reload the page. Since we are enforcing ad blocking on ads violations, // expect that the ad script is not loaded and that the subresource filter UI // shows up. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); EXPECT_FALSE( WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 1); histogram_tester.ExpectBucketCount( kAdsInterventionRecordedHistogram, subresource_filter::mojom::AdsViolation::kLargeStickyAd, 1); } class LargeStickyAdViolationBrowserTestWithoutEnforcement : public LargeStickyAdViolationBrowserTest { public: LargeStickyAdViolationBrowserTestWithoutEnforcement() = default; void SetUp() override { std::vector<base::test::FeatureRef> enabled = { subresource_filter::kAdTagging}; std::vector<base::test::FeatureRef> disabled = { subresource_filter::kAdsInterventionsEnforced, blink::features::kFrequencyCappingForLargeStickyAdDetection}; feature_list_.InitWithFeatures(enabled, disabled); SubresourceFilterBrowserTest::SetUp(); } private: base::test::ScopedFeatureList feature_list_; }; IN_PROC_BROWSER_TEST_F(LargeStickyAdViolationBrowserTestWithoutEnforcement, LargeStickyAd_NoAdInterventionTriggered) { base::HistogramTester histogram_tester; GURL url = embedded_test_server()->GetURL( "a.com", "/ads_observer/large_scrollable_page_with_adiframe_writer.html"); page_load_metrics::NavigateAndWaitForFirstContentfulPaint(web_contents(), url); page_load_metrics::TriggerAndDetectLargeStickyAd(web_contents()); // Reload the page. Since we are not enforcing ad blocking on ads violations, // expect that the ad script is loaded and that the subresource filter UI // doesn't show up. Expect a histogram recording as the intervention is // running in dry run mode. EXPECT_TRUE(content::NavigateToURL(web_contents(), url)); EXPECT_TRUE( WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame())); histogram_tester.ExpectBucketCount( "SubresourceFilter.Actions2", subresource_filter::SubresourceFilterAction::kUIShown, 0); histogram_tester.ExpectBucketCount( kAdsInterventionRecordedHistogram, subresource_filter::mojom::AdsViolation::kLargeStickyAd, 1); } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/large_sticky_ad_intervention_browsertest.cc
C++
unknown
5,910
// 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/browser/media/local_presentation_manager_factory.h" #include "base/no_destructor.h" namespace weblayer { // static LocalPresentationManagerFactory* LocalPresentationManagerFactory::GetInstance() { static base::NoDestructor<LocalPresentationManagerFactory> instance; return instance.get(); } LocalPresentationManagerFactory::LocalPresentationManagerFactory() = default; LocalPresentationManagerFactory::~LocalPresentationManagerFactory() = default; content::BrowserContext* LocalPresentationManagerFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return context; } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/media/local_presentation_manager_factory.cc
C++
unknown
794
// 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_BROWSER_MEDIA_LOCAL_PRESENTATION_MANAGER_FACTORY_H_ #define WEBLAYER_BROWSER_MEDIA_LOCAL_PRESENTATION_MANAGER_FACTORY_H_ #include "base/no_destructor.h" #include "components/media_router/browser/presentation/local_presentation_manager_factory.h" namespace content { class BrowserContext; } namespace weblayer { // A version of LocalPresentationManagerFactory that does not redirect from // incognito to normal context. class LocalPresentationManagerFactory : public media_router::LocalPresentationManagerFactory { public: LocalPresentationManagerFactory(const LocalPresentationManagerFactory&) = delete; LocalPresentationManagerFactory& operator=( const LocalPresentationManagerFactory&) = delete; static LocalPresentationManagerFactory* GetInstance(); private: friend base::NoDestructor<LocalPresentationManagerFactory>; LocalPresentationManagerFactory(); ~LocalPresentationManagerFactory() override; // BrowserContextKeyedServiceFactory interface. content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_MEDIA_LOCAL_PRESENTATION_MANAGER_FACTORY_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/media/local_presentation_manager_factory.h
C++
unknown
1,360
// 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/browser/media/media_router_factory.h" #include "base/android/jni_android.h" #include "base/no_destructor.h" #include "components/media_router/browser/android/media_router_android.h" #include "components/media_router/browser/android/media_router_dialog_controller_android.h" #include "components/media_router/browser/media_router_dialog_controller.h" #include "content/public/browser/browser_context.h" #include "weblayer/browser/java/jni/MediaRouterClientImpl_jni.h" namespace weblayer { // static MediaRouterFactory* MediaRouterFactory::GetInstance() { static base::NoDestructor<MediaRouterFactory> instance; return instance.get(); } // static bool MediaRouterFactory::IsFeatureEnabled() { static bool enabled = Java_MediaRouterClientImpl_isMediaRouterEnabled( base::android::AttachCurrentThread()); return enabled; } // static void MediaRouterFactory::DoPlatformInitIfNeeded() { static bool init_done = false; if (init_done) return; Java_MediaRouterClientImpl_initialize(base::android::AttachCurrentThread()); media_router::MediaRouterDialogController::SetGetOrCreate( base::BindRepeating([](content::WebContents* web_contents) { DCHECK(web_contents); // This call does nothing if the controller already exists. media_router::MediaRouterDialogControllerAndroid::CreateForWebContents( web_contents); return static_cast<media_router::MediaRouterDialogController*>( media_router::MediaRouterDialogControllerAndroid::FromWebContents( web_contents)); })); init_done = true; } MediaRouterFactory::MediaRouterFactory() = default; MediaRouterFactory::~MediaRouterFactory() = default; content::BrowserContext* MediaRouterFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return context; } KeyedService* MediaRouterFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { media_router::MediaRouterBase* media_router = new media_router::MediaRouterAndroid(); media_router->Initialize(); return media_router; } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/media/media_router_factory.cc
C++
unknown
2,278
// 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_BROWSER_MEDIA_MEDIA_ROUTER_FACTORY_H_ #define WEBLAYER_BROWSER_MEDIA_MEDIA_ROUTER_FACTORY_H_ #include "base/no_destructor.h" #include "components/media_router/browser/media_router_factory.h" namespace content { class BrowserContext; } namespace weblayer { class MediaRouterFactory : public media_router::MediaRouterFactory { public: MediaRouterFactory(const MediaRouterFactory&) = delete; MediaRouterFactory& operator=(const MediaRouterFactory&) = delete; static MediaRouterFactory* GetInstance(); // Determines if media router related features should be enabled. static bool IsFeatureEnabled(); // Performs platform and WebLayer-specific initialization for media_router. static void DoPlatformInitIfNeeded(); private: friend base::NoDestructor<MediaRouterFactory>; MediaRouterFactory(); ~MediaRouterFactory() override; // MediaRouterFactory: content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_MEDIA_MEDIA_ROUTER_FACTORY_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/media/media_router_factory.h
C++
unknown
1,330
// 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 "weblayer/test/weblayer_browser_test.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/functional/callback.h" #include "base/functional/callback_helpers.h" #include "base/memory/raw_ptr.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "components/variations/net/variations_http_headers.h" #include "components/variations/variations_ids_provider.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/url_loader_interceptor.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_response.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "weblayer/browser/tab_impl.h" #include "weblayer/public/browser.h" #include "weblayer/public/browser_observer.h" #include "weblayer/public/navigation.h" #include "weblayer/public/navigation_controller.h" #include "weblayer/public/navigation_observer.h" #include "weblayer/public/new_tab_delegate.h" #include "weblayer/shell/browser/shell.h" #include "weblayer/test/interstitial_utils.h" #include "weblayer/test/test_navigation_observer.h" #include "weblayer/test/weblayer_browser_test_utils.h" namespace weblayer { namespace { // NavigationObserver that allows registering a callback for various // NavigationObserver functions. class NavigationObserverImpl : public NavigationObserver { public: explicit NavigationObserverImpl(NavigationController* controller) : controller_(controller) { controller_->AddObserver(this); } ~NavigationObserverImpl() override { controller_->RemoveObserver(this); } using Callback = base::RepeatingCallback<void(Navigation*)>; using PageLanguageDeterminedCallback = base::RepeatingCallback<void(Page*, std::string)>; void SetStartedCallback(Callback callback) { started_callback_ = std::move(callback); } void SetRedirectedCallback(Callback callback) { redirected_callback_ = std::move(callback); } void SetFailedCallback(Callback callback) { failed_callback_ = std::move(callback); } void SetCompletedClosure(Callback callback) { completed_callback_ = std::move(callback); } void SetOnPageLanguageDeterminedCallback( PageLanguageDeterminedCallback callback) { on_page_language_determined_callback_ = std::move(callback); } // NavigationObserver: void NavigationStarted(Navigation* navigation) override { if (started_callback_) started_callback_.Run(navigation); } void NavigationRedirected(Navigation* navigation) override { if (redirected_callback_) redirected_callback_.Run(navigation); } void NavigationCompleted(Navigation* navigation) override { if (completed_callback_) completed_callback_.Run(navigation); } void NavigationFailed(Navigation* navigation) override { // As |this| may be deleted when running the callback, the callback must be // copied before running. To do otherwise results in use-after-free. auto callback = failed_callback_; if (callback) callback.Run(navigation); } void OnPageLanguageDetermined(Page* page, const std::string& language) override { if (on_page_language_determined_callback_) on_page_language_determined_callback_.Run(page, language); } private: raw_ptr<NavigationController> controller_; Callback started_callback_; Callback redirected_callback_; Callback completed_callback_; Callback failed_callback_; PageLanguageDeterminedCallback on_page_language_determined_callback_; }; } // namespace class NavigationBrowserTest : public WebLayerBrowserTest { public: NavigationController* GetNavigationController() { return shell()->tab()->GetNavigationController(); } void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); content::SetupCrossSiteRedirector(embedded_test_server()); } }; IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, NoError) { EXPECT_TRUE(embedded_test_server()->Start()); OneShotNavigationObserver observer(shell()); GetNavigationController()->Navigate( embedded_test_server()->GetURL("/simple_page.html")); observer.WaitForNavigation(); EXPECT_TRUE(observer.completed()); EXPECT_FALSE(observer.is_error_page()); EXPECT_FALSE(observer.is_download()); EXPECT_FALSE(observer.is_reload()); EXPECT_FALSE(observer.was_stop_called()); EXPECT_EQ(observer.load_error(), Navigation::kNoError); EXPECT_EQ(observer.http_status_code(), 200); EXPECT_EQ(observer.navigation_state(), NavigationState::kComplete); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, IsPageInitiatedTrueForWindowHistoryBack) { EXPECT_TRUE(embedded_test_server()->Start()); std::unique_ptr<OneShotNavigationObserver> observer = std::make_unique<OneShotNavigationObserver>(shell()); GetNavigationController()->Navigate( embedded_test_server()->GetURL("a.com", "/simple_page.html")); observer->WaitForNavigation(); ASSERT_TRUE(observer->completed()); EXPECT_FALSE(observer->is_page_initiated()); observer = std::make_unique<OneShotNavigationObserver>(shell()); GetNavigationController()->Navigate( embedded_test_server()->GetURL("b.com", "/simple_page.html")); observer->WaitForNavigation(); ASSERT_TRUE(observer->completed()); EXPECT_FALSE(observer->is_page_initiated()); observer = std::make_unique<OneShotNavigationObserver>(shell()); shell()->tab()->ExecuteScript( u"window.history.back();", false, base::BindLambdaForTesting( [&](base::Value value) { LOG(ERROR) << "executescript result"; })); observer->WaitForNavigation(); ASSERT_TRUE(observer->completed()); EXPECT_TRUE(observer->is_page_initiated()); } // Http client error when the server returns a non-empty response. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, HttpClientError) { EXPECT_TRUE(embedded_test_server()->Start()); OneShotNavigationObserver observer(shell()); GetNavigationController()->Navigate( embedded_test_server()->GetURL("/non_empty404.html")); observer.WaitForNavigation(); EXPECT_TRUE(observer.completed()); EXPECT_FALSE(observer.is_error_page()); EXPECT_EQ(observer.load_error(), Navigation::kHttpClientError); EXPECT_EQ(observer.http_status_code(), 404); EXPECT_EQ(observer.navigation_state(), NavigationState::kComplete); } // Http client error when the server returns an empty response. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, HttpClientErrorEmptyResponse) { EXPECT_TRUE(embedded_test_server()->Start()); OneShotNavigationObserver observer(shell()); GetNavigationController()->Navigate( embedded_test_server()->GetURL("/empty404.html")); observer.WaitForNavigation(); EXPECT_FALSE(observer.completed()); EXPECT_TRUE(observer.is_error_page()); EXPECT_EQ(observer.load_error(), Navigation::kHttpClientError); EXPECT_EQ(observer.http_status_code(), 404); EXPECT_EQ(observer.navigation_state(), NavigationState::kFailed); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, HttpServerError) { EXPECT_TRUE(embedded_test_server()->Start()); OneShotNavigationObserver observer(shell()); GetNavigationController()->Navigate( embedded_test_server()->GetURL("/echo?status=500")); observer.WaitForNavigation(); EXPECT_TRUE(observer.completed()); EXPECT_FALSE(observer.is_error_page()); EXPECT_EQ(observer.load_error(), Navigation::kHttpServerError); EXPECT_EQ(observer.http_status_code(), 500); EXPECT_EQ(observer.navigation_state(), NavigationState::kComplete); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, SSLError) { net::EmbeddedTestServer https_server_mismatched( net::EmbeddedTestServer::TYPE_HTTPS); https_server_mismatched.SetSSLConfig( net::EmbeddedTestServer::CERT_MISMATCHED_NAME); https_server_mismatched.AddDefaultHandlers( base::FilePath(FILE_PATH_LITERAL("weblayer/test/data"))); ASSERT_TRUE(https_server_mismatched.Start()); OneShotNavigationObserver observer(shell()); GetNavigationController()->Navigate( https_server_mismatched.GetURL("/simple_page.html")); observer.WaitForNavigation(); EXPECT_FALSE(observer.completed()); EXPECT_TRUE(observer.is_error_page()); EXPECT_EQ(observer.load_error(), Navigation::kSSLError); EXPECT_EQ(observer.navigation_state(), NavigationState::kFailed); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, HttpConnectivityError) { GURL url("http://doesntexist.com/foo"); auto interceptor = content::URLLoaderInterceptor::SetupRequestFailForURL( url, net::ERR_NAME_NOT_RESOLVED); OneShotNavigationObserver observer(shell()); GetNavigationController()->Navigate(url); observer.WaitForNavigation(); EXPECT_FALSE(observer.completed()); EXPECT_TRUE(observer.is_error_page()); EXPECT_EQ(observer.load_error(), Navigation::kConnectivityError); EXPECT_EQ(observer.navigation_state(), NavigationState::kFailed); } #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // https://crbug.com/1296643 #define MAYBE_Download DISABLED_Download #else #define MAYBE_Download Download #endif IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, MAYBE_Download) { EXPECT_TRUE(embedded_test_server()->Start()); GURL url(embedded_test_server()->GetURL("/content-disposition.html")); OneShotNavigationObserver observer(shell()); GetNavigationController()->Navigate(url); observer.WaitForNavigation(); EXPECT_FALSE(observer.completed()); EXPECT_FALSE(observer.is_error_page()); EXPECT_TRUE(observer.is_download()); EXPECT_FALSE(observer.was_stop_called()); EXPECT_EQ(observer.load_error(), Navigation::kOtherError); EXPECT_EQ(observer.navigation_state(), NavigationState::kFailed); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, StopInOnStart) { ASSERT_TRUE(embedded_test_server()->Start()); base::RunLoop run_loop; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback(base::BindLambdaForTesting( [&](Navigation*) { GetNavigationController()->Stop(); })); observer.SetFailedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { ASSERT_TRUE(navigation->WasStopCalled()); run_loop.Quit(); })); GetNavigationController()->Navigate( embedded_test_server()->GetURL("/simple_page.html")); run_loop.Run(); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, DestroyTabInNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); Tab* new_tab = shell()->browser()->CreateTab(); base::RunLoop run_loop; std::unique_ptr<NavigationObserverImpl> observer = std::make_unique<NavigationObserverImpl>( new_tab->GetNavigationController()); observer->SetFailedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { observer.reset(); shell()->browser()->DestroyTab(new_tab); // Destroying the tab posts a task to delete the WebContents, which must // be run before the test shuts down lest it access deleted state. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, run_loop.QuitClosure()); })); new_tab->GetNavigationController()->Navigate( embedded_test_server()->GetURL("/simple_pageX.html")); run_loop.Run(); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, StopInOnRedirect) { ASSERT_TRUE(embedded_test_server()->Start()); base::RunLoop run_loop; NavigationObserverImpl observer(GetNavigationController()); observer.SetRedirectedCallback(base::BindLambdaForTesting( [&](Navigation*) { GetNavigationController()->Stop(); })); observer.SetFailedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { ASSERT_TRUE(navigation->WasStopCalled()); run_loop.Quit(); })); const GURL original_url = embedded_test_server()->GetURL("/simple_page.html"); GetNavigationController()->Navigate(embedded_test_server()->GetURL( "/server-redirect?" + original_url.spec())); run_loop.Run(); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, NavigateFromRendererInitiatedNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); NavigationController* controller = shell()->tab()->GetNavigationController(); const GURL final_url = embedded_test_server()->GetURL("/simple_page2.html"); int failed_count = 0; int completed_count = 0; NavigationObserverImpl observer(controller); base::RunLoop run_loop; observer.SetFailedCallback( base::BindLambdaForTesting([&](Navigation*) { failed_count++; })); observer.SetCompletedClosure( base::BindLambdaForTesting([&](Navigation* navigation) { completed_count++; if (navigation->GetURL().path() == "/simple_page2.html") run_loop.Quit(); })); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { if (navigation->GetURL().path() == "/simple_page.html") controller->Navigate(final_url); })); controller->Navigate(embedded_test_server()->GetURL("/simple_page4.html")); run_loop.Run(); EXPECT_EQ(1, failed_count); EXPECT_EQ(2, completed_count); ASSERT_EQ(2, controller->GetNavigationListSize()); EXPECT_EQ(final_url, controller->GetNavigationEntryDisplayURL(1)); } class BrowserObserverImpl : public BrowserObserver { public: explicit BrowserObserverImpl(Browser* browser) : browser_(browser) { browser->AddObserver(this); } ~BrowserObserverImpl() override { browser_->RemoveObserver(this); } void SetNewTabCallback(base::RepeatingCallback<void(Tab*)> callback) { new_tab_callback_ = callback; } // BrowserObserver: void OnTabAdded(Tab* tab) override { new_tab_callback_.Run(tab); } private: base::RepeatingCallback<void(Tab*)> new_tab_callback_; raw_ptr<Browser> browser_; }; class NewTabDelegateImpl : public NewTabDelegate { public: // NewTabDelegate: void OnNewTab(Tab* new_tab, NewTabType type) override {} }; // Ensures calling Navigate() from within NavigationStarted() for a popup does // not crash. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, NavigateFromNewWindow) { ASSERT_TRUE(embedded_test_server()->Start()); NavigateAndWaitForCompletion( embedded_test_server()->GetURL("/simple_page2.html"), shell()); NewTabDelegate* old_new_tab_delegate = static_cast<TabImpl*>(shell()->tab())->new_tab_delegate(); NewTabDelegateImpl new_tab_delegate; shell()->tab()->SetNewTabDelegate(&new_tab_delegate); BrowserObserverImpl browser_observer(shell()->tab()->GetBrowser()); std::unique_ptr<NavigationObserverImpl> popup_navigation_observer; base::RunLoop run_loop; Tab* popup_tab = nullptr; auto popup_started_navigation = [&](Navigation* navigation) { if (navigation->GetURL().path() == "/simple_page.html") { popup_tab->GetNavigationController()->Navigate( embedded_test_server()->GetURL("/simple_page3.html")); } else if (navigation->GetURL().path() == "/simple_page3.html") { run_loop.Quit(); } }; browser_observer.SetNewTabCallback(base::BindLambdaForTesting([&](Tab* tab) { popup_tab = tab; popup_navigation_observer = std::make_unique<NavigationObserverImpl>( tab->GetNavigationController()); popup_navigation_observer->SetStartedCallback( base::BindLambdaForTesting(popup_started_navigation)); })); // 'noopener' is key to triggering the problematic case. const std::string window_open = base::StringPrintf( "window.open('%s', '', 'noopener')", embedded_test_server()->GetURL("/simple_page.html").spec().c_str()); ExecuteScriptWithUserGesture(shell()->tab(), window_open); run_loop.Run(); // Restore the old delegate to make sure it is cleaned up on Android. shell()->tab()->SetNewTabDelegate(old_new_tab_delegate); } // Verifies calling Navigate() from NavigationRedirected() works. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, NavigateFromRedirect) { net::test_server::ControllableHttpResponse response_1(embedded_test_server(), "", true); net::test_server::ControllableHttpResponse response_2(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); NavigationObserverImpl observer(GetNavigationController()); bool got_redirect = false; const GURL url_to_load_on_redirect = embedded_test_server()->GetURL("/url_to_load_on_redirect.html"); observer.SetRedirectedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { shell()->LoadURL(url_to_load_on_redirect); got_redirect = true; })); shell()->LoadURL(embedded_test_server()->GetURL("/initial_url.html")); response_1.WaitForRequest(); response_1.Send( "HTTP/1.1 302 Moved Temporarily\r\nLocation: /redirect_dest_url\r\n\r\n"); response_1.Done(); response_2.WaitForRequest(); response_2.Done(); EXPECT_EQ(url_to_load_on_redirect, response_2.http_request()->GetURL()); EXPECT_TRUE(got_redirect); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, SetRequestHeader) { net::test_server::ControllableHttpResponse response_1(embedded_test_server(), "", true); net::test_server::ControllableHttpResponse response_2(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); const std::string header_name = "header"; const std::string header_value = "value"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetRequestHeader(header_name, header_value); })); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); response_1.WaitForRequest(); // Header should be present in initial request. EXPECT_EQ(header_value, response_1.http_request()->headers.at(header_name)); response_1.Send( "HTTP/1.1 302 Moved Temporarily\r\nLocation: /new_doc\r\n\r\n"); response_1.Done(); // Header should carry through to redirect. response_2.WaitForRequest(); EXPECT_EQ(header_value, response_2.http_request()->headers.at(header_name)); } // Verifies setting the 'referer' via SetRequestHeader() works as expected. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, SetRequestHeaderWithReferer) { net::test_server::ControllableHttpResponse response(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); const std::string header_name = "Referer"; const std::string header_value = "http://request.com"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetRequestHeader(header_name, header_value); })); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); response.WaitForRequest(); // Verify 'referer' matches expected value. EXPECT_EQ(GURL(header_value), GURL(response.http_request()->headers.at(header_name))); } // Like above but checks that referer isn't sent when it's https and the target // url is http. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, SetRequestHeaderWithRefererDowngrade) { net::test_server::ControllableHttpResponse response(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); const std::string header_name = "Referer"; const std::string header_value = "https://request.com"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetRequestHeader(header_name, header_value); })); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); response.WaitForRequest(); EXPECT_EQ(0u, response.http_request()->headers.count(header_name)); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, SetRequestHeaderInRedirect) { net::test_server::ControllableHttpResponse response_1(embedded_test_server(), "", true); net::test_server::ControllableHttpResponse response_2(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); const std::string header_name = "header"; const std::string header_value = "value"; NavigationObserverImpl observer(GetNavigationController()); observer.SetRedirectedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetRequestHeader(header_name, header_value); })); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); response_1.WaitForRequest(); // Header should not be present in initial request. EXPECT_FALSE(base::Contains(response_1.http_request()->headers, header_name)); response_1.Send( "HTTP/1.1 302 Moved Temporarily\r\nLocation: /new_doc\r\n\r\n"); response_1.Done(); response_2.WaitForRequest(); // Header should be in redirect. ASSERT_TRUE(base::Contains(response_2.http_request()->headers, header_name)); EXPECT_EQ(header_value, response_2.http_request()->headers.at(header_name)); } class NavigationBrowserTestUserAgentOverrideSubstring : public NavigationBrowserTest { public: void SetUp() override { scoped_feature_list_.InitWithFeatures({blink::features::kUACHOverrideBlank}, {}); NavigationBrowserTest::SetUp(); } private: base::test::ScopedFeatureList scoped_feature_list_; }; IN_PROC_BROWSER_TEST_F(NavigationBrowserTestUserAgentOverrideSubstring, PageSeesUserAgentString) { net::test_server::EmbeddedTestServer https_server( net::test_server::EmbeddedTestServer::TYPE_HTTPS); https_server.AddDefaultHandlers( base::FilePath(FILE_PATH_LITERAL("weblayer/test/data"))); ASSERT_TRUE(https_server.Start()); const std::string custom_ua = "custom"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetUserAgentString(custom_ua); })); OneShotNavigationObserver navigation_observer(shell()); shell()->LoadURL(https_server.GetURL("/simple_page.html")); navigation_observer.WaitForNavigation(); base::RunLoop run_loop; shell()->tab()->ExecuteScript( u"navigator.userAgent;", false, base::BindLambdaForTesting([&](base::Value value) { ASSERT_TRUE(value.is_string()); EXPECT_EQ(custom_ua, value.GetString()); run_loop.Quit(); })); run_loop.Run(); // Ensure that userAgentData is blank when custom user agent is set. base::RunLoop run_loop2; shell()->tab()->ExecuteScript( u"navigator.userAgentData.platform;", false, base::BindLambdaForTesting([&](base::Value value) { ASSERT_TRUE(value.is_string()); EXPECT_EQ("", value.GetString()); run_loop2.Quit(); })); run_loop2.Run(); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, Reload) { ASSERT_TRUE(embedded_test_server()->Start()); OneShotNavigationObserver observer(shell()); GetNavigationController()->Navigate( embedded_test_server()->GetURL("/simple_page.html")); observer.WaitForNavigation(); OneShotNavigationObserver observer2(shell()); shell()->tab()->ExecuteScript(u"location.reload();", false, base::DoNothing()); observer2.WaitForNavigation(); EXPECT_TRUE(observer2.completed()); EXPECT_TRUE(observer2.is_reload()); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTestUserAgentOverrideSubstring, SetUserAgentString) { std::unique_ptr<net::test_server::EmbeddedTestServer> https_server = std::make_unique<net::test_server::EmbeddedTestServer>( net::test_server::EmbeddedTestServer::TYPE_HTTPS); https_server->AddDefaultHandlers( base::FilePath(FILE_PATH_LITERAL("weblayer/test/data"))); net::test_server::ControllableHttpResponse response_1(https_server.get(), "", true); net::test_server::ControllableHttpResponse response_2(https_server.get(), "", true); ASSERT_TRUE(https_server->Start()); const std::string custom_ua = "CUSTOM"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetUserAgentString(custom_ua); })); shell()->LoadURL(https_server->GetURL("/simple_page.html")); response_1.WaitForRequest(); // |custom_ua| should be present in initial request. ASSERT_TRUE(base::Contains(response_1.http_request()->headers, net::HttpRequestHeaders::kUserAgent)); const std::string new_header = response_1.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent); EXPECT_EQ(custom_ua, new_header); ASSERT_TRUE(base::Contains(response_1.http_request()->headers, "sec-ch-ua")); const std::string new_ch_header = response_1.http_request()->headers.at("Sec-CH-UA"); EXPECT_EQ("", new_ch_header); content::FetchHistogramsFromChildProcesses(); // Header should carry through to redirect. response_1.Send( "HTTP/1.1 302 Moved Temporarily\r\nLocation: /new_doc\r\n\r\n"); response_1.Done(); response_2.WaitForRequest(); EXPECT_EQ(custom_ua, response_2.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent)); EXPECT_EQ("", response_2.http_request()->headers.at("Sec-CH-UA")); } #if BUILDFLAG(IS_ANDROID) IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, SetUserAgentStringDoesntChangeViewportMetaTag) { ASSERT_TRUE(embedded_test_server()->Start()); NavigationObserverImpl observer(GetNavigationController()); const std::string custom_ua = "custom-ua"; observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetUserAgentString(custom_ua); })); OneShotNavigationObserver load_observer(shell()); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); load_observer.WaitForNavigation(); // Just because we set a custom user agent doesn't mean we should ignore // viewport meta tags. auto* tab = static_cast<TabImpl*>(shell()->tab()); auto* web_contents = tab->web_contents(); ASSERT_TRUE(web_contents->GetOrCreateWebPreferences().viewport_meta_enabled); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, RequestDesktopSiteChangesViewportMetaTag) { ASSERT_TRUE(embedded_test_server()->Start()); OneShotNavigationObserver load_observer(shell()); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); load_observer.WaitForNavigation(); auto* tab = static_cast<TabImpl*>(shell()->tab()); OneShotNavigationObserver load_observer2(shell()); tab->SetDesktopUserAgentEnabled(nullptr, true); load_observer2.WaitForNavigation(); auto* web_contents = tab->web_contents(); ASSERT_FALSE(web_contents->GetOrCreateWebPreferences().viewport_meta_enabled); } #endif // Verifies changing the user agent twice in a row works. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, UserAgentDoesntCarryThrough1) { net::test_server::ControllableHttpResponse response_1(embedded_test_server(), "", true); net::test_server::ControllableHttpResponse response_2(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); const std::string custom_ua1 = "my ua1"; const std::string custom_ua2 = "my ua2"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetUserAgentString(custom_ua1); })); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); response_1.WaitForRequest(); EXPECT_EQ(custom_ua1, response_1.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent)); // Before the request is done, start another navigation. observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetUserAgentString(custom_ua2); })); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page2.html")); response_2.WaitForRequest(); EXPECT_EQ(custom_ua2, response_2.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent)); } // Verifies changing the user agent doesn't bleed through to next navigation. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, UserAgentDoesntCarryThrough2) { net::test_server::ControllableHttpResponse response_1(embedded_test_server(), "", true); net::test_server::ControllableHttpResponse response_2(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); const std::string custom_ua = "my ua1"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetUserAgentString(custom_ua); })); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); response_1.WaitForRequest(); EXPECT_EQ(custom_ua, response_1.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent)); // Before the request is done, start another navigation. observer.SetStartedCallback(base::DoNothing()); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page2.html")); response_2.WaitForRequest(); EXPECT_NE(custom_ua, response_2.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent)); EXPECT_FALSE(response_2.http_request() ->headers.at(net::HttpRequestHeaders::kUserAgent) .empty()); } // Verifies changing the user-agent applies to child resources, such as an // <img>. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, UserAgentAppliesToChildResources) { net::test_server::ControllableHttpResponse response_1(embedded_test_server(), "", true); net::test_server::ControllableHttpResponse response_2(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); const std::string custom_ua = "custom-ua"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetUserAgentString(custom_ua); })); shell()->LoadURL(embedded_test_server()->GetURL("/foo.html")); response_1.WaitForRequest(); response_1.Send(net::HTTP_OK, "text/html", "<img src=\"image.png\">"); response_1.Done(); EXPECT_EQ(custom_ua, response_1.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent)); observer.SetStartedCallback(base::DoNothing()); response_2.WaitForRequest(); EXPECT_EQ(custom_ua, response_2.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent)); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, SetUserAgentStringRendererInitiated) { net::test_server::ControllableHttpResponse response_1(embedded_test_server(), "", true); net::test_server::ControllableHttpResponse response_2(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); OneShotNavigationObserver load_observer(shell()); NavigationObserverImpl observer(GetNavigationController()); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); response_1.WaitForRequest(); response_1.Send(net::HTTP_OK, "text/html", "<html>"); response_1.Done(); load_observer.WaitForNavigation(); const std::string custom_ua = "custom-ua"; observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetUserAgentString(custom_ua); })); const GURL target_url = embedded_test_server()->GetURL("/foo.html"); shell()->tab()->ExecuteScript( u"location.href='" + base::ASCIIToUTF16(target_url.spec()) + u"';", false, base::DoNothing()); response_2.WaitForRequest(); // |custom_ua| should be present in the renderer initiated navigation. ASSERT_TRUE(base::Contains(response_2.http_request()->headers, net::HttpRequestHeaders::kUserAgent)); const std::string new_ua = response_2.http_request()->headers.at( net::HttpRequestHeaders::kUserAgent); EXPECT_EQ(custom_ua, new_ua); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, AutoPlayDefault) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url(embedded_test_server()->GetURL("/autoplay.html")); auto* tab = static_cast<TabImpl*>(shell()->tab()); NavigateAndWaitForCompletion(url, tab); auto* web_contents = tab->web_contents(); bool playing = false; // There's no notification to watch that would signal video wasn't autoplayed, // so instead check once through javascript. EXPECT_TRUE(content::ExecuteScriptAndExtractBool( web_contents, "window.domAutomationController.send(!document.getElementById('vid')." "paused)", &playing)); ASSERT_FALSE(playing); } namespace { class WaitForMediaPlaying : public content::WebContentsObserver { public: explicit WaitForMediaPlaying(content::WebContents* web_contents) : WebContentsObserver(web_contents) {} WaitForMediaPlaying(const WaitForMediaPlaying&) = delete; WaitForMediaPlaying& operator=(const WaitForMediaPlaying&) = delete; // WebContentsObserver override. void MediaStartedPlaying(const MediaPlayerInfo& info, const content::MediaPlayerId&) final { run_loop_.Quit(); CHECK(info.has_audio); CHECK(info.has_video); } void Wait() { run_loop_.Run(); } private: base::RunLoop run_loop_; }; } // namespace IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, AutoPlayEnabled) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url(embedded_test_server()->GetURL("/autoplay.html")); NavigationController::NavigateParams params; params.enable_auto_play = true; GetNavigationController()->Navigate(url, params); auto* tab = static_cast<TabImpl*>(shell()->tab()); WaitForMediaPlaying wait_for_media(tab->web_contents()); wait_for_media.Wait(); } class NavigationBrowserTest2 : public NavigationBrowserTest { public: void SetUp() override { // HTTPS server only serves a valid cert for localhost, so this is needed to // load pages from "www.google.com" without an interstitial. base::CommandLine::ForCurrentProcess()->AppendSwitch( "ignore-certificate-errors"); NavigationBrowserTest::SetUp(); } void SetUpOnMainThread() override { NavigationBrowserTest::SetUpOnMainThread(); https_server_ = std::make_unique<net::EmbeddedTestServer>( net::EmbeddedTestServer::TYPE_HTTPS); // The test makes requests to google.com which we want to redirect to the // test server. host_resolver()->AddRule("*", "127.0.0.1"); // Forces variations code to set the header. auto* variations_provider = variations::VariationsIdsProvider::GetInstance(); variations_provider->ForceVariationIds({"12", "456", "t789"}, ""); } net::EmbeddedTestServer* https_server() { return https_server_.get(); } private: std::unique_ptr<net::EmbeddedTestServer> https_server_; }; // This test verifies the embedder can replace the X-Client-Data header that // is also set by //components/variations. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest2, ReplaceXClientDataHeader) { std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>(); std::string last_header_value; auto main_task_runner = base::SequencedTaskRunner::GetCurrentDefault(); https_server()->RegisterRequestHandler(base::BindLambdaForTesting( [&, main_task_runner](const net::test_server::HttpRequest& request) -> std::unique_ptr<net::test_server::HttpResponse> { auto iter = request.headers.find(variations::kClientDataHeader); if (iter != request.headers.end()) { main_task_runner->PostTask( FROM_HERE, base::BindOnce(base::BindLambdaForTesting( [&](const std::string& value) { last_header_value = value; run_loop->Quit(); }), iter->second)); } return std::make_unique<net::test_server::BasicHttpResponse>(); })); ASSERT_TRUE(https_server()->Start()); // Verify the header is set by default. const GURL url = https_server()->GetURL("www.google.com", "/"); shell()->LoadURL(url); run_loop->Run(); EXPECT_FALSE(last_header_value.empty()); // Repeat, but clobber the header when navigating. const std::string header_value = "value"; EXPECT_NE(last_header_value, header_value); last_header_value.clear(); run_loop = std::make_unique<base::RunLoop>(); NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetRequestHeader(variations::kClientDataHeader, header_value); })); shell()->LoadURL(https_server()->GetURL("www.google.com", "/foo")); run_loop->Run(); EXPECT_EQ(header_value, last_header_value); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest2, SetXClientDataHeaderCarriesThroughToRedirect) { std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>(); std::string last_header_value; bool should_redirect = true; auto main_task_runner = base::SequencedTaskRunner::GetCurrentDefault(); https_server()->RegisterRequestHandler(base::BindLambdaForTesting( [&, main_task_runner](const net::test_server::HttpRequest& request) -> std::unique_ptr<net::test_server::HttpResponse> { auto response = std::make_unique<net::test_server::BasicHttpResponse>(); if (should_redirect) { should_redirect = false; response->set_code(net::HTTP_MOVED_PERMANENTLY); response->AddCustomHeader( "Location", https_server()->GetURL("www.google.com", "/redirect").spec()); } else { auto iter = request.headers.find(variations::kClientDataHeader); main_task_runner->PostTask( FROM_HERE, base::BindOnce(base::BindLambdaForTesting( [&](const std::string& value) { last_header_value = value; run_loop->Quit(); }), iter->second)); } return response; })); ASSERT_TRUE(https_server()->Start()); const std::string header_value = "value"; run_loop = std::make_unique<base::RunLoop>(); NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetRequestHeader(variations::kClientDataHeader, header_value); })); shell()->LoadURL(https_server()->GetURL("www.google.com", "/foo")); run_loop->Run(); EXPECT_EQ(header_value, last_header_value); } IN_PROC_BROWSER_TEST_F(NavigationBrowserTest2, SetXClientDataHeaderInRedirect) { std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>(); std::string last_header_value; bool should_redirect = true; auto main_task_runner = base::SequencedTaskRunner::GetCurrentDefault(); https_server()->RegisterRequestHandler(base::BindLambdaForTesting( [&, main_task_runner](const net::test_server::HttpRequest& request) -> std::unique_ptr<net::test_server::HttpResponse> { auto response = std::make_unique<net::test_server::BasicHttpResponse>(); if (should_redirect) { should_redirect = false; response->set_code(net::HTTP_MOVED_PERMANENTLY); response->AddCustomHeader( "Location", https_server()->GetURL("www.google.com", "/redirect").spec()); } else { auto iter = request.headers.find(variations::kClientDataHeader); main_task_runner->PostTask( FROM_HERE, base::BindOnce(base::BindLambdaForTesting( [&](const std::string& value) { last_header_value = value; run_loop->Quit(); }), iter->second)); } return response; })); ASSERT_TRUE(https_server()->Start()); const std::string header_value = "value"; NavigationObserverImpl observer(GetNavigationController()); observer.SetRedirectedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetRequestHeader(variations::kClientDataHeader, header_value); })); shell()->LoadURL(https_server()->GetURL("www.google.com", "/foo")); run_loop->Run(); EXPECT_EQ(header_value, last_header_value); } #if BUILDFLAG(IS_ANDROID) // Verifies setting the 'referer' to an android-app url works. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, AndroidAppReferer) { net::test_server::ControllableHttpResponse response(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); const std::string header_name = "Referer"; const std::string header_value = "android-app://google.com/"; NavigationObserverImpl observer(GetNavigationController()); observer.SetStartedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { navigation->SetRequestHeader(header_name, header_value); })); shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html")); response.WaitForRequest(); // Verify 'referer' matches expected value. EXPECT_EQ(header_value, response.http_request()->headers.at(header_name)); } #endif IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, OnPageLanguageDeterminedCallback) { ASSERT_TRUE(embedded_test_server()->Start()); NavigationController* controller = shell()->tab()->GetNavigationController(); NavigationObserverImpl observer(controller); Page* committed_page = nullptr; Page* page_with_language_determined = nullptr; std::string determined_language = ""; base::RunLoop navigation_run_loop1; base::RunLoop page_language_determination_run_loop1; base::RunLoop* navigation_run_loop = &navigation_run_loop1; base::RunLoop* page_language_determination_run_loop = &page_language_determination_run_loop1; observer.SetCompletedClosure( base::BindLambdaForTesting([&](Navigation* navigation) { committed_page = navigation->GetPage(); navigation_run_loop->Quit(); })); observer.SetOnPageLanguageDeterminedCallback( base::BindLambdaForTesting([&](Page* page, std::string language) { page_with_language_determined = page; determined_language = language; page_language_determination_run_loop->Quit(); })); // Navigate to a page in English. controller->Navigate(embedded_test_server()->GetURL("/english_page.html")); navigation_run_loop1.Run(); EXPECT_TRUE(committed_page); // Verify that the language determined event fires as expected. page_language_determination_run_loop1.Run(); EXPECT_EQ(committed_page, page_with_language_determined); EXPECT_EQ("en", determined_language); // Now navigate to a page in French. committed_page = nullptr; page_with_language_determined = nullptr; base::RunLoop navigation_run_loop2; base::RunLoop page_language_determination_run_loop2; navigation_run_loop = &navigation_run_loop2; page_language_determination_run_loop = &page_language_determination_run_loop2; controller->Navigate(embedded_test_server()->GetURL("/french_page.html")); navigation_run_loop2.Run(); EXPECT_TRUE(committed_page); // Verify that the language determined event fires as expected. page_language_determination_run_loop2.Run(); EXPECT_EQ(committed_page, page_with_language_determined); EXPECT_EQ("fr", determined_language); } // Verifies that closing a tab when a navigation is waiting for a response // causes the navigation to be marked as failed to the embedder. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, CloseTabWithNavigationWaitingForResponse) { net::test_server::ControllableHttpResponse response(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); GURL url = embedded_test_server()->GetURL("/initial_url.html"); base::RunLoop run_loop; Navigation* ongoing_navigation = nullptr; auto observer = std::make_unique<NavigationObserverImpl>(GetNavigationController()); observer->SetStartedCallback(base::BindLambdaForTesting( [&](Navigation* navigation) { ongoing_navigation = navigation; })); observer->SetFailedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { EXPECT_EQ(url, navigation->GetURL()); EXPECT_EQ(NavigationState::kFailed, navigation->GetState()); run_loop.Quit(); // The NavigationControllerImpl that |observer| is observing will // be destroyed before control returns to the test, so destroy // |observer| now to avoid UaF. observer.reset(); })); shell()->LoadURL(url); response.WaitForRequest(); EXPECT_EQ(NavigationState::kWaitingResponse, ongoing_navigation->GetState()); shell()->browser()->DestroyTab(shell()->tab()); run_loop.Run(); } // Verifies that closing a tab when a navigation is in the middle of receiving a // response causes the navigation to be marked as failed to the embedder. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, CloseTabWithNavigationReceivingBytes) { net::test_server::ControllableHttpResponse response(embedded_test_server(), "", true); ASSERT_TRUE(embedded_test_server()->Start()); GURL url = embedded_test_server()->GetURL("/initial_url.html"); base::RunLoop run_loop; Navigation* ongoing_navigation = nullptr; auto observer = std::make_unique<NavigationObserverImpl>(GetNavigationController()); observer->SetStartedCallback(base::BindLambdaForTesting( [&](Navigation* navigation) { ongoing_navigation = navigation; })); observer->SetFailedCallback( base::BindLambdaForTesting([&](Navigation* navigation) { EXPECT_EQ(url, navigation->GetURL()); EXPECT_EQ(NavigationState::kFailed, navigation->GetState()); run_loop.Quit(); // The NavigationControllerImpl that |observer| is observing will // be destroyed before control returns to the test, so destroy // |observer| now to avoid UaF. observer.reset(); })); auto* tab = static_cast<TabImpl*>(shell()->tab()); auto wait_for_response_start = std::make_unique<content::TestNavigationManager>(tab->web_contents(), url); shell()->LoadURL(url); // Wait until request is ready to start. EXPECT_TRUE(wait_for_response_start->WaitForRequestStart()); // Start the request. wait_for_response_start->ResumeNavigation(); // Wait for the request to arrive to ControllableHttpResponse. response.WaitForRequest(); response.Send(net::HTTP_OK, "text/html", "<html>"); ASSERT_TRUE(wait_for_response_start->WaitForResponse()); EXPECT_EQ(NavigationState::kReceivingBytes, ongoing_navigation->GetState()); // Destroy |wait_for_response_start| before we indirectly destroy the // WebContents it's observing. wait_for_response_start.reset(); shell()->browser()->DestroyTab(tab); run_loop.Run(); } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_browsertest.cc
C++
unknown
49,751
// 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/browser/navigation_controller_impl.h" #include <utility> #include "base/auto_reset.h" #include "base/containers/contains.h" #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner.h" #include "build/build_config.h" #include "components/content_relationship_verification/response_header_verifier.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/navigation_throttle.h" #include "content/public/browser/web_contents.h" #include "third_party/blink/public/mojom/navigation/was_activated_option.mojom-shared.h" #include "ui/base/page_transition_types.h" #include "weblayer/browser/browser_impl.h" #include "weblayer/browser/navigation_entry_data.h" #include "weblayer/browser/navigation_ui_data_impl.h" #include "weblayer/browser/page_impl.h" #include "weblayer/browser/tab_impl.h" #include "weblayer/public/navigation_observer.h" #if BUILDFLAG(IS_ANDROID) #include "base/android/jni_string.h" #include "base/trace_event/trace_event.h" #include "components/embedder_support/android/util/web_resource_response.h" #include "weblayer/browser/java/jni/NavigationControllerImpl_jni.h" #endif #if BUILDFLAG(IS_ANDROID) using base::android::AttachCurrentThread; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; #endif namespace weblayer { class NavigationControllerImpl::DelayDeletionHelper { public: explicit DelayDeletionHelper(NavigationControllerImpl* controller) : controller_(controller->weak_ptr_factory_.GetWeakPtr()) { // This should never be called reentrantly. DCHECK(!controller->should_delay_web_contents_deletion_); controller->should_delay_web_contents_deletion_ = true; } DelayDeletionHelper(const DelayDeletionHelper&) = delete; DelayDeletionHelper& operator=(const DelayDeletionHelper&) = delete; ~DelayDeletionHelper() { if (controller_) controller_->should_delay_web_contents_deletion_ = false; } bool WasControllerDeleted() { return controller_.get() == nullptr; } private: base::WeakPtr<NavigationControllerImpl> controller_; }; // NavigationThrottle implementation responsible for delaying certain // operations and performing them when safe. This is necessary as content // does allow certain operations to be called at certain times. For example, // content does not allow calling WebContents::Stop() from // WebContentsObserver::DidStartNavigation() (to do so crashes). To work around // this NavigationControllerImpl detects these scenarios and delays processing // until safe. // // Most of the support for these scenarios is handled by a custom // NavigationThrottle. To make things interesting, the NavigationThrottle is // created after some of the scenarios this code wants to handle. As such, // NavigationImpl does some amount of caching until the NavigationThrottle is // created. class NavigationControllerImpl::NavigationThrottleImpl : public content::NavigationThrottle { public: NavigationThrottleImpl(NavigationControllerImpl* controller, content::NavigationHandle* handle) : NavigationThrottle(handle), controller_(controller) {} NavigationThrottleImpl(const NavigationThrottleImpl&) = delete; NavigationThrottleImpl& operator=(const NavigationThrottleImpl&) = delete; ~NavigationThrottleImpl() override = default; void ScheduleCancel() { should_cancel_ = true; } void ScheduleBlock() { should_block_ = true; } // content::NavigationThrottle: ThrottleCheckResult WillStartRequest() override { if (should_cancel_) { return CANCEL; } if (should_block_) { return BLOCK_REQUEST; } return PROCEED; } ThrottleCheckResult WillRedirectRequest() override { controller_->WillRedirectRequest(this, navigation_handle()); if (should_cancel_) { return CANCEL; } if (should_block_) { return BLOCK_REQUEST; } return PROCEED; } const char* GetNameForLogging() override { return "WebLayerNavigationControllerThrottle"; } private: raw_ptr<NavigationControllerImpl> controller_; bool should_cancel_ = false; bool should_block_ = false; }; NavigationControllerImpl::NavigationControllerImpl(TabImpl* tab) : WebContentsObserver(tab->web_contents()), tab_(tab) {} NavigationControllerImpl::~NavigationControllerImpl() = default; std::unique_ptr<content::NavigationThrottle> NavigationControllerImpl::CreateNavigationThrottle( content::NavigationHandle* handle) { if (!handle->IsInMainFrame()) return nullptr; auto throttle = std::make_unique<NavigationThrottleImpl>(this, handle); DCHECK(navigation_map_.find(handle) != navigation_map_.end()); auto* navigation = navigation_map_[handle].get(); if (navigation->should_stop_when_throttle_created()) throttle->ScheduleCancel(); if (navigation->should_block_when_throttle_created()) { throttle->ScheduleBlock(); } return throttle; } NavigationImpl* NavigationControllerImpl::GetNavigationImplFromHandle( content::NavigationHandle* handle) { auto iter = navigation_map_.find(handle); return iter == navigation_map_.end() ? nullptr : iter->second.get(); } NavigationImpl* NavigationControllerImpl::GetNavigationImplFromId( int64_t navigation_id) { for (const auto& iter : navigation_map_) { if (iter.first->GetNavigationId() == navigation_id) return iter.second.get(); } return nullptr; } void NavigationControllerImpl::OnFirstContentfulPaint( const base::TimeTicks& navigation_start, const base::TimeDelta& first_contentful_paint) { #if BUILDFLAG(IS_ANDROID) TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_onFirstContentfulPaint2"); int64_t first_contentful_paint_ms = first_contentful_paint.InMilliseconds(); Java_NavigationControllerImpl_onFirstContentfulPaint2( AttachCurrentThread(), java_controller_, navigation_start.ToUptimeMillis(), first_contentful_paint_ms); #endif for (auto& observer : observers_) observer.OnFirstContentfulPaint(navigation_start, first_contentful_paint); } void NavigationControllerImpl::OnLargestContentfulPaint( const base::TimeTicks& navigation_start, const base::TimeDelta& largest_contentful_paint) { #if BUILDFLAG(IS_ANDROID) TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_onLargestContentfulPaint2"); int64_t largest_contentful_paint_ms = largest_contentful_paint.InMilliseconds(); Java_NavigationControllerImpl_onLargestContentfulPaint( AttachCurrentThread(), java_controller_, navigation_start.ToUptimeMillis(), largest_contentful_paint_ms); #endif for (auto& observer : observers_) observer.OnLargestContentfulPaint(navigation_start, largest_contentful_paint); } void NavigationControllerImpl::OnPageDestroyed(Page* page) { for (auto& observer : observers_) observer.OnPageDestroyed(page); } void NavigationControllerImpl::OnPageLanguageDetermined( Page* page, const std::string& language) { #if BUILDFLAG(IS_ANDROID) JNIEnv* env = AttachCurrentThread(); Java_NavigationControllerImpl_onPageLanguageDetermined( env, java_controller_, static_cast<PageImpl*>(page)->java_page(), base::android::ConvertUTF8ToJavaString(env, language)); #endif for (auto& observer : observers_) observer.OnPageLanguageDetermined(page, language); } #if BUILDFLAG(IS_ANDROID) void NavigationControllerImpl::SetNavigationControllerImpl( JNIEnv* env, const JavaParamRef<jobject>& java_controller) { java_controller_ = java_controller; } void NavigationControllerImpl::Navigate( JNIEnv* env, const JavaParamRef<jstring>& url, jboolean should_replace_current_entry, jboolean disable_intent_processing, jboolean allow_intent_launches_in_background, jboolean disable_network_error_auto_reload, jboolean enable_auto_play, const base::android::JavaParamRef<jobject>& response) { auto params = std::make_unique<content::NavigationController::LoadURLParams>( GURL(base::android::ConvertJavaStringToUTF8(env, url))); params->should_replace_current_entry = should_replace_current_entry; // On android, the transition type largely dictates whether intent processing // happens. PAGE_TRANSITION_TYPED does not process intents, where as // PAGE_TRANSITION_LINK will (with the caveat that even links may not trigger // intent processing under some circumstances). params->transition_type = disable_intent_processing ? ui::PAGE_TRANSITION_TYPED : ui::PAGE_TRANSITION_LINK; auto data = std::make_unique<NavigationUIDataImpl>(); if (disable_network_error_auto_reload) data->set_disable_network_error_auto_reload(true); data->set_allow_intent_launches_in_background( allow_intent_launches_in_background); if (!response.is_null()) { data->SetResponse( std::make_unique<embedder_support::WebResourceResponse>(response)); } params->navigation_ui_data = std::move(data); if (enable_auto_play) params->was_activated = blink::mojom::WasActivatedOption::kYes; DoNavigate(std::move(params)); } ScopedJavaLocalRef<jstring> NavigationControllerImpl::GetNavigationEntryDisplayUri(JNIEnv* env, int index) { return ScopedJavaLocalRef<jstring>(base::android::ConvertUTF8ToJavaString( env, GetNavigationEntryDisplayURL(index).spec())); } ScopedJavaLocalRef<jstring> NavigationControllerImpl::GetNavigationEntryTitle( JNIEnv* env, int index) { return ScopedJavaLocalRef<jstring>(base::android::ConvertUTF8ToJavaString( env, GetNavigationEntryTitle(index))); } bool NavigationControllerImpl::IsNavigationEntrySkippable(JNIEnv* env, int index) { return IsNavigationEntrySkippable(index); } base::android::ScopedJavaGlobalRef<jobject> NavigationControllerImpl::GetNavigationImplFromId(JNIEnv* env, int64_t id) { auto* navigation_impl = GetNavigationImplFromId(id); return navigation_impl ? navigation_impl->java_navigation() : nullptr; } #endif void NavigationControllerImpl::WillRedirectRequest( NavigationThrottleImpl* throttle, content::NavigationHandle* navigation_handle) { DCHECK(navigation_handle->IsInMainFrame()); DCHECK(navigation_map_.find(navigation_handle) != navigation_map_.end()); auto* navigation = navigation_map_[navigation_handle].get(); navigation->set_safe_to_set_request_headers(true); DCHECK(!active_throttle_); base::AutoReset<NavigationThrottleImpl*> auto_reset(&active_throttle_, throttle); #if BUILDFLAG(IS_ANDROID) if (java_controller_) { TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_navigationRedirected"); Java_NavigationControllerImpl_navigationRedirected( AttachCurrentThread(), java_controller_, navigation->java_navigation()); } #endif for (auto& observer : observers_) observer.NavigationRedirected(navigation); navigation->set_safe_to_set_request_headers(false); } void NavigationControllerImpl::AddObserver(NavigationObserver* observer) { observers_.AddObserver(observer); } void NavigationControllerImpl::RemoveObserver(NavigationObserver* observer) { observers_.RemoveObserver(observer); } void NavigationControllerImpl::Navigate(const GURL& url) { DoNavigate( std::make_unique<content::NavigationController::LoadURLParams>(url)); } void NavigationControllerImpl::Navigate( const GURL& url, const NavigationController::NavigateParams& params) { auto load_params = std::make_unique<content::NavigationController::LoadURLParams>(url); load_params->should_replace_current_entry = params.should_replace_current_entry; if (params.enable_auto_play) load_params->was_activated = blink::mojom::WasActivatedOption::kYes; DoNavigate(std::move(load_params)); } void NavigationControllerImpl::GoBack() { web_contents()->GetController().GoBack(); } void NavigationControllerImpl::GoForward() { web_contents()->GetController().GoForward(); } bool NavigationControllerImpl::CanGoBack() { return web_contents()->GetController().CanGoBack(); } bool NavigationControllerImpl::CanGoForward() { return web_contents()->GetController().CanGoForward(); } void NavigationControllerImpl::GoToIndex(int index) { web_contents()->GetController().GoToIndex(index); } void NavigationControllerImpl::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, true); } void NavigationControllerImpl::Stop() { CancelDelayedLoad(); NavigationImpl* navigation = nullptr; if (navigation_starting_) { navigation_starting_->set_should_stop_when_throttle_created(); navigation = navigation_starting_; } else if (active_throttle_) { active_throttle_->ScheduleCancel(); DCHECK(navigation_map_.find(active_throttle_->navigation_handle()) != navigation_map_.end()); navigation = navigation_map_[active_throttle_->navigation_handle()].get(); } else { web_contents()->Stop(); } if (navigation) navigation->set_was_stopped(); } int NavigationControllerImpl::GetNavigationListSize() { if (web_contents() ->GetController() .GetLastCommittedEntry() ->IsInitialEntry()) { // If we're currently on the initial NavigationEntry, no navigation has // committed, so the initial NavigationEntry should not be part of the // "Navigation List", and we should return 0 as the navigation list size. // This also preserves the old behavior where we used to not have the // initial NavigationEntry. return 0; } return web_contents()->GetController().GetEntryCount(); } int NavigationControllerImpl::GetNavigationListCurrentIndex() { if (web_contents() ->GetController() .GetLastCommittedEntry() ->IsInitialEntry()) { // If we're currently on the initial NavigationEntry, no navigation has // committed, so the initial NavigationEntry should not be part of the // "Navigation List", and we should return -1 as the current index. This // also preserves the old behavior where we used to not have the initial // NavigationEntry. return -1; } return web_contents()->GetController().GetCurrentEntryIndex(); } GURL NavigationControllerImpl::GetNavigationEntryDisplayURL(int index) { auto* entry = web_contents()->GetController().GetEntryAtIndex(index); // This function should never be called when GetNavigationListSize() is 0 // because `index` should be between 0 and GetNavigationListSize() - 1, which // also means `entry` must not be the initial NavigationEntry. DCHECK_NE(0, GetNavigationListSize()); DCHECK(!entry->IsInitialEntry()); return entry->GetVirtualURL(); } std::string NavigationControllerImpl::GetNavigationEntryTitle(int index) { auto* entry = web_contents()->GetController().GetEntryAtIndex(index); // This function should never be called when GetNavigationListSize() is 0 // because `index` should be between 0 and GetNavigationListSize() - 1, which // also means `entry` must not be the initial NavigationEntry. DCHECK_NE(0, GetNavigationListSize()); DCHECK(!entry->IsInitialEntry()); return base::UTF16ToUTF8(entry->GetTitle()); } bool NavigationControllerImpl::IsNavigationEntrySkippable(int index) { return web_contents()->GetController().IsEntryMarkedToBeSkipped(index); } void NavigationControllerImpl::DidStartNavigation( content::NavigationHandle* navigation_handle) { // TODO(https://crbug.com/1218946): With MPArch there may be multiple main // frames. This caller was converted automatically to the primary main frame // to preserve its semantics. Follow up to confirm correctness. if (!navigation_handle->IsInPrimaryMainFrame()) return; // This function should not be called reentrantly. DCHECK(!navigation_starting_); DCHECK(!base::Contains(navigation_map_, navigation_handle)); navigation_map_[navigation_handle] = std::make_unique<NavigationImpl>(navigation_handle); auto* navigation = navigation_map_[navigation_handle].get(); base::AutoReset<NavigationImpl*> auto_reset(&navigation_starting_, navigation); navigation->set_safe_to_set_request_headers(true); navigation->set_safe_to_disable_network_error_auto_reload(true); navigation->set_safe_to_disable_intent_processing(true); #if BUILDFLAG(IS_ANDROID) // Desktop mode and per-navigation UA use the same mechanism and so don't // interact well. It's not possible to support both at the same time since // if there's a per-navigation UA active and desktop mode is turned on, or // was on previously, the WebContent's state would have to change before // navigation even though that would be wrong for the previous navigation if // the new navigation didn't commit. if (!TabImpl::FromWebContents(web_contents())->desktop_user_agent_enabled()) #endif navigation->set_safe_to_set_user_agent(true); #if BUILDFLAG(IS_ANDROID) NavigationUIDataImpl* navigation_ui_data = static_cast<NavigationUIDataImpl*>( navigation_handle->GetNavigationUIData()); if (navigation_ui_data) { auto response = navigation_ui_data->TakeResponse(); if (response) navigation->SetResponse(std::move(response)); } if (java_controller_) { JNIEnv* env = AttachCurrentThread(); if (navigation->GetURL().SchemeIsHTTPOrHTTPS()) { TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_isUrlAllowed"); ScopedJavaLocalRef<jstring> jstring_url = base::android::ConvertUTF8ToJavaString(env, navigation->GetURL().spec()); jboolean is_allowed = Java_NavigationControllerImpl_isUrlAllowed( env, java_controller_, jstring_url); if (!is_allowed) { navigation->set_should_block_when_throttle_created(); } } { TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_createNavigation"); ScopedJavaLocalRef<jobject> java_navigation = Java_NavigationControllerImpl_createNavigation( env, java_controller_, reinterpret_cast<jlong>(navigation)); navigation->SetJavaNavigation( base::android::ScopedJavaGlobalRef<jobject>(java_navigation)); } TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_navigationStarted"); Java_NavigationControllerImpl_navigationStarted( env, java_controller_, navigation->java_navigation()); } #endif for (auto& observer : observers_) observer.NavigationStarted(navigation); navigation->set_safe_to_set_user_agent(false); navigation->set_safe_to_set_request_headers(false); navigation->set_safe_to_disable_network_error_auto_reload(false); navigation->set_safe_to_disable_intent_processing(false); } void NavigationControllerImpl::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { // NOTE: this implementation should remain empty. Real implementation is in // WillRedirectNavigation(). See description of NavigationThrottleImpl for // more information. } void NavigationControllerImpl::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { #if BUILDFLAG(IS_ANDROID) // TODO(https://crbug.com/1218946): With MPArch there may be multiple main // frames. This caller was converted automatically to the primary main frame // to preserve its semantics. Follow up to confirm correctness. if (!navigation_handle->IsInPrimaryMainFrame()) return; DCHECK(navigation_map_.find(navigation_handle) != navigation_map_.end()); auto* navigation = navigation_map_[navigation_handle].get(); if (java_controller_) { TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_readyToCommitNavigation"); Java_NavigationControllerImpl_readyToCommitNavigation( AttachCurrentThread(), java_controller_, navigation->java_navigation()); } #endif } void NavigationControllerImpl::DidFinishNavigation( content::NavigationHandle* navigation_handle) { // TODO(https://crbug.com/1218946): With MPArch there may be multiple main // frames. This caller was converted automatically to the primary main frame // to preserve its semantics. Follow up to confirm correctness. if (!navigation_handle->IsInPrimaryMainFrame()) return; DelayDeletionHelper deletion_helper(this); DCHECK(navigation_map_.find(navigation_handle) != navigation_map_.end()); auto* navigation = navigation_map_[navigation_handle].get(); navigation->set_finished(); if (navigation_handle->HasCommitted()) { // Set state on NavigationEntry user data if a per-navigation user agent was // specified. This can't be done earlier because a NavigationEntry might not // have existed at the time that SetUserAgentString was called. if (navigation->set_user_agent_string_called()) { auto* entry = web_contents()->GetController().GetLastCommittedEntry(); if (entry) { auto* entry_data = NavigationEntryData::Get(entry); if (entry_data) entry_data->set_per_navigation_user_agent_override(true); } } auto* rfh = navigation_handle->GetRenderFrameHost(); PageImpl::GetOrCreateForPage(rfh->GetPage()); navigation->set_safe_to_get_page(); #if BUILDFLAG(IS_ANDROID) // Ensure that the Java-side Page object for this navigation is // populated from and linked to the native Page object. Without this // call, the Java-side navigation object won't be created and linked to // the native object until/unless the client calls Navigation#getPage(), // which is problematic when implementation-side callers need to bridge // the C++ Page object into Java (e.g., to fire // NavigationCallback#onPageLanguageDetermined()). Java_NavigationControllerImpl_getOrCreatePageForNavigation( AttachCurrentThread(), java_controller_, navigation->java_navigation()); #endif } // In some corner cases (e.g., a tab closing with an ongoing navigation) // navigations finish without committing but without any other error state. // Such navigations are regarded as failed by WebLayer. if (navigation_handle->HasCommitted() && navigation_handle->GetNetErrorCode() == net::OK && !navigation_handle->IsErrorPage()) { if (!navigation_handle->IsSameDocument()) { content_relationship_verification::ResponseHeaderVerificationResult header_verification_result = content_relationship_verification::ResponseHeaderVerifier::Verify( tab_->browser()->GetPackageName(), navigation->GetNormalizedHeader( content_relationship_verification:: kEmbedderAncestorHeader)); bool allowed_or_missing_consent = header_verification_result == content_relationship_verification:: ResponseHeaderVerificationResult::kAllow || header_verification_result == content_relationship_verification:: ResponseHeaderVerificationResult::kMissing; navigation->set_consenting_content(allowed_or_missing_consent); } #if BUILDFLAG(IS_ANDROID) if (java_controller_) { TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_navigationCompleted"); Java_NavigationControllerImpl_navigationCompleted( AttachCurrentThread(), java_controller_, navigation->java_navigation()); if (deletion_helper.WasControllerDeleted()) return; } #endif for (auto& observer : observers_) { observer.NavigationCompleted(navigation); if (deletion_helper.WasControllerDeleted()) return; } } else { #if BUILDFLAG(IS_ANDROID) navigation->set_consenting_content(false); if (java_controller_) { TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_navigationFailed"); Java_NavigationControllerImpl_navigationFailed( AttachCurrentThread(), java_controller_, navigation->java_navigation()); if (deletion_helper.WasControllerDeleted()) return; } #endif for (auto& observer : observers_) { observer.NavigationFailed(navigation); if (deletion_helper.WasControllerDeleted()) return; } } // Note InsertVisualStateCallback currently does not take into account // any delays from surface sync, ie a frame submitted by renderer may not // be displayed immediately. Such situations should be rare however, so // this should be good enough for the purposes needed. web_contents()->GetPrimaryMainFrame()->InsertVisualStateCallback( base::BindOnce(&NavigationControllerImpl::OldPageNoLongerRendered, weak_ptr_factory_.GetWeakPtr(), navigation_handle->GetURL())); navigation_map_.erase(navigation_map_.find(navigation_handle)); } void NavigationControllerImpl::DidStartLoading() { NotifyLoadStateChanged(); } void NavigationControllerImpl::DidStopLoading() { NotifyLoadStateChanged(); } void NavigationControllerImpl::LoadProgressChanged(double progress) { #if BUILDFLAG(IS_ANDROID) if (java_controller_) { TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_loadProgressChanged"); Java_NavigationControllerImpl_loadProgressChanged( AttachCurrentThread(), java_controller_, progress); } #endif for (auto& observer : observers_) observer.LoadProgressChanged(progress); } void NavigationControllerImpl::DidFirstVisuallyNonEmptyPaint() { #if BUILDFLAG(IS_ANDROID) TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_onFirstContentfulPaint"); Java_NavigationControllerImpl_onFirstContentfulPaint(AttachCurrentThread(), java_controller_); #endif for (auto& observer : observers_) observer.OnFirstContentfulPaint(); } void NavigationControllerImpl::OldPageNoLongerRendered(const GURL& url, bool success) { #if BUILDFLAG(IS_ANDROID) TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_onOldPageNoLongerRendered"); JNIEnv* env = AttachCurrentThread(); Java_NavigationControllerImpl_onOldPageNoLongerRendered( env, java_controller_, base::android::ConvertUTF8ToJavaString(env, url.spec())); #endif for (auto& observer : observers_) observer.OnOldPageNoLongerRendered(url); } void NavigationControllerImpl::NotifyLoadStateChanged() { #if BUILDFLAG(IS_ANDROID) if (java_controller_) { TRACE_EVENT0("weblayer", "Java_NavigationControllerImpl_loadStateChanged"); Java_NavigationControllerImpl_loadStateChanged( AttachCurrentThread(), java_controller_, web_contents()->IsLoading(), web_contents()->ShouldShowLoadingUI()); } #endif for (auto& observer : observers_) { observer.LoadStateChanged(web_contents()->IsLoading(), web_contents()->ShouldShowLoadingUI()); } } void NavigationControllerImpl::DoNavigate( std::unique_ptr<content::NavigationController::LoadURLParams> params) { CancelDelayedLoad(); // Navigations should use the default user-agent (which may be overridden if // desktop mode is turned on). If the embedder wants a custom user-agent, the // embedder will call Navigation::SetUserAgentString() in DidStartNavigation. #if BUILDFLAG(IS_ANDROID) // We need to set UA_OVERRIDE_FALSE if per navigation UA is set. However at // this point we don't know if the embedder will call that later. Since we // ensure that the two can't be set at the same time, it's sufficient to // not enable it if desktop mode is turned on. if (!TabImpl::FromWebContents(web_contents())->desktop_user_agent_enabled()) #endif params->override_user_agent = content::NavigationController::UA_OVERRIDE_FALSE; if (navigation_starting_ || active_throttle_) { // DoNavigate() is being called reentrantly. Delay processing until it's // safe. Stop(); ScheduleDelayedLoad(std::move(params)); return; } params->has_user_gesture = true; web_contents()->GetController().LoadURLWithParams(*params); // So that if the user had entered the UI in a bar it stops flashing the // caret. web_contents()->Focus(); } void NavigationControllerImpl::ScheduleDelayedLoad( std::unique_ptr<content::NavigationController::LoadURLParams> params) { delayed_load_params_ = std::move(params); base::SequencedTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(&NavigationControllerImpl::ProcessDelayedLoad, weak_ptr_factory_.GetWeakPtr())); } void NavigationControllerImpl::CancelDelayedLoad() { delayed_load_params_.reset(); } void NavigationControllerImpl::ProcessDelayedLoad() { if (delayed_load_params_) DoNavigate(std::move(delayed_load_params_)); } #if BUILDFLAG(IS_ANDROID) static jlong JNI_NavigationControllerImpl_GetNavigationController(JNIEnv* env, jlong tab) { return reinterpret_cast<jlong>( reinterpret_cast<Tab*>(tab)->GetNavigationController()); } #endif } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_controller_impl.cc
C++
unknown
29,677
// 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_BROWSER_NAVIGATION_CONTROLLER_IMPL_H_ #define WEBLAYER_BROWSER_NAVIGATION_CONTROLLER_IMPL_H_ #include <map> #include <memory> #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "build/build_config.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/web_contents_observer.h" #include "weblayer/browser/navigation_impl.h" #include "weblayer/public/navigation_controller.h" #if BUILDFLAG(IS_ANDROID) #include "base/android/scoped_java_ref.h" #endif namespace content { class NavigationHandle; class NavigationThrottle; } // namespace content namespace weblayer { class NavigationImpl; class TabImpl; class NavigationControllerImpl : public NavigationController, public content::WebContentsObserver { public: explicit NavigationControllerImpl(TabImpl* tab); NavigationControllerImpl(const NavigationControllerImpl&) = delete; NavigationControllerImpl& operator=(const NavigationControllerImpl&) = delete; ~NavigationControllerImpl() override; // Creates the NavigationThrottle used to ensure WebContents::Stop() is called // at safe times. See NavigationControllerImpl for details. std::unique_ptr<content::NavigationThrottle> CreateNavigationThrottle( content::NavigationHandle* handle); // Returns the NavigationImpl for |handle|, or null if there isn't one. NavigationImpl* GetNavigationImplFromHandle( content::NavigationHandle* handle); // Returns the NavigationImpl for |navigation_id|, or null if there isn't one. NavigationImpl* GetNavigationImplFromId(int64_t navigation_id); // Called when the first contentful paint page load metric is available. // |navigation_start| is the navigation start time. // |first_contentful_paint_ms| is the duration to first contentful paint from // navigation start. void OnFirstContentfulPaint(const base::TimeTicks& navigation_start, const base::TimeDelta& first_contentful_paint); // Called 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. void OnLargestContentfulPaint( const base::TimeTicks& navigation_start, const base::TimeDelta& largest_contentful_paint); void OnPageDestroyed(Page* page); void OnPageLanguageDetermined(Page* page, const std::string& language); #if BUILDFLAG(IS_ANDROID) void SetNavigationControllerImpl( JNIEnv* env, const base::android::JavaParamRef<jobject>& java_controller); void Navigate(JNIEnv* env, const base::android::JavaParamRef<jstring>& url, jboolean should_replace_current_entry, jboolean disable_intent_processing, jboolean allow_intent_launches_in_background, jboolean disable_network_error_auto_reload, jboolean enable_auto_play, const base::android::JavaParamRef<jobject>& response); void GoBack(JNIEnv* env) { GoBack(); } void GoForward(JNIEnv* env) { GoForward(); } bool CanGoBack(JNIEnv* env) { return CanGoBack(); } bool CanGoForward(JNIEnv* env) { return CanGoForward(); } void GoToIndex(JNIEnv* env, int index) { return GoToIndex(index); } void Reload(JNIEnv* env) { Reload(); } void Stop(JNIEnv* env) { Stop(); } int GetNavigationListSize(JNIEnv* env) { return GetNavigationListSize(); } int GetNavigationListCurrentIndex(JNIEnv* env) { return GetNavigationListCurrentIndex(); } base::android::ScopedJavaLocalRef<jstring> GetNavigationEntryDisplayUri( JNIEnv* env, int index); base::android::ScopedJavaLocalRef<jstring> GetNavigationEntryTitle( JNIEnv* env, int index); bool IsNavigationEntrySkippable(JNIEnv* env, int index); base::android::ScopedJavaGlobalRef<jobject> GetNavigationImplFromId( JNIEnv* env, int64_t id); #endif bool should_delay_web_contents_deletion() { return should_delay_web_contents_deletion_; } private: class DelayDeletionHelper; class NavigationThrottleImpl; // Called from NavigationControllerImpl::WillRedirectRequest(). See // description of NavigationControllerImpl for details. void WillRedirectRequest(NavigationThrottleImpl* throttle, content::NavigationHandle* navigation_handle); // NavigationController implementation: void AddObserver(NavigationObserver* observer) override; void RemoveObserver(NavigationObserver* observer) override; void Navigate(const GURL& url) override; void Navigate(const GURL& url, const NavigateParams& params) override; void GoBack() override; void GoForward() override; bool CanGoBack() override; bool CanGoForward() override; void GoToIndex(int index) override; void Reload() override; void Stop() override; int GetNavigationListSize() override; int GetNavigationListCurrentIndex() override; GURL GetNavigationEntryDisplayURL(int index) override; std::string GetNavigationEntryTitle(int index) override; bool IsNavigationEntrySkippable(int index) override; // content::WebContentsObserver implementation: void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void DidRedirectNavigation( content::NavigationHandle* navigation_handle) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void DidStartLoading() override; void DidStopLoading() override; void LoadProgressChanged(double progress) override; void DidFirstVisuallyNonEmptyPaint() override; void OldPageNoLongerRendered(const GURL& url, bool success); void NotifyLoadStateChanged(); void DoNavigate( std::unique_ptr<content::NavigationController::LoadURLParams> params); // Schedules a load to happen as soon as possible. This is used in cases // where it is not safe to call load. In particular, if a load was just // started. Content is generally not reentrant when starting a load and has // CHECKs to ensure it doesn't happen. void ScheduleDelayedLoad( std::unique_ptr<content::NavigationController::LoadURLParams> params); void CancelDelayedLoad(); void ProcessDelayedLoad(); // |tab_| owns |this|. raw_ptr<TabImpl> tab_; base::ObserverList<NavigationObserver>::Unchecked observers_; std::map<content::NavigationHandle*, std::unique_ptr<NavigationImpl>> navigation_map_; // If non-null then processing is inside DidStartNavigation() and // |navigation_starting_| is the NavigationImpl that was created. // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION NavigationImpl* navigation_starting_ = nullptr; // Set to non-null while in WillRedirectRequest(). // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION NavigationThrottleImpl* active_throttle_ = nullptr; #if BUILDFLAG(IS_ANDROID) base::android::ScopedJavaGlobalRef<jobject> java_controller_; #endif // Set to true while processing an observer/callback and it's unsafe to // delete the WebContents. This is not used for all callbacks, just the // ones that we need to allow deletion from (such as completed/failed). bool should_delay_web_contents_deletion_ = false; // See comment in ScheduleDelayedLoad() for details. std::unique_ptr<content::NavigationController::LoadURLParams> delayed_load_params_; base::WeakPtrFactory<NavigationControllerImpl> weak_ptr_factory_{this}; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NAVIGATION_CONTROLLER_IMPL_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_controller_impl.h
C++
unknown
8,042
// 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/browser/navigation_entry_data.h" #include "base/memory/ptr_util.h" #include "content/public/browser/navigation_entry.h" namespace weblayer { namespace { const char kCacheKey[] = "weblayer_navigation_entry_data"; } // namespace NavigationEntryData::ResponseData::ResponseData() = default; NavigationEntryData::ResponseData::~ResponseData() = default; NavigationEntryData::NavigationEntryData() = default; NavigationEntryData::~NavigationEntryData() = default; std::unique_ptr<base::SupportsUserData::Data> NavigationEntryData::Clone() { auto rv = base::WrapUnique(new NavigationEntryData); rv->per_navigation_user_agent_override_ = per_navigation_user_agent_override_; if (response_data_) { rv->response_data_ = std::make_unique<ResponseData>(); rv->response_data_->response_head = response_data_->response_head.Clone(); rv->response_data_->data = response_data_->data; rv->response_data_->request_time = response_data_->request_time; rv->response_data_->response_time = response_data_->response_time; } return rv; } NavigationEntryData* NavigationEntryData::Get(content::NavigationEntry* entry) { auto* data = static_cast<NavigationEntryData*>(entry->GetUserData(kCacheKey)); if (!data) { auto data_object = base::WrapUnique(new NavigationEntryData); data = data_object.get(); entry->SetUserData(kCacheKey, std::move(data_object)); } return data; } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_entry_data.cc
C++
unknown
1,598
// 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_BROWSER_NAVIGATION_ENTRY_DATA_H_ #define WEBLAYER_BROWSER_NAVIGATION_ENTRY_DATA_H_ #include "base/supports_user_data.h" #include "base/time/time.h" #include "services/network/public/mojom/url_response_head.mojom.h" namespace content { class NavigationEntry; } namespace weblayer { // Holds extra data stored on content::NavigationEntry. class NavigationEntryData : public base::SupportsUserData::Data { public: ~NavigationEntryData() override; // base::SupportsUserData::Data implementation: std::unique_ptr<Data> Clone() override; static NavigationEntryData* Get(content::NavigationEntry* entry); // Stored on the NavigationEntry when we have a cached response from an // InputStream. struct ResponseData { ResponseData(); ~ResponseData(); network::mojom::URLResponseHeadPtr response_head; std::string data; base::Time request_time; base::Time response_time; }; void set_response_data(std::unique_ptr<ResponseData> data) { response_data_ = std::move(data); } void reset_response_data() { response_data_.reset(); } ResponseData* response_data() { return response_data_.get(); } void set_per_navigation_user_agent_override(bool value) { per_navigation_user_agent_override_ = value; } bool per_navigation_user_agent_override() { return per_navigation_user_agent_override_; } private: NavigationEntryData(); std::unique_ptr<ResponseData> response_data_; bool per_navigation_user_agent_override_ = false; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NAVIGATION_ENTRY_DATA_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_entry_data.h
C++
unknown
1,734
// 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/browser/navigation_error_navigation_throttle.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "net/base/net_errors.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "weblayer/browser/navigation_controller_impl.h" #include "weblayer/browser/tab_impl.h" #include "weblayer/common/error_page_helper.mojom.h" #include "weblayer/public/error_page.h" #include "weblayer/public/error_page_delegate.h" using content::NavigationThrottle; namespace weblayer { NavigationErrorNavigationThrottle::NavigationErrorNavigationThrottle( content::NavigationHandle* handle) : NavigationThrottle(handle) { // As this calls to the delegate, and the delegate only knows about main // frames, this should only be used for main frames. DCHECK(handle->IsInMainFrame()); } NavigationErrorNavigationThrottle::~NavigationErrorNavigationThrottle() = default; NavigationThrottle::ThrottleCheckResult NavigationErrorNavigationThrottle::WillFailRequest() { // The embedder is not allowed to replace ssl error pages. if (navigation_handle()->GetNetErrorCode() == net::Error::OK || net::IsCertificateError(navigation_handle()->GetNetErrorCode())) { return NavigationThrottle::PROCEED; } TabImpl* tab = TabImpl::FromWebContents(navigation_handle()->GetWebContents()); // Instances of this class are only created if there is a Tab associated // with the WebContents. DCHECK(tab); if (!tab->error_page_delegate()) return NavigationThrottle::PROCEED; NavigationImpl* navigation = static_cast<NavigationControllerImpl*>(tab->GetNavigationController()) ->GetNavigationImplFromHandle(navigation_handle()); // The navigation this was created for should always outlive this. DCHECK(navigation); auto error_page = tab->error_page_delegate()->GetErrorPageContent(navigation); if (!error_page) return NavigationThrottle::PROCEED; mojo::AssociatedRemote<mojom::ErrorPageHelper> remote_error_page_helper; navigation_handle() ->GetRenderFrameHost() ->GetRemoteAssociatedInterfaces() ->GetInterface(&remote_error_page_helper); remote_error_page_helper->DisableErrorPageHelperForNextError(); return NavigationThrottle::ThrottleCheckResult( NavigationThrottle::BLOCK_REQUEST, navigation_handle()->GetNetErrorCode(), error_page->html); } const char* NavigationErrorNavigationThrottle::GetNameForLogging() { return "NavigationErrorNavigationThrottle"; } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_error_navigation_throttle.cc
C++
unknown
2,754
// 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_BROWSER_NAVIGATION_ERROR_NAVIGATION_THROTTLE_H_ #define WEBLAYER_BROWSER_NAVIGATION_ERROR_NAVIGATION_THROTTLE_H_ #include "content/public/browser/navigation_throttle.h" namespace weblayer { // NavigationThrottle implementation that allows the embedder to inject an // error page for non-ssl errors. class NavigationErrorNavigationThrottle : public content::NavigationThrottle { public: explicit NavigationErrorNavigationThrottle(content::NavigationHandle* handle); NavigationErrorNavigationThrottle(const NavigationErrorNavigationThrottle&) = delete; NavigationErrorNavigationThrottle& operator=( const NavigationErrorNavigationThrottle&) = delete; ~NavigationErrorNavigationThrottle() override; // content::NavigationThrottle: ThrottleCheckResult WillFailRequest() override; const char* GetNameForLogging() override; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NAVIGATION_ERROR_NAVIGATION_THROTTLE_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_error_navigation_throttle.h
C++
unknown
1,108
// 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/test/weblayer_browser_test.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "build/build_config.h" #include "content/public/test/url_loader_interceptor.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "weblayer/browser/tab_impl.h" #include "weblayer/public/error_page.h" #include "weblayer/public/error_page_delegate.h" #include "weblayer/shell/browser/shell.h" #include "weblayer/test/test_navigation_observer.h" #include "weblayer/test/weblayer_browser_test_utils.h" #include "base/run_loop.h" namespace weblayer { namespace { class TestErrorPageDelegate : public ErrorPageDelegate { public: void set_error_page_content(const std::string& value) { content_ = value; } // ErrorPageDelegate: bool OnBackToSafety() override { return false; } std::unique_ptr<ErrorPage> GetErrorPageContent( Navigation* navigation) override { if (!content_.has_value()) return nullptr; auto error_page = std::make_unique<ErrorPage>(); error_page->html = *content_; return error_page; } private: absl::optional<std::string> content_; }; } // namespace using NavigationErrorNavigationThrottleBrowserTest = WebLayerBrowserTest; // Verifies the delegate can inject an error page. IN_PROC_BROWSER_TEST_F(NavigationErrorNavigationThrottleBrowserTest, InjectErrorPage) { GURL url("http://doesntexist.com/foo"); auto interceptor = content::URLLoaderInterceptor::SetupRequestFailForURL( url, net::ERR_NAME_NOT_RESOLVED); TestErrorPageDelegate delegate; delegate.set_error_page_content("<html><head><title>test error</title>"); shell()->tab()->SetErrorPageDelegate(&delegate); NavigateAndWaitForFailure(url, shell()); EXPECT_EQ(u"test error", GetTitle(shell())); } // Verifies the delegate can inject an empty page. IN_PROC_BROWSER_TEST_F(NavigationErrorNavigationThrottleBrowserTest, InjectEmptyErrorPage) { GURL url("http://doesntexist.com/foo"); auto interceptor = content::URLLoaderInterceptor::SetupRequestFailForURL( url, net::ERR_NAME_NOT_RESOLVED); TestErrorPageDelegate delegate; delegate.set_error_page_content(std::string()); shell()->tab()->SetErrorPageDelegate(&delegate); NavigateAndWaitForFailure(url, shell()); base::Value body_text = ExecuteScript(shell()->tab(), "document.body.textContent", false); ASSERT_TRUE(body_text.is_string()); EXPECT_TRUE(body_text.GetString().empty()); } // Verifies a null return value results in a default error page. // Network errors only have non-empty error pages on android. #if BUILDFLAG(IS_ANDROID) IN_PROC_BROWSER_TEST_F(NavigationErrorNavigationThrottleBrowserTest, DefaultErrorPage) { GURL url("http://doesntexist.com/foo"); auto interceptor = content::URLLoaderInterceptor::SetupRequestFailForURL( url, net::ERR_NAME_NOT_RESOLVED); TestErrorPageDelegate delegate; shell()->tab()->SetErrorPageDelegate(&delegate); NavigateAndWaitForFailure(url, shell()); base::Value body_text = ExecuteScript(shell()->tab(), "document.body.textContent", false); ASSERT_TRUE(body_text.is_string()); EXPECT_FALSE(body_text.GetString().empty()); } #endif } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_error_navigation_throttle_browsertest.cc
C++
unknown
3,410
// 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/browser/navigation_impl.h" #include "build/build_config.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/loader/referrer.mojom.h" #include "weblayer/browser/navigation_ui_data_impl.h" #include "weblayer/browser/page_impl.h" #if BUILDFLAG(IS_ANDROID) #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "components/embedder_support/android/util/web_resource_response.h" #include "weblayer/browser/java/jni/NavigationImpl_jni.h" #endif #if BUILDFLAG(IS_ANDROID) using base::android::AttachCurrentThread; using base::android::ScopedJavaLocalRef; #endif namespace weblayer { NavigationImpl::NavigationImpl(content::NavigationHandle* navigation_handle) : navigation_handle_(navigation_handle) { auto* navigation_entry = navigation_handle->GetNavigationEntry(); if (navigation_entry && navigation_entry->GetURL() == navigation_handle->GetURL()) { navigation_entry_unique_id_ = navigation_entry->GetUniqueID(); } } NavigationImpl::~NavigationImpl() { #if BUILDFLAG(IS_ANDROID) if (java_navigation_) { Java_NavigationImpl_onNativeDestroyed(AttachCurrentThread(), java_navigation_); } #endif } #if BUILDFLAG(IS_ANDROID) ScopedJavaLocalRef<jstring> NavigationImpl::GetUri(JNIEnv* env) { return ScopedJavaLocalRef<jstring>( base::android::ConvertUTF8ToJavaString(env, GetURL().spec())); } ScopedJavaLocalRef<jobjectArray> NavigationImpl::GetRedirectChain(JNIEnv* env) { std::vector<std::string> jni_redirects; for (const GURL& redirect : GetRedirectChain()) jni_redirects.push_back(redirect.spec()); return base::android::ToJavaArrayOfStrings(env, jni_redirects); } ScopedJavaLocalRef<jobjectArray> NavigationImpl::GetResponseHeaders( JNIEnv* env) { std::vector<std::string> jni_headers; auto* headers = GetResponseHeaders(); if (headers) { size_t iterator = 0; std::string name; std::string value; while (headers->EnumerateHeaderLines(&iterator, &name, &value)) { jni_headers.push_back(name); jni_headers.push_back(value); } } return base::android::ToJavaArrayOfStrings(env, jni_headers); } jboolean NavigationImpl::GetIsConsentingContent(JNIEnv* env) { if (GetState() != NavigationState::kComplete) { return false; } return is_consenting_content_; } jboolean NavigationImpl::SetRequestHeader( JNIEnv* env, const base::android::JavaParamRef<jstring>& name, const base::android::JavaParamRef<jstring>& value) { if (!safe_to_set_request_headers_) return false; SetRequestHeader(ConvertJavaStringToUTF8(name), ConvertJavaStringToUTF8(value)); return true; } jboolean NavigationImpl::SetUserAgentString( JNIEnv* env, const base::android::JavaParamRef<jstring>& value) { if (!safe_to_set_user_agent_) return false; SetUserAgentString(ConvertJavaStringToUTF8(value)); return true; } jboolean NavigationImpl::DisableNetworkErrorAutoReload(JNIEnv* env) { if (!safe_to_disable_network_error_auto_reload_) return false; DisableNetworkErrorAutoReload(); return true; } jboolean NavigationImpl::DisableIntentProcessing(JNIEnv* env) { if (!safe_to_disable_intent_processing_) return false; disable_intent_processing_ = true; return true; } jboolean NavigationImpl::AreIntentLaunchesAllowedInBackground(JNIEnv* env) { NavigationUIDataImpl* navigation_ui_data = static_cast<NavigationUIDataImpl*>( navigation_handle_->GetNavigationUIData()); if (!navigation_ui_data) return false; return navigation_ui_data->are_intent_launches_allowed_in_background(); } base::android::ScopedJavaLocalRef<jstring> NavigationImpl::GetReferrer( JNIEnv* env) { return ScopedJavaLocalRef<jstring>( base::android::ConvertUTF8ToJavaString(env, GetReferrer().spec())); } jlong NavigationImpl::GetPage(JNIEnv* env) { if (!safe_to_get_page_) return -1; return reinterpret_cast<intptr_t>(GetPage()); } jint NavigationImpl::GetNavigationEntryOffset(JNIEnv* env) { return GetNavigationEntryOffset(); } jboolean NavigationImpl::WasFetchedFromCache(JNIEnv* env) { return WasFetchedFromCache(); } void NavigationImpl::SetResponse( std::unique_ptr<embedder_support::WebResourceResponse> response) { response_ = std::move(response); } std::unique_ptr<embedder_support::WebResourceResponse> NavigationImpl::TakeResponse() { return std::move(response_); } void NavigationImpl::SetJavaNavigation( const base::android::ScopedJavaGlobalRef<jobject>& java_navigation) { // SetJavaNavigation() should only be called once. DCHECK(!java_navigation_); java_navigation_ = java_navigation; } #endif bool NavigationImpl::IsPageInitiated() { return navigation_handle_->IsRendererInitiated(); } bool NavigationImpl::IsReload() { return navigation_handle_->GetReloadType() != content::ReloadType::NONE; } bool NavigationImpl::IsServedFromBackForwardCache() { return navigation_handle_->IsServedFromBackForwardCache(); } Page* NavigationImpl::GetPage() { if (!safe_to_get_page_) return nullptr; return PageImpl::GetForPage( navigation_handle_->GetRenderFrameHost()->GetPage()); } int NavigationImpl::GetNavigationEntryOffset() { return navigation_handle_->GetNavigationEntryOffset(); } bool NavigationImpl::WasFetchedFromCache() { return navigation_handle_->WasResponseCached(); } GURL NavigationImpl::GetURL() { return navigation_handle_->GetURL(); } const std::vector<GURL>& NavigationImpl::GetRedirectChain() { return navigation_handle_->GetRedirectChain(); } NavigationState NavigationImpl::GetState() { if (navigation_handle_->IsErrorPage() || navigation_handle_->IsDownload() || (finished_ && !navigation_handle_->HasCommitted())) return NavigationState::kFailed; if (navigation_handle_->HasCommitted()) return NavigationState::kComplete; if (navigation_handle_->GetResponseHeaders()) return NavigationState::kReceivingBytes; return NavigationState::kWaitingResponse; } int NavigationImpl::GetHttpStatusCode() { auto* response_headers = navigation_handle_->GetResponseHeaders(); return response_headers ? response_headers->response_code() : 0; } const net::HttpResponseHeaders* NavigationImpl::GetResponseHeaders() { return navigation_handle_->GetResponseHeaders(); } std::string NavigationImpl::GetNormalizedHeader(const std::string& name) { std::string header_value; if (GetResponseHeaders()) { GetResponseHeaders()->GetNormalizedHeader(name, &header_value); } return header_value; } bool NavigationImpl::IsSameDocument() { return navigation_handle_->IsSameDocument(); } bool NavigationImpl::IsErrorPage() { return navigation_handle_->IsErrorPage(); } bool NavigationImpl::IsDownload() { return navigation_handle_->IsDownload(); } bool NavigationImpl::IsKnownProtocol() { return !navigation_handle_->IsExternalProtocol(); } bool NavigationImpl::WasStopCalled() { return was_stopped_; } Navigation::LoadError NavigationImpl::GetLoadError() { auto error_code = navigation_handle_->GetNetErrorCode(); if (auto* response_headers = navigation_handle_->GetResponseHeaders()) { auto response_code = response_headers->response_code(); if (response_code >= 400 && response_code < 500) return kHttpClientError; if (response_code >= 500 && response_code < 600) return kHttpServerError; } if (error_code == net::OK) return kNoError; // The safe browsing navigation throttle fails navigations with // ERR_BLOCKED_BY_CLIENT when showing safe browsing interstitials. if (error_code == net::ERR_BLOCKED_BY_CLIENT) return kSafeBrowsingError; if (net::IsCertificateError(error_code)) return kSSLError; if (error_code <= -100 && error_code > -200) return kConnectivityError; return kOtherError; } void NavigationImpl::SetRequestHeader(const std::string& name, const std::string& value) { if (base::ToLowerASCII(name) == "referer") { // The referrer needs to be special cased as content maintains it // separately. auto referrer = blink::mojom::Referrer::New(); referrer->url = GURL(value); referrer->policy = network::mojom::ReferrerPolicy::kDefault; navigation_handle_->SetReferrer(std::move(referrer)); } else { // Any headers coming from the client should be exempt from CORS checks. navigation_handle_->SetCorsExemptRequestHeader(name, value); } } void NavigationImpl::SetUserAgentString(const std::string& value) { DCHECK(safe_to_set_user_agent_); // By default renderer initiated navigations inherit the user-agent override // of the current NavigationEntry. But we don't want this per-navigation UA to // be inherited. navigation_handle_->GetWebContents() ->SetRendererInitiatedUserAgentOverrideOption( content::NavigationController::UA_OVERRIDE_FALSE); navigation_handle_->GetWebContents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(value), /* override_in_new_tabs */ false); navigation_handle_->SetIsOverridingUserAgent(!value.empty()); set_user_agent_string_called_ = true; } void NavigationImpl::DisableNetworkErrorAutoReload() { DCHECK(safe_to_disable_network_error_auto_reload_); disable_network_error_auto_reload_ = true; } bool NavigationImpl::IsFormSubmission() { return navigation_handle_->IsFormSubmission(); } GURL NavigationImpl::GetReferrer() { return navigation_handle_->GetReferrer().url; } #if BUILDFLAG(IS_ANDROID) static jboolean JNI_NavigationImpl_IsValidRequestHeaderName( JNIEnv* env, const base::android::JavaParamRef<jstring>& name) { return net::HttpUtil::IsValidHeaderName(ConvertJavaStringToUTF8(name)); } static jboolean JNI_NavigationImpl_IsValidRequestHeaderValue( JNIEnv* env, const base::android::JavaParamRef<jstring>& value) { return net::HttpUtil::IsValidHeaderValue(ConvertJavaStringToUTF8(value)); } #endif } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_impl.cc
C++
unknown
10,469
// 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_BROWSER_NAVIGATION_IMPL_H_ #define WEBLAYER_BROWSER_NAVIGATION_IMPL_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "build/build_config.h" #include "weblayer/public/navigation.h" #if BUILDFLAG(IS_ANDROID) #include "base/android/scoped_java_ref.h" #endif namespace content { class NavigationHandle; } namespace embedder_support { class WebResourceResponse; } namespace weblayer { class NavigationImpl : public Navigation { public: explicit NavigationImpl(content::NavigationHandle* navigation_handle); NavigationImpl(const NavigationImpl&) = delete; NavigationImpl& operator=(const NavigationImpl&) = delete; ~NavigationImpl() override; int navigation_entry_unique_id() const { return navigation_entry_unique_id_; } void set_should_stop_when_throttle_created() { should_stop_when_throttle_created_ = true; } bool should_stop_when_throttle_created() const { return should_stop_when_throttle_created_; } void set_should_block_when_throttle_created() { should_block_when_throttle_created_ = true; } bool should_block_when_throttle_created() const { return should_block_when_throttle_created_; } void set_safe_to_set_request_headers(bool value) { safe_to_set_request_headers_ = value; } void set_safe_to_set_user_agent(bool value) { safe_to_set_user_agent_ = value; } void set_safe_to_disable_network_error_auto_reload(bool value) { safe_to_disable_network_error_auto_reload_ = value; } void set_safe_to_disable_intent_processing(bool value) { safe_to_disable_intent_processing_ = value; } void set_safe_to_get_page() { safe_to_get_page_ = true; } void set_was_stopped() { was_stopped_ = true; } bool set_user_agent_string_called() { return set_user_agent_string_called_; } bool disable_network_error_auto_reload() { return disable_network_error_auto_reload_; } bool disable_intent_processing() { return disable_intent_processing_; } void set_finished() { finished_ = true; } void set_consenting_content(bool value) { is_consenting_content_ = value; } #if BUILDFLAG(IS_ANDROID) int GetState(JNIEnv* env) { return static_cast<int>(GetState()); } base::android::ScopedJavaLocalRef<jstring> GetUri(JNIEnv* env); base::android::ScopedJavaLocalRef<jobjectArray> GetRedirectChain(JNIEnv* env); int GetHttpStatusCode(JNIEnv* env) { return GetHttpStatusCode(); } base::android::ScopedJavaLocalRef<jobjectArray> GetResponseHeaders( JNIEnv* env); jboolean GetIsConsentingContent(JNIEnv* env); bool IsSameDocument(JNIEnv* env) { return IsSameDocument(); } bool IsErrorPage(JNIEnv* env) { return IsErrorPage(); } bool IsDownload(JNIEnv* env) { return IsDownload(); } bool IsKnownProtocol(JNIEnv* env) { return IsKnownProtocol(); } bool WasStopCalled(JNIEnv* env) { return WasStopCalled(); } int GetLoadError(JNIEnv* env) { return static_cast<int>(GetLoadError()); } jboolean SetRequestHeader(JNIEnv* env, const base::android::JavaParamRef<jstring>& name, const base::android::JavaParamRef<jstring>& value); jboolean SetUserAgentString( JNIEnv* env, const base::android::JavaParamRef<jstring>& value); jboolean IsPageInitiated(JNIEnv* env) { return IsPageInitiated(); } jboolean IsReload(JNIEnv* env) { return IsReload(); } jboolean IsServedFromBackForwardCache(JNIEnv* env) { return IsServedFromBackForwardCache(); } jboolean DisableNetworkErrorAutoReload(JNIEnv* env); jboolean DisableIntentProcessing(JNIEnv* env); jboolean AreIntentLaunchesAllowedInBackground(JNIEnv* env); jboolean IsFormSubmission(JNIEnv* env) { return IsFormSubmission(); } base::android::ScopedJavaLocalRef<jstring> GetReferrer(JNIEnv* env); jlong GetPage(JNIEnv* env); int GetNavigationEntryOffset(JNIEnv* env); jboolean WasFetchedFromCache(JNIEnv* env); void SetResponse( std::unique_ptr<embedder_support::WebResourceResponse> response); std::unique_ptr<embedder_support::WebResourceResponse> TakeResponse(); void SetJavaNavigation( const base::android::ScopedJavaGlobalRef<jobject>& java_navigation); base::android::ScopedJavaGlobalRef<jobject> java_navigation() { return java_navigation_; } #endif std::string GetNormalizedHeader(const std::string& name); // Navigation implementation: GURL GetURL() override; const std::vector<GURL>& GetRedirectChain() override; NavigationState GetState() override; int GetHttpStatusCode() override; const net::HttpResponseHeaders* GetResponseHeaders() override; bool IsSameDocument() override; bool IsErrorPage() override; bool IsDownload() override; bool IsKnownProtocol() override; bool WasStopCalled() override; LoadError GetLoadError() override; void SetRequestHeader(const std::string& name, const std::string& value) override; void SetUserAgentString(const std::string& value) override; void DisableNetworkErrorAutoReload() override; bool IsPageInitiated() override; bool IsReload() override; bool IsServedFromBackForwardCache() override; bool IsFormSubmission() override; GURL GetReferrer() override; Page* GetPage() override; int GetNavigationEntryOffset() override; bool WasFetchedFromCache() override; private: raw_ptr<content::NavigationHandle> navigation_handle_; // The NavigationEntry's unique ID for this navigation, or -1 if there isn't // one. int navigation_entry_unique_id_ = -1; // Used to delay calling Stop() until safe. See // NavigationControllerImpl::NavigationThrottleImpl for details. bool should_stop_when_throttle_created_ = false; // Used to prevent URLs from loading. Only set when starting navigation. bool should_block_when_throttle_created_ = false; // Whether SetRequestHeader() is allowed at this time. bool safe_to_set_request_headers_ = false; // Whether SetUserAgentString() is allowed at this time. bool safe_to_set_user_agent_ = false; // Whether NavigationController::Stop() was called for this navigation. bool was_stopped_ = false; // Whether SetUserAgentString was called. bool set_user_agent_string_called_ = false; // Whether DisableNetworkErrorAutoReload is allowed at this time. bool safe_to_disable_network_error_auto_reload_ = false; // Whether DisableIntentProcessing is allowed at this time. bool safe_to_disable_intent_processing_ = false; // Whether GetPage is allowed at this time. bool safe_to_get_page_ = false; bool disable_network_error_auto_reload_ = false; bool disable_intent_processing_ = false; // Whether this navigation has finished. bool finished_ = false; bool is_consenting_content_ = false; #if BUILDFLAG(IS_ANDROID) base::android::ScopedJavaGlobalRef<jobject> java_navigation_; std::unique_ptr<embedder_support::WebResourceResponse> response_; #endif }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NAVIGATION_IMPL_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_impl.h
C++
unknown
7,098
// 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/browser/navigation_ui_data_impl.h" #include "build/build_config.h" namespace weblayer { #if BUILDFLAG(IS_ANDROID) NavigationUIDataImpl::ResponseHolder::ResponseHolder( std::unique_ptr<embedder_support::WebResourceResponse> response) : response_(std::move(response)) {} NavigationUIDataImpl::ResponseHolder::~ResponseHolder() = default; std::unique_ptr<embedder_support::WebResourceResponse> NavigationUIDataImpl::ResponseHolder::TakeResponse() { return std::move(response_); } #endif // BUILDFLAG(IS_ANDROID) NavigationUIDataImpl::NavigationUIDataImpl() = default; NavigationUIDataImpl::~NavigationUIDataImpl() = default; std::unique_ptr<content::NavigationUIData> NavigationUIDataImpl::Clone() { auto rv = std::make_unique<NavigationUIDataImpl>(); rv->disable_network_error_auto_reload_ = disable_network_error_auto_reload_; #if BUILDFLAG(IS_ANDROID) rv->intent_launches_allowed_in_background_ = intent_launches_allowed_in_background_; rv->response_holder_ = response_holder_; #endif // BUILDFLAG(IS_ANDROID) return rv; } #if BUILDFLAG(IS_ANDROID) void NavigationUIDataImpl::SetResponse( std::unique_ptr<embedder_support::WebResourceResponse> response) { DCHECK(!response_holder_); response_holder_ = base::MakeRefCounted<ResponseHolder>(std::move(response)); } std::unique_ptr<embedder_support::WebResourceResponse> NavigationUIDataImpl::TakeResponse() { if (!response_holder_) return nullptr; return response_holder_->TakeResponse(); } #endif // BUILDFLAG(IS_ANDROID) } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_ui_data_impl.cc
C++
unknown
1,716
// 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_BROWSER_NAVIGATION_UI_DATA_IMPL_H_ #define WEBLAYER_BROWSER_NAVIGATION_UI_DATA_IMPL_H_ #include "base/memory/ref_counted.h" #include "build/build_config.h" #include "content/public/browser/navigation_ui_data.h" #if BUILDFLAG(IS_ANDROID) #include "components/embedder_support/android/util/web_resource_response.h" #endif namespace weblayer { // Data that we pass to content::NavigationController::LoadURLWithParams // and can access from content::NavigationHandle later. class NavigationUIDataImpl : public content::NavigationUIData { public: NavigationUIDataImpl(); NavigationUIDataImpl(const NavigationUIDataImpl&) = delete; NavigationUIDataImpl& operator=(const NavigationUIDataImpl&) = delete; ~NavigationUIDataImpl() override; // content::NavigationUIData implementation: std::unique_ptr<content::NavigationUIData> Clone() override; void set_disable_network_error_auto_reload(bool value) { disable_network_error_auto_reload_ = value; } bool disable_network_error_auto_reload() const { return disable_network_error_auto_reload_; } #if BUILDFLAG(IS_ANDROID) void set_allow_intent_launches_in_background(bool value) { intent_launches_allowed_in_background_ = value; } bool are_intent_launches_allowed_in_background() const { return intent_launches_allowed_in_background_; } void SetResponse( std::unique_ptr<embedder_support::WebResourceResponse> response); std::unique_ptr<embedder_support::WebResourceResponse> TakeResponse(); #endif private: bool disable_network_error_auto_reload_ = false; #if BUILDFLAG(IS_ANDROID) bool intent_launches_allowed_in_background_ = false; // Even though NavigationUIData is copyable, the WebResourceResponse would // only be used once since there are no network-retries applicable in this // case. class ResponseHolder : public base::RefCounted<ResponseHolder> { public: explicit ResponseHolder( std::unique_ptr<embedder_support::WebResourceResponse> response_); std::unique_ptr<embedder_support::WebResourceResponse> TakeResponse(); private: friend class base::RefCounted<ResponseHolder>; virtual ~ResponseHolder(); std::unique_ptr<embedder_support::WebResourceResponse> response_; }; scoped_refptr<ResponseHolder> response_holder_; #endif }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NAVIGATION_UI_DATA_IMPL_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/navigation_ui_data_impl.h
C++
unknown
2,542
// 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/browser/new_tab_callback_proxy.h" #include "base/trace_event/trace_event.h" #include "url/gurl.h" #include "weblayer/browser/java/jni/NewTabCallbackProxy_jni.h" #include "weblayer/browser/tab_impl.h" using base::android::AttachCurrentThread; using base::android::ScopedJavaLocalRef; namespace weblayer { NewTabCallbackProxy::NewTabCallbackProxy(JNIEnv* env, jobject obj, TabImpl* tab) : tab_(tab), java_impl_(env, obj) { DCHECK(!tab_->has_new_tab_delegate()); tab_->SetNewTabDelegate(this); } NewTabCallbackProxy::~NewTabCallbackProxy() { tab_->SetNewTabDelegate(nullptr); } void NewTabCallbackProxy::OnNewTab(Tab* tab, NewTabType type) { JNIEnv* env = AttachCurrentThread(); TRACE_EVENT0("weblayer", "Java_NewTabCallbackProxy_onNewTab"); Java_NewTabCallbackProxy_onNewTab(env, java_impl_, static_cast<TabImpl*>(tab)->GetJavaTab(), static_cast<int>(type)); } static jlong JNI_NewTabCallbackProxy_CreateNewTabCallbackProxy( JNIEnv* env, const base::android::JavaParamRef<jobject>& proxy, jlong tab) { return reinterpret_cast<jlong>( new NewTabCallbackProxy(env, proxy, reinterpret_cast<TabImpl*>(tab))); } static void JNI_NewTabCallbackProxy_DeleteNewTabCallbackProxy(JNIEnv* env, jlong proxy) { delete reinterpret_cast<NewTabCallbackProxy*>(proxy); } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/new_tab_callback_proxy.cc
C++
unknown
1,620
// 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_BROWSER_NEW_TAB_CALLBACK_PROXY_H_ #define WEBLAYER_BROWSER_NEW_TAB_CALLBACK_PROXY_H_ #include <jni.h> #include "base/android/scoped_java_ref.h" #include "base/memory/raw_ptr.h" #include "weblayer/public/new_tab_delegate.h" namespace weblayer { class TabImpl; // NewTabCallbackProxy forwards all NewTabDelegate functions to the Java // side. There is one NewTabCallbackProxy per Tab. class NewTabCallbackProxy : public NewTabDelegate { public: NewTabCallbackProxy(JNIEnv* env, jobject obj, TabImpl* tab); NewTabCallbackProxy(const NewTabCallbackProxy&) = delete; NewTabCallbackProxy& operator=(const NewTabCallbackProxy&) = delete; ~NewTabCallbackProxy() override; // NewTabDelegate: void OnNewTab(Tab* tab, NewTabType type) override; private: raw_ptr<TabImpl> tab_; base::android::ScopedJavaGlobalRef<jobject> java_impl_; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NEW_TAB_CALLBACK_PROXY_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/new_tab_callback_proxy.h
C++
unknown
1,094
// 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/public/new_tab_delegate.h" #include "base/strings/stringprintf.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "weblayer/browser/tab_impl.h" #include "weblayer/public/browser.h" #include "weblayer/public/new_tab_delegate.h" #include "weblayer/public/tab.h" #include "weblayer/shell/browser/shell.h" #include "weblayer/test/weblayer_browser_test.h" #include "weblayer/test/weblayer_browser_test_utils.h" namespace weblayer { namespace { class DestroyingNewTabDelegate : public NewTabDelegate { public: void WaitForOnNewTab() { run_loop_.Run(); } bool was_on_new_tab_called() const { return was_on_new_tab_called_; } // NewTabDelegate: void OnNewTab(Tab* new_tab, NewTabType type) override { was_on_new_tab_called_ = true; new_tab->GetBrowser()->DestroyTab(new_tab); run_loop_.Quit(); } private: base::RunLoop run_loop_; bool was_on_new_tab_called_ = false; }; } // namespace using NewTabDelegateTest = WebLayerBrowserTest; IN_PROC_BROWSER_TEST_F(NewTabDelegateTest, DestroyTabOnNewTab) { ASSERT_TRUE(embedded_test_server()->Start()); NavigateAndWaitForCompletion(embedded_test_server()->GetURL("/echo"), shell()->tab()); DestroyingNewTabDelegate new_tab_delegate; shell()->tab()->SetNewTabDelegate(&new_tab_delegate); GURL popup_url = embedded_test_server()->GetURL("/echo?popup"); ExecuteScriptWithUserGesture( shell()->tab(), base::StringPrintf("window.open('%s')", popup_url.spec().c_str())); new_tab_delegate.WaitForOnNewTab(); EXPECT_TRUE(new_tab_delegate.was_on_new_tab_called()); EXPECT_EQ(1u, shell()->tab()->GetBrowser()->GetTabs().size()); } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/new_tab_delegate_browsertest.cc
C++
unknown
1,868
// 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 <memory> #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/threading/platform_thread.h" #include "build/build_config.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h" #include "components/no_state_prefetch/browser/prerender_histograms.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/url_loader_monitor.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "services/network/public/cpp/resource_request.h" #include "weblayer/browser/no_state_prefetch/no_state_prefetch_link_manager_factory.h" #include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h" #include "weblayer/browser/profile_impl.h" #include "weblayer/browser/tab_impl.h" #include "weblayer/public/prerender_controller.h" #include "weblayer/shell/browser/shell.h" #include "weblayer/test/weblayer_browser_test.h" #include "weblayer/test/weblayer_browser_test_utils.h" #if BUILDFLAG(IS_ANDROID) #include "components/ukm/test_ukm_recorder.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "weblayer/browser/android/metrics/metrics_test_helper.h" #endif namespace weblayer { class NoStatePrefetchBrowserTest : public WebLayerBrowserTest { public: #if BUILDFLAG(IS_ANDROID) void SetUp() override { InstallTestGmsBridge(ConsentType::kConsent); WebLayerBrowserTest::SetUp(); } void TearDown() override { RemoveTestGmsBridge(); WebLayerBrowserTest::TearDown(); } #endif void SetUpOnMainThread() override { prerendered_page_fetched_ = std::make_unique<base::RunLoop>(); script_resource_fetched_ = std::make_unique<base::RunLoop>(); https_server_ = std::make_unique<net::EmbeddedTestServer>( net::EmbeddedTestServer::TYPE_HTTPS); https_server_->RegisterRequestHandler(base::BindRepeating( &NoStatePrefetchBrowserTest::HandleRequest, base::Unretained(this))); https_server_->AddDefaultHandlers( base::FilePath(FILE_PATH_LITERAL("weblayer/test/data"))); ASSERT_TRUE(https_server_->Start()); #if BUILDFLAG(IS_ANDROID) ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>(); #endif } // Helper methods. std::unique_ptr<net::test_server::HttpResponse> HandleRequest( const net::test_server::HttpRequest& request) { if (request.GetURL().path().find("prerendered_page") != std::string::npos) { prerendered_page_fetched_->Quit(); prerendered_page_was_fetched_ = true; } if (request.GetURL().path().find("prefetch.js") != std::string::npos) { script_fetched_ = true; auto iter = request.headers.find("Purpose"); purpose_header_value_ = iter->second; script_resource_fetched_->Quit(); } if (request.GetURL().path().find("prefetch_meta.js") != std::string::npos) { script_executed_ = true; } // The default handlers will take care of this request. return nullptr; } void NavigateToPageAndWaitForTitleChange(const GURL& navigate_to, std::u16string expected_title) { content::TitleWatcher title_watcher( static_cast<TabImpl*>(shell()->tab())->web_contents(), expected_title); NavigateAndWaitForCompletion(navigate_to, shell()); ASSERT_TRUE(expected_title == title_watcher.WaitAndGetTitle()); } protected: content::BrowserContext* GetBrowserContext() { Tab* tab = shell()->tab(); TabImpl* tab_impl = static_cast<TabImpl*>(tab); return tab_impl->web_contents()->GetBrowserContext(); } std::unique_ptr<base::RunLoop> prerendered_page_fetched_; std::unique_ptr<base::RunLoop> script_resource_fetched_; bool prerendered_page_was_fetched_ = false; bool script_fetched_ = false; bool script_executed_ = false; std::string purpose_header_value_; std::unique_ptr<net::EmbeddedTestServer> https_server_; #if BUILDFLAG(IS_ANDROID) std::unique_ptr<ukm::TestAutoSetUkmRecorder> ukm_recorder_; #endif }; IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, CreateNoStatePrefetchManager) { auto* no_state_prefetch_manager = NoStatePrefetchManagerFactory::GetForBrowserContext(GetBrowserContext()); EXPECT_TRUE(no_state_prefetch_manager); } IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, CreateNoStatePrefetchLinkManager) { auto* no_state_prefetch_link_manager = NoStatePrefetchLinkManagerFactory::GetForBrowserContext( GetBrowserContext()); EXPECT_TRUE(no_state_prefetch_link_manager); } // Test that adding a link-rel prerender tag causes a fetch. IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, LinkRelPrerenderPageFetched) { NavigateAndWaitForCompletion(GURL(https_server_->GetURL("/parent_page.html")), shell()); prerendered_page_fetched_->Run(); } // Test that only render blocking resources are loaded during NoStatePrefetch. // TODO(https://crbug.com/1144282): Fix failures on Asan. #if defined(ADDRESS_SANITIZER) #define MAYBE_NSPLoadsRenderBlockingResource \ DISABLED_NSPLoadsRenderBlockingResource #else #define MAYBE_NSPLoadsRenderBlockingResource NSPLoadsRenderBlockingResource #endif IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, MAYBE_NSPLoadsRenderBlockingResource) { NavigateAndWaitForCompletion(GURL(https_server_->GetURL("/parent_page.html")), shell()); script_resource_fetched_->Run(); EXPECT_EQ("prefetch", purpose_header_value_); EXPECT_FALSE(script_executed_); } // Test that navigating to a no-state-prefetched page executes JS and reuses // prerendered resources. // TODO(https://crbug.com/1144282): Fix failures on Asan. #if defined(ADDRESS_SANITIZER) #define MAYBE_NavigateToPrerenderedPage DISABLED_NavigateToPrerenderedPage #else #define MAYBE_NavigateToPrerenderedPage NavigateToPrerenderedPage #endif IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, MAYBE_NavigateToPrerenderedPage) { NavigateAndWaitForCompletion(GURL(https_server_->GetURL("/parent_page.html")), shell()); script_resource_fetched_->Run(); // Navigate to the prerendered page and wait for its title to change. script_fetched_ = false; NavigateToPageAndWaitForTitleChange( GURL(https_server_->GetURL("/prerendered_page.html")), u"Prefetch Page"); EXPECT_FALSE(script_fetched_); EXPECT_TRUE(script_executed_); } #if BUILDFLAG(IS_ANDROID) // Test that no-state-prefetch results in UKM getting recorded. // TODO(https://crbug.com/1292252): Flaky failures. IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, DISABLED_UKMRecorded) { GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, true); NavigateAndWaitForCompletion(GURL(https_server_->GetURL("/parent_page.html")), shell()); script_resource_fetched_->Run(); NavigateToPageAndWaitForTitleChange( GURL(https_server_->GetURL("/prerendered_page.html")), u"Prefetch Page"); auto entries = ukm_recorder_->GetEntriesByName( ukm::builders::NoStatePrefetch::kEntryName); ASSERT_EQ(entries.size(), 1u); const auto* entry = entries[0]; // FinalStatus must be set to FINAL_STATUS_NOSTATE_PREFETCH_FINISHED. ukm_recorder_->ExpectEntryMetric( entry, ukm::builders::NoStatePrefetch::kPrefetchedRecently_FinalStatusName, 56); // Origin must be set to ORIGIN_LINK_REL_PRERENDER_SAMEDOMAIN. ukm_recorder_->ExpectEntryMetric( entry, ukm::builders::NoStatePrefetch::kPrefetchedRecently_OriginName, 7); } #endif // link-rel="prerender" happens even when NoStatePrefetch has been disabled. IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, LinkRelPrerenderWithNSPDisabled) { GetProfile()->SetBooleanSetting(SettingType::NETWORK_PREDICTION_ENABLED, false); NavigateAndWaitForCompletion(GURL(https_server_->GetURL("/parent_page.html")), shell()); prerendered_page_fetched_->Run(); } // link-rel="next" URLs should not be prefetched. IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, LinkRelNextWithNSPDisabled) { NavigateAndWaitForCompletion( GURL(https_server_->GetURL("/link_rel_next_parent.html")), shell()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(prerendered_page_was_fetched_); } // Non-web initiated prerender succeeds and subsequent navigations reuse // previously downloaded resources. // TODO(https://crbug.com/1144282): Fix failures on Asan. #if defined(ADDRESS_SANITIZER) #define MAYBE_ExternalPrerender DISABLED_ExternalPrerender #else #define MAYBE_ExternalPrerender ExternalPrerender #endif IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, MAYBE_ExternalPrerender) { GetProfile()->GetPrerenderController()->Prerender( GURL(https_server_->GetURL("/prerendered_page.html"))); script_resource_fetched_->Run(); // Navigate to the prerendered page and wait for its title to change. script_fetched_ = false; NavigateToPageAndWaitForTitleChange( GURL(https_server_->GetURL("/prerendered_page.html")), u"Prefetch Page"); EXPECT_FALSE(script_fetched_); } // Non-web initiated prerender fails when the user has opted out. IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, ExternalPrerenderWhenOptedOut) { GetProfile()->SetBooleanSetting(SettingType::NETWORK_PREDICTION_ENABLED, false); GetProfile()->GetPrerenderController()->Prerender( GURL(https_server_->GetURL("/prerendered_page.html"))); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(prerendered_page_was_fetched_); } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_browsertest.cc
C++
unknown
10,022
// 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/browser/no_state_prefetch/no_state_prefetch_link_manager_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/no_state_prefetch/browser/no_state_prefetch_link_manager.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h" #include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h" namespace weblayer { // static prerender::NoStatePrefetchLinkManager* NoStatePrefetchLinkManagerFactory::GetForBrowserContext( content::BrowserContext* browser_context) { return static_cast<prerender::NoStatePrefetchLinkManager*>( GetInstance()->GetServiceForBrowserContext(browser_context, true)); } // static NoStatePrefetchLinkManagerFactory* NoStatePrefetchLinkManagerFactory::GetInstance() { return base::Singleton<NoStatePrefetchLinkManagerFactory>::get(); } NoStatePrefetchLinkManagerFactory::NoStatePrefetchLinkManagerFactory() : BrowserContextKeyedServiceFactory( "NoStatePrefetchLinkManager", BrowserContextDependencyManager::GetInstance()) { DependsOn(weblayer::NoStatePrefetchManagerFactory::GetInstance()); } KeyedService* NoStatePrefetchLinkManagerFactory::BuildServiceInstanceFor( content::BrowserContext* browser_context) const { DCHECK(browser_context); prerender::NoStatePrefetchManager* no_state_prefetch_manager = NoStatePrefetchManagerFactory::GetForBrowserContext(browser_context); if (!no_state_prefetch_manager) return nullptr; return new prerender::NoStatePrefetchLinkManager(no_state_prefetch_manager); } content::BrowserContext* NoStatePrefetchLinkManagerFactory::GetBrowserContextToUse( content::BrowserContext* browser_context) const { return browser_context; } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_link_manager_factory.cc
C++
unknown
1,945
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_LINK_MANAGER_FACTORY_H_ #define WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_LINK_MANAGER_FACTORY_H_ #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "components/no_state_prefetch/browser/no_state_prefetch_link_manager.h" namespace content { class BrowserContext; } namespace weblayer { class NoStatePrefetchLinkManagerFactory : public BrowserContextKeyedServiceFactory { public: // Returns the prerender::NoStatePrefetchLinkManager for |context|. static prerender::NoStatePrefetchLinkManager* GetForBrowserContext( content::BrowserContext* context); static NoStatePrefetchLinkManagerFactory* GetInstance(); private: friend struct base::DefaultSingletonTraits<NoStatePrefetchLinkManagerFactory>; NoStatePrefetchLinkManagerFactory(); ~NoStatePrefetchLinkManagerFactory() override = default; // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* browser) const override; content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_LINK_MANAGER_FACTORY_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_link_manager_factory.h
C++
unknown
1,476
// 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/browser/no_state_prefetch/no_state_prefetch_manager_delegate_impl.h" #include "components/no_state_prefetch/browser/no_state_prefetch_contents_delegate.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "weblayer/browser/browser_context_impl.h" #include "weblayer/browser/cookie_settings_factory.h" #include "weblayer/browser/profile_impl.h" #include "weblayer/public/profile.h" namespace weblayer { NoStatePrefetchManagerDelegateImpl::NoStatePrefetchManagerDelegateImpl( content::BrowserContext* browser_context) : browser_context_(browser_context) {} scoped_refptr<content_settings::CookieSettings> NoStatePrefetchManagerDelegateImpl::GetCookieSettings() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); return CookieSettingsFactory::GetForBrowserContext(browser_context_); } std::unique_ptr<prerender::NoStatePrefetchContentsDelegate> NoStatePrefetchManagerDelegateImpl::GetNoStatePrefetchContentsDelegate() { return std::make_unique<prerender::NoStatePrefetchContentsDelegate>(); } bool NoStatePrefetchManagerDelegateImpl:: IsNetworkPredictionPreferenceEnabled() { auto* profile = ProfileImpl::FromBrowserContext(browser_context_); DCHECK(profile); return profile->GetBooleanSetting(SettingType::NETWORK_PREDICTION_ENABLED); } std::string NoStatePrefetchManagerDelegateImpl::GetReasonForDisablingPrediction() { return IsNetworkPredictionPreferenceEnabled() ? "" : "Disabled by user setting"; } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_manager_delegate_impl.cc
C++
unknown
1,736
// 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_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_MANAGER_DELEGATE_IMPL_H_ #define WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_MANAGER_DELEGATE_IMPL_H_ #include "base/memory/raw_ptr.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager_delegate.h" namespace content { class BrowserContext; } namespace weblayer { class NoStatePrefetchManagerDelegateImpl : public prerender::NoStatePrefetchManagerDelegate { public: explicit NoStatePrefetchManagerDelegateImpl( content::BrowserContext* browser_context); ~NoStatePrefetchManagerDelegateImpl() override = default; // NoStatePrefetchManagerDelegate overrides. scoped_refptr<content_settings::CookieSettings> GetCookieSettings() override; std::unique_ptr<prerender::NoStatePrefetchContentsDelegate> GetNoStatePrefetchContentsDelegate() override; bool IsNetworkPredictionPreferenceEnabled() override; std::string GetReasonForDisablingPrediction() override; private: raw_ptr<content::BrowserContext> browser_context_; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_MANAGER_DELEGATE_IMPL_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_manager_delegate_impl.h
C++
unknown
1,372
// 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/browser/no_state_prefetch/no_state_prefetch_manager_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h" #include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_delegate_impl.h" namespace weblayer { // static prerender::NoStatePrefetchManager* NoStatePrefetchManagerFactory::GetForBrowserContext( content::BrowserContext* context) { return static_cast<prerender::NoStatePrefetchManager*>( GetInstance()->GetServiceForBrowserContext(context, true)); } // static NoStatePrefetchManagerFactory* NoStatePrefetchManagerFactory::GetInstance() { return base::Singleton<NoStatePrefetchManagerFactory>::get(); } NoStatePrefetchManagerFactory::NoStatePrefetchManagerFactory() : BrowserContextKeyedServiceFactory( "NoStatePrefetchManager", BrowserContextDependencyManager::GetInstance()) {} KeyedService* NoStatePrefetchManagerFactory::BuildServiceInstanceFor( content::BrowserContext* browser_context) const { return new prerender::NoStatePrefetchManager( browser_context, std::make_unique<NoStatePrefetchManagerDelegateImpl>(browser_context)); } content::BrowserContext* NoStatePrefetchManagerFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return context; } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.cc
C++
unknown
1,565
// 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_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_MANAGER_FACTORY_H_ #define WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_MANAGER_FACTORY_H_ #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace content { class BrowserContext; } namespace prerender { class NoStatePrefetchManager; } namespace weblayer { // Singleton that owns all NoStatePrefetchManagers and associates them with // BrowserContexts. Listens for the BrowserContext's destruction notification // and cleans up the associated NoStatePrefetchManager. class NoStatePrefetchManagerFactory : public BrowserContextKeyedServiceFactory { public: // Returns the NoStatePrefetchManager for |context|. static prerender::NoStatePrefetchManager* GetForBrowserContext( content::BrowserContext* context); static NoStatePrefetchManagerFactory* GetInstance(); private: friend struct base::DefaultSingletonTraits<NoStatePrefetchManagerFactory>; NoStatePrefetchManagerFactory(); ~NoStatePrefetchManagerFactory() override = default; // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* browser) const override; content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_MANAGER_FACTORY_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h
C++
unknown
1,602
// 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/browser/no_state_prefetch/no_state_prefetch_processor_impl_delegate_impl.h" #include "components/no_state_prefetch/browser/no_state_prefetch_link_manager.h" #include "content/public/browser/browser_context.h" #include "weblayer/browser/no_state_prefetch/no_state_prefetch_link_manager_factory.h" namespace weblayer { prerender::NoStatePrefetchLinkManager* NoStatePrefetchProcessorImplDelegateImpl::GetNoStatePrefetchLinkManager( content::BrowserContext* browser_context) { return NoStatePrefetchLinkManagerFactory::GetForBrowserContext( browser_context); } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_processor_impl_delegate_impl.cc
C++
unknown
761
// 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_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_PROCESSOR_IMPL_DELEGATE_IMPL_H_ #define WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_PROCESSOR_IMPL_DELEGATE_IMPL_H_ #include "components/no_state_prefetch/browser/no_state_prefetch_processor_impl_delegate.h" namespace content { class BrowserContext; } namespace prerender { class NoStatePrefetchLinkManager; } namespace weblayer { class NoStatePrefetchProcessorImplDelegateImpl : public prerender::NoStatePrefetchProcessorImplDelegate { public: NoStatePrefetchProcessorImplDelegateImpl() = default; ~NoStatePrefetchProcessorImplDelegateImpl() override = default; // prerender::NoStatePrefetchProcessorImplDelegate overrides, prerender::NoStatePrefetchLinkManager* GetNoStatePrefetchLinkManager( content::BrowserContext* browser_context) override; }; } // namespace weblayer #endif // WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_PROCESSOR_IMPL_DELEGATE_IMPL_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_processor_impl_delegate_impl.h
C++
unknown
1,112
// 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/browser/no_state_prefetch/no_state_prefetch_utils.h" #include "components/no_state_prefetch/browser/no_state_prefetch_contents.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h" #include "content/public/browser/web_contents.h" #include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h" namespace weblayer { prerender::NoStatePrefetchContents* NoStatePrefetchContentsFromWebContents( content::WebContents* web_contents) { if (!web_contents) return nullptr; prerender::NoStatePrefetchManager* no_state_prefetch_manager = NoStatePrefetchManagerFactory::GetForBrowserContext( web_contents->GetBrowserContext()); if (!no_state_prefetch_manager) return nullptr; return no_state_prefetch_manager->GetNoStatePrefetchContents(web_contents); } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_utils.cc
C++
unknown
1,014
// 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_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_UTILS_H_ #define WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_UTILS_H_ namespace content { class WebContents; } namespace prerender { class NoStatePrefetchContents; } namespace weblayer { prerender::NoStatePrefetchContents* NoStatePrefetchContentsFromWebContents( content::WebContents* web_contents); } // namespace weblayer #endif // WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_UTILS_H_
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/no_state_prefetch_utils.h
C++
unknown
622
// 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/browser/no_state_prefetch/prerender_controller_impl.h" #include "build/build_config.h" #include "components/no_state_prefetch/browser/no_state_prefetch_handle.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h" #include "content/public/browser/browser_context.h" #include "ui/gfx/geometry/rect.h" #include "url/gurl.h" #include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h" #if BUILDFLAG(IS_ANDROID) #include "base/android/jni_string.h" #include "weblayer/browser/java/jni/PrerenderControllerImpl_jni.h" #endif namespace weblayer { PrerenderControllerImpl::PrerenderControllerImpl( content::BrowserContext* browser_context) : browser_context_(browser_context) { DCHECK(browser_context_); } PrerenderControllerImpl::~PrerenderControllerImpl() = default; #if BUILDFLAG(IS_ANDROID) void PrerenderControllerImpl::Prerender( JNIEnv* env, const base::android::JavaParamRef<jstring>& url) { Prerender(GURL(ConvertJavaStringToUTF8(url))); } #endif void PrerenderControllerImpl::Prerender(const GURL& url) { auto* no_state_prefetch_manager = NoStatePrefetchManagerFactory::GetForBrowserContext(browser_context_); DCHECK(no_state_prefetch_manager); // The referrer parameter results in a header being set that lets the server // serving the URL being prefetched see where the request originated. It's an // optional header, it's okay to skip setting it here. SessionStorageNamespace // isn't necessary for NoStatePrefetch, so it's okay to pass in a nullptr. // NoStatePrefetchManager uses default bounds if the one provided is empty. no_state_prefetch_manager->StartPrefetchingFromExternalRequest( url, content::Referrer(), /* session_storage_namespace= */ nullptr, /* bounds= */ gfx::Rect()); } void PrerenderControllerImpl::DestroyAllContents() { auto* no_state_prefetch_manager = NoStatePrefetchManagerFactory::GetForBrowserContext(browser_context_); DCHECK(no_state_prefetch_manager); no_state_prefetch_manager->DestroyAllContents( prerender::FINAL_STATUS_APP_TERMINATING); } } // namespace weblayer
Zhao-PengFei35/chromium_src_4
weblayer/browser/no_state_prefetch/prerender_controller_impl.cc
C++
unknown
2,296