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.
#ifndef WEBLAYER_BROWSER_HOST_CONTENT_SETTINGS_MAP_FACTORY_H_
#define WEBLAYER_BROWSER_HOST_CONTENT_SETTINGS_MAP_FACTORY_H_
#include "base/memory/ref_counted.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/content/refcounted_browser_context_keyed_service_factory.h"
class HostContentSettingsMap;
namespace weblayer {
class HostContentSettingsMapFactory
: public RefcountedBrowserContextKeyedServiceFactory {
public:
HostContentSettingsMapFactory(const HostContentSettingsMapFactory&) = delete;
HostContentSettingsMapFactory& operator=(
const HostContentSettingsMapFactory&) = delete;
static HostContentSettingsMap* GetForBrowserContext(
content::BrowserContext* browser_context);
static HostContentSettingsMapFactory* GetInstance();
private:
friend struct base::DefaultSingletonTraits<HostContentSettingsMapFactory>;
HostContentSettingsMapFactory();
~HostContentSettingsMapFactory() override;
// RefcountedBrowserContextKeyedServiceFactory methods:
scoped_refptr<RefcountedKeyedService> BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_HOST_CONTENT_SETTINGS_MAP_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/host_content_settings_map_factory.h | C++ | unknown | 1,484 |
// 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/http_auth_handler_impl.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "net/base/auth.h"
#include "url/android/gurl_android.h"
#include "weblayer/browser/java/jni/HttpAuthHandlerImpl_jni.h"
#include "weblayer/browser/tab_impl.h"
namespace weblayer {
HttpAuthHandlerImpl::HttpAuthHandlerImpl(
const net::AuthChallengeInfo& auth_info,
content::WebContents* web_contents,
bool first_auth_attempt,
LoginAuthRequiredCallback callback)
: callback_(std::move(callback)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
url_ = auth_info.challenger.GetURL().Resolve(auth_info.path);
auto* tab = TabImpl::FromWebContents(web_contents);
JNIEnv* env = base::android::AttachCurrentThread();
java_impl_ = Java_HttpAuthHandlerImpl_create(
env, reinterpret_cast<intptr_t>(this), tab->GetJavaTab(),
url::GURLAndroid::FromNativeGURL(env, url_));
}
HttpAuthHandlerImpl::~HttpAuthHandlerImpl() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
CloseDialog();
if (java_impl_) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_HttpAuthHandlerImpl_handlerDestroyed(env, java_impl_);
java_impl_ = nullptr;
}
}
void HttpAuthHandlerImpl::CloseDialog() {
if (!java_impl_)
return;
JNIEnv* env = base::android::AttachCurrentThread();
Java_HttpAuthHandlerImpl_closeDialog(env, java_impl_);
}
void HttpAuthHandlerImpl::Proceed(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& username,
const base::android::JavaParamRef<jstring>& password) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (callback_) {
std::move(callback_).Run(net::AuthCredentials(
base::android::ConvertJavaStringToUTF16(env, username),
base::android::ConvertJavaStringToUTF16(env, password)));
}
CloseDialog();
}
void HttpAuthHandlerImpl::Cancel(JNIEnv* env) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (callback_)
std::move(callback_).Run(absl::nullopt);
CloseDialog();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/http_auth_handler_impl.cc | C++ | unknown | 2,318 |
// 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_HTTP_AUTH_HANDLER_IMPL_H_
#define WEBLAYER_BROWSER_HTTP_AUTH_HANDLER_IMPL_H_
#include "base/android/scoped_java_ref.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/login_delegate.h"
#include "url/gurl.h"
namespace weblayer {
// Implements support for http auth.
class HttpAuthHandlerImpl : public content::LoginDelegate {
public:
HttpAuthHandlerImpl(const net::AuthChallengeInfo& auth_info,
content::WebContents* web_contents,
bool first_auth_attempt,
LoginAuthRequiredCallback callback);
~HttpAuthHandlerImpl() override;
void Proceed(JNIEnv* env,
const base::android::JavaParamRef<jstring>& username,
const base::android::JavaParamRef<jstring>& password);
void Cancel(JNIEnv* env);
private:
void CloseDialog();
GURL url_;
LoginAuthRequiredCallback callback_;
base::android::ScopedJavaGlobalRef<jobject> java_impl_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_HTTP_AUTH_HANDLER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/http_auth_handler_impl.h | C++ | unknown | 1,236 |
// 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/i18n_util.h"
#include "base/i18n/rtl.h"
#include "base/no_destructor.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "net/http/http_util.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/locale_utils.h"
#include "ui/base/resource/resource_bundle.h"
#include "weblayer/browser/java/jni/LocaleChangedBroadcastReceiver_jni.h"
#endif
namespace {
base::RepeatingClosureList& GetLocaleChangeClosures() {
static base::NoDestructor<base::RepeatingClosureList> instance;
return *instance;
}
} // namespace
namespace weblayer {
namespace i18n {
std::string GetApplicationLocale() {
// The locale is set in ContentMainDelegateImpl::InitializeResourceBundle().
return base::i18n::GetConfiguredLocale();
}
std::string GetAcceptLangs() {
#if BUILDFLAG(IS_ANDROID)
std::string locale_list = base::android::GetDefaultLocaleListString();
#else
std::string locale_list = GetApplicationLocale();
#endif
return net::HttpUtil::ExpandLanguageList(locale_list);
}
base::CallbackListSubscription RegisterLocaleChangeCallback(
base::RepeatingClosure locale_changed) {
return GetLocaleChangeClosures().Add(locale_changed);
}
#if BUILDFLAG(IS_ANDROID)
static void JNI_LocaleChangedBroadcastReceiver_LocaleChanged(JNIEnv* env) {
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce([]() {
// Passing an empty |pref_locale| means the Android system locale will
// be used (base::android::GetDefaultLocaleString()).
ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources(
{} /*pref_locale*/);
}),
base::BindOnce([]() { GetLocaleChangeClosures().Notify(); }));
// TODO(estade): need to update the ResourceBundle for non-Browser processes
// as well.
}
#endif
} // namespace i18n
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/i18n_util.cc | C++ | unknown | 2,046 |
// 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_I18N_UTIL_H_
#define WEBLAYER_BROWSER_I18N_UTIL_H_
#include <string>
#include "base/callback_list.h"
namespace weblayer {
namespace i18n {
// Returns the currently-in-use ICU locale. This may be called on any thread.
std::string GetApplicationLocale();
// Returns a list of locales suitable for use in the ACCEPT-LANGUAGE header.
// This may be called on any thread.
std::string GetAcceptLangs();
base::CallbackListSubscription RegisterLocaleChangeCallback(
base::RepeatingClosure locale_changed);
} // namespace i18n
} // namespace weblayer
#endif // WEBLAYER_BROWSER_I18N_UTIL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/i18n_util.h | C++ | unknown | 766 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/infobar_container_android.h"
#include "base/android/jni_android.h"
#include "base/check.h"
#include "base/metrics/histogram_functions.h"
#include "components/infobars/android/infobar_android.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar.h"
#include "components/infobars/core/infobar_delegate.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/android/resource_mapper.h"
#include "weblayer/browser/java/jni/InfoBarContainer_jni.h"
using base::android::JavaParamRef;
namespace weblayer {
// InfoBarContainerAndroid ----------------------------------------------------
InfoBarContainerAndroid::InfoBarContainerAndroid(JNIEnv* env, jobject obj)
: infobars::InfoBarContainer(NULL),
weak_java_infobar_container_(env, obj) {}
InfoBarContainerAndroid::~InfoBarContainerAndroid() {
RemoveAllInfoBarsForDestruction();
}
void InfoBarContainerAndroid::SetWebContents(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
const JavaParamRef<jobject>& web_contents) {
infobars::ContentInfoBarManager* infobar_manager =
web_contents
? infobars::ContentInfoBarManager::FromWebContents(
content::WebContents::FromJavaWebContents(web_contents))
: nullptr;
ChangeInfoBarManager(infobar_manager);
}
void InfoBarContainerAndroid::Destroy(JNIEnv* env,
const JavaParamRef<jobject>& obj) {
delete this;
}
// Creates the Java equivalent of |android_bar| and add it to the java
// container.
void InfoBarContainerAndroid::PlatformSpecificAddInfoBar(
infobars::InfoBar* infobar,
size_t position) {
DCHECK(infobar);
infobars::InfoBarAndroid* android_bar =
static_cast<infobars::InfoBarAndroid*>(infobar);
if (android_bar->HasSetJavaInfoBar())
return;
JNIEnv* env = base::android::AttachCurrentThread();
if (Java_InfoBarContainer_hasInfoBars(
env, weak_java_infobar_container_.get(env))) {
base::UmaHistogramSparse("InfoBar.Shown.Hidden",
android_bar->delegate()->GetIdentifier());
infobars::InfoBarDelegate::InfoBarIdentifier identifier =
static_cast<infobars::InfoBarDelegate::InfoBarIdentifier>(
Java_InfoBarContainer_getTopInfoBarIdentifier(
env, weak_java_infobar_container_.get(env)));
if (identifier != infobars::InfoBarDelegate::InfoBarIdentifier::INVALID) {
base::UmaHistogramSparse("InfoBar.Shown.Hiding", identifier);
}
} else {
base::UmaHistogramSparse("InfoBar.Shown.Visible",
android_bar->delegate()->GetIdentifier());
}
base::android::ScopedJavaLocalRef<jobject> java_infobar =
android_bar->CreateRenderInfoBar(
env, base::BindRepeating(&MapToJavaDrawableId));
android_bar->SetJavaInfoBar(java_infobar);
Java_InfoBarContainer_addInfoBar(env, weak_java_infobar_container_.get(env),
java_infobar);
}
void InfoBarContainerAndroid::PlatformSpecificReplaceInfoBar(
infobars::InfoBar* old_infobar,
infobars::InfoBar* new_infobar) {
static_cast<infobars::InfoBarAndroid*>(new_infobar)
->PassJavaInfoBar(static_cast<infobars::InfoBarAndroid*>(old_infobar));
}
void InfoBarContainerAndroid::PlatformSpecificRemoveInfoBar(
infobars::InfoBar* infobar) {
infobars::InfoBarAndroid* android_infobar =
static_cast<infobars::InfoBarAndroid*>(infobar);
android_infobar->CloseJavaInfoBar();
}
// Native JNI methods ---------------------------------------------------------
static jlong JNI_InfoBarContainer_Init(JNIEnv* env,
const JavaParamRef<jobject>& obj) {
InfoBarContainerAndroid* infobar_container =
new InfoBarContainerAndroid(env, obj);
return reinterpret_cast<intptr_t>(infobar_container);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/infobar_container_android.cc | C++ | unknown | 4,077 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_INFOBAR_CONTAINER_ANDROID_H_
#define WEBLAYER_BROWSER_INFOBAR_CONTAINER_ANDROID_H_
#include <stddef.h>
#include "base/android/jni_weak_ref.h"
#include "base/android/scoped_java_ref.h"
#include "base/compiler_specific.h"
#include "components/infobars/core/infobar_container.h"
namespace weblayer {
class InfoBarContainerAndroid : public infobars::InfoBarContainer {
public:
InfoBarContainerAndroid(JNIEnv* env, jobject infobar_container);
InfoBarContainerAndroid(const InfoBarContainerAndroid&) = delete;
InfoBarContainerAndroid& operator=(const InfoBarContainerAndroid&) = delete;
void SetWebContents(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
const base::android::JavaParamRef<jobject>& web_contents);
void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj);
JavaObjectWeakGlobalRef java_container() const {
return weak_java_infobar_container_;
}
private:
~InfoBarContainerAndroid() override;
// InfobarContainer:
void PlatformSpecificAddInfoBar(infobars::InfoBar* infobar,
size_t position) override;
void PlatformSpecificRemoveInfoBar(infobars::InfoBar* infobar) override;
void PlatformSpecificReplaceInfoBar(infobars::InfoBar* old_infobar,
infobars::InfoBar* new_infobar) override;
// We're owned by the java infobar, need to use a weak ref so it can destroy
// us.
JavaObjectWeakGlobalRef weak_java_infobar_container_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_INFOBAR_CONTAINER_ANDROID_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/infobar_container_android.h | C++ | unknown | 1,779 |
// 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/insecure_form_controller_client.h"
#include "components/security_interstitials/content/insecure_form_tab_storage.h"
#include "components/security_interstitials/content/settings_page_helper.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/i18n_util.h"
namespace weblayer {
// static
std::unique_ptr<security_interstitials::MetricsHelper>
InsecureFormControllerClient::GetMetricsHelper(const GURL& url) {
security_interstitials::MetricsHelper::ReportDetails settings;
settings.metric_prefix = "insecure_form";
return std::make_unique<security_interstitials::MetricsHelper>(url, settings,
nullptr);
}
// static
std::unique_ptr<security_interstitials::SettingsPageHelper>
InsecureFormControllerClient::GetSettingsPageHelper() {
// Return nullptr since there is no enhanced protection message in insecure
// form interstitials.
return nullptr;
}
InsecureFormControllerClient::InsecureFormControllerClient(
content::WebContents* web_contents,
const GURL& form_target_url)
: SecurityInterstitialControllerClient(
web_contents,
GetMetricsHelper(form_target_url),
nullptr, /* prefs */
i18n::GetApplicationLocale(),
GURL("about:blank") /* default_safe_page */,
GetSettingsPageHelper()),
web_contents_(web_contents) {}
InsecureFormControllerClient::~InsecureFormControllerClient() = default;
void InsecureFormControllerClient::GoBack() {
SecurityInterstitialControllerClient::GoBackAfterNavigationCommitted();
}
void InsecureFormControllerClient::Proceed() {
// Set the is_proceeding flag on the tab storage so reload doesn't trigger
// another interstitial.
security_interstitials::InsecureFormTabStorage* tab_storage =
security_interstitials::InsecureFormTabStorage::GetOrCreate(
web_contents_);
tab_storage->SetIsProceeding(true);
// We don't check for repost on the proceed reload since the interstitial
// explains this will submit the form.
web_contents_->GetController().Reload(content::ReloadType::NORMAL, false);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/insecure_form_controller_client.cc | C++ | unknown | 2,335 |
// 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_INSECURE_FORM_CONTROLLER_CLIENT_H_
#define WEBLAYER_BROWSER_INSECURE_FORM_CONTROLLER_CLIENT_H_
#include "base/memory/raw_ptr.h"
#include "components/security_interstitials/content/security_interstitial_controller_client.h"
#include "components/security_interstitials/core/metrics_helper.h"
namespace content {
class WebContents;
}
namespace weblayer {
// A stripped-down version of the class by the same name in
// //chrome/browser/ssl, which provides basic functionality for interacting with
// the insecure form interstitial.
class InsecureFormControllerClient
: public security_interstitials::SecurityInterstitialControllerClient {
public:
static std::unique_ptr<security_interstitials::MetricsHelper>
GetMetricsHelper(const GURL& url);
static std::unique_ptr<security_interstitials::SettingsPageHelper>
GetSettingsPageHelper();
InsecureFormControllerClient(content::WebContents* web_contents,
const GURL& form_target_url);
InsecureFormControllerClient(const InsecureFormControllerClient&) = delete;
InsecureFormControllerClient& operator=(const InsecureFormControllerClient&) =
delete;
~InsecureFormControllerClient() override;
// security_interstitials::SecurityInterstitialControllerClient:
void GoBack() override;
void Proceed() override;
private:
raw_ptr<content::WebContents> web_contents_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_INSECURE_FORM_CONTROLLER_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/insecure_form_controller_client.h | C++ | unknown | 1,636 |
include_rules = [
"+components/browser_ui/browser_ui/android",
"+components/browser_ui/http_auth",
"+components/browser_ui/util/android",
"+components/component_updater/android",
"+components/content_capture/android",
"+components/content_settings/android/java",
"+components/crash/android/java",
"+components/content_relationship_verification/android/java",
"+components/external_intents",
"+components/infobars/android",
"+components/location/android/java/src/org/chromium/components/location",
"+components/minidump_uploader",
"+components/page_info/android/java",
"+components/payments/content/android",
"+components/webapk/android/libs",
"+components/webauthn/android",
"+components/image_fetcher",
"+services/device/public/java/src/org/chromium/device/geolocation",
# WebLayerNotificationWrapperBuilder should be used for all notifications.
"-components/browser_ui/notifications/android/java/src/org/chromium/components/browser_ui/notifications/NotificationWrapperCompatBuilder.java",
"-components/browser_ui/notifications/android/java/src/org/chromium/components/browser_ui/notifications/NotificationWrapperStandardBuilder.java",
]
specific_include_rules = {
"WebLayerNotificationWrapperBuilder.java": [
"+components/browser_ui/notifications/android/java/src/org/chromium/components/browser_ui/notifications/NotificationWrapperCompatBuilder.java",
"+components/browser_ui/notifications/android/java/src/org/chromium/components/browser_ui/notifications/NotificationWrapperStandardBuilder.java",
]
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/DEPS | Python | unknown | 1,560 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.RemoteException;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.Nullable;
import org.chromium.base.PackageManagerUtils;
import org.chromium.content_public.browser.ActionModeCallbackHelper;
import org.chromium.content_public.browser.SelectionPopupController;
import org.chromium.content_public.browser.WebContents;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.ActionModeItemType;
import org.chromium.weblayer_private.interfaces.ITabClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* A class that handles selection action mode for WebLayer.
*/
public final class ActionModeCallback extends ActionMode.Callback2 {
private final ActionModeCallbackHelper mHelper;
// Can be null during init.
private @Nullable ITabClient mTabClient;
// Bitfield of @ActionModeItemType values.
private int mActionModeOverride;
// Convert from content ActionModeCallbackHelper.MENU_ITEM_* values to
// @ActionModeItemType values.
private static int contentToWebLayerType(int contentType) {
switch (contentType) {
case ActionModeCallbackHelper.MENU_ITEM_SHARE:
return ActionModeItemType.SHARE;
case ActionModeCallbackHelper.MENU_ITEM_WEB_SEARCH:
return ActionModeItemType.WEB_SEARCH;
case ActionModeCallbackHelper.MENU_ITEM_PROCESS_TEXT:
case 0:
return 0;
default:
assert false;
return 0;
}
}
public ActionModeCallback(WebContents webContents) {
mHelper =
SelectionPopupController.fromWebContents(webContents).getActionModeCallbackHelper();
}
public void setTabClient(ITabClient tabClient) {
mTabClient = tabClient;
}
public void setOverride(int actionModeItemTypes) {
mActionModeOverride = actionModeItemTypes;
}
@Override
public final boolean onCreateActionMode(ActionMode mode, Menu menu) {
int allowedActionModes = ActionModeCallbackHelper.MENU_ITEM_PROCESS_TEXT
| ActionModeCallbackHelper.MENU_ITEM_SHARE;
if ((mActionModeOverride & ActionModeItemType.WEB_SEARCH) != 0 || isWebSearchAvailable()) {
allowedActionModes |= ActionModeCallbackHelper.MENU_ITEM_WEB_SEARCH;
}
mHelper.setAllowedMenuItems(allowedActionModes);
mHelper.onCreateActionMode(mode, menu);
return true;
}
private boolean isWebSearchAvailable() {
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.EXTRA_NEW_SEARCH, true);
return PackageManagerUtils.canResolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
}
@Override
public final boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return mHelper.onPrepareActionMode(mode, menu);
}
@Override
public final boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int menuItemType = contentToWebLayerType(mHelper.getAllowedMenuItemIfAny(mode, item));
if ((menuItemType & mActionModeOverride) == 0) {
return mHelper.onActionItemClicked(mode, item);
}
assert WebLayerFactoryImpl.getClientMajorVersion() >= 88;
try {
mTabClient.onActionItemClicked(
menuItemType, ObjectWrapper.wrap(mHelper.getSelectedText()));
} catch (RemoteException e) {
throw new APICallException(e);
}
mode.finish();
return true;
}
@Override
public final void onDestroyActionMode(ActionMode mode) {
mHelper.onDestroyActionMode();
}
@Override
public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
mHelper.onGetContentRect(mode, view, outRect);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ActionModeCallback.java | Java | unknown | 4,302 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/** Exposes values of metadata tags to native code. */
@JNINamespace("weblayer")
public class ApplicationInfoHelper {
private ApplicationInfoHelper() {}
/**
* Returns the boolean value for a metadata tag in the application's manifest.
*/
@CalledByNative
public static boolean getMetadataAsBoolean(String metadataTag, boolean defaultValue) {
Context context = ContextUtils.getApplicationContext();
try {
ApplicationInfo info = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
return info.metaData.getBoolean(metadataTag, defaultValue);
} catch (NameNotFoundException exception) {
return defaultValue;
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ApplicationInfoHelper.java | Java | unknown | 1,291 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.view.MotionEvent;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import org.chromium.components.webxr.ArCompositorDelegate;
import org.chromium.content_public.browser.WebContents;
/**
* Weblayer-specific implementation of ArCompositorDelegate interface.
*/
public class ArCompositorDelegateImpl implements ArCompositorDelegate {
private final BrowserImpl mBrowser;
ArCompositorDelegateImpl(WebContents webContents) {
TabImpl tab = TabImpl.fromWebContents(webContents);
mBrowser = tab.getBrowser();
}
@Override
public void setOverlayImmersiveArMode(boolean enabled, boolean domSurfaceNeedsConfiguring) {
BrowserViewController controller =
mBrowser.getBrowserFragment().getPossiblyNullViewController();
if (controller != null) {
controller.setSurfaceProperties(/*requiresAlphaChannel=*/enabled,
/*zOrderMediaOverlay=*/domSurfaceNeedsConfiguring);
}
}
@Override
public void dispatchTouchEvent(MotionEvent ev) {
BrowserViewController controller =
mBrowser.getBrowserFragment().getPossiblyNullViewController();
if (controller != null) {
controller.getContentView().dispatchTouchEvent(ev);
}
}
@Override
@NonNull
public ViewGroup getArSurfaceParent() {
BrowserViewController controller =
mBrowser.getBrowserFragment().getPossiblyNullViewController();
if (controller == null) return null;
return controller.getArViewHolder();
}
@Override
public boolean shouldToggleArSurfaceParentVisibility() {
return true;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ArCompositorDelegateImpl.java | Java | unknown | 1,886 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.components.webxr.ArCompositorDelegate;
import org.chromium.components.webxr.ArCompositorDelegateProvider;
import org.chromium.content_public.browser.WebContents;
/**
* Weblayer-specific implementation of ArCompositorDelegateProvider interface.
*/
@JNINamespace("weblayer")
public class ArCompositorDelegateProviderImpl implements ArCompositorDelegateProvider {
@CalledByNative
public ArCompositorDelegateProviderImpl() {}
@Override
public ArCompositorDelegate create(WebContents webContents) {
return new ArCompositorDelegateImpl(webContents);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ArCompositorDelegateProviderImpl.java | Java | unknown | 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.
package org.chromium.weblayer_private;
import android.content.pm.PackageManager;
import android.os.Bundle;
import org.chromium.base.PackageUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
@JNINamespace("weblayer")
class ArCoreVersionUtils {
// Corresponds to V1.32. Must be updated if the arcore version in
// //third_party/arcore-android-sdk-client is rolled.
private static final int MIN_APK_VERSION = 221020000;
private static final String AR_CORE_PACKAGE = "com.google.ar.core";
private static final String METADATA_KEY_MIN_APK_VERSION = "com.google.ar.core.min_apk_version";
@CalledByNative
public static boolean isEnabled() {
// If the appropriate metadata entries are not present in the app manifest, the feature
// should be disabled.
Bundle metaData = PackageUtils.getApplicationPackageInfo(PackageManager.GET_META_DATA)
.applicationInfo.metaData;
return metaData.containsKey(AR_CORE_PACKAGE)
&& metaData.containsKey(METADATA_KEY_MIN_APK_VERSION) && isInstalledAndCompatible();
}
@CalledByNative
public static boolean isInstalledAndCompatible() {
return PackageUtils.getPackageVersion(AR_CORE_PACKAGE) >= MIN_APK_VERSION;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ArCoreVersionUtils.java | Java | unknown | 1,481 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.base.LifetimeAssert;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.omnibox.AutocompleteSchemeClassifier;
/**
* Creates the c++ class that provides scheme classification logic for WebLayer
* Must call destroy() after using this object to delete the native object.
*/
@JNINamespace("weblayer")
public class AutocompleteSchemeClassifierImpl extends AutocompleteSchemeClassifier {
private final LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this);
public AutocompleteSchemeClassifierImpl() {
super(AutocompleteSchemeClassifierImplJni.get().createAutocompleteClassifier());
}
@Override
public void destroy() {
super.destroy();
AutocompleteSchemeClassifierImplJni.get().deleteAutocompleteClassifier(
super.getNativePtr());
// If mLifetimeAssert is GC'ed before this is called, it will throw an exception
// with a stack trace showing the stack during LifetimeAssert.create().
LifetimeAssert.setSafeToGc(mLifetimeAssert, true);
}
@NativeMethods
interface Natives {
long createAutocompleteClassifier();
void deleteAutocompleteClassifier(long weblayerAutocompleteSchemeClassifier);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/AutocompleteSchemeClassifierImpl.java | Java | unknown | 1,503 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.SystemClock;
import android.view.ContextThemeWrapper;
import android.view.SurfaceControlViewHost;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import org.chromium.base.ContextUtils;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.components.embedder_support.application.ClassLoaderContextWrapperFactory;
import org.chromium.components.embedder_support.view.ContentView;
import org.chromium.ui.base.IntentRequestTracker;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
/**
* Implementation of RemoteFragmentImpl which provides the Fragment implementation for BrowserImpl.
*/
public class BrowserFragmentImpl extends FragmentHostingRemoteFragmentImpl {
private static int sResumedCount;
private static long sSessionStartTimeMs;
private BrowserImpl mBrowser;
private BrowserViewController mViewController;
private LocaleChangedBroadcastReceiver mLocaleReceiver;
private boolean mViewAttachedToWindow;
private int mMinimumSurfaceWidth;
private int mMinimumSurfaceHeight;
private FragmentWindowAndroid mWindowAndroid;
private Context mEmbedderContext;
// Tracks whether the fragment is in the middle of a configuration change when stopped. During
// a configuration change the fragment goes through a full lifecycle and usually the webContents
// is hidden when detached and shown again when re-attached. Tracking the configuration change
// allows continuing to show the WebContents (still following all other lifecycle events as
// normal), which allows continuous playback of videos.
private boolean mInConfigurationChangeAndWasAttached;
/**
* @param windowAndroid a window that was created by a {@link BrowserFragmentImpl}. It's not
* valid to call this method with other {@link WindowAndroid} instances. Typically this
* should be the {@link WindowAndroid} of a {@link WebContents}.
* @return the associated BrowserImpl instance.
*/
public static BrowserFragmentImpl fromWindowAndroid(WindowAndroid windowAndroid) {
assert windowAndroid instanceof FragmentWindowAndroid;
return ((FragmentWindowAndroid) windowAndroid).getFragment();
}
public BrowserFragmentImpl(BrowserImpl browser, Context context) {
super(context);
mBrowser = browser;
mWindowAndroid = new FragmentWindowAndroid(getWebLayerContext(), this);
}
private void createAttachmentState(Context embedderContext) {
assert mViewController == null;
mViewController = new BrowserViewController(embedderContext, mWindowAndroid, false);
mViewController.setMinimumSurfaceSize(mMinimumSurfaceWidth, mMinimumSurfaceHeight);
mViewAttachedToWindow = true;
mLocaleReceiver = new LocaleChangedBroadcastReceiver(mWindowAndroid.getContext().get());
}
private void destroyAttachmentState() {
if (mLocaleReceiver != null) {
mLocaleReceiver.destroy();
mLocaleReceiver = null;
}
if (mViewController != null) {
mViewController.destroy();
mViewController = null;
mViewAttachedToWindow = false;
mBrowser.updateAllTabsViewAttachedState();
}
}
@Override
protected void onCreate() {
StrictModeWorkaround.apply();
super.onCreate();
}
@Override
protected void onStart() {
StrictModeWorkaround.apply();
super.onStart();
mBrowser.notifyFragmentInit();
mBrowser.updateAllTabs();
}
@Override
protected void onPause() {
super.onPause();
sResumedCount--;
if (sResumedCount == 0) {
long deltaMs = SystemClock.uptimeMillis() - sSessionStartTimeMs;
RecordHistogram.recordLongTimesHistogram("Session.TotalDuration", deltaMs);
}
mBrowser.notifyFragmentPause();
}
@Override
protected void onResume() {
super.onResume();
sResumedCount++;
if (sResumedCount == 1) sSessionStartTimeMs = SystemClock.uptimeMillis();
mBrowser.notifyFragmentResume();
}
@Override
protected void onAttach(Context embedderContext) {
StrictModeWorkaround.apply();
super.onAttach(embedderContext);
mEmbedderContext = embedderContext;
mInConfigurationChangeAndWasAttached = false;
setMinimumSurfaceSize(mMinimumSurfaceWidth, mMinimumSurfaceHeight);
createAttachmentState(embedderContext);
mBrowser.updateAllTabs();
setActiveTab(mBrowser.getActiveTab());
mBrowser.checkPreferences();
}
@Override
protected void onDetach() {
StrictModeWorkaround.apply();
super.onDetach();
mEmbedderContext = null;
destroyAttachmentState();
mBrowser.updateAllTabs();
}
@Override
protected void onStop() {
super.onStop();
Activity activity = ContextUtils.activityFromContext(mEmbedderContext);
if (activity != null) {
mInConfigurationChangeAndWasAttached = activity.getChangingConfigurations() != 0;
}
mBrowser.updateAllTabs();
}
@Override
protected void onDestroy() {
StrictModeWorkaround.apply();
super.onDestroy();
}
@Override
public boolean startActivityForResult(Intent intent, int requestCode, Bundle options) {
try {
return mClient.startActivityForResult(
ObjectWrapper.wrap(intent), requestCode, ObjectWrapper.wrap(options));
} catch (RemoteException e) {
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
StrictModeWorkaround.apply();
if (mWindowAndroid != null) {
IntentRequestTracker tracker = mWindowAndroid.getIntentRequestTracker();
assert tracker != null;
tracker.onActivityResult(requestCode, resultCode, data);
}
}
@Override
protected void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
StrictModeWorkaround.apply();
if (mWindowAndroid != null) {
mWindowAndroid.handlePermissionResult(requestCode, permissions, grantResults);
}
}
@RequiresApi(Build.VERSION_CODES.R)
@Override
protected void setSurfaceControlViewHost(SurfaceControlViewHost host) {
// TODO(rayankans): Handle fallback for older devices.
host.setView(getViewController().getView(), 0, 0);
}
@Override
protected View getContentViewRenderView() {
return getViewController().getView();
}
@Override
public void setMinimumSurfaceSize(int width, int height) {
StrictModeWorkaround.apply();
mMinimumSurfaceWidth = width;
mMinimumSurfaceHeight = height;
if (mViewController == null) return;
mViewController.setMinimumSurfaceSize(width, height);
}
// Only call this if it's guaranteed that Browser is attached to an activity.
@NonNull
public BrowserViewController getViewController() {
if (mViewController == null) {
throw new RuntimeException("Currently Tab requires Activity context, so "
+ "it exists only while WebFragment is attached to an Activity");
}
return mViewController;
}
@Nullable
public BrowserViewController getPossiblyNullViewController() {
return mViewController;
}
public BrowserImpl getBrowser() {
return mBrowser;
}
void setActiveTab(TabImpl tab) {
if (mViewController == null) return;
mViewController.setActiveTab(tab);
}
boolean compositorHasSurface() {
if (mViewController == null) return false;
return mViewController.compositorHasSurface();
}
@Nullable
ContentView getViewAndroidDelegateContainerView() {
if (mViewController == null) return null;
return mViewController.getContentView();
}
FragmentWindowAndroid getWindowAndroid() {
return mWindowAndroid;
}
boolean isAttached() {
return mViewAttachedToWindow;
}
/**
* Returns true if the Fragment should be considered visible.
*/
boolean isVisible() {
return mInConfigurationChangeAndWasAttached || mViewAttachedToWindow;
}
void shutdown() {
destroyAttachmentState();
if (mWindowAndroid != null) {
mWindowAndroid.destroy();
mWindowAndroid = null;
}
}
@Override
protected FragmentHostingRemoteFragmentImpl.RemoteFragmentContext createRemoteFragmentContext(
Context embedderContext) {
Context wrappedContext = ClassLoaderContextWrapperFactory.get(embedderContext);
Context themedContext =
new ContextThemeWrapper(wrappedContext, R.style.Theme_WebLayer_Settings);
return new FragmentHostingRemoteFragmentImpl.RemoteFragmentContext(themedContext);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/BrowserFragmentImpl.java | Java | unknown | 9,667 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.base.ObserverList;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.embedder_support.util.Origin;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.weblayer_private.interfaces.BrowserFragmentArgs;
import org.chromium.weblayer_private.interfaces.DarkModeStrategy;
import org.chromium.weblayer_private.interfaces.IBrowser;
import org.chromium.weblayer_private.interfaces.IBrowserClient;
import org.chromium.weblayer_private.interfaces.IMediaRouteDialogFragment;
import org.chromium.weblayer_private.interfaces.IRemoteFragment;
import org.chromium.weblayer_private.interfaces.ITab;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import org.chromium.weblayer_private.media.MediaRouteDialogFragmentImpl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Implementation of {@link IBrowser}.
*/
@JNINamespace("weblayer")
public class BrowserImpl extends IBrowser.Stub {
private final ObserverList<VisibleSecurityStateObserver> mVisibleSecurityStateObservers =
new ObserverList<VisibleSecurityStateObserver>();
// Number of instances that have not been destroyed.
private static int sInstanceCount;
private long mNativeBrowser;
private final ProfileImpl mProfile;
private final boolean mIsExternalIntentsEnabled;
private Context mServiceContext;
private @Nullable List<Origin> mAllowedOrigins;
private IBrowserClient mClient;
private boolean mInDestroy;
// Cache the value instead of querying system every time.
private Boolean mPasswordEchoEnabled;
private Boolean mDarkThemeEnabled;
@DarkModeStrategy
private int mDarkModeStrategy = DarkModeStrategy.WEB_THEME_DARKENING_ONLY;
private Float mFontScale;
// Created in the constructor from saved state.
private FullPersistenceInfo mFullPersistenceInfo;
private BrowserFragmentImpl mBrowserFragmentImpl;
// This persistence state is saved to disk, and loaded async.
private static final class FullPersistenceInfo {
String mPersistenceId;
};
/**
* Allows observing of visible security state of the active tab.
*/
public static interface VisibleSecurityStateObserver {
public void onVisibleSecurityStateOfActiveTabChanged();
}
public void addVisibleSecurityStateObserver(VisibleSecurityStateObserver observer) {
mVisibleSecurityStateObservers.addObserver(observer);
}
public void removeVisibleSecurityStateObserver(VisibleSecurityStateObserver observer) {
mVisibleSecurityStateObservers.removeObserver(observer);
}
public BrowserImpl(Context serviceContext, ProfileManager profileManager, Bundle fragmentArgs) {
++sInstanceCount;
mServiceContext = serviceContext;
String persistenceId = fragmentArgs.getString(BrowserFragmentArgs.PERSISTENCE_ID);
String name = fragmentArgs.getString(BrowserFragmentArgs.PROFILE_NAME);
boolean isIncognito;
if (fragmentArgs.containsKey(BrowserFragmentArgs.IS_INCOGNITO)) {
isIncognito = fragmentArgs.getBoolean(BrowserFragmentArgs.IS_INCOGNITO, false);
} else {
isIncognito = "".equals(name);
}
mProfile = profileManager.getProfile(name, isIncognito);
mProfile.checkNotDestroyed(); // TODO(swestphal): or mProfile != null
mIsExternalIntentsEnabled =
fragmentArgs.getBoolean(BrowserFragmentArgs.IS_EXTERNAL_INTENTS_ENABLED);
List<String> allowedOriginStrings =
fragmentArgs.getStringArrayList(BrowserFragmentArgs.ALLOWED_ORIGINS);
if (allowedOriginStrings != null) {
mAllowedOrigins = new ArrayList<Origin>();
for (String allowedOriginString : allowedOriginStrings) {
Origin allowedOrigin = Origin.create(allowedOriginString);
if (allowedOrigin != null) {
mAllowedOrigins.add(allowedOrigin);
}
}
}
if (!isIncognito && !TextUtils.isEmpty(persistenceId)) {
mFullPersistenceInfo = new FullPersistenceInfo();
mFullPersistenceInfo.mPersistenceId = persistenceId;
}
mNativeBrowser = BrowserImplJni.get().createBrowser(
mProfile.getNativeProfile(), serviceContext.getPackageName(), this);
mPasswordEchoEnabled = null;
notifyFragmentInit(); // TODO(swestphal): Perhaps move to createBrowserFragmentImpl()?
}
@Override
public IRemoteFragment createBrowserFragmentImpl() {
StrictModeWorkaround.apply();
mBrowserFragmentImpl = new BrowserFragmentImpl(this, mServiceContext);
return mBrowserFragmentImpl;
}
@Override
public IMediaRouteDialogFragment createMediaRouteDialogFragmentImpl() {
StrictModeWorkaround.apply();
MediaRouteDialogFragmentImpl fragment = new MediaRouteDialogFragmentImpl(mServiceContext);
return fragment.asIMediaRouteDialogFragment();
}
public Context getContext() {
return mBrowserFragmentImpl.getWebLayerContext();
}
@Override
public TabImpl createTab() {
StrictModeWorkaround.apply();
TabImpl tab = new TabImpl(this, mProfile, mBrowserFragmentImpl.getWindowAndroid());
// This needs |alwaysAdd| set to true as the Tab is created with the Browser already set to
// this.
addTab(tab, /* alwaysAdd */ true);
return tab;
}
@Override
@NonNull
public ProfileImpl getProfile() {
StrictModeWorkaround.apply();
return mProfile;
}
@Override
public void addTab(ITab iTab) {
StrictModeWorkaround.apply();
addTab((TabImpl) iTab, /* alwaysAdd */ false);
}
private void addTab(TabImpl tab, boolean alwaysAdd) {
if (!alwaysAdd && tab.getBrowser() == this) return;
BrowserImplJni.get().addTab(mNativeBrowser, tab.getNativeTab());
}
@CalledByNative
private void createJavaTabForNativeTab(long nativeTab) {
new TabImpl(this, mProfile, mBrowserFragmentImpl.getWindowAndroid(), nativeTab);
}
void checkPreferences() {
boolean changed = false;
if (mPasswordEchoEnabled != null) {
boolean oldEnabled = mPasswordEchoEnabled;
mPasswordEchoEnabled = null;
boolean newEnabled = getPasswordEchoEnabled();
changed = changed || oldEnabled != newEnabled;
}
if (mDarkThemeEnabled != null) {
boolean oldEnabled = mDarkThemeEnabled;
mDarkThemeEnabled = null;
boolean newEnabled = getDarkThemeEnabled();
changed = changed || oldEnabled != newEnabled;
}
if (changed) {
BrowserImplJni.get().webPreferencesChanged(mNativeBrowser);
}
}
@CalledByNative
private boolean getPasswordEchoEnabled() {
Context context = getContext();
if (context == null) return false;
if (mPasswordEchoEnabled == null) {
mPasswordEchoEnabled = Settings.System.getInt(context.getContentResolver(),
Settings.System.TEXT_SHOW_PASSWORD, 1)
== 1;
}
return mPasswordEchoEnabled;
}
@CalledByNative
boolean getDarkThemeEnabled() {
if (mServiceContext == null) return false;
if (mDarkThemeEnabled == null) {
if (mServiceContext == null) return false;
int uiMode = mServiceContext.getApplicationContext()
.getResources()
.getConfiguration()
.uiMode;
mDarkThemeEnabled =
(uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
}
return mDarkThemeEnabled;
}
@CalledByNative
private void onTabAdded(TabImpl tab) throws RemoteException {
tab.attachToBrowser(this);
if (mClient != null) mClient.onTabAdded(tab);
}
@CalledByNative
private void onActiveTabChanged(TabImpl tab) throws RemoteException {
mBrowserFragmentImpl.setActiveTab(tab);
if (!mInDestroy && mClient != null) {
mClient.onActiveTabChanged(tab != null ? tab.getId() : 0);
}
}
@CalledByNative
private void onTabRemoved(TabImpl tab) throws RemoteException {
if (mInDestroy) return;
if (mClient != null) mClient.onTabRemoved(tab.getId());
// This doesn't reset state on TabImpl as |browser| is either about to be
// destroyed, or switching to a different fragment.
}
@CalledByNative
private void onVisibleSecurityStateOfActiveTabChanged() {
for (VisibleSecurityStateObserver observer : mVisibleSecurityStateObservers) {
observer.onVisibleSecurityStateOfActiveTabChanged();
}
}
@CalledByNative
private boolean compositorHasSurface() {
return mBrowserFragmentImpl.compositorHasSurface();
}
@Override
public boolean setActiveTab(ITab iTab) {
StrictModeWorkaround.apply();
TabImpl tab = (TabImpl) iTab;
if (tab != null && tab.getBrowser() != this) return false;
BrowserImplJni.get().setActiveTab(mNativeBrowser, tab != null ? tab.getNativeTab() : 0);
mBrowserFragmentImpl.setActiveTab(tab);
return true;
}
public @Nullable TabImpl getActiveTab() {
return BrowserImplJni.get().getActiveTab(mNativeBrowser);
}
@Override
public List<TabImpl> getTabs() {
StrictModeWorkaround.apply();
return Arrays.asList(BrowserImplJni.get().getTabs(mNativeBrowser));
}
@Override
public int getActiveTabId() {
StrictModeWorkaround.apply();
return getActiveTab() != null ? getActiveTab().getId() : 0;
}
@Override
public int[] getTabIds() {
StrictModeWorkaround.apply();
List<TabImpl> tabs = getTabs();
int[] ids = new int[tabs.size()];
for(int i = 0; i < tabs.size(); i++) {
ids[i] = tabs.get(i).getId();
}
return ids;
}
void notifyFragmentInit() {
// TODO(crbug.com/1378606): rename this.
BrowserImplJni.get().onFragmentStart(mNativeBrowser);
}
void notifyFragmentResume() {
WebLayerAccessibilityUtil.get().onBrowserResumed(mProfile);
BrowserImplJni.get().onFragmentResume(mNativeBrowser);
}
void notifyFragmentPause() {
BrowserImplJni.get().onFragmentPause(mNativeBrowser);
}
boolean isExternalIntentsEnabled() {
return mIsExternalIntentsEnabled;
}
boolean isUrlAllowed(String url) {
// Defaults to all origins being allowed if a developer list is not provided.
if (mAllowedOrigins == null) {
return true;
}
return mAllowedOrigins.contains(Origin.create(url));
}
public boolean isWindowOnSmallDevice() {
WindowAndroid windowAndroid = mBrowserFragmentImpl.getWindowAndroid();
assert windowAndroid != null;
return !DeviceFormFactor.isWindowOnTablet(windowAndroid);
}
@Override
public void setClient(IBrowserClient client) {
// This function is called from the client once everything has been setup (meaning all the
// client classes have been created and AIDL interfaces established in both directions).
// This function is called immediately after the constructor of BrowserImpl from the client.
StrictModeWorkaround.apply();
mClient = client;
if (mFullPersistenceInfo != null) {
FullPersistenceInfo persistenceInfo = mFullPersistenceInfo;
mFullPersistenceInfo = null;
BrowserImplJni.get().restoreStateIfNecessary(
mNativeBrowser, persistenceInfo.mPersistenceId);
} else {
boolean setActiveResult = setActiveTab(createTab());
assert setActiveResult;
try {
onTabInitializationCompleted();
} catch (RemoteException e) {
}
}
}
@Override
public void destroyTab(ITab iTab) {
StrictModeWorkaround.apply();
TabImpl tab = (TabImpl) iTab;
if (tab.getBrowser() != this) return;
destroyTabImpl((TabImpl) iTab);
}
@CalledByNative
private void destroyTabImpl(TabImpl tab) {
tab.destroy();
}
@Override
public void setDarkModeStrategy(@DarkModeStrategy int strategy) {
StrictModeWorkaround.apply();
if (mDarkModeStrategy == strategy) {
return;
}
mDarkModeStrategy = strategy;
BrowserImplJni.get().webPreferencesChanged(mNativeBrowser);
}
@CalledByNative
int getDarkModeStrategy() {
return mDarkModeStrategy;
}
@Override
public boolean isRestoringPreviousState() {
StrictModeWorkaround.apply();
return BrowserImplJni.get().isRestoringPreviousState(mNativeBrowser);
}
@CalledByNative
private void onRestoreCompleted() throws RemoteException {
mClient.onTabInitializationCompleted();
}
private void onTabInitializationCompleted() throws RemoteException {
mClient.onTabInitializationCompleted();
}
@Override
public void shutdown() {
StrictModeWorkaround.apply();
mInDestroy = true;
BrowserImplJni.get().prepareForShutdown(mNativeBrowser);
for (Object tab : getTabs()) {
destroyTabImpl((TabImpl) tab);
}
mBrowserFragmentImpl.shutdown();
BrowserImplJni.get().deleteBrowser(mNativeBrowser);
mVisibleSecurityStateObservers.clear();
if (--sInstanceCount == 0) {
WebLayerAccessibilityUtil.get().onAllBrowsersDestroyed();
}
}
void updateAllTabsViewAttachedState() {
for (Object tab : getTabs()) {
((TabImpl) tab).updateViewAttachedStateFromBrowser();
}
}
void updateAllTabs() {
for (Object tab : getTabs()) {
((TabImpl) tab).updateFromBrowser();
}
}
long getNativeBrowser() {
return mNativeBrowser;
}
public BrowserFragmentImpl getBrowserFragment() {
return mBrowserFragmentImpl;
}
@NativeMethods
interface Natives {
long createBrowser(long profile, String packageName, BrowserImpl caller);
void deleteBrowser(long browser);
void addTab(long nativeBrowserImpl, long nativeTab);
TabImpl[] getTabs(long nativeBrowserImpl);
void setActiveTab(long nativeBrowserImpl, long nativeTab);
TabImpl getActiveTab(long nativeBrowserImpl);
void prepareForShutdown(long nativeBrowserImpl);
void restoreStateIfNecessary(long nativeBrowserImpl, String persistenceId);
void webPreferencesChanged(long nativeBrowserImpl);
void onFragmentStart(long nativeBrowserImpl);
void onFragmentResume(long nativeBrowserImpl);
void onFragmentPause(long nativeBrowserImpl);
boolean isRestoringPreviousState(long nativeBrowserImpl);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/BrowserImpl.java | Java | unknown | 15,832 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import androidx.annotation.NonNull;
import org.chromium.base.ObserverList;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
/**
* Tracks the set of Browsers.
*/
@JNINamespace("weblayer")
public final class BrowserList {
private static BrowserList sInstance;
private final ObserverList<BrowserListObserver> mObservers;
@CalledByNative
private static BrowserList createBrowserList() {
// The native side should call this only once.
assert sInstance == null;
sInstance = new BrowserList();
return sInstance;
}
@NonNull
public static BrowserList getInstance() {
// The native side creates this early on. It should never be null.
if (sInstance == null) {
BrowserListJni.get().createBrowserList();
assert sInstance != null;
}
return sInstance;
}
private BrowserList() {
mObservers = new ObserverList<>();
}
public void addObserver(BrowserListObserver o) {
mObservers.addObserver(o);
}
public void removeObserver(BrowserListObserver o) {
mObservers.removeObserver(o);
}
@CalledByNative
private void onBrowserCreated(BrowserImpl browser) {
for (BrowserListObserver observer : mObservers) {
observer.onBrowserCreated(browser);
}
}
@CalledByNative
private void onBrowserDestroyed(BrowserImpl browser) {
for (BrowserListObserver observer : mObservers) {
observer.onBrowserDestroyed(browser);
}
}
@NativeMethods
interface Natives {
void createBrowserList();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/BrowserList.java | Java | unknown | 1,921 |
// 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;
/**
* Notified of changes to BrowserList.
*/
public interface BrowserListObserver {
void onBrowserCreated(BrowserImpl browser);
void onBrowserDestroyed(BrowserImpl browser);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/BrowserListObserver.java | Java | unknown | 370 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.RemoteException;
import android.util.AndroidRuntimeException;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.components.browser_ui.bottomsheet.BottomSheetControllerFactory;
import org.chromium.components.browser_ui.bottomsheet.BottomSheetObserver;
import org.chromium.components.browser_ui.bottomsheet.EmptyBottomSheetObserver;
import org.chromium.components.browser_ui.bottomsheet.ManagedBottomSheetController;
import org.chromium.components.browser_ui.modaldialog.AppModalPresenter;
import org.chromium.components.browser_ui.widget.InsetObserverView;
import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator;
import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator.SystemUiScrimDelegate;
import org.chromium.components.content_capture.ContentCaptureConsumer;
import org.chromium.components.content_capture.OnscreenContentProvider;
import org.chromium.components.embedder_support.view.ContentView;
import org.chromium.components.webapps.bottomsheet.PwaBottomSheetController;
import org.chromium.components.webapps.bottomsheet.PwaBottomSheetControllerFactory;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.KeyboardVisibilityDelegate;
import org.chromium.ui.modaldialog.DialogDismissalCause;
import org.chromium.ui.modaldialog.ModalDialogManager;
import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogType;
import org.chromium.ui.modaldialog.ModalDialogProperties;
import org.chromium.ui.modaldialog.SimpleModalDialogController;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.util.TokenHolder;
/**
* BrowserViewController controls the set of Views needed to show the WebContents.
*/
@JNINamespace("weblayer")
public final class BrowserViewController
implements WebContentsGestureStateTracker.OnGestureStateChangedListener,
ModalDialogManager.ModalDialogManagerObserver {
private final ContentViewRenderView mContentViewRenderView;
private final Context mWeblayerContext;
// Child of mContentViewRenderView. Be very careful adding Views to this, as any Views are not
// accessible (ContentView provides it's own accessible implementation that interacts with
// WebContents).
private final ContentView mContentView;
// Child of mContentViewRenderView, holds the SurfaceView for WebXR.
private final FrameLayout mArViewHolder;
// Other child of mContentViewRenderView, which holds views that sit on top of the web contents,
// such as tab modal dialogs.
private final FrameLayout mWebContentsOverlayView;
private final FragmentWindowAndroid mWindowAndroid;
private final ModalDialogManager mModalDialogManager;
private final ScrimCoordinator mScrim;
private final ViewGroup mBottomSheetContainer;
private final ManagedBottomSheetController mBottomSheetController;
private final BottomSheetObserver mBottomSheetObserver;
private PwaBottomSheetController mPwaBottomSheetController;
private TabImpl mTab;
private WebContentsGestureStateTracker mGestureStateTracker;
private OnscreenContentProvider mOnscreenContentProvider;
public BrowserViewController(Context embedderContext, FragmentWindowAndroid windowAndroid,
boolean recreateForConfigurationChange) {
mWindowAndroid = windowAndroid;
mWeblayerContext = windowAndroid.getContext().get();
mContentViewRenderView =
new ContentViewRenderView(embedderContext, recreateForConfigurationChange);
mContentViewRenderView.onNativeLibraryLoaded(mWindowAndroid);
mContentView = ContentViewWithAutofill.createContentView(embedderContext, null);
mContentViewRenderView.addView(mContentView,
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
mArViewHolder = new FrameLayout(embedderContext);
mArViewHolder.setVisibility(View.GONE);
mContentViewRenderView.addView(mArViewHolder,
new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mWebContentsOverlayView = new FrameLayout(embedderContext);
RelativeLayout.LayoutParams overlayParams = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mContentViewRenderView.addView(mWebContentsOverlayView, overlayParams);
mWindowAndroid.setAnimationPlaceholderView(mWebContentsOverlayView);
mModalDialogManager = new ModalDialogManager(
new AppModalPresenter(mWeblayerContext), ModalDialogManager.ModalDialogType.APP);
mModalDialogManager.addObserver(this);
mModalDialogManager.registerPresenter(
new WebLayerTabModalPresenter(this, mWeblayerContext), ModalDialogType.TAB);
mWindowAndroid.setModalDialogManager(mModalDialogManager);
SystemUiScrimDelegate systemUiDelegate = new SystemUiScrimDelegate() {
@Override
public void setStatusBarScrimFraction(float scrimFraction) {
// TODO(mdjones): Support status bar tinting if it is needed by WebLayer.
}
@Override
public void setNavigationBarScrimFraction(float scrimFraction) {}
};
mScrim = new ScrimCoordinator(embedderContext, systemUiDelegate, mContentViewRenderView,
mWeblayerContext.getResources().getColor(R.color.default_scrim_color));
mBottomSheetContainer = new FrameLayout(mWeblayerContext);
mBottomSheetContainer.setLayoutParams(
new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mBottomSheetContainer.setClipChildren(false);
mBottomSheetContainer.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View view, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
// Allow the sheet container to layout once before hiding it until it is used.
mBottomSheetContainer.setVisibility(View.GONE);
mBottomSheetContainer.removeOnLayoutChangeListener(this);
}
});
mContentViewRenderView.addView(mBottomSheetContainer);
Activity activity = ContextUtils.activityFromContext(embedderContext);
if (activity == null) {
// TODO(rayankans): Remove assumptions about Activity from BottomSheetController.
mBottomSheetController = null;
mPwaBottomSheetController = null;
mBottomSheetObserver = null;
return;
}
mBottomSheetController = BottomSheetControllerFactory.createBottomSheetController(
() -> mScrim, (v) -> {}, activity.getWindow(),
KeyboardVisibilityDelegate.getInstance(), () -> mBottomSheetContainer);
BottomSheetControllerFactory.attach(mWindowAndroid, mBottomSheetController);
mPwaBottomSheetController =
PwaBottomSheetControllerFactory.createPwaBottomSheetController(mWeblayerContext);
PwaBottomSheetControllerFactory.attach(mWindowAndroid, mPwaBottomSheetController);
mBottomSheetObserver = new EmptyBottomSheetObserver() {
/** A token for suppressing app modal dialogs. */
private int mAppModalToken = TokenHolder.INVALID_TOKEN;
/** A token for suppressing tab modal dialogs. */
private int mTabModalToken = TokenHolder.INVALID_TOKEN;
@Override
public void onSheetOpened(int reason) {
assert mAppModalToken == TokenHolder.INVALID_TOKEN;
assert mTabModalToken == TokenHolder.INVALID_TOKEN;
mAppModalToken =
mModalDialogManager.suspendType(ModalDialogManager.ModalDialogType.APP);
mTabModalToken =
mModalDialogManager.suspendType(ModalDialogManager.ModalDialogType.TAB);
}
@Override
public void onSheetClosed(int reason) {
if (mAppModalToken != TokenHolder.INVALID_TOKEN
|| mTabModalToken != TokenHolder.INVALID_TOKEN) {
// If one modal dialog token is set, the other should be as well.
assert mAppModalToken != TokenHolder.INVALID_TOKEN
&& mTabModalToken != TokenHolder.INVALID_TOKEN;
mModalDialogManager.resumeType(
ModalDialogManager.ModalDialogType.APP, mAppModalToken);
mModalDialogManager.resumeType(
ModalDialogManager.ModalDialogType.TAB, mTabModalToken);
}
mAppModalToken = TokenHolder.INVALID_TOKEN;
mTabModalToken = TokenHolder.INVALID_TOKEN;
}
};
mBottomSheetController.addObserver(mBottomSheetObserver);
mBottomSheetController.setAccessibilityUtil(WebLayerAccessibilityUtil.get());
}
public void destroy() {
if (mBottomSheetController != null) {
BottomSheetControllerFactory.detach(mBottomSheetController);
mBottomSheetController.removeObserver(mBottomSheetObserver);
PwaBottomSheetControllerFactory.detach(mPwaBottomSheetController);
}
mWindowAndroid.setModalDialogManager(null);
setActiveTab(null);
if (mOnscreenContentProvider != null) mOnscreenContentProvider.destroy();
mContentViewRenderView.destroy();
}
/** Returns top-level View this Controller works with */
public View getView() {
return mContentViewRenderView;
}
public InsetObserverView getInsetObserverView() {
return mContentViewRenderView.getInsetObserverView();
}
/** Returns the ViewGroup into which the InfoBarContainer should be parented. **/
public ViewGroup getInfoBarContainerParentView() {
return mContentViewRenderView;
}
public ContentView getContentView() {
return mContentView;
}
public FrameLayout getWebContentsOverlayView() {
return mWebContentsOverlayView;
}
public ViewGroup getArViewHolder() {
return mArViewHolder;
}
public void setSurfaceProperties(boolean requiresAlphaChannel, boolean zOrderMediaOverlay) {
mContentViewRenderView.setSurfaceProperties(requiresAlphaChannel, zOrderMediaOverlay);
}
// Returns the index at which the infobar container view should be inserted.
public int getDesiredInfoBarContainerViewIndex() {
// Ensure that infobars are positioned behind WebContents overlays in z-order.
// TODO(blundell): Should infobars instead be hidden while a WebContents overlay is
// presented?
return mContentViewRenderView.indexOfChild(mWebContentsOverlayView) - 1;
}
public void setActiveTab(TabImpl tab) {
if (tab == mTab) return;
if (mTab != null) {
mTab.onDetachedFromViewController();
// WebContentsGestureStateTracker is relatively cheap, easier to destroy rather than
// update WebContents.
mGestureStateTracker.destroy();
mGestureStateTracker = null;
}
mModalDialogManager.dismissDialogsOfType(
ModalDialogType.TAB, DialogDismissalCause.TAB_SWITCHED);
mTab = tab;
WebContents webContents = mTab != null ? mTab.getWebContents() : null;
// Create the WebContentsGestureStateTracker before setting the WebContents on
// the views as they may call back to this class.
if (mTab != null) {
mGestureStateTracker =
new WebContentsGestureStateTracker(mContentView, webContents, this);
}
mContentView.setWebContents(webContents);
mContentViewRenderView.setWebContents(webContents);
if (mTab != null) {
mTab.onAttachedToViewController();
mContentView.requestFocus();
}
if (mOnscreenContentProvider == null) {
mOnscreenContentProvider = new OnscreenContentProvider(
mWeblayerContext, mContentViewRenderView, webContents);
} else {
mOnscreenContentProvider.onWebContentsChanged(webContents);
}
}
public TabImpl getTab() {
return mTab;
}
public void addContentCaptureConsumerForTesting(ContentCaptureConsumer consumer) {
mOnscreenContentProvider.addConsumer(consumer);
}
public boolean compositorHasSurface() {
return mContentViewRenderView.hasSurface();
}
public void setWebContentIsObscured(boolean isObscured) {
mContentView.setIsObscuredForAccessibility(isObscured);
}
public View getViewForMagnifierReadback() {
return mContentViewRenderView.getViewForMagnifierReadback();
}
@Override
public void onGestureStateChanged() {}
@Override
public void onDialogAdded(PropertyModel model) {
onDialogVisibilityChanged(true);
}
@Override
public void onLastDialogDismissed() {
onDialogVisibilityChanged(false);
}
private void onDialogVisibilityChanged(boolean showing) {
if (mModalDialogManager.getCurrentType() == ModalDialogType.TAB) {
// This shouldn't be called when |mTab| is null and the modal dialog type is TAB. OTOH,
// when an app-modal is displayed for a javascript dialog, this method can be called
// after the tab is destroyed.
assert mTab != null;
try {
mTab.getClient().onTabModalStateChanged(showing);
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
}
}
public void setMinimumSurfaceSize(int width, int height) {
mContentViewRenderView.setMinimumSurfaceSize(width, height);
}
/**
* @return true if a tab modal was showing and has been dismissed.
*/
public boolean dismissTabModalOverlay() {
return mModalDialogManager.dismissActiveDialogOfType(
ModalDialogType.TAB, DialogDismissalCause.NAVIGATE_BACK_OR_TOUCH_OUTSIDE);
}
/**
* Asks the user to confirm a page reload on a POSTed page.
*/
public void showRepostFormWarningDialog() {
ModalDialogProperties.Controller dialogController =
new SimpleModalDialogController(mModalDialogManager, (Integer dismissalCause) -> {
WebContents webContents = mTab == null ? null : mTab.getWebContents();
if (webContents == null) return;
switch (dismissalCause) {
case DialogDismissalCause.POSITIVE_BUTTON_CLICKED:
webContents.getNavigationController().continuePendingReload();
break;
default:
webContents.getNavigationController().cancelPendingReload();
break;
}
});
Resources resources = mWeblayerContext.getResources();
PropertyModel dialogModel =
new PropertyModel.Builder(ModalDialogProperties.ALL_KEYS)
.with(ModalDialogProperties.CONTROLLER, dialogController)
.with(ModalDialogProperties.TITLE, resources,
R.string.http_post_warning_title)
.with(ModalDialogProperties.MESSAGE_PARAGRAPH_1,
resources.getString(R.string.http_post_warning))
.with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, resources,
R.string.http_post_warning_resend)
.with(ModalDialogProperties.NEGATIVE_BUTTON_TEXT, resources,
R.string.cancel)
.with(ModalDialogProperties.CANCEL_ON_TOUCH_OUTSIDE, true)
.build();
mModalDialogManager.showDialog(dialogModel, ModalDialogManager.ModalDialogType.TAB, true);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/BrowserViewController.java | Java | unknown | 16,815 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.webkit.WebViewFactory;
import com.google.android.gms.common.GooglePlayServicesUtilLight;
import org.chromium.base.StrictModeContext;
import org.chromium.base.library_loader.LibraryLoader;
import org.chromium.base.library_loader.NativeLibraryPreloader;
import org.chromium.base.process_launcher.ChildProcessService;
import org.chromium.build.annotations.UsedByReflection;
import org.chromium.components.embedder_support.application.ClassLoaderContextWrapperFactory;
import org.chromium.content_public.app.ChildProcessServiceFactory;
import org.chromium.weblayer_private.interfaces.IChildProcessService;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
/**
* Implementation of IChildProcessService.
*/
@UsedByReflection("WebLayer")
public final class ChildProcessServiceImpl extends IChildProcessService.Stub {
private static final String TAG = "WebLayer";
private ChildProcessService mService;
@UsedByReflection("WebLayer")
public static IBinder create(Service service, Context appContext, Context remoteContext) {
setLibraryPreloader(remoteContext.getPackageName(), remoteContext.getClassLoader());
ClassLoaderContextWrapperFactory.setLightDarkResourceOverrideContext(
remoteContext, remoteContext);
// Wrap the app context so that it can be used to load WebLayer implementation classes.
appContext = ClassLoaderContextWrapperFactory.get(appContext);
// The GPU process may use GMS APIs using the host app's context. This is called in the
// browser process in GmsBridge.
GooglePlayServicesUtilLight.enableUsingApkIndependentContext();
return new ChildProcessServiceImpl(service, appContext);
}
@Override
public void onCreate() {
StrictModeWorkaround.apply();
mService.onCreate();
}
@Override
public void onDestroy() {
StrictModeWorkaround.apply();
mService.onDestroy();
mService = null;
}
@Override
public IObjectWrapper onBind(IObjectWrapper intent) {
StrictModeWorkaround.apply();
return ObjectWrapper.wrap(mService.onBind(ObjectWrapper.unwrap(intent, Intent.class)));
}
private ChildProcessServiceImpl(Service service, Context context) {
mService = ChildProcessServiceFactory.create(service, context);
}
public static void setLibraryPreloader(String webLayerPackageName, ClassLoader classLoader) {
if (!LibraryLoader.getInstance().isLoadedByZygote()) {
LibraryLoader.getInstance().setNativeLibraryPreloader(new NativeLibraryPreloader() {
@Override
public int loadLibrary(String packageName) {
return loadNativeLibrary(webLayerPackageName, classLoader);
}
});
}
}
private static int loadNativeLibrary(String packageName, ClassLoader cl) {
// Loading the library triggers disk access.
try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) {
return WebViewFactory.loadWebViewNativeLibraryFromPackage(packageName, cl);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ChildProcessServiceImpl.java | Java | unknown | 3,587 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.webkit.ValueCallback;
import androidx.annotation.Nullable;
import org.chromium.components.browser_ui.contacts_picker.ContactDetails;
import org.chromium.components.browser_ui.contacts_picker.PickerAdapter;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.weblayer_private.interfaces.IUserIdentityCallbackClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
/**
* A {@link PickerAdapter} for WebLayer.
* This class synthesizes the self contact based on data provided by the client.
*/
public class ContactsPickerAdapter extends PickerAdapter {
private final WindowAndroid mWindowAndroid;
// The avatar returned by the client, or null if it hasn't been returned.
private Bitmap mAvatar;
// True after the self contact has been synthesized and prepended to the contact list.
private boolean mSelfContactSynthesized;
ContactsPickerAdapter(WindowAndroid windowAndroid) {
mWindowAndroid = windowAndroid;
}
// PickerAdapter:
@Override
protected String findOwnerEmail() {
IUserIdentityCallbackClient identityCallback = getUserIdentityCallback();
if (identityCallback == null) return null;
String email;
try {
email = identityCallback.getEmail();
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
return TextUtils.isEmpty(email) ? null : email;
}
@Override
protected void addOwnerInfoToContacts(ArrayList<ContactDetails> contacts) {
// This method should only be called if there was a valid email returned in
// findOwnerEmail().
IUserIdentityCallbackClient identityCallback = getUserIdentityCallback();
assert identityCallback != null;
String name;
// Weak ref so that the outstanding callback doesn't hold a ref to |this|.
final WeakReference<ContactsPickerAdapter> weakThis =
new WeakReference<ContactsPickerAdapter>(this);
try {
name = identityCallback.getFullName();
ValueCallback<Bitmap> onAvatarLoaded = (Bitmap returnedAvatar) -> {
ContactsPickerAdapter strongThis = weakThis.get();
if (strongThis == null) return;
strongThis.updateOwnerInfoWithIcon(returnedAvatar);
};
identityCallback.getAvatar(getIconRawPixelSize(), ObjectWrapper.wrap(onAvatarLoaded));
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
if (TextUtils.isEmpty(name)) {
name = getOwnerEmail();
}
ContactDetails contact = new ContactDetails(ContactDetails.SELF_CONTACT_ID, name,
Collections.singletonList(getOwnerEmail()), /*phoneNumbers=*/null,
/*addresses=*/null);
contact.setIsSelf(true);
contact.setSelfIcon(createAvatarDrawable());
contacts.add(0, contact);
mSelfContactSynthesized = true;
}
@Nullable
private IUserIdentityCallbackClient getUserIdentityCallback() {
return BrowserFragmentImpl.fromWindowAndroid(mWindowAndroid)
.getBrowser()
.getProfile()
.getUserIdentityCallbackClient();
}
private void updateOwnerInfoWithIcon(Bitmap icon) {
if (icon == null) return;
mAvatar = icon.copy(icon.getConfig(), true);
mAvatar.setDensity(
mWindowAndroid.getContext().get().getResources().getConfiguration().densityDpi);
if (mSelfContactSynthesized) {
getAllContacts().get(0).setSelfIcon(createAvatarDrawable());
update();
}
}
private Drawable createAvatarDrawable() {
if (mAvatar == null) return null;
Resources res = mWindowAndroid.getContext().get().getResources();
int sideLength = getIconRawPixelSize();
return new BitmapDrawable(
res, Bitmap.createScaledBitmap(mAvatar, sideLength, sideLength, true));
}
private int getIconRawPixelSize() {
Resources res = mWindowAndroid.getContext().get().getResources();
return res.getDimensionPixelSize(R.dimen.contact_picker_icon_size);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ContactsPickerAdapter.java | Java | unknown | 4,797 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.SystemClock;
import android.util.Size;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.browser_ui.widget.InsetObserverView;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.display.DisplayAndroid;
import org.chromium.ui.resources.ResourceManager;
import java.util.ArrayList;
/**
* This class manages the chromium compositor and the Surface that is used by
* the chromium compositor. Note it can be used to display only one WebContents.
*/
@JNINamespace("weblayer")
public class ContentViewRenderView
extends RelativeLayout implements WindowAndroid.SelectionHandlesObserver {
private static final int CONFIG_TIMEOUT_MS = 1000;
// A child view of this class. Parent of SurfaceView.
// Needed to support not resizing the surface when soft keyboard is showing.
private final SurfaceParent mSurfaceParent;
// This is mode that is requested by client.
private SurfaceData mRequested;
// This is the mode that last supplied the Surface to the compositor.
// This should generally be equal to |mRequested| except during transitions.
private SurfaceData mCurrent;
// The native side of this object.
private long mNativeContentViewRenderView;
private Surface mLastSurface;
private boolean mLastCanBeUsedWithSurfaceControl;
private int mMinimumSurfaceWidth;
private int mMinimumSurfaceHeight;
// An invisible view that notifies observers of changes to window insets and safe area.
private InsetObserverView mInsetObserverView;
private WindowAndroid mWindowAndroid;
private WebContents mWebContents;
private int mBackgroundColor;
// This is the size of the surfaces, so the "physical" size for the compositor.
// This is the size of the |mSurfaceParent| view, which is the immediate parent
// of the SurfaceView. Note this does not always match the size of
// this ContentViewRenderView; when the soft keyboard is displayed,
// ContentViewRenderView will shrink in height, but |mSurfaceParent| will not.
private int mPhysicalWidth;
private int mPhysicalHeight;
private int mWebContentsHeightDelta;
private boolean mCompositorHasSurface;
private DisplayAndroid.DisplayAndroidObserver mDisplayAndroidObserver;
private boolean mSelectionHandlesActive;
private boolean mRequiresAlphaChannel;
private boolean mZOrderMediaOverlay;
// The time stamp when a configuration was detected (if any).
// This is used along with a timeout to determine if a resize surface resize
// is due to screen rotation.
private long mConfigurationChangedTimestamp;
private final ArrayList<TrackedRunnable> mPendingRunnables = new ArrayList<>();
// Runnables posted via View.postOnAnimation may not run after the view is detached,
// if nothing else causes animation. However a pending runnable may held by a GC root
// from the thread itself, and thus can cause leaks. This class here is so ensure that
// on destroy, all pending tasks are run immediately so they do not lead to leaks.
private abstract class TrackedRunnable implements Runnable {
private boolean mHasRun;
public TrackedRunnable() {
mPendingRunnables.add(this);
}
@Override
public final void run() {
// View.removeCallbacks is not always reliable, and may run the callback even
// after it has been removed.
if (mHasRun) return;
assert mPendingRunnables.contains(this);
mPendingRunnables.remove(this);
mHasRun = true;
doRun();
}
protected abstract void doRun();
}
// Non-static class that forward calls to native Compositor.
// It is also responsible for updating |mRequested| and |mCurrent|.
private class SurfaceEventListener {
private SurfaceData mSurfaceData;
public void setRequestData(SurfaceData surfaceData) {
assert mSurfaceData == null;
mSurfaceData = surfaceData;
}
public void surfaceCreated() {
assert mNativeContentViewRenderView != 0;
assert mSurfaceData == ContentViewRenderView.this.mRequested
|| mSurfaceData == ContentViewRenderView.this.mCurrent;
if (ContentViewRenderView.this.mCurrent != null
&& ContentViewRenderView.this.mCurrent != mSurfaceData) {
ContentViewRenderView.this.mCurrent.markForDestroy(true /* hasNextSurface */);
mSurfaceData.setSurfaceDataNeedsDestroy(ContentViewRenderView.this.mCurrent);
}
ContentViewRenderView.this.mCurrent = mSurfaceData;
updateNeedsDidSwapBuffersCallback();
ContentViewRenderViewJni.get().surfaceCreated(mNativeContentViewRenderView);
}
public void surfaceChanged(Surface surface, boolean canBeUsedWithSurfaceControl, int width,
int height, boolean transparentBackground) {
assert mNativeContentViewRenderView != 0;
assert mSurfaceData == ContentViewRenderView.this.mCurrent;
if (mLastSurface == surface
&& mLastCanBeUsedWithSurfaceControl == canBeUsedWithSurfaceControl) {
surface = null;
} else {
mLastSurface = surface;
mLastCanBeUsedWithSurfaceControl = canBeUsedWithSurfaceControl;
}
ContentViewRenderViewJni.get().surfaceChanged(mNativeContentViewRenderView,
canBeUsedWithSurfaceControl, width, height, transparentBackground, surface);
mCompositorHasSurface = mLastSurface != null;
maybeUpdatePhysicalBackingSize(width, height);
updateBackgroundColor();
}
public void surfaceDestroyed(boolean cacheBackBuffer) {
assert mNativeContentViewRenderView != 0;
assert mSurfaceData == ContentViewRenderView.this.mCurrent;
ContentViewRenderViewJni.get().surfaceDestroyed(
mNativeContentViewRenderView, cacheBackBuffer);
mCompositorHasSurface = false;
mLastSurface = null;
mLastCanBeUsedWithSurfaceControl = false;
}
}
// Abstract lifetime of one SurfaceView.
private class SurfaceData implements SurfaceHolder.Callback2 {
private final SurfaceEventListener mListener;
private final FrameLayout mParent;
private final boolean mAllowSurfaceControl;
private final boolean mRequiresAlphaChannel;
private final boolean mZOrderMediaOverlay;
private final Runnable mEvict;
private boolean mMarkedForDestroy;
private boolean mCachedSurfaceNeedsEviction;
private boolean mNeedsOnSurfaceDestroyed;
// During transitioning between two SurfaceData, there is a complicated series of calls to
// avoid visual artifacts.
// 1) Allocate new SurfaceData, and insert it into view hierarchy below the existing
// SurfaceData, so it is not yet showing.
// 2) When Surface is allocated by new View, swap chromium compositor to the
// new Surface. |markForDestroy| is called on the previous SurfaceData, and the two
// SurfaceDatas are linked through these two variables.
// Note at this point the existing view is still visible.
// 3) Wait wait for two swaps from the chromium compositor so it has content and is ready to
// be shown.
// 4) New SurfaceData calls |destroy| on previous SurfaceData. To avoid flicker, move it to
// the back first before and wait two frames before detaching.
private SurfaceData mPrevSurfaceDataNeedsDestroy;
private final SurfaceView mSurfaceView;
private int mNumSurfaceViewSwapsUntilVisible;
private ArrayList<Runnable> mSurfaceRedrawNeededCallbacks;
public SurfaceData(FrameLayout parent, SurfaceEventListener listener, int backgroundColor,
boolean allowSurfaceControl, boolean requiresAlphaChannel,
boolean zOrderMediaOverlay, Runnable evict) {
mListener = listener;
mParent = parent;
mAllowSurfaceControl = allowSurfaceControl;
mRequiresAlphaChannel = requiresAlphaChannel;
mZOrderMediaOverlay = zOrderMediaOverlay;
mEvict = evict;
mSurfaceView = new SurfaceView(parent.getContext());
mSurfaceView.setZOrderMediaOverlay(mZOrderMediaOverlay);
mSurfaceView.setBackgroundColor(backgroundColor);
mSurfaceView.getHolder().addCallback(this);
mSurfaceView.setVisibility(View.VISIBLE);
// TODO(boliu): This is only needed when video is lifted into a separate
// surface. Keeping this constantly will use one more byte per pixel constantly.
mSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
// This postOnAnimation is to avoid manipulating the view tree inside layout or draw.
parent.postOnAnimation(new TrackedRunnable() {
@Override
protected void doRun() {
if (mMarkedForDestroy) return;
View view = mSurfaceView;
assert view != null;
// Always insert view for new surface below the existing view to avoid artifacts
// during surface swaps. Index 0 is the lowest child.
mParent.addView(view, 0,
new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mParent.invalidate();
}
});
}
public void setSurfaceDataNeedsDestroy(SurfaceData surfaceData) {
assert !mMarkedForDestroy;
assert mPrevSurfaceDataNeedsDestroy == null;
mPrevSurfaceDataNeedsDestroy = surfaceData;
}
public boolean getAllowSurfaceControl() {
return mAllowSurfaceControl;
}
public boolean getRequiresAlphaChannel() {
return mRequiresAlphaChannel;
}
public boolean getZOrderMediaOverlay() {
return mZOrderMediaOverlay;
}
// Tearing down is separated into markForDestroy and destroy. After markForDestroy
// this class will is guaranteed to not issue any calls to its SurfaceEventListener.
public void markForDestroy(boolean hasNextSurface) {
if (mMarkedForDestroy) return;
mMarkedForDestroy = true;
if (mNeedsOnSurfaceDestroyed) {
// SurfaceView being used with SurfaceControl need to cache the back buffer
// (EGLSurface). Otherwise the surface is destroyed immediate before the
// SurfaceView is detached.
mCachedSurfaceNeedsEviction = hasNextSurface;
mListener.surfaceDestroyed(mCachedSurfaceNeedsEviction);
mNeedsOnSurfaceDestroyed = false;
}
runSurfaceRedrawNeededCallbacks();
mSurfaceView.getHolder().removeCallback(this);
}
// Remove view from parent hierarchy.
public void destroy() {
assert mMarkedForDestroy;
// This postOnAnimation is to avoid manipulating the view tree inside layout or draw.
mParent.postOnAnimation(new TrackedRunnable() {
@Override
protected void doRun() {
// Detaching a SurfaceView causes a flicker because the SurfaceView
// tears down the Surface in SurfaceFlinger before removing its hole in
// the view tree. This is a complicated heuristics to avoid this. It
// first moves the SurfaceView behind the new View. Then wait two frames
// before detaching the SurfaceView. Waiting for a single frame still
// causes flickers on high end devices like Pixel 3.
moveChildToBackWithoutDetach(mParent, mSurfaceView);
TrackedRunnable inner = new TrackedRunnable() {
@Override
public void doRun() {
mParent.removeView(mSurfaceView);
mParent.invalidate();
if (mCachedSurfaceNeedsEviction) {
mEvict.run();
mCachedSurfaceNeedsEviction = false;
}
}
};
TrackedRunnable outer = new TrackedRunnable() {
@Override
public void doRun() {
mParent.postOnAnimation(inner);
}
};
mParent.postOnAnimation(outer);
}
});
}
private void moveChildToBackWithoutDetach(ViewGroup parent, View child) {
final int numberOfChildren = parent.getChildCount();
final int childIndex = parent.indexOfChild(child);
if (childIndex <= 0) return;
for (int i = 0; i < childIndex; ++i) {
parent.bringChildToFront(parent.getChildAt(0));
}
assert parent.indexOfChild(child) == 0;
for (int i = 0; i < numberOfChildren - childIndex - 1; ++i) {
parent.bringChildToFront(parent.getChildAt(1));
}
parent.invalidate();
}
public void setBackgroundColor(int color) {
assert !mMarkedForDestroy;
mSurfaceView.setBackgroundColor(color);
}
/** @return true if should keep swapping frames */
public boolean didSwapFrame() {
if (mSurfaceView != null && mSurfaceView.getBackground() != null) {
mSurfaceView.post(new Runnable() {
@Override
public void run() {
if (mSurfaceView != null) mSurfaceView.setBackgroundResource(0);
}
});
}
// We have no reliable signal for when to show a SurfaceView. This is a heuristic
// (used by chrome as well) is to wait for 2 swaps from the chromium comopsitor
// as a signal that the SurfaceView has content and is ready to be displayed.
if (mNumSurfaceViewSwapsUntilVisible > 0) {
mNumSurfaceViewSwapsUntilVisible--;
}
if (mNumSurfaceViewSwapsUntilVisible == 0) {
destroyPreviousData();
}
return mNumSurfaceViewSwapsUntilVisible > 0;
}
public void runSurfaceRedrawNeededCallbacks() {
ArrayList<Runnable> callbacks = mSurfaceRedrawNeededCallbacks;
mSurfaceRedrawNeededCallbacks = null;
if (callbacks == null) return;
for (Runnable r : callbacks) {
r.run();
}
updateNeedsDidSwapBuffersCallback();
}
public boolean hasSurfaceRedrawNeededCallbacks() {
return mSurfaceRedrawNeededCallbacks != null
&& !mSurfaceRedrawNeededCallbacks.isEmpty();
}
public View getView() {
return mSurfaceView;
}
private void destroyPreviousData() {
if (mPrevSurfaceDataNeedsDestroy != null) {
mPrevSurfaceDataNeedsDestroy.destroy();
mPrevSurfaceDataNeedsDestroy = null;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mMarkedForDestroy) return;
// On pre-M Android, layers start in the hidden state until a relayout happens.
// There is a bug that manifests itself when entering overlay mode on pre-M devices,
// where a relayout never happens. This bug is out of Chromium's control, but can be
// worked around by forcibly re-setting the visibility of the surface view.
// Otherwise, the screen stays black, and some tests fail.
if (mSurfaceView != null) {
mSurfaceView.setVisibility(mSurfaceView.getVisibility());
}
mListener.surfaceCreated();
mNeedsOnSurfaceDestroyed = true;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Surface surface, boolean canBeUsedWithSurfaceControl, int width,
// int height, boolean transparentBackground) {
if (mMarkedForDestroy) return;
// Selection magnifier does not work with surface control enabled.
mListener.surfaceChanged(holder.getSurface(), mAllowSurfaceControl, width, height,
/*transparentBackground=*/false);
mNumSurfaceViewSwapsUntilVisible = 2;
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mMarkedForDestroy) return;
assert mNeedsOnSurfaceDestroyed;
mListener.surfaceDestroyed(/*cacheBackBuffer=*/false);
mNeedsOnSurfaceDestroyed = false;
runSurfaceRedrawNeededCallbacks();
}
@Override
public void surfaceRedrawNeeded(SurfaceHolder holder) {
// Intentionally not implemented.
}
@Override
public void surfaceRedrawNeededAsync(SurfaceHolder holder, Runnable drawingFinished) {
if (mMarkedForDestroy) {
drawingFinished.run();
return;
}
assert mNativeContentViewRenderView != 0;
assert this == ContentViewRenderView.this.mCurrent;
if (mSurfaceRedrawNeededCallbacks == null) {
mSurfaceRedrawNeededCallbacks = new ArrayList<>();
}
mSurfaceRedrawNeededCallbacks.add(drawingFinished);
updateNeedsDidSwapBuffersCallback();
ContentViewRenderViewJni.get().setNeedsRedraw(mNativeContentViewRenderView);
}
}
// This is a child of ContentViewRenderView and parent of SurfaceView.
// This exists to avoid resizing SurfaceView when the soft keyboard is displayed.
// Also has workaround for SurfaceView `onAttachedToWindow` visual glitch.
private class SurfaceParent extends FrameLayout {
// This view is used to cover up any SurfaceView for a few frames immediately
// after `onAttachedToWindow`. This is the workaround a bug in SurfaceView (on some versions
// of android) which punches a hole before the surface below has any content, resulting in
// black for a few frames. `mCoverView` is a workaround for this bug. It covers up
// SurfaceView with the background color, and is removed after a few swaps.
private final View mCoverView;
private int mNumSwapsUntilHideCover;
public SurfaceParent(Context context) {
super(context);
mCoverView = new View(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int existingHeight = getMeasuredHeight();
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (width <= mMinimumSurfaceWidth && height <= mMinimumSurfaceHeight) {
width = mMinimumSurfaceWidth;
height = mMinimumSurfaceHeight;
}
// If width is the same and height shrinks, then check if we should
// avoid this resize for displaying the soft keyboard.
if (getMeasuredWidth() == width && existingHeight > height
&& shouldAvoidSurfaceResizeForSoftKeyboard()) {
// Just set the height to the current height.
height = existingHeight;
}
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mPhysicalWidth = w;
mPhysicalHeight = h;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mNumSwapsUntilHideCover = 2;
// Add as the top child covering up any other children.
addView(mCoverView,
new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
if (mNativeContentViewRenderView != 0) {
ContentViewRenderViewJni.get().setNeedsRedraw(mNativeContentViewRenderView);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mNumSwapsUntilHideCover = 0;
removeView(mCoverView);
}
/** @return true if should keep swapping frames */
public boolean didSwapFrame() {
if (mNumSwapsUntilHideCover <= 0) return false;
mNumSwapsUntilHideCover--;
if (mNumSwapsUntilHideCover == 0) removeView(mCoverView);
return mNumSwapsUntilHideCover > 0;
}
public void updateCoverViewColor(int color) {
mCoverView.setBackgroundColor(color);
}
}
/**
* Constructs a new ContentViewRenderView.
* This should be called and the {@link ContentViewRenderView} should be added to the view
* hierarchy before the first draw to avoid a black flash that is seen every time a
* {@link SurfaceView} is added.
* @param context The context used to create this.
* @param recreateForConfigurationChange indicates that views are recreated after BrowserImpl
* is retained, but Activity is recreated, for a
* configuration change.
*/
public ContentViewRenderView(Context context, boolean recreateForConfigurationChange) {
super(context);
mSurfaceParent = new SurfaceParent(context);
addView(mSurfaceParent,
new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
mInsetObserverView = InsetObserverView.create(context);
addView(mInsetObserverView);
mInsetObserverView.addObserver(new InsetObserverView.WindowInsetObserver() {
@Override
public void onInsetChanged(int left, int top, int right, int bottom) {
if (mWebContents != null && mWebContents.isFullscreenForCurrentTab()) {
updateWebContentsSize();
}
}
@Override
public void onSafeAreaChanged(Rect area) {}
});
if (recreateForConfigurationChange) updateConfigChangeTimeStamp();
}
/**
* Initialization that requires native libraries should be done here.
* Native code should add/remove the layers to be rendered through the ContentViewLayerRenderer.
* @param rootWindow The {@link WindowAndroid} this render view should be linked to.
*/
public void onNativeLibraryLoaded(WindowAndroid rootWindow) {
assert rootWindow != null;
mNativeContentViewRenderView =
ContentViewRenderViewJni.get().init(ContentViewRenderView.this, rootWindow);
assert mNativeContentViewRenderView != 0;
mWindowAndroid = rootWindow;
maybeRecreateSurfaceView();
mDisplayAndroidObserver = new DisplayAndroid.DisplayAndroidObserver() {
@Override
public void onRotationChanged(int rotation) {
updateConfigChangeTimeStamp();
}
};
mWindowAndroid.getDisplay().addObserver(mDisplayAndroidObserver);
mWindowAndroid.addSelectionHandlesObserver(this);
updateBackgroundColor();
}
public void maybeRecreateSurfaceView() {
boolean allowSurfaceControl = !mSelectionHandlesActive && !mRequiresAlphaChannel;
if (mRequested != null
&& (mRequested.getAllowSurfaceControl() != allowSurfaceControl
|| mRequested.getRequiresAlphaChannel() != mRequiresAlphaChannel
|| mRequested.getZOrderMediaOverlay() != mZOrderMediaOverlay)) {
if (mRequested != mCurrent) {
mRequested.markForDestroy(false /* hasNextSurface */);
mRequested.destroy();
}
mRequested = null;
}
if (mRequested == null) {
SurfaceEventListener listener = new SurfaceEventListener();
mRequested =
new SurfaceData(mSurfaceParent, listener, mBackgroundColor, allowSurfaceControl,
mRequiresAlphaChannel, mZOrderMediaOverlay, this::evictCachedSurface);
listener.setRequestData(mRequested);
}
}
public void setMinimumSurfaceSize(int width, int height) {
mMinimumSurfaceWidth = width;
mMinimumSurfaceHeight = height;
}
/**
* Sets how much to decrease the height of the WebContents by.
*/
public void setWebContentsHeightDelta(int delta) {
if (delta == mWebContentsHeightDelta) return;
mWebContentsHeightDelta = delta;
updateWebContentsSize();
}
/**
* Return the view used for selection magnifier readback.
*/
public View getViewForMagnifierReadback() {
if (mCurrent == null) return null;
return mCurrent.getView();
}
private void updateWebContentsSize() {
if (mWebContents == null) return;
Size size = getViewportSize();
mWebContents.setSize(size.getWidth(), size.getHeight() - mWebContentsHeightDelta);
}
/** {@link CompositorViewHolder#getViewportSize()} for explanation. */
private Size getViewportSize() {
if (mWebContents.isFullscreenForCurrentTab()
&& mWindowAndroid.getKeyboardDelegate().isKeyboardShowing(getContext(), this)) {
Rect visibleRect = new Rect();
getWindowVisibleDisplayFrame(visibleRect);
return new Size(Math.min(visibleRect.width(), getWidth()),
Math.min(visibleRect.height(), getHeight()));
}
return new Size(getWidth(), getHeight());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (mWebContents == null) return;
updateWebContentsSize();
Size viewportSize = getViewportSize();
ContentViewRenderViewJni.get().onViewportSizeChanged(
mNativeContentViewRenderView, viewportSize.getWidth(), viewportSize.getHeight());
}
/**
* View's method override to notify WindowAndroid about changes in its visibility.
*/
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (mWindowAndroid == null) return;
if (visibility == View.GONE) {
mWindowAndroid.onVisibilityChanged(false);
} else if (visibility == View.VISIBLE) {
mWindowAndroid.onVisibilityChanged(true);
}
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
updateBackgroundColor();
}
/**
* Sets the background color of the surface / texture view. This method is necessary because
* the background color of ContentViewRenderView itself is covered by the background of
* SurfaceView.
* @param color The color of the background.
*/
@Override
public void setBackgroundColor(int color) {
if (mBackgroundColor == color) return;
mBackgroundColor = color;
super.setBackgroundColor(color);
mSurfaceParent.updateCoverViewColor(color);
if (mRequested != null) {
mRequested.setBackgroundColor(color);
}
if (mCurrent != null) {
mCurrent.setBackgroundColor(color);
}
ContentViewRenderViewJni.get().updateBackgroundColor(mNativeContentViewRenderView);
}
// SelectionHandlesObserver overrides
@Override
public void onSelectionHandlesStateChanged(boolean active) {
if (mSelectionHandlesActive == active) return;
mSelectionHandlesActive = active;
if (mCurrent == null) return;
// maybeRecreateSurfaceView will take into account the updated |mSelectionHandlesActive|
// and respond appropriately, even if mode is the same.
maybeRecreateSurfaceView();
}
public InsetObserverView getInsetObserverView() {
return mInsetObserverView;
}
public void setSurfaceProperties(boolean requiresAlphaChannel, boolean zOrderMediaOverlay) {
if (mRequiresAlphaChannel == requiresAlphaChannel
&& mZOrderMediaOverlay == zOrderMediaOverlay) {
return;
}
mRequiresAlphaChannel = requiresAlphaChannel;
mZOrderMediaOverlay = zOrderMediaOverlay;
if (mCurrent == null) return;
maybeRecreateSurfaceView();
ContentViewRenderViewJni.get().setRequiresAlphaChannel(
mNativeContentViewRenderView, requiresAlphaChannel);
}
/**
* Should be called when the ContentViewRenderView is not needed anymore so its associated
* native resource can be freed.
*/
public void destroy() {
if (mRequested != null) {
mRequested.markForDestroy(false /* hasNextSurface */);
mRequested.destroy();
if (mCurrent != null && mCurrent != mRequested) {
mCurrent.markForDestroy(false /* hasNextSurface */);
mCurrent.destroy();
}
}
mRequested = null;
mCurrent = null;
if (mDisplayAndroidObserver != null) {
mWindowAndroid.getDisplay().removeObserver(mDisplayAndroidObserver);
mDisplayAndroidObserver = null;
}
mWindowAndroid.removeSelectionHandlesObserver(this);
mWindowAndroid = null;
while (!mPendingRunnables.isEmpty()) {
TrackedRunnable runnable = mPendingRunnables.get(0);
mSurfaceParent.removeCallbacks(runnable);
runnable.run();
assert !mPendingRunnables.contains(runnable);
}
ContentViewRenderViewJni.get().destroy(mNativeContentViewRenderView);
mNativeContentViewRenderView = 0;
}
public void setWebContents(WebContents webContents) {
assert mNativeContentViewRenderView != 0;
mWebContents = webContents;
if (webContents != null && getWidth() != 0 && getHeight() != 0) {
updateWebContentsSize();
maybeUpdatePhysicalBackingSize(mPhysicalWidth, mPhysicalHeight);
}
ContentViewRenderViewJni.get().setCurrentWebContents(
mNativeContentViewRenderView, webContents);
}
public ResourceManager getResourceManager() {
return ContentViewRenderViewJni.get().getResourceManager(mNativeContentViewRenderView);
}
public boolean hasSurface() {
return mCompositorHasSurface;
}
@CalledByNative
private boolean didSwapFrame() {
assert mCurrent != null;
boolean ret = mCurrent.didSwapFrame();
ret = ret || mSurfaceParent.didSwapFrame();
return ret;
}
@CalledByNative
private void didSwapBuffers(boolean sizeMatches) {
assert mCurrent != null;
if (!sizeMatches) return;
mCurrent.runSurfaceRedrawNeededCallbacks();
}
// Should be called any time inputs used to compute `needsDidSwapBuffersCallback` change.
private void updateNeedsDidSwapBuffersCallback() {
boolean needsDidSwapBuffersCallback =
mCurrent != null && mCurrent.hasSurfaceRedrawNeededCallbacks();
ContentViewRenderViewJni.get().setDidSwapBuffersCallbackEnabled(
mNativeContentViewRenderView, needsDidSwapBuffersCallback);
}
private void evictCachedSurface() {
if (mNativeContentViewRenderView == 0) return;
ContentViewRenderViewJni.get().evictCachedSurface(mNativeContentViewRenderView);
}
public long getNativeHandle() {
return mNativeContentViewRenderView;
}
private void updateBackgroundColor() {
int uiMode = getContext().getResources().getConfiguration().uiMode;
boolean darkThemeEnabled =
(uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
int color;
if (darkThemeEnabled) {
color = Color.BLACK;
} else {
color = Color.WHITE;
}
setBackgroundColor(color);
}
@CalledByNative
private int getBackgroundColor() {
return mBackgroundColor;
}
private boolean shouldAvoidSurfaceResizeForSoftKeyboard() {
boolean isFullWidth = isAttachedToWindow() && getWidth() == getRootView().getWidth();
if (!isFullWidth) return false;
InputMethodManager inputMethodManager =
(InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return inputMethodManager.isActive();
}
private void updateConfigChangeTimeStamp() {
mConfigurationChangedTimestamp = SystemClock.uptimeMillis();
}
private void maybeUpdatePhysicalBackingSize(int width, int height) {
if (mWebContents == null) return;
boolean forConfigChange =
SystemClock.uptimeMillis() - mConfigurationChangedTimestamp < CONFIG_TIMEOUT_MS;
ContentViewRenderViewJni.get().onPhysicalBackingSizeChanged(
mNativeContentViewRenderView, mWebContents, width, height, forConfigChange);
}
@NativeMethods
interface Natives {
long init(ContentViewRenderView caller, WindowAndroid rootWindow);
void destroy(long nativeContentViewRenderView);
void setCurrentWebContents(long nativeContentViewRenderView, WebContents webContents);
void onPhysicalBackingSizeChanged(long nativeContentViewRenderView, WebContents webContents,
int width, int height, boolean forConfigChange);
void onViewportSizeChanged(long nativeContentViewRenderView, int width, int height);
void surfaceCreated(long nativeContentViewRenderView);
void surfaceDestroyed(long nativeContentViewRenderView, boolean cacheBackBuffer);
void surfaceChanged(long nativeContentViewRenderView, boolean canBeUsedWithSurfaceControl,
int width, int height, boolean transparentBackground, Surface newSurface);
void setNeedsRedraw(long nativeContentViewRenderView);
void evictCachedSurface(long nativeContentViewRenderView);
ResourceManager getResourceManager(long nativeContentViewRenderView);
void updateBackgroundColor(long nativeContentViewRenderView);
void setRequiresAlphaChannel(
long nativeContentViewRenderView, boolean requiresAlphaChannel);
void setDidSwapBuffersCallbackEnabled(long nativeContentViewRenderView, boolean enabled);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ContentViewRenderView.java | Java | unknown | 36,451 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import android.os.Build;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewStructure;
import android.view.autofill.AutofillValue;
import org.chromium.components.embedder_support.view.ContentView;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.EventOffsetHandler;
/**
* API level 26 implementation that includes autofill.
*/
public class ContentViewWithAutofill extends ContentView {
public static ContentView createContentView(
Context context, EventOffsetHandler eventOffsetHandler) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return new ContentViewWithAutofill(context, eventOffsetHandler);
}
return ContentView.createContentView(context, eventOffsetHandler, null /* webContents */);
}
private TabImpl mTab;
private ContentViewWithAutofill(Context context, EventOffsetHandler eventOffsetHandler) {
super(context, eventOffsetHandler, null /* webContents */);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The Autofill system-level infrastructure has heuristics for which Views it considers
// important for autofill; only these Views will be queried for their autofill
// structure on notifications that a new (virtual) View was entered. By default,
// FrameLayout is not considered important for autofill. Thus, for ContentView to be
// queried for its autofill structure, we must explicitly inform the autofill system
// that this View is important for autofill.
setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_YES);
}
}
@Override
public void setWebContents(WebContents webContents) {
mTab = TabImpl.fromWebContents(webContents);
super.setWebContents(webContents);
}
@Override
public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
// A new (virtual) View has been entered, and the autofill system-level
// infrastructure wants us to populate |structure| with the autofill structure of the
// (virtual) View. Forward this on to TabImpl to accomplish.
if (mTab != null) {
mTab.onProvideAutofillVirtualStructure(structure, flags);
}
}
@Override
public void autofill(final SparseArray<AutofillValue> values) {
// The autofill system-level infrastructure has information that we can use to
// autofill the current (virtual) View. Forward this on to TabImpl to
// accomplish.
if (mTab != null) {
mTab.autofill(values);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ContentViewWithAutofill.java | Java | unknown | 2,907 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import android.webkit.ValueCallback;
import org.chromium.base.Callback;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.CookieChangeCause;
import org.chromium.weblayer_private.interfaces.ExceptionType;
import org.chromium.weblayer_private.interfaces.IBooleanCallback;
import org.chromium.weblayer_private.interfaces.ICookieChangedCallbackClient;
import org.chromium.weblayer_private.interfaces.ICookieManager;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IStringCallback;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.List;
/**
* Implementation of ICookieManager.
*/
@JNINamespace("weblayer")
public final class CookieManagerImpl extends ICookieManager.Stub {
private long mNativeCookieManager;
private ProfileImpl mProfile;
CookieManagerImpl(long nativeCookieManager, ProfileImpl profile) {
mNativeCookieManager = nativeCookieManager;
mProfile = profile;
}
public void destroy() {
mNativeCookieManager = 0;
}
@Override
public void setCookie(String url, String value, IBooleanCallback callback) {
StrictModeWorkaround.apply();
WebLayerOriginVerificationScheduler originVerifier =
WebLayerOriginVerificationScheduler.getInstance();
originVerifier.verify(url, (verified) -> {
if (!verified) {
try {
callback.onException(ExceptionType.RESTRICTED_API,
"Application does not have permissions to modify " + url);
} catch (RemoteException e) {
}
}
Callback<Boolean> baseCallback = (Boolean result) -> {
try {
callback.onResult(result);
} catch (RemoteException e) {
}
};
CookieManagerImplJni.get().setCookie(mNativeCookieManager, url, value, baseCallback);
});
}
@Override
public void getCookie(String url, IStringCallback callback) {
StrictModeWorkaround.apply();
WebLayerOriginVerificationScheduler originVerifier =
WebLayerOriginVerificationScheduler.getInstance();
originVerifier.verify(url, (verified) -> {
if (!verified) {
try {
callback.onException(ExceptionType.RESTRICTED_API,
"Application does not have permissions to modify " + url);
} catch (RemoteException e) {
}
}
Callback<String> baseCallback = (String result) -> {
try {
callback.onResult(result);
} catch (RemoteException e) {
}
};
CookieManagerImplJni.get().getCookie(mNativeCookieManager, url, baseCallback);
});
}
@Override
public void getResponseCookies(String url, IObjectWrapper callback) {
StrictModeWorkaround.apply();
ValueCallback<List<String>> valueCallback =
(ValueCallback<List<String>>) ObjectWrapper.unwrap(callback, ValueCallback.class);
Callback<String[]> baseCallback =
(String[] result) -> valueCallback.onReceiveValue(Arrays.asList(result));
CookieManagerImplJni.get().getResponseCookies(mNativeCookieManager, url, baseCallback);
}
@Override
public IObjectWrapper addCookieChangedCallback(
String url, String name, ICookieChangedCallbackClient callback) {
StrictModeWorkaround.apply();
int id = CookieManagerImplJni.get().addCookieChangedCallback(
mNativeCookieManager, url, name, callback);
// Use a weak reference to make sure we don't keep |this| alive in the closure.
WeakReference<CookieManagerImpl> weakSelf = new WeakReference<>(this);
Runnable close = () -> {
CookieManagerImpl impl = weakSelf.get();
if (impl != null && impl.mNativeCookieManager != 0) {
CookieManagerImplJni.get().removeCookieChangedCallback(
impl.mNativeCookieManager, id);
}
};
return ObjectWrapper.wrap(close);
}
@CalledByNative
private static void onCookieChange(ICookieChangedCallbackClient callback, String cookie,
int cause) throws RemoteException {
callback.onCookieChanged(cookie, mojoCauseToJavaType(cause));
}
@CookieChangeCause
private static int mojoCauseToJavaType(int cause) {
assert org.chromium.network.mojom.CookieChangeCause.isKnownValue(cause);
switch (cause) {
case org.chromium.network.mojom.CookieChangeCause.INSERTED:
return CookieChangeCause.INSERTED;
case org.chromium.network.mojom.CookieChangeCause.EXPLICIT:
return CookieChangeCause.EXPLICIT;
case org.chromium.network.mojom.CookieChangeCause.UNKNOWN_DELETION:
return CookieChangeCause.UNKNOWN_DELETION;
case org.chromium.network.mojom.CookieChangeCause.OVERWRITE:
return CookieChangeCause.OVERWRITE;
case org.chromium.network.mojom.CookieChangeCause.EXPIRED:
return CookieChangeCause.EXPIRED;
case org.chromium.network.mojom.CookieChangeCause.EVICTED:
return CookieChangeCause.EVICTED;
case org.chromium.network.mojom.CookieChangeCause.EXPIRED_OVERWRITE:
return CookieChangeCause.EXPIRED_OVERWRITE;
}
assert false;
return CookieChangeCause.EXPLICIT;
}
@NativeMethods
interface Natives {
void setCookie(
long nativeCookieManagerImpl, String url, String value, Callback<Boolean> callback);
void getCookie(long nativeCookieManagerImpl, String url, Callback<String> callback);
void getResponseCookies(
long nativeCookieManagerImpl, String url, Callback<String[]> callback);
int addCookieChangedCallback(long nativeCookieManagerImpl, String url, String name,
ICookieChangedCallbackClient callback);
void removeCookieChangedCallback(long nativeCookieManagerImpl, int id);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/CookieManagerImpl.java | Java | unknown | 6,776 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.AndroidRuntimeException;
import androidx.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import org.chromium.base.Log;
import org.chromium.base.PathUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.task.AsyncTask;
import org.chromium.components.crash.browser.ChildProcessCrashObserver;
import org.chromium.components.minidump_uploader.CrashFileManager;
import org.chromium.components.minidump_uploader.MinidumpUploader;
import org.chromium.weblayer_private.interfaces.ICrashReporterController;
import org.chromium.weblayer_private.interfaces.ICrashReporterControllerClient;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
/**
* Provides the implementation of the API for managing captured crash reports.
*
* @see org.chromium.weblayer.CrashReporterController
*/
public final class CrashReporterControllerImpl extends ICrashReporterController.Stub {
private static final String TAG = "CrashReporter";
private static final int MAX_UPLOAD_RETRIES = 3;
@Nullable
private ICrashReporterControllerClient mClient;
private CrashFileManager mCrashFileManager;
private boolean mIsNativeInitialized;
private static class Holder {
static CrashReporterControllerImpl sInstance = new CrashReporterControllerImpl();
}
private CrashReporterControllerImpl() {}
public static CrashReporterControllerImpl getInstance() {
return Holder.sInstance;
}
public void notifyNativeInitialized() {
mIsNativeInitialized = true;
if (mClient != null) {
processNewMinidumps();
}
}
@Override
public void deleteCrash(String localId) {
StrictModeWorkaround.apply();
AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
deleteCrashOnBackgroundThread(localId);
try {
mClient.onCrashDeleted(localId);
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
});
}
@Override
public void uploadCrash(String localId) {
StrictModeWorkaround.apply();
AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
TraceEvent.instant(TAG, "CrashReporterController: Begin uploading crash");
File minidumpFile = getCrashFileManager().getCrashFileWithLocalId(localId);
if (minidumpFile == null) {
try {
mClient.onCrashUploadFailed(localId, "invalid crash id");
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
return;
}
MinidumpUploader.Result result = new MinidumpUploader().upload(minidumpFile);
if (result.isSuccess()) {
CrashFileManager.markUploadSuccess(minidumpFile);
} else {
CrashFileManager.tryIncrementAttemptNumber(minidumpFile);
}
try {
if (result.isSuccess()) {
TraceEvent.instant(TAG, "CrashReporterController: Crash upload succeeded.");
mClient.onCrashUploadSucceeded(localId, result.message());
} else {
TraceEvent.instant(TAG, "CrashReporterController: Crash upload failed.");
mClient.onCrashUploadFailed(localId, result.message());
}
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
});
}
@Override
public @Nullable Bundle getCrashKeys(String localId) {
StrictModeWorkaround.apply();
JSONObject data = readSidecar(localId);
if (data == null) {
return null;
}
Bundle result = new Bundle();
Iterator<String> iter = data.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
result.putCharSequence(key, data.getString(key));
} catch (JSONException e) {
// Skip non-string values.
}
}
return result;
}
@Override
public void checkForPendingCrashReports() {
StrictModeWorkaround.apply();
AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
try {
mClient.onPendingCrashReports(getPendingMinidumpsOnBackgroundThread());
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
});
}
@Override
public void setClient(ICrashReporterControllerClient client) {
StrictModeWorkaround.apply();
mClient = client;
if (mIsNativeInitialized) {
processNewMinidumps();
}
// Now that there is a client, register to observe child process crashes.
TraceEvent.instant(TAG, "Start observing child process crashes");
ChildProcessCrashObserver.registerCrashCallback(
new ChildProcessCrashObserver.ChildCrashedCallback() {
@Override
public void childCrashed(int pid) {
TraceEvent.instant(TAG, "Child process crashed. Process new minidumps.");
processNewMinidumps();
}
});
}
/** Start an async task to import crashes, and notify if any are found. */
private void processNewMinidumps() {
AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
String[] localIds = processNewMinidumpsOnBackgroundThread();
if (localIds.length > 0) {
try {
mClient.onPendingCrashReports(localIds);
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
}
});
}
/** Delete a crash report (and any sidecar file) given its local ID. */
private void deleteCrashOnBackgroundThread(String localId) {
File minidumpFile = getCrashFileManager().getCrashFileWithLocalId(localId);
File sidecarFile = sidecarFile(localId);
if (minidumpFile != null) {
CrashFileManager.deleteFile(minidumpFile);
}
if (sidecarFile != null) {
CrashFileManager.deleteFile(sidecarFile);
}
}
/**
* Determine the set of crashes that are currently ready to be uploaded.
*
* Clean out crashes that are too old, and return the any remaining crashes that have not
* exceeded their upload retry limit.
*
* @return An array of local IDs for crashes that are ready to be uploaded.
*/
private String[] getPendingMinidumpsOnBackgroundThread() {
TraceEvent.instant(
TAG, "CrashReporterController: Start determining crashes ready to be uploaded.");
getCrashFileManager().cleanOutAllNonFreshMinidumpFiles();
File[] pendingMinidumps =
getCrashFileManager().getMinidumpsReadyForUpload(MAX_UPLOAD_RETRIES);
ArrayList<String> localIds = new ArrayList<>(pendingMinidumps.length);
for (File minidump : pendingMinidumps) {
localIds.add(CrashFileManager.getCrashLocalIdFromFileName(minidump.getName()));
}
TraceEvent.instant(
TAG, "CrashReporterController: Finish determinining crashes ready to be uploaded.");
return localIds.toArray(new String[0]);
}
/**
* Use the CrashFileManager to import crashes from crashpad.
*
* For each imported crash, a sidecar file (in JSON format) is written, containing the
* crash keys that were recorded at the time of the crash.
*
* @return An array of local IDs of the new crashes (may be empty).
*/
private String[] processNewMinidumpsOnBackgroundThread() {
TraceEvent.instant(
TAG, "CrashReporterController: Start processing minidumps in the background.");
Map<String, Map<String, String>> crashesInfoMap =
getCrashFileManager().importMinidumpsCrashKeys();
if (crashesInfoMap == null) return new String[0];
ArrayList<String> localIds = new ArrayList<>(crashesInfoMap.size());
for (Map.Entry<String, Map<String, String>> entry : crashesInfoMap.entrySet()) {
JSONObject crashKeysJson = new JSONObject(entry.getValue());
String uuid = entry.getKey();
// TODO(tobiasjs): the minidump uploader uses the last component of the uuid as
// the local ID. The ergonomics of this should be improved.
localIds.add(CrashFileManager.getCrashLocalIdFromFileName(uuid + ".dmp"));
writeSidecar(uuid, crashKeysJson);
}
for (File minidump : getCrashFileManager().getMinidumpsSansLogcat()) {
CrashFileManager.trySetReadyForUpload(minidump);
}
TraceEvent.instant(
TAG, "CrashReporterController: Finish processing minidumps in the background.");
return localIds.toArray(new String[0]);
}
/**
* Generate a sidecar file path given a crash local ID.
*
* The sidecar file holds a JSON representation of the crash keys associated
* with the crash. All crash keys and values are strings.
*/
private @Nullable File sidecarFile(String localId) {
File minidumpFile = getCrashFileManager().getCrashFileWithLocalId(localId);
if (minidumpFile == null) {
return null;
}
String uuid = minidumpFile.getName().split("\\.")[0];
return new File(minidumpFile.getParent(), uuid + ".json");
}
/** Write JSON formatted crash key data to the sidecar file for a crash. */
private void writeSidecar(String localId, JSONObject data) {
File sidecar = sidecarFile(localId);
if (sidecar == null) {
return;
}
try (FileOutputStream out = new FileOutputStream(sidecar)) {
out.write(data.toString().getBytes("UTF-8"));
} catch (IOException e) {
Log.w(TAG, "Failed to write crash keys JSON for crash " + localId);
sidecar.delete();
}
}
/** Read JSON formatted crash key data previously written to a crash sidecar file. */
private @Nullable JSONObject readSidecar(String localId) {
File sidecar = sidecarFile(localId);
if (sidecar == null) {
return null;
}
try (FileInputStream in = new FileInputStream(sidecar)) {
byte[] data = new byte[(int) sidecar.length()];
int offset = 0;
while (offset < data.length) {
int count = in.read(data, offset, data.length - offset);
if (count <= 0) break;
offset += count;
}
return new JSONObject(new String(data, "UTF-8"));
} catch (IOException | JSONException e) {
return null;
}
}
private CrashFileManager getCrashFileManager() {
if (mCrashFileManager == null) {
File cacheDir = new File(PathUtils.getCacheDirectory());
// Make sure the cache dir has been created, since this may be called before WebLayer
// has been initialized.
cacheDir.mkdir();
mCrashFileManager = new CrashFileManager(cacheDir);
}
return mCrashFileManager;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/CrashReporterControllerImpl.java | Java | unknown | 11,842 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.Manifest.permission;
import android.content.pm.PackageManager;
import android.os.RemoteException;
import android.webkit.ValueCallback;
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.ui.base.WindowAndroid;
import org.chromium.url.GURL;
import org.chromium.weblayer_private.interfaces.IDownloadCallbackClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* Owns the c++ DownloadCallbackProxy class, which is responsible for forwarding all
* DownloadDelegate delegate calls to this class, which in turn forwards to the
* DownloadCallbackClient.
*/
@JNINamespace("weblayer")
public final class DownloadCallbackProxy {
private final ProfileImpl mProfile;
private long mNativeDownloadCallbackProxy;
private IDownloadCallbackClient mClient;
DownloadCallbackProxy(ProfileImpl profile) {
mProfile = profile;
mNativeDownloadCallbackProxy = DownloadCallbackProxyJni.get().createDownloadCallbackProxy(
this, profile.getNativeProfile());
}
public void setClient(IDownloadCallbackClient client) {
mClient = client;
}
public void destroy() {
DownloadCallbackProxyJni.get().deleteDownloadCallbackProxy(mNativeDownloadCallbackProxy);
mNativeDownloadCallbackProxy = 0;
}
@CalledByNative
private boolean interceptDownload(String url, String userAgent, String contentDisposition,
String mimetype, long contentLength) throws RemoteException {
if (mClient == null) {
return false;
}
return mClient.interceptDownload(
url, userAgent, contentDisposition, mimetype, contentLength);
}
@CalledByNative
private void allowDownload(TabImpl tab, String url, String requestMethod,
String requestInitiator, long callbackId) throws RemoteException {
WindowAndroid window = tab.getBrowser().getBrowserFragment().getWindowAndroid();
if (window.hasPermission(permission.WRITE_EXTERNAL_STORAGE)) {
continueAllowDownload(url, requestMethod, requestInitiator, callbackId);
return;
}
String[] requestPermissions = new String[] {permission.WRITE_EXTERNAL_STORAGE};
window.requestPermissions(requestPermissions, (permissions, grantResults) -> {
if (grantResults.length == 0 || grantResults[0] == PackageManager.PERMISSION_DENIED) {
DownloadCallbackProxyJni.get().allowDownload(callbackId, false);
return;
}
try {
continueAllowDownload(url, requestMethod, requestInitiator, callbackId);
} catch (RemoteException e) {
}
});
}
private void continueAllowDownload(String url, String requestMethod, String requestInitiator,
long callbackId) throws RemoteException {
if (mClient == null) {
DownloadCallbackProxyJni.get().allowDownload(callbackId, true);
return;
}
ValueCallback<Boolean> callback = new ValueCallback<Boolean>() {
@Override
public void onReceiveValue(Boolean result) {
ThreadUtils.assertOnUiThread();
if (mNativeDownloadCallbackProxy == 0) {
throw new IllegalStateException("Called after destroy()");
}
DownloadCallbackProxyJni.get().allowDownload(callbackId, result);
}
};
mClient.allowDownload(url, requestMethod, requestInitiator, ObjectWrapper.wrap(callback));
}
@CalledByNative
private DownloadImpl createDownload(
long nativeDownloadImpl, int id, boolean isTransient, GURL sourceUrl) {
return new DownloadImpl(mProfile.getName(), mProfile.isIncognito(), mClient,
nativeDownloadImpl, id, isTransient, sourceUrl);
}
@CalledByNative
private void downloadStarted(DownloadImpl download) throws RemoteException {
if (mClient != null) {
mClient.downloadStarted(download.getClientDownload());
}
download.downloadStarted();
}
@CalledByNative
private void downloadProgressChanged(DownloadImpl download) throws RemoteException {
if (mClient != null) {
mClient.downloadProgressChanged(download.getClientDownload());
}
download.downloadProgressChanged();
}
@CalledByNative
private void downloadCompleted(DownloadImpl download) throws RemoteException {
if (mClient != null) {
mClient.downloadCompleted(download.getClientDownload());
}
download.downloadCompleted();
}
@CalledByNative
private void downloadFailed(DownloadImpl download) throws RemoteException {
if (mClient != null) {
mClient.downloadFailed(download.getClientDownload());
}
download.downloadFailed();
}
@NativeMethods
interface Natives {
long createDownloadCallbackProxy(DownloadCallbackProxy proxy, long tab);
void deleteDownloadCallbackProxy(long proxy);
void allowDownload(long callbackId, boolean allow);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/DownloadCallbackProxy.java | Java | unknown | 5,497 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.RemoteException;
import android.text.TextUtils;
import androidx.annotation.VisibleForTesting;
import androidx.core.app.NotificationCompat;
import org.chromium.base.ContentUriUtils;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
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.PendingIntentProvider;
import org.chromium.components.browser_ui.util.DownloadUtils;
import org.chromium.url.GURL;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.DownloadError;
import org.chromium.weblayer_private.interfaces.DownloadState;
import org.chromium.weblayer_private.interfaces.IClientDownload;
import org.chromium.weblayer_private.interfaces.IDownload;
import org.chromium.weblayer_private.interfaces.IDownloadCallbackClient;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.io.File;
import java.util.HashMap;
/**
* Implementation of IDownload.
*/
@JNINamespace("weblayer")
public final class DownloadImpl extends IDownload.Stub {
private static final String DOWNLOADS_PREFIX = "org.chromium.weblayer.downloads";
// These actions have to be synchronized with the receiver defined in AndroidManifest.xml.
private static final String OPEN_INTENT = DOWNLOADS_PREFIX + ".OPEN";
private static final String ACTIVATE_TRANSIENT_INTENT =
DOWNLOADS_PREFIX + ".ACTIVATE_TRANSIENT";
private static final String DELETE_INTENT = DOWNLOADS_PREFIX + ".DELETE";
private static final String PAUSE_INTENT = DOWNLOADS_PREFIX + ".PAUSE";
private static final String RESUME_INTENT = DOWNLOADS_PREFIX + ".RESUME";
private static final String CANCEL_INTENT = DOWNLOADS_PREFIX + ".CANCEL";
private static final String EXTRA_NOTIFICATION_ID = DOWNLOADS_PREFIX + ".NOTIFICATION_ID";
private static final String EXTRA_NOTIFICATION_LOCATION =
DOWNLOADS_PREFIX + ".NOTIFICATION_LOCATION";
private static final String EXTRA_NOTIFICATION_MIME_TYPE =
DOWNLOADS_PREFIX + ".NOTIFICATION_MIME_TYPE";
private static final String EXTRA_NOTIFICATION_PROFILE =
DOWNLOADS_PREFIX + ".NOTIFICATION_PROFILE";
private static final String EXTRA_NOTIFICATION_PROFILE_IS_INCOGNITO =
DOWNLOADS_PREFIX + ".NOTIFICATION_PROFILE_IS_INCOGNITO";
private static final String EXTRA_NOTIFICATION_SESSION_ID =
DOWNLOADS_PREFIX + ".NOTIFICATION_SESSION_ID";
// The intent prefix is used as the notification's tag since it's guaranteed not to conflict
// with intent prefixes used by other subsystems that display notifications.
private static final String NOTIFICATION_TAG = DOWNLOADS_PREFIX;
private static final String TAG = "DownloadImpl";
private final String mProfileName;
private final boolean mIsIncognito;
// The client is only used for downloads to disk, so it will be null for transient downloads.
private final IDownloadCallbackClient mClient;
private final IClientDownload mClientDownload;
// WARNING: DownloadImpl may outlive the native side, in which case this member is set to 0.
private long mNativeDownloadImpl;
private boolean mDisableNotification;
// The time this download started, in milliseconds.
private final long mStartTime;
// A transient download is not persisted to disk, which affects its UI treatment.
private final boolean mIsTransient;
// The originating URL for this download.
private final GURL mSourceUrl;
// The large icon to show. Once this is successfully fetched from native, it won't be updated.
private Bitmap mLargeIcon;
private final int mNotificationId;
private static final HashMap<Integer, DownloadImpl> sMap = new HashMap<Integer, DownloadImpl>();
/**
* @return a string that prefixes all intents that can be handled by {@link forwardIntent}.
*/
public static String getIntentPrefix() {
return DOWNLOADS_PREFIX;
}
public static void forwardIntent(
Context context, Intent intent, ProfileManager profileManager) {
if (intent.getAction().equals(OPEN_INTENT)) {
String location = intent.getStringExtra(EXTRA_NOTIFICATION_LOCATION);
if (TextUtils.isEmpty(location)) {
Log.d(TAG, "Didn't find location for open intent");
return;
}
String mimeType = intent.getStringExtra(EXTRA_NOTIFICATION_MIME_TYPE);
Intent openIntent = new Intent(Intent.ACTION_VIEW);
if (TextUtils.isEmpty(mimeType)) {
openIntent.setData(getDownloadUri(location));
} else {
openIntent.setDataAndType(getDownloadUri(location), mimeType);
}
openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
openIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
openIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(openIntent);
} catch (ActivityNotFoundException ex) {
// TODO: show some UI that there were no apps to handle this?
}
return;
}
String profileName = intent.getStringExtra(EXTRA_NOTIFICATION_PROFILE);
boolean isIncognito;
if (intent.hasExtra(EXTRA_NOTIFICATION_PROFILE_IS_INCOGNITO)) {
isIncognito = intent.getBooleanExtra(EXTRA_NOTIFICATION_PROFILE_IS_INCOGNITO, false);
} else {
isIncognito = "".equals(profileName);
}
ProfileImpl profile = profileManager.getProfile(profileName, isIncognito);
if (!profile.areDownloadsInitialized()) {
profile.addDownloadNotificationIntent(intent);
} else {
handleIntent(intent);
}
}
public static void handleIntent(Intent intent) {
int id = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1);
DownloadImpl download = sMap.get(id);
if (download == null) {
Log.d(TAG, "Didn't find download for " + id);
// TODO(jam): handle download resumption after restart
return;
}
if (intent.getAction().equals(PAUSE_INTENT)) {
download.pause();
} else if (intent.getAction().equals(RESUME_INTENT)) {
download.resume();
} else if (intent.getAction().equals(CANCEL_INTENT)) {
download.cancel();
} else if (intent.getAction().equals(DELETE_INTENT)) {
sMap.remove(id);
DownloadImplJni.get().onFinishedImpl(download.mNativeDownloadImpl, /*activated=*/false);
} else if (intent.getAction().equals(ACTIVATE_TRANSIENT_INTENT)) {
assert download.mIsTransient;
DownloadImplJni.get().onFinishedImpl(download.mNativeDownloadImpl, /*activated=*/true);
}
}
public DownloadImpl(String profileName, boolean isIncognito, IDownloadCallbackClient client,
long nativeDownloadImpl, int id, boolean isTransient, GURL sourceUrl) {
mProfileName = profileName;
mIsIncognito = isIncognito;
mClient = isTransient ? null : client;
mNativeDownloadImpl = nativeDownloadImpl;
mNotificationId = id;
mStartTime = System.currentTimeMillis();
mIsTransient = isTransient;
mSourceUrl = sourceUrl;
if (mClient == null) {
mClientDownload = null;
} else {
try {
mClientDownload = mClient.createClientDownload(this);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
DownloadImplJni.get().setJavaDownload(mNativeDownloadImpl, DownloadImpl.this);
}
public IClientDownload getClientDownload() {
return mClientDownload;
}
@DownloadState
private static int implStateToJavaType(@ImplDownloadState int type) {
switch (type) {
case ImplDownloadState.IN_PROGRESS:
return DownloadState.IN_PROGRESS;
case ImplDownloadState.COMPLETE:
return DownloadState.COMPLETE;
case ImplDownloadState.PAUSED:
return DownloadState.PAUSED;
case ImplDownloadState.CANCELLED:
return DownloadState.CANCELLED;
case ImplDownloadState.FAILED:
return DownloadState.FAILED;
}
assert false;
return DownloadState.FAILED;
}
@DownloadError
private static int implErrorToJavaType(@ImplDownloadError int type) {
switch (type) {
case ImplDownloadError.NO_ERROR:
return DownloadError.NO_ERROR;
case ImplDownloadError.SERVER_ERROR:
return DownloadError.SERVER_ERROR;
case ImplDownloadError.SSL_ERROR:
return DownloadError.SSL_ERROR;
case ImplDownloadError.CONNECTIVITY_ERROR:
return DownloadError.CONNECTIVITY_ERROR;
case ImplDownloadError.NO_SPACE:
return DownloadError.NO_SPACE;
case ImplDownloadError.FILE_ERROR:
return DownloadError.FILE_ERROR;
case ImplDownloadError.CANCELLED:
return DownloadError.CANCELLED;
case ImplDownloadError.OTHER_ERROR:
return DownloadError.OTHER_ERROR;
}
assert false;
return DownloadError.OTHER_ERROR;
}
@Override
@DownloadState
public int getState() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return implStateToJavaType(DownloadImplJni.get().getStateImpl(mNativeDownloadImpl));
}
@Override
public long getTotalBytes() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return DownloadImplJni.get().getTotalBytesImpl(mNativeDownloadImpl);
}
@Override
public long getReceivedBytes() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return DownloadImplJni.get().getReceivedBytesImpl(mNativeDownloadImpl);
}
@Override
public void pause() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
DownloadImplJni.get().pauseImpl(mNativeDownloadImpl);
updateNotification();
}
@Override
public void resume() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
DownloadImplJni.get().resumeImpl(mNativeDownloadImpl);
updateNotification();
}
@Override
public void cancel() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
DownloadImplJni.get().cancelImpl(mNativeDownloadImpl);
updateNotification();
}
@Override
public String getLocation() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return DownloadImplJni.get().getLocationImpl(mNativeDownloadImpl);
}
@Override
public String getFileNameToReportToUser() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return DownloadImplJni.get().getFileNameToReportToUserImpl(mNativeDownloadImpl);
}
@Override
public String getMimeType() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return DownloadImplJni.get().getMimeTypeImpl(mNativeDownloadImpl);
}
@Override
@DownloadError
public int getError() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return implErrorToJavaType(DownloadImplJni.get().getErrorImpl(mNativeDownloadImpl));
}
@Override
public void disableNotification() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
mDisableNotification = true;
NotificationManagerProxy notificationManager = getNotificationManager();
notificationManager.cancel(NOTIFICATION_TAG, mNotificationId);
}
private void throwIfNativeDestroyed() {
if (mNativeDownloadImpl == 0) {
throw new IllegalStateException("Using Download after native destroyed");
}
}
private Intent createIntent(String actionId) {
// Because the intent is using classes from the implementation's class loader,
// we need to use the constructor which doesn't take the app's context.
Intent intent = WebLayerImpl.createIntent();
intent.setAction(actionId);
intent.putExtra(EXTRA_NOTIFICATION_ID, mNotificationId);
intent.putExtra(EXTRA_NOTIFICATION_PROFILE, mProfileName);
intent.putExtra(EXTRA_NOTIFICATION_PROFILE_IS_INCOGNITO, mIsIncognito);
return intent;
}
public void downloadStarted() {
if (mDisableNotification) return;
// TODO(jam): create a foreground service while the download is running to avoid the process
// being shut down if the user switches apps.
sMap.put(Integer.valueOf(mNotificationId), this);
updateNotification();
}
public void downloadProgressChanged() {
updateNotification();
}
public void downloadCompleted() {
updateNotification();
}
public void downloadFailed() {
updateNotification();
}
private void updateNotification() {
NotificationManagerProxy notificationManager = getNotificationManager();
if (mDisableNotification || notificationManager == null) return;
Context context = ContextUtils.getApplicationContext();
Intent deleteIntent = createIntent(DELETE_INTENT);
PendingIntentProvider deletePendingIntent = getPendingIntentProvider(deleteIntent);
@DownloadState
int state = getState();
if (state == DownloadState.CANCELLED) {
notificationManager.cancel(NOTIFICATION_TAG, mNotificationId);
mDisableNotification = true;
return;
}
String channelId = state == DownloadState.COMPLETE
? WebLayerNotificationChannels.ChannelId.COMPLETED_DOWNLOADS
: WebLayerNotificationChannels.ChannelId.ACTIVE_DOWNLOADS;
WebLayerNotificationWrapperBuilder builder = WebLayerNotificationWrapperBuilder.create(
channelId, new NotificationMetadata(0, NOTIFICATION_TAG, mNotificationId));
builder.setOngoing(true)
.setWhen(mStartTime)
.setShowWhen(true)
.setDeleteIntent(deletePendingIntent)
.setPriorityBeforeO(NotificationCompat.PRIORITY_DEFAULT);
// The filename might not have been available initially.
String name = getFileNameToReportToUser();
if (!TextUtils.isEmpty(name)) {
builder.setContentTitle(name);
}
// Set the large icon/thumbnail, except when incognito.
if (!mIsIncognito && mLargeIcon == null) {
mLargeIcon = DownloadImplJni.get().getLargeIconImpl(mNativeDownloadImpl);
}
if (mLargeIcon != null) {
builder.setLargeIcon(mLargeIcon);
}
// As with Chrome, transient downloads "promote" the source URL.
if (!mIsIncognito && mIsTransient) {
String formattedUrl = DownloadUtils.formatUrlForDisplayInNotification(mSourceUrl);
if (formattedUrl != null) builder.setSubText(formattedUrl);
}
// TODO(estade): In incognito, Chrome uses a subtext of "Incognito tab". Should WL display
// something similar?
Resources resources = context.getResources();
if (state == DownloadState.COMPLETE) {
builder.setOngoing(false)
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setAutoCancel(true)
.setProgress(0, 0, false);
Intent openIntent = null;
if (mIsTransient) {
builder.setContentText(
resources.getString(R.string.download_notification_completed));
openIntent = createIntent(ACTIVATE_TRANSIENT_INTENT);
} else {
builder.setContentText(
resources.getString(R.string.download_notification_completed_with_size,
DownloadUtils.getStringForBytes(context, getTotalBytes())));
openIntent = createIntent(OPEN_INTENT);
openIntent.putExtra(EXTRA_NOTIFICATION_LOCATION, getLocation());
openIntent.putExtra(EXTRA_NOTIFICATION_MIME_TYPE, getMimeType());
}
builder.setContentIntent(getPendingIntentProvider(openIntent));
} else if (state == DownloadState.FAILED) {
builder.setContentText(resources.getString(R.string.download_notification_failed))
.setOngoing(false)
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setProgress(0, 0, false);
} else if (state == DownloadState.IN_PROGRESS) {
Intent pauseIntent = createIntent(PAUSE_INTENT);
PendingIntentProvider pausePendingIntent = getPendingIntentProvider(pauseIntent);
long bytes = getReceivedBytes();
long totalBytes = getTotalBytes();
boolean indeterminate = totalBytes == -1;
int progressCurrent = -1;
if (!indeterminate && totalBytes != 0) {
progressCurrent = (int) (bytes * 100 / totalBytes);
}
if (!mIsTransient) {
String contentText;
String bytesString = DownloadUtils.getStringForBytes(context, bytes);
if (indeterminate) {
contentText = resources.getString(
R.string.download_ui_indeterminate_bytes, bytesString);
} else {
String totalString = DownloadUtils.getStringForBytes(context, totalBytes);
contentText = resources.getString(
R.string.download_ui_determinate_bytes, bytesString, totalString);
}
builder.setContentText(contentText);
}
builder.addAction(0 /* no icon */,
resources.getString(R.string.download_notification_pause_button),
pausePendingIntent, 0 /* no action for UMA */)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setProgress(100, progressCurrent, indeterminate);
} else if (state == DownloadState.PAUSED) {
Intent resumeIntent = createIntent(RESUME_INTENT);
PendingIntentProvider resumePendingIntent = getPendingIntentProvider(resumeIntent);
builder.setContentText(resources.getString(R.string.download_notification_paused))
.addAction(0 /* no icon */,
resources.getString(R.string.download_notification_resume_button),
resumePendingIntent, 0 /* no action for UMA */)
.setSmallIcon(android.R.drawable.ic_media_pause)
.setProgress(0, 0, false);
}
if (state == DownloadState.IN_PROGRESS || state == DownloadState.PAUSED) {
Intent cancelIntent = createIntent(CANCEL_INTENT);
PendingIntentProvider cancelPendingIntent = getPendingIntentProvider(cancelIntent);
builder.addAction(0 /* no icon */,
resources.getString(R.string.download_notification_cancel_button),
cancelPendingIntent, 0 /* no action for UMA */);
}
notificationManager.notify(builder.buildNotificationWrapper());
}
private PendingIntentProvider getPendingIntentProvider(Intent notificationIntent) {
// Transient intents use FLAG_CANCEL_CURRENT because the IDs can overlap across sessions.
// CANCEL_CURRENT makes sure the PendingIntent is not also reused, and prevents intents from
// old sessions from working (e.g. notifications lingering after WebLayer has crashed and
// failed to clear them).
return PendingIntentProvider.getBroadcast(ContextUtils.getApplicationContext(),
mNotificationId, notificationIntent,
mIsTransient ? PendingIntent.FLAG_CANCEL_CURRENT : 0);
}
/**
* Returns the notification manager.
*/
private static NotificationManagerProxy getNotificationManager() {
return new NotificationManagerProxyImpl(ContextUtils.getApplicationContext());
}
private static Uri getDownloadUri(String location) {
if (ContentUriUtils.isContentUri(location)) return Uri.parse(location);
return ContentUriUtils.getContentUriFromFile(new File(location));
}
@VisibleForTesting
public static void activateNotificationForTesting(int id) {
DownloadImpl download = sMap.get(id);
assert download != null;
DownloadImplJni.get().onFinishedImpl(download.mNativeDownloadImpl, /*activated=*/true);
}
@CalledByNative
private void onNativeDestroyed() {
mNativeDownloadImpl = 0;
sMap.remove(mNotificationId);
if (mIsTransient) {
getNotificationManager().cancel(NOTIFICATION_TAG, mNotificationId);
}
// TODO: this should likely notify delegate in some way.
}
@NativeMethods
interface Natives {
void setJavaDownload(long nativeDownloadImpl, DownloadImpl caller);
int getStateImpl(long nativeDownloadImpl);
long getTotalBytesImpl(long nativeDownloadImpl);
long getReceivedBytesImpl(long nativeDownloadImpl);
void pauseImpl(long nativeDownloadImpl);
void resumeImpl(long nativeDownloadImpl);
void cancelImpl(long nativeDownloadImpl);
void onFinishedImpl(long nativeDownloadImpl, boolean activated);
String getLocationImpl(long nativeDownloadImpl);
String getFileNameToReportToUserImpl(long nativeDownloadImpl);
String getMimeTypeImpl(long nativeDownloadImpl);
int getErrorImpl(long nativeDownloadImpl);
Bitmap getLargeIconImpl(long nativeDownloadImpl);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/DownloadImpl.java | Java | unknown | 23,008 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.IErrorPageCallbackClient;
/**
* Owns the c++ ErrorPageCallbackProxy class, which is responsible for forwarding all
* ErrorPageDelegate calls to this class, which in turn forwards to the
* ErrorPageCallbackClient.
*/
@JNINamespace("weblayer")
public final class ErrorPageCallbackProxy {
private long mNativeErrorPageCallbackProxy;
private IErrorPageCallbackClient mClient;
ErrorPageCallbackProxy(long tab, IErrorPageCallbackClient client) {
assert client != null;
mClient = client;
mNativeErrorPageCallbackProxy =
ErrorPageCallbackProxyJni.get().createErrorPageCallbackProxy(this, tab);
}
public void setClient(IErrorPageCallbackClient client) {
assert client != null;
mClient = client;
}
public void destroy() {
ErrorPageCallbackProxyJni.get().deleteErrorPageCallbackProxy(mNativeErrorPageCallbackProxy);
mNativeErrorPageCallbackProxy = 0;
}
@CalledByNative
private boolean onBackToSafety() throws RemoteException {
return mClient.onBackToSafety();
}
@CalledByNative
private String getErrorPageContent(NavigationImpl navigation) throws RemoteException {
return mClient.getErrorPageContent(navigation.getClientNavigation());
}
@NativeMethods
interface Natives {
long createErrorPageCallbackProxy(ErrorPageCallbackProxy proxy, long tab);
void deleteErrorPageCallbackProxy(long proxy);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ErrorPageCallbackProxy.java | Java | unknown | 1,894 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import android.webkit.ValueCallback;
import org.chromium.base.Callback;
import org.chromium.weblayer_private.interfaces.IExternalIntentInIncognitoCallbackClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* Proxies calls to present the warning dialog gating external intent launches in incognito to
* ExternalIntentInIncognitoCallbackClient.
*/
public final class ExternalIntentInIncognitoCallbackProxy {
private IExternalIntentInIncognitoCallbackClient mClient;
ExternalIntentInIncognitoCallbackProxy(IExternalIntentInIncognitoCallbackClient client) {
setClient(client);
}
void setClient(IExternalIntentInIncognitoCallbackClient client) {
mClient = client;
}
/*
* Proxies onExternalIntentInIncognito() calls to the client.
*/
void onExternalIntentInIncognito(Callback<Integer> onUserDecisionCallback)
throws RemoteException {
assert mClient != null;
ValueCallback<Integer> onUserDecisionValueCallback = (Integer userDecision) -> {
onUserDecisionCallback.onResult(userDecision);
};
mClient.onExternalIntentInIncognito(ObjectWrapper.wrap(onUserDecisionValueCallback));
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ExternalIntentInIncognitoCallbackProxy.java | Java | unknown | 1,439 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.RemoteException;
import org.chromium.base.Callback;
import org.chromium.base.supplier.Supplier;
import org.chromium.components.embedder_support.util.UrlUtilities;
import org.chromium.components.external_intents.ExternalNavigationDelegate;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.url.GURL;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.ExternalIntentInIncognitoUserDecision;
import java.util.List;
/**
* WebLayer's implementation of the {@link ExternalNavigationDelegate}.
*/
public class ExternalNavigationDelegateImpl implements ExternalNavigationDelegate {
private final TabImpl mTab;
private boolean mTabDestroyed;
public ExternalNavigationDelegateImpl(TabImpl tab) {
assert tab != null;
mTab = tab;
}
public void onTabDestroyed() {
mTabDestroyed = true;
}
@Override
public Context getContext() {
return mTab.getBrowser().getContext();
}
@Override
public boolean willAppHandleIntent(Intent intent) {
return false;
}
@Override
public boolean shouldDisableExternalIntentRequestsForUrl(GURL url) {
return !mTab.getBrowser().isExternalIntentsEnabled();
}
@Override
public boolean shouldAvoidDisambiguationDialog(GURL intentDataUrl) {
// Don't show the disambiguation dialog if WebLayer can handle the intent.
return UrlUtilities.isAcceptedScheme(intentDataUrl);
}
@Override
public boolean isApplicationInForeground() {
return mTab.getBrowser().getBrowserFragment().isVisible();
}
@Override
public void maybeSetWindowId(Intent intent) {}
@Override
public boolean canLoadUrlInCurrentTab() {
return true;
}
@Override
public void closeTab() {
InterceptNavigationDelegateClientImpl.closeTab(mTab);
}
@Override
public boolean isIncognito() {
return mTab.getProfile().isIncognito();
}
@Override
public boolean hasCustomLeavingIncognitoDialog() {
return mTab.getExternalIntentInIncognitoCallbackProxy() != null;
}
@Override
public void presentLeavingIncognitoModalDialog(Callback<Boolean> onUserDecision) {
try {
mTab.getExternalIntentInIncognitoCallbackProxy().onExternalIntentInIncognito(
(Integer result) -> {
@ExternalIntentInIncognitoUserDecision
int userDecision = result.intValue();
switch (userDecision) {
case ExternalIntentInIncognitoUserDecision.ALLOW:
onUserDecision.onResult(Boolean.valueOf(true));
break;
case ExternalIntentInIncognitoUserDecision.DENY:
onUserDecision.onResult(Boolean.valueOf(false));
break;
default:
assert false;
}
});
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@Override
// This is relevant only if the intent ends up being handled by this app, which does not happen
// for WebLayer.
public void maybeSetRequestMetadata(
Intent intent, boolean hasUserGesture, boolean isRendererInitiated) {}
@Override
// This is relevant only if the intent ends up being handled by this app, which does not happen
// for WebLayer.
public void maybeSetPendingReferrer(Intent intent, GURL referrerUrl) {}
@Override
// This is relevant only if the intent ends up being handled by this app, which does not happen
// for WebLayer.
public void maybeSetPendingIncognitoUrl(Intent intent) {}
@Override
public WindowAndroid getWindowAndroid() {
return mTab.getBrowser().getBrowserFragment().getWindowAndroid();
}
@Override
public WebContents getWebContents() {
return mTab.getWebContents();
}
@Override
public boolean hasValidTab() {
assert mTab != null;
return !mTabDestroyed;
}
@Override
public boolean canCloseTabOnIncognitoIntentLaunch() {
return hasValidTab();
}
@Override
public boolean isForTrustedCallingApp(Supplier<List<ResolveInfo>> resolveInfoSupplier) {
return false;
}
@Override
public boolean shouldLaunchWebApksOnInitialIntent() {
return false;
}
@Override
public void setPackageForTrustedCallingApp(Intent intent) {
assert false;
}
@Override
public boolean shouldEmbedderInitiatedNavigationsStayInBrowser() {
// WebLayer already has APIs that allow the embedder to specify that a navigation shouldn't
// result in an external intent (Navigation#disableIntentProcessing() and
// NavigateParams#disableIntentProcessing()), and historically embedder-initiated
// navigations have been allowed to leave the browser on the initial navigation, so we need
// to maintain that behavior.
return false;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ExternalNavigationDelegateImpl.java | Java | unknown | 5,569 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.graphics.Bitmap;
import android.os.RemoteException;
import android.util.AndroidRuntimeException;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.IFaviconFetcher;
import org.chromium.weblayer_private.interfaces.IFaviconFetcherClient;
/**
* Owns the c++ ErrorPageCallbackProxy class, which is responsible for forwarding all
* ErrorPageDelegate calls to this class, which in turn forwards to the
* ErrorPageCallbackClient.
*/
@JNINamespace("weblayer")
public final class FaviconCallbackProxy extends IFaviconFetcher.Stub {
private TabImpl mTab;
private long mNativeFaviconCallbackProxy;
private IFaviconFetcherClient mClient;
FaviconCallbackProxy(TabImpl tab, long nativeTab, IFaviconFetcherClient client) {
assert client != null;
mTab = tab;
mClient = client;
mNativeFaviconCallbackProxy =
FaviconCallbackProxyJni.get().createFaviconCallbackProxy(this, nativeTab);
}
@Override
public void destroy() {
// As Tab implicitly destroys this, and the embedder is allowed to destroy this, allow
// destroy() to be called multiple times.
if (mNativeFaviconCallbackProxy == 0) {
return;
}
mTab.removeFaviconCallbackProxy(this);
try {
mClient.onDestroyed();
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
FaviconCallbackProxyJni.get().deleteFaviconCallbackProxy(mNativeFaviconCallbackProxy);
mNativeFaviconCallbackProxy = 0;
mClient = null;
}
@CalledByNative
private void onFaviconChanged(Bitmap bitmap) throws RemoteException {
mTab.onFaviconChanged(bitmap);
mClient.onFaviconChanged(bitmap);
}
@NativeMethods
interface Natives {
long createFaviconCallbackProxy(FaviconCallbackProxy proxy, long tab);
void deleteFaviconCallbackProxy(long proxy);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/FaviconCallbackProxy.java | Java | unknown | 2,287 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.base.compat.ApiHelperForM;
import org.chromium.ui.permissions.AndroidPermissionDelegateWithRequester;
/**
* AndroidPermissionDelegate implementation for BrowserFragment.
*/
public class FragmentAndroidPermissionDelegate extends AndroidPermissionDelegateWithRequester {
private BrowserFragmentImpl mFragment;
public FragmentAndroidPermissionDelegate(BrowserFragmentImpl fragment) {
mFragment = fragment;
}
@Override
public final boolean shouldShowRequestPermissionRationale(String permission) {
if (mFragment.getActivity() == null) return false;
return mFragment.shouldShowRequestPermissionRationale(permission);
}
@Override
protected final boolean isPermissionRevokedByPolicyInternal(String permission) {
if (mFragment.getActivity() == null) return false;
return ApiHelperForM.isPermissionRevokedByPolicy(mFragment.getActivity(), permission);
}
@Override
protected final boolean requestPermissionsFromRequester(String[] permissions, int requestCode) {
if (mFragment.getActivity() == null) return false;
mFragment.requestPermissions(permissions, requestCode);
return true;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/FragmentAndroidPermissionDelegate.java | Java | unknown | 1,399 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.FragmentController;
import androidx.fragment.app.FragmentHostCallback;
import androidx.fragment.app.FragmentManager;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.lang.reflect.Constructor;
/**
* A base class for RemoteFragmentImpls that need to host child Fragments.
*
* Because Fragments created in WebLayer use the AndroidX library from WebLayer's ClassLoader, we
* can't attach Fragments created here directly to the embedder's Fragment tree, and have to create
* a local FragmentController to manage them. This class handles creating the FragmentController,
* and forwards all Fragment lifecycle events from the RemoteFragment in the embedder's Fragment
* tree to child Fragments of this class.
*/
public abstract class FragmentHostingRemoteFragmentImpl extends RemoteFragmentImpl {
// The WebLayer-wrapped context object. This context gets assets and resources from WebLayer,
// not from the embedder. Use this for the most part, especially to resolve WebLayer-specific
// resource IDs.
private Context mContext;
private boolean mStarted;
private FragmentController mFragmentController;
protected static class RemoteFragmentContext
extends ContextWrapper implements LayoutInflater.Factory2 {
private static final Class<?>[] VIEW_CONSTRUCTOR_ARGS =
new Class[] {Context.class, AttributeSet.class};
public RemoteFragmentContext(Context webLayerContext) {
super(webLayerContext);
}
// This method is needed to work around a LayoutInflater bug in Android <N. Before
// LayoutInflater creates an instance of a View, it needs to look up the class by name to
// get a reference to its Constructor. As an optimization, it caches this name to
// Constructor mapping. This cache causes issues if a class gets loaded multiple times with
// different ClassLoaders. In some UIs, some AndroidX Views get loaded early on with the
// embedding app's ClassLoader, so the Constructor from that ClassLoader's version of the
// class gets cached. When the WebLayer implementation later tries to inflate the same
// class, it instantiates a version from the wrong ClassLoader, which leads to a
// ClassCastException when casting that View to its original class. This was fixed in
// Android N, but to work around it on L & M, we inflate the Views manually here, which
// bypasses LayoutInflater's cache.
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
// If the class doesn't have a '.' in its name, it's probably a built-in Android View,
// which are often referenced by just their class names with no package prefix. For
// these classes we can return null to fall back to LayoutInflater's default behavior.
if (name.indexOf('.') == -1) {
return null;
}
Class<? extends View> clazz = null;
try {
clazz = context.getClassLoader().loadClass(name).asSubclass(View.class);
LayoutInflater inflater = getLayoutInflater();
if (inflater.getFilter() != null && !inflater.getFilter().onLoadClass(clazz)) {
throw new InflateException(attrs.getPositionDescription()
+ ": Class not allowed to be inflated " + name);
}
Constructor<? extends View> constructor =
clazz.getConstructor(VIEW_CONSTRUCTOR_ARGS);
constructor.setAccessible(true);
View view = constructor.newInstance(new Object[] {context, attrs});
if (view instanceof ViewStub) {
// Use the same Context when inflating ViewStub later.
ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(inflater.cloneInContext(context));
}
return view;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()));
ie.initCause(e);
throw ie;
}
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
StrictModeWorkaround.apply();
return null;
}
private LayoutInflater getLayoutInflater() {
return (LayoutInflater) getBaseContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
}
private static class RemoteFragmentHostCallback extends FragmentHostCallback<Context> {
private final FragmentHostingRemoteFragmentImpl mFragmentImpl;
private RemoteFragmentHostCallback(FragmentHostingRemoteFragmentImpl fragmentImpl) {
super(fragmentImpl.getWebLayerContext(), new Handler(), 0);
mFragmentImpl = fragmentImpl;
}
@Override
public Context onGetHost() {
return mFragmentImpl.getWebLayerContext();
}
@Override
public LayoutInflater onGetLayoutInflater() {
Context context = mFragmentImpl.getWebLayerContext();
return ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.cloneInContext(context);
}
@Override
public boolean onHasView() {
// This is always false.
return mFragmentImpl.getView() != null;
}
@Override
public View onFindViewById(int id) {
// This is always null.
return onHasView() ? mFragmentImpl.getView().findViewById(id) : null;
}
}
protected FragmentHostingRemoteFragmentImpl(Context context) {
super();
mContext = createRemoteFragmentContext(context);
}
@Override
protected void onAttach(Context embedderContext) {
StrictModeWorkaround.apply();
super.onAttach(embedderContext);
// Some appcompat functionality depends on Fragments being hosted from within an
// AppCompatActivity, which performs some static initialization. Even if we're running
// within an AppCompatActivity, it will be from the embedder's ClassLoader, so in WebLayer's
// ClassLoader the initialization hasn't occurred. Creating an AppCompatDelegate manually
// here will perform the necessary initialization.
if (getActivity() != null) {
AppCompatDelegate.create(getActivity(), null);
}
}
@Override
protected void onCreate() {
StrictModeWorkaround.apply();
super.onCreate();
mFragmentController =
FragmentController.createController(new RemoteFragmentHostCallback(this));
mFragmentController.attachHost(null);
mFragmentController.dispatchCreate();
}
@Override
protected void onDestroyView() {
StrictModeWorkaround.apply();
super.onDestroyView();
mFragmentController.dispatchDestroyView();
}
@Override
protected void onDestroy() {
StrictModeWorkaround.apply();
super.onDestroy();
if (!mFragmentController.getSupportFragmentManager().isDestroyed()) {
mFragmentController.dispatchDestroy();
assert mFragmentController.getSupportFragmentManager().isDestroyed();
}
}
@Override
protected void onDetach() {
StrictModeWorkaround.apply();
super.onDetach();
}
@Override
protected void onStart() {
StrictModeWorkaround.apply();
super.onStart();
if (!mStarted) {
mStarted = true;
mFragmentController.dispatchActivityCreated();
}
mFragmentController.noteStateNotSaved();
mFragmentController.execPendingActions();
mFragmentController.dispatchStart();
}
@Override
protected void onStop() {
StrictModeWorkaround.apply();
super.onStop();
mFragmentController.dispatchStop();
}
@Override
protected void onResume() {
StrictModeWorkaround.apply();
super.onResume();
mFragmentController.dispatchResume();
}
@Override
protected void onPause() {
StrictModeWorkaround.apply();
super.onPause();
mFragmentController.dispatchPause();
}
public FragmentManager getSupportFragmentManager() {
return mFragmentController.getSupportFragmentManager();
}
/**
* Returns the RemoteFragmentContext that should be used in the child Fragment tree.
*
* Implementations will typically wrap embedderContext with ClassLoaderContextWrapperFactory,
* and possibly set a Theme.
*/
protected abstract RemoteFragmentContext createRemoteFragmentContext(Context embedderContext);
protected Context getWebLayerContext() {
return mContext;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/FragmentHostingRemoteFragmentImpl.java | Java | unknown | 9,693 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Build;
import android.view.View;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentManager;
import org.chromium.ui.base.ActivityKeyboardVisibilityDelegate;
import org.chromium.ui.base.ImmutableWeakReference;
import org.chromium.ui.base.IntentRequestTracker;
import org.chromium.ui.base.IntentRequestTracker.Delegate;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.modaldialog.ModalDialogManager;
import java.lang.ref.WeakReference;
/**
* Implements intent sending for a fragment based window. This should be created when
* onAttach() is called on the fragment, and destroyed when onDetach() is called.
*/
public class FragmentWindowAndroid extends WindowAndroid {
private final BrowserFragmentImpl mFragment;
private ModalDialogManager mModalDialogManager;
/**
* WebLayer's implementation of the delegate of a IntentRequestTracker.
*/
private static class TrackerDelegateImpl implements Delegate {
private final RemoteFragmentImpl mFragment;
// This WeakReference is purely to avoid gc churn of creating a new WeakReference in
// every getActivity call. It is not needed for correctness.
private ImmutableWeakReference<Activity> mActivityWeakRefHolder;
/**
* Create an instance of delegate for the given fragment that will own the
* IntentRequestTracker.
* @param fragment The fragment that owns the IntentRequestTracker.
*/
private TrackerDelegateImpl(RemoteFragmentImpl fragment) {
mFragment = fragment;
}
@Override
public boolean startActivityForResult(Intent intent, int requestCode) {
return mFragment.startActivityForResult(intent, requestCode, null);
}
@Override
public boolean startIntentSenderForResult(IntentSender intentSender, int requestCode) {
return mFragment.startIntentSenderForResult(
intentSender, requestCode, new Intent(), 0, 0, 0, null);
}
@Override
public void finishActivity(int requestCode) {
Activity activity = getActivity().get();
if (activity == null) return;
activity.finishActivity(requestCode);
}
@Override
public final WeakReference<Activity> getActivity() {
if (mActivityWeakRefHolder == null
|| mActivityWeakRefHolder.get() != mFragment.getActivity()) {
mActivityWeakRefHolder = new ImmutableWeakReference<>(mFragment.getActivity());
}
return mActivityWeakRefHolder;
}
}
/* package */ FragmentWindowAndroid(Context context, BrowserFragmentImpl fragment) {
super(context, IntentRequestTracker.createFromDelegate(new TrackerDelegateImpl(fragment)));
mFragment = fragment;
setKeyboardDelegate(new ActivityKeyboardVisibilityDelegate(getActivity()));
setAndroidPermissionDelegate(new FragmentAndroidPermissionDelegate(mFragment));
}
@Override
public final WeakReference<Activity> getActivity() {
return getIntentRequestTracker().getActivity();
}
@Override
public final ModalDialogManager getModalDialogManager() {
return mModalDialogManager;
}
@Override
public View getReadbackView() {
BrowserViewController viewController = mFragment.getPossiblyNullViewController();
if (viewController == null) return null;
return viewController.getViewForMagnifierReadback();
}
public void setModalDialogManager(ModalDialogManager modalDialogManager) {
mModalDialogManager = modalDialogManager;
}
public BrowserFragmentImpl getFragment() {
return mFragment;
}
public FragmentManager getFragmentManager() {
return mFragment.getSupportFragmentManager();
}
@Override
@RequiresApi(Build.VERSION_CODES.O)
public void setWideColorEnabled(boolean enabled) {
// WebLayer should not change its behavior when the content contains wide color.
// Rather, the app embedding the WebLayer gets to choose whether or not it is wide.
// So we should do nothing in this override.
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/FragmentWindowAndroid.java | Java | unknown | 4,566 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import android.webkit.ValueCallback;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.IFullscreenCallbackClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* Owns the c++ FullscreenCallbackProxy class, which is responsible for forwarding all
* FullscreenDelegate delegate calls to this class, which in turn forwards to the
* FullscreenCallbackClient.
*/
@JNINamespace("weblayer")
public final class FullscreenCallbackProxy {
private long mNativeFullscreenCallbackProxy;
private IFullscreenCallbackClient mClient;
private TabImpl mTab;
private FullscreenToast mToast;
private boolean mIsNotifyingClientOfEnter;
// Used so that only the most recent callback supplied to the client is acted on.
private int mNextFullscreenId;
FullscreenCallbackProxy(TabImpl tab, long nativeTab, IFullscreenCallbackClient client) {
assert client != null;
mClient = client;
mTab = tab;
mNativeFullscreenCallbackProxy =
FullscreenCallbackProxyJni.get().createFullscreenCallbackProxy(this, nativeTab);
}
public void setClient(IFullscreenCallbackClient client) {
assert client != null;
mClient = client;
}
public void destroy() {
FullscreenCallbackProxyJni.get().deleteFullscreenCallbackProxy(
mNativeFullscreenCallbackProxy);
mNativeFullscreenCallbackProxy = 0;
destroyToast();
mTab = null;
}
public void destroyToast() {
if (mToast == null) return;
mToast.destroy();
mToast = null;
}
@VisibleForTesting
public boolean didShowFullscreenToast() {
return mToast != null && mToast.didShowFullscreenToast();
}
@CalledByNative
private void enterFullscreen() throws RemoteException {
final int id = ++mNextFullscreenId;
ValueCallback<Void> exitFullscreenCallback = new ValueCallback<Void>() {
@Override
public void onReceiveValue(Void result) {
ThreadUtils.assertOnUiThread();
if (id != mNextFullscreenId) {
// This is an old fullscreen request. Ignore it.
return;
}
if (mNativeFullscreenCallbackProxy == 0) {
throw new IllegalStateException("Called after destroy()");
}
if (mIsNotifyingClientOfEnter) {
throw new IllegalStateException(
"Fullscreen callback must not be called synchronously");
}
destroyToast();
FullscreenCallbackProxyJni.get().doExitFullscreen(mNativeFullscreenCallbackProxy);
}
};
destroyToast();
mToast = new FullscreenToast(mTab);
mIsNotifyingClientOfEnter = true;
try {
mClient.enterFullscreen(ObjectWrapper.wrap(exitFullscreenCallback));
} finally {
mIsNotifyingClientOfEnter = false;
}
}
@CalledByNative
private void exitFullscreen() throws RemoteException {
mClient.exitFullscreen();
destroyToast();
}
@NativeMethods
interface Natives {
long createFullscreenCallbackProxy(FullscreenCallbackProxy proxy, long tab);
void deleteFullscreenCallbackProxy(long proxy);
void doExitFullscreen(long nativeFullscreenCallbackProxy);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/FullscreenCallbackProxy.java | Java | unknown | 3,894 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.view.Gravity;
import android.view.View;
import androidx.annotation.VisibleForTesting;
import org.chromium.components.embedder_support.view.ContentView;
import org.chromium.ui.widget.Toast;
/**
* FullscreenToast is responsible for showing toast when fullscreen mode is entered. As the embedder
* is responsible for entering fullscreen mode, there is no guarantee when or if fullscreen mode
* will be entered. This waits for the system to enter fullscreen mode and then show the toast. If
* fullscreen isn't entered after a short delay this assumes the embedder won't enter fullscreen
* and the toast is never shown.
*/
public final class FullscreenToast {
// The tab the toast is showing from.
private TabImpl mTab;
// View used to register for system ui change notification.
private ContentView mView;
private View.OnSystemUiVisibilityChangeListener mSystemUiVisibilityChangeListener;
// Set to true once toast is shown.
private boolean mDidShowToast;
// The toast.
private Toast mToast;
FullscreenToast(TabImpl tab) {
mTab = tab;
// TODO(https://crbug.com/1130096): This should really be handled lower down in the stack.
if (tab.getBrowser().getActiveTab() != tab) return;
addSystemUiChangedObserver();
}
@VisibleForTesting
public boolean didShowFullscreenToast() {
return mDidShowToast;
}
public void destroy() {
// This may be called more than once.
if (mTab == null) return;
if (mSystemUiVisibilityChangeListener != null) {
// mSystemUiVisibilityChangeListener is only installed if mView is non-null.
assert mView != null;
mView.removeOnSystemUiVisibilityChangeListener(mSystemUiVisibilityChangeListener);
mSystemUiVisibilityChangeListener = null;
}
mTab = null;
mView = null;
if (mToast != null) {
mToast.cancel();
mToast = null;
}
}
private void addSystemUiChangedObserver() {
if (mTab.getBrowser().getBrowserFragment().getViewAndroidDelegateContainerView() == null) {
return;
}
mView = mTab.getBrowser().getBrowserFragment().getViewAndroidDelegateContainerView();
mSystemUiVisibilityChangeListener = new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
// The listener should have been removed if destroy() was called.
assert mTab != null;
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
// No longer in fullscreen. Destroy.
destroy();
} else if ((visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
&& !mDidShowToast) {
// Only show the toast when navigation is hidden and toast wasn't already shown.
showToast();
mDidShowToast = true;
}
}
};
mView.addOnSystemUiVisibilityChangeListener(mSystemUiVisibilityChangeListener);
// See class description for details on why a timeout is used.
mView.postDelayed(() -> {
if (!mDidShowToast) destroy();
}, 1000);
}
private void showToast() {
assert mToast == null;
mDidShowToast = true;
int resId = R.string.immersive_fullscreen_api_notification;
mToast = Toast.makeText(
mTab.getBrowser().getBrowserFragment().getWindowAndroid().getContext().get(), resId,
Toast.LENGTH_LONG);
mToast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 0);
mToast.show();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/FullscreenToast.java | Java | unknown | 3,964 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.Service;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import androidx.annotation.Nullable;
import org.chromium.base.Callback;
import org.chromium.base.ThreadUtils;
import org.chromium.components.metrics.AndroidMetricsLogConsumer;
import org.chromium.components.metrics.AndroidMetricsLogUploader;
/**
* This class manages functionality related to Google Mobile Services (i.e. GMS).
* Platform specific implementations are provided in GmsBridgeImpl.java.
*/
public abstract class GmsBridge {
private static GmsBridge sInstance;
private static final Object sInstanceLock = new Object();
private static HandlerThread sHandlerThread;
private static Handler sHandler;
private static final Object sHandlerLock = new Object();
protected GmsBridge() {
AndroidMetricsLogUploader.setConsumer(new AndroidMetricsLogConsumer() {
@Override
public int log(byte[] data) {
logMetrics(data);
// Just pass 200 (HTTP OK) and pretend everything is peachy.
return 200;
}
});
}
public static GmsBridge getInstance() {
synchronized (sInstanceLock) {
if (sInstance == null) {
// Load an instance of GmsBridgeImpl. Because this can change depending on
// the GN configuration, this may not be the GmsBridgeImpl defined upstream.
sInstance = new GmsBridgeImpl();
}
return sInstance;
}
}
// Provide a mocked GmsBridge for testing.
public static void injectInstance(GmsBridge testBridge) {
synchronized (sInstanceLock) {
sInstance = testBridge;
}
}
// Return a handler appropriate for executing blocking Platform Service tasks.
public static Handler getHandler() {
synchronized (sHandlerLock) {
if (sHandler == null) {
sHandlerThread = new HandlerThread("GmsBridgeHandlerThread");
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
}
return sHandler;
}
// Returns true if the WebLayer can use Google Mobile Services (GMS).
public boolean canUseGms() {
return false;
}
public void setSafeBrowsingHandler() {
// We don't have this specialized service here.
}
public void initializeBuiltInPaymentApps() {
// We don't have this specialized service here.
}
/** Creates an instance of GooglePayDataCallbacksService. */
@Nullable
public Service createGooglePayDataCallbacksService() {
// We don't have this specialized service here.
return null;
}
// Overriding implementations may call "callback" asynchronously. For simplicity (and not
// because of any technical limitation) we require that "queryMetricsSetting" and "callback"
// both get called on WebLayer's UI thread.
public void queryMetricsSetting(Callback<Boolean> callback) {
ThreadUtils.assertOnUiThread();
callback.onResult(false);
}
public void logMetrics(byte[] data) {}
/**
* Performs checks to make sure the client app context can load WebLayer. Throws an
* AndroidRuntimeException on failure.
*
* TODO(crbug.com/1192294): Consider moving this somewhere else since it doesn't use anything
* from GMS.
*/
public void checkClientAppContext(Context context) {}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/GmsBridge.java | Java | unknown | 3,731 |
// 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;
/**
* Instantiable version of {@link GmsBridge}, don't add anything to this class!
* Downstream targets may provide a different implementation.
*/
public class GmsBridgeImpl extends GmsBridge {}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/GmsBridgeImpl.java | Java | unknown | 382 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import android.webkit.ValueCallback;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.IGoogleAccountAccessTokenFetcherClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Owns the C++ GoogleAccountAccessTokenFetcherProxy class, which is responsible for forwarding all
* access token fetches made from C++ to this class, which in turn forwards to the
* GoogleAccountAccessTokenFetcherClient.
*/
@JNINamespace("weblayer")
public final class GoogleAccountAccessTokenFetcherProxy {
private long mNativeGoogleAccountAccessTokenFetcherProxy;
private IGoogleAccountAccessTokenFetcherClient mClient;
GoogleAccountAccessTokenFetcherProxy(ProfileImpl profile) {
mNativeGoogleAccountAccessTokenFetcherProxy =
GoogleAccountAccessTokenFetcherProxyJni.get()
.createGoogleAccountAccessTokenFetcherProxy(
this, profile.getNativeProfile());
}
public void setClient(IGoogleAccountAccessTokenFetcherClient client) {
mClient = client;
}
public void destroy() {
GoogleAccountAccessTokenFetcherProxyJni.get().deleteGoogleAccountAccessTokenFetcherProxy(
mNativeGoogleAccountAccessTokenFetcherProxy);
mNativeGoogleAccountAccessTokenFetcherProxy = 0;
}
/*
* Proxies fetchAccessToken() calls to the client. Returns the empty string if the client is not
* set.
*/
public void fetchAccessToken(Set<String> scopes, ValueCallback<String> onTokenFetchedCallback)
throws RemoteException {
if (mClient == null) {
onTokenFetchedCallback.onReceiveValue("");
return;
}
mClient.fetchAccessToken(
ObjectWrapper.wrap(scopes), ObjectWrapper.wrap(onTokenFetchedCallback));
}
/*
* Proxies onAccessTokenIdentifiedAsInvalid() calls to the client if it is set.
*/
public void onAccessTokenIdentifiedAsInvalid(Set<String> scopes, String token)
throws RemoteException {
if (WebLayerFactoryImpl.getClientMajorVersion() < 93) return;
if (mClient == null) return;
mClient.onAccessTokenIdentifiedAsInvalid(
ObjectWrapper.wrap(scopes), ObjectWrapper.wrap(token));
}
/*
* Proxies access token requests from C++ to the public fetchAccessToken() interface.
*/
@CalledByNative
private void fetchAccessToken(String[] scopes, long callbackId) throws RemoteException {
ValueCallback<String> onTokenFetchedCallback = (String token) -> {
GoogleAccountAccessTokenFetcherProxyJni.get().runOnTokenFetchedCallback(
callbackId, token);
};
fetchAccessToken(new HashSet<String>(Arrays.asList(scopes)), onTokenFetchedCallback);
}
/*
* Proxies invalid access token notifications from C++ to the public interface.
*/
@CalledByNative
private void onAccessTokenIdentifiedAsInvalid(String[] scopes, String token)
throws RemoteException {
onAccessTokenIdentifiedAsInvalid(new HashSet<String>(Arrays.asList(scopes)), token);
}
@NativeMethods
interface Natives {
long createGoogleAccountAccessTokenFetcherProxy(
GoogleAccountAccessTokenFetcherProxy proxy, long profile);
void deleteGoogleAccountAccessTokenFetcherProxy(long proxy);
void runOnTokenFetchedCallback(long callbackId, String token);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/GoogleAccountAccessTokenFetcherProxy.java | Java | unknown | 3,921 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.signin.GAIAServiceType;
import org.chromium.weblayer_private.interfaces.GoogleAccountServiceType;
import org.chromium.weblayer_private.interfaces.IGoogleAccountsCallbackClient;
/**
* Owns the C++ GoogleAccountsCallbackProxy which is responsible for forwarding all calls to this
* class.
*/
@JNINamespace("weblayer")
public final class GoogleAccountsCallbackProxy {
private long mNativeGoogleAccountsCallbackProxy;
private IGoogleAccountsCallbackClient mClient;
GoogleAccountsCallbackProxy(long tab, IGoogleAccountsCallbackClient client) {
assert client != null;
mClient = client;
mNativeGoogleAccountsCallbackProxy =
GoogleAccountsCallbackProxyJni.get().createGoogleAccountsCallbackProxy(this, tab);
}
public void setClient(IGoogleAccountsCallbackClient client) {
assert client != null;
mClient = client;
}
public void destroy() {
GoogleAccountsCallbackProxyJni.get().deleteGoogleAccountsCallbackProxy(
mNativeGoogleAccountsCallbackProxy);
mNativeGoogleAccountsCallbackProxy = 0;
}
@CalledByNative
private void onGoogleAccountsRequest(@GAIAServiceType int serviceType, String email,
String continueUrl, boolean isSameTab) throws RemoteException {
mClient.onGoogleAccountsRequest(
implTypeToJavaType(serviceType), email, continueUrl, isSameTab);
}
@CalledByNative
private String getGaiaId() throws RemoteException {
return mClient.getGaiaId();
}
@GoogleAccountServiceType
private static int implTypeToJavaType(@GAIAServiceType int type) {
switch (type) {
case GAIAServiceType.GAIA_SERVICE_TYPE_SIGNOUT:
return GoogleAccountServiceType.SIGNOUT;
case GAIAServiceType.GAIA_SERVICE_TYPE_ADDSESSION:
return GoogleAccountServiceType.ADD_SESSION;
// SIGNUP and INCOGNITO should not be possible currently, so pass through to DEFAULT.
case GAIAServiceType.GAIA_SERVICE_TYPE_SIGNUP:
case GAIAServiceType.GAIA_SERVICE_TYPE_INCOGNITO:
case GAIAServiceType.GAIA_SERVICE_TYPE_DEFAULT:
return GoogleAccountServiceType.DEFAULT;
}
assert false;
return GoogleAccountServiceType.DEFAULT;
}
@NativeMethods
interface Natives {
long createGoogleAccountsCallbackProxy(GoogleAccountsCallbackProxy proxy, long tab);
void deleteGoogleAccountsCallbackProxy(long proxy);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/GoogleAccountsCallbackProxy.java | Java | unknown | 2,944 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.browser_ui.http_auth.LoginPrompt;
import org.chromium.url.GURL;
/**
* Handles showing http auth prompt.
*/
@JNINamespace("weblayer")
public final class HttpAuthHandlerImpl implements LoginPrompt.Observer {
private long mNativeHttpAuthHandlerImpl;
private LoginPrompt mLoginPrompt;
@CalledByNative
public static HttpAuthHandlerImpl create(long nativeAuthHandler, TabImpl tab, GURL url) {
return new HttpAuthHandlerImpl(nativeAuthHandler, tab.getBrowser().getContext(), url);
}
@CalledByNative
void handlerDestroyed() {
mNativeHttpAuthHandlerImpl = 0;
}
@CalledByNative
private void closeDialog() {
if (mLoginPrompt != null) mLoginPrompt.dismiss();
}
private HttpAuthHandlerImpl(long nativeHttpAuthHandlerImpl, Context context, GURL url) {
mNativeHttpAuthHandlerImpl = nativeHttpAuthHandlerImpl;
mLoginPrompt = new LoginPrompt(context, url.getHost(), url, this);
mLoginPrompt.show();
}
@Override
public void proceed(String username, String password) {
if (mNativeHttpAuthHandlerImpl != 0) {
HttpAuthHandlerImplJni.get().proceed(mNativeHttpAuthHandlerImpl, username, password);
}
}
@Override
public void cancel() {
if (mNativeHttpAuthHandlerImpl != 0) {
HttpAuthHandlerImplJni.get().cancel(mNativeHttpAuthHandlerImpl);
}
}
@NativeMethods
interface Natives {
void proceed(long nativeHttpAuthHandlerImpl, String username, String password);
void cancel(long nativeHttpAuthHandlerImpl);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/HttpAuthHandlerImpl.java | Java | unknown | 2,007 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.ObserverList;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.chrome.browser.infobar.InfoBarIdentifier;
import org.chromium.components.infobars.InfoBar;
import org.chromium.components.infobars.InfoBarAnimationListener;
import org.chromium.components.infobars.InfoBarUiItem;
import org.chromium.content_public.browser.NavigationHandle;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;
import org.chromium.ui.KeyboardVisibilityDelegate.KeyboardVisibilityListener;
import org.chromium.ui.util.AccessibilityUtil;
import java.util.ArrayList;
/**
* A container for all the infobars of a specific tab.
* Note that infobars creation can be initiated from Java or from native code.
* When initiated from native code, special code is needed to keep the Java and native infobar in
* sync, see NativeInfoBar.
*/
@JNINamespace("weblayer")
public class InfoBarContainer implements KeyboardVisibilityListener, InfoBar.Container {
private static final String TAG = "InfoBarContainer";
// Number of instances that have not been destroyed.
private static int sInstanceCount;
// InfoBarContainer's handling of accessibility is a global toggle, and thus a static observer
// suffices. However, observing accessibility events has the wrinkle that all accessibility
// observers are removed when there are no more Browsers and are not re-added if a new Browser
// is subsequently created. To handle this wrinkle, |sAccessibilityObserver| is added as an
// observer whenever the number of non-destroyed InfoBarContainers becomes non-zero and removed
// whenever that number flips to zero.
private static final AccessibilityUtil.Observer sAccessibilityObserver;
static {
sAccessibilityObserver = (enabled) -> setIsAllowedToAutoHide(!enabled);
}
/**
* An observer that is notified of changes to a {@link InfoBarContainer} object.
*/
public interface InfoBarContainerObserver {
/**
* Called when an {@link InfoBar} is about to be added (before the animation).
* @param container The notifying {@link InfoBarContainer}
* @param infoBar An {@link InfoBar} being added
* @param isFirst Whether the infobar container was empty
*/
void onAddInfoBar(InfoBarContainer container, InfoBar infoBar, boolean isFirst);
/**
* Called when an {@link InfoBar} is about to be removed (before the animation).
* @param container The notifying {@link InfoBarContainer}
* @param infoBar An {@link InfoBar} being removed
* @param isLast Whether the infobar container is going to be empty
*/
void onRemoveInfoBar(InfoBarContainer container, InfoBar infoBar, boolean isLast);
/**
* Called when the InfobarContainer is attached to the window.
* @param hasInfobars True if infobar container has infobars to show.
*/
void onInfoBarContainerAttachedToWindow(boolean hasInfobars);
/**
* A notification that the shown ratio of the infobar container has changed.
* @param container The notifying {@link InfoBarContainer}
* @param shownRatio The shown ratio of the infobar container.
*/
void onInfoBarContainerShownRatioChanged(InfoBarContainer container, float shownRatio);
}
/**
* Resets the visibility of the InfoBarContainer when the user navigates, following Chrome's
* behavior. In particular in Chrome some features hide the infobar container. This hiding is
* always on a per-URL basis that should be undone on navigation. While no feature in WebLayer
* yet does this, we put this * defensive behavior in place so that any such added features
* don't end up inadvertently hiding the infobar container "forever" in a given tab.
*/
private final WebContentsObserver mWebContentsObserver = new WebContentsObserver() {
@Override
public void didFinishNavigationInPrimaryMainFrame(NavigationHandle navigation) {
if (navigation.hasCommitted()) {
setHidden(false);
}
}
};
public void onTabAttachedToViewController() {
initializeContainerView(mTab.getBrowser().getContext());
updateWebContents();
mInfoBarContainerView.addToParentView();
}
public void onTabDetachedFromViewController() {
mInfoBarContainerView.removeFromParentView();
destroyContainerView();
}
/** The list of all InfoBars in this container, regardless of whether they've been shown yet. */
private final ArrayList<InfoBar> mInfoBars = new ArrayList<>();
private final ObserverList<InfoBarContainerObserver> mObservers = new ObserverList<>();
private final ObserverList<InfoBarAnimationListener> mAnimationListeners = new ObserverList<>();
private final InfoBarContainerView.ContainerViewObserver mContainerViewObserver =
new InfoBarContainerView.ContainerViewObserver() {
@Override
public void notifyAnimationFinished(int animationType) {
for (InfoBarAnimationListener listener : mAnimationListeners) {
listener.notifyAnimationFinished(animationType);
}
}
@Override
public void notifyAllAnimationsFinished(InfoBarUiItem frontInfoBar) {
for (InfoBarAnimationListener listener : mAnimationListeners) {
listener.notifyAllAnimationsFinished(frontInfoBar);
}
}
@Override
public void onShownRatioChanged(float shownFraction) {
for (InfoBarContainer.InfoBarContainerObserver observer : mObservers) {
observer.onInfoBarContainerShownRatioChanged(
InfoBarContainer.this, shownFraction);
}
}
};
/** The tab that hosts this infobar container. */
private final TabImpl mTab;
/** Native InfoBarContainer pointer which will be set by InfoBarContainerJni.get().init(). */
private long mNativeInfoBarContainer;
/** True when this container has been emptied and its native counterpart has been destroyed. */
private boolean mDestroyed;
/** Whether or not this View should be hidden. */
private boolean mIsHidden;
/**
* The view for this {@link InfoBarContainer}. It will be null when the {@link Tab} is detached
* from a {@link ChromeActivity}.
*/
private @Nullable InfoBarContainerView mInfoBarContainerView;
InfoBarContainer(TabImpl tab) {
if (++sInstanceCount == 1) {
WebLayerAccessibilityUtil.get().addObserver(sAccessibilityObserver);
}
mTab = tab;
mTab.getWebContents().addObserver(mWebContentsObserver);
// Chromium's InfoBarContainer may add an InfoBar immediately during this initialization
// call, so make sure everything in the InfoBarContainer is completely ready beforehand.
mNativeInfoBarContainer = InfoBarContainerJni.get().init(InfoBarContainer.this);
}
/**
* Adds an {@link InfoBarContainerObserver}.
* @param observer The {@link InfoBarContainerObserver} to add.
*/
public void addObserver(InfoBarContainerObserver observer) {
mObservers.addObserver(observer);
}
/**
* Removes a {@link InfoBarContainerObserver}.
* @param observer The {@link InfoBarContainerObserver} to remove.
*/
public void removeObserver(InfoBarContainerObserver observer) {
mObservers.removeObserver(observer);
}
/**
* Sets the parent {@link ViewGroup} that contains the {@link InfoBarContainer}.
*/
public void setParentView(ViewGroup parent) {
assert mTab.getBrowser().getActiveTab() == mTab;
if (mInfoBarContainerView != null) mInfoBarContainerView.setParentView(parent);
}
@VisibleForTesting
public void addAnimationListener(InfoBarAnimationListener listener) {
mAnimationListeners.addObserver(listener);
}
/**
* Removes the passed in {@link InfoBarAnimationListener} from the {@link InfoBarContainer}.
*/
public void removeAnimationListener(InfoBarAnimationListener listener) {
mAnimationListeners.removeObserver(listener);
}
/**
* Adds an InfoBar to the view hierarchy.
* @param infoBar InfoBar to add to the View hierarchy.
*/
@CalledByNative
private void addInfoBar(InfoBar infoBar) {
assert !mDestroyed;
if (infoBar == null) {
return;
}
if (mInfoBars.contains(infoBar)) {
assert false : "Trying to add an info bar that has already been added.";
return;
}
infoBar.setContext(mInfoBarContainerView.getContext());
infoBar.setContainer(this);
// We notify observers immediately (before the animation starts).
for (InfoBarContainerObserver observer : mObservers) {
observer.onAddInfoBar(this, infoBar, mInfoBars.isEmpty());
}
assert mInfoBarContainerView != null : "The container view is null when adding an InfoBar";
// We add the infobar immediately to mInfoBars but we wait for the animation to end to
// notify it's been added, as tests rely on this notification but expects the infobar view
// to be available when they get the notification.
mInfoBars.add(infoBar);
mInfoBarContainerView.addInfoBar(infoBar);
}
@VisibleForTesting
public View getViewForTesting() {
return mInfoBarContainerView;
}
/**
* Adds an InfoBar to the view hierarchy.
* @param infoBar InfoBar to add to the View hierarchy.
*/
@VisibleForTesting
public void addInfoBarForTesting(InfoBar infoBar) {
addInfoBar(infoBar);
}
@Override
public void notifyInfoBarViewChanged() {
assert !mDestroyed;
if (mInfoBarContainerView != null) mInfoBarContainerView.notifyInfoBarViewChanged();
}
/**
* Sets the visibility for the {@link InfoBarContainerView}.
* @param visibility One of {@link View#GONE}, {@link View#INVISIBLE}, or {@link View#VISIBLE}.
*/
public void setVisibility(int visibility) {
if (mInfoBarContainerView != null) mInfoBarContainerView.setVisibility(visibility);
}
/**
* @return The visibility of the {@link InfoBarContainerView}.
*/
public int getVisibility() {
return mInfoBarContainerView != null ? mInfoBarContainerView.getVisibility() : View.GONE;
}
@Override
public void removeInfoBar(InfoBar infoBar) {
assert !mDestroyed;
if (!mInfoBars.remove(infoBar)) {
assert false : "Trying to remove an InfoBar that is not in this container.";
return;
}
// Notify observers immediately, before any animations begin.
for (InfoBarContainerObserver observer : mObservers) {
observer.onRemoveInfoBar(this, infoBar, mInfoBars.isEmpty());
}
assert mInfoBarContainerView
!= null : "The container view is null when removing an InfoBar.";
mInfoBarContainerView.removeInfoBar(infoBar);
}
@Override
public boolean isDestroyed() {
return mDestroyed;
}
public void destroy() {
mTab.getWebContents().removeObserver(mWebContentsObserver);
if (--sInstanceCount == 0) {
WebLayerAccessibilityUtil.get().removeObserver(sAccessibilityObserver);
}
if (mInfoBarContainerView != null) destroyContainerView();
if (mNativeInfoBarContainer != 0) {
InfoBarContainerJni.get().destroy(mNativeInfoBarContainer, InfoBarContainer.this);
mNativeInfoBarContainer = 0;
}
mDestroyed = true;
}
/**
* @return all of the InfoBars held in this container.
*/
@VisibleForTesting
public ArrayList<InfoBar> getInfoBarsForTesting() {
return mInfoBars;
}
/**
* @return True if the container has any InfoBars.
*/
@CalledByNative
public boolean hasInfoBars() {
return !mInfoBars.isEmpty();
}
/**
* @return InfoBarIdentifier of the InfoBar which is currently at the top of the infobar stack,
* or InfoBarIdentifier.INVALID if there are no infobars.
*/
@CalledByNative
private @InfoBarIdentifier int getTopInfoBarIdentifier() {
if (!hasInfoBars()) return InfoBarIdentifier.INVALID;
return mInfoBars.get(0).getInfoBarIdentifier();
}
/**
* Hides or stops hiding this View.
*
* @param isHidden Whether this View is should be hidden.
*/
public void setHidden(boolean isHidden) {
mIsHidden = isHidden;
if (mInfoBarContainerView == null) return;
mInfoBarContainerView.setHidden(isHidden);
}
/**
* Sets whether the InfoBarContainer is allowed to auto-hide when the user scrolls the page.
* Expected to be called when Touch Exploration is enabled.
* @param isAllowed Whether auto-hiding is allowed.
*/
private static void setIsAllowedToAutoHide(boolean isAllowed) {
InfoBarContainerView.setIsAllowedToAutoHide(isAllowed);
}
// KeyboardVisibilityListener implementation.
@Override
public void keyboardVisibilityChanged(boolean isKeyboardShowing) {
assert mInfoBarContainerView != null;
boolean isShowing = (mInfoBarContainerView.getVisibility() == View.VISIBLE);
if (isKeyboardShowing) {
if (isShowing) {
mInfoBarContainerView.setVisibility(View.INVISIBLE);
}
} else {
if (!isShowing && !mIsHidden) {
mInfoBarContainerView.setVisibility(View.VISIBLE);
}
}
}
private void updateWebContents() {
// When the tab is detached, we don't update the InfoBarContainer web content so that it
// stays null until the tab is attached to some ChromeActivity.
if (mInfoBarContainerView == null) return;
WebContents webContents = mTab.getWebContents();
if (webContents != null && webContents != mInfoBarContainerView.getWebContents()) {
mInfoBarContainerView.setWebContents(webContents);
if (mNativeInfoBarContainer != 0) {
InfoBarContainerJni.get().setWebContents(
mNativeInfoBarContainer, InfoBarContainer.this, webContents);
}
}
}
private void initializeContainerView(Context chromeActivity) {
assert chromeActivity
!= null
: "ChromeActivity should not be null when initializing InfoBarContainerView";
mInfoBarContainerView = new InfoBarContainerView(chromeActivity, mContainerViewObserver,
mTab, /*isTablet=*/!mTab.getBrowser().isWindowOnSmallDevice());
mInfoBarContainerView.addOnAttachStateChangeListener(
new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View view) {
for (InfoBarContainer.InfoBarContainerObserver observer : mObservers) {
observer.onInfoBarContainerAttachedToWindow(!mInfoBars.isEmpty());
}
}
@Override
public void onViewDetachedFromWindow(View view) {}
});
mInfoBarContainerView.setHidden(mIsHidden);
BrowserViewController viewController =
mTab.getBrowser().getBrowserFragment().getPossiblyNullViewController();
if (viewController != null) {
setParentView(viewController.getInfoBarContainerParentView());
}
mTab.getBrowser()
.getBrowserFragment()
.getWindowAndroid()
.getKeyboardDelegate()
.addKeyboardVisibilityListener(this);
}
private void destroyContainerView() {
if (mInfoBarContainerView != null) {
mInfoBarContainerView.setWebContents(null);
if (mNativeInfoBarContainer != 0) {
InfoBarContainerJni.get().setWebContents(
mNativeInfoBarContainer, InfoBarContainer.this, null);
}
mInfoBarContainerView.destroy();
mInfoBarContainerView = null;
}
mTab.getBrowser()
.getBrowserFragment()
.getWindowAndroid()
.getKeyboardDelegate()
.removeKeyboardVisibilityListener(this);
}
@Override
public boolean isFrontInfoBar(InfoBar infoBar) {
if (mInfoBars.isEmpty()) return false;
return mInfoBars.get(0) == infoBar;
}
/**
* Returns true if any animations are pending or in progress.
*/
@VisibleForTesting
public boolean isAnimating() {
assert mInfoBarContainerView != null;
return mInfoBarContainerView.isAnimating();
}
/**
* @return The {@link InfoBarContainerView} this class holds.
*/
@VisibleForTesting
public InfoBarContainerView getContainerViewForTesting() {
return mInfoBarContainerView;
}
@NativeMethods
interface Natives {
long init(InfoBarContainer caller);
void setWebContents(long nativeInfoBarContainerAndroid, InfoBarContainer caller,
WebContents webContents);
void destroy(long nativeInfoBarContainerAndroid, InfoBarContainer caller);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/InfoBarContainer.java | Java | unknown | 18,277 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.MathUtils;
import org.chromium.components.browser_ui.banners.SwipableOverlayView;
import org.chromium.components.infobars.InfoBar;
import org.chromium.components.infobars.InfoBarAnimationListener;
import org.chromium.components.infobars.InfoBarContainerLayout;
import org.chromium.components.infobars.InfoBarUiItem;
import org.chromium.ui.display.DisplayAndroid;
import org.chromium.ui.display.DisplayUtil;
/**
* The {@link View} for the {@link InfoBarContainer}.
*/
public class InfoBarContainerView extends SwipableOverlayView {
/**
* Observes container view changes.
*/
public interface ContainerViewObserver extends InfoBarAnimationListener {
/**
* Called when the height of shown content changed.
* @param shownFraction The ratio of height of shown content to the height of the container
* view.
*/
void onShownRatioChanged(float shownFraction);
}
/** Top margin, including the toolbar and tabstrip height and 48dp of web contents. */
private static final int TOP_MARGIN_PHONE_DP = 104;
private static final int TOP_MARGIN_TABLET_DP = 144;
/** Length of the animation to fade the InfoBarContainer back into View. */
private static final long REATTACH_FADE_IN_MS = 250;
/** Whether or not the InfoBarContainer is allowed to hide when the user scrolls. */
private static boolean sIsAllowedToAutoHide = true;
private final ContainerViewObserver mContainerViewObserver;
private final InfoBarContainerLayout mLayout;
/** Parent view that contains the InfoBarContainerLayout. */
private ViewGroup mParentView;
private TabImpl mTab;
/** Animation used to snap the container to the nearest state if scroll direction changes. */
private Animator mScrollDirectionChangeAnimation;
/** Whether or not the current scroll is downward. */
private boolean mIsScrollingDownward;
/** Tracks the previous event's scroll offset to determine if a scroll is up or down. */
private int mLastScrollOffsetY;
/**
* @param context The {@link Context} that this view is attached to.
* @param containerViewObserver The {@link ContainerViewObserver} that gets notified on
* container view changes.
* @param isTablet Whether this view is displayed on tablet or not.
*/
InfoBarContainerView(@NonNull Context context,
@NonNull ContainerViewObserver containerViewObserver, TabImpl tab, boolean isTablet) {
super(context, null);
mTab = tab;
mContainerViewObserver = containerViewObserver;
// TODO(newt): move this workaround into the infobar views if/when they're scrollable.
// Workaround for http://crbug.com/407149. See explanation in onMeasure() below.
setVerticalScrollBarEnabled(false);
updateLayoutParams(context, isTablet);
Runnable makeContainerVisibleRunnable = () -> runUpEventAnimation(true);
mLayout = new InfoBarContainerLayout(
context, makeContainerVisibleRunnable, new InfoBarAnimationListener() {
@Override
public void notifyAnimationFinished(int animationType) {
mContainerViewObserver.notifyAnimationFinished(animationType);
}
@Override
public void notifyAllAnimationsFinished(InfoBarUiItem frontInfoBar) {
mContainerViewObserver.notifyAllAnimationsFinished(frontInfoBar);
}
});
addView(mLayout,
new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
Gravity.CENTER_HORIZONTAL));
}
void destroy() {
removeFromParentView();
mTab = null;
}
// SwipableOverlayView implementation.
@Override
@VisibleForTesting
public boolean isAllowedToAutoHide() {
return sIsAllowedToAutoHide;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (getVisibility() != View.GONE) {
setVisibility(VISIBLE);
setAlpha(0f);
animate().alpha(1f).setDuration(REATTACH_FADE_IN_MS);
}
}
@Override
protected void runUpEventAnimation(boolean visible) {
if (mScrollDirectionChangeAnimation != null) mScrollDirectionChangeAnimation.cancel();
super.runUpEventAnimation(visible);
}
@Override
protected boolean isIndependentlyAnimating() {
return mScrollDirectionChangeAnimation != null;
}
// View implementation.
@Override
public void setTranslationY(float translationY) {
int contentHeightDelta = 0; // No bottom bar.
// Push the infobar container up by any delta caused by the bottom toolbar while ensuring
// that it does not ascend beyond the top of the bottom toolbar nor descend beyond its own
// height.
float newTranslationY = MathUtils.clamp(
translationY - contentHeightDelta, -contentHeightDelta, getHeight());
super.setTranslationY(newTranslationY);
float shownFraction = 0;
if (getHeight() > 0) {
shownFraction = contentHeightDelta > 0 ? 1f : 1f - (translationY / getHeight());
}
mContainerViewObserver.onShownRatioChanged(shownFraction);
}
/**
* Sets whether the InfoBarContainer is allowed to auto-hide when the user scrolls the page.
* Expected to be called when Touch Exploration is enabled.
* @param isAllowed Whether auto-hiding is allowed.
*/
public static void setIsAllowedToAutoHide(boolean isAllowed) {
sIsAllowedToAutoHide = isAllowed;
}
/**
* Notifies that an infobar's View ({@link InfoBar#getView}) has changed. If the infobar is
* visible, a view swapping animation will be run.
*/
void notifyInfoBarViewChanged() {
mLayout.notifyInfoBarViewChanged();
}
/**
* Sets the parent {@link ViewGroup} that contains the {@link InfoBarContainer}.
*/
void setParentView(ViewGroup parent) {
mParentView = parent;
// Don't attach the container to the new parent if it is not previously attached.
if (removeFromParentView()) addToParentView();
}
/**
* Adds this class to the parent view {@link #mParentView}.
*/
void addToParentView() {
// If mTab is null, destroy() was called. This should not be added after destroyed.
assert mTab != null;
BrowserViewController viewController =
mTab.getBrowser().getBrowserFragment().getPossiblyNullViewController();
if (viewController != null) {
super.addToParentViewAtIndex(
mParentView, viewController.getDesiredInfoBarContainerViewIndex());
}
}
/**
* Adds an {@link InfoBar} to the layout.
* @param infoBar The {@link InfoBar} to be added.
*/
void addInfoBar(InfoBar infoBar) {
infoBar.createView();
mLayout.addInfoBar(infoBar);
}
/**
* Removes an {@link InfoBar} from the layout.
* @param infoBar The {@link InfoBar} to be removed.
*/
void removeInfoBar(InfoBar infoBar) {
mLayout.removeInfoBar(infoBar);
}
/**
* Hides or stops hiding this View.
* @param isHidden Whether this View is should be hidden.
*/
void setHidden(boolean isHidden) {
setVisibility(isHidden ? View.GONE : View.VISIBLE);
}
/**
* Run an animation when the scrolling direction of a gesture has changed (this does not mean
* the gesture has ended).
* @param visible Whether or not the view should be visible.
*/
private void runDirectionChangeAnimation(boolean visible) {
mScrollDirectionChangeAnimation = createVerticalSnapAnimation(visible);
mScrollDirectionChangeAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mScrollDirectionChangeAnimation = null;
}
});
mScrollDirectionChangeAnimation.start();
}
@Override
// Ensure that this view's custom layout params are passed when adding it to its parent.
public ViewGroup.MarginLayoutParams createLayoutParams() {
return (ViewGroup.MarginLayoutParams) getLayoutParams();
}
private void updateLayoutParams(Context context, boolean isTablet) {
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
int topMarginDp = isTablet ? TOP_MARGIN_TABLET_DP : TOP_MARGIN_PHONE_DP;
lp.topMargin = DisplayUtil.dpToPx(DisplayAndroid.getNonMultiDisplay(context), topMarginDp);
setLayoutParams(lp);
}
/**
* Returns true if any animations are pending or in progress.
*/
@VisibleForTesting
public boolean isAnimating() {
return mLayout.isAnimating();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/InfoBarContainerView.java | Java | unknown | 9,747 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.components.installedapp.InstalledAppProviderImpl;
import org.chromium.content_public.browser.RenderFrameHost;
import org.chromium.content_public.browser.WebContentsStatics;
import org.chromium.installedapp.mojom.InstalledAppProvider;
import org.chromium.services.service_manager.InterfaceFactory;
/** Factory to create instances of the InstalledAppProvider Mojo service. */
public class InstalledAppProviderFactory implements InterfaceFactory<InstalledAppProvider> {
private final RenderFrameHost mRenderFrameHost;
public InstalledAppProviderFactory(RenderFrameHost renderFrameHost) {
mRenderFrameHost = renderFrameHost;
}
@Override
public InstalledAppProvider createImpl() {
TabImpl tab =
TabImpl.fromWebContents(WebContentsStatics.fromRenderFrameHost(mRenderFrameHost));
if (tab == null) return null;
return new InstalledAppProviderImpl(
tab.getProfile(), mRenderFrameHost, (unusedA, unusedB, unusedC) -> false);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/InstalledAppProviderFactory.java | Java | unknown | 1,214 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Intent;
import android.os.RemoteException;
import android.util.AndroidRuntimeException;
/** A utility class for creating and handling common intents. */
public class IntentUtils {
private static final String sExtraTabId = "TAB_ID";
private static final String sActivateTabAction =
"org.chromium.weblayer.intent_utils.ACTIVATE_TAB";
/**
* Handles an intent generated by this class.
* @return true if the intent was handled, or false if the intent wasn't generated by this
* class.
*/
public static boolean handleIntent(Intent intent) {
if (!intent.getAction().equals(sActivateTabAction)) return false;
int tabId = intent.getIntExtra(sExtraTabId, -1);
TabImpl tab = TabImpl.getTabById(tabId);
if (tab == null) return true;
try {
tab.getClient().bringTabToFront();
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
return true;
}
/**
* Creates an intent to bring a tab to the foreground.
* This intent should also bring the app to the foreground.
* @param tabId the identifier for the tab.
*/
public static Intent createBringTabToFrontIntent(int tabId) {
Intent intent = WebLayerImpl.createIntent();
intent.putExtra(sExtraTabId, tabId);
intent.setAction(sActivateTabAction);
return intent;
}
};
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/IntentUtils.java | Java | unknown | 1,636 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.Activity;
import android.os.SystemClock;
import org.chromium.base.ContextUtils;
import org.chromium.components.external_intents.ExternalNavigationHandler;
import org.chromium.components.external_intents.ExternalNavigationHandler.OverrideUrlLoadingAsyncActionType;
import org.chromium.components.external_intents.ExternalNavigationHandler.OverrideUrlLoadingResult;
import org.chromium.components.external_intents.ExternalNavigationHandler.OverrideUrlLoadingResultType;
import org.chromium.components.external_intents.InterceptNavigationDelegateClient;
import org.chromium.components.external_intents.InterceptNavigationDelegateImpl;
import org.chromium.components.external_intents.RedirectHandler;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.NavigationHandle;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;
/**
* Class that provides embedder-level information to InterceptNavigationDelegateImpl based off a
* Tab.
*/
public class InterceptNavigationDelegateClientImpl implements InterceptNavigationDelegateClient {
private TabImpl mTab;
private WebContentsObserver mWebContentsObserver;
private RedirectHandler mRedirectHandler;
private InterceptNavigationDelegateImpl mInterceptNavigationDelegate;
private long mLastNavigationWithUserGestureTime = RedirectHandler.INVALID_TIME;
private boolean mDestroyed;
InterceptNavigationDelegateClientImpl(TabImpl tab) {
mTab = tab;
mRedirectHandler = RedirectHandler.create();
mWebContentsObserver = new WebContentsObserver() {
@Override
public void didFinishNavigationInPrimaryMainFrame(NavigationHandle navigationHandle) {
mInterceptNavigationDelegate.onNavigationFinishedInPrimaryMainFrame(
navigationHandle);
}
};
}
public void initializeWithDelegate(InterceptNavigationDelegateImpl delegate) {
mInterceptNavigationDelegate = delegate;
getWebContents().addObserver(mWebContentsObserver);
}
public void onActivityAttachmentChanged(boolean attached) {
if (attached) {
mInterceptNavigationDelegate.setExternalNavigationHandler(
createExternalNavigationHandler());
}
}
public void destroy() {
mDestroyed = true;
getWebContents().removeObserver(mWebContentsObserver);
mInterceptNavigationDelegate.associateWithWebContents(null);
}
@Override
public WebContents getWebContents() {
return mTab.getWebContents();
}
@Override
public ExternalNavigationHandler createExternalNavigationHandler() {
return new ExternalNavigationHandler(new ExternalNavigationDelegateImpl(mTab));
}
@Override
public long getLastUserInteractionTime() {
// NOTE: Chrome listens for user interaction with its Activity. However, this depends on
// being able to subclass the Activity, which is not possible in WebLayer. As a proxy,
// WebLayer uses the time of the last navigation with a user gesture to serve as the last
// time of user interaction. Note that the user interacting with the webpage causes the
// user gesture bit to be set on any navigation in that page for the next several seconds
// (cf. comments on //third_party/blink/public/common/frame/user_activation_state.h). This
// fact further increases the fidelity of this already-reasonable heuristic as a proxy. To
// date we have not seen any concrete evidence of user-visible differences resulting from
// the use of the different heuristic.
return mLastNavigationWithUserGestureTime;
}
@Override
public RedirectHandler getOrCreateRedirectHandler() {
return mRedirectHandler;
}
@Override
public boolean isIncognito() {
return mTab.getProfile().isIncognito();
}
@Override
public boolean areIntentLaunchesAllowedInHiddenTabsForNavigation(
NavigationHandle navigationHandle) {
NavigationImpl navigation = mTab.getNavigationControllerImpl().getNavigationImplFromId(
navigationHandle.getNavigationId());
if (navigation == null) return false;
return navigation.areIntentLaunchesAllowedInBackground();
}
@Override
public Activity getActivity() {
return ContextUtils.activityFromContext(mTab.getBrowser().getContext());
}
@Override
public boolean wasTabLaunchedFromExternalApp() {
return false;
}
@Override
public boolean wasTabLaunchedFromLongPressInBackground() {
return false;
}
@Override
public void closeTab() {
// When InterceptNavigationDelegate determines that a tab needs to be closed, it posts a
// task invoking this method. It is possible that in the interim the tab was closed for
// another reason. In that case there is nothing more to do here.
if (mDestroyed) return;
closeTab(mTab);
}
@Override
public void onNavigationStarted(NavigationHandle navigationHandle) {
if (navigationHandle.hasUserGesture()) {
mLastNavigationWithUserGestureTime = SystemClock.elapsedRealtime();
}
}
@Override
public void onDecisionReachedForNavigation(
NavigationHandle navigationHandle, OverrideUrlLoadingResult overrideUrlLoadingResult) {
NavigationImpl navigation = mTab.getNavigationControllerImpl().getNavigationImplFromId(
navigationHandle.getNavigationId());
// As the navigation is still ongoing at this point there should be a NavigationImpl
// instance for it.
assert navigation != null;
switch (overrideUrlLoadingResult.getResultType()) {
case OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT:
navigation.setIntentLaunched();
break;
case OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION:
if (overrideUrlLoadingResult.getAsyncActionType()
== OverrideUrlLoadingAsyncActionType.UI_GATING_INTENT_LAUNCH) {
navigation.setIsUserDecidingIntentLaunch();
}
break;
case OverrideUrlLoadingResultType.OVERRIDE_WITH_NAVIGATE_TAB:
case OverrideUrlLoadingResultType.NO_OVERRIDE:
default:
break;
}
}
static void closeTab(TabImpl tab) {
tab.getBrowser().destroyTab(tab);
}
@Override
public void loadUrlIfPossible(LoadUrlParams loadUrlParams) {
if (mDestroyed) return;
mTab.loadUrl(loadUrlParams);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/InterceptNavigationDelegateClientImpl.java | Java | unknown | 7,007 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
/**
* Triggered when Android's locale changes.
*/
@JNINamespace("weblayer::i18n")
public class LocaleChangedBroadcastReceiver extends BroadcastReceiver {
private final Context mContext;
public LocaleChangedBroadcastReceiver(Context context) {
mContext = context;
ContextUtils.registerProtectedBroadcastReceiver(
mContext, this, new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
}
public void destroy() {
mContext.unregisterReceiver(this);
}
@Override
public void onReceive(Context context, Intent intent) {
if (!Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) return;
LocaleChangedBroadcastReceiverJni.get().localeChanged();
WebLayerNotificationChannels.onLocaleChanged();
}
@NativeMethods
interface Natives {
void localeChanged();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/LocaleChangedBroadcastReceiver.java | Java | unknown | 1,336 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.blink.mojom.Authenticator;
import org.chromium.components.webauthn.AuthenticatorFactory;
import org.chromium.content_public.browser.InterfaceRegistrar;
import org.chromium.content_public.browser.RenderFrameHost;
import org.chromium.content_public.browser.WebContents;
import org.chromium.installedapp.mojom.InstalledAppProvider;
import org.chromium.payments.mojom.PaymentRequest;
import org.chromium.services.service_manager.InterfaceRegistry;
import org.chromium.weblayer_private.payments.WebLayerPaymentRequestFactory;
import org.chromium.webshare.mojom.ShareService;
/**
* Registers Java implementations of mojo interfaces.
*/
class MojoInterfaceRegistrar {
@CalledByNative
private static void registerMojoInterfaces() {
InterfaceRegistrar.Registry.addWebContentsRegistrar(new WebContentsInterfaceRegistrar());
InterfaceRegistrar.Registry.addRenderFrameHostRegistrar(
new RenderFrameHostInterfaceRegistrar());
}
private static class WebContentsInterfaceRegistrar implements InterfaceRegistrar<WebContents> {
@Override
public void registerInterfaces(InterfaceRegistry registry, final WebContents webContents) {
registry.addInterface(ShareService.MANAGER, new WebShareServiceFactory(webContents));
}
}
private static class RenderFrameHostInterfaceRegistrar
implements InterfaceRegistrar<RenderFrameHost> {
@Override
public void registerInterfaces(
InterfaceRegistry registry, final RenderFrameHost renderFrameHost) {
registry.addInterface(Authenticator.MANAGER, new AuthenticatorFactory(renderFrameHost));
registry.addInterface(
InstalledAppProvider.MANAGER, new InstalledAppProviderFactory(renderFrameHost));
registry.addInterface(
PaymentRequest.MANAGER, new WebLayerPaymentRequestFactory(renderFrameHost));
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/MojoInterfaceRegistrar.java | Java | unknown | 2,203 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import android.webkit.WebResourceResponse;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.embedder_support.util.WebResourceResponseInfo;
import org.chromium.weblayer_private.TabImpl.HeaderVerificationStatus;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IClientPage;
import org.chromium.weblayer_private.interfaces.INavigateParams;
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.NavigateParams;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.util.HashMap;
import java.util.Map;
/**
* Acts as the bridge between java and the C++ implementation of of NavigationController.
*/
@JNINamespace("weblayer")
public final class NavigationControllerImpl extends INavigationController.Stub {
private final TabImpl mTab;
private long mNativeNavigationController;
private INavigationControllerClient mNavigationControllerClient;
private Map<Long, PageImpl> mPages = new HashMap<>();
public NavigationControllerImpl(TabImpl tab, INavigationControllerClient client) {
mTab = tab;
mNavigationControllerClient = client;
mNativeNavigationController =
NavigationControllerImplJni.get().getNavigationController(tab.getNativeTab());
NavigationControllerImplJni.get().setNavigationControllerImpl(
mNativeNavigationController, NavigationControllerImpl.this);
}
@Override
public void navigate(String uri, NavigateParams params) {
StrictModeWorkaround.apply();
mTab.setHeaderVerification(HeaderVerificationStatus.PENDING);
if (WebLayerFactoryImpl.getClientMajorVersion() < 83) {
assert params == null;
}
NavigationControllerImplJni.get().navigate(mNativeNavigationController, uri,
params == null ? false : params.mShouldReplaceCurrentEntry, false, false, false,
false, null);
}
@Override
public void navigate2(String uri, boolean shouldReplaceCurrentEntry,
boolean disableIntentProcessing, boolean disableNetworkErrorAutoReload,
boolean enableAutoPlay) {
StrictModeWorkaround.apply();
NavigationControllerImplJni.get().navigate(mNativeNavigationController, uri,
shouldReplaceCurrentEntry, disableIntentProcessing,
/*allowIntentLaunchesInBackground=*/false, disableNetworkErrorAutoReload,
enableAutoPlay, null);
}
@Override
public INavigateParams createNavigateParams() {
StrictModeWorkaround.apply();
return new NavigateParamsImpl();
}
@Override
public void navigate3(String uri, INavigateParams iParams) {
StrictModeWorkaround.apply();
NavigateParamsImpl params = (NavigateParamsImpl) iParams;
WebResourceResponseInfo responseInfo = null;
if (params.getResponse() != null) {
WebResourceResponse response =
ObjectWrapper.unwrap(params.getResponse(), WebResourceResponse.class);
responseInfo = new WebResourceResponseInfo(response.getMimeType(),
response.getEncoding(), response.getData(), response.getStatusCode(),
response.getReasonPhrase(), response.getResponseHeaders());
}
NavigationControllerImplJni.get().navigate(mNativeNavigationController, uri,
params.shouldReplaceCurrentEntry(), params.isIntentProcessingDisabled(),
params.areIntentLaunchesAllowedInBackground(),
params.isNetworkErrorAutoReloadDisabled(), params.isAutoPlayEnabled(),
responseInfo);
}
@Override
public void goBack() {
StrictModeWorkaround.apply();
NavigationControllerImplJni.get().goBack(mNativeNavigationController);
}
@Override
public void goForward() {
StrictModeWorkaround.apply();
NavigationControllerImplJni.get().goForward(mNativeNavigationController);
}
@Override
public boolean canGoBack() {
StrictModeWorkaround.apply();
return NavigationControllerImplJni.get().canGoBack(mNativeNavigationController);
}
@Override
public boolean canGoForward() {
StrictModeWorkaround.apply();
return NavigationControllerImplJni.get().canGoForward(mNativeNavigationController);
}
@Override
public void goToIndex(int index) {
StrictModeWorkaround.apply();
NavigationControllerImplJni.get().goToIndex(mNativeNavigationController, index);
}
@Override
public void reload() {
StrictModeWorkaround.apply();
NavigationControllerImplJni.get().reload(mNativeNavigationController);
}
@Override
public void stop() {
StrictModeWorkaround.apply();
NavigationControllerImplJni.get().stop(mNativeNavigationController);
}
@Override
public int getNavigationListSize() {
StrictModeWorkaround.apply();
return NavigationControllerImplJni.get().getNavigationListSize(mNativeNavigationController);
}
@Override
public int getNavigationListCurrentIndex() {
StrictModeWorkaround.apply();
return NavigationControllerImplJni.get().getNavigationListCurrentIndex(
mNativeNavigationController);
}
@Override
public String getNavigationEntryDisplayUri(int index) {
StrictModeWorkaround.apply();
return NavigationControllerImplJni.get().getNavigationEntryDisplayUri(
mNativeNavigationController, index);
}
@Override
public String getNavigationEntryTitle(int index) {
StrictModeWorkaround.apply();
return NavigationControllerImplJni.get().getNavigationEntryTitle(
mNativeNavigationController, index);
}
@Override
public boolean isNavigationEntrySkippable(int index) {
StrictModeWorkaround.apply();
return NavigationControllerImplJni.get().isNavigationEntrySkippable(
mNativeNavigationController, index);
}
public NavigationImpl getNavigationImplFromId(long id) {
StrictModeWorkaround.apply();
return NavigationControllerImplJni.get().getNavigationImplFromId(
mNativeNavigationController, id);
}
public PageImpl getPage(long nativePageImpl) {
// Ensure that each C++ object has only one Java counterpart so that the embedder sees the
// same object for multiple navigations that have the same Page.
PageImpl page = mPages.get(nativePageImpl);
if (page == null) {
IClientPage clientPage = null;
if (WebLayerFactoryImpl.getClientMajorVersion() >= 90) {
try {
clientPage = mNavigationControllerClient.createClientPage();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
page = new PageImpl(clientPage, nativePageImpl, this);
mPages.put(nativePageImpl, page);
}
return page;
}
public void onPageDestroyed(PageImpl page) {
mPages.remove(page.getNativePageImpl());
if (WebLayerFactoryImpl.getClientMajorVersion() >= 90) {
try {
mNavigationControllerClient.onPageDestroyed(page.getClientPage());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
}
@CalledByNative
private NavigationImpl createNavigation(long nativeNavigationImpl) {
return new NavigationImpl(mNavigationControllerClient, nativeNavigationImpl, this);
}
@CalledByNative
private void navigationStarted(NavigationImpl navigation) throws RemoteException {
mTab.setHeaderVerification(HeaderVerificationStatus.PENDING);
mNavigationControllerClient.navigationStarted(navigation.getClientNavigation());
}
@CalledByNative
private void navigationRedirected(NavigationImpl navigation) throws RemoteException {
mNavigationControllerClient.navigationRedirected(navigation.getClientNavigation());
}
@CalledByNative
private void readyToCommitNavigation(NavigationImpl navigation) throws RemoteException {
mNavigationControllerClient.readyToCommitNavigation(navigation.getClientNavigation());
}
@CalledByNative
private void getOrCreatePageForNavigation(NavigationImpl navigation) throws RemoteException {
navigation.getPage();
}
@CalledByNative
private void navigationCompleted(NavigationImpl navigation) throws RemoteException {
if (navigation.getIsConsentingContent()) {
mTab.setHeaderVerification(HeaderVerificationStatus.VALIDATED);
} else {
mTab.setHeaderVerification(HeaderVerificationStatus.NOT_VALIDATED);
}
mNavigationControllerClient.navigationCompleted(navigation.getClientNavigation());
}
@CalledByNative
private void navigationFailed(NavigationImpl navigation) throws RemoteException {
mNavigationControllerClient.navigationFailed(navigation.getClientNavigation());
}
@CalledByNative
private void loadStateChanged(boolean isLoading, boolean shouldShowLoadingUi)
throws RemoteException {
mNavigationControllerClient.loadStateChanged(isLoading, shouldShowLoadingUi);
}
@CalledByNative
private void loadProgressChanged(double progress) throws RemoteException {
mNavigationControllerClient.loadProgressChanged(progress);
}
@CalledByNative
private void onFirstContentfulPaint() throws RemoteException {
mNavigationControllerClient.onFirstContentfulPaint();
}
@CalledByNative
private void onFirstContentfulPaint2(
long navigationStartMs, long firstContentfulPaintDurationMs) throws RemoteException {
if (WebLayerFactoryImpl.getClientMajorVersion() < 88) return;
mNavigationControllerClient.onFirstContentfulPaint2(
navigationStartMs, firstContentfulPaintDurationMs);
}
@CalledByNative
private void onLargestContentfulPaint(
long navigationStartMs, long largestContentfulPaintDurationMs) throws RemoteException {
if (WebLayerFactoryImpl.getClientMajorVersion() < 88) return;
mNavigationControllerClient.onLargestContentfulPaint(
navigationStartMs, largestContentfulPaintDurationMs);
}
@CalledByNative
private void onOldPageNoLongerRendered(String uri) throws RemoteException {
mNavigationControllerClient.onOldPageNoLongerRendered(uri);
}
@CalledByNative
private void onPageLanguageDetermined(PageImpl page, String language) throws RemoteException {
if (WebLayerFactoryImpl.getClientMajorVersion() < 93) return;
mNavigationControllerClient.onPageLanguageDetermined(page.getClientPage(), language);
}
@CalledByNative
private boolean isUrlAllowed(String url) {
return mTab.getBrowser().isUrlAllowed(url);
}
private static final class NavigateParamsImpl extends INavigateParams.Stub {
private boolean mReplaceCurrentEntry;
private boolean mIntentProcessingDisabled;
private boolean mIntentLaunchesAllowedInBackground;
private boolean mNetworkErrorAutoReloadDisabled;
private boolean mAutoPlayEnabled;
private IObjectWrapper mResponse;
@Override
public void replaceCurrentEntry() {
mReplaceCurrentEntry = true;
}
@Override
public void disableIntentProcessing() {
mIntentProcessingDisabled = true;
}
@Override
public void allowIntentLaunchesInBackground() {
mIntentLaunchesAllowedInBackground = true;
}
@Override
public void disableNetworkErrorAutoReload() {
mNetworkErrorAutoReloadDisabled = true;
}
@Override
public void enableAutoPlay() {
mAutoPlayEnabled = true;
}
@Override
public void setResponse(IObjectWrapper response) {
mResponse = response;
}
public boolean shouldReplaceCurrentEntry() {
return mReplaceCurrentEntry;
}
public boolean isIntentProcessingDisabled() {
return mIntentProcessingDisabled;
}
public boolean areIntentLaunchesAllowedInBackground() {
return mIntentLaunchesAllowedInBackground;
}
public boolean isNetworkErrorAutoReloadDisabled() {
return mNetworkErrorAutoReloadDisabled;
}
public boolean isAutoPlayEnabled() {
return mAutoPlayEnabled;
}
IObjectWrapper getResponse() {
return mResponse;
}
}
@NativeMethods
interface Natives {
void setNavigationControllerImpl(
long nativeNavigationControllerImpl, NavigationControllerImpl caller);
long getNavigationController(long tab);
void navigate(long nativeNavigationControllerImpl, String uri,
boolean shouldReplaceCurrentEntry, boolean disableIntentProcessing,
boolean allowIntentLaunchesInBackground, boolean disableNetworkErrorAutoReload,
boolean enableAutoPlay, WebResourceResponseInfo response);
void goBack(long nativeNavigationControllerImpl);
void goForward(long nativeNavigationControllerImpl);
boolean canGoBack(long nativeNavigationControllerImpl);
boolean canGoForward(long nativeNavigationControllerImpl);
void goToIndex(long nativeNavigationControllerImpl, int index);
void reload(long nativeNavigationControllerImpl);
void stop(long nativeNavigationControllerImpl);
int getNavigationListSize(long nativeNavigationControllerImpl);
int getNavigationListCurrentIndex(long nativeNavigationControllerImpl);
String getNavigationEntryDisplayUri(long nativeNavigationControllerImpl, int index);
String getNavigationEntryTitle(long nativeNavigationControllerImpl, int index);
boolean isNavigationEntrySkippable(long nativeNavigationControllerImpl, int index);
NavigationImpl getNavigationImplFromId(long nativeNavigationControllerImpl, long id);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/NavigationControllerImpl.java | Java | unknown | 14,967 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.IClientNavigation;
import org.chromium.weblayer_private.interfaces.IClientPage;
import org.chromium.weblayer_private.interfaces.INavigation;
import org.chromium.weblayer_private.interfaces.INavigationControllerClient;
import org.chromium.weblayer_private.interfaces.LoadError;
import org.chromium.weblayer_private.interfaces.NavigationState;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.util.Arrays;
import java.util.List;
/**
* Implementation of INavigation.
*/
@JNINamespace("weblayer")
public final class NavigationImpl extends INavigation.Stub {
private final IClientNavigation mClientNavigation;
private final NavigationControllerImpl mNavigationController;
// WARNING: NavigationImpl may outlive the native side, in which case this member is set to 0.
private long mNativeNavigationImpl;
// Set to true if/when it is determined that an external intent was launched for this
// navigation.
private boolean mIntentLaunched;
// Set to true if/when it is determined that this navigation result in UI being presented to the
// user via which the user will determine whether an intent should be launched.
private boolean mIsUserDecidingIntentLaunch;
private PageImpl mPage;
public NavigationImpl(INavigationControllerClient client, long nativeNavigationImpl,
NavigationControllerImpl navigationController) {
mNativeNavigationImpl = nativeNavigationImpl;
mNavigationController = navigationController;
try {
mClientNavigation = client.createClientNavigation(this);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public IClientNavigation getClientNavigation() {
return mClientNavigation;
}
@NavigationState
private static int implTypeToJavaType(@ImplNavigationState int type) {
switch (type) {
case ImplNavigationState.WAITING_RESPONSE:
return NavigationState.WAITING_RESPONSE;
case ImplNavigationState.RECEIVING_BYTES:
return NavigationState.RECEIVING_BYTES;
case ImplNavigationState.COMPLETE:
return NavigationState.COMPLETE;
case ImplNavigationState.FAILED:
return NavigationState.FAILED;
}
assert false;
return NavigationState.FAILED;
}
@Override
@NavigationState
public int getState() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return implTypeToJavaType(NavigationImplJni.get().getState(mNativeNavigationImpl));
}
@Override
public String getUri() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().getUri(mNativeNavigationImpl);
}
@Override
public List<String> getRedirectChain() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return Arrays.asList(NavigationImplJni.get().getRedirectChain(mNativeNavigationImpl));
}
@Override
public int getHttpStatusCode() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().getHttpStatusCode(mNativeNavigationImpl);
}
@Override
public List<String> getResponseHeaders() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return Arrays.asList(NavigationImplJni.get().getResponseHeaders(mNativeNavigationImpl));
}
public boolean getIsConsentingContent() {
return NavigationImplJni.get().getIsConsentingContent(mNativeNavigationImpl);
}
@Override
public boolean isSameDocument() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().isSameDocument(mNativeNavigationImpl);
}
@Override
public boolean isErrorPage() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().isErrorPage(mNativeNavigationImpl);
}
@Override
public int getLoadError() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return implLoadErrorToLoadError(
NavigationImplJni.get().getLoadError(mNativeNavigationImpl));
}
@Override
public void setRequestHeader(String name, String value) {
if (!NavigationImplJni.get().isValidRequestHeaderName(name)) {
throw new IllegalArgumentException("Invalid header");
}
if (!NavigationImplJni.get().isValidRequestHeaderValue(value)) {
throw new IllegalArgumentException("Invalid value");
}
if (!NavigationImplJni.get().setRequestHeader(mNativeNavigationImpl, name, value)) {
throw new IllegalStateException();
}
}
@Override
public void setUserAgentString(String value) {
if (!NavigationImplJni.get().isValidRequestHeaderValue(value)) {
throw new IllegalArgumentException("Invalid value");
}
if (!NavigationImplJni.get().setUserAgentString(mNativeNavigationImpl, value)) {
throw new IllegalStateException();
}
}
@Override
public boolean isDownload() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().isDownload(mNativeNavigationImpl);
}
@Override
public boolean isKnownProtocol() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().isKnownProtocol(mNativeNavigationImpl);
}
@Override
public boolean wasIntentLaunched() {
return mIntentLaunched;
}
@Override
public boolean isUserDecidingIntentLaunch() {
return mIsUserDecidingIntentLaunch;
}
@Override
public boolean wasStopCalled() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().wasStopCalled(mNativeNavigationImpl);
}
@Override
public boolean isPageInitiated() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().isPageInitiated(mNativeNavigationImpl);
}
@Override
public boolean isReload() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().isReload(mNativeNavigationImpl);
}
@Override
public boolean isServedFromBackForwardCache() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().isServedFromBackForwardCache(mNativeNavigationImpl);
}
@Override
public void disableNetworkErrorAutoReload() {
if (!NavigationImplJni.get().disableNetworkErrorAutoReload(mNativeNavigationImpl)) {
throw new IllegalStateException();
}
}
@Override
public void disableIntentProcessing() {
if (!NavigationImplJni.get().disableIntentProcessing(mNativeNavigationImpl)) {
throw new IllegalStateException();
}
}
@Override
public boolean isFormSubmission() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().isFormSubmission(mNativeNavigationImpl);
}
@Override
public String getReferrer() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().getReferrer(mNativeNavigationImpl);
}
@Override
public IClientPage getPage() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
if (mPage == null) {
long nativePageImpl = NavigationImplJni.get().getPage(mNativeNavigationImpl);
if (nativePageImpl == -1) {
throw new IllegalStateException(
"Invoking Navigation#getPage() outside of valid calling context");
}
// There should always be a Page associated with the navigation within the valid
// calling contexts for Navigation#getPage().
assert (nativePageImpl != 0);
mPage = mNavigationController.getPage(nativePageImpl);
}
return mPage.getClientPage();
}
@Override
public int getNavigationEntryOffset() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().getNavigationEntryOffset(mNativeNavigationImpl);
}
@Override
public boolean wasFetchedFromCache() {
StrictModeWorkaround.apply();
throwIfNativeDestroyed();
return NavigationImplJni.get().wasFetchedFromCache(mNativeNavigationImpl);
}
public void setIntentLaunched() {
mIntentLaunched = true;
}
public void setIsUserDecidingIntentLaunch() {
mIsUserDecidingIntentLaunch = true;
}
public boolean areIntentLaunchesAllowedInBackground() {
return NavigationImplJni.get().areIntentLaunchesAllowedInBackground(mNativeNavigationImpl);
}
private void throwIfNativeDestroyed() {
if (mNativeNavigationImpl == 0) {
throw new IllegalStateException("Using Navigation after native destroyed");
}
}
@LoadError
private static int implLoadErrorToLoadError(@ImplLoadError int loadError) {
switch (loadError) {
case ImplLoadError.NO_ERROR:
return LoadError.NO_ERROR;
case ImplLoadError.HTTP_CLIENT_ERROR:
return LoadError.HTTP_CLIENT_ERROR;
case ImplLoadError.HTTP_SERVER_ERROR:
return LoadError.HTTP_SERVER_ERROR;
case ImplLoadError.SSL_ERROR:
return LoadError.SSL_ERROR;
case ImplLoadError.CONNECTIVITY_ERROR:
return LoadError.CONNECTIVITY_ERROR;
case ImplLoadError.OTHER_ERROR:
return LoadError.OTHER_ERROR;
case ImplLoadError.SAFE_BROWSING_ERROR:
return LoadError.SAFE_BROWSING_ERROR;
default:
throw new IllegalArgumentException("Unexpected load error " + loadError);
}
}
@CalledByNative
private void onNativeDestroyed() {
mNativeNavigationImpl = 0;
// TODO: this should likely notify delegate in some way.
}
@NativeMethods
interface Natives {
int getState(long nativeNavigationImpl);
String getUri(long nativeNavigationImpl);
String[] getRedirectChain(long nativeNavigationImpl);
int getHttpStatusCode(long nativeNavigationImpl);
String[] getResponseHeaders(long nativeNavigationImpl);
boolean getIsConsentingContent(long nativeNavigationImpl);
boolean isSameDocument(long nativeNavigationImpl);
boolean isErrorPage(long nativeNavigationImpl);
boolean isDownload(long nativeNavigationImpl);
boolean isKnownProtocol(long nativeNavigationImpl);
boolean wasStopCalled(long nativeNavigationImpl);
int getLoadError(long nativeNavigationImpl);
boolean setRequestHeader(long nativeNavigationImpl, String name, String value);
boolean isValidRequestHeaderName(String name);
boolean isValidRequestHeaderValue(String value);
boolean setUserAgentString(long nativeNavigationImpl, String value);
boolean isPageInitiated(long nativeNavigationImpl);
boolean isReload(long nativeNavigationImpl);
boolean isServedFromBackForwardCache(long nativeNavigationImpl);
boolean disableNetworkErrorAutoReload(long nativeNavigationImpl);
boolean disableIntentProcessing(long nativeNavigationImpl);
boolean areIntentLaunchesAllowedInBackground(long nativeNavigationImpl);
boolean isFormSubmission(long nativeNavigationImpl);
String getReferrer(long nativeNavigationImpl);
long getPage(long nativeNavigationImpl);
int getNavigationEntryOffset(long nativeNavigationImpl);
boolean wasFetchedFromCache(long nativeNavigationImpl);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/NavigationImpl.java | Java | unknown | 12,553 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.NewTabType;
/**
* Owns the c++ NewTabCallback class, which is responsible for forwarding all
* NewTabCallback calls to this class, which in turn forwards to ITabClient.
*/
@JNINamespace("weblayer")
public final class NewTabCallbackProxy {
private long mNativeNewTabCallbackProxy;
private final TabImpl mTab;
public NewTabCallbackProxy(TabImpl tab) {
mTab = tab;
mNativeNewTabCallbackProxy =
NewTabCallbackProxyJni.get().createNewTabCallbackProxy(this, tab.getNativeTab());
}
public void destroy() {
NewTabCallbackProxyJni.get().deleteNewTabCallbackProxy(mNativeNewTabCallbackProxy);
mNativeNewTabCallbackProxy = 0;
}
@NewTabType
private static int implTypeToJavaType(@ImplNewTabType int type) {
switch (type) {
case ImplNewTabType.FOREGROUND:
return NewTabType.FOREGROUND_TAB;
case ImplNewTabType.BACKGROUND:
return NewTabType.BACKGROUND_TAB;
case ImplNewTabType.NEW_POPUP:
return NewTabType.NEW_POPUP;
case ImplNewTabType.NEW_WINDOW:
return NewTabType.NEW_WINDOW;
}
assert false;
return NewTabType.FOREGROUND_TAB;
}
@CalledByNative
public void onNewTab(TabImpl tab, @ImplNewTabType int mode) throws RemoteException {
// This class should only be created while the tab is attached to a fragment.
assert mTab.getBrowser() != null;
assert mTab.getBrowser().equals(tab.getBrowser());
mTab.getClient().onNewTab(tab.getId(), implTypeToJavaType(mode));
}
@NativeMethods
interface Natives {
long createNewTabCallbackProxy(NewTabCallbackProxy proxy, long tab);
void deleteNewTabCallbackProxy(long proxy);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/NewTabCallbackProxy.java | Java | unknown | 2,234 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.IClientPage;
/**
* Implementation side of Page.
*/
@JNINamespace("weblayer")
public final class PageImpl {
// Will be null for clients libraries that are old and don't support this.
private final IClientPage mClientPage;
// WARNING: PageImpl may outlive the native side, in which case this member is set to 0.
private long mNativePageImpl;
private final NavigationControllerImpl mNavigationController;
public PageImpl(IClientPage clientPage, long nativePageImpl,
NavigationControllerImpl navigationController) {
mClientPage = clientPage;
mNativePageImpl = nativePageImpl;
mNavigationController = navigationController;
PageImplJni.get().setJavaPage(mNativePageImpl, PageImpl.this);
}
public IClientPage getClientPage() {
return mClientPage;
}
long getNativePageImpl() {
return mNativePageImpl;
}
@CalledByNative
private void onNativeDestroyed() {
mNavigationController.onPageDestroyed(this);
mNativePageImpl = 0;
}
@NativeMethods
interface Natives {
void setJavaPage(long nativePageImpl, PageImpl caller);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/PageImpl.java | Java | unknown | 1,557 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.base.LifetimeAssert;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.IPrerenderController;
/**
* Implementation of {@link IPrerenderController}.
*/
@JNINamespace("weblayer")
public class PrerenderControllerImpl extends IPrerenderController.Stub {
private long mNativePrerenderController;
private final LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this);
void destroy() {
mNativePrerenderController = 0;
// If mLifetimeAssert is GC'ed before this is called, it will throw an exception
// with a stack trace showing the stack during LifetimeAssert.create().
LifetimeAssert.setSafeToGc(mLifetimeAssert, true);
}
public PrerenderControllerImpl(long nativePrerenderController) {
mNativePrerenderController = nativePrerenderController;
}
@Override
public void prerender(String url) {
PrerenderControllerImplJni.get().prerender(mNativePrerenderController, url);
}
@NativeMethods()
interface Natives {
void prerender(long nativePrerenderControllerImpl, String url);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/PrerenderControllerImpl.java | Java | unknown | 1,392 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.RemoteException;
import android.text.TextUtils;
import android.webkit.ValueCallback;
import androidx.annotation.NonNull;
import org.chromium.base.Callback;
import org.chromium.base.CollectionUtil;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.base.task.PostTask;
import org.chromium.base.task.TaskTraits;
import org.chromium.components.browser_ui.accessibility.FontSizePrefs;
import org.chromium.components.content_capture.PlatformContentCaptureController;
import org.chromium.content_public.browser.BrowserContextHandle;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.BrowsingDataType;
import org.chromium.weblayer_private.interfaces.IBrowser;
import org.chromium.weblayer_private.interfaces.ICookieManager;
import org.chromium.weblayer_private.interfaces.IDownloadCallbackClient;
import org.chromium.weblayer_private.interfaces.IGoogleAccountAccessTokenFetcherClient;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IOpenUrlCallbackClient;
import org.chromium.weblayer_private.interfaces.IPrerenderController;
import org.chromium.weblayer_private.interfaces.IProfile;
import org.chromium.weblayer_private.interfaces.IProfileClient;
import org.chromium.weblayer_private.interfaces.IUserIdentityCallbackClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.SettingType;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Implementation of IProfile.
*/
@JNINamespace("weblayer")
public final class ProfileImpl
extends IProfile.Stub implements BrowserContextHandle, BrowserListObserver {
private final String mName;
private final boolean mIsIncognito;
private long mNativeProfile;
private CookieManagerImpl mCookieManager;
private PrerenderControllerImpl mPrerenderController;
private Runnable mOnDestroyCallback;
private boolean mBeingDeleted;
private boolean mDownloadsInitialized;
private DownloadCallbackProxy mDownloadCallbackProxy;
private GoogleAccountAccessTokenFetcherProxy mAccessTokenFetcherProxy;
private IUserIdentityCallbackClient mUserIdentityCallbackClient;
private IOpenUrlCallbackClient mOpenUrlCallbackClient;
private List<Intent> mDownloadNotificationIntents = new ArrayList<>();
private IProfileClient mClient;
// If non-null, indicates when no browsers reference this Profile the Profile is destroyed. The
// contents are the list of runnables supplied to destroyAndDeleteDataFromDiskSoon().
private List<Runnable> mDelayedDestroyCallbacks;
public static void enumerateAllProfileNames(ValueCallback<String[]> callback) {
final Callback<String[]> baseCallback = (String[] names) -> callback.onReceiveValue(names);
ProfileImplJni.get().enumerateAllProfileNames(baseCallback);
}
ProfileImpl(String name, boolean isIncognito, Runnable onDestroyCallback) {
// Normal profiles have restrictions on the name.
if (!isIncognito && !name.matches("^\\w+$")) {
throw new IllegalArgumentException(
"Non-incognito profiles names can only contain words: " + name);
}
mIsIncognito = isIncognito;
mName = name;
mNativeProfile = ProfileImplJni.get().createProfile(name, ProfileImpl.this, mIsIncognito);
mCookieManager = new CookieManagerImpl(
ProfileImplJni.get().getCookieManager(mNativeProfile), ProfileImpl.this);
mPrerenderController = new PrerenderControllerImpl(
ProfileImplJni.get().getPrerenderController(mNativeProfile));
mOnDestroyCallback = onDestroyCallback;
mDownloadCallbackProxy = new DownloadCallbackProxy(this);
mAccessTokenFetcherProxy = new GoogleAccountAccessTokenFetcherProxy(this);
}
private void destroyDependentJavaObjects() {
if (mDownloadCallbackProxy != null) {
mDownloadCallbackProxy.destroy();
mDownloadCallbackProxy = null;
}
if (mAccessTokenFetcherProxy != null) {
mAccessTokenFetcherProxy.destroy();
mAccessTokenFetcherProxy = null;
}
if (mCookieManager != null) {
mCookieManager.destroy();
mCookieManager = null;
}
if (mPrerenderController != null) {
mPrerenderController.destroy();
mPrerenderController = null;
}
FontSizePrefs.destroyInstance();
}
@Override
public void destroy() {
StrictModeWorkaround.apply();
if (mBeingDeleted) return;
destroyDependentJavaObjects();
deleteNativeProfile();
maybeRunDestroyCallback();
}
private void deleteNativeProfile() {
ProfileImplJni.get().deleteProfile(mNativeProfile);
mNativeProfile = 0;
}
private void maybeRunDestroyCallback() {
if (mOnDestroyCallback == null) return;
mOnDestroyCallback.run();
mOnDestroyCallback = null;
}
@Override
public void destroyAndDeleteDataFromDisk(IObjectWrapper completionCallback) {
StrictModeWorkaround.apply();
checkNotDestroyed();
assert mNativeProfile != 0;
if (!canDestroyNow()) {
throw new IllegalStateException("Profile still in use: " + mName);
}
final Runnable callback = ObjectWrapper.unwrap(completionCallback, Runnable.class);
destroyAndDeleteDataFromDiskImpl(callback);
}
private void destroyAndDeleteDataFromDiskImpl(Runnable callback) {
assert canDestroyNow();
mBeingDeleted = true;
BrowserList.getInstance().removeObserver(this);
destroyDependentJavaObjects();
if (mClient != null) {
try {
mClient.onProfileDestroyed();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
ProfileImplJni.get().destroyAndDeleteDataFromDisk(mNativeProfile, () -> {
if (callback != null) callback.run();
if (mDelayedDestroyCallbacks != null) {
for (Runnable r : mDelayedDestroyCallbacks) r.run();
mDelayedDestroyCallbacks = null;
}
});
mNativeProfile = 0;
maybeRunDestroyCallback();
}
private boolean canDestroyNow() {
return ProfileImplJni.get().getNumBrowserImpl(mNativeProfile) == 0;
}
@Override
public void destroyAndDeleteDataFromDiskSoon(IObjectWrapper completionCallback) {
StrictModeWorkaround.apply();
checkNotDestroyed();
assert mNativeProfile != 0;
if (canDestroyNow()) {
destroyAndDeleteDataFromDisk(completionCallback);
return;
}
// The profile is still in use. Wait for all browsers to be destroyed before cleaning up.
if (mDelayedDestroyCallbacks == null) {
BrowserList.getInstance().addObserver(this);
mDelayedDestroyCallbacks = new ArrayList<>();
ProfileImplJni.get().markAsDeleted(mNativeProfile);
}
final Runnable callback = ObjectWrapper.unwrap(completionCallback, Runnable.class);
if (callback != null) mDelayedDestroyCallbacks.add(callback);
}
@Override
public void setClient(IProfileClient client) {
mClient = client;
}
@Override
public String getName() {
StrictModeWorkaround.apply();
checkNotDestroyed();
return mName;
}
@Override
public long getNativeBrowserContextPointer() {
if (mNativeProfile == 0) {
return 0;
}
return ProfileImplJni.get().getBrowserContext(mNativeProfile);
}
@Override
public void setUserIdentityCallbackClient(IUserIdentityCallbackClient client) {
StrictModeWorkaround.apply();
mUserIdentityCallbackClient = client;
}
public IUserIdentityCallbackClient getUserIdentityCallbackClient() {
return mUserIdentityCallbackClient;
}
@Override
public void setGoogleAccountAccessTokenFetcherClient(
IGoogleAccountAccessTokenFetcherClient client) {
StrictModeWorkaround.apply();
mAccessTokenFetcherProxy.setClient(client);
}
@Override
public void setTablessOpenUrlCallbackClient(IOpenUrlCallbackClient client) {
StrictModeWorkaround.apply();
mOpenUrlCallbackClient = client;
}
@Override
public boolean isIncognito() {
return mIsIncognito;
}
public boolean areDownloadsInitialized() {
return mDownloadsInitialized;
}
public void addDownloadNotificationIntent(Intent intent) {
mDownloadNotificationIntents.add(intent);
ProfileImplJni.get().ensureBrowserContextInitialized(mNativeProfile);
}
@Override
public void onBrowserCreated(BrowserImpl browser) {}
@Override
public void onBrowserDestroyed(BrowserImpl browser) {
if (!canDestroyNow()) return;
// onBrowserDestroyed() is called from the destructor of Browser. This is a rather fragile
// time to destroy the profile. Delay.
PostTask.postTask(TaskTraits.UI_DEFAULT, () -> {
if (!mBeingDeleted && canDestroyNow()) {
destroyAndDeleteDataFromDiskImpl(null);
}
});
}
@Override
public void clearBrowsingData(@NonNull @BrowsingDataType int[] dataTypes, long fromMillis,
long toMillis, @NonNull IObjectWrapper completionCallback) {
StrictModeWorkaround.apply();
checkNotDestroyed();
// `toMillis` should be greater than `fromMillis`
assert fromMillis < toMillis;
// Handle ContentCapture data clearing.
PlatformContentCaptureController controller =
PlatformContentCaptureController.getInstance();
if (controller != null) {
for (int type : dataTypes) {
if (type == BrowsingDataType.COOKIES_AND_SITE_DATA) {
controller.clearAllContentCaptureData();
break;
}
}
}
Runnable callback = ObjectWrapper.unwrap(completionCallback, Runnable.class);
ProfileImplJni.get().clearBrowsingData(
mNativeProfile, mapBrowsingDataTypes(dataTypes), fromMillis, toMillis, callback);
}
@Override
public void setDownloadDirectory(String directory) {
StrictModeWorkaround.apply();
checkNotDestroyed();
ProfileImplJni.get().setDownloadDirectory(mNativeProfile, directory);
}
@Override
public void setDownloadCallbackClient(IDownloadCallbackClient client) {
mDownloadCallbackProxy.setClient(client);
}
@Override
public ICookieManager getCookieManager() {
StrictModeWorkaround.apply();
checkNotDestroyed();
return mCookieManager;
}
@Override
public IPrerenderController getPrerenderController() {
StrictModeWorkaround.apply();
checkNotDestroyed();
return mPrerenderController;
}
@Override
public void getBrowserPersistenceIds(@NonNull IObjectWrapper callback) {
StrictModeWorkaround.apply();
checkNotDestroyed();
ValueCallback<Set<String>> valueCallback =
(ValueCallback<Set<String>>) ObjectWrapper.unwrap(callback, ValueCallback.class);
Callback<String[]> baseCallback = (String[] result) -> {
valueCallback.onReceiveValue(new HashSet<String>(Arrays.asList(result)));
};
ProfileImplJni.get().getBrowserPersistenceIds(mNativeProfile, baseCallback);
}
@Override
public void removeBrowserPersistenceStorage(String[] ids, @NonNull IObjectWrapper callback) {
StrictModeWorkaround.apply();
checkNotDestroyed();
ValueCallback<Boolean> valueCallback =
(ValueCallback<Boolean>) ObjectWrapper.unwrap(callback, ValueCallback.class);
Callback<Boolean> baseCallback = valueCallback::onReceiveValue;
for (String id : ids) {
if (TextUtils.isEmpty(id)) {
throw new IllegalArgumentException("id must be non-null and non-empty");
}
}
ProfileImplJni.get().removeBrowserPersistenceStorage(mNativeProfile, ids, baseCallback);
}
@Override
public void prepareForPossibleCrossOriginNavigation() {
StrictModeWorkaround.apply();
checkNotDestroyed();
ProfileImplJni.get().prepareForPossibleCrossOriginNavigation(mNativeProfile);
}
@Override
public void getCachedFaviconForPageUri(@NonNull String uri, @NonNull IObjectWrapper callback) {
StrictModeWorkaround.apply();
checkNotDestroyed();
ValueCallback<Bitmap> valueCallback =
(ValueCallback<Bitmap>) ObjectWrapper.unwrap(callback, ValueCallback.class);
Callback<Bitmap> baseCallback = valueCallback::onReceiveValue;
ProfileImplJni.get().getCachedFaviconForPageUrl(mNativeProfile, uri, baseCallback);
}
void checkNotDestroyed() {
if (!mBeingDeleted) return;
throw new IllegalArgumentException("Profile being destroyed: " + mName);
}
private static @ImplBrowsingDataType int[] mapBrowsingDataTypes(
@NonNull @BrowsingDataType int[] dataTypes) {
// Convert data types coming from aidl to the ones accepted by C++ (ImplBrowsingDataType is
// generated from a C++ enum).
List<Integer> convertedTypes = new ArrayList<>();
for (int aidlType : dataTypes) {
switch (aidlType) {
case BrowsingDataType.COOKIES_AND_SITE_DATA:
convertedTypes.add(ImplBrowsingDataType.COOKIES_AND_SITE_DATA);
break;
case BrowsingDataType.CACHE:
convertedTypes.add(ImplBrowsingDataType.CACHE);
break;
case BrowsingDataType.SITE_SETTINGS:
convertedTypes.add(ImplBrowsingDataType.SITE_SETTINGS);
break;
default:
break; // Skip unrecognized values for forward compatibility.
}
}
return CollectionUtil.integerListToIntArray(convertedTypes);
}
long getNativeProfile() {
return mNativeProfile;
}
@CalledByNative
public void downloadsInitialized() {
mDownloadsInitialized = true;
for (Intent intent : mDownloadNotificationIntents) {
DownloadImpl.handleIntent(intent);
}
mDownloadNotificationIntents.clear();
}
@CalledByNative
public long getBrowserForNewTab() throws RemoteException {
if (mOpenUrlCallbackClient == null) return 0;
IBrowser browser = mOpenUrlCallbackClient.getBrowserForNewTab();
if (browser == null) return 0;
return ((BrowserImpl) browser).getNativeBrowser();
}
@CalledByNative
public void onTabAdded(TabImpl tab) throws RemoteException {
if (mOpenUrlCallbackClient == null) return;
mOpenUrlCallbackClient.onTabAdded(tab.getId());
}
@Override
public void setBooleanSetting(@SettingType int type, boolean value) {
ProfileImplJni.get().setBooleanSetting(mNativeProfile, type, value);
}
@Override
public boolean getBooleanSetting(@SettingType int type) {
return ProfileImplJni.get().getBooleanSetting(mNativeProfile, type);
}
public void fetchAccessTokenForTesting(IObjectWrapper scopesWrapper,
IObjectWrapper onTokenFetchedWrapper) throws RemoteException {
mAccessTokenFetcherProxy.fetchAccessToken(ObjectWrapper.unwrap(scopesWrapper, Set.class),
ObjectWrapper.unwrap(onTokenFetchedWrapper, ValueCallback.class));
}
public void fireOnAccessTokenIdentifiedAsInvalidForTesting(
IObjectWrapper scopesWrapper, IObjectWrapper tokenWrapper) throws RemoteException {
mAccessTokenFetcherProxy.onAccessTokenIdentifiedAsInvalid(
ObjectWrapper.unwrap(scopesWrapper, Set.class),
ObjectWrapper.unwrap(tokenWrapper, String.class));
}
@NativeMethods
interface Natives {
void enumerateAllProfileNames(Callback<String[]> callback);
long createProfile(String name, ProfileImpl caller, boolean isIncognito);
void deleteProfile(long profile);
long getBrowserContext(long nativeProfileImpl);
int getNumBrowserImpl(long nativeProfileImpl);
void destroyAndDeleteDataFromDisk(long nativeProfileImpl, Runnable completionCallback);
void clearBrowsingData(long nativeProfileImpl, @ImplBrowsingDataType int[] dataTypes,
long fromMillis, long toMillis, Runnable callback);
void setDownloadDirectory(long nativeProfileImpl, String directory);
long getCookieManager(long nativeProfileImpl);
long getPrerenderController(long nativeProfileImpl);
void ensureBrowserContextInitialized(long nativeProfileImpl);
void setBooleanSetting(long nativeProfileImpl, int type, boolean value);
boolean getBooleanSetting(long nativeProfileImpl, int type);
void getBrowserPersistenceIds(long nativeProfileImpl, Callback<String[]> callback);
void removeBrowserPersistenceStorage(
long nativeProfileImpl, String[] ids, Callback<Boolean> callback);
void prepareForPossibleCrossOriginNavigation(long nativeProfileImpl);
void getCachedFaviconForPageUrl(
long nativeProfileImpl, String url, Callback<Bitmap> callback);
void markAsDeleted(long nativeProfileImpl);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ProfileImpl.java | Java | unknown | 18,266 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import java.util.HashMap;
import java.util.Map;
/**
* Creates and maintains the active Profiles.
*/
public class ProfileManager {
private final Map<String, ProfileImpl> mProfiles = new HashMap<>();
private final Map<String, ProfileImpl> mIncognitoProfiles = new HashMap<>();
/** Returns existing or new Profile associated with the given name. */
public ProfileImpl getProfile(String name, boolean isIncognito) {
if (name == null) throw new IllegalArgumentException("Name shouldn't be null");
Map<String, ProfileImpl> nameToProfileMap = getMapForProfileType(isIncognito);
ProfileImpl existingProfile = nameToProfileMap.get(name);
if (existingProfile != null) {
return existingProfile;
}
ProfileImpl profile =
new ProfileImpl(name, isIncognito, () -> nameToProfileMap.remove(name));
nameToProfileMap.put(name, profile);
return profile;
}
private Map<String, ProfileImpl> getMapForProfileType(boolean isIncognito) {
return isIncognito ? mIncognitoProfiles : mProfiles;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/ProfileManager.java | Java | unknown | 1,288 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Build;
import android.os.Bundle;
import android.view.SurfaceControlViewHost;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IRemoteFragment;
import org.chromium.weblayer_private.interfaces.IRemoteFragmentClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
/**
* Base for the classes controlling a Fragment that exists in another ClassLoader. Extending this
* class is similar to extending Fragment: e.g. one can override lifecycle methods, not forgetting
* to call super, etc.
*/
public abstract class RemoteFragmentImpl extends IRemoteFragment.Stub {
@Nullable
protected IRemoteFragmentClient mClient;
protected RemoteFragmentImpl() {}
// TODO(swestphal): remove this.
protected final Activity getActivity() {
return null;
}
protected final View getView() {
return null;
}
protected void onCreate() {}
protected void onAttach(Context context) {}
protected void onStart() {}
protected void onDestroy() {}
protected void onDetach() {}
protected void onResume() {}
protected void onDestroyView() {}
protected void onStop() {}
protected void onPause() {}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {}
protected void requestPermissions(String[] permissions, int requestCode) {}
protected void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {}
@RequiresApi(Build.VERSION_CODES.R)
protected void setSurfaceControlViewHost(SurfaceControlViewHost host) {}
protected View getContentViewRenderView() {
return null;
}
protected void setMinimumSurfaceSize(int width, int height) {}
// TODO(crbug/1378606): Either remove below methods together with callers or provide a client
// implementation on weblayer side.
protected boolean startActivityForResult(Intent intent, int requestCode, Bundle options) {
return false;
}
protected boolean startIntentSenderForResult(IntentSender intent, int requestCode,
Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) {
return false;
}
protected boolean shouldShowRequestPermissionRationale(String permission) {
return false;
}
protected void removeFragmentFromFragmentManager() {}
// IRemoteFragment implementation below.
@Override
public void setClient(IRemoteFragmentClient client) {
mClient = client;
}
@Override
public final void handleOnStart() {
StrictModeWorkaround.apply();
onStart();
}
@Override
public final void handleOnCreate() {
StrictModeWorkaround.apply();
onCreate();
}
@Override
public final void handleOnAttach(IObjectWrapper context) {
StrictModeWorkaround.apply();
onAttach(ObjectWrapper.unwrap(context, Context.class));
}
@Override
public final void handleOnResume() {
StrictModeWorkaround.apply();
onResume();
}
@Override
public final void handleOnPause() {
StrictModeWorkaround.apply();
onPause();
}
@Override
public final void handleOnStop() {
StrictModeWorkaround.apply();
onStop();
}
@Override
public final void handleOnDestroyView() {
StrictModeWorkaround.apply();
onDestroyView();
}
@Override
public final void handleOnDetach() {
StrictModeWorkaround.apply();
onDetach();
}
@Override
public final void handleOnDestroy() {
StrictModeWorkaround.apply();
onDestroy();
}
@Override
public final void handleOnActivityResult(int requestCode, int resultCode, IObjectWrapper data) {
StrictModeWorkaround.apply();
onActivityResult(requestCode, resultCode, ObjectWrapper.unwrap(data, Intent.class));
}
@Override
public final void handleOnRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
StrictModeWorkaround.apply();
onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@RequiresApi(Build.VERSION_CODES.R)
@Override
public final void handleSetSurfaceControlViewHost(IObjectWrapper host) {
StrictModeWorkaround.apply();
setSurfaceControlViewHost(ObjectWrapper.unwrap(host, SurfaceControlViewHost.class));
}
@Override
public final IObjectWrapper handleGetContentViewRenderView() {
StrictModeWorkaround.apply();
return ObjectWrapper.wrap(getContentViewRenderView());
}
@Override
public final void handleSetMinimumSurfaceSize(int width, int height) {
StrictModeWorkaround.apply();
setMinimumSurfaceSize(width, height);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/RemoteFragmentImpl.java | Java | unknown | 5,397 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.RemoteException;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.weblayer_private.interfaces.ITabClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
/**
* Owns the C++ TabCallbackProxy class, which is responsible for forwarding all
* BrowserObserver calls to this class, which in turn forwards to the TabClient.
* To avoid unnecessary IPC only one TabCallbackProxy is created per Tab.
*/
@JNINamespace("weblayer")
public final class TabCallbackProxy {
private long mNativeTabCallbackProxy;
private ITabClient mClient;
TabCallbackProxy(long tab, ITabClient client) {
mClient = client;
mNativeTabCallbackProxy = TabCallbackProxyJni.get().createTabCallbackProxy(this, tab);
}
public void destroy() {
TabCallbackProxyJni.get().deleteTabCallbackProxy(mNativeTabCallbackProxy);
mNativeTabCallbackProxy = 0;
}
@CalledByNative
private void visibleUriChanged(String string) throws RemoteException {
mClient.visibleUriChanged(string);
}
@CalledByNative
private void onRenderProcessGone() throws RemoteException {
mClient.onRenderProcessGone();
}
@CalledByNative
private void onTitleUpdated(String title) throws RemoteException {
mClient.onTitleUpdated(ObjectWrapper.wrap(title));
}
@NativeMethods
interface Natives {
long createTabCallbackProxy(TabCallbackProxy proxy, long tab);
void deleteTabCallbackProxy(long proxy);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/TabCallbackProxy.java | Java | unknown | 1,820 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import static org.chromium.cc.mojom.RootScrollOffsetUpdateFrequency.ALL_UPDATES;
import android.Manifest.permission;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.util.Pair;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ViewStructure;
import android.view.autofill.AutofillValue;
import android.webkit.ValueCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.Callback;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.base.supplier.ObservableSupplier;
import org.chromium.components.autofill.AutofillActionModeCallback;
import org.chromium.components.autofill.AutofillProvider;
import org.chromium.components.browser_ui.display_cutout.DisplayCutoutController;
import org.chromium.components.browser_ui.media.MediaSessionHelper;
import org.chromium.components.browser_ui.widget.InsetObserverView;
import org.chromium.components.embedder_support.contextmenu.ContextMenuParams;
import org.chromium.components.embedder_support.util.UrlUtilities;
import org.chromium.components.external_intents.InterceptNavigationDelegateImpl;
import org.chromium.components.find_in_page.FindInPageBridge;
import org.chromium.components.find_in_page.FindMatchRectsDetails;
import org.chromium.components.find_in_page.FindResultBar;
import org.chromium.components.infobars.InfoBar;
import org.chromium.components.url_formatter.UrlFormatter;
import org.chromium.components.webapps.AddToHomescreenCoordinator;
import org.chromium.components.webapps.AppBannerManager;
import org.chromium.content_public.browser.GestureListenerManager;
import org.chromium.content_public.browser.GestureStateListener;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.MessagePayload;
import org.chromium.content_public.browser.MessagePayloadType;
import org.chromium.content_public.browser.MessagePort;
import org.chromium.content_public.browser.MessagePort.MessageCallback;
import org.chromium.content_public.browser.NavigationHandle;
import org.chromium.content_public.browser.SelectionClient;
import org.chromium.content_public.browser.SelectionPopupController;
import org.chromium.content_public.browser.ViewEventSink;
import org.chromium.content_public.browser.Visibility;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;
import org.chromium.ui.base.ViewAndroidDelegate;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.url.GURL;
import org.chromium.weblayer_private.interfaces.APICallException;
import org.chromium.weblayer_private.interfaces.ExceptionType;
import org.chromium.weblayer_private.interfaces.IContextMenuParams;
import org.chromium.weblayer_private.interfaces.IErrorPageCallbackClient;
import org.chromium.weblayer_private.interfaces.IExternalIntentInIncognitoCallbackClient;
import org.chromium.weblayer_private.interfaces.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.INavigationControllerClient;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IStringCallback;
import org.chromium.weblayer_private.interfaces.ITab;
import org.chromium.weblayer_private.interfaces.ITabClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.ScrollNotificationType;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import org.chromium.weblayer_private.media.MediaSessionManager;
import org.chromium.weblayer_private.media.MediaStreamManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Implementation of ITab.
*/
@JNINamespace("weblayer")
public final class TabImpl extends ITab.Stub {
private static int sNextId = 1;
// Map from id to TabImpl.
private static final Map<Integer, TabImpl> sTabMap = new HashMap<Integer, TabImpl>();
private long mNativeTab;
private ProfileImpl mProfile;
private WebContents mWebContents;
private WebContentsObserver mWebContentsObserver;
private TabCallbackProxy mTabCallbackProxy;
private NavigationControllerImpl mNavigationController;
private ErrorPageCallbackProxy mErrorPageCallbackProxy;
private FullscreenCallbackProxy mFullscreenCallbackProxy;
private TabViewAndroidDelegate mViewAndroidDelegate;
private GoogleAccountsCallbackProxy mGoogleAccountsCallbackProxy;
private ExternalIntentInIncognitoCallbackProxy mExternalIntentInIncognitoCallbackProxy;
private MessagePort[] mChannel;
// BrowserImpl this TabImpl is in.
@NonNull
private BrowserImpl mBrowser;
/**
* The AutofillProvider that integrates with system-level autofill. This is null until
* updateFromBrowser() is invoked.
*/
private AutofillProvider mAutofillProvider;
private MediaStreamManager mMediaStreamManager;
private NewTabCallbackProxy mNewTabCallbackProxy;
private ITabClient mClient;
private final int mId;
private IFindInPageCallbackClient mFindInPageCallbackClient;
private FindInPageBridge mFindInPageBridge;
private FindResultBar mFindResultBar;
// See usage note in {@link #onFindResultAvailable}.
private boolean mWaitingForMatchRects;
private InterceptNavigationDelegateClientImpl mInterceptNavigationDelegateClient;
private InterceptNavigationDelegateImpl mInterceptNavigationDelegate;
private InfoBarContainer mInfoBarContainer;
private MediaSessionHelper mMediaSessionHelper;
private DisplayCutoutController mDisplayCutoutController;
private boolean mPostContainerViewInitDone;
private ActionModeCallback mActionModeCallback;
private Set<FaviconCallbackProxy> mFaviconCallbackProxies = new HashSet<>();
// Only non-null if scroll offsets have been requested.
private @Nullable GestureStateListener mGestureStateListener;
private HeaderVerificationStatus mHeaderVerification;
enum HeaderVerificationStatus {
PENDING,
NOT_VALIDATED,
VALIDATED,
}
private static class InternalAccessDelegateImpl
implements ViewEventSink.InternalAccessDelegate {
@Override
public boolean super_onKeyUp(int keyCode, KeyEvent event) {
return false;
}
@Override
public boolean super_dispatchKeyEvent(KeyEvent event) {
return false;
}
@Override
public boolean super_onGenericMotionEvent(MotionEvent event) {
return false;
}
@Override
public void onScrollChanged(int lPix, int tPix, int oldlPix, int oldtPix) {}
}
private class TabViewAndroidDelegate extends ViewAndroidDelegate {
private boolean mIgnoreRenderer;
TabViewAndroidDelegate() {
super(null);
}
/**
* Causes {@link onTopControlsChanged()} and {@link onBottomControlsChanged()} to be
* ignored.
* @param ignoreRenderer whether to ignore renderer-initiated updates to the controls state.
*/
public void setIgnoreRendererUpdates(boolean ignoreRenderer) {
mIgnoreRenderer = ignoreRenderer;
}
@Override
public void onBackgroundColorChanged(int color) {
try {
mClient.onBackgroundColorChanged(color);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
@Override
protected void onVerticalScrollDirectionChanged(
boolean directionUp, float currentScrollRatio) {
super.onVerticalScrollDirectionChanged(directionUp, currentScrollRatio);
try {
mClient.onScrollNotification(directionUp
? ScrollNotificationType.DIRECTION_CHANGED_UP
: ScrollNotificationType.DIRECTION_CHANGED_DOWN,
currentScrollRatio);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
}
class NativeStringCallback implements Callback<String> {
private IStringCallback mCallback;
NativeStringCallback(IStringCallback callback) {
mCallback = callback;
}
@Override
public void onResult(String result) {
try {
mCallback.onResult(result);
} catch (RemoteException e) {
}
}
}
public static TabImpl fromWebContents(WebContents webContents) {
if (webContents == null || webContents.isDestroyed()) return null;
return TabImplJni.get().fromWebContents(webContents);
}
public static TabImpl getTabById(int tabId) {
return sTabMap.get(tabId);
}
public TabImpl(BrowserImpl browser, ProfileImpl profile, WindowAndroid windowAndroid) {
mBrowser = browser;
mId = ++sNextId;
init(profile, windowAndroid, TabImplJni.get().createTab(profile.getNativeProfile(), this));
}
/**
* This constructor is called when the native side triggers creation of a TabImpl
* (as happens with popups and other scenarios).
*/
public TabImpl(
BrowserImpl browser, ProfileImpl profile, WindowAndroid windowAndroid, long nativeTab) {
mId = ++sNextId;
mBrowser = browser;
TabImplJni.get().setJavaImpl(nativeTab, TabImpl.this);
init(profile, windowAndroid, nativeTab);
}
private void init(ProfileImpl profile, WindowAndroid windowAndroid, long nativeTab) {
mProfile = profile;
mNativeTab = nativeTab;
mWebContents = TabImplJni.get().getWebContents(mNativeTab);
mViewAndroidDelegate = new TabViewAndroidDelegate();
mWebContents.initialize("", mViewAndroidDelegate, new InternalAccessDelegateImpl(),
windowAndroid, WebContents.createDefaultInternalsHolder());
mWebContentsObserver = new WebContentsObserver() {
@Override
public void didStartNavigationInPrimaryMainFrame(NavigationHandle navigationHandle) {
if (!navigationHandle.isSameDocument()) {
hideFindInPageUiAndNotifyClient();
}
}
@Override
public void viewportFitChanged(@WebContentsObserver.ViewportFitType int value) {
ensureDisplayCutoutController();
mDisplayCutoutController.setViewportFit(value);
}
};
mWebContents.addObserver(mWebContentsObserver);
mHeaderVerification = HeaderVerificationStatus.PENDING;
mMediaStreamManager = new MediaStreamManager(this);
mInterceptNavigationDelegateClient = new InterceptNavigationDelegateClientImpl(this);
mInterceptNavigationDelegate =
new InterceptNavigationDelegateImpl(mInterceptNavigationDelegateClient);
mInterceptNavigationDelegateClient.initializeWithDelegate(mInterceptNavigationDelegate);
sTabMap.put(mId, this);
mInfoBarContainer = new InfoBarContainer(this);
mMediaSessionHelper = new MediaSessionHelper(
mWebContents, MediaSessionManager.createMediaSessionHelperDelegate(this));
GestureListenerManager.fromWebContents(mWebContents)
.addListener(new GestureStateListener() {
@Override
public void didOverscroll(
float accumulatedOverscrollX, float accumulatedOverscrollY) {
if (WebLayerFactoryImpl.getClientMajorVersion() < 101) return;
try {
mClient.onVerticalOverscroll(accumulatedOverscrollY);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
}, ALL_UPDATES);
}
private void doInitAfterSettingContainerView() {
if (mPostContainerViewInitDone) return;
if (mBrowser.getBrowserFragment().getViewAndroidDelegateContainerView() != null) {
mPostContainerViewInitDone = true;
SelectionPopupController selectionPopupController =
SelectionPopupController.fromWebContents(mWebContents);
mActionModeCallback = new ActionModeCallback(mWebContents);
mActionModeCallback.setTabClient(mClient);
selectionPopupController.setActionModeCallback(mActionModeCallback);
selectionPopupController.setSelectionClient(
SelectionClient.createSmartSelectionClient(mWebContents));
}
}
public ProfileImpl getProfile() {
return mProfile;
}
public ITabClient getClient() {
return mClient;
}
public void setHeaderVerification(HeaderVerificationStatus headerVerification) {
mHeaderVerification = headerVerification;
}
/**
* Sets the BrowserImpl this TabImpl is contained in.
*/
public void attachToBrowser(BrowserImpl browser) {
// NOTE: during tab creation this is called with |browser| set to |mBrowser|. This happens
// because the tab is created with |mBrowser| already set (to avoid having a bunch of null
// checks).
mBrowser = browser;
updateFromBrowser();
}
public void updateFromBrowser() {
mViewAndroidDelegate.setContainerView(
mBrowser.getBrowserFragment().getViewAndroidDelegateContainerView());
doInitAfterSettingContainerView();
updateViewAttachedStateFromBrowser();
boolean attached = mBrowser.getBrowserFragment().isAttached();
mInterceptNavigationDelegateClient.onActivityAttachmentChanged(attached);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
SelectionPopupController selectionController =
SelectionPopupController.fromWebContentsNoCreate(mWebContents);
if (!attached) {
// The Context and ViewContainer in which Autofill was previously operating have
// gone away, so tear down |mAutofillProvider|.
if (mAutofillProvider != null) {
mAutofillProvider.destroy();
mAutofillProvider = null;
}
if (selectionController != null) {
selectionController.setNonSelectionActionModeCallback(null);
}
} else {
if (mAutofillProvider == null) {
// Set up |mAutofillProvider| to operate in the new Context. It's safe to assume
// the context won't change unless it is first nulled out, since the fragment
// must be detached before it can be reattached to a new Context.
mAutofillProvider = new AutofillProvider(mBrowser.getContext(),
mBrowser.getBrowserFragment().getViewAndroidDelegateContainerView(),
mWebContents, "WebLayer");
TabImplJni.get().initializeAutofillIfNecessary(mNativeTab);
}
mAutofillProvider.onContainerViewChanged(
mBrowser.getBrowserFragment().getViewAndroidDelegateContainerView());
mAutofillProvider.setWebContents(mWebContents);
if (selectionController != null) {
selectionController.setNonSelectionActionModeCallback(
new AutofillActionModeCallback(
mBrowser.getContext(), mAutofillProvider));
}
}
}
}
@VisibleForTesting
public AutofillProvider getAutofillProviderForTesting() {
// The test needs to make sure the |mAutofillProvider| is not null.
return mAutofillProvider;
}
public void updateViewAttachedStateFromBrowser() {
updateWebContentsVisibility();
updateDisplayCutoutController();
}
public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
if (mAutofillProvider == null) return;
mAutofillProvider.onProvideAutoFillVirtualStructure(structure, flags);
}
public void autofill(final SparseArray<AutofillValue> values) {
if (mAutofillProvider == null) return;
mAutofillProvider.autofill(values);
}
public BrowserImpl getBrowser() {
return mBrowser;
}
@Override
public void setNewTabsEnabled(boolean enable) {
StrictModeWorkaround.apply();
if (enable && mNewTabCallbackProxy == null) {
mNewTabCallbackProxy = new NewTabCallbackProxy(this);
} else if (!enable && mNewTabCallbackProxy != null) {
mNewTabCallbackProxy.destroy();
mNewTabCallbackProxy = null;
}
}
@Override
public int getId() {
StrictModeWorkaround.apply();
return mId;
}
@Override
public String getUri() {
StrictModeWorkaround.apply();
return mWebContents.getVisibleUrl().getSpec();
}
/**
* Called when this TabImpl is attached to the BrowserViewController.
*/
public void onAttachedToViewController() {
mWebContents.setTopLevelNativeWindow(mBrowser.getBrowserFragment().getWindowAndroid());
doInitAfterSettingContainerView();
mInfoBarContainer.onTabAttachedToViewController();
updateWebContentsVisibility();
updateDisplayCutoutController();
}
/**
* Called when this TabImpl is detached from the BrowserViewController.
*/
public void onDetachedFromViewController() {
mWebContents.setTopLevelNativeWindow(null);
if (mAutofillProvider != null) {
mAutofillProvider.hidePopup();
}
if (mFullscreenCallbackProxy != null) mFullscreenCallbackProxy.destroyToast();
hideFindInPageUiAndNotifyClient();
updateWebContentsVisibility();
updateDisplayCutoutController();
// This method is called as part of the final phase of TabImpl destruction, at which
// point mInfoBarContainer has already been destroyed.
if (mInfoBarContainer != null) {
mInfoBarContainer.onTabDetachedFromViewController();
}
}
/**
* Returns whether this Tab is visible.
*/
public boolean isVisible() {
return isActiveTab() && mBrowser.getBrowserFragment().isVisible();
}
@CalledByNative
public boolean willAutomaticallyReloadAfterCrashImpl() {
return !isVisible();
}
@Override
public boolean willAutomaticallyReloadAfterCrash() {
StrictModeWorkaround.apply();
return willAutomaticallyReloadAfterCrashImpl();
}
public boolean isActiveTab() {
return mBrowser.getActiveTab() == this;
}
private void updateWebContentsVisibility() {
if (SelectionPopupController.fromWebContentsNoCreate(mWebContents) == null) return;
boolean visibleNow = isVisible();
boolean webContentsVisible = mWebContents.getVisibility() == Visibility.VISIBLE;
if (visibleNow) {
if (!webContentsVisible) mWebContents.onShow();
} else {
if (webContentsVisible) mWebContents.onHide();
}
}
private void updateDisplayCutoutController() {
if (mDisplayCutoutController == null) return;
mDisplayCutoutController.onActivityAttachmentChanged(
mBrowser.getBrowserFragment().getWindowAndroid());
mDisplayCutoutController.maybeUpdateLayout();
}
public void loadUrl(LoadUrlParams loadUrlParams) {
String url = loadUrlParams.getUrl();
if (url == null || url.isEmpty()) return;
// TODO(https://crbug.com/783819): Don't fix up all URLs. Documentation on FixupURL
// explicitly says not to use it on URLs coming from untrustworthy sources, like other apps.
// Once migrations of Java code to GURL are complete and incoming URLs are converted to
// GURLs at their source, we can make decisions of whether or not to fix up GURLs on a
// case-by-case basis based on trustworthiness of the incoming URL.
GURL fixedUrl = UrlFormatter.fixupUrl(url);
if (!fixedUrl.isValid()) return;
loadUrlParams.setUrl(fixedUrl.getSpec());
getWebContents().getNavigationController().loadUrl(loadUrlParams);
}
public WebContents getWebContents() {
return mWebContents;
}
public NavigationControllerImpl getNavigationControllerImpl() {
return mNavigationController;
}
// Public for tests.
@VisibleForTesting
public long getNativeTab() {
return mNativeTab;
}
@VisibleForTesting
public InfoBarContainer getInfoBarContainerForTesting() {
return mInfoBarContainer;
}
@Override
public NavigationControllerImpl createNavigationController(INavigationControllerClient client) {
StrictModeWorkaround.apply();
// This should only be called once.
assert mNavigationController == null;
mNavigationController = new NavigationControllerImpl(this, client);
return mNavigationController;
}
@Override
public void setClient(ITabClient client) {
StrictModeWorkaround.apply();
mClient = client;
mTabCallbackProxy = new TabCallbackProxy(mNativeTab, client);
}
@Override
public void setErrorPageCallbackClient(IErrorPageCallbackClient client) {
StrictModeWorkaround.apply();
if (client != null) {
if (mErrorPageCallbackProxy == null) {
mErrorPageCallbackProxy = new ErrorPageCallbackProxy(mNativeTab, client);
} else {
mErrorPageCallbackProxy.setClient(client);
}
} else if (mErrorPageCallbackProxy != null) {
mErrorPageCallbackProxy.destroy();
mErrorPageCallbackProxy = null;
}
}
@Override
public void setFullscreenCallbackClient(IFullscreenCallbackClient client) {
StrictModeWorkaround.apply();
if (client != null) {
if (mFullscreenCallbackProxy == null) {
mFullscreenCallbackProxy = new FullscreenCallbackProxy(this, mNativeTab, client);
} else {
mFullscreenCallbackProxy.setClient(client);
}
} else if (mFullscreenCallbackProxy != null) {
mFullscreenCallbackProxy.destroy();
mFullscreenCallbackProxy = null;
}
}
@Override
public void setGoogleAccountsCallbackClient(IGoogleAccountsCallbackClient client) {
StrictModeWorkaround.apply();
if (client != null) {
if (mGoogleAccountsCallbackProxy == null) {
mGoogleAccountsCallbackProxy = new GoogleAccountsCallbackProxy(mNativeTab, client);
} else {
mGoogleAccountsCallbackProxy.setClient(client);
}
} else if (mGoogleAccountsCallbackProxy != null) {
mGoogleAccountsCallbackProxy.destroy();
mGoogleAccountsCallbackProxy = null;
}
}
public GoogleAccountsCallbackProxy getGoogleAccountsCallbackProxy() {
return mGoogleAccountsCallbackProxy;
}
@Override
public IFaviconFetcher createFaviconFetcher(IFaviconFetcherClient client) {
StrictModeWorkaround.apply();
FaviconCallbackProxy proxy = new FaviconCallbackProxy(this, mNativeTab, client);
mFaviconCallbackProxies.add(proxy);
return proxy;
}
@Override
public void setTranslateTargetLanguage(String targetLanguage) {
StrictModeWorkaround.apply();
TabImplJni.get().setTranslateTargetLanguage(mNativeTab, targetLanguage);
}
@Override
public void setScrollOffsetsEnabled(boolean enabled) {
StrictModeWorkaround.apply();
if (enabled) {
if (mGestureStateListener == null) {
mGestureStateListener = new GestureStateListener() {
@Override
public void onScrollOffsetOrExtentChanged(
int scrollOffsetY, int scrollExtentY) {
try {
mClient.onVerticalScrollOffsetChanged(scrollOffsetY);
} catch (RemoteException e) {
throw new APICallException(e);
}
}
};
GestureListenerManager.fromWebContents(mWebContents)
.addListener(mGestureStateListener, ALL_UPDATES);
}
} else if (mGestureStateListener != null) {
GestureListenerManager.fromWebContents(mWebContents)
.removeListener(mGestureStateListener);
mGestureStateListener = null;
}
}
@Override
public void setFloatingActionModeOverride(int actionModeItemTypes) {
StrictModeWorkaround.apply();
mActionModeCallback.setOverride(actionModeItemTypes);
}
@Override
public void setDesktopUserAgentEnabled(boolean enable) {
StrictModeWorkaround.apply();
TabImplJni.get().setDesktopUserAgentEnabled(mNativeTab, enable);
}
@Override
public boolean isDesktopUserAgentEnabled() {
StrictModeWorkaround.apply();
return TabImplJni.get().isDesktopUserAgentEnabled(mNativeTab);
}
@Override
public void download(IContextMenuParams contextMenuParams) {
StrictModeWorkaround.apply();
NativeContextMenuParamsHolder nativeContextMenuParamsHolder =
(NativeContextMenuParamsHolder) contextMenuParams;
WindowAndroid window = getBrowser().getBrowserFragment().getWindowAndroid();
if (window.hasPermission(permission.WRITE_EXTERNAL_STORAGE)) {
continueDownload(nativeContextMenuParamsHolder);
return;
}
String[] requestPermissions = new String[] {permission.WRITE_EXTERNAL_STORAGE};
window.requestPermissions(requestPermissions, (permissions, grantResults) -> {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
continueDownload(nativeContextMenuParamsHolder);
}
});
}
private void continueDownload(NativeContextMenuParamsHolder nativeContextMenuParamsHolder) {
TabImplJni.get().download(
mNativeTab, nativeContextMenuParamsHolder.mNativeContextMenuParams);
}
@Override
public void addToHomescreen() {
StrictModeWorkaround.apply();
// TODO(estade): should it be verified that |this| is the active tab?
// This is used for UMA, and is only meaningful for Chrome. TODO(estade): remove.
Bundle menuItemData = new Bundle();
menuItemData.putInt(AppBannerManager.MENU_TITLE_KEY, 0);
// TODO(estade): simplify these parameters.
AddToHomescreenCoordinator.showForAppMenu(mBrowser.getContext(),
mBrowser.getBrowserFragment().getWindowAndroid(),
mBrowser.getBrowserFragment().getWindowAndroid().getModalDialogManager(),
mWebContents, menuItemData);
}
@Override
public void setExternalIntentInIncognitoCallbackClient(
IExternalIntentInIncognitoCallbackClient client) {
StrictModeWorkaround.apply();
if (client != null) {
if (mExternalIntentInIncognitoCallbackProxy == null) {
mExternalIntentInIncognitoCallbackProxy =
new ExternalIntentInIncognitoCallbackProxy(client);
} else {
mExternalIntentInIncognitoCallbackProxy.setClient(client);
}
} else if (mExternalIntentInIncognitoCallbackProxy != null) {
mExternalIntentInIncognitoCallbackProxy = null;
}
}
public ExternalIntentInIncognitoCallbackProxy getExternalIntentInIncognitoCallbackProxy() {
return mExternalIntentInIncognitoCallbackProxy;
}
public void removeFaviconCallbackProxy(FaviconCallbackProxy proxy) {
mFaviconCallbackProxies.remove(proxy);
}
@Override
public void executeScript(String script, boolean useSeparateIsolate, IStringCallback callback) {
StrictModeWorkaround.apply();
if (mHeaderVerification == HeaderVerificationStatus.VALIDATED) {
TabImplJni.get().executeScript(
mNativeTab, script, useSeparateIsolate, new NativeStringCallback(callback));
return;
}
WebLayerOriginVerificationScheduler originVerifier =
WebLayerOriginVerificationScheduler.getInstance();
String url = mWebContents.getVisibleUrl().getSpec();
originVerifier.verify(url, (verified) -> {
// Make sure the page hasn't changed since we started verification.
if (!url.equals(mWebContents.getVisibleUrl().getSpec())) {
return;
}
if (!verified) {
try {
callback.onException(ExceptionType.RESTRICTED_API,
"Application does not have permissions to modify " + url);
} catch (RemoteException e) {
}
}
TabImplJni.get().executeScript(
mNativeTab, script, useSeparateIsolate, new NativeStringCallback(callback));
});
}
@Override
public boolean setFindInPageCallbackClient(IFindInPageCallbackClient client) {
StrictModeWorkaround.apply();
if (client == null) {
// Null now to avoid calling onFindEnded.
mFindInPageCallbackClient = null;
hideFindInPageUiAndNotifyClient();
return true;
}
if (mFindInPageCallbackClient != null) return false;
BrowserViewController controller = getViewController();
if (controller == null) return false;
mFindInPageCallbackClient = client;
assert mFindInPageBridge == null;
mFindInPageBridge = new FindInPageBridge(mWebContents);
assert mFindResultBar == null;
mFindResultBar =
new FindResultBar(mBrowser.getContext(), controller.getWebContentsOverlayView(),
mBrowser.getBrowserFragment().getWindowAndroid(), mFindInPageBridge);
return true;
}
@Override
public void findInPage(String searchText, boolean forward) {
StrictModeWorkaround.apply();
if (mFindInPageBridge == null) return;
if (searchText.length() > 0) {
mFindInPageBridge.startFinding(searchText, forward, false);
} else {
mFindInPageBridge.stopFinding(true);
}
}
private void hideFindInPageUiAndNotifyClient() {
if (mFindInPageBridge == null) return;
mFindInPageBridge.stopFinding(true);
mFindResultBar.dismiss();
mFindResultBar = null;
mFindInPageBridge.destroy();
mFindInPageBridge = null;
try {
if (mFindInPageCallbackClient != null) mFindInPageCallbackClient.onFindEnded();
mFindInPageCallbackClient = null;
} catch (RemoteException e) {
throw new AndroidRuntimeException(e);
}
}
@Override
public void dispatchBeforeUnloadAndClose() {
StrictModeWorkaround.apply();
mWebContents.dispatchBeforeUnload(false);
}
@Override
public boolean dismissTransientUi() {
StrictModeWorkaround.apply();
BrowserViewController viewController = getViewController();
if (viewController != null && viewController.dismissTabModalOverlay()) return true;
if (mWebContents.isFullscreenForCurrentTab()) {
mWebContents.exitFullscreen();
return true;
}
SelectionPopupController popup =
SelectionPopupController.fromWebContentsNoCreate(mWebContents);
if (popup != null && popup.isSelectActionBarShowing()) {
popup.clearSelection();
return true;
}
return false;
}
@Override
public String getGuid() {
StrictModeWorkaround.apply();
return TabImplJni.get().getGuid(mNativeTab);
}
@Override
public boolean setData(Map data) {
StrictModeWorkaround.apply();
String[] flattenedMap = new String[data.size() * 2];
int i = 0;
for (Map.Entry<String, String> entry : ((Map<String, String>) data).entrySet()) {
flattenedMap[i++] = entry.getKey();
flattenedMap[i++] = entry.getValue();
}
return TabImplJni.get().setData(mNativeTab, flattenedMap);
}
@Override
public Map getData() {
StrictModeWorkaround.apply();
String[] data = TabImplJni.get().getData(mNativeTab);
Map<String, String> map = new HashMap<>();
for (int i = 0; i < data.length; i += 2) {
map.put(data[i], data[i + 1]);
}
return map;
}
@Override
public void captureScreenShot(float scale, IObjectWrapper valueCallback) {
StrictModeWorkaround.apply();
ValueCallback<Pair<Bitmap, Integer>> unwrappedCallback =
(ValueCallback<Pair<Bitmap, Integer>>) ObjectWrapper.unwrap(
valueCallback, ValueCallback.class);
TabImplJni.get().captureScreenShot(mNativeTab, scale, unwrappedCallback);
}
@Override
public boolean canTranslate() {
StrictModeWorkaround.apply();
return TabImplJni.get().canTranslate(mNativeTab);
}
@Override
public void showTranslateUi() {
StrictModeWorkaround.apply();
TabImplJni.get().showTranslateUi(mNativeTab);
}
@CalledByNative
private static void runCaptureScreenShotCallback(
ValueCallback<Pair<Bitmap, Integer>> callback, Bitmap bitmap, int errorCode) {
callback.onReceiveValue(Pair.create(bitmap, errorCode));
}
@CalledByNative
private static RectF createRectF(float x, float y, float right, float bottom) {
return new RectF(x, y, right, bottom);
}
@CalledByNative
private static FindMatchRectsDetails createFindMatchRectsDetails(
int version, int numRects, RectF activeRect) {
return new FindMatchRectsDetails(version, numRects, activeRect);
}
@CalledByNative
private static void setMatchRectByIndex(
FindMatchRectsDetails findMatchRectsDetails, int index, RectF rect) {
findMatchRectsDetails.rects[index] = rect;
}
@CalledByNative
private void onFindResultAvailable(int numberOfMatches, int activeMatchOrdinal,
boolean finalUpdate) throws RemoteException {
if (mFindInPageCallbackClient != null) {
// The WebLayer API deals in indices instead of ordinals.
mFindInPageCallbackClient.onFindResult(
numberOfMatches, activeMatchOrdinal - 1, finalUpdate);
}
if (mFindResultBar != null) {
mFindResultBar.onFindResult();
if (finalUpdate) {
if (numberOfMatches > 0) {
mWaitingForMatchRects = true;
mFindInPageBridge.requestFindMatchRects(mFindResultBar.getRectsVersion());
} else {
// Match rects results that correlate to an earlier call to
// requestFindMatchRects might still come in, so set this sentinel to false to
// make sure we ignore them instead of showing stale results.
mWaitingForMatchRects = false;
mFindResultBar.clearMatchRects();
}
}
}
}
@CalledByNative
private void onFindMatchRectsAvailable(FindMatchRectsDetails matchRects) {
if (mFindResultBar != null && mWaitingForMatchRects) {
mFindResultBar.setMatchRects(
matchRects.version, matchRects.rects, matchRects.activeRect);
}
}
@Override
public void setMediaCaptureCallbackClient(IMediaCaptureCallbackClient client) {
StrictModeWorkaround.apply();
mMediaStreamManager.setClient(client);
}
@Override
public void stopMediaCapturing() {
StrictModeWorkaround.apply();
mMediaStreamManager.stopStreaming();
}
@CalledByNative
private void handleCloseFromWebContents() throws RemoteException {
if (getBrowser() == null) return;
getBrowser().destroyTab(this);
}
private String getAppOrigin() {
// TODO(rayankans): Consider exposing the embedder app's fingerprints as well.
return "app://" + mBrowser.getContext().getPackageName();
}
@Override
public void postMessage(String message, String targetOrigin) {
StrictModeWorkaround.apply();
if (mChannel == null || mChannel[0].isClosed() || mChannel[0].isTransferred()
|| mChannel[1].isClosed() || mChannel[1].isTransferred()) {
mChannel = mWebContents.createMessageChannel();
mChannel[0].setMessageCallback(new MessageCallback() {
@Override
public void onMessage(MessagePayload messagePayload, MessagePort[] sentPorts) {
try {
if (messagePayload.getType() == MessagePayloadType.ARRAY_BUFFER) {
// TODO(rayankans): Consider supporting passing array buffers.
return;
}
mClient.onPostMessage(messagePayload.getAsString(),
mWebContents.getVisibleUrl().getOrigin().getSpec());
} catch (RemoteException e) {
}
}
}, null);
}
mWebContents.postMessageToMainFrame(new MessagePayload(message), getAppOrigin(),
targetOrigin, new MessagePort[] {mChannel[1]});
}
public void destroy() {
// Ensure that this method isn't called twice.
assert mInterceptNavigationDelegate != null;
TabImplJni.get().removeTabFromBrowserBeforeDestroying(mNativeTab);
// Notify the client that this instance is being destroyed to prevent it from calling
// back into this object if the embedder mistakenly tries to do so.
try {
mClient.onTabDestroyed();
} catch (RemoteException e) {
throw new APICallException(e);
}
if (mDisplayCutoutController != null) {
mDisplayCutoutController.destroy();
mDisplayCutoutController = null;
}
// This is called to ensure a listener is removed from the WebContents.
setScrollOffsetsEnabled(false);
if (mTabCallbackProxy != null) {
mTabCallbackProxy.destroy();
mTabCallbackProxy = null;
}
if (mErrorPageCallbackProxy != null) {
mErrorPageCallbackProxy.destroy();
mErrorPageCallbackProxy = null;
}
if (mFullscreenCallbackProxy != null) {
mFullscreenCallbackProxy.destroy();
mFullscreenCallbackProxy = null;
}
if (mNewTabCallbackProxy != null) {
mNewTabCallbackProxy.destroy();
mNewTabCallbackProxy = null;
}
if (mGoogleAccountsCallbackProxy != null) {
mGoogleAccountsCallbackProxy.destroy();
mGoogleAccountsCallbackProxy = null;
}
mInterceptNavigationDelegateClient.destroy();
mInterceptNavigationDelegateClient = null;
mInterceptNavigationDelegate = null;
mInfoBarContainer.destroy();
mInfoBarContainer = null;
mMediaStreamManager.destroy();
mMediaStreamManager = null;
if (mMediaSessionHelper != null) {
mMediaSessionHelper.destroy();
mMediaSessionHelper = null;
}
if (mAutofillProvider != null) {
mAutofillProvider.destroy();
mAutofillProvider = null;
}
// Destroying FaviconCallbackProxy removes from mFaviconCallbackProxies. Copy to avoid
// problems.
Set<FaviconCallbackProxy> faviconCallbackProxies = mFaviconCallbackProxies;
mFaviconCallbackProxies = new HashSet<>();
for (FaviconCallbackProxy proxy : faviconCallbackProxies) {
proxy.destroy();
}
assert mFaviconCallbackProxies.isEmpty();
sTabMap.remove(mId);
hideFindInPageUiAndNotifyClient();
mFindInPageCallbackClient = null;
mNavigationController = null;
mWebContents.removeObserver(mWebContentsObserver);
TabImplJni.get().deleteTab(mNativeTab);
mNativeTab = 0;
}
@CalledByNative
public void showRepostFormWarningDialog() {
BrowserViewController viewController = getViewController();
if (viewController == null) {
mWebContents.getNavigationController().cancelPendingReload();
} else {
viewController.showRepostFormWarningDialog();
}
}
private static String nonEmptyOrNull(String s) {
return TextUtils.isEmpty(s) ? null : s;
}
private static class NativeContextMenuParamsHolder extends IContextMenuParams.Stub {
// Note: avoid adding more members since an object with a finalizer will delay GC of any
// object it references.
private final long mNativeContextMenuParams;
NativeContextMenuParamsHolder(long nativeContextMenuParams) {
mNativeContextMenuParams = nativeContextMenuParams;
}
/**
* A finalizer is required to ensure that the native object associated with
* this object gets destructed, otherwise there would be a memory leak.
*
* This is safe because it makes a simple call into C++ code that is both
* thread-safe and very fast.
*
* @see java.lang.Object#finalize()
*/
@Override
protected final void finalize() throws Throwable {
super.finalize();
TabImplJni.get().destroyContextMenuParams(mNativeContextMenuParams);
}
}
@CalledByNative
private void showContextMenu(ContextMenuParams params, long nativeContextMenuParams)
throws RemoteException {
if (WebLayerFactoryImpl.getClientMajorVersion() < 88) {
mClient.showContextMenu(ObjectWrapper.wrap(params.getPageUrl().getSpec()),
ObjectWrapper.wrap(nonEmptyOrNull(params.getLinkUrl().getSpec())),
ObjectWrapper.wrap(nonEmptyOrNull(params.getLinkText())),
ObjectWrapper.wrap(nonEmptyOrNull(params.getTitleText())),
ObjectWrapper.wrap(nonEmptyOrNull(params.getSrcUrl().getSpec())));
return;
}
boolean canDownload =
(params.isImage() && UrlUtilities.isDownloadableScheme(params.getSrcUrl()))
|| (params.isVideo() && UrlUtilities.isDownloadableScheme(params.getSrcUrl())
&& params.canSaveMedia())
|| (params.isAnchor() && UrlUtilities.isDownloadableScheme(params.getLinkUrl()));
mClient.showContextMenu2(ObjectWrapper.wrap(params.getPageUrl().getSpec()),
ObjectWrapper.wrap(nonEmptyOrNull(params.getLinkUrl().getSpec())),
ObjectWrapper.wrap(nonEmptyOrNull(params.getLinkText())),
ObjectWrapper.wrap(nonEmptyOrNull(params.getTitleText())),
ObjectWrapper.wrap(nonEmptyOrNull(params.getSrcUrl().getSpec())), params.isImage(),
params.isVideo(), canDownload,
new NativeContextMenuParamsHolder(nativeContextMenuParams));
}
@VisibleForTesting
public boolean didShowFullscreenToast() {
return mFullscreenCallbackProxy != null
&& mFullscreenCallbackProxy.didShowFullscreenToast();
}
private void ensureDisplayCutoutController() {
if (mDisplayCutoutController != null) return;
mDisplayCutoutController =
new DisplayCutoutController(new DisplayCutoutController.Delegate() {
@Override
public Activity getAttachedActivity() {
WindowAndroid window = mBrowser.getBrowserFragment().getWindowAndroid();
return window == null ? null : window.getActivity().get();
}
@Override
public WebContents getWebContents() {
return mWebContents;
}
@Override
public InsetObserverView getInsetObserverView() {
BrowserViewController controller =
mBrowser.getBrowserFragment().getPossiblyNullViewController();
return controller != null ? controller.getInsetObserverView() : null;
}
@Override
public ObservableSupplier<Integer> getBrowserDisplayCutoutModeSupplier() {
// No activity-wide display cutout mode override.
return null;
}
@Override
public boolean isInteractable() {
return isVisible();
}
@Override
public boolean isInBrowserFullscreen() {
return false;
}
});
}
/**
* Returns the BrowserViewController for this TabImpl, but only if this
* is the active TabImpl. Can also return null if in the middle of shutdown
* or Browser is not attached to any activity.
*/
@Nullable
private BrowserViewController getViewController() {
if (!isActiveTab()) return null;
// During rotation it's possible for this to be called before BrowserViewController has been
// updated. Verify BrowserViewController reflects this is the active tab before returning
// it.
BrowserViewController viewController =
mBrowser.getBrowserFragment().getPossiblyNullViewController();
return viewController != null && viewController.getTab() == this ? viewController : null;
}
@VisibleForTesting
public boolean canInfoBarContainerScrollForTesting() {
return mInfoBarContainer.getContainerViewForTesting().isAllowedToAutoHide();
}
@VisibleForTesting
public String getTranslateInfoBarTargetLanguageForTesting() {
if (!mInfoBarContainer.hasInfoBars()) return null;
ArrayList<InfoBar> infobars = mInfoBarContainer.getInfoBarsForTesting();
TranslateCompactInfoBar translateInfoBar = (TranslateCompactInfoBar) infobars.get(0);
return translateInfoBar.getTargetLanguageForTesting();
}
/** Called by {@link FaviconCallbackProxy} when the favicon for the current page has changed. */
public void onFaviconChanged(Bitmap bitmap) {
if (mMediaSessionHelper != null) {
mMediaSessionHelper.updateFavicon(bitmap);
}
}
@NativeMethods
interface Natives {
TabImpl fromWebContents(WebContents webContents);
long createTab(long tab, TabImpl caller);
void removeTabFromBrowserBeforeDestroying(long nativeTabImpl);
void deleteTab(long tab);
void setJavaImpl(long nativeTabImpl, TabImpl impl);
void initializeAutofillIfNecessary(long nativeTabImpl);
WebContents getWebContents(long nativeTabImpl);
void executeScript(long nativeTabImpl, String script, boolean useSeparateIsolate,
Callback<String> callback);
String getGuid(long nativeTabImpl);
void captureScreenShot(long nativeTabImpl, float scale,
ValueCallback<Pair<Bitmap, Integer>> valueCallback);
boolean setData(long nativeTabImpl, String[] data);
String[] getData(long nativeTabImpl);
boolean canTranslate(long nativeTabImpl);
void showTranslateUi(long nativeTabImpl);
void setTranslateTargetLanguage(long nativeTabImpl, String targetLanguage);
void setDesktopUserAgentEnabled(long nativeTabImpl, boolean enable);
boolean isDesktopUserAgentEnabled(long nativeTabImpl);
void download(long nativeTabImpl, long nativeContextMenuParams);
void destroyContextMenuParams(long contextMenuParams);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/TabImpl.java | Java | unknown | 49,787 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLayoutChangeListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import androidx.core.content.ContextCompat;
import com.google.android.material.tabs.TabLayout;
import org.chromium.base.StrictModeContext;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.chrome.browser.infobar.ActionType;
import org.chromium.chrome.browser.infobar.InfobarEvent;
import org.chromium.components.infobars.InfoBar;
import org.chromium.components.infobars.InfoBarCompactLayout;
import org.chromium.components.translate.TranslateMenu;
import org.chromium.components.translate.TranslateMenuHelper;
import org.chromium.components.translate.TranslateOption;
import org.chromium.components.translate.TranslateOptions;
import org.chromium.components.translate.TranslateTabLayout;
import org.chromium.ui.widget.Toast;
/**
* Java version of the compact translate infobar.
*/
@JNINamespace("weblayer")
public class TranslateCompactInfoBar extends InfoBar
implements TabLayout.OnTabSelectedListener, TranslateMenuHelper.TranslateMenuListener {
public static final int TRANSLATING_INFOBAR = 1;
public static final int AFTER_TRANSLATING_INFOBAR = 2;
private static final int SOURCE_TAB_INDEX = 0;
private static final int TARGET_TAB_INDEX = 1;
// Action ID for Snackbar.
// Actions performed by clicking on on the overflow menu.
public static final int ACTION_OVERFLOW_ALWAYS_TRANSLATE = 0;
public static final int ACTION_OVERFLOW_NEVER_SITE = 1;
public static final int ACTION_OVERFLOW_NEVER_LANGUAGE = 2;
// Actions triggered automatically. (when translation or denied count reaches the threshold.)
public static final int ACTION_AUTO_ALWAYS_TRANSLATE = 3;
public static final int ACTION_AUTO_NEVER_LANGUAGE = 4;
private final int mInitialStep;
private final int mDefaultTextColor;
private final TranslateOptions mOptions;
private long mNativeTranslateInfoBarPtr;
private TranslateTabLayout mTabLayout;
// Metric to track the total number of translations in a page, including reverts to original.
private int mTotalTranslationCount;
// Histogram names for logging metrics.
private static final String INFOBAR_HISTOGRAM_TRANSLATE_LANGUAGE =
"Translate.CompactInfobar.Language.Translate";
private static final String INFOBAR_HISTOGRAM_MORE_LANGUAGES_LANGUAGE =
"Translate.CompactInfobar.Language.MoreLanguages";
private static final String INFOBAR_HISTOGRAM_PAGE_NOT_IN_LANGUAGE =
"Translate.CompactInfobar.Language.PageNotIn";
private static final String INFOBAR_HISTOGRAM_ALWAYS_TRANSLATE_LANGUAGE =
"Translate.CompactInfobar.Language.AlwaysTranslate";
private static final String INFOBAR_HISTOGRAM_NEVER_TRANSLATE_LANGUAGE =
"Translate.CompactInfobar.Language.NeverTranslate";
private static final String INFOBAR_HISTOGRAM = "Translate.CompactInfobar.Event";
// Need 2 instances of TranslateMenuHelper to prevent a race condition bug which happens when
// showing language menu after dismissing overflow menu.
private TranslateMenuHelper mOverflowMenuHelper;
private TranslateMenuHelper mLanguageMenuHelper;
private ImageButton mMenuButton;
private InfoBarCompactLayout mParent;
private boolean mMenuExpanded;
private boolean mIsFirstLayout = true;
private boolean mUserInteracted;
@CalledByNative
private static InfoBar create(TabImpl tab, int initialStep, String sourceLanguageCode,
String targetLanguageCode, boolean neverLanguage, boolean neverDomain,
boolean alwaysTranslate, boolean triggeredFromMenu, String[] languages,
String[] languageCodes, int[] hashCodes, int tabTextColor) {
recordInfobarAction(InfobarEvent.INFOBAR_IMPRESSION);
return new TranslateCompactInfoBar(initialStep, sourceLanguageCode, targetLanguageCode,
neverLanguage, neverDomain, alwaysTranslate, triggeredFromMenu, languages,
languageCodes, hashCodes, tabTextColor);
}
TranslateCompactInfoBar(int initialStep, String sourceLanguageCode, String targetLanguageCode,
boolean neverLanguage, boolean neverDomain, boolean alwaysTranslate,
boolean triggeredFromMenu, String[] languages, String[] languageCodes, int[] hashCodes,
int tabTextColor) {
super(R.drawable.infobar_translate_compact, 0, null, null);
mInitialStep = initialStep;
mDefaultTextColor = tabTextColor;
mOptions = TranslateOptions.create(sourceLanguageCode, targetLanguageCode, languages,
languageCodes, neverLanguage, neverDomain, alwaysTranslate, triggeredFromMenu,
hashCodes,
/*contentLanguagesCodes*/ null);
}
@Override
protected boolean usesCompactLayout() {
return true;
}
@Override
protected void createCompactLayoutContent(InfoBarCompactLayout parent) {
LinearLayout content;
// LayoutInflater may trigger accessing the disk.
try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) {
content = (LinearLayout) LayoutInflater.from(getContext())
.inflate(R.layout.weblayer_infobar_translate_compact_content, parent,
false);
}
// When parent tab is being switched out (view detached), dismiss all menus and snackbars.
content.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View view) {}
@Override
public void onViewDetachedFromWindow(View view) {
dismissMenusAndSnackbars();
}
});
mTabLayout =
(TranslateTabLayout) content.findViewById(R.id.weblayer_translate_infobar_tabs);
if (mDefaultTextColor > 0) {
mTabLayout.setTabTextColors(
ContextCompat.getColor(getContext(), R.color.default_text_color_baseline),
ContextCompat.getColor(
getContext(), R.color.weblayer_tab_layout_selected_tab_color));
}
mTabLayout.addTabs(mOptions.sourceLanguageName(), mOptions.targetLanguageName());
if (mInitialStep == TRANSLATING_INFOBAR) {
// Set translating status in the beginning for pages translated automatically.
mTabLayout.getTabAt(TARGET_TAB_INDEX).select();
mTabLayout.showProgressBarOnTab(TARGET_TAB_INDEX);
mUserInteracted = true;
} else if (mInitialStep == AFTER_TRANSLATING_INFOBAR) {
// Focus on target tab since we are after translation.
mTabLayout.getTabAt(TARGET_TAB_INDEX).select();
}
mTabLayout.addOnTabSelectedListener(this);
// Dismiss all menus and end scrolling animation when there is layout changed.
mTabLayout.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (left != oldLeft || top != oldTop || right != oldRight || bottom != oldBottom) {
// Dismiss all menus to prevent menu misplacement.
dismissMenus();
if (mIsFirstLayout) {
// Scrolls to the end to make sure the target language tab is visible when
// language tabs is too long.
mTabLayout.startScrollingAnimationIfNeeded();
mIsFirstLayout = false;
return;
}
// End scrolling animation when layout changed.
mTabLayout.endScrollingAnimationIfPlaying();
}
}
});
mMenuButton = content.findViewById(R.id.weblayer_translate_infobar_menu_button);
mMenuButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTabLayout.endScrollingAnimationIfPlaying();
recordInfobarAction(InfobarEvent.INFOBAR_OPTIONS);
initMenuHelper(TranslateMenu.MENU_OVERFLOW);
mOverflowMenuHelper.show(TranslateMenu.MENU_OVERFLOW, getParentWidth());
mMenuExpanded = true;
}
});
parent.addContent(content, 1.0f);
mParent = parent;
}
private void initMenuHelper(int menuType) {
boolean isIncognito = TranslateCompactInfoBarJni.get().isIncognito(
mNativeTranslateInfoBarPtr, TranslateCompactInfoBar.this);
boolean isSourceLangUnknown = mOptions.sourceLanguageCode().equals("und");
switch (menuType) {
case TranslateMenu.MENU_OVERFLOW:
mOverflowMenuHelper = new TranslateMenuHelper(getContext(), mMenuButton, mOptions,
this, isIncognito, isSourceLangUnknown);
return;
case TranslateMenu.MENU_TARGET_LANGUAGE:
case TranslateMenu.MENU_SOURCE_LANGUAGE:
if (mLanguageMenuHelper == null) {
mLanguageMenuHelper = new TranslateMenuHelper(getContext(), mMenuButton,
mOptions, this, isIncognito, isSourceLangUnknown);
}
return;
default:
assert false : "Unsupported Menu Item Id";
}
}
private void startTranslating(int tabPosition) {
if (TARGET_TAB_INDEX == tabPosition) {
// Already on the target tab.
mTabLayout.showProgressBarOnTab(TARGET_TAB_INDEX);
onButtonClicked(ActionType.TRANSLATE);
mUserInteracted = true;
} else {
mTabLayout.getTabAt(TARGET_TAB_INDEX).select();
}
}
@CalledByNative
private void onPageTranslated(int errorType) {
if (mTabLayout != null) {
mTabLayout.hideProgressBar();
if (errorType != 0) {
Toast.makeText(getContext(), R.string.translate_infobar_error, Toast.LENGTH_SHORT)
.show();
// Disable OnTabSelectedListener then revert selection.
mTabLayout.removeOnTabSelectedListener(this);
mTabLayout.getTabAt(SOURCE_TAB_INDEX).select();
// Add OnTabSelectedListener back.
mTabLayout.addOnTabSelectedListener(this);
}
}
}
@CalledByNative
private void setNativePtr(long nativePtr) {
mNativeTranslateInfoBarPtr = nativePtr;
}
@CalledByNative
private void setAutoAlwaysTranslate() {
createAndShowSnackbar(ACTION_AUTO_ALWAYS_TRANSLATE);
}
@Override
protected void resetNativeInfoBar() {
mNativeTranslateInfoBarPtr = 0;
super.resetNativeInfoBar();
}
private void closeInfobar(boolean explicitly) {
if (isDismissed()) return;
if (!mUserInteracted) {
recordInfobarAction(InfobarEvent.INFOBAR_DECLINE);
}
// NOTE: In Chrome there is a check for whether auto "never translate" should be triggered
// via a snackbar here. However, WebLayer does not have snackbars and thus does not have
// this check as there would be no way to inform the user of the functionality being
// triggered. The user of course has the option of choosing "never translate" from the
// overflow menu.
// This line will dismiss this infobar.
super.onCloseButtonClicked();
}
@Override
public void onCloseButtonClicked() {
mTabLayout.endScrollingAnimationIfPlaying();
closeInfobar(true);
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case SOURCE_TAB_INDEX:
recordInfobarAction(InfobarEvent.INFOBAR_REVERT);
onButtonClicked(ActionType.TRANSLATE_SHOW_ORIGINAL);
return;
case TARGET_TAB_INDEX:
recordInfobarAction(InfobarEvent.INFOBAR_TARGET_TAB_TRANSLATE);
recordInfobarLanguageData(
INFOBAR_HISTOGRAM_TRANSLATE_LANGUAGE, mOptions.targetLanguageCode());
startTranslating(TARGET_TAB_INDEX);
return;
default:
assert false : "Unexpected Tab Index";
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {}
@Override
public void onTabReselected(TabLayout.Tab tab) {}
@Override
public void onOverflowMenuItemClicked(int itemId) {
switch (itemId) {
case TranslateMenu.ID_OVERFLOW_MORE_LANGUAGE:
recordInfobarAction(InfobarEvent.INFOBAR_MORE_LANGUAGES);
initMenuHelper(TranslateMenu.MENU_TARGET_LANGUAGE);
mLanguageMenuHelper.show(TranslateMenu.MENU_TARGET_LANGUAGE, getParentWidth());
return;
case TranslateMenu.ID_OVERFLOW_ALWAYS_TRANSLATE:
// Only show snackbar when "Always Translate" is enabled.
if (!mOptions.getTranslateState(TranslateOptions.Type.ALWAYS_LANGUAGE)) {
recordInfobarAction(InfobarEvent.INFOBAR_ALWAYS_TRANSLATE);
recordInfobarLanguageData(INFOBAR_HISTOGRAM_ALWAYS_TRANSLATE_LANGUAGE,
mOptions.sourceLanguageCode());
createAndShowSnackbar(ACTION_OVERFLOW_ALWAYS_TRANSLATE);
} else {
recordInfobarAction(InfobarEvent.INFOBAR_ALWAYS_TRANSLATE_UNDO);
handleTranslateOverflowOption(ACTION_OVERFLOW_ALWAYS_TRANSLATE);
}
return;
case TranslateMenu.ID_OVERFLOW_NEVER_LANGUAGE:
// Only show snackbar when "Never Translate" is enabled.
if (!mOptions.getTranslateState(TranslateOptions.Type.NEVER_LANGUAGE)) {
recordInfobarAction(InfobarEvent.INFOBAR_NEVER_TRANSLATE);
recordInfobarLanguageData(INFOBAR_HISTOGRAM_NEVER_TRANSLATE_LANGUAGE,
mOptions.sourceLanguageCode());
createAndShowSnackbar(ACTION_OVERFLOW_NEVER_LANGUAGE);
} else {
recordInfobarAction(InfobarEvent.INFOBAR_NEVER_TRANSLATE_UNDO);
handleTranslateOverflowOption(ACTION_OVERFLOW_NEVER_LANGUAGE);
}
return;
case TranslateMenu.ID_OVERFLOW_NEVER_SITE:
// Only show snackbar when "Never Translate Site" is enabled.
if (!mOptions.getTranslateState(TranslateOptions.Type.NEVER_DOMAIN)) {
recordInfobarAction(InfobarEvent.INFOBAR_NEVER_TRANSLATE_SITE);
createAndShowSnackbar(ACTION_OVERFLOW_NEVER_SITE);
} else {
recordInfobarAction(InfobarEvent.INFOBAR_NEVER_TRANSLATE_SITE_UNDO);
handleTranslateOverflowOption(ACTION_OVERFLOW_NEVER_SITE);
}
return;
case TranslateMenu.ID_OVERFLOW_NOT_THIS_LANGUAGE:
recordInfobarAction(InfobarEvent.INFOBAR_PAGE_NOT_IN);
initMenuHelper(TranslateMenu.MENU_SOURCE_LANGUAGE);
mLanguageMenuHelper.show(TranslateMenu.MENU_SOURCE_LANGUAGE, getParentWidth());
return;
default:
assert false : "Unexpected overflow menu code";
}
}
@Override
public void onTargetMenuItemClicked(String code) {
// Reset target code in both UI and native.
if (mNativeTranslateInfoBarPtr != 0 && mOptions.setTargetLanguage(code)) {
recordInfobarAction(InfobarEvent.INFOBAR_MORE_LANGUAGES_TRANSLATE);
recordInfobarLanguageData(
INFOBAR_HISTOGRAM_MORE_LANGUAGES_LANGUAGE, mOptions.targetLanguageCode());
TranslateCompactInfoBarJni.get().applyStringTranslateOption(mNativeTranslateInfoBarPtr,
TranslateCompactInfoBar.this, TranslateOption.TARGET_CODE, code);
// Adjust UI.
mTabLayout.replaceTabTitle(TARGET_TAB_INDEX, mOptions.getRepresentationFromCode(code));
startTranslating(mTabLayout.getSelectedTabPosition());
}
}
@Override
public void onSourceMenuItemClicked(String code) {
// Reset source code in both UI and native.
if (mNativeTranslateInfoBarPtr != 0 && mOptions.setSourceLanguage(code)) {
recordInfobarLanguageData(
INFOBAR_HISTOGRAM_PAGE_NOT_IN_LANGUAGE, mOptions.sourceLanguageCode());
TranslateCompactInfoBarJni.get().applyStringTranslateOption(mNativeTranslateInfoBarPtr,
TranslateCompactInfoBar.this, TranslateOption.SOURCE_CODE, code);
// Adjust UI.
mTabLayout.replaceTabTitle(SOURCE_TAB_INDEX, mOptions.getRepresentationFromCode(code));
startTranslating(mTabLayout.getSelectedTabPosition());
}
}
// Dismiss all overflow menus that remains open.
// This is called when infobar started hiding or layout changed.
private void dismissMenus() {
if (mOverflowMenuHelper != null) mOverflowMenuHelper.dismiss();
if (mLanguageMenuHelper != null) mLanguageMenuHelper.dismiss();
}
// Dismiss all overflow menus and snackbars that belong to this infobar and remain open.
private void dismissMenusAndSnackbars() {
dismissMenus();
}
@Override
protected void onStartedHiding() {
dismissMenusAndSnackbars();
}
@Override
protected CharSequence getAccessibilityMessage(CharSequence defaultMessage) {
return getContext().getString(R.string.translate_button);
}
/**
* Returns true if overflow menu is showing. This is only used for automation testing.
*/
public boolean isShowingOverflowMenuForTesting() {
if (mOverflowMenuHelper == null) return false;
return mOverflowMenuHelper.isShowing();
}
/**
* Returns true if language menu is showing. This is only used for automation testing.
*/
public boolean isShowingLanguageMenuForTesting() {
if (mLanguageMenuHelper == null) return false;
return mLanguageMenuHelper.isShowing();
}
/**
* Returns true if the tab at the given |tabIndex| is selected. This is only used for automation
* testing.
*/
private boolean isTabSelectedForTesting(int tabIndex) {
return mTabLayout.getTabAt(tabIndex).isSelected();
}
/**
* Returns true if the target tab is selected. This is only used for automation testing.
*/
public boolean isSourceTabSelectedForTesting() {
return this.isTabSelectedForTesting(SOURCE_TAB_INDEX);
}
/**
* Returns true if the target tab is selected. This is only used for automation testing.
*/
public boolean isTargetTabSelectedForTesting() {
return this.isTabSelectedForTesting(TARGET_TAB_INDEX);
}
/**
* Returns the name of the target language. This is only used for automation testing.
*/
public String getTargetLanguageForTesting() {
return mOptions.targetLanguageName();
}
private void createAndShowSnackbar(int actionId) {
// NOTE: WebLayer doesn't have snackbars, so the relevant action is just taken directly.
// TODO(blundell): If WebLayer ends up staying with this implementation long-term, update
// the nomenclature of this file to avoid any references to snackbars.
handleTranslateOverflowOption(actionId);
}
private void handleTranslateOverflowOption(int actionId) {
// Quit if native is destroyed.
if (mNativeTranslateInfoBarPtr == 0) return;
switch (actionId) {
case ACTION_OVERFLOW_ALWAYS_TRANSLATE:
toggleAlwaysTranslate();
// Start translating if always translate is selected and if page is not already
// translated to the target language.
if (mOptions.getTranslateState(TranslateOptions.Type.ALWAYS_LANGUAGE)
&& mTabLayout.getSelectedTabPosition() == SOURCE_TAB_INDEX) {
startTranslating(mTabLayout.getSelectedTabPosition());
}
return;
case ACTION_AUTO_ALWAYS_TRANSLATE:
toggleAlwaysTranslate();
return;
case ACTION_OVERFLOW_NEVER_LANGUAGE:
mUserInteracted = true;
// Fallthrough intentional.
case ACTION_AUTO_NEVER_LANGUAGE:
mOptions.toggleNeverTranslateLanguageState(
!mOptions.getTranslateState(TranslateOptions.Type.NEVER_LANGUAGE));
TranslateCompactInfoBarJni.get().applyBoolTranslateOption(
mNativeTranslateInfoBarPtr, TranslateCompactInfoBar.this,
TranslateOption.NEVER_TRANSLATE,
mOptions.getTranslateState(TranslateOptions.Type.NEVER_LANGUAGE));
return;
case ACTION_OVERFLOW_NEVER_SITE:
mUserInteracted = true;
mOptions.toggleNeverTranslateDomainState(
!mOptions.getTranslateState(TranslateOptions.Type.NEVER_DOMAIN));
TranslateCompactInfoBarJni.get().applyBoolTranslateOption(
mNativeTranslateInfoBarPtr, TranslateCompactInfoBar.this,
TranslateOption.NEVER_TRANSLATE_SITE,
mOptions.getTranslateState(TranslateOptions.Type.NEVER_DOMAIN));
return;
default:
assert false : "Unsupported Menu Item Id, in handle post snackbar";
}
}
private void toggleAlwaysTranslate() {
mOptions.toggleAlwaysTranslateLanguageState(
!mOptions.getTranslateState(TranslateOptions.Type.ALWAYS_LANGUAGE));
TranslateCompactInfoBarJni.get().applyBoolTranslateOption(mNativeTranslateInfoBarPtr,
TranslateCompactInfoBar.this, TranslateOption.ALWAYS_TRANSLATE,
mOptions.getTranslateState(TranslateOptions.Type.ALWAYS_LANGUAGE));
}
private static void recordInfobarAction(int action) {
RecordHistogram.recordEnumeratedHistogram(
INFOBAR_HISTOGRAM, action, InfobarEvent.INFOBAR_HISTOGRAM_BOUNDARY);
}
private void recordInfobarLanguageData(String histogram, String langCode) {
Integer hashCode = mOptions.getUMAHashCodeFromCode(langCode);
if (hashCode != null) {
RecordHistogram.recordSparseHistogram(histogram, hashCode);
}
}
// Return the width of parent in pixels. Return 0 if there is no parent.
private int getParentWidth() {
return mParent != null ? mParent.getWidth() : 0;
}
// Selects the tab corresponding to |actionType| to simulate the user pressing on this tab.
void selectTabForTesting(int actionType) {
if (actionType == ActionType.TRANSLATE) {
mTabLayout.getTabAt(TARGET_TAB_INDEX).select();
} else if (actionType == ActionType.TRANSLATE_SHOW_ORIGINAL) {
mTabLayout.getTabAt(SOURCE_TAB_INDEX).select();
} else {
assert false;
}
}
@NativeMethods
interface Natives {
void applyStringTranslateOption(long nativeTranslateCompactInfoBar,
TranslateCompactInfoBar caller, int option, String value);
void applyBoolTranslateOption(long nativeTranslateCompactInfoBar,
TranslateCompactInfoBar caller, int option, boolean value);
boolean shouldAutoNeverTranslate(long nativeTranslateCompactInfoBar,
TranslateCompactInfoBar caller, boolean menuExpanded);
boolean isIncognito(long nativeTranslateCompactInfoBar, TranslateCompactInfoBar caller);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/TranslateCompactInfoBar.java | Java | unknown | 24,688 |
// 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;
import android.graphics.Bitmap;
import org.chromium.base.Callback;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.components.webapps.WebApkInstallResult;
/**
* Java counterpart to webapk_install_scheduler_bridge.
* Contains functionality to schedule WebAPK installs with the {@link
* WebApkInstallCoordinatorService} in Chrome. This Java object is created by and owned by the
* native WebApkInstallSchedulerBridge.
*/
@JNINamespace("weblayer")
public class WebApkInstallSchedulerBridge {
// Raw pointer to the native WebApkInstallSchedulerBridge that is cleared when the native object
// destroys this object.
private long mNativePointer;
/**
* This callback is passed via the {@link WebApkInstallSchedulerClient} to the Chrome
* {@link WebApkInstallCoordinatorService} and will be called from there with the result
* of the install. This result is passed along to the native side.
*/
Callback<Integer> mOnInstallCompleteCallback = (result) -> {
if (mNativePointer != 0) {
WebApkInstallSchedulerBridgeJni.get().onInstallFinished(
mNativePointer, WebApkInstallSchedulerBridge.this, result);
}
};
private WebApkInstallSchedulerBridge(long nativePtr) {
mNativePointer = nativePtr;
}
@CalledByNative
private static WebApkInstallSchedulerBridge create(long nativePtr) {
return new WebApkInstallSchedulerBridge(nativePtr);
}
@CalledByNative
public void scheduleInstall(
byte[] apkProto, Bitmap primaryIcon, boolean isPrimaryIconMaskable) {
WebApkInstallSchedulerClient.scheduleInstall(
apkProto, primaryIcon, isPrimaryIconMaskable, mOnInstallCompleteCallback);
}
/**
* Returns if the {@link WebApkInstallCoordinatorService} is available.
*/
@CalledByNative
public static boolean isInstallServiceAvailable() {
return WebApkInstallSchedulerClient.isInstallServiceAvailable();
}
@CalledByNative
private void destroy() {
// Remove the reference to the native side.
mNativePointer = 0;
}
@NativeMethods
interface Natives {
void onInstallFinished(long nativeWebApkInstallSchedulerBridge,
WebApkInstallSchedulerBridge caller, @WebApkInstallResult int result);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebApkInstallSchedulerBridge.java | Java | unknown | 2,652 |
// 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;
import android.graphics.Bitmap;
import android.os.RemoteException;
import androidx.annotation.BinderThread;
import androidx.annotation.MainThread;
import org.chromium.base.Callback;
import org.chromium.base.Log;
import org.chromium.base.Promise;
import org.chromium.base.task.PostTask;
import org.chromium.base.task.TaskTraits;
import org.chromium.components.webapk_install.IOnFinishInstallCallback;
import org.chromium.components.webapk_install.IWebApkInstallCoordinatorService;
import org.chromium.components.webapps.WebApkInstallResult;
/**
* Contains functionality to connect to the {@link WebApkInstallCoordinatorService} in Chrome using
* the {@link WebApkServiceConnection}, schedule the install of one WebAPK and receive the install
* result via the {@link IOnFinishInstallCallback}.
*/
public class WebApkInstallSchedulerClient {
private static final String TAG = "WebApkInstallClient";
/**
* Casts an int to {@link WebApkInstallResult}.
*/
public @WebApkInstallResult static int asWebApkInstallResult(int webApkInstallResult) {
return webApkInstallResult;
}
@MainThread
Promise<Integer> startInstallTask(byte[] apkProto, Bitmap primaryIcon,
boolean isPrimaryIconMaskable, IWebApkInstallCoordinatorService serviceInterface) {
Promise<Integer> whenInstallTaskCompleted = new Promise<>();
IOnFinishInstallCallback.Stub serviceCallback = new IOnFinishInstallCallback.Stub() {
@Override
@BinderThread
public void handleOnFinishInstall(int result) {
// Post the task back to the main thread as promises have to be accessed from a
// single thread.
PostTask.postTask(
TaskTraits.UI_DEFAULT, () -> { whenInstallTaskCompleted.fulfill(result); });
}
};
try {
serviceInterface.scheduleInstallAsync(
apkProto, primaryIcon, isPrimaryIconMaskable, serviceCallback);
} catch (RemoteException e) {
Log.w(TAG, "Failed to schedule install with Chrome WebAPK install service.", e);
whenInstallTaskCompleted.reject();
}
return whenInstallTaskCompleted;
}
/**
* Schedules the install of one WebAPK with Chrome's {@link WebApkInstallCoordinatorService}.
* The {@code onInstallFinishedCallback} is triggered when the install finished or failed.
*/
@MainThread
public static void scheduleInstall(byte[] apkProto, Bitmap primaryIcon,
boolean isPrimaryIconMaskable, Callback<Integer> onInstallFinishedCallback) {
WebApkInstallSchedulerClient client = new WebApkInstallSchedulerClient();
WebApkServiceConnection webApkServiceConnection = new WebApkServiceConnection();
Promise<IWebApkInstallCoordinatorService> whenServiceConnected =
webApkServiceConnection.connect();
whenServiceConnected
.then(
/*fulfilled */
(IWebApkInstallCoordinatorService serviceInterface)
-> client.startInstallTask(apkProto, primaryIcon,
isPrimaryIconMaskable, serviceInterface))
.then(
/*fulfilled */
installResult
-> {
webApkServiceConnection.unbindIfNeeded();
onInstallFinishedCallback.onResult(
asWebApkInstallResult(installResult));
},
/*rejected*/
err -> {
webApkServiceConnection.unbindIfNeeded();
onInstallFinishedCallback.onResult(WebApkInstallResult.FAILURE);
});
}
/**
* Returns if the {@link WebApkInstallCoordinatorService} is available.
*/
public static boolean isInstallServiceAvailable() {
return WebApkServiceConnection.isInstallServiceAvailable();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebApkInstallSchedulerClient.java | Java | unknown | 4,306 |
// 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;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ResolveInfo;
import android.os.IBinder;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.Promise;
import org.chromium.components.webapk_install.IWebApkInstallCoordinatorService;
/**
* Service Connection to the {@link WebApkInstallCoordinatorService} in Chrome.
*/
class WebApkServiceConnection implements ServiceConnection {
private static final String TAG = "WebApkServiceConn";
private static final String BIND_WEBAPK_SCHEDULE_INSTALL_INTENT_ACTION =
"org.chromium.intent.action.INSTALL_WEB_APK";
// TODO(swestphal): set package name of production chrome apk
private static final String CHROME_PACKAGE_NAME = "com.google.android.apps.chrome";
private Context mContext;
private boolean mIsBound;
// The promise is fulfilled as soon as the connection is established, it will then provide the
// {@link IWebApkInstallCoordinatorService}. It will be rejected if the connection to the
// service cannot be established. Retrieve the {@code mPromiseServiceInterface} by calling
// {@link connect()}.
Promise<IWebApkInstallCoordinatorService> mPromiseServiceInterface;
WebApkServiceConnection() {
mContext = ContextUtils.getApplicationContext();
mPromiseServiceInterface = new Promise<>();
}
private static Intent createChromeInstallServiceIntent() {
Intent intent = new Intent(BIND_WEBAPK_SCHEDULE_INSTALL_INTENT_ACTION);
intent.setPackage(CHROME_PACKAGE_NAME);
return intent;
}
/**
* Tries to bind to the service, returns a promise which will be fulfilled as
* soon as the connection is established or rejected in the failure case.
* This function must only be called once.
*/
Promise<IWebApkInstallCoordinatorService> connect() {
Intent intent = createChromeInstallServiceIntent();
try {
mIsBound = mContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
if (!mIsBound) {
Log.w(TAG, "Failed to bind to Chrome install service.");
mPromiseServiceInterface.reject();
}
} catch (SecurityException e) {
Log.w(TAG, "SecurityException while binding to Chrome install service.", e);
mPromiseServiceInterface.reject();
}
return mPromiseServiceInterface;
}
/**
* Unbinds the service connection if it is currently bound.
*/
void unbindIfNeeded() {
if (mIsBound) {
mContext.unbindService(this);
}
mIsBound = false;
}
/**
* Returns if the {@link WebApkInstallCoordinatorService} is available.
*/
public static boolean isInstallServiceAvailable() {
ResolveInfo info = ContextUtils.getApplicationContext().getPackageManager().resolveService(
createChromeInstallServiceIntent(), 0);
return info != null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IWebApkInstallCoordinatorService serviceInterface =
IWebApkInstallCoordinatorService.Stub.asInterface(service);
mPromiseServiceInterface.fulfill(serviceInterface);
}
@Override
public void onServiceDisconnected(ComponentName name) {
if (!mPromiseServiceInterface.isFulfilled() && !mPromiseServiceInterface.isRejected()) {
mPromiseServiceInterface.reject();
}
// Called when the Service closes the connection so we still might need to unbind.
unbindIfNeeded();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebApkServiceConnection.java | Java | unknown | 3,939 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.view.MotionEvent;
import android.view.View;
import org.chromium.content_public.browser.GestureListenerManager;
import org.chromium.content_public.browser.GestureStateListener;
import org.chromium.content_public.browser.WebContents;
/**
* WebContentsGestureStateTracker is responsible for tracking when a scroll/gesture is in progress
* and notifying when the state changes.
*/
// TODO(sky): refactor TabGestureStateListener and this to a common place.
public final class WebContentsGestureStateTracker {
private GestureListenerManager mGestureListenerManager;
private GestureStateListener mGestureListener;
private final OnGestureStateChangedListener mListener;
private boolean mScrolling;
private boolean mIsInGesture;
/**
* The View events are tracked on.
*/
private View mContentView;
/**
* Notified when the gesture state changes.
*/
public interface OnGestureStateChangedListener {
/**
* Called when the value of isInGestureOrScroll() changes.
*/
public void onGestureStateChanged();
}
public WebContentsGestureStateTracker(
View contentView, WebContents webContents, OnGestureStateChangedListener listener) {
mListener = listener;
mGestureListenerManager = GestureListenerManager.fromWebContents(webContents);
mContentView = contentView;
mContentView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
final int eventAction = event.getActionMasked();
final boolean oldState = isInGestureOrScroll();
if (eventAction == MotionEvent.ACTION_DOWN
|| eventAction == MotionEvent.ACTION_POINTER_DOWN) {
mIsInGesture = true;
} else if (eventAction == MotionEvent.ACTION_CANCEL
|| eventAction == MotionEvent.ACTION_UP) {
mIsInGesture = false;
}
if (isInGestureOrScroll() != oldState) {
mListener.onGestureStateChanged();
}
return false;
}
});
mGestureListener = new GestureStateListener() {
@Override
public void onFlingStartGesture(
int scrollOffsetY, int scrollExtentY, boolean isDirectionUp) {
onScrollingStateChanged();
}
@Override
public void onFlingEndGesture(int scrollOffsetY, int scrollExtentY) {
onScrollingStateChanged();
}
@Override
public void onScrollStarted(
int scrollOffsetY, int scrollExtentY, boolean isDirectionUp) {
onScrollingStateChanged();
}
@Override
public void onScrollEnded(int scrollOffsetY, int scrollExtentY) {
onScrollingStateChanged();
}
private void onScrollingStateChanged() {
final boolean oldState = isInGestureOrScroll();
mScrolling = mGestureListenerManager.isScrollInProgress();
if (oldState != isInGestureOrScroll()) {
mListener.onGestureStateChanged();
}
}
};
mGestureListenerManager.addListener(mGestureListener);
}
public void destroy() {
mGestureListenerManager.removeListener(mGestureListener);
mGestureListener = null;
mGestureListenerManager = null;
mContentView.setOnTouchListener(null);
}
/**
* Returns true if the user has touched the target view, or is scrolling.
*/
public boolean isInGestureOrScroll() {
return mIsInGesture || mScrolling;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebContentsGestureStateTracker.java | Java | unknown | 4,045 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.components.browser_ui.accessibility.FontSizePrefs;
import org.chromium.ui.util.AccessibilityUtil;
/**
* Exposes information about the current accessibility state.
*/
public class WebLayerAccessibilityUtil extends AccessibilityUtil {
private static WebLayerAccessibilityUtil sInstance;
public static WebLayerAccessibilityUtil get() {
if (sInstance == null) sInstance = new WebLayerAccessibilityUtil();
return sInstance;
}
private WebLayerAccessibilityUtil() {}
public void onBrowserResumed(ProfileImpl profile) {
// When a browser is resumed the cached state may have be stale and needs to be
// recalculated.
updateIsAccessibilityEnabledAndNotify();
FontSizePrefs.getInstance(profile).onSystemFontScaleChanged();
}
public void onAllBrowsersDestroyed() {
// When there are no more browsers alive there is no need to monitor state. Calling
// isAccessibilityEnabled() will trigger observing the necessary state.
stopTrackingStateAndRemoveObservers();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerAccessibilityUtil.java | Java | unknown | 1,268 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* A helper class to determine if an exception is relevant to WebLayer. Called if an uncaught
* exception is detected.
*/
@JNINamespace("weblayer")
public final class WebLayerExceptionFilter {
// The filename prefix used by Chromium proguarding, which we use to
// recognise stack frames that reference WebLayer.
private static final String CHROMIUM_PREFIX = "chromium-";
@CalledByNative
private static boolean stackTraceContainsWebLayerCode(Throwable t) {
for (StackTraceElement frame : t.getStackTrace()) {
if (frame.getClassName().startsWith("org.chromium.")
|| (frame.getFileName() != null
&& frame.getFileName().startsWith(CHROMIUM_PREFIX))) {
return true;
}
}
return false;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerExceptionFilter.java | Java | unknown | 1,116 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.os.IBinder;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.build.annotations.UsedByReflection;
import org.chromium.components.version_info.VersionConstants;
import org.chromium.weblayer_private.interfaces.IWebLayer;
import org.chromium.weblayer_private.interfaces.IWebLayerFactory;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import org.chromium.weblayer_private.interfaces.WebLayerVersionConstants;
/**
* Factory used to create WebLayer as well as verify compatibility.
* This is constructed by the client library using reflection.
*/
@UsedByReflection("WebLayer")
public final class WebLayerFactoryImpl extends IWebLayerFactory.Stub {
private static int sClientMajorVersion;
private static String sClientVersion;
/**
* This function is called by the client using reflection.
*
* @param clientVersion The full version string the client was compiled from.
* @param clientMajorVersion The major version number the client was compiled from. This is also
* contained in clientVersion.
* @param clientWebLayerVersion The version from interfaces.WebLayerVersion the client was
* compiled with.
*/
@UsedByReflection("WebLayer")
public static IBinder create(
String clientVersion, int clientMajorVersion, int clientWebLayerVersion) {
return new WebLayerFactoryImpl(clientVersion, clientMajorVersion);
}
private WebLayerFactoryImpl(String clientVersion, int clientMajorVersion) {
sClientMajorVersion = clientMajorVersion;
sClientVersion = clientVersion;
}
/**
* Returns true if the client compiled with the specific version is compatible with this
* implementation. The client library calls this exactly once.
*/
@Override
public boolean isClientSupported() {
StrictModeWorkaround.apply();
if (sClientMajorVersion < WebLayerVersionConstants.MIN_VERSION) {
return false;
}
int implMajorVersion = getImplementationMajorVersion();
// While the client always calls this method, the most recently shipped product gets to
// decide compatibility. If we instead let the implementation always decide, then we would
// not be able to change the allowed skew of older implementations, even if the client could
// support it.
if (sClientMajorVersion > implMajorVersion) return true;
return implMajorVersion - sClientMajorVersion <= WebLayerVersionConstants.MAX_SKEW;
}
/**
* Returns the major version of the implementation.
*/
@Override
public int getImplementationMajorVersion() {
StrictModeWorkaround.apply();
return VersionConstants.PRODUCT_MAJOR_VERSION;
}
@CalledByNative
public static int getClientMajorVersion() {
if (sClientMajorVersion == 0) {
throw new IllegalStateException(
"This should only be called once WebLayer is initialized");
}
return sClientMajorVersion;
}
/**
* Returns the full version string of the implementation.
*/
@Override
public String getImplementationVersion() {
StrictModeWorkaround.apply();
return VersionConstants.PRODUCT_VERSION;
}
@Override
public IWebLayer createWebLayer() {
StrictModeWorkaround.apply();
assert isClientSupported();
return new WebLayerImpl();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerFactoryImpl.java | Java | unknown | 3,682 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.util.SparseArray;
import android.webkit.ValueCallback;
import android.webkit.WebViewDelegate;
import android.webkit.WebViewFactory;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import dalvik.system.DexFile;
import org.chromium.base.BuildInfo;
import org.chromium.base.BundleUtils;
import org.chromium.base.CommandLine;
import org.chromium.base.ContentUriUtils;
import org.chromium.base.ContextUtils;
import org.chromium.base.FileUtils;
import org.chromium.base.Log;
import org.chromium.base.PathUtils;
import org.chromium.base.StrictModeContext;
import org.chromium.base.TraceEvent;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.base.library_loader.LibraryLoader;
import org.chromium.base.library_loader.LibraryProcessType;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.task.AsyncTask;
import org.chromium.base.task.BackgroundOnlyAsyncTask;
import org.chromium.base.task.PostTask;
import org.chromium.base.task.TaskTraits;
import org.chromium.build.annotations.DoNotInline;
import org.chromium.components.browser_ui.contacts_picker.ContactsPickerDialog;
import org.chromium.components.browser_ui.photo_picker.DecoderServiceHost;
import org.chromium.components.browser_ui.photo_picker.ImageDecoder;
import org.chromium.components.browser_ui.photo_picker.PhotoPickerDelegateBase;
import org.chromium.components.browser_ui.photo_picker.PhotoPickerDialog;
import org.chromium.components.browser_ui.share.ClipboardImageFileProvider;
import org.chromium.components.browser_ui.share.ShareImageFileUtils;
import org.chromium.components.component_updater.ComponentLoaderPolicyBridge;
import org.chromium.components.component_updater.EmbeddedComponentLoader;
import org.chromium.components.embedder_support.application.ClassLoaderContextWrapperFactory;
import org.chromium.components.embedder_support.application.FirebaseConfig;
import org.chromium.components.payments.PaymentDetailsUpdateService;
import org.chromium.components.webapk.lib.client.ChromeWebApkHostSignature;
import org.chromium.components.webapk.lib.client.WebApkValidator;
import org.chromium.content_public.browser.BrowserStartupController;
import org.chromium.content_public.browser.ChildProcessCreationParams;
import org.chromium.content_public.browser.ChildProcessLauncherHelper;
import org.chromium.content_public.browser.ContactsPicker;
import org.chromium.content_public.browser.ContactsPickerListener;
import org.chromium.content_public.browser.DeviceUtils;
import org.chromium.content_public.browser.SelectionPopupController;
import org.chromium.net.NetworkChangeNotifier;
import org.chromium.ui.base.Clipboard;
import org.chromium.ui.base.PhotoPicker;
import org.chromium.ui.base.PhotoPickerListener;
import org.chromium.ui.base.ResourceBundle;
import org.chromium.ui.base.SelectFileDialog;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.weblayer_private.interfaces.APICallException;
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.IWebLayer;
import org.chromium.weblayer_private.interfaces.IWebLayerClient;
import org.chromium.weblayer_private.interfaces.ObjectWrapper;
import org.chromium.weblayer_private.interfaces.StrictModeWorkaround;
import org.chromium.weblayer_private.media.MediaRouterClientImpl;
import org.chromium.weblayer_private.media.MediaSessionManager;
import org.chromium.weblayer_private.media.MediaStreamManager;
import org.chromium.weblayer_private.metrics.MetricsServiceClient;
import org.chromium.weblayer_private.metrics.UmaUtils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Root implementation class for WebLayer.
*/
@JNINamespace("weblayer")
public final class WebLayerImpl extends IWebLayer.Stub {
// TODO: should there be one tag for all this code?
private static final String TAG = "WebLayer";
private static final String PRIVATE_DIRECTORY_SUFFIX = "weblayer";
// Command line flags are only read in debug builds.
// WARNING: this file is written to by testing code in chrome (see
// "//chrome/test/chromedriver/chrome/device_manager.cc"). If you change this variable, update
// "device_manager.cc" too. If the command line file exists in the app's private files
// directory, it will be read from there, otherwise it will be read from
// PUBLIC_COMMAND_LINE_FILE.
private static final String COMMAND_LINE_FILE = "weblayer-command-line";
private static final String PUBLIC_COMMAND_LINE_FILE = "/data/local/tmp/" + COMMAND_LINE_FILE;
// This metadata key, if defined, overrides the default behaviour of loading WebLayer from the
// current WebView implementation. This is only intended for testing, and does not enforce any
// signature requirements on the implementation, nor does it use the production code path to
// load the code. Do not set this in production APKs!
private static final String PACKAGE_MANIFEST_KEY = "org.chromium.weblayer.WebLayerPackage";
// SharedPreferences key storing the versionCode of the most recently loaded WebLayer library.
public static final String PREF_LAST_VERSION_CODE =
"org.chromium.weblayer.last_version_code_used";
// The required package ID for WebLayer when loaded as a shared library, hardcoded in the
// resources. If this value changes make sure to change _SHARED_LIBRARY_HARDCODED_ID in
// //build/android/gyp/util/protoresources.py and WebViewChromiumFactoryProvider.java.
private static final int REQUIRED_PACKAGE_IDENTIFIER = 36;
// 0 results in using the default value.
private static int sMaxNavigationsForInstanceState = 0;
private final ProfileManager mProfileManager = new ProfileManager();
private boolean mInited;
private static IWebLayerClient sClient;
// Whether WebView is running in process. Set in init().
private boolean mIsWebViewCompatMode;
private boolean mOnNativeLoadedCalled;
private static class FileProviderHelper implements ContentUriUtils.FileProviderUtil {
// Keep this variable in sync with the value defined in AndroidManifest.xml.
private static final String API_AUTHORITY_SUFFIX =
".org.chromium.weblayer.client.FileProvider";
@Override
public Uri getContentUriFromFile(File file) {
Context appContext = ContextUtils.getApplicationContext();
return FileProvider.getUriForFile(
appContext, appContext.getPackageName() + API_AUTHORITY_SUFFIX, file);
}
}
WebLayerImpl() {}
@Override
public void loadAsync(IObjectWrapper appContextWrapper, IObjectWrapper remoteContextWrapper,
IObjectWrapper loadedCallbackWrapper) {
StrictModeWorkaround.apply();
Context appContext = ObjectWrapper.unwrap(appContextWrapper, Context.class);
Context remoteContext = ObjectWrapper.unwrap(remoteContextWrapper, Context.class);
init(appContext, remoteContext);
final ValueCallback<Boolean> loadedCallback = (ValueCallback<Boolean>) ObjectWrapper.unwrap(
loadedCallbackWrapper, ValueCallback.class);
// WARNING: Ensure any method calls from this guard against the possibility of being called
// multiple times (see comment in loadSync()).
BrowserStartupController.getInstance().startBrowserProcessesAsync(
LibraryProcessType.PROCESS_WEBLAYER,
/* startGpu */ true, /* startMinimalBrowser */ false,
new BrowserStartupController.StartupCallback() {
@Override
public void onSuccess() {
onNativeLoaded(appContext);
loadedCallback.onReceiveValue(true);
}
@Override
public void onFailure() {
loadedCallback.onReceiveValue(false);
}
});
}
@Override
public void loadSync(IObjectWrapper appContextWrapper, IObjectWrapper remoteContextWrapper) {
StrictModeWorkaround.apply();
Context appContext = ObjectWrapper.unwrap(appContextWrapper, Context.class);
Context remoteContext = ObjectWrapper.unwrap(remoteContextWrapper, Context.class);
init(appContext, remoteContext);
BrowserStartupController.getInstance().startBrowserProcessesSync(
LibraryProcessType.PROCESS_WEBLAYER,
/*singleProcess=*/false, /*startGpuProcess=*/true);
onNativeLoaded(appContext);
// WARNING: loadAsync() may be in progress, and may call methods that this does as well.
// Ensure any method calls from this guard against the possibility of being called multiple
// times.
}
private void onNativeLoaded(Context appContext) {
// This may be called multiple times, ensure processing only happens once.
if (mOnNativeLoadedCalled) return;
mOnNativeLoadedCalled = true;
// TODO(swestphal): Move this earlier when it is not depending on native code being loaded.
ChildProcessLauncherHelper.warmUp(appContext, true);
CrashReporterControllerImpl.getInstance().notifyNativeInitialized();
NetworkChangeNotifier.init();
NetworkChangeNotifier.registerToReceiveNotificationsAlways();
// Native and variations has to be loaded before this.
loadComponents();
// This issues JNI calls which require native code to be loaded.
MetricsServiceClient.init();
WebLayerOriginVerificationScheduler.init(appContext.getPackageName(),
mProfileManager.getProfile(/* name= */ "", true), appContext);
assert mInited;
WebLayerImplJni.get().setIsWebViewCompatMode(mIsWebViewCompatMode);
}
private void init(Context appContext, Context remoteContext) {
if (mInited) {
return;
}
mInited = true;
UmaUtils.recordMainEntryPointTime();
LibraryLoader.getInstance().setLibraryProcessType(LibraryProcessType.PROCESS_WEBLAYER);
// The remote context will have a different class loader than WebLayerImpl here if we are in
// WebView compat mode, since WebView compat mode creates it's own class loader. The class
// loader from remoteContext will actually never be used, since
// ClassLoaderContextWrapperFactory will override the class loader, and all contexts used in
// WebLayer should come from ClassLoaderContextWrapperFactory.
mIsWebViewCompatMode = remoteContext != null
&& !remoteContext.getClassLoader().equals(WebLayerImpl.class.getClassLoader());
if (mIsWebViewCompatMode) {
notifyWebViewRunningInProcess(remoteContext.getClassLoader());
}
Context wrappedAppContext = minimalInitForContext(appContext, remoteContext);
GmsBridge.getInstance().checkClientAppContext(wrappedAppContext);
// Load library in the background since it may be expensive.
// TODO(crbug.com/1146438): Look into enabling relro sharing in browser process. It seems to
// crash when WebView is loaded in the same process.
new BackgroundOnlyAsyncTask<Void>() {
@Override
protected Void doInBackground() {
LibraryLoader.getInstance().loadNow();
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
PackageInfo packageInfo = WebViewFactory.getLoadedPackageInfo();
if (!CommandLine.isInitialized()) {
if (BuildInfo.isDebugAndroid()) {
// This disk read in the critical path is for development purposes only.
try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) {
File localCommandLineFile =
new File(wrappedAppContext.getFilesDir(), COMMAND_LINE_FILE);
if (localCommandLineFile.exists()) {
CommandLine.initFromFile(localCommandLineFile.getPath());
} else {
CommandLine.initFromFile(PUBLIC_COMMAND_LINE_FILE);
}
}
} else {
CommandLine.init(null);
}
}
TraceEvent.maybeEnableEarlyTracing(/*readCommandLine=*/true);
TraceEvent.begin("WebLayer init");
WebApkValidator.init(
ChromeWebApkHostSignature.EXPECTED_SIGNATURE, ChromeWebApkHostSignature.PUBLIC_KEY);
BuildInfo.setBrowserPackageInfo(packageInfo);
BuildInfo.setFirebaseAppId(
FirebaseConfig.getFirebaseAppIdForPackage(packageInfo.packageName));
SelectionPopupController.setMustUseWebContentsContext();
SelectionPopupController.setShouldGetReadbackViewFromWindowAndroid();
ResourceBundle.setAvailablePakLocales(ProductConfig.LOCALES);
BundleUtils.setIsBundle(ProductConfig.IS_BUNDLE);
setChildProcessCreationParams(wrappedAppContext, packageInfo.packageName);
// Creating the Android shared preferences object causes I/O.
try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) {
SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
deleteDataIfPackageDowngrade(prefs, packageInfo);
}
DeviceUtils.addDeviceSpecificUserAgentSwitch();
ContentUriUtils.setFileProviderUtil(new FileProviderHelper());
GmsBridge.getInstance().setSafeBrowsingHandler();
GmsBridge.getInstance().initializeBuiltInPaymentApps();
MediaStreamManager.onWebLayerInit();
WebLayerNotificationChannels.updateChannelsIfNecessary();
ContactsPicker.setContactsPickerDelegate(
(WindowAndroid windowAndroid, ContactsPickerListener listener,
boolean allowMultiple, boolean includeNames, boolean includeEmails,
boolean includeTel, boolean includeAddresses, boolean includeIcons,
String formattedOrigin) -> {
ContactsPickerDialog dialog = new ContactsPickerDialog(windowAndroid,
new ContactsPickerAdapter(windowAndroid), listener, allowMultiple,
includeNames, includeEmails, includeTel, includeAddresses, includeIcons,
formattedOrigin);
dialog.show();
return dialog;
});
DecoderServiceHost.setIntentSupplier(() -> { return createImageDecoderServiceIntent(); });
SelectFileDialog.setPhotoPickerDelegate(new PhotoPickerDelegateBase() {
@Override
public PhotoPicker showPhotoPicker(WindowAndroid windowAndroid,
PhotoPickerListener listener, boolean allowMultiple, List<String> mimeTypes) {
PhotoPickerDialog dialog = new PhotoPickerDialog(windowAndroid,
windowAndroid.getContext().get().getContentResolver(), listener,
allowMultiple, mimeTypes);
dialog.show();
return dialog;
}
});
Clipboard.getInstance().setImageFileProvider(new ClipboardImageFileProvider());
// Clear previously shared images from disk in the background.
new BackgroundOnlyAsyncTask<Void>() {
@Override
protected Void doInBackground() {
ShareImageFileUtils.clearSharedImages();
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
performDexFixIfNecessary(packageInfo);
TraceEvent.end("WebLayer init");
}
@Override
public IBrowser createBrowser(IObjectWrapper serviceContext, IObjectWrapper fragmentArgs) {
StrictModeWorkaround.apply();
Bundle unwrappedFragmentArgs = ObjectWrapper.unwrap(fragmentArgs, Bundle.class);
Context unwrappedServiceContext = ObjectWrapper.unwrap(serviceContext, Context.class);
BrowserImpl browser =
new BrowserImpl(unwrappedServiceContext, mProfileManager, unwrappedFragmentArgs);
return browser;
}
@Override
public IProfile getProfile(String profileName) {
StrictModeWorkaround.apply();
boolean isIncognito = "".equals(profileName);
return mProfileManager.getProfile(profileName, isIncognito);
}
@Override
public IProfile getIncognitoProfile(String profileName) {
StrictModeWorkaround.apply();
return mProfileManager.getProfile(profileName, true);
}
@Override
public void setRemoteDebuggingEnabled(boolean enabled) {
StrictModeWorkaround.apply();
WebLayerImplJni.get().setRemoteDebuggingEnabled(enabled);
}
@Override
public boolean isRemoteDebuggingEnabled() {
StrictModeWorkaround.apply();
return WebLayerImplJni.get().isRemoteDebuggingEnabled();
}
@Override
public ICrashReporterController getCrashReporterController(
IObjectWrapper appContext, IObjectWrapper remoteContext) {
StrictModeWorkaround.apply();
// This is a no-op if init has already happened.
minimalInitForContext(ObjectWrapper.unwrap(appContext, Context.class),
ObjectWrapper.unwrap(remoteContext, Context.class));
return CrashReporterControllerImpl.getInstance();
}
@Override
public void onReceivedBroadcast(IObjectWrapper appContextWrapper, Intent intent) {
StrictModeWorkaround.apply();
Context context = ObjectWrapper.unwrap(appContextWrapper, Context.class);
if (IntentUtils.handleIntent(intent)) return;
if (intent.getAction().startsWith(DownloadImpl.getIntentPrefix())) {
DownloadImpl.forwardIntent(context, intent, mProfileManager);
}
}
@Override
public void onMediaSessionServiceStarted(IObjectWrapper sessionService, Intent intent) {
StrictModeWorkaround.apply();
MediaSessionManager.serviceStarted(
ObjectWrapper.unwrap(sessionService, Service.class), intent);
}
@Override
public void onMediaSessionServiceDestroyed() {
StrictModeWorkaround.apply();
MediaSessionManager.serviceDestroyed();
}
@Override
public void onRemoteMediaServiceStarted(IObjectWrapper sessionService, Intent intent) {
StrictModeWorkaround.apply();
MediaRouterClientImpl.serviceStarted(
ObjectWrapper.unwrap(sessionService, Service.class), intent);
}
@Override
public void onRemoteMediaServiceDestroyed(int id) {
StrictModeWorkaround.apply();
MediaRouterClientImpl.serviceDestroyed(id);
}
@Override
public IBinder initializeImageDecoder(IObjectWrapper appContext, IObjectWrapper remoteContext) {
StrictModeWorkaround.apply();
assert ContextUtils.getApplicationContext() == null;
CommandLine.init(null);
minimalInitForContext(ObjectWrapper.unwrap(appContext, Context.class),
ObjectWrapper.unwrap(remoteContext, Context.class));
LibraryLoader.getInstance().setLibraryProcessType(
LibraryProcessType.PROCESS_WEBLAYER_CHILD);
LibraryLoader.getInstance().ensureInitialized();
ImageDecoder imageDecoder = new ImageDecoder();
imageDecoder.initializeSandbox();
return imageDecoder;
}
@Override
public IObjectWrapper createGooglePayDataCallbacksService() {
StrictModeWorkaround.apply();
return ObjectWrapper.wrap(GmsBridge.getInstance().createGooglePayDataCallbacksService());
}
@Override
public IObjectWrapper createPaymentDetailsUpdateService() {
StrictModeWorkaround.apply();
return ObjectWrapper.wrap(new PaymentDetailsUpdateService());
}
@Override
public void enumerateAllProfileNames(IObjectWrapper valueCallback) {
StrictModeWorkaround.apply();
final ValueCallback<String[]> callback =
(ValueCallback<String[]>) ObjectWrapper.unwrap(valueCallback, ValueCallback.class);
ProfileImpl.enumerateAllProfileNames(callback);
}
@Override
public void setClient(IWebLayerClient client) {
StrictModeWorkaround.apply();
sClient = client;
if (WebLayerFactoryImpl.getClientMajorVersion() >= 88) {
try {
RecordHistogram.recordTimesHistogram("WebLayer.Startup.ClassLoaderCreationTime",
sClient.getClassLoaderCreationTime());
RecordHistogram.recordTimesHistogram(
"WebLayer.Startup.ContextCreationTime", sClient.getContextCreationTime());
RecordHistogram.recordTimesHistogram("WebLayer.Startup.WebLayerLoaderCreationTime",
sClient.getWebLayerLoaderCreationTime());
} catch (RemoteException e) {
throw new APICallException(e);
}
}
}
@Override
public String getUserAgentString() {
StrictModeWorkaround.apply();
return WebLayerImplJni.get().getUserAgentString();
}
@Override
public void registerExternalExperimentIDs(String trialName, int[] experimentIDs) {
StrictModeWorkaround.apply();
WebLayerImplJni.get().registerExternalExperimentIDs(experimentIDs);
}
@Override
public String getXClientDataHeader() {
StrictModeWorkaround.apply();
return WebLayerImplJni.get().getXClientDataHeader();
}
@Override
public IObjectWrapper getApplicationContext() {
StrictModeWorkaround.apply();
return ObjectWrapper.wrap(ContextUtils.getApplicationContext());
}
public static int getMaxNavigationsPerTabForInstanceState() {
try {
return (WebLayerFactoryImpl.getClientMajorVersion() >= 98)
? sClient.getMaxNavigationsPerTabForInstanceState()
: 0;
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static Intent createIntent() {
if (sClient == null) {
throw new IllegalStateException("WebLayer should have been initialized already.");
}
try {
return sClient.createIntent();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static Intent createMediaSessionServiceIntent() {
if (sClient == null) {
throw new IllegalStateException("WebLayer should have been initialized already.");
}
try {
return sClient.createMediaSessionServiceIntent();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static Intent createImageDecoderServiceIntent() {
if (sClient == null) {
throw new IllegalStateException("WebLayer should have been initialized already.");
}
try {
return sClient.createImageDecoderServiceIntent();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static int getMediaSessionNotificationId() {
if (sClient == null) {
throw new IllegalStateException("WebLayer should have been initialized already.");
}
try {
return sClient.getMediaSessionNotificationId();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static Intent createRemoteMediaServiceIntent() {
if (sClient == null) {
throw new IllegalStateException("WebLayer should have been initialized already.");
}
try {
return sClient.createRemoteMediaServiceIntent();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static int getPresentationApiNotificationId() {
if (sClient == null) {
throw new IllegalStateException("WebLayer should have been initialized already.");
}
try {
return sClient.getPresentationApiNotificationId();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static int getRemotePlaybackApiNotificationId() {
if (sClient == null) {
throw new IllegalStateException("WebLayer should have been initialized already.");
}
try {
return sClient.getRemotePlaybackApiNotificationId();
} catch (RemoteException e) {
throw new APICallException(e);
}
}
public static String getClientApplicationName() {
Context context = ContextUtils.getApplicationContext();
return new StringBuilder()
.append(context.getPackageManager().getApplicationLabel(
context.getApplicationInfo()))
.toString();
}
/**
* Converts the given id into a resource ID that can be shown in system UI, such as
* notifications.
*/
public static int getResourceIdForSystemUi(int id) {
if (isAndroidResource(id)) {
return id;
}
Context context = ContextUtils.getApplicationContext();
try {
// String may be missing translations, since they are loaded at a different package ID
// by default in standalone WebView.
assert !context.getResources().getResourceTypeName(id).equals("string");
} catch (Resources.NotFoundException e) {
}
id &= 0x00ffffff;
id |= (0x01000000
* getPackageId(context, WebViewFactory.getLoadedPackageInfo().packageName));
return id;
}
/** Returns whether this ID is from the android system package. */
public static boolean isAndroidResource(int id) {
try {
return ContextUtils.getApplicationContext()
.getResources()
.getResourcePackageName(id)
.equals("android");
} catch (Resources.NotFoundException e) {
return false;
}
}
/**
* Performs the minimal initialization needed for a context. This is used for example in
* CrashReporterControllerImpl, so it can be used before full WebLayer initialization.
*/
private static Context minimalInitForContext(Context appContext, Context remoteContext) {
if (ContextUtils.getApplicationContext() != null) {
return ContextUtils.getApplicationContext();
}
assert remoteContext != null;
Context lightContext = createContextForMode(remoteContext, Configuration.UI_MODE_NIGHT_NO);
Context darkContext = createContextForMode(remoteContext, Configuration.UI_MODE_NIGHT_YES);
ClassLoaderContextWrapperFactory.setLightDarkResourceOverrideContext(
lightContext, darkContext);
int lightPackageId = forceCorrectPackageId(lightContext);
int darkPackageId = forceCorrectPackageId(darkContext);
assert lightPackageId == darkPackageId;
// TODO: The call to onResourcesLoaded() can be slow, we may need to parallelize this with
// other expensive startup tasks.
R.onResourcesLoaded(lightPackageId);
// Wrap the app context so that it can be used to load WebLayer implementation classes.
appContext = ClassLoaderContextWrapperFactory.get(appContext);
ContextUtils.initApplicationContext(appContext);
PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DIRECTORY_SUFFIX, PRIVATE_DIRECTORY_SUFFIX);
return appContext;
}
/** Forces the correct package ID or dies with a runtime exception. */
private static int forceCorrectPackageId(Context remoteContext) {
int packageId = getPackageId(remoteContext, remoteContext.getPackageName());
// This is using app_as_shared_lib, no change needed.
if (packageId >= 0x7f) {
return packageId;
}
if (packageId > REQUIRED_PACKAGE_IDENTIFIER) {
throw new AndroidRuntimeException(
"WebLayer can't be used with other shared libraries. Package ID: " + packageId
+ ", Loaded packages: " + getLoadedPackageNames(remoteContext));
}
forceAddAssetPaths(remoteContext, packageId);
return REQUIRED_PACKAGE_IDENTIFIER;
}
/** Forces adding entries to the package identifiers array until we hit the required ID. */
private static void forceAddAssetPaths(Context remoteContext, int packageId) {
try {
Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
String path = remoteContext.getApplicationInfo().sourceDir;
// Add enough paths to make sure we reach the required ID.
for (int i = packageId; i < REQUIRED_PACKAGE_IDENTIFIER; i++) {
// Change the path to ensure the asset path is re-added and grabs a new package ID.
path = "/." + path;
addAssetPath.invoke(remoteContext.getAssets(), path);
}
} catch (ReflectiveOperationException e) {
throw new AndroidRuntimeException(e);
}
}
/**
* Returns the package ID to use when calling R.onResourcesLoaded().
*/
private static int getPackageId(Context appContext, String implPackageName) {
try {
Constructor<WebViewDelegate> constructor =
WebViewDelegate.class.getDeclaredConstructor();
constructor.setAccessible(true);
WebViewDelegate delegate = constructor.newInstance();
return delegate.getPackageId(appContext.getResources(), implPackageName);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
/** Gets a string with all the loaded package names in this context. */
private static String getLoadedPackageNames(Context appContext) {
try {
Method getAssignedPackageIdentifiers =
AssetManager.class.getMethod("getAssignedPackageIdentifiers");
SparseArray<String> packageIdentifiers =
(SparseArray) getAssignedPackageIdentifiers.invoke(
appContext.getResources().getAssets());
List<String> packageNames = new ArrayList<>();
for (int i = 0; i < packageIdentifiers.size(); i++) {
String name = packageIdentifiers.valueAt(i);
int key = packageIdentifiers.keyAt(i);
// This is the android package.
if (key == 1) {
continue;
}
// Make sure this doesn't look like a URL so it doesn't get removed from crashes.
packageNames.add(name.replace(".", "_") + " -> " + key);
}
return TextUtils.join(",", packageNames);
} catch (ReflectiveOperationException e) {
return "unknown";
}
}
private void setChildProcessCreationParams(Context appContext, String implPackageName) {
final boolean bindToCaller = true;
final boolean ignoreVisibilityForImportance = false;
final String privilegedServicesPackageName = appContext.getPackageName();
final String privilegedServicesName =
"org.chromium.weblayer.ChildProcessService$Privileged";
String sandboxedServicesPackageName = appContext.getPackageName();
String sandboxedServicesName = "org.chromium.weblayer.ChildProcessService$Sandboxed";
boolean isExternalService = false;
boolean loadedFromWebView = wasLoadedFromWebView(appContext);
if (loadedFromWebView && supportsBindingToWebViewService(appContext, implPackageName)) {
// When loading from a WebView implementation, use WebView's declared external services
// as our renderers. This means on O+ we benefit from the webview zygote process, and on
// other versions we ensure the client app doesn't slow down isolated process startup.
// We still need to use the client's privileged services, as only isolated services can
// be external.
isExternalService = true;
sandboxedServicesPackageName = implPackageName;
sandboxedServicesName = null;
}
ChildProcessCreationParams.set(privilegedServicesPackageName, privilegedServicesName,
sandboxedServicesPackageName, sandboxedServicesName, isExternalService,
LibraryProcessType.PROCESS_WEBLAYER_CHILD, bindToCaller,
ignoreVisibilityForImportance);
}
private static boolean supportsBindingToWebViewService(Context context, String packageName) {
// Android N has issues with WebView with the non-system user.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
try {
PackageInfo packageInfo =
context.getPackageManager().getPackageInfo(packageName, 0);
// Package may be disabled for non-system users.
if (!packageInfo.applicationInfo.enabled) {
return false;
}
} catch (PackageManager.NameNotFoundException e) {
// Package may be uninstalled for non-system users.
return false;
}
}
return true;
}
private static boolean wasLoadedFromWebView(Context appContext) {
try {
Bundle metaData = appContext.getPackageManager()
.getApplicationInfo(appContext.getPackageName(),
PackageManager.GET_META_DATA)
.metaData;
if (metaData != null && metaData.getString(PACKAGE_MANIFEST_KEY) != null) {
return false;
}
return true;
} catch (PackageManager.NameNotFoundException e) {
// This would indicate the client app doesn't exist;
// just return true as there's nothing sensible to do here.
return true;
}
}
private static void deleteDataIfPackageDowngrade(
SharedPreferences prefs, PackageInfo packageInfo) {
int previousVersion = prefs.getInt(PREF_LAST_VERSION_CODE, 0);
int currentVersion = packageInfo.versionCode;
if (getBranchFromVersionCode(currentVersion) < getBranchFromVersionCode(previousVersion)) {
// WebLayer was downgraded since the last run. Delete the data and cache directories.
File dataDir = new File(PathUtils.getDataDirectory());
Log.i(TAG,
"WebLayer package downgraded from " + previousVersion + " to " + currentVersion
+ "; deleting contents of " + dataDir);
deleteDirectoryContents(dataDir);
}
if (previousVersion != currentVersion) {
prefs.edit().putInt(PREF_LAST_VERSION_CODE, currentVersion).apply();
}
}
/**
* Chromium versionCodes follow the scheme "BBBBPPPAX":
* BBBB: 4 digit branch number. It monotonically increases over time.
* PPP: Patch number in the branch. It is padded with zeroes to the left. These three digits
* may change their meaning in the future.
* A: Architecture digit.
* X: A digit to differentiate APKs for other reasons.
*
* @return The branch number of versionCode.
*/
private static int getBranchFromVersionCode(int versionCode) {
return versionCode / 1_000_00;
}
private static void deleteDirectoryContents(File directory) {
File[] files = directory.listFiles();
if (files == null) {
return;
}
for (File file : files) {
if (!FileUtils.recursivelyDeleteFile(file, FileUtils.DELETE_ALL)) {
Log.w(TAG, "Failed to delete " + file);
}
}
}
private static void notifyWebViewRunningInProcess(ClassLoader webViewClassLoader) {
// TODO(crbug.com/1112001): Investigate why loading classes causes strict mode
// violations in some situations.
try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) {
Class<?> webViewChromiumFactoryProviderClass =
Class.forName("com.android.webview.chromium.WebViewChromiumFactoryProvider",
true, webViewClassLoader);
Method setter = webViewChromiumFactoryProviderClass.getDeclaredMethod(
"setWebLayerRunningInSameProcess");
setter.invoke(null);
} catch (Exception e) {
Log.w(TAG, "Unable to notify WebView running in process.");
}
}
@SuppressLint("DiscouragedPrivateApi")
private static Context createContextForMode(Context remoteContext, int uiMode) {
Configuration configuration = new Configuration();
configuration.uiMode = uiMode;
Context context = remoteContext.createConfigurationContext(configuration);
// DrawableInflater uses the ClassLoader from the Resources object. We need to make sure
// this ClassLoader is correct. See crbug.com/1287000 and crbug.com/1293849 for more
// details.
try {
Field classLoaderField = Resources.class.getDeclaredField("mClassLoader");
classLoaderField.setAccessible(true);
classLoaderField.set(context.getResources(), WebLayerImpl.class.getClassLoader());
} catch (ReflectiveOperationException e) {
Log.e(TAG, "Error setting Resources ClassLoader.", e);
}
return context;
}
@CalledByNative
@Nullable
private static String getEmbedderName() {
return getClientApplicationName();
}
/*
* Android O MR1 has a bug where bg-dexopt-job will break optimized dex files for isolated
* splits. This leads to *very* slow startup on those devices. To mitigate this, we attempt
* to force a dex compile if necessary.
*/
private static void performDexFixIfNecessary(PackageInfo packageInfo) {
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O_MR1) {
return;
}
PostTask.postTask(TaskTraits.BEST_EFFORT_MAY_BLOCK, () -> {
ApplicationInfo appInfo = packageInfo.applicationInfo;
String[] splitNames = appInfo.splitNames;
if (splitNames == null) {
return;
}
for (int i = 0; i < splitNames.length; i++) {
String splitName = splitNames[i];
// WebLayer depends on the "weblayer" split and "chrome" split (if running in
// Monochrome).
if (!splitName.equals("chrome") && !splitName.equals("weblayer")) {
continue;
}
String splitDir = appInfo.splitSourceDirs[i];
try {
if (DexFile.isDexOptNeeded(splitDir)) {
String cmd = String.format("cmd package compile -r shared --split %s %s",
new File(splitDir).getName(), packageInfo.packageName);
Runtime.getRuntime().exec(cmd);
}
} catch (IOException e) {
Log.e(TAG, "Error fixing dex files.", e);
}
}
});
}
/**
* Load components files from {@link
* org.chromium.android_webview.services.ComponentsProviderService}.
*/
private static void loadComponents() {
ComponentLoaderPolicyBridge[] componentPolicies =
WebLayerImplJni.get().getComponentLoaderPolicies();
// Don't connect to the service if there are no components to load.
if (componentPolicies.length == 0) {
return;
}
final Intent intent = new Intent();
intent.setClassName(getWebViewFactoryPackageName(),
EmbeddedComponentLoader.AW_COMPONENTS_PROVIDER_SERVICE);
new EmbeddedComponentLoader(Arrays.asList(componentPolicies)).connect(intent);
}
/**
* WebViewFactory is not a public android API so R8 is unable to compute its
* API level. This causes R8 to not be able to inline WebLayerImplJni#get
* into WebLayerImpl#loadComponents.
* References to WebViewFactory are in a separate method to avoid this issue
* and allow WebLayerImplJni#get to be inlined into WebLayerImpl#loadComponents.
* @DoNotInline is to avoid any similar inlining issues whenever this method
* is referenced.
*/
@DoNotInline
private static String getWebViewFactoryPackageName() {
return WebViewFactory.getLoadedPackageInfo().packageName;
}
@NativeMethods
interface Natives {
void setRemoteDebuggingEnabled(boolean enabled);
boolean isRemoteDebuggingEnabled();
void setIsWebViewCompatMode(boolean value);
String getUserAgentString();
void registerExternalExperimentIDs(int[] experimentIDs);
String getXClientDataHeader();
ComponentLoaderPolicyBridge[] getComponentLoaderPolicies();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java | Java | unknown | 42,778 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.NotificationManager;
import android.content.SharedPreferences;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.annotation.StringDef;
import org.chromium.base.ContextUtils;
import org.chromium.components.browser_ui.notifications.NotificationManagerProxyImpl;
import org.chromium.components.browser_ui.notifications.channels.ChannelDefinitions;
import org.chromium.components.browser_ui.notifications.channels.ChannelDefinitions.PredefinedChannel;
import org.chromium.components.browser_ui.notifications.channels.ChannelsInitializer;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Defines notification channels for WebLayer. */
@RequiresApi(Build.VERSION_CODES.O)
public class WebLayerNotificationChannels extends ChannelDefinitions {
/**
* Version number identifying the current set of channels. This must be incremented whenever the
* set of channels returned by {@link #getStartupChannelIds()} or {@link #getLegacyChannelIds()}
* changes.
*/
static final int sChannelsVersion = 0;
static final String sChannelsVersionKey = "org.chromium.weblayer.notification_channels_version";
private static class LazyHolder {
private static WebLayerNotificationChannels sInstance = new WebLayerNotificationChannels();
}
public static WebLayerNotificationChannels getInstance() {
return LazyHolder.sInstance;
}
private WebLayerNotificationChannels() {}
/**
* To define a new channel, add the channel ID to this StringDef and add a new entry to
* PredefinedChannels.MAP below with the appropriate channel parameters. To remove an existing
* channel, remove the ID from this StringDef, remove its entry from Predefined Channels.MAP,
* and add it to the return value of {@link #getLegacyChannelIds()}.
*/
@StringDef({ChannelId.ACTIVE_DOWNLOADS, ChannelId.COMPLETED_DOWNLOADS, ChannelId.MEDIA_PLAYBACK,
ChannelId.WEBRTC_CAM_AND_MIC})
@Retention(RetentionPolicy.SOURCE)
public @interface ChannelId {
String ACTIVE_DOWNLOADS = "org.chromium.weblayer.active_downloads";
String COMPLETED_DOWNLOADS = "org.chromium.weblayer.completed_downloads";
String MEDIA_PLAYBACK = "org.chromium.weblayer.media_playback";
String WEBRTC_CAM_AND_MIC = "org.chromium.weblayer.webrtc_cam_and_mic";
}
@StringDef({ChannelGroupId.WEBLAYER})
@Retention(RetentionPolicy.SOURCE)
public @interface ChannelGroupId {
String WEBLAYER = "org.chromium.weblayer";
}
// Map defined in static inner class so it's only initialized lazily.
private static class PredefinedChannels {
static final Map<String, PredefinedChannel> MAP;
static {
Map<String, PredefinedChannel> map = new HashMap<>();
map.put(ChannelId.ACTIVE_DOWNLOADS,
PredefinedChannel.create(ChannelId.ACTIVE_DOWNLOADS,
R.string.notification_category_downloads,
NotificationManager.IMPORTANCE_LOW, ChannelGroupId.WEBLAYER));
map.put(ChannelId.COMPLETED_DOWNLOADS,
PredefinedChannel.create(ChannelId.COMPLETED_DOWNLOADS,
R.string.notification_category_completed_downloads,
NotificationManager.IMPORTANCE_LOW, ChannelGroupId.WEBLAYER));
map.put(ChannelId.MEDIA_PLAYBACK,
PredefinedChannel.create(ChannelId.MEDIA_PLAYBACK,
R.string.notification_category_media_playback,
NotificationManager.IMPORTANCE_LOW, ChannelGroupId.WEBLAYER));
map.put(ChannelId.WEBRTC_CAM_AND_MIC,
PredefinedChannel.create(ChannelId.WEBRTC_CAM_AND_MIC,
R.string.notification_category_webrtc_cam_and_mic,
NotificationManager.IMPORTANCE_LOW, ChannelGroupId.WEBLAYER));
MAP = Collections.unmodifiableMap(map);
}
}
// Map defined in static inner class so it's only initialized lazily.
private static class PredefinedChannelGroups {
static final Map<String, PredefinedChannelGroup> MAP;
static {
Map<String, PredefinedChannelGroup> map = new HashMap<>();
map.put(ChannelGroupId.WEBLAYER,
new PredefinedChannelGroup(ChannelGroupId.WEBLAYER,
R.string.weblayer_notification_channel_group_name));
MAP = Collections.unmodifiableMap(map);
}
}
@Override
public Set<String> getAllChannelGroupIds() {
return PredefinedChannelGroups.MAP.keySet();
}
@Override
public Set<String> getAllChannelIds() {
return PredefinedChannels.MAP.keySet();
}
@Override
public Set<String> getStartupChannelIds() {
return Collections.emptySet();
}
@Override
public List<String> getLegacyChannelIds() {
return Collections.emptyList();
}
@Override
public PredefinedChannelGroup getChannelGroup(@ChannelGroupId String groupId) {
return PredefinedChannelGroups.MAP.get(groupId);
}
@Override
public PredefinedChannel getChannelFromId(@ChannelId String channelId) {
return PredefinedChannels.MAP.get(channelId);
}
/**
* Updates the user-facing channel names after a locale switch.
*/
public static void onLocaleChanged() {
if (!isAtLeastO()) return;
getChannelsInitializer().updateLocale(ContextUtils.getApplicationContext().getResources());
}
/**
* Updates the registered channels based on {@link sChannelsVersion}.
*/
public static void updateChannelsIfNecessary() {
if (!isAtLeastO()) return;
SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
if (prefs.getInt(sChannelsVersionKey, -1) == sChannelsVersion) return;
ChannelsInitializer initializer = getChannelsInitializer();
initializer.deleteLegacyChannels();
initializer.initializeStartupChannels();
prefs.edit().putInt(sChannelsVersionKey, sChannelsVersion).apply();
}
private static boolean isAtLeastO() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
}
private static ChannelsInitializer getChannelsInitializer() {
assert isAtLeastO();
return new ChannelsInitializer(
new NotificationManagerProxyImpl(ContextUtils.getApplicationContext()),
getInstance(), ContextUtils.getApplicationContext().getResources());
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerNotificationChannels.java | Java | unknown | 6,978 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.drawable.Icon;
import android.webkit.WebViewFactory;
import androidx.annotation.NonNull;
import org.chromium.base.ContextUtils;
import org.chromium.components.browser_ui.notifications.NotificationManagerProxyImpl;
import org.chromium.components.browser_ui.notifications.NotificationMetadata;
import org.chromium.components.browser_ui.notifications.NotificationWrapperBuilder;
import org.chromium.components.browser_ui.notifications.NotificationWrapperStandardBuilder;
import org.chromium.components.browser_ui.notifications.channels.ChannelsInitializer;
/** A notification builder for WebLayer which has extra logic to make icons work correctly. */
public final class WebLayerNotificationWrapperBuilder extends NotificationWrapperStandardBuilder {
/** Creates a notification builder. */
public static WebLayerNotificationWrapperBuilder create(
@WebLayerNotificationChannels.ChannelId String channelId,
@NonNull NotificationMetadata metadata) {
Context appContext = ContextUtils.getApplicationContext();
ChannelsInitializer initializer =
new ChannelsInitializer(new NotificationManagerProxyImpl(appContext),
WebLayerNotificationChannels.getInstance(), appContext.getResources());
return new WebLayerNotificationWrapperBuilder(appContext, channelId, initializer, metadata);
}
private WebLayerNotificationWrapperBuilder(Context context, String channelId,
ChannelsInitializer channelsInitializer, NotificationMetadata metadata) {
super(context, channelId, channelsInitializer, metadata);
}
@Override
public NotificationWrapperBuilder setSmallIcon(int icon) {
if (WebLayerImpl.isAndroidResource(icon)) {
super.setSmallIcon(icon);
} else {
super.setSmallIcon(createIcon(icon));
}
return this;
}
@Override
@SuppressWarnings("deprecation")
public NotificationWrapperBuilder addAction(
int icon, CharSequence title, PendingIntent intent) {
if (WebLayerImpl.isAndroidResource(icon)) {
super.addAction(icon, title, intent);
} else {
super.addAction(
new Notification.Action.Builder(createIcon(icon), title, intent).build());
}
return this;
}
private Icon createIcon(int resId) {
return Icon.createWithResource(WebViewFactory.getLoadedPackageInfo().packageName,
WebLayerImpl.getResourceIdForSystemUi(resId));
}
/**
* Finds a reasonable replacement for the given app-defined resource from among stock android
* resources. This is useful when {@link Icon} is not available.
*/
private int getFallbackAndroidResource(int appResourceId) {
if (appResourceId == R.drawable.ic_play_arrow_white_24dp) {
return android.R.drawable.ic_media_play;
}
if (appResourceId == R.drawable.ic_pause_white_24dp) {
return android.R.drawable.ic_media_pause;
}
if (appResourceId == R.drawable.ic_stop_white_24dp) {
// There's no ic_media_stop. This standin is at least a square. In practice this
// shouldn't ever come up as stop is only used in (Chrome) cast notifications.
return android.R.drawable.checkbox_off_background;
}
if (appResourceId == R.drawable.ic_skip_previous_white_24dp) {
return android.R.drawable.ic_media_previous;
}
if (appResourceId == R.drawable.ic_skip_next_white_24dp) {
return android.R.drawable.ic_media_next;
}
if (appResourceId == R.drawable.ic_fast_forward_white_24dp) {
return android.R.drawable.ic_media_ff;
}
if (appResourceId == R.drawable.ic_fast_rewind_white_24dp) {
return android.R.drawable.ic_media_rew;
}
if (appResourceId == R.drawable.audio_playing) {
return android.R.drawable.ic_lock_silent_mode_off;
}
return android.R.drawable.radiobutton_on_background;
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerNotificationWrapperBuilder.java | Java | unknown | 4,400 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import org.chromium.base.Callback;
import org.chromium.base.ThreadUtils;
import org.chromium.components.content_relationship_verification.OriginVerificationScheduler;
import org.chromium.components.content_relationship_verification.OriginVerifier;
import org.chromium.components.content_relationship_verification.OriginVerifierHelper;
import org.chromium.components.embedder_support.util.Origin;
import org.chromium.content_public.browser.BrowserContextHandle;
import java.util.Set;
/**
* Singleton.
* WebLayerOriginVerificationScheduler provides a WebLayer specific implementation of {@link
* OriginVerificationScheduler}.
*
* Call {@link WebLayerOriginVerificationScheduler#init} to initialize the statement list and call
* {@link WebLayerOriginVerificationScheduler#verify} to perform an origin validation.
*/
public class WebLayerOriginVerificationScheduler extends OriginVerificationScheduler {
private static final String TAG = "WLOriginVerification";
private static WebLayerOriginVerificationScheduler sInstance;
private WebLayerOriginVerifier mOriginVerifier;
private WebLayerOriginVerificationScheduler(
WebLayerOriginVerifier originVerifier, Set<Origin> pendingOrigins) {
super(originVerifier, pendingOrigins);
mOriginVerifier = originVerifier;
}
/**
* Initializes the WebLayerOriginVerificationScheduler.
* This should be called exactly only once as it parses the AndroidManifest and statement list.
*
* @param packageName the package name of the host application.
* @param profile the profile to use for the simpleUrlLoader to download the asset links file.
* @param context a context associated with an Activity/Service to load resources.
*/
static void init(String packageName, BrowserContextHandle profile, Context context) {
ThreadUtils.assertOnUiThread();
assert sInstance
== null : "`init(String packageName, Context context)` must only be called once";
sInstance = new WebLayerOriginVerificationScheduler(
new WebLayerOriginVerifier(packageName, OriginVerifier.HANDLE_ALL_URLS, profile,
WebLayerVerificationResultStore.getInstance()),
OriginVerifierHelper.getClaimedOriginsFromManifest(packageName, context));
}
static WebLayerOriginVerificationScheduler getInstance() {
assert sInstance != null : "Call to `init(String packageName, Context context)` missing";
return sInstance;
}
@Override
public void verify(String url, Callback<Boolean> callback) {
if (mOriginVerifier.skipOriginVerification()) {
callback.onResult(true);
return;
}
super.verify(url, callback);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerOriginVerificationScheduler.java | Java | unknown | 3,018 |
// 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;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.ContextUtils;
import org.chromium.components.content_relationship_verification.OriginVerifier;
import org.chromium.components.content_relationship_verification.Relationship;
import org.chromium.components.embedder_support.util.Origin;
import org.chromium.components.embedder_support.util.UrlConstants;
import org.chromium.content_public.browser.BrowserContextHandle;
import java.util.List;
import java.util.Locale;
/**
* WebLayerOriginVerifier performs OriginVerifications for Weblayer.
* It uses the WebLayerVerificationResultStore to cache validations.
*/
public class WebLayerOriginVerifier extends OriginVerifier {
private static final String METADATA_SKIP_ORIGIN_VERIFICATION_KEY =
"org.chromium.weblayer.skipOriginVerification";
private static final String METADATA_STRICT_LOCALHOST_VERIFICATION_KEY =
"org.chromium.weblayer.strictLocalhostVerification";
private final boolean mSkipOriginVerification = getSkipOriginVerificationFromManifest();
private final boolean mStrictLocalhostVerification =
getStrictLocalhostVerificationFromManifest();
/**
* Main constructor.
* Use {@link WebLayerOriginVerifier#start}.
* @param packageName The package for the Android application for verification.
* @param relationship Digital Asset Links relationship to use during verification.
* @param profile profile to retrieve the browser context for creating the url
* loader factory.
* @param verificationResultStore The {@link ChromeVerificationResultStore} for persisting
* results.
*
*/
public WebLayerOriginVerifier(String packageName, String relationship,
BrowserContextHandle profile,
@Nullable WebLayerVerificationResultStore verificationResultStore) {
super(packageName, relationship, null, profile, verificationResultStore);
}
@Override
public boolean isAllowlisted(String packageName, Origin origin, String relation) {
String host = origin.uri().getHost();
if (UrlConstants.LOCALHOST.equals(host.toLowerCase(Locale.US))) {
return !mStrictLocalhostVerification;
}
return false;
}
@Override
public boolean wasPreviouslyVerified(Origin origin) {
return wasPreviouslyVerified(mPackageName, mSignatureFingerprints, origin, mRelation);
}
/**
* Returns whether an origin is first-party relative to a given package name.
*
* This only returns data from previously cached relations, and does not trigger an asynchronous
* validation.
*
* @param packageName The package name.
* @param signatureFingerprint The signatures of the package.
* @param origin The origin to verify.
* @param relation The Digital Asset Links relation to verify for.
*/
private static boolean wasPreviouslyVerified(String packageName,
List<String> signatureFingerprints, Origin origin, String relation) {
WebLayerVerificationResultStore resultStore = WebLayerVerificationResultStore.getInstance();
return resultStore.shouldOverride(packageName, origin, relation)
|| resultStore.isRelationshipSaved(
new Relationship(packageName, signatureFingerprints, origin, relation));
}
// TODO(swestphal): Only for testing during development, remove again eventually.
boolean skipOriginVerification() {
return mSkipOriginVerification;
}
private boolean getSkipOriginVerificationFromManifest() {
try {
Context context = ContextUtils.getApplicationContext();
Bundle metaData = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA)
.metaData;
if (metaData != null) {
return metaData.getBoolean(METADATA_SKIP_ORIGIN_VERIFICATION_KEY);
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
@VisibleForTesting
boolean getStrictLocalhostVerificationFromManifest() {
try {
Context context = ContextUtils.getApplicationContext();
Bundle metaData = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA)
.metaData;
if (metaData != null) {
return metaData.getBoolean(METADATA_STRICT_LOCALHOST_VERIFICATION_KEY);
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
@Override
public void recordResultMetrics(OriginVerifier.VerifierResult result) {
// TODO(swestphal): Implement UMA logging.
}
@Override
public void recordVerificationTimeMetrics(long duration, boolean online) {
// TODO(swestphal): Implement UMA logging.
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerOriginVerifier.java | Java | unknown | 5,493 |
// 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;
import static org.robolectric.Shadows.shadowOf;
import android.os.Process;
import androidx.test.core.app.ApplicationProvider;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
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.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.JniMocker;
import org.chromium.components.content_relationship_verification.OriginVerifier;
import org.chromium.components.content_relationship_verification.OriginVerifier.OriginVerificationListener;
import org.chromium.components.content_relationship_verification.OriginVerifierJni;
import org.chromium.components.content_relationship_verification.OriginVerifierUnitTestSupport;
import org.chromium.components.content_relationship_verification.RelationshipCheckResult;
import org.chromium.components.embedder_support.util.Origin;
import org.chromium.content_public.browser.BrowserContextHandle;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import java.util.concurrent.CountDownLatch;
/** Tests for WebLayerOriginVerifier. */
@RunWith(BaseRobolectricTestRunner.class)
@Batch(WebLayerOriginVerifierTest.TEST_BATCH_NAME)
public class WebLayerOriginVerifierTest {
public static final String TEST_BATCH_NAME = "weblayer_origin_verifier";
private static final String PACKAGE_NAME = "org.chromium.weblayer_private";
private int mUid = Process.myUid();
private Origin mHttpsOrigin = Origin.create("https://www.example.com");
private Origin mHttpOrigin = Origin.create("http://www.android.com");
private Origin mHttpLocalhostOrigin = Origin.create("http://localhost:1234/");
private boolean mStrictLocalhostVerification;
private WebLayerOriginVerifier mHandleAllUrlsVerifier;
@Rule
public MockitoRule mMockitoRule = MockitoJUnit.rule().strictness(Strictness.WARN);
@Rule
public JniMocker mJniMocker = new JniMocker();
@Mock
private OriginVerifier.Natives mMockOriginVerifierJni;
private CountDownLatch mVerificationResultLatch = new CountDownLatch(1);
private CountDownLatch mVerificationResultLatch2 = new CountDownLatch(1);
private static class TestOriginVerificationListener implements OriginVerificationListener {
private CountDownLatch mLatch;
private boolean mVerified;
TestOriginVerificationListener(CountDownLatch latch) {
mLatch = latch;
}
@Override
public void onOriginVerified(
String packageName, Origin origin, boolean verified, Boolean online) {
mVerified = verified;
mLatch.countDown();
}
public boolean isVerified() {
return mVerified;
}
}
private class TestWebLayerOriginVerifier extends WebLayerOriginVerifier {
public TestWebLayerOriginVerifier(String packageName, String relationship,
WebLayerVerificationResultStore verificationResultStore) {
super(packageName, relationship, Mockito.mock(BrowserContextHandle.class),
verificationResultStore);
}
@Override
boolean getStrictLocalhostVerificationFromManifest() {
return mStrictLocalhostVerification;
}
}
@Before
public void setUp() throws Exception {
OriginVerifierUnitTestSupport.registerPackageWithSignature(
shadowOf(ApplicationProvider.getApplicationContext().getPackageManager()),
PACKAGE_NAME, mUid);
mJniMocker.mock(OriginVerifierJni.TEST_HOOKS, mMockOriginVerifierJni);
Mockito.doAnswer(args -> { return 100L; })
.when(mMockOriginVerifierJni)
.init(Mockito.any(), Mockito.any());
Mockito.doAnswer(args -> {
mHandleAllUrlsVerifier.onOriginVerificationResult(
args.getArgument(4), RelationshipCheckResult.SUCCESS);
return true;
})
.when(mMockOriginVerifierJni)
.verifyOrigin(ArgumentMatchers.anyLong(), Mockito.any(),
ArgumentMatchers.anyString(), Mockito.any(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyString(), Mockito.any());
mHandleAllUrlsVerifier = new TestWebLayerOriginVerifier(PACKAGE_NAME,
"delegate_permission/common.handle_all_urls",
WebLayerVerificationResultStore.getInstance());
}
@Test
public void testHttpsVerification() throws Exception {
TestOriginVerificationListener resultListener =
new TestOriginVerificationListener(mVerificationResultLatch);
TestThreadUtils.runOnUiThreadBlocking(
() -> mHandleAllUrlsVerifier.start(resultListener, mHttpsOrigin));
mVerificationResultLatch.await();
Assert.assertTrue(resultListener.isVerified());
}
@Test
public void testHttpVerificationNotAllowed() throws Exception {
TestOriginVerificationListener resultListener =
new TestOriginVerificationListener(mVerificationResultLatch);
TestThreadUtils.runOnUiThreadBlocking(
() -> mHandleAllUrlsVerifier.start(resultListener, mHttpOrigin));
mVerificationResultLatch.await();
Assert.assertFalse(resultListener.isVerified());
}
@Test
public void testHttpLocalhostVerificationAllowed() throws Exception {
Mockito.doAnswer(args -> {
Assert.fail("verifyOrigin was unexpectedly called.");
return true;
})
.when(mMockOriginVerifierJni)
.verifyOrigin(ArgumentMatchers.anyLong(), Mockito.any(),
ArgumentMatchers.anyString(), Mockito.any(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyString(), Mockito.any());
TestOriginVerificationListener resultListener =
new TestOriginVerificationListener(mVerificationResultLatch);
TestThreadUtils.runOnUiThreadBlocking(
() -> mHandleAllUrlsVerifier.start(resultListener, mHttpLocalhostOrigin));
mVerificationResultLatch.await();
Assert.assertTrue(resultListener.isVerified());
}
@Test
public void testHttpLocalhostVerificationNotSkippedWithFlag() throws Exception {
mStrictLocalhostVerification = true;
Mockito.doAnswer(args -> {
mHandleAllUrlsVerifier.onOriginVerificationResult(
args.getArgument(4), RelationshipCheckResult.SUCCESS);
return true;
})
.when(mMockOriginVerifierJni)
.verifyOrigin(ArgumentMatchers.anyLong(), Mockito.any(),
ArgumentMatchers.anyString(), Mockito.any(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyString(), Mockito.any());
TestOriginVerificationListener resultListener =
new TestOriginVerificationListener(mVerificationResultLatch);
TestThreadUtils.runOnUiThreadBlocking(
() -> mHandleAllUrlsVerifier.start(resultListener, mHttpLocalhostOrigin));
mVerificationResultLatch.await();
Assert.assertTrue(resultListener.isVerified());
}
@Test
public void testConcurrentVerifications() throws Exception {
Mockito.doAnswer(args -> {
// Don't call onOriginVerificationResult to simulate a long request.
return true;
})
.when(mMockOriginVerifierJni)
.verifyOrigin(ArgumentMatchers.anyLong(), Mockito.any(),
ArgumentMatchers.anyString(), Mockito.any(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyString(), Mockito.any());
TestOriginVerificationListener verificationResult1 =
new TestOriginVerificationListener(mVerificationResultLatch);
TestThreadUtils.runOnUiThreadBlocking(
() -> mHandleAllUrlsVerifier.start(verificationResult1, mHttpsOrigin));
Assert.assertFalse(verificationResult1.isVerified());
Assert.assertEquals(mHandleAllUrlsVerifier.getNumListeners(mHttpsOrigin), 1);
// Never called, but if it was called, the following asserts would break.
Mockito.doAnswer(args -> {
mHandleAllUrlsVerifier.onOriginVerificationResult(
args.getArgument(4), RelationshipCheckResult.SUCCESS);
return true;
})
.when(mMockOriginVerifierJni)
.verifyOrigin(ArgumentMatchers.anyLong(), Mockito.any(),
ArgumentMatchers.anyString(), Mockito.any(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyString(), Mockito.any());
TestOriginVerificationListener verificationResult2 =
new TestOriginVerificationListener(mVerificationResultLatch2);
TestThreadUtils.runOnUiThreadBlocking(
() -> mHandleAllUrlsVerifier.start(verificationResult2, mHttpsOrigin));
Assert.assertFalse(verificationResult2.isVerified());
// Check that both requests are registered as Listeners.
Assert.assertEquals(mHandleAllUrlsVerifier.getNumListeners(mHttpsOrigin), 2);
// Call the {@link OriginVerifier#onOriginVerificationResult} callback and verify that
// both listeners receive the result.
mHandleAllUrlsVerifier.onOriginVerificationResult(
mHttpsOrigin.toString(), RelationshipCheckResult.SUCCESS);
mVerificationResultLatch.await();
mVerificationResultLatch2.await();
Assert.assertTrue(verificationResult1.isVerified());
Assert.assertTrue(verificationResult2.isVerified());
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerOriginVerifierTest.java | Java | unknown | 10,305 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.chromium.components.browser_ui.modaldialog.TabModalPresenter;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.LayoutInflaterUtils;
import org.chromium.ui.modelutil.PropertyModel;
/**
* The presenter that displays a single tab modal dialog.
*
* TODO(estade): any tab modal dialog should be dismissed on system back (currently, system back
* will navigate).
*/
public class WebLayerTabModalPresenter extends TabModalPresenter {
private final BrowserViewController mBrowserView;
private final Context mContext;
/**
* Constructor for initializing dialog container.
* @param browserView the BrowserViewController that hosts the dialog container.
* @param context the context used for layout inflation.
*/
public WebLayerTabModalPresenter(BrowserViewController browserView, Context context) {
super(context);
mBrowserView = browserView;
mContext = context;
}
@Override
protected void showDialogContainer() {
mBrowserView.setWebContentIsObscured(true);
// TODO(estade): to match Chrome, don't show the dialog container before browser controls
// are guaranteed fully visible.
runEnterAnimation();
}
@Override
protected void removeDialogView(PropertyModel model) {
mBrowserView.setWebContentIsObscured(false);
super.removeDialogView(model);
}
private FrameLayout loadDialogContainer() {
return (FrameLayout) LayoutInflaterUtils.inflate(
mContext, R.layout.modal_dialog_container, null);
}
@Override
protected ViewGroup createDialogContainer() {
FrameLayout dialogContainer = loadDialogContainer();
dialogContainer.setVisibility(View.GONE);
dialogContainer.setClickable(true);
mBrowserView.getWebContentsOverlayView().addView(dialogContainer,
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
return dialogContainer;
}
@Override
protected void setBrowserControlsAccess(boolean restricted) {
TabImpl tab = mBrowserView.getTab();
WebContents webContents = tab.getWebContents();
if (restricted) {
if (webContents.isFullscreenForCurrentTab()) webContents.exitFullscreen();
saveOrRestoreTextSelection(webContents, true);
} else {
saveOrRestoreTextSelection(webContents, false);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerTabModalPresenter.java | Java | unknown | 2,839 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.components.content_relationship_verification.VerificationResultStore;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* WebLayerVerificationResultStore stores relationships in a local variable.
*/
public class WebLayerVerificationResultStore extends VerificationResultStore {
private static final WebLayerVerificationResultStore sInstance =
new WebLayerVerificationResultStore();
private Set<String> mVerifiedOrigins = Collections.synchronizedSet(new HashSet<>());
private WebLayerVerificationResultStore() {}
public static WebLayerVerificationResultStore getInstance() {
return sInstance;
}
@Override
protected Set<String> getRelationships() {
return mVerifiedOrigins;
}
@Override
protected void setRelationships(Set<String> relationships) {
mVerifiedOrigins = relationships;
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebLayerVerificationResultStore.java | Java | unknown | 1,129 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import org.chromium.components.browser_ui.share.ShareHelper;
import org.chromium.components.browser_ui.share.ShareParams;
import org.chromium.components.browser_ui.webshare.ShareServiceImpl;
import org.chromium.content_public.browser.WebContents;
import org.chromium.services.service_manager.InterfaceFactory;
import org.chromium.webshare.mojom.ShareService;
/**
* Factory that creates instances of ShareService.
*/
public class WebShareServiceFactory implements InterfaceFactory<ShareService> {
private final WebContents mWebContents;
public WebShareServiceFactory(WebContents webContents) {
mWebContents = webContents;
}
@Override
public ShareService createImpl() {
ShareServiceImpl.WebShareDelegate delegate = new ShareServiceImpl.WebShareDelegate() {
@Override
public boolean canShare() {
return mWebContents.getTopLevelNativeWindow().getActivity() != null;
}
@Override
public void share(ShareParams params) {
ShareHelper.shareWithSystemShareSheetUi(params);
}
};
return new ShareServiceImpl(mWebContents, delegate);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebShareServiceFactory.java | Java | unknown | 1,376 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.components.webapps.WebappsUtils;
class WebappsHelper {
private WebappsHelper() {}
@CalledByNative
public static void addShortcutToHomescreen(
String id, String url, String userTitle, Bitmap icon, boolean isIconAdaptive) {
Intent shortcutIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
WebappsUtils.addShortcutToHomescreen(id, userTitle, icon, isIconAdaptive, shortcutIntent);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/WebappsHelper.java | Java | unknown | 780 |
// 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.bluetooth;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.components.omnibox.AutocompleteSchemeClassifier;
import org.chromium.components.permissions.BluetoothChooserAndroidDelegate;
import org.chromium.weblayer_private.AutocompleteSchemeClassifierImpl;
/**
* The implementation of {@link BluetoothChooserAndroidDelegate} for WebLayer.
*/
@JNINamespace("weblayer")
public class WebLayerBluetoothChooserAndroidDelegate implements BluetoothChooserAndroidDelegate {
/**
* {@inheritDoc}
*/
@Override
public AutocompleteSchemeClassifier createAutocompleteSchemeClassifier() {
return new AutocompleteSchemeClassifierImpl();
}
@CalledByNative
private static WebLayerBluetoothChooserAndroidDelegate create() {
return new WebLayerBluetoothChooserAndroidDelegate();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/bluetooth/WebLayerBluetoothChooserAndroidDelegate.java | Java | unknown | 1,079 |
// 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.bluetooth;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.components.omnibox.AutocompleteSchemeClassifier;
import org.chromium.components.permissions.BluetoothScanningPromptAndroidDelegate;
import org.chromium.weblayer_private.AutocompleteSchemeClassifierImpl;
/**
* The implementation of {@link BluetoothScanningPromptAndroidDelegate} for WebLayer.
*/
@JNINamespace("weblayer")
public class WebLayerBluetoothScanningPromptAndroidDelegate
implements BluetoothScanningPromptAndroidDelegate {
/**
* {@inheritDoc}
*/
@Override
public AutocompleteSchemeClassifier createAutocompleteSchemeClassifier() {
return new AutocompleteSchemeClassifierImpl();
}
@CalledByNative
private static WebLayerBluetoothScanningPromptAndroidDelegate create() {
return new WebLayerBluetoothScanningPromptAndroidDelegate();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/bluetooth/WebLayerBluetoothScanningPromptAndroidDelegate.java | Java | unknown | 1,129 |
// 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.util.AndroidRuntimeException;
/**
* Error thrown if there is an error communicating over the AIDL boundary.
*/
public class APICallException extends AndroidRuntimeException {
/**
* Constructs a new exception with the specified cause.
*/
public APICallException(Exception cause) {
super(cause);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/APICallException.java | Java | unknown | 541 |
// 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({ActionModeItemType.SHARE, ActionModeItemType.WEB_SEARCH})
@Retention(RetentionPolicy.SOURCE)
public @interface ActionModeItemType {
int SHARE = 1 << 0;
int WEB_SEARCH = 1 << 1;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/ActionModeItemType.java | Java | unknown | 512 |
// 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;
/** Keys for the Bundle of arguments with which BrowserFragments are created. */
public interface BrowserFragmentArgs {
String PROFILE_NAME = "profile_name";
String PERSISTENCE_ID = "persistence_id";
/**
* A boolean value indicating whether the profile is incognito.
*/
String IS_INCOGNITO = "is_incognito";
String IS_EXTERNAL_INTENTS_ENABLED = "is_external_intents_enabled";
String USE_VIEW_MODEL = "use_view_model";
String ALLOWED_ORIGINS = "allowed_origins";
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/BrowserFragmentArgs.java | Java | unknown | 697 |
// 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({BrowsingDataType.COOKIES_AND_SITE_DATA, BrowsingDataType.CACHE,
BrowsingDataType.SITE_SETTINGS})
@Retention(RetentionPolicy.SOURCE)
public @interface BrowsingDataType {
int COOKIES_AND_SITE_DATA = 0;
int CACHE = 1;
int SITE_SETTINGS = 2;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/BrowsingDataType.java | Java | unknown | 585 |
// 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({CookieChangeCause.INSERTED, CookieChangeCause.EXPLICIT, CookieChangeCause.UNKNOWN_DELETION,
CookieChangeCause.OVERWRITE, CookieChangeCause.EXPIRED, CookieChangeCause.EVICTED,
CookieChangeCause.EXPIRED_OVERWRITE})
@Retention(RetentionPolicy.SOURCE)
public @interface CookieChangeCause {
int INSERTED = 0;
int EXPLICIT = 1;
int UNKNOWN_DELETION = 2;
int OVERWRITE = 3;
int EXPIRED = 4;
int EVICTED = 5;
int EXPIRED_OVERWRITE = 6;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/CookieChangeCause.java | Java | unknown | 799 |
// 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 androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@IntDef({DarkModeStrategy.PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING,
DarkModeStrategy.WEB_THEME_DARKENING_ONLY, DarkModeStrategy.USER_AGENT_DARKENING_ONLY})
@Retention(RetentionPolicy.SOURCE)
public @interface DarkModeStrategy {
int WEB_THEME_DARKENING_ONLY = 0;
int USER_AGENT_DARKENING_ONLY = 1;
int PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING = 2;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/DarkModeStrategy.java | Java | unknown | 689 |
// 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({DownloadError.NO_ERROR, DownloadError.SERVER_ERROR, DownloadError.SSL_ERROR,
DownloadError.CONNECTIVITY_ERROR, DownloadError.NO_SPACE, DownloadError.FILE_ERROR,
DownloadError.CANCELLED, DownloadError.OTHER_ERROR})
@Retention(RetentionPolicy.SOURCE)
public @interface DownloadError {
int NO_ERROR = 0;
int SERVER_ERROR = 1;
int SSL_ERROR = 2;
int CONNECTIVITY_ERROR = 3;
int NO_SPACE = 4;
int FILE_ERROR = 5;
int CANCELLED = 6;
int OTHER_ERROR = 7;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/DownloadError.java | Java | unknown | 823 |
// 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({DownloadState.IN_PROGRESS, DownloadState.COMPLETE, DownloadState.PAUSED,
DownloadState.CANCELLED, DownloadState.FAILED})
@Retention(RetentionPolicy.SOURCE)
public @interface DownloadState {
int IN_PROGRESS = 0;
int COMPLETE = 1;
int PAUSED = 2;
int CANCELLED = 3;
int FAILED = 4;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/DownloadState.java | Java | unknown | 635 |
// 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;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@IntDef({ExceptionType.RESTRICTED_API, ExceptionType.UNKNOWN})
@Retention(RetentionPolicy.SOURCE)
public @interface ExceptionType {
int UNKNOWN = 0;
int RESTRICTED_API = 1;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/ExceptionType.java | Java | unknown | 499 |
// 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 androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@IntDef({ExternalIntentInIncognitoUserDecision.ALLOW, ExternalIntentInIncognitoUserDecision.DENY})
@Retention(RetentionPolicy.SOURCE)
public @interface ExternalIntentInIncognitoUserDecision {
int ALLOW = 0;
int DENY = 1;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/ExternalIntentInIncognitoUserDecision.java | Java | unknown | 547 |
// 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({GoogleAccountServiceType.SIGNOUT, GoogleAccountServiceType.ADD_SESSION,
GoogleAccountServiceType.DEFAULT})
@Retention(RetentionPolicy.SOURCE)
public @interface GoogleAccountServiceType {
int SIGNOUT = 0;
int ADD_SESSION = 1;
int DEFAULT = 2;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/GoogleAccountServiceType.java | Java | unknown | 589 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private.interfaces;
oneway interface IBooleanCallback {
void onResult(in boolean result) = 1;
// TODO(swestphal): Replace parameters with actual Exception when supported to also propagate stacktrace.
void onException(in int type, in String msg) = 2;
} | Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/IBooleanCallback.aidl | AIDL | unknown | 439 |
// 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.IBrowserClient;
import org.chromium.weblayer_private.interfaces.IRemoteFragment;
import org.chromium.weblayer_private.interfaces.IMediaRouteDialogFragment;
import org.chromium.weblayer_private.interfaces.IObjectWrapper;
import org.chromium.weblayer_private.interfaces.IProfile;
import org.chromium.weblayer_private.interfaces.ITab;
import java.util.List;
interface IBrowser {
IProfile getProfile() = 0;
// Sets the active tab, returns false if tab is not attached to this fragment.
boolean setActiveTab(in ITab tab) = 3;
int getActiveTabId() = 4;
List getTabs() = 5;
void setClient(in IBrowserClient client) = 6;
void addTab(in ITab tab) = 7;
void destroyTab(in ITab tab) = 8;
ITab createTab() = 11;
boolean isRestoringPreviousState() = 14;
// Added in 90.
void setDarkModeStrategy(in int strategy) = 16;
// Added in 105
int[] getTabIds() = 20;
void shutdown() = 22;
IRemoteFragment createBrowserFragmentImpl() = 23;
IMediaRouteDialogFragment createMediaRouteDialogFragmentImpl() = 24;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/IBrowser.aidl | AIDL | unknown | 1,278 |
// 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.IRemoteFragment;
import org.chromium.weblayer_private.interfaces.ITab;
interface IBrowserClient {
void onActiveTabChanged(in int activeTabId) = 0;
void onTabAdded(in ITab tab) = 1;
void onTabRemoved(in int tabId) = 2;
IRemoteFragment createMediaRouteDialogFragment() = 3;
void onTabInitializationCompleted() = 5;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/IBrowserClient.aidl | AIDL | unknown | 569 |
// 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;
/** Interface to forward service calls to the service implementation. */
interface IChildProcessService {
void onCreate() = 0;
void onDestroy() = 1;
IObjectWrapper onBind(IObjectWrapper intent) = 2;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/IChildProcessService.aidl | AIDL | unknown | 469 |
// 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;
/**
* Represents a download on the *client* side.
*/
interface IClientDownload {
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/IClientDownload.aidl | AIDL | unknown | 280 |
// 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;
/**
* Represents a navigation on the *client* side.
*/
interface IClientNavigation {
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/IClientNavigation.aidl | AIDL | unknown | 284 |
// 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;
/**
* Represents a page on the *client* side.
*/
interface IClientPage {
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/IClientPage.aidl | AIDL | unknown | 272 |
// 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;
/**
* Holds on to the native ContextMenuParams object.
*/
interface IContextMenuParams {
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/IContextMenuParams.aidl | AIDL | unknown | 288 |
// 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 ICookieChangedCallbackClient {
void onCookieChanged(in String cookie, int cause);
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/java/org/chromium/weblayer_private/interfaces/ICookieChangedCallbackClient.aidl | AIDL | unknown | 291 |