code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/ssl_error_controller_client.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "components/security_interstitials/content/settings_page_helper.h"
#include "components/security_interstitials/content/utils.h"
#include "components/security_interstitials/core/metrics_helper.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/ssl_host_state_delegate.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/i18n_util.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/error_page_delegate.h"
namespace weblayer {
SSLErrorControllerClient::SSLErrorControllerClient(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
std::unique_ptr<security_interstitials::MetricsHelper> metrics_helper,
std::unique_ptr<security_interstitials::SettingsPageHelper>
settings_page_helper)
: security_interstitials::SecurityInterstitialControllerClient(
web_contents,
std::move(metrics_helper),
nullptr /*prefs*/,
i18n::GetApplicationLocale(),
GURL("about:blank") /*default_safe_page*/,
std::move(settings_page_helper)),
cert_error_(cert_error),
ssl_info_(ssl_info),
request_url_(request_url) {}
void SSLErrorControllerClient::GoBack() {
ErrorPageDelegate* delegate =
TabImpl::FromWebContents(web_contents_)->error_page_delegate();
if (delegate && delegate->OnBackToSafety())
return;
SecurityInterstitialControllerClient::GoBackAfterNavigationCommitted();
}
void SSLErrorControllerClient::Proceed() {
web_contents_->GetBrowserContext()->GetSSLHostStateDelegate()->AllowCert(
request_url_.host(), *ssl_info_.cert.get(), cert_error_,
web_contents_->GetPrimaryMainFrame()->GetStoragePartition());
Reload();
}
void SSLErrorControllerClient::OpenUrlInNewForegroundTab(const GURL& url) {
// For now WebLayer doesn't support multiple tabs, so just open the Learn
// More link in the current tab.
OpenUrlInCurrentTab(url);
}
bool SSLErrorControllerClient::CanLaunchDateAndTimeSettings() {
return true;
}
void SSLErrorControllerClient::LaunchDateAndTimeSettings() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::ThreadPool::PostTask(
FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()},
base::BindOnce(&security_interstitials::LaunchDateAndTimeSettings));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/ssl_error_controller_client.cc | C++ | unknown | 2,732 |
// 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_SSL_ERROR_CONTROLLER_CLIENT_H_
#define WEBLAYER_BROWSER_SSL_ERROR_CONTROLLER_CLIENT_H_
#include "components/security_interstitials/content/security_interstitial_controller_client.h"
#include "net/ssl/ssl_info.h"
#include "url/gurl.h"
namespace content {
class WebContents;
}
namespace security_interstitials {
class MetricsHelper;
class SettingsPageHelper;
} // namespace security_interstitials
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 SSL interstitial.
class SSLErrorControllerClient
: public security_interstitials::SecurityInterstitialControllerClient {
public:
SSLErrorControllerClient(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
std::unique_ptr<security_interstitials::MetricsHelper> metrics_helper,
std::unique_ptr<security_interstitials::SettingsPageHelper>
settings_page_helper);
SSLErrorControllerClient(const SSLErrorControllerClient&) = delete;
SSLErrorControllerClient& operator=(const SSLErrorControllerClient&) = delete;
~SSLErrorControllerClient() override = default;
// security_interstitials::SecurityInterstitialControllerClient:
void GoBack() override;
void Proceed() override;
void OpenUrlInNewForegroundTab(const GURL& url) override;
bool CanLaunchDateAndTimeSettings() override;
void LaunchDateAndTimeSettings() override;
private:
const int cert_error_;
const net::SSLInfo ssl_info_;
const GURL request_url_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SSL_ERROR_CONTROLLER_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/ssl_error_controller_client.h | C++ | unknown | 1,869 |
// 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/stateful_ssl_host_state_delegate_factory.h"
#include <memory>
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
StatefulSSLHostStateDelegate*
StatefulSSLHostStateDelegateFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<StatefulSSLHostStateDelegate*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
StatefulSSLHostStateDelegateFactory*
StatefulSSLHostStateDelegateFactory::GetInstance() {
return base::Singleton<StatefulSSLHostStateDelegateFactory>::get();
}
StatefulSSLHostStateDelegateFactory::StatefulSSLHostStateDelegateFactory()
: BrowserContextKeyedServiceFactory(
"StatefulSSLHostStateDelegate",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
StatefulSSLHostStateDelegateFactory::~StatefulSSLHostStateDelegateFactory() =
default;
KeyedService* StatefulSSLHostStateDelegateFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new StatefulSSLHostStateDelegate(
context, user_prefs::UserPrefs::Get(context),
HostContentSettingsMapFactory::GetForBrowserContext(context));
}
content::BrowserContext*
StatefulSSLHostStateDelegateFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/stateful_ssl_host_state_delegate_factory.cc | C++ | unknown | 1,878 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_STATEFUL_SSL_HOST_STATE_DELEGATE_FACTORY_H_
#define WEBLAYER_BROWSER_STATEFUL_SSL_HOST_STATE_DELEGATE_FACTORY_H_
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
#include "components/prefs/pref_service.h"
class StatefulSSLHostStateDelegate;
namespace weblayer {
// Singleton that associates all StatefulSSLHostStateDelegates with
// BrowserContexts.
class StatefulSSLHostStateDelegateFactory
: public BrowserContextKeyedServiceFactory {
public:
static StatefulSSLHostStateDelegate* GetForBrowserContext(
content::BrowserContext* browser_context);
static StatefulSSLHostStateDelegateFactory* GetInstance();
private:
friend struct base::DefaultSingletonTraits<
StatefulSSLHostStateDelegateFactory>;
StatefulSSLHostStateDelegateFactory();
~StatefulSSLHostStateDelegateFactory() override;
StatefulSSLHostStateDelegateFactory(
const StatefulSSLHostStateDelegateFactory&) = delete;
StatefulSSLHostStateDelegateFactory& operator=(
const StatefulSSLHostStateDelegateFactory&) = delete;
// BrowserContextKeyedServiceFactory methods:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_STATEFUL_SSL_HOST_STATE_DELEGATE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/stateful_ssl_host_state_delegate_factory.h | C++ | unknown | 1,623 |
// 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 "base/json/json_reader.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "build/build_config.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/subresource_filter/content/browser/ads_intervention_manager.h"
#include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h"
#include "components/subresource_filter/content/browser/ruleset_service.h"
#include "components/subresource_filter/content/browser/subresource_filter_observer_test_utils.h"
#include "components/subresource_filter/content/browser/subresource_filter_profile_context.h"
#include "components/subresource_filter/core/browser/subresource_filter_constants.h"
#include "components/subresource_filter/core/browser/subresource_filter_features.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/subresource_filter_profile_context_factory.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/grit/weblayer_resources.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/subresource_filter_browser_test_harness.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/infobars/android/infobar_android.h" // nogncheck
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar_manager.h" // nogncheck
#endif
namespace weblayer {
namespace {
const char kAdsInterventionRecordedHistogram[] =
"SubresourceFilter.PageLoad.AdsInterventionTriggered";
const char kTimeSinceAdsInterventionTriggeredHistogram[] =
"SubresourceFilter.PageLoad."
"TimeSinceLastActiveAdsIntervention";
const char kSubresourceFilterActionsHistogram[] = "SubresourceFilter.Actions2";
#if BUILDFLAG(IS_ANDROID)
class TestInfoBarManagerObserver : public infobars::InfoBarManager::Observer {
public:
TestInfoBarManagerObserver() = default;
~TestInfoBarManagerObserver() override = default;
void OnInfoBarAdded(infobars::InfoBar* infobar) override {
if (on_infobar_added_callback_)
std::move(on_infobar_added_callback_).Run();
}
void OnInfoBarRemoved(infobars::InfoBar* infobar, bool animate) override {
if (on_infobar_removed_callback_)
std::move(on_infobar_removed_callback_).Run();
}
void set_on_infobar_added_callback(base::OnceClosure callback) {
on_infobar_added_callback_ = std::move(callback);
}
void set_on_infobar_removed_callback(base::OnceClosure callback) {
on_infobar_removed_callback_ = std::move(callback);
}
private:
base::OnceClosure on_infobar_added_callback_;
base::OnceClosure on_infobar_removed_callback_;
};
#endif // if BUILDFLAG(IS_ANDROID)
} // namespace
// Tests that the ruleset service is available.
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, RulesetService) {
EXPECT_NE(BrowserProcess::GetInstance()->subresource_filter_ruleset_service(),
nullptr);
}
// Tests that the expected ruleset data was published as part of startup.
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, RulesArePublished) {
auto* ruleset_service =
BrowserProcess::GetInstance()->subresource_filter_ruleset_service();
auto ruleset_version = ruleset_service->GetMostRecentlyIndexedVersion();
EXPECT_TRUE(ruleset_version.IsValid());
std::string most_recently_indexed_content_version =
ruleset_version.content_version;
std::string packaged_ruleset_manifest_string =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_SUBRESOURCE_FILTER_UNINDEXED_RULESET_MANIFEST_JSON);
auto packaged_ruleset_manifest =
base::JSONReader::Read(packaged_ruleset_manifest_string);
std::string* packaged_content_version =
packaged_ruleset_manifest->FindStringKey("version");
EXPECT_EQ(most_recently_indexed_content_version, *packaged_content_version);
}
// The below test is restricted to Android as it tests activation of the
// subresource filter in its default production configuration and WebLayer
// currently has a safe browsing database available in production only on
// Android; the safe browsing database being non-null is a prerequisite for
// subresource filter operation.
#if BUILDFLAG(IS_ANDROID)
// Tests that page activation state is computed as part of a pageload.
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
PageActivationStateComputed) {
// Set up prereqs.
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
content::WebContentsConsoleObserver console_observer(web_contents);
console_observer.SetPattern(subresource_filter::kActivationConsoleMessage);
GURL test_url(embedded_test_server()->GetURL("/simple_page.html"));
subresource_filter::TestSubresourceFilterObserver observer(web_contents);
absl::optional<subresource_filter::mojom::ActivationLevel> page_activation =
observer.GetPageActivation(test_url);
EXPECT_FALSE(page_activation);
// Verify that a navigation results in both (a) the page activation level
// being computed, and (b) the result of that computation being the default
// level of "dry run" due to AdTagging.
NavigateAndWaitForCompletion(test_url, shell());
page_activation = observer.GetPageActivation(test_url);
EXPECT_TRUE(page_activation);
EXPECT_EQ(subresource_filter::mojom::ActivationLevel::kDryRun,
page_activation.value());
EXPECT_TRUE(console_observer.messages().empty());
}
#endif // (OS_ANDROID)
// Verifies that subframes that are flagged by the subresource filter ruleset
// are blocked from loading on activated URLs.
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
DisallowedSubframeURLBlockedOnActivatedURL) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
content::WebContentsConsoleObserver console_observer(web_contents);
console_observer.SetPattern(subresource_filter::kActivationConsoleMessage);
GURL test_url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
subresource_filter::TestSubresourceFilterObserver observer(web_contents);
absl::optional<subresource_filter::mojom::ActivationLevel> page_activation =
observer.GetPageActivation(test_url);
EXPECT_FALSE(page_activation);
ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url);
// Verify that the "ad" subframe is loaded if it is not flagged by the
// ruleset.
ASSERT_NO_FATAL_FAILURE(SetRulesetToDisallowURLsWithPathSuffix(
"suffix-that-does-not-match-anything"));
NavigateAndWaitForCompletion(test_url, shell());
// The subresource filter should have been activated on this navigation...
page_activation = observer.GetPageActivation(test_url);
EXPECT_TRUE(page_activation);
EXPECT_EQ(subresource_filter::mojom::ActivationLevel::kEnabled,
page_activation.value());
EXPECT_TRUE(console_observer.Wait());
// ... but it should not have blocked the subframe from being loaded.
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// Do a different-document navigation to ensure that that the next navigation
// to |test_url| executes as desired (e.g., to avoid any optimizations from
// being made due to it being a same-document navigation that would interfere
// with the logic of the test). Without this intervening navigation, we have
// seen flake on the Windows trybot that indicates that such optimizations are
// occurring.
NavigateAndWaitForCompletion(GURL("about:blank"), shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// Verify that the "ad" subframe is blocked if it is flagged by the
// ruleset.
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// Do a different-document navigation to ensure that that the next navigation
// to |test_url| executes as desired (e.g., to avoid any optimizations from
// being made due to it being a same-document navigation that would interfere
// with the logic of the test). Without this intervening navigation, we have
// seen flake on the Windows trybot that indicates that such optimizations are
// occurring.
NavigateAndWaitForCompletion(GURL("about:blank"), shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// The main frame document should never be filtered.
SetRulesetToDisallowURLsWithPathSuffix("frame_with_included_script.html");
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
}
// Verifies that subframes are not blocked on non-activated URLs.
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
DisallowedSubframeURLNotBlockedOnNonActivatedURL) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
GURL test_url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
// Verify that the "ad" subframe is loaded if it is not flagged by the
// ruleset.
ASSERT_NO_FATAL_FAILURE(SetRulesetToDisallowURLsWithPathSuffix(
"suffix-that-does-not-match-anything"));
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// Verify that the "ad" subframe is loaded if even it is flagged by the
// ruleset as the URL is not activated.
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
}
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
ContentSettingsAllowlist_DoNotActivate) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
GURL test_url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url);
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
content::WebContentsConsoleObserver console_observer(web_contents);
console_observer.SetPattern(subresource_filter::kActivationConsoleMessage);
// Simulate explicitly allowlisting via content settings.
HostContentSettingsMap* settings_map =
HostContentSettingsMapFactory::GetForBrowserContext(
web_contents->GetBrowserContext());
settings_map->SetContentSettingDefaultScope(
test_url, test_url, ContentSettingsType::ADS, CONTENT_SETTING_ALLOW);
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// No message for allowlisted url.
EXPECT_TRUE(console_observer.messages().empty());
}
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
ContentSettingsAllowlistGlobal_DoNotActivate) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
GURL test_url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url);
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
content::WebContentsConsoleObserver console_observer(web_contents);
console_observer.SetPattern(subresource_filter::kActivationConsoleMessage);
// Simulate globally allowing ads via content settings.
HostContentSettingsMap* settings_map =
HostContentSettingsMapFactory::GetForBrowserContext(
web_contents->GetBrowserContext());
settings_map->SetDefaultContentSetting(ContentSettingsType::ADS,
CONTENT_SETTING_ALLOW);
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// No message for loads that are not activated.
EXPECT_TRUE(console_observer.messages().empty());
}
#if BUILDFLAG(IS_ANDROID)
// Test that the ads blocked infobar is presented when visiting a page where the
// subresource filter blocks resources from being loaded and is removed when
// navigating away.
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, InfoBarPresentation) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
// Configure the subresource filter to activate on the test URL and to block
// its script from loading.
GURL test_url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url);
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
EXPECT_EQ(0u, infobar_manager->infobar_count());
// Navigate such that the script is blocked and verify that the ads blocked
// infobar is presented.
NavigateAndWaitForCompletion(test_url, shell());
run_loop.Run();
EXPECT_EQ(1u, infobar_manager->infobar_count());
auto* infobar =
static_cast<infobars::InfoBarAndroid*>(infobar_manager->infobar_at(0));
EXPECT_TRUE(infobar->HasSetJavaInfoBar());
EXPECT_EQ(infobar->delegate()->GetIdentifier(),
infobars::InfoBarDelegate::ADS_BLOCKED_INFOBAR_DELEGATE_ANDROID);
// Navigate away and verify that the infobar is removed.
base::RunLoop run_loop2;
infobar_observer.set_on_infobar_removed_callback(run_loop2.QuitClosure());
NavigateAndWaitForCompletion(GURL("about:blank"), shell());
run_loop2.Run();
EXPECT_EQ(0u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
#endif
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
ContentSettingsAllowlistViaReload_DoNotActivate) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
GURL test_url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url);
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// Allowlist via a reload.
content::TestNavigationObserver navigation_observer(web_contents, 1);
GetPrimaryPageThrottleManager()->OnReloadRequested();
navigation_observer.Wait();
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
}
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
ContentSettingsAllowlistViaReload_AllowlistIsByDomain) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
GURL test_url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
ActivateSubresourceFilterInWebContentsForURL(web_contents, test_url);
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// Allowlist via a reload.
content::TestNavigationObserver navigation_observer(web_contents, 1);
GetPrimaryPageThrottleManager()->OnReloadRequested();
navigation_observer.Wait();
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// Another navigation to the same domain should be allowed too.
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html?query"),
shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
// A cross site blocklisted navigation should stay activated, however.
GURL a_url(embedded_test_server()->GetURL(
"a.com", "/subresource_filter/frame_with_included_script.html"));
ActivateSubresourceFilterInWebContentsForURL(web_contents, a_url);
NavigateAndWaitForCompletion(a_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
}
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
AdsInterventionEnforced_PageActivated) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
auto* ads_intervention_manager =
SubresourceFilterProfileContextFactory::GetForBrowserContext(
web_contents->GetBrowserContext())
->ads_intervention_manager();
auto test_clock = std::make_unique<base::SimpleTestClock>();
ads_intervention_manager->set_clock_for_testing(test_clock.get());
const GURL url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
// Should not trigger activation as the URL is not on the blocklist and
// has no active ads interventions.
NavigateAndWaitForCompletion(url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
histogram_tester.ExpectTotalCount(kTimeSinceAdsInterventionTriggeredHistogram,
0);
auto entries = ukm_recorder.GetEntriesByName(
ukm::builders::AdsIntervention_LastIntervention::kEntryName);
EXPECT_EQ(0u, entries.size());
// Trigger an ads violation and renavigate the page. Should trigger
// subresource filter activation.
GetPrimaryPageThrottleManager()->OnAdsViolationTriggered(
web_contents->GetPrimaryMainFrame(),
subresource_filter::mojom::AdsViolation::kMobileAdDensityByHeightAbove30);
NavigateAndWaitForCompletion(url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30),
1);
histogram_tester.ExpectBucketCount(
kTimeSinceAdsInterventionTriggeredHistogram, 0, 1);
entries = ukm_recorder.GetEntriesByName(
ukm::builders::AdsIntervention_LastIntervention::kEntryName);
EXPECT_EQ(1u, entries.size());
ukm_recorder.ExpectEntryMetric(
entries.front(),
ukm::builders::AdsIntervention_LastIntervention::kInterventionTypeName,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30));
ukm_recorder.ExpectEntryMetric(
entries.front(),
ukm::builders::AdsIntervention_LastIntervention::kInterventionStatusName,
static_cast<int>(AdsInterventionStatus::kBlocking));
// Advance the clock to clear the intervention.
test_clock->Advance(subresource_filter::kAdsInterventionDuration.Get());
NavigateAndWaitForCompletion(url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30),
1);
histogram_tester.ExpectBucketCount(
kTimeSinceAdsInterventionTriggeredHistogram,
subresource_filter::kAdsInterventionDuration.Get().InHours(), 1);
entries = ukm_recorder.GetEntriesByName(
ukm::builders::AdsIntervention_LastIntervention::kEntryName);
EXPECT_EQ(2u, entries.size());
// One of the entries is kBlocking, verify that the other is kExpired after
// the intervention is cleared.
EXPECT_TRUE(
(*ukm_recorder.GetEntryMetric(
entries.front(), ukm::builders::AdsIntervention_LastIntervention::
kInterventionStatusName) ==
static_cast<int>(AdsInterventionStatus::kExpired)) ||
(*ukm_recorder.GetEntryMetric(
entries.back(), ukm::builders::AdsIntervention_LastIntervention::
kInterventionStatusName) ==
static_cast<int>(AdsInterventionStatus::kExpired)));
}
IN_PROC_BROWSER_TEST_F(
SubresourceFilterBrowserTest,
MultipleAdsInterventions_PageActivationClearedAfterFirst) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
auto* ads_intervention_manager =
SubresourceFilterProfileContextFactory::GetForBrowserContext(
web_contents->GetBrowserContext())
->ads_intervention_manager();
auto test_clock = std::make_unique<base::SimpleTestClock>();
ads_intervention_manager->set_clock_for_testing(test_clock.get());
const GURL url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
// Should not trigger activation as the URL is not on the blocklist and
// has no active ads interventions.
NavigateAndWaitForCompletion(url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
histogram_tester.ExpectTotalCount(kTimeSinceAdsInterventionTriggeredHistogram,
0);
auto entries = ukm_recorder.GetEntriesByName(
ukm::builders::AdsIntervention_LastIntervention::kEntryName);
EXPECT_EQ(0u, entries.size());
// Trigger an ads violation and renavigate the page. Should trigger
// subresource filter activation.
GetPrimaryPageThrottleManager()->OnAdsViolationTriggered(
web_contents->GetPrimaryMainFrame(),
subresource_filter::mojom::AdsViolation::kMobileAdDensityByHeightAbove30);
NavigateAndWaitForCompletion(url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30),
1);
histogram_tester.ExpectBucketCount(
kTimeSinceAdsInterventionTriggeredHistogram, 0, 1);
entries = ukm_recorder.GetEntriesByName(
ukm::builders::AdsIntervention_LastIntervention::kEntryName);
EXPECT_EQ(1u, entries.size());
ukm_recorder.ExpectEntryMetric(
entries.front(),
ukm::builders::AdsIntervention_LastIntervention::kInterventionTypeName,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30));
ukm_recorder.ExpectEntryMetric(
entries.front(),
ukm::builders::AdsIntervention_LastIntervention::kInterventionStatusName,
static_cast<int>(AdsInterventionStatus::kBlocking));
// Advance the clock by less than kAdsInterventionDuration and trigger another
// intervention. This intervention is a no-op.
test_clock->Advance(subresource_filter::kAdsInterventionDuration.Get() -
base::Minutes(30));
GetPrimaryPageThrottleManager()->OnAdsViolationTriggered(
web_contents->GetPrimaryMainFrame(),
subresource_filter::mojom::AdsViolation::kMobileAdDensityByHeightAbove30);
// Advance the clock to to kAdsInterventionDuration from the first
// intervention, this clear the intervention.
test_clock->Advance(base::Minutes(30));
NavigateAndWaitForCompletion(url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30),
1);
histogram_tester.ExpectBucketCount(
kTimeSinceAdsInterventionTriggeredHistogram,
subresource_filter::kAdsInterventionDuration.Get().InHours(), 1);
entries = ukm_recorder.GetEntriesByName(
ukm::builders::AdsIntervention_LastIntervention::kEntryName);
EXPECT_EQ(2u, entries.size());
// One of the entries is kBlocking, verify that the other is kExpired after
// the intervention is cleared.
EXPECT_TRUE(
(*ukm_recorder.GetEntryMetric(
entries.front(), ukm::builders::AdsIntervention_LastIntervention::
kInterventionStatusName) ==
static_cast<int>(AdsInterventionStatus::kExpired)) ||
(*ukm_recorder.GetEntryMetric(
entries.back(), ukm::builders::AdsIntervention_LastIntervention::
kInterventionStatusName) ==
static_cast<int>(AdsInterventionStatus::kExpired)));
}
class SubresourceFilterBrowserTestWithoutAdsInterventionEnforcement
: public SubresourceFilterBrowserTest {
public:
SubresourceFilterBrowserTestWithoutAdsInterventionEnforcement() {
feature_list_.InitAndDisableFeature(
subresource_filter::kAdsInterventionsEnforced);
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(
SubresourceFilterBrowserTestWithoutAdsInterventionEnforcement,
AdsInterventionNotEnforced_NoPageActivation) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
auto* ads_intervention_manager =
SubresourceFilterProfileContextFactory::GetForBrowserContext(
web_contents->GetBrowserContext())
->ads_intervention_manager();
auto test_clock = std::make_unique<base::SimpleTestClock>();
ads_intervention_manager->set_clock_for_testing(test_clock.get());
const GURL url(embedded_test_server()->GetURL(
"/subresource_filter/frame_with_included_script.html"));
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
// Should not trigger activation as the URL is not on the blocklist and
// has no active ads interventions.
NavigateAndWaitForCompletion(url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
auto entries = ukm_recorder.GetEntriesByName(
ukm::builders::AdsIntervention_LastIntervention::kEntryName);
EXPECT_EQ(0u, entries.size());
// Trigger an ads violation and renavigate to the page. Interventions are not
// enforced so no activation should occur.
GetPrimaryPageThrottleManager()->OnAdsViolationTriggered(
web_contents->GetPrimaryMainFrame(),
subresource_filter::mojom::AdsViolation::kMobileAdDensityByHeightAbove30);
const base::TimeDelta kRenavigationDelay = base::Hours(2);
test_clock->Advance(kRenavigationDelay);
NavigateAndWaitForCompletion(url, shell());
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30),
1);
histogram_tester.ExpectBucketCount(
kTimeSinceAdsInterventionTriggeredHistogram, kRenavigationDelay.InHours(),
1);
entries = ukm_recorder.GetEntriesByName(
ukm::builders::AdsIntervention_LastIntervention::kEntryName);
EXPECT_EQ(1u, entries.size());
ukm_recorder.ExpectEntryMetric(
entries.front(),
ukm::builders::AdsIntervention_LastIntervention::kInterventionTypeName,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30));
ukm_recorder.ExpectEntryMetric(
entries.front(),
ukm::builders::AdsIntervention_LastIntervention::kInterventionStatusName,
static_cast<int>(AdsInterventionStatus::kWouldBlock));
}
// Test the "smart" UI, aka the logic to hide the UI on subsequent same-domain
// navigations, until a certain time threshold has been reached. This is an
// android-only feature.
IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
DoNotShowUIUntilThresholdReached) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
auto* settings_manager =
SubresourceFilterProfileContextFactory::GetForBrowserContext(
web_contents->GetBrowserContext())
->settings_manager();
settings_manager->set_should_use_smart_ui_for_testing(true);
ASSERT_NO_FATAL_FAILURE(
SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
GURL a_url(embedded_test_server()->GetURL(
"a.com", "/subresource_filter/frame_with_included_script.html"));
GURL b_url(embedded_test_server()->GetURL(
"b.com", "/subresource_filter/frame_with_included_script.html"));
// Test utils only support one blocklisted site at a time.
// TODO(csharrison): Add support for more than one URL.
ActivateSubresourceFilterInWebContentsForURL(web_contents, a_url);
auto test_clock = std::make_unique<base::SimpleTestClock>();
base::SimpleTestClock* raw_clock = test_clock.get();
settings_manager->set_clock_for_testing(std::move(test_clock));
base::HistogramTester histogram_tester;
// First load should trigger the UI.
NavigateAndWaitForCompletion(a_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kSubresourceFilterActionsHistogram,
subresource_filter::SubresourceFilterAction::kUIShown, 1);
histogram_tester.ExpectBucketCount(
kSubresourceFilterActionsHistogram,
subresource_filter::SubresourceFilterAction::kUISuppressed, 0);
// Second load should not trigger the UI, but should still filter content.
NavigateAndWaitForCompletion(a_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kSubresourceFilterActionsHistogram,
subresource_filter::SubresourceFilterAction::kUIShown, 1);
histogram_tester.ExpectBucketCount(
kSubresourceFilterActionsHistogram,
subresource_filter::SubresourceFilterAction::kUISuppressed, 1);
ActivateSubresourceFilterInWebContentsForURL(web_contents, b_url);
// Load to another domain should trigger the UI.
NavigateAndWaitForCompletion(b_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kSubresourceFilterActionsHistogram,
subresource_filter::SubresourceFilterAction::kUIShown, 2);
ActivateSubresourceFilterInWebContentsForURL(web_contents, a_url);
// Fast forward the clock, and a_url should trigger the UI again.
raw_clock->Advance(
subresource_filter::SubresourceFilterContentSettingsManager::
kDelayBeforeShowingInfobarAgain);
NavigateAndWaitForCompletion(a_url, shell());
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
kSubresourceFilterActionsHistogram,
subresource_filter::SubresourceFilterAction::kUIShown, 3);
histogram_tester.ExpectBucketCount(
kSubresourceFilterActionsHistogram,
subresource_filter::SubresourceFilterAction::kUISuppressed, 1);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/subresource_filter_browsertest.cc | C++ | unknown | 32,954 |
// 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/subresource_filter_profile_context_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/subresource_filter/content/browser/subresource_filter_profile_context.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
subresource_filter::SubresourceFilterProfileContext*
SubresourceFilterProfileContextFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<subresource_filter::SubresourceFilterProfileContext*>(
GetInstance()->GetServiceForBrowserContext(browser_context,
true /* create */));
}
// static
SubresourceFilterProfileContextFactory*
SubresourceFilterProfileContextFactory::GetInstance() {
static base::NoDestructor<SubresourceFilterProfileContextFactory> factory;
return factory.get();
}
SubresourceFilterProfileContextFactory::SubresourceFilterProfileContextFactory()
: BrowserContextKeyedServiceFactory(
"SubresourceFilterProfileContext",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
KeyedService* SubresourceFilterProfileContextFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
auto* subresource_filter_profile_context =
new subresource_filter::SubresourceFilterProfileContext(
HostContentSettingsMapFactory::GetForBrowserContext(context));
return subresource_filter_profile_context;
}
content::BrowserContext*
SubresourceFilterProfileContextFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/subresource_filter_profile_context_factory.cc | C++ | unknown | 1,992 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SUBRESOURCE_FILTER_PROFILE_CONTEXT_FACTORY_H_
#define WEBLAYER_BROWSER_SUBRESOURCE_FILTER_PROFILE_CONTEXT_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace content {
class BrowserContext;
}
namespace subresource_filter {
class SubresourceFilterProfileContext;
}
namespace weblayer {
// This class is responsible for instantiating a profile-scoped context for
// subresource filtering.
class SubresourceFilterProfileContextFactory
: public BrowserContextKeyedServiceFactory {
public:
static SubresourceFilterProfileContextFactory* GetInstance();
static subresource_filter::SubresourceFilterProfileContext*
GetForBrowserContext(content::BrowserContext* browser_context);
SubresourceFilterProfileContextFactory(
const SubresourceFilterProfileContextFactory&) = delete;
SubresourceFilterProfileContextFactory& operator=(
const SubresourceFilterProfileContextFactory&) = delete;
private:
friend class base::NoDestructor<SubresourceFilterProfileContextFactory>;
SubresourceFilterProfileContextFactory();
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SUBRESOURCE_FILTER_PROFILE_CONTEXT_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/subresource_filter_profile_context_factory.h | C++ | unknown | 1,643 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/system_network_context_manager.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/net_log/net_export_file_writer.h"
#include "components/variations/net/variations_http_headers.h"
#include "content/public/browser/network_service_instance.h"
#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace weblayer {
namespace {
// The global instance of the SystemNetworkContextmanager.
SystemNetworkContextManager* g_system_network_context_manager = nullptr;
} // namespace
// static
SystemNetworkContextManager* SystemNetworkContextManager::CreateInstance(
const std::string& user_agent) {
DCHECK(!g_system_network_context_manager);
g_system_network_context_manager =
new SystemNetworkContextManager(user_agent);
return g_system_network_context_manager;
}
// static
bool SystemNetworkContextManager::HasInstance() {
return !!g_system_network_context_manager;
}
// static
SystemNetworkContextManager* SystemNetworkContextManager::GetInstance() {
DCHECK(g_system_network_context_manager);
return g_system_network_context_manager;
}
// static
void SystemNetworkContextManager::DeleteInstance() {
DCHECK(g_system_network_context_manager);
delete g_system_network_context_manager;
g_system_network_context_manager = nullptr;
}
// static
network::mojom::NetworkContextParamsPtr
SystemNetworkContextManager::CreateDefaultNetworkContextParams(
const std::string& user_agent) {
network::mojom::NetworkContextParamsPtr network_context_params =
network::mojom::NetworkContextParams::New();
network_context_params->cert_verifier_params = content::GetCertVerifierParams(
cert_verifier::mojom::CertVerifierCreationParams::New());
ConfigureDefaultNetworkContextParams(network_context_params.get(),
user_agent);
variations::UpdateCorsExemptHeaderForVariations(network_context_params.get());
return network_context_params;
}
// static
void SystemNetworkContextManager::ConfigureDefaultNetworkContextParams(
network::mojom::NetworkContextParams* network_context_params,
const std::string& user_agent) {
network_context_params->user_agent = user_agent;
// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_WIN)
// We're not configuring the cookie encryption on these platforms yet.
network_context_params->enable_encrypted_cookies = false;
#endif // (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) ||
// BUILDFLAG(IS_WIN)
}
SystemNetworkContextManager::SystemNetworkContextManager(
const std::string& user_agent)
: user_agent_(user_agent) {}
SystemNetworkContextManager::~SystemNetworkContextManager() = default;
network::mojom::NetworkContext*
SystemNetworkContextManager::GetSystemNetworkContext() {
if (!system_network_context_ || !system_network_context_.is_connected()) {
// This should call into OnNetworkServiceCreated(), which will re-create
// the network service, if needed. There's a chance that it won't be
// invoked, if the NetworkContext has encountered an error but the
// NetworkService has not yet noticed its pipe was closed. In that case,
// trying to create a new NetworkContext would fail, anyways, and hopefully
// a new NetworkContext will be created on the next GetContext() call.
content::GetNetworkService();
DCHECK(system_network_context_);
}
return system_network_context_.get();
}
void SystemNetworkContextManager::OnNetworkServiceCreated(
network::mojom::NetworkService* network_service) {
system_network_context_.reset();
network_service->CreateNetworkContext(
system_network_context_.BindNewPipeAndPassReceiver(),
CreateSystemNetworkContextManagerParams());
}
network::mojom::NetworkContextParamsPtr
SystemNetworkContextManager::CreateSystemNetworkContextManagerParams() {
network::mojom::NetworkContextParamsPtr network_context_params =
CreateDefaultNetworkContextParams(user_agent_);
return network_context_params;
}
scoped_refptr<network::SharedURLLoaderFactory>
SystemNetworkContextManager::GetSharedURLLoaderFactory() {
if (!url_loader_factory_) {
auto url_loader_factory_params =
network::mojom::URLLoaderFactoryParams::New();
url_loader_factory_params->process_id = network::mojom::kBrowserProcessId;
url_loader_factory_params->is_corb_enabled = false;
GetSystemNetworkContext()->CreateURLLoaderFactory(
url_loader_factory_.BindNewPipeAndPassReceiver(),
std::move(url_loader_factory_params));
shared_url_loader_factory_ =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
url_loader_factory_.get());
}
return shared_url_loader_factory_;
}
net_log::NetExportFileWriter*
SystemNetworkContextManager::GetNetExportFileWriter() {
if (!net_export_file_writer_) {
net_export_file_writer_ = std::make_unique<net_log::NetExportFileWriter>();
}
return net_export_file_writer_.get();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/system_network_context_manager.cc | C++ | unknown | 5,363 |
// 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_SYSTEM_NETWORK_CONTEXT_MANAGER_H_
#define WEBLAYER_BROWSER_SYSTEM_NETWORK_CONTEXT_MANAGER_H_
#include "base/memory/scoped_refptr.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/network_service.mojom.h"
namespace network {
class SharedURLLoaderFactory;
} // namespace network
namespace net_log {
class NetExportFileWriter;
}
namespace weblayer {
// Manages a system-wide network context that's not tied to a profile.
class SystemNetworkContextManager {
public:
// Creates the global instance of SystemNetworkContextManager.
static SystemNetworkContextManager* CreateInstance(
const std::string& user_agent);
// Checks if the global SystemNetworkContextManager has been created.
static bool HasInstance();
// Gets the global SystemNetworkContextManager instance or DCHECKs if there
// isn't one..
static SystemNetworkContextManager* GetInstance();
// Destroys the global SystemNetworkContextManager instance.
static void DeleteInstance();
static network::mojom::NetworkContextParamsPtr
CreateDefaultNetworkContextParams(const std::string& user_agent);
static void ConfigureDefaultNetworkContextParams(
network::mojom::NetworkContextParams* network_context_params,
const std::string& user_agent);
SystemNetworkContextManager(const SystemNetworkContextManager&) = delete;
SystemNetworkContextManager& operator=(const SystemNetworkContextManager&) =
delete;
~SystemNetworkContextManager();
// Returns the System NetworkContext. Does any initialization of the
// NetworkService that may be needed when first called.
network::mojom::NetworkContext* GetSystemNetworkContext();
// Called when content creates a NetworkService. Creates the
// system NetworkContext, if the network service is enabled.
void OnNetworkServiceCreated(network::mojom::NetworkService* network_service);
// Returns a SharedURLLoaderFactory owned by the SystemNetworkContextManager
// that is backed by the SystemNetworkContext.
// NOTE: This factory assumes that the network service is running in the
// browser process, which is a valid assumption for Android. If WebLayer is
// productionized beyond Android, it will need to be extended to handle
// network service crashes.
scoped_refptr<network::SharedURLLoaderFactory> GetSharedURLLoaderFactory();
// Returns a shared global NetExportFileWriter instance, used by net-export.
// It lives here so it can outlive chrome://net-export/ if the tab is closed
// or destroyed, and so that it's destroyed before Mojo is shut down.
net_log::NetExportFileWriter* GetNetExportFileWriter();
private:
explicit SystemNetworkContextManager(const std::string& user_agent);
network::mojom::NetworkContextParamsPtr
CreateSystemNetworkContextManagerParams();
std::string user_agent_;
mojo::Remote<network::mojom::URLLoaderFactory> url_loader_factory_;
scoped_refptr<network::WeakWrapperSharedURLLoaderFactory>
shared_url_loader_factory_;
mojo::Remote<network::mojom::NetworkContext> system_network_context_;
// Initialized on first access.
std::unique_ptr<net_log::NetExportFileWriter> net_export_file_writer_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SYSTEM_NETWORK_CONTEXT_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/system_network_context_manager.h | C++ | unknown | 3,595 |
// 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/tab_callback_proxy.h"
#include "base/android/jni_string.h"
#include "base/trace_event/trace_event.h"
#include "url/gurl.h"
#include "weblayer/browser/java/jni/TabCallbackProxy_jni.h"
#include "weblayer/browser/tab_impl.h"
using base::android::AttachCurrentThread;
using base::android::ConvertUTF8ToJavaString;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
TabCallbackProxy::TabCallbackProxy(JNIEnv* env, jobject obj, Tab* tab)
: tab_(tab), java_observer_(env, obj) {
tab_->AddObserver(this);
}
TabCallbackProxy::~TabCallbackProxy() {
tab_->RemoveObserver(this);
}
void TabCallbackProxy::DisplayedUrlChanged(const GURL& url) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jstring> jstring_uri_string(
ConvertUTF8ToJavaString(env, url.spec()));
TRACE_EVENT0("weblayer", "Java_TabCallbackProxy_visibleUriChanged");
Java_TabCallbackProxy_visibleUriChanged(env, java_observer_,
jstring_uri_string);
}
void TabCallbackProxy::OnRenderProcessGone() {
TRACE_EVENT0("weblayer", "Java_TabCallbackProxy_onRenderProcessGone");
Java_TabCallbackProxy_onRenderProcessGone(AttachCurrentThread(),
java_observer_);
}
void TabCallbackProxy::OnTitleUpdated(const std::u16string& title) {
JNIEnv* env = AttachCurrentThread();
Java_TabCallbackProxy_onTitleUpdated(
env, java_observer_, base::android::ConvertUTF16ToJavaString(env, title));
}
static jlong JNI_TabCallbackProxy_CreateTabCallbackProxy(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& proxy,
jlong tab) {
return reinterpret_cast<jlong>(
new TabCallbackProxy(env, proxy, reinterpret_cast<TabImpl*>(tab)));
}
static void JNI_TabCallbackProxy_DeleteTabCallbackProxy(JNIEnv* env,
jlong proxy) {
delete reinterpret_cast<TabCallbackProxy*>(proxy);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/tab_callback_proxy.cc | C++ | unknown | 2,127 |
// 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_TAB_CALLBACK_PROXY_H_
#define WEBLAYER_BROWSER_TAB_CALLBACK_PROXY_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "base/memory/raw_ptr.h"
#include "weblayer/public/tab_observer.h"
namespace weblayer {
class Tab;
// TabCallbackProxy forwards all TabObserver functions to the Java side. There
// is one TabCallbackProxy per Tab.
class TabCallbackProxy : public TabObserver {
public:
TabCallbackProxy(JNIEnv* env, jobject obj, Tab* tab);
TabCallbackProxy(const TabCallbackProxy&) = delete;
TabCallbackProxy& operator=(const TabCallbackProxy&) = delete;
~TabCallbackProxy() override;
// TabObserver:
void DisplayedUrlChanged(const GURL& url) override;
void OnRenderProcessGone() override;
void OnTitleUpdated(const std::u16string& title) override;
private:
raw_ptr<Tab> tab_;
base::android::ScopedJavaGlobalRef<jobject> java_observer_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_TAB_CALLBACK_PROXY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/tab_callback_proxy.h | C++ | unknown | 1,135 |
// 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/tab_impl.h"
#include <cmath>
#include "base/auto_reset.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/guid.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/task/thread_pool.h"
#include "base/time/default_tick_clock.h"
#include "build/build_config.h"
#include "cc/layers/layer.h"
#include "components/autofill/content/browser/content_autofill_driver_factory.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/blocked_content/popup_blocker.h"
#include "components/blocked_content/popup_blocker_tab_helper.h"
#include "components/blocked_content/popup_opener_tab_helper.h"
#include "components/blocked_content/popup_tracker.h"
#include "components/captive_portal/core/buildflags.h"
#include "components/content_settings/browser/page_specific_content_settings.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/find_in_page/find_tab_helper.h"
#include "components/find_in_page/find_types.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/permissions/permission_manager.h"
#include "components/permissions/permission_request_manager.h"
#include "components/permissions/permission_result.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/core/browser/db/database_manager.h"
#include "components/sessions/content/session_tab_helper.h"
#include "components/subresource_filter/content/browser/content_subresource_filter_web_contents_helper.h"
#include "components/subresource_filter/content/browser/ruleset_service.h"
#include "components/translate/core/browser/translate_manager.h"
#include "components/ukm/content/source_url_recorder.h"
#include "components/webapps/browser/installable/installable_manager.h"
#include "components/webrtc/media_stream_devices_controller.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/permission_controller.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/renderer_preferences_util.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/common/permissions/permission_utils.h"
#include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/mojom/context_menu/context_menu.mojom.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
#include "third_party/blink/public/mojom/permissions/permission_status.mojom.h"
#include "third_party/blink/public/mojom/window_features/window_features.mojom.h"
#include "ui/base/window_open_disposition.h"
#include "weblayer/browser/autofill_client_impl.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/content_browser_client_impl.h"
#include "weblayer/browser/favicon/favicon_fetcher_impl.h"
#include "weblayer/browser/favicon/favicon_tab_helper.h"
#include "weblayer/browser/file_select_helper.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/i18n_util.h"
#include "weblayer/browser/navigation_controller_impl.h"
#include "weblayer/browser/navigation_entry_data.h"
#include "weblayer/browser/no_state_prefetch/prerender_tab_helper.h"
#include "weblayer/browser/page_load_metrics_initialize.h"
#include "weblayer/browser/page_specific_content_settings_delegate.h"
#include "weblayer/browser/password_manager_driver_factory.h"
#include "weblayer/browser/persistence/browser_persister.h"
#include "weblayer/browser/popup_navigation_delegate_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#include "weblayer/browser/subresource_filter_profile_context_factory.h"
#include "weblayer/browser/translate_client_impl.h"
#include "weblayer/browser/weblayer_features.h"
#include "weblayer/common/isolated_world_ids.h"
#include "weblayer/public/fullscreen_delegate.h"
#include "weblayer/public/new_tab_delegate.h"
#include "weblayer/public/tab_observer.h"
#if !BUILDFLAG(IS_ANDROID)
#include "ui/views/controls/webview/webview.h"
#endif
#if BUILDFLAG(IS_ANDROID)
#include "base/android/callback_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/json/json_writer.h"
#include "base/trace_event/trace_event.h"
#include "components/android_autofill/browser/android_autofill_manager.h"
#include "components/android_autofill/browser/autofill_provider.h"
#include "components/android_autofill/browser/autofill_provider_android.h"
#include "components/browser_ui/sms/android/sms_infobar.h"
#include "components/download/content/public/context_menu_download.h"
#include "components/embedder_support/android/contextmenu/context_menu_builder.h"
#include "components/embedder_support/android/delegate/color_chooser_android.h"
#include "components/javascript_dialogs/tab_modal_dialog_manager.h" // nogncheck
#include "components/safe_browsing/android/remote_database_manager.h"
#include "components/safe_browsing/content/browser/safe_browsing_navigation_observer.h"
#include "components/safe_browsing/content/browser/safe_browsing_tab_observer.h"
#include "components/site_engagement/content/site_engagement_helper.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "components/translate/core/browser/translate_manager.h"
#include "ui/android/view_android.h"
#include "ui/gfx/android/java_bitmap.h"
#include "weblayer/browser/java/jni/TabImpl_jni.h"
#include "weblayer/browser/javascript_tab_modal_dialog_manager_delegate_android.h"
#include "weblayer/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.h"
#include "weblayer/browser/safe_browsing/weblayer_safe_browsing_tab_observer_delegate.h"
#include "weblayer/browser/translate_client_impl.h"
#include "weblayer/browser/webapps/weblayer_app_banner_manager_android.h"
#include "weblayer/browser/weblayer_factory_impl_android.h"
#include "weblayer/browser/webrtc/media_stream_manager.h"
#include "weblayer/common/features.h"
#endif
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
#include "components/captive_portal/content/captive_portal_tab_helper.h"
#include "weblayer/browser/captive_portal_service_factory.h"
#endif
#if BUILDFLAG(IS_ANDROID)
using base::android::AttachCurrentThread;
using base::android::JavaParamRef;
using base::android::ScopedJavaGlobalRef;
using base::android::ScopedJavaLocalRef;
#endif
namespace weblayer {
namespace {
// Maximum size of data when calling SetData().
constexpr int kMaxDataSize = 4096;
#if BUILDFLAG(IS_ANDROID)
bool g_system_autofill_disabled_for_testing = false;
#endif
NewTabType NewTabTypeFromWindowDisposition(WindowOpenDisposition disposition) {
// WindowOpenDisposition has a *ton* of types, but the following are really
// the only ones that should be hit for this code path.
switch (disposition) {
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
return NewTabType::kForeground;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
return NewTabType::kBackground;
case WindowOpenDisposition::NEW_POPUP:
return NewTabType::kNewPopup;
case WindowOpenDisposition::NEW_WINDOW:
return NewTabType::kNewWindow;
default:
// The set of allowed types are in
// ContentTabClientImpl::CanCreateWindow().
NOTREACHED();
return NewTabType::kForeground;
}
}
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
// Opens a captive portal login page in |web_contents|.
void OpenCaptivePortalLoginTabInWebContents(
content::WebContents* web_contents) {
content::OpenURLParams params(
CaptivePortalServiceFactory::GetForBrowserContext(
web_contents->GetBrowserContext())
->test_url(),
content::Referrer(), WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui::PAGE_TRANSITION_LINK, false);
web_contents->OpenURL(params);
}
#endif
// Pointer value of this is used as a key in base::SupportsUserData for
// WebContents. Value of the key is an instance of |UserData|.
constexpr int kWebContentsUserDataKey = 0;
struct UserData : public base::SupportsUserData::Data {
raw_ptr<TabImpl> tab = nullptr;
};
#if BUILDFLAG(IS_ANDROID)
void HandleJavaScriptResult(const ScopedJavaGlobalRef<jobject>& callback,
base::Value result) {
std::string json;
base::JSONWriter::Write(result, &json);
base::android::RunStringCallbackAndroid(callback, json);
}
void OnConvertedToJavaBitmap(const ScopedJavaGlobalRef<jobject>& value_callback,
const ScopedJavaGlobalRef<jobject>& java_bitmap) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
TabImpl::ScreenShotErrors error =
java_bitmap ? TabImpl::ScreenShotErrors::kNone
: TabImpl::ScreenShotErrors::kBitmapAllocationFailed;
Java_TabImpl_runCaptureScreenShotCallback(AttachCurrentThread(),
value_callback, java_bitmap,
static_cast<int>(error));
}
// Convert SkBitmap to java Bitmap on a background thread since it involves a
// memcpy.
void ConvertToJavaBitmapBackgroundThread(
const SkBitmap& bitmap,
base::OnceCallback<void(const ScopedJavaGlobalRef<jobject>&)> callback) {
// Make sure to only pass ScopedJavaGlobalRef between threads.
ScopedJavaGlobalRef<jobject> java_bitmap = ScopedJavaGlobalRef<jobject>(
gfx::ConvertToJavaBitmap(bitmap, gfx::OomBehavior::kReturnNullOnOom));
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), std::move(java_bitmap)));
}
void OnScreenShotCaptured(const ScopedJavaGlobalRef<jobject>& value_callback,
const SkBitmap& bitmap) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (bitmap.isNull() || bitmap.drawsNothing()) {
Java_TabImpl_runCaptureScreenShotCallback(
AttachCurrentThread(), value_callback, nullptr,
static_cast<int>(TabImpl::ScreenShotErrors::kCaptureFailed));
return;
}
// Not using PostTaskAndReplyWithResult to ensure ScopedJavaLocalRef is not
// passed between threads.
base::ThreadPool::PostTask(
FROM_HERE,
{base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(&ConvertToJavaBitmapBackgroundThread, bitmap,
base::BindOnce(&OnConvertedToJavaBitmap, value_callback)));
}
#endif // BUILDFLAG(IS_ANDROID)
std::set<TabImpl*>& GetTabs() {
static base::NoDestructor<std::set<TabImpl*>> s_all_tab_impl;
return *s_all_tab_impl;
}
// Returns a scoped refptr to the SafeBrowsingService's database manager, if
// available. Otherwise returns nullptr.
const scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager>
GetDatabaseManagerFromSafeBrowsingService() {
#if BUILDFLAG(IS_ANDROID)
SafeBrowsingService* safe_browsing_service =
BrowserProcess::GetInstance()->GetSafeBrowsingService();
return scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager>(
safe_browsing_service->GetSafeBrowsingDBManager());
#else
return nullptr;
#endif
}
// Creates a ContentSubresourceFilterWebContentsHelper for |web_contents|,
// passing it the needed embedder-level state.
void CreateContentSubresourceFilterWebContentsHelper(
content::WebContents* web_contents) {
subresource_filter::RulesetService* ruleset_service =
BrowserProcess::GetInstance()->subresource_filter_ruleset_service();
subresource_filter::VerifiedRulesetDealer::Handle* dealer =
ruleset_service ? ruleset_service->GetRulesetDealer() : nullptr;
subresource_filter::ContentSubresourceFilterWebContentsHelper::
CreateForWebContents(
web_contents,
SubresourceFilterProfileContextFactory::GetForBrowserContext(
web_contents->GetBrowserContext()),
GetDatabaseManagerFromSafeBrowsingService(), dealer);
}
} // namespace
#if BUILDFLAG(IS_ANDROID)
static ScopedJavaLocalRef<jobject> JNI_TabImpl_FromWebContents(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& j_web_contents) {
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(j_web_contents);
TabImpl* tab = TabImpl::FromWebContents(web_contents);
if (tab)
return ScopedJavaLocalRef<jobject>(tab->GetJavaTab());
return nullptr;
}
static void JNI_TabImpl_DestroyContextMenuParams(
JNIEnv* env,
jlong native_context_menu_params) {
// Note: this runs on the finalizer thread which isn't the UI thread.
auto* context_menu_params =
reinterpret_cast<content::ContextMenuParams*>(native_context_menu_params);
delete context_menu_params;
}
TabImpl::TabImpl(ProfileImpl* profile,
const JavaParamRef<jobject>& java_impl,
std::unique_ptr<content::WebContents> web_contents)
: TabImpl(profile, std::move(web_contents)) {
java_impl_ = java_impl;
}
#endif
TabImpl::TabImpl(ProfileImpl* profile,
std::unique_ptr<content::WebContents> web_contents,
const std::string& guid)
: profile_(profile),
web_contents_(std::move(web_contents)),
guid_(guid.empty() ? base::GenerateGUID() : guid) {
GetTabs().insert(this);
DCHECK(web_contents_);
// This code path is hit when the page requests a new tab, which should
// only be possible from the same profile.
DCHECK_EQ(profile_->GetBrowserContext(), web_contents_->GetBrowserContext());
// FaviconTabHelper adds a WebContentsObserver. Create FaviconTabHelper
// before |this| observes the WebContents to ensure favicons are reset before
// notifying weblayer observers of changes.
FaviconTabHelper::CreateForWebContents(web_contents_.get());
UpdateRendererPrefs(false);
locale_change_subscription_ =
i18n::RegisterLocaleChangeCallback(base::BindRepeating(
&TabImpl::UpdateRendererPrefs, base::Unretained(this), true));
std::unique_ptr<UserData> user_data = std::make_unique<UserData>();
user_data->tab = this;
web_contents_->SetUserData(&kWebContentsUserDataKey, std::move(user_data));
web_contents_->SetDelegate(this);
Observe(web_contents_.get());
navigation_controller_ = std::make_unique<NavigationControllerImpl>(this);
find_in_page::FindTabHelper::CreateForWebContents(web_contents_.get());
GetFindTabHelper()->AddObserver(this);
TranslateClientImpl::CreateForWebContents(web_contents_.get());
#if BUILDFLAG(IS_ANDROID)
// infobars::ContentInfoBarManager must be created before
// SubresourceFilterClientImpl as the latter depends on it.
infobars::ContentInfoBarManager::CreateForWebContents(web_contents_.get());
#endif
CreateContentSubresourceFilterWebContentsHelper(web_contents_.get());
sessions::SessionTabHelper::CreateForWebContents(
web_contents_.get(),
base::BindRepeating(&TabImpl::GetSessionServiceTabHelperDelegate));
permissions::PermissionRequestManager::CreateForWebContents(
web_contents_.get());
content_settings::PageSpecificContentSettings::CreateForWebContents(
web_contents_.get(),
std::make_unique<PageSpecificContentSettingsDelegate>(
web_contents_.get()));
blocked_content::PopupBlockerTabHelper::CreateForWebContents(
web_contents_.get());
blocked_content::PopupOpenerTabHelper::CreateForWebContents(
web_contents_.get(), base::DefaultTickClock::GetInstance(),
HostContentSettingsMapFactory::GetForBrowserContext(
web_contents_->GetBrowserContext()));
PasswordManagerDriverFactory::CreateForWebContents(web_contents_.get());
InitializePageLoadMetricsForWebContents(web_contents_.get());
ukm::InitializeSourceUrlRecorderForWebContents(web_contents_.get());
#if BUILDFLAG(IS_ANDROID)
javascript_dialogs::TabModalDialogManager::CreateForWebContents(
web_contents_.get(),
std::make_unique<JavaScriptTabModalDialogManagerDelegateAndroid>(
web_contents_.get()));
if (base::FeatureList::IsEnabled(
features::kWebLayerClientSidePhishingDetection)) {
safe_browsing::SafeBrowsingTabObserver::CreateForWebContents(
web_contents_.get(),
std::make_unique<WebLayerSafeBrowsingTabObserverDelegate>());
}
if (site_engagement::SiteEngagementService::IsEnabled()) {
site_engagement::SiteEngagementService::Helper::CreateForWebContents(
web_contents_.get());
}
auto* browser_context =
static_cast<BrowserContextImpl*>(web_contents_->GetBrowserContext());
safe_browsing::SafeBrowsingNavigationObserver::MaybeCreateForWebContents(
web_contents_.get(),
HostContentSettingsMapFactory::GetForBrowserContext(browser_context),
SafeBrowsingNavigationObserverManagerFactory::GetForBrowserContext(
browser_context),
browser_context->pref_service(),
BrowserProcess::GetInstance()->GetSafeBrowsingService());
#endif
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
captive_portal::CaptivePortalTabHelper::CreateForWebContents(
web_contents_.get(),
CaptivePortalServiceFactory::GetForBrowserContext(
web_contents_->GetBrowserContext()),
base::BindRepeating(&OpenCaptivePortalLoginTabInWebContents,
web_contents_.get()));
#endif
// PrerenderTabHelper adds a WebContentsObserver.
PrerenderTabHelper::CreateForWebContents(web_contents_.get());
webapps::InstallableManager::CreateForWebContents(web_contents_.get());
#if BUILDFLAG(IS_ANDROID)
// Must be created after InstallableManager.
WebLayerAppBannerManagerAndroid::CreateForWebContents(web_contents_.get());
#endif
}
TabImpl::~TabImpl() {
DCHECK(!browser_);
GetFindTabHelper()->RemoveObserver(this);
Observe(nullptr);
web_contents_->SetDelegate(nullptr);
if (navigation_controller_->should_delay_web_contents_deletion()) {
// Some user-data on WebContents directly or indirectly references this.
// Remove that linkage to avoid use-after-free.
web_contents_->RemoveUserData(&kWebContentsUserDataKey);
// Have Profile handle the task posting to ensure the WebContents is
// deleted before Profile. To do otherwise means it would be possible for
// the Profile to outlive the WebContents, which is problematic (crash).
profile_->DeleteWebContentsSoon(std::move(web_contents_));
}
web_contents_.reset();
GetTabs().erase(this);
}
// static
TabImpl* TabImpl::FromWebContents(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
UserData* user_data = reinterpret_cast<UserData*>(
web_contents->GetUserData(&kWebContentsUserDataKey));
return user_data ? user_data->tab.get() : nullptr;
}
// static
std::set<TabImpl*> TabImpl::GetAllTabImpl() {
return GetTabs();
}
void TabImpl::AddDataObserver(DataObserver* observer) {
data_observers_.AddObserver(observer);
}
void TabImpl::RemoveDataObserver(DataObserver* observer) {
data_observers_.RemoveObserver(observer);
}
Browser* TabImpl::GetBrowser() {
return browser_;
}
void TabImpl::SetErrorPageDelegate(ErrorPageDelegate* delegate) {
error_page_delegate_ = delegate;
}
void TabImpl::SetFullscreenDelegate(FullscreenDelegate* delegate) {
if (delegate == fullscreen_delegate_)
return;
const bool had_delegate = (fullscreen_delegate_ != nullptr);
const bool has_delegate = (delegate != nullptr);
// If currently fullscreen, and the delegate is being set to null, force an
// exit now (otherwise the delegate can't take us out of fullscreen).
if (is_fullscreen_ && fullscreen_delegate_ && had_delegate != has_delegate)
OnExitFullscreen();
fullscreen_delegate_ = delegate;
// Whether fullscreen is enabled depends upon whether there is a delegate. If
// having a delegate changed, then update the renderer (which is where
// fullscreen enabled is tracked).
if (had_delegate != has_delegate)
web_contents_->OnWebPreferencesChanged();
}
void TabImpl::SetNewTabDelegate(NewTabDelegate* delegate) {
new_tab_delegate_ = delegate;
}
void TabImpl::SetGoogleAccountsDelegate(GoogleAccountsDelegate* delegate) {
google_accounts_delegate_ = delegate;
}
void TabImpl::AddObserver(TabObserver* observer) {
observers_.AddObserver(observer);
}
void TabImpl::RemoveObserver(TabObserver* observer) {
observers_.RemoveObserver(observer);
}
NavigationController* TabImpl::GetNavigationController() {
return navigation_controller_.get();
}
void TabImpl::ExecuteScript(const std::u16string& script,
bool use_separate_isolate,
JavaScriptResultCallback callback) {
if (use_separate_isolate) {
web_contents_->GetPrimaryMainFrame()->ExecuteJavaScriptInIsolatedWorld(
script, std::move(callback), ISOLATED_WORLD_ID_WEBLAYER);
} else {
content::RenderFrameHost::AllowInjectingJavaScript();
web_contents_->GetPrimaryMainFrame()->ExecuteJavaScript(
script, std::move(callback));
}
}
const std::string& TabImpl::GetGuid() {
return guid_;
}
void TabImpl::SetData(const std::map<std::string, std::string>& data) {
bool result = SetDataInternal(data);
DCHECK(result) << "Data given to SetData() was too large.";
}
const std::map<std::string, std::string>& TabImpl::GetData() {
return data_;
}
void TabImpl::ExecuteScriptWithUserGestureForTests(
const std::u16string& script) {
web_contents_->GetPrimaryMainFrame()
->ExecuteJavaScriptWithUserGestureForTests(script, base::NullCallback());
}
std::unique_ptr<FaviconFetcher> TabImpl::CreateFaviconFetcher(
FaviconFetcherDelegate* delegate) {
return std::make_unique<FaviconFetcherImpl>(web_contents_.get(), delegate);
}
void TabImpl::SetTranslateTargetLanguage(
const std::string& translate_target_lang) {
translate::TranslateManager* translate_manager =
TranslateClientImpl::FromWebContents(web_contents())
->GetTranslateManager();
translate_manager->SetPredefinedTargetLanguage(
translate_target_lang,
/*should_auto_translate=*/true);
}
#if !BUILDFLAG(IS_ANDROID)
void TabImpl::AttachToView(views::WebView* web_view) {
web_view->SetWebContents(web_contents_.get());
web_contents_->Focus();
}
#endif
void TabImpl::WebPreferencesChanged() {
web_contents_->OnWebPreferencesChanged();
}
void TabImpl::SetWebPreferences(blink::web_pref::WebPreferences* prefs) {
prefs->fullscreen_supported = !!fullscreen_delegate_;
if (!browser_)
return;
browser_->SetWebPreferences(prefs);
}
void TabImpl::OnGainedActive() {
web_contents()->GetController().LoadIfNecessary();
if (enter_fullscreen_on_gained_active_)
EnterFullscreenImpl();
}
void TabImpl::OnLosingActive() {
if (is_fullscreen_)
web_contents_->ExitFullscreen(/* will_cause_resize */ false);
}
bool TabImpl::IsActive() {
return browser_->GetActiveTab() == this;
}
void TabImpl::ShowContextMenu(const content::ContextMenuParams& params) {
#if BUILDFLAG(IS_ANDROID)
Java_TabImpl_showContextMenu(
base::android::AttachCurrentThread(), java_impl_,
context_menu::BuildJavaContextMenuParams(params),
reinterpret_cast<jlong>(new content::ContextMenuParams(params)));
#endif
}
#if BUILDFLAG(IS_ANDROID)
// static
void TabImpl::DisableAutofillSystemIntegrationForTesting() {
g_system_autofill_disabled_for_testing = true;
}
static jlong JNI_TabImpl_CreateTab(JNIEnv* env,
jlong profile,
const JavaParamRef<jobject>& java_impl) {
ProfileImpl* profile_impl = reinterpret_cast<ProfileImpl*>(profile);
content::WebContents::CreateParams create_params(
profile_impl->GetBrowserContext());
create_params.initially_hidden = true;
return reinterpret_cast<intptr_t>(new TabImpl(
profile_impl, java_impl, content::WebContents::Create(create_params)));
}
static void JNI_TabImpl_DeleteTab(JNIEnv* env, jlong tab) {
TabImpl* tab_impl = reinterpret_cast<TabImpl*>(tab);
DCHECK(tab_impl);
// RemoveTabBeforeDestroyingFromJava() should have been called before this,
// which sets browser to null.
DCHECK(!tab_impl->browser());
delete tab_impl;
}
ScopedJavaLocalRef<jobject> TabImpl::GetWebContents(JNIEnv* env) {
return web_contents_->GetJavaWebContents();
}
void TabImpl::SetJavaImpl(JNIEnv* env, const JavaParamRef<jobject>& impl) {
// This should only be called early on and only once.
DCHECK(!java_impl_);
java_impl_ = impl;
}
void TabImpl::ExecuteScript(JNIEnv* env,
const JavaParamRef<jstring>& script,
bool use_separate_isolate,
const JavaParamRef<jobject>& callback) {
ScopedJavaGlobalRef<jobject> jcallback(env, callback);
ExecuteScript(base::android::ConvertJavaStringToUTF16(script),
use_separate_isolate,
base::BindOnce(&HandleJavaScriptResult, jcallback));
}
void TabImpl::InitializeAutofillIfNecessary(JNIEnv* env) {
if (g_system_autofill_disabled_for_testing)
return;
if (!autofill::ContentAutofillDriverFactory::FromWebContents(
web_contents_.get())) {
InitializeAutofillDriver();
}
}
ScopedJavaLocalRef<jstring> TabImpl::GetGuid(JNIEnv* env) {
return base::android::ConvertUTF8ToJavaString(AttachCurrentThread(),
GetGuid());
}
TabImpl::ScreenShotErrors TabImpl::PrepareForCaptureScreenShot(
float scale,
content::RenderWidgetHostView** rwhv,
gfx::Rect* src_rect,
gfx::Size* output_size) {
if (scale <= 0.f || scale > 1.f)
return ScreenShotErrors::kScaleOutOfRange;
if (!IsActive())
return ScreenShotErrors::kTabNotActive;
if (web_contents_->GetVisibility() != content::Visibility::VISIBLE)
return ScreenShotErrors::kWebContentsNotVisible;
if (!browser_ || !browser_->CompositorHasSurface())
return ScreenShotErrors::kNoSurface;
*rwhv = web_contents_->GetTopLevelRenderWidgetHostView();
if (!*rwhv)
return ScreenShotErrors::kNoRenderWidgetHostView;
if (!(*rwhv)->GetNativeView()->GetWindowAndroid())
return ScreenShotErrors::kNoWindowAndroid;
*src_rect =
gfx::Rect(web_contents_->GetNativeView()->GetPhysicalBackingSize());
if (src_rect->IsEmpty())
return ScreenShotErrors::kEmptyViewport;
*output_size = gfx::ScaleToCeiledSize(src_rect->size(), scale, scale);
if (output_size->IsEmpty())
return ScreenShotErrors::kScaledToEmpty;
return ScreenShotErrors::kNone;
}
void TabImpl::CaptureScreenShot(
JNIEnv* env,
jfloat scale,
const base::android::JavaParamRef<jobject>& value_callback) {
content::RenderWidgetHostView* rwhv = nullptr;
gfx::Rect src_rect;
gfx::Size output_size;
ScreenShotErrors error =
PrepareForCaptureScreenShot(scale, &rwhv, &src_rect, &output_size);
if (error != ScreenShotErrors::kNone) {
Java_TabImpl_runCaptureScreenShotCallback(
env, ScopedJavaLocalRef<jobject>(value_callback),
ScopedJavaLocalRef<jobject>(), static_cast<int>(error));
return;
}
rwhv->CopyFromSurface(
src_rect, output_size,
base::BindOnce(&OnScreenShotCaptured,
ScopedJavaGlobalRef<jobject>(value_callback)));
}
jboolean TabImpl::SetData(
JNIEnv* env,
const base::android::JavaParamRef<jobjectArray>& data) {
std::vector<std::string> flattened_map;
base::android::AppendJavaStringArrayToStringVector(env, data, &flattened_map);
std::map<std::string, std::string> data_map;
for (size_t i = 0; i < flattened_map.size(); i += 2) {
data_map.insert({flattened_map[i], flattened_map[i + 1]});
}
return SetDataInternal(data_map);
}
base::android::ScopedJavaLocalRef<jobjectArray> TabImpl::GetData(JNIEnv* env) {
std::vector<std::string> flattened_map;
for (const auto& kv : data_) {
flattened_map.push_back(kv.first);
flattened_map.push_back(kv.second);
}
return base::android::ToJavaArrayOfStrings(env, flattened_map);
}
jboolean TabImpl::CanTranslate(JNIEnv* env) {
return TranslateClientImpl::FromWebContents(web_contents())
->GetTranslateManager()
->CanManuallyTranslate();
}
void TabImpl::ShowTranslateUi(JNIEnv* env) {
TranslateClientImpl::FromWebContents(web_contents())
->ShowTranslateUiWhenReady();
}
void TabImpl::RemoveTabFromBrowserBeforeDestroying(JNIEnv* env) {
DCHECK(browser_);
browser_->RemoveTabBeforeDestroyingFromJava(this);
}
void TabImpl::SetTranslateTargetLanguage(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& translate_target_lang) {
SetTranslateTargetLanguage(
base::android::ConvertJavaStringToUTF8(env, translate_target_lang));
}
void TabImpl::SetDesktopUserAgentEnabled(JNIEnv* env, jboolean enable) {
if (desktop_user_agent_enabled_ == enable)
return;
desktop_user_agent_enabled_ = enable;
// Reset state that an earlier call to Navigation::SetUserAgentString()
// could have modified.
embedder_support::SetDesktopUserAgentOverride(
web_contents_.get(), embedder_support::GetUserAgentMetadata(),
/* override_in_new_tabs= */ false);
web_contents_->SetRendererInitiatedUserAgentOverrideOption(
content::NavigationController::UA_OVERRIDE_INHERIT);
content::NavigationEntry* entry =
web_contents_->GetController().GetLastCommittedEntry();
if (!entry)
return;
entry->SetIsOverridingUserAgent(enable);
web_contents_->NotifyPreferencesChanged();
web_contents_->GetController().Reload(
content::ReloadType::ORIGINAL_REQUEST_URL, true);
}
jboolean TabImpl::IsDesktopUserAgentEnabled(JNIEnv* env) {
auto* entry = web_contents_->GetController().GetLastCommittedEntry();
if (!entry)
return false;
// The same user agent override mechanism is used for per-navigation user
// agent and desktop mode. Make sure not to return desktop mode for
// navigation entries which used a per-navigation user agent.
auto* entry_data = NavigationEntryData::Get(entry);
if (entry_data && entry_data->per_navigation_user_agent_override())
return false;
return entry->GetIsOverridingUserAgent();
}
void TabImpl::Download(JNIEnv* env, jlong native_context_menu_params) {
auto* context_menu_params =
reinterpret_cast<content::ContextMenuParams*>(native_context_menu_params);
bool is_link = context_menu_params->media_type !=
blink::mojom::ContextMenuDataMediaType::kImage &&
context_menu_params->media_type !=
blink::mojom::ContextMenuDataMediaType::kVideo;
download::CreateContextMenuDownload(web_contents_.get(), *context_menu_params,
std::string(), is_link);
}
#endif // BUILDFLAG(IS_ANDROID)
content::WebContents* TabImpl::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
if (blocked_content::ConsiderForPopupBlocking(params.disposition)) {
bool blocked = blocked_content::MaybeBlockPopup(
source, nullptr,
std::make_unique<PopupNavigationDelegateImpl>(
params, source, nullptr),
¶ms, blink::mojom::WindowFeatures(),
HostContentSettingsMapFactory::GetForBrowserContext(
source->GetBrowserContext())) == nullptr;
if (blocked)
return nullptr;
}
if (params.disposition == WindowOpenDisposition::CURRENT_TAB) {
source->GetController().LoadURLWithParams(
content::NavigationController::LoadURLParams(params));
return source;
}
// All URLs not opening in the current tab will get a new tab.
std::unique_ptr<content::WebContents> new_tab_contents =
content::WebContents::Create(content::WebContents::CreateParams(
web_contents()->GetBrowserContext()));
base::WeakPtr<content::WebContents> new_tab_contents_weak_ptr(
new_tab_contents->GetWeakPtr());
bool was_blocked = false;
AddNewContents(web_contents(), std::move(new_tab_contents), params.url,
params.disposition, {}, params.user_gesture, &was_blocked);
if (was_blocked || !new_tab_contents_weak_ptr)
return nullptr;
new_tab_contents_weak_ptr->GetController().LoadURLWithParams(
content::NavigationController::LoadURLParams(params));
return new_tab_contents_weak_ptr.get();
}
void TabImpl::ShowRepostFormWarningDialog(content::WebContents* source) {
#if BUILDFLAG(IS_ANDROID)
Java_TabImpl_showRepostFormWarningDialog(base::android::AttachCurrentThread(),
java_impl_);
#else
source->GetController().CancelPendingReload();
#endif
}
void TabImpl::NavigationStateChanged(content::WebContents* source,
content::InvalidateTypes changed_flags) {
DCHECK_EQ(web_contents_.get(), source);
if (changed_flags & content::INVALIDATE_TYPE_URL) {
for (auto& observer : observers_)
observer.DisplayedUrlChanged(source->GetVisibleURL());
UpdateBrowserVisibleSecurityStateIfNecessary();
}
// TODO(crbug.com/1064582): INVALIDATE_TYPE_TITLE is called only when a title
// is set on the active navigation entry, but not when the active entry
// changes, so check INVALIDATE_TYPE_LOAD here as well. However this should
// be fixed and INVALIDATE_TYPE_LOAD should be removed.
if (changed_flags &
(content::INVALIDATE_TYPE_TITLE | content::INVALIDATE_TYPE_LOAD)) {
std::u16string title = web_contents_->GetTitle();
if (title_ != title) {
title_ = title;
for (auto& observer : observers_)
observer.OnTitleUpdated(title);
}
}
}
content::JavaScriptDialogManager* TabImpl::GetJavaScriptDialogManager(
content::WebContents* web_contents) {
#if BUILDFLAG(IS_ANDROID)
return javascript_dialogs::TabModalDialogManager::FromWebContents(
web_contents);
#else
return nullptr;
#endif
}
#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<content::ColorChooser> TabImpl::OpenColorChooser(
content::WebContents* web_contents,
SkColor color,
const std::vector<blink::mojom::ColorSuggestionPtr>& suggestions) {
return std::make_unique<web_contents_delegate_android::ColorChooserAndroid>(
web_contents, color, suggestions);
}
#endif
void TabImpl::CreateSmsPrompt(content::RenderFrameHost* render_frame_host,
const std::vector<url::Origin>& origin_list,
const std::string& one_time_code,
base::OnceClosure on_confirm,
base::OnceClosure on_cancel) {
#if BUILDFLAG(IS_ANDROID)
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
sms::SmsInfoBar::Create(
web_contents,
infobars::ContentInfoBarManager::FromWebContents(web_contents),
origin_list, one_time_code, std::move(on_confirm), std::move(on_cancel));
#else
NOTREACHED();
#endif
}
void TabImpl::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
bool TabImpl::IsBackForwardCacheSupported() {
return true;
}
void TabImpl::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
#if BUILDFLAG(IS_ANDROID)
MediaStreamManager::FromWebContents(web_contents)
->RequestMediaAccessPermission(request, std::move(callback));
#else
std::move(callback).Run(blink::mojom::StreamDevicesSet(),
blink::mojom::MediaStreamRequestResult::NOT_SUPPORTED,
nullptr);
#endif
}
bool TabImpl::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
blink::PermissionType permission_type =
type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE
? blink::PermissionType::AUDIO_CAPTURE
: blink::PermissionType::VIDEO_CAPTURE;
// TODO(crbug.com/1321100): Remove `security_origin`.
if (render_frame_host->GetLastCommittedOrigin().GetURL() != security_origin) {
return false;
}
// It is OK to ignore `security_origin` because it will be calculated from
// `render_frame_host` and we always ignore `requesting_origin` for
// `AUDIO_CAPTURE` and `VIDEO_CAPTURE`.
// `render_frame_host->GetMainFrame()->GetLastCommittedOrigin()` will be used
// instead.
return render_frame_host->GetBrowserContext()
->GetPermissionController()
->GetPermissionStatusForCurrentDocument(permission_type,
render_frame_host) ==
blink::mojom::PermissionStatus::GRANTED;
}
void TabImpl::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
// TODO(crbug.com/1232147): support |options|.
if (is_fullscreen_) {
// Typically EnterFullscreenModeForTab() should not be called consecutively,
// but there may be corner cases with oopif that lead to multiple
// consecutive calls. Avoid notifying the delegate in this case.
return;
}
is_fullscreen_ = true;
if (!IsActive()) {
// Process the request the tab is made active.
enter_fullscreen_on_gained_active_ = true;
return;
}
EnterFullscreenImpl();
}
void TabImpl::ExitFullscreenModeForTab(content::WebContents* web_contents) {
weak_ptr_factory_for_fullscreen_exit_.InvalidateWeakPtrs();
is_fullscreen_ = false;
if (enter_fullscreen_on_gained_active_)
enter_fullscreen_on_gained_active_ = false;
else
fullscreen_delegate_->ExitFullscreen();
}
bool TabImpl::IsFullscreenForTabOrPending(
const content::WebContents* web_contents) {
return is_fullscreen_;
}
blink::mojom::DisplayMode TabImpl::GetDisplayMode(
const content::WebContents* web_contents) {
return is_fullscreen_ ? blink::mojom::DisplayMode::kFullscreen
: blink::mojom::DisplayMode::kBrowser;
}
void TabImpl::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
if (!new_tab_delegate_) {
*was_blocked = true;
return;
}
// At this point the |new_contents| is beyond the popup blocker, but we use
// the same logic for determining if the popup tracker needs to be attached.
if (source && blocked_content::ConsiderForPopupBlocking(disposition)) {
blocked_content::PopupTracker::CreateForWebContents(new_contents.get(),
source, disposition);
}
new_tab_delegate_->OnNewTab(browser_->CreateTab(std::move(new_contents)),
NewTabTypeFromWindowDisposition(disposition));
}
void TabImpl::CloseContents(content::WebContents* source) {
// The only time that |browser_| is null is during shutdown, and this callback
// shouldn't come in at that time.
DCHECK(browser_);
#if BUILDFLAG(IS_ANDROID)
JNIEnv* env = AttachCurrentThread();
Java_TabImpl_handleCloseFromWebContents(env, java_impl_);
// The above call resulted in the destruction of this; nothing to do but
// return.
#else
browser_->DestroyTab(this);
#endif
}
void TabImpl::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
GetFindTabHelper()->HandleFindReply(request_id, number_of_matches,
selection_rect, active_match_ordinal,
final_update);
}
#if BUILDFLAG(IS_ANDROID)
// FindMatchRectsReply and OnFindResultAvailable forward find-related results to
// the Java TabImpl. The find actions themselves are initiated directly from
// Java via FindInPageBridge.
void TabImpl::FindMatchRectsReply(content::WebContents* web_contents,
int version,
const std::vector<gfx::RectF>& rects,
const gfx::RectF& active_rect) {
JNIEnv* env = AttachCurrentThread();
// Create the details object.
ScopedJavaLocalRef<jobject> details_object =
Java_TabImpl_createFindMatchRectsDetails(
env, version, rects.size(),
ScopedJavaLocalRef<jobject>(Java_TabImpl_createRectF(
env, active_rect.x(), active_rect.y(), active_rect.right(),
active_rect.bottom())));
// Add the rects.
for (size_t i = 0; i < rects.size(); ++i) {
const gfx::RectF& rect = rects[i];
Java_TabImpl_setMatchRectByIndex(
env, details_object, i,
ScopedJavaLocalRef<jobject>(Java_TabImpl_createRectF(
env, rect.x(), rect.y(), rect.right(), rect.bottom())));
}
Java_TabImpl_onFindMatchRectsAvailable(env, java_impl_, details_object);
}
#endif
void TabImpl::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
#if BUILDFLAG(IS_ANDROID)
// If a renderer process is lost when the tab is not visible, indicate to the
// WebContents that it should automatically reload the next time it becomes
// visible.
JNIEnv* env = AttachCurrentThread();
if (Java_TabImpl_willAutomaticallyReloadAfterCrashImpl(env, java_impl_))
web_contents()->GetController().SetNeedsReload();
#endif
for (auto& observer : observers_)
observer.OnRenderProcessGone();
}
void TabImpl::OnFindResultAvailable(content::WebContents* web_contents) {
#if BUILDFLAG(IS_ANDROID)
const find_in_page::FindNotificationDetails& find_result =
GetFindTabHelper()->find_result();
JNIEnv* env = AttachCurrentThread();
Java_TabImpl_onFindResultAvailable(
env, java_impl_, find_result.number_of_matches(),
find_result.active_match_ordinal(), find_result.final_update());
#endif
}
void TabImpl::DidChangeVisibleSecurityState() {
UpdateBrowserVisibleSecurityStateIfNecessary();
}
void TabImpl::UpdateBrowserVisibleSecurityStateIfNecessary() {
if (browser_ && browser_->GetActiveTab() == this)
browser_->VisibleSecurityStateOfActiveTabChanged();
}
void TabImpl::OnExitFullscreen() {
// If |processing_enter_fullscreen_| is true, it means the callback is being
// called while processing EnterFullscreenModeForTab(). WebContents doesn't
// deal well with this. FATAL as Android generally doesn't run with DCHECKs.
LOG_IF(FATAL, processing_enter_fullscreen_)
<< "exiting fullscreen while entering fullscreen is not supported";
web_contents_->ExitFullscreen(/* will_cause_resize */ false);
}
void TabImpl::UpdateRendererPrefs(bool should_sync_prefs) {
blink::RendererPreferences* prefs = web_contents_->GetMutableRendererPrefs();
content::UpdateFontRendererPreferencesFromSystemSettings(prefs);
prefs->accept_languages = i18n::GetAcceptLangs();
if (should_sync_prefs)
web_contents_->SyncRendererPrefs();
}
#if BUILDFLAG(IS_ANDROID)
void TabImpl::InitializeAutofillForTests() {
InitializeAutofillDriver();
}
void TabImpl::InitializeAutofillDriver() {
content::WebContents* web_contents = web_contents_.get();
DCHECK(
!autofill::ContentAutofillDriverFactory::FromWebContents(web_contents));
DCHECK(autofill::AutofillProvider::FromWebContents(web_contents));
AutofillClientImpl::CreateForWebContents(web_contents);
}
#endif // BUILDFLAG(IS_ANDROID)
find_in_page::FindTabHelper* TabImpl::GetFindTabHelper() {
return find_in_page::FindTabHelper::FromWebContents(web_contents_.get());
}
// static
sessions::SessionTabHelperDelegate* TabImpl::GetSessionServiceTabHelperDelegate(
content::WebContents* web_contents) {
TabImpl* tab = FromWebContents(web_contents);
return (tab && tab->browser_) ? tab->browser_->browser_persister() : nullptr;
}
bool TabImpl::SetDataInternal(const std::map<std::string, std::string>& data) {
int total_size = 0;
for (const auto& kv : data)
total_size += kv.first.size() + kv.second.size();
if (total_size > kMaxDataSize)
return false;
data_ = data;
for (auto& observer : data_observers_)
observer.OnDataChanged(this, data_);
return true;
}
void TabImpl::EnterFullscreenImpl() {
// This ensures the existing callback is ignored.
weak_ptr_factory_for_fullscreen_exit_.InvalidateWeakPtrs();
auto exit_fullscreen_closure =
base::BindOnce(&TabImpl::OnExitFullscreen,
weak_ptr_factory_for_fullscreen_exit_.GetWeakPtr());
base::AutoReset<bool> reset(&processing_enter_fullscreen_, true);
fullscreen_delegate_->EnterFullscreen(std::move(exit_fullscreen_closure));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/tab_impl.cc | C++ | unknown | 45,944 |
// 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_TAB_IMPL_H_
#define WEBLAYER_BROWSER_TAB_IMPL_H_
#include <memory>
#include <set>
#include <string>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/scoped_observation_traits.h"
#include "build/build_config.h"
#include "components/find_in_page/find_result_observer.h"
#include "content/public/browser/color_chooser.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "weblayer/browser/i18n_util.h"
#include "weblayer/public/tab.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/scoped_java_ref.h"
#endif
namespace blink {
namespace web_pref {
struct WebPreferences;
}
} // namespace blink
namespace content {
class RenderWidgetHostView;
class WebContents;
struct ContextMenuParams;
} // namespace content
namespace gfx {
class Rect;
class Size;
} // namespace gfx
namespace sessions {
class SessionTabHelperDelegate;
}
namespace weblayer {
class BrowserImpl;
class FullscreenDelegate;
class NavigationControllerImpl;
class NewTabDelegate;
class ProfileImpl;
class TabImpl : public Tab,
public content::WebContentsDelegate,
public content::WebContentsObserver,
public find_in_page::FindResultObserver {
public:
enum class ScreenShotErrors {
kNone = 0,
kScaleOutOfRange,
kTabNotActive,
kWebContentsNotVisible,
kNoSurface,
kNoRenderWidgetHostView,
kNoWindowAndroid,
kEmptyViewport,
kHiddenByControls,
kScaledToEmpty,
kCaptureFailed,
kBitmapAllocationFailed,
};
class DataObserver {
public:
// Called when SetData() is called on |tab|.
virtual void OnDataChanged(
TabImpl* tab,
const std::map<std::string, std::string>& data) = 0;
};
// TODO(sky): investigate a better way to not have so many ifdefs.
#if BUILDFLAG(IS_ANDROID)
TabImpl(ProfileImpl* profile,
const base::android::JavaParamRef<jobject>& java_impl,
std::unique_ptr<content::WebContents> web_contents);
#endif
explicit TabImpl(ProfileImpl* profile,
std::unique_ptr<content::WebContents> web_contents,
const std::string& guid = std::string());
TabImpl(const TabImpl&) = delete;
TabImpl& operator=(const TabImpl&) = delete;
~TabImpl() override;
// Returns the TabImpl from the specified WebContents (which may be null), or
// null if |web_contents| was not created by a TabImpl.
static TabImpl* FromWebContents(content::WebContents* web_contents);
static std::set<TabImpl*> GetAllTabImpl();
ProfileImpl* profile() { return profile_; }
void set_browser(BrowserImpl* browser) { browser_ = browser; }
BrowserImpl* browser() { return browser_; }
content::WebContents* web_contents() const { return web_contents_.get(); }
bool has_new_tab_delegate() const { return new_tab_delegate_ != nullptr; }
NewTabDelegate* new_tab_delegate() const { return new_tab_delegate_; }
// Called from Browser when this Tab is gaining/losing active status.
void OnGainedActive();
void OnLosingActive();
bool IsActive();
void ShowContextMenu(const content::ContextMenuParams& params);
#if BUILDFLAG(IS_ANDROID)
base::android::ScopedJavaGlobalRef<jobject> GetJavaTab() {
return java_impl_;
}
bool desktop_user_agent_enabled() { return desktop_user_agent_enabled_; }
// Call this method to disable integration with the system-level Autofill
// infrastructure. Useful in conjunction with InitializeAutofillForTests().
// Should be called early in the lifetime of WebLayer, and in
// particular, must be called before the TabImpl is attached to the browser
// on the Java side to have the desired effect.
static void DisableAutofillSystemIntegrationForTesting();
base::android::ScopedJavaLocalRef<jobject> GetWebContents(JNIEnv* env);
void ExecuteScript(JNIEnv* env,
const base::android::JavaParamRef<jstring>& script,
bool use_separate_isolate,
const base::android::JavaParamRef<jobject>& callback);
void SetJavaImpl(JNIEnv* env,
const base::android::JavaParamRef<jobject>& impl);
// Invoked every time that the Java-side AutofillProvider instance is created,
// the native side autofill might have been initialized in the case that
// Android context is switched.
void InitializeAutofillIfNecessary(JNIEnv* env);
base::android::ScopedJavaLocalRef<jstring> GetGuid(JNIEnv* env);
void CaptureScreenShot(
JNIEnv* env,
jfloat scale,
const base::android::JavaParamRef<jobject>& value_callback);
jboolean SetData(JNIEnv* env,
const base::android::JavaParamRef<jobjectArray>& data);
base::android::ScopedJavaLocalRef<jobjectArray> GetData(JNIEnv* env);
jboolean CanTranslate(JNIEnv* env);
void ShowTranslateUi(JNIEnv* env);
void RemoveTabFromBrowserBeforeDestroying(JNIEnv* env);
void SetTranslateTargetLanguage(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& translate_target_lang);
void SetDesktopUserAgentEnabled(JNIEnv* env, jboolean enable);
jboolean IsDesktopUserAgentEnabled(JNIEnv* env);
void Download(JNIEnv* env, jlong native_context_menu_params);
#endif
ErrorPageDelegate* error_page_delegate() { return error_page_delegate_; }
void AddDataObserver(DataObserver* observer);
void RemoveDataObserver(DataObserver* observer);
GoogleAccountsDelegate* google_accounts_delegate() {
return google_accounts_delegate_;
}
// Tab:
Browser* GetBrowser() override;
void SetErrorPageDelegate(ErrorPageDelegate* delegate) override;
void SetFullscreenDelegate(FullscreenDelegate* delegate) override;
void SetNewTabDelegate(NewTabDelegate* delegate) override;
void SetGoogleAccountsDelegate(GoogleAccountsDelegate* delegate) override;
void AddObserver(TabObserver* observer) override;
void RemoveObserver(TabObserver* observer) override;
NavigationController* GetNavigationController() override;
void ExecuteScript(const std::u16string& script,
bool use_separate_isolate,
JavaScriptResultCallback callback) override;
const std::string& GetGuid() override;
void SetData(const std::map<std::string, std::string>& data) override;
const std::map<std::string, std::string>& GetData() override;
std::unique_ptr<FaviconFetcher> CreateFaviconFetcher(
FaviconFetcherDelegate* delegate) override;
void SetTranslateTargetLanguage(
const std::string& translate_target_lang) override;
#if !BUILDFLAG(IS_ANDROID)
void AttachToView(views::WebView* web_view) override;
#endif
void WebPreferencesChanged();
void SetWebPreferences(blink::web_pref::WebPreferences* prefs);
// Executes |script| with a user gesture.
void ExecuteScriptWithUserGestureForTests(const std::u16string& script);
#if BUILDFLAG(IS_ANDROID)
// Initializes the autofill system for tests.
void InitializeAutofillForTests();
#endif // BUILDFLAG(IS_ANDROID)
private:
// content::WebContentsDelegate:
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;
void ShowRepostFormWarningDialog(content::WebContents* source) override;
void NavigationStateChanged(content::WebContents* source,
content::InvalidateTypes changed_flags) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* web_contents) override;
#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<content::ColorChooser> OpenColorChooser(
content::WebContents* web_contents,
SkColor color,
const std::vector<blink::mojom::ColorSuggestionPtr>& suggestions)
override;
#endif
void RunFileChooser(content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) override;
void CreateSmsPrompt(content::RenderFrameHost*,
const std::vector<url::Origin>&,
const std::string& one_time_code,
base::OnceClosure on_confirm,
base::OnceClosure on_cancel) override;
bool IsBackForwardCacheSupported() override;
void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) override;
bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) override;
void EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) override;
void ExitFullscreenModeForTab(content::WebContents* web_contents) override;
bool IsFullscreenForTabOrPending(
const content::WebContents* web_contents) override;
blink::mojom::DisplayMode GetDisplayMode(
const content::WebContents* web_contents) override;
void AddNewContents(content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) override;
void CloseContents(content::WebContents* source) override;
void FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) override;
#if BUILDFLAG(IS_ANDROID)
void FindMatchRectsReply(content::WebContents* web_contents,
int version,
const std::vector<gfx::RectF>& rects,
const gfx::RectF& active_rect) override;
// Pointer arguments are outputs. Check the preconditions for capturing a
// screenshot and either set all outputs, or return an error code, in which
// case the state of output arguments is undefined.
ScreenShotErrors PrepareForCaptureScreenShot(
float scale,
content::RenderWidgetHostView** rwhv,
gfx::Rect* src_rect,
gfx::Size* output_size);
#endif
// content::WebContentsObserver:
void PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) override;
void DidChangeVisibleSecurityState() override;
// find_in_page::FindResultObserver:
void OnFindResultAvailable(content::WebContents* web_contents) override;
// Called from closure supplied to delegate to exit fullscreen.
void OnExitFullscreen();
void UpdateRendererPrefs(bool should_sync_prefs);
// Returns the FindTabHelper for the page, or null if none exists.
find_in_page::FindTabHelper* GetFindTabHelper();
static sessions::SessionTabHelperDelegate* GetSessionServiceTabHelperDelegate(
content::WebContents* web_contents);
#if BUILDFLAG(IS_ANDROID)
void InitializeAutofillDriver();
#endif
void UpdateBrowserVisibleSecurityStateIfNecessary();
bool SetDataInternal(const std::map<std::string, std::string>& data);
void EnterFullscreenImpl();
raw_ptr<BrowserImpl> browser_ = nullptr;
raw_ptr<ErrorPageDelegate> error_page_delegate_ = nullptr;
raw_ptr<FullscreenDelegate> fullscreen_delegate_ = nullptr;
raw_ptr<NewTabDelegate> new_tab_delegate_ = nullptr;
raw_ptr<GoogleAccountsDelegate> google_accounts_delegate_ = nullptr;
raw_ptr<ProfileImpl> profile_;
std::unique_ptr<content::WebContents> web_contents_;
std::unique_ptr<NavigationControllerImpl> navigation_controller_;
base::ObserverList<TabObserver>::Unchecked observers_;
base::CallbackListSubscription locale_change_subscription_;
#if BUILDFLAG(IS_ANDROID)
base::android::ScopedJavaGlobalRef<jobject> java_impl_;
bool desktop_user_agent_enabled_ = false;
#endif
bool is_fullscreen_ = false;
// Set to true doing EnterFullscreenModeForTab().
bool processing_enter_fullscreen_ = false;
// If true, the fullscreen delegate is called when the tab gains active.
bool enter_fullscreen_on_gained_active_ = false;
const std::string guid_;
std::map<std::string, std::string> data_;
base::ObserverList<DataObserver>::Unchecked data_observers_;
std::u16string title_;
base::WeakPtrFactory<TabImpl> weak_ptr_factory_for_fullscreen_exit_{this};
};
} // namespace weblayer
namespace base {
template <>
struct ScopedObservationTraits<weblayer::TabImpl,
weblayer::TabImpl::DataObserver> {
static void AddObserver(weblayer::TabImpl* source,
weblayer::TabImpl::DataObserver* observer) {
source->AddDataObserver(observer);
}
static void RemoveObserver(weblayer::TabImpl* source,
weblayer::TabImpl::DataObserver* observer) {
source->RemoveDataObserver(observer);
}
};
} // namespace base
#endif // WEBLAYER_BROWSER_TAB_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/tab_impl.h | C++ | unknown | 13,458 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/test/test_infobar.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar_delegate.h"
#include "weblayer/browser/java/test_jni/TestInfoBar_jni.h"
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
class TestInfoBarDelegate : public infobars::InfoBarDelegate {
public:
TestInfoBarDelegate() = default;
~TestInfoBarDelegate() override = default;
infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override {
return InfoBarDelegate::InfoBarIdentifier::TEST_INFOBAR;
}
};
TestInfoBar::TestInfoBar(std::unique_ptr<TestInfoBarDelegate> delegate)
: infobars::InfoBarAndroid(std::move(delegate)) {}
TestInfoBar::~TestInfoBar() = default;
void TestInfoBar::ProcessButton(int action) {}
ScopedJavaLocalRef<jobject> TestInfoBar::CreateRenderInfoBar(
JNIEnv* env,
const ResourceIdMapper& resource_id_mapper) {
return Java_TestInfoBar_create(env);
}
// static
void TestInfoBar::Show(content::WebContents* web_contents) {
infobars::ContentInfoBarManager* manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
manager->AddInfoBar(
std::make_unique<TestInfoBar>(std::make_unique<TestInfoBarDelegate>()));
}
static void JNI_TestInfoBar_Show(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& j_web_contents) {
auto* web_contents =
content::WebContents::FromJavaWebContents(j_web_contents);
TestInfoBar::Show(web_contents);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/test/test_infobar.cc | C++ | unknown | 1,794 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_TEST_TEST_INFOBAR_H_
#define WEBLAYER_BROWSER_TEST_TEST_INFOBAR_H_
#include "base/android/jni_android.h"
#include "base/android/scoped_java_ref.h"
#include "components/infobars/android/infobar_android.h"
#include "components/infobars/core/infobar_delegate.h"
#include "content/public/browser/web_contents.h"
namespace weblayer {
class TestInfoBarDelegate;
// A test infobar.
class TestInfoBar : public infobars::InfoBarAndroid {
public:
explicit TestInfoBar(std::unique_ptr<TestInfoBarDelegate> delegate);
~TestInfoBar() override;
TestInfoBar(const TestInfoBar&) = delete;
TestInfoBar& operator=(const TestInfoBar&) = delete;
static void Show(content::WebContents* web_contents);
protected:
infobars::InfoBarDelegate* GetDelegate();
// infobars::InfoBarAndroid overrides.
void ProcessButton(int action) override;
base::android::ScopedJavaLocalRef<jobject> CreateRenderInfoBar(
JNIEnv* env,
const ResourceIdMapper& resource_id_mapper) override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_TEST_TEST_INFOBAR_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/test/test_infobar.h | C++ | unknown | 1,232 |
// 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/java/test_jni/TestWebLayerImpl_jni.h"
#include <utility>
#include "base/android/callback_android.h"
#include "base/android/jni_string.h"
#include "base/no_destructor.h"
#include "base/test/scoped_feature_list.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/download/public/background_service/features.h"
#include "components/translate/core/browser/translate_manager.h"
#include "content/public/test/browser_test_utils.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
using base::android::AttachCurrentThread;
using base::android::ScopedJavaGlobalRef;
namespace weblayer {
namespace {
void CheckMetadata(
std::unique_ptr<content::RenderFrameSubmissionObserver> observer,
int top_height,
int bottom_height,
const ScopedJavaGlobalRef<jobject>& runnable) {
const cc::RenderFrameMetadata& last_metadata =
observer->LastRenderFrameMetadata();
if (last_metadata.top_controls_height == top_height &&
last_metadata.bottom_controls_height == bottom_height) {
base::android::RunRunnableAndroid(runnable);
return;
}
auto* const observer_ptr = observer.get();
observer_ptr->NotifyOnNextMetadataChange(
base::BindOnce(&CheckMetadata, std::move(observer), top_height,
bottom_height, runnable));
}
} // namespace
static void JNI_TestWebLayerImpl_WaitForBrowserControlsMetadataState(
JNIEnv* env,
jlong tab_impl,
jint top_height,
jint bottom_height,
const base::android::JavaParamRef<jobject>& runnable) {
TabImpl* tab = reinterpret_cast<TabImpl*>(tab_impl);
auto observer = std::make_unique<content::RenderFrameSubmissionObserver>(
tab->web_contents());
CheckMetadata(std::move(observer), top_height, bottom_height,
ScopedJavaGlobalRef<jobject>(runnable));
}
static void JNI_TestWebLayerImpl_SetIgnoreMissingKeyForTranslateManager(
JNIEnv* env,
jboolean ignore) {
translate::TranslateManager::SetIgnoreMissingKeyForTesting(ignore);
}
static void JNI_TestWebLayerImpl_ExpediteDownloadService(JNIEnv* env) {
static base::NoDestructor<base::test::ScopedFeatureList> feature_list;
feature_list->InitAndEnableFeatureWithParameters(
download::kDownloadServiceFeature, {{"start_up_delay_ms", "0"}});
}
static void JNI_TestWebLayerImpl_GrantLocationPermission(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& jurl) {
GURL url(base::android::ConvertJavaStringToUTF8(env, jurl));
for (auto* profile : ProfileImpl::GetAllProfiles()) {
HostContentSettingsMapFactory::GetForBrowserContext(
profile->GetBrowserContext())
->SetContentSettingDefaultScope(
url, url, ContentSettingsType::GEOLOCATION, CONTENT_SETTING_ALLOW);
}
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/test/test_weblayer_impl.cc | C++ | unknown | 3,107 |
// 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 "build/build_config.h"
#include "components/infobars/android/infobar_android.h" // nogncheck
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar_manager.h" // nogncheck
#include "components/translate/content/browser/translate_waiter.h"
#include "components/translate/core/browser/language_state.h"
#include "components/translate/core/browser/translate_download_manager.h"
#include "components/translate/core/browser/translate_error_details.h"
#include "components/translate/core/browser/translate_manager.h"
#include "components/translate/core/common/language_detection_details.h"
#include "components/translate/core/common/translate_switches.h"
#include "content/public/browser/browser_context.h"
#include "net/base/mock_network_change_notifier.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/browser/translate_client_impl.h"
#include "weblayer/browser/translate_compact_infobar.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/android/browsertests_apk/translate_test_bridge.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/test_navigation_observer.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
static std::string kTestValidScript = R"(
var google = {};
google.translate = (function() {
return {
TranslateService: function() {
return {
isAvailable : function() {
return true;
},
restore : function() {
return;
},
getDetectedLanguage : function() {
return "fr";
},
translatePage : function(sourceLang, targetLang,
onTranslateProgress) {
var error = (sourceLang == 'auto') ? true : false;
onTranslateProgress(100, true, error);
}
};
}
};
})();
cr.googleTranslate.onTranslateElementLoad();)";
static std::string kTestScriptInitializationError = R"(
var google = {};
google.translate = (function() {
return {
TranslateService: function() {
return error;
}
};
})();
cr.googleTranslate.onTranslateElementLoad();)";
static std::string kTestScriptTimeout = R"(
var google = {};
google.translate = (function() {
return {
TranslateService: function() {
return {
isAvailable : function() {
return false;
},
};
}
};
})();
cr.googleTranslate.onTranslateElementLoad();)";
TranslateClientImpl* GetTranslateClient(Shell* shell) {
return TranslateClientImpl::FromWebContents(
static_cast<TabImpl*>(shell->tab())->web_contents());
}
std::unique_ptr<translate::TranslateWaiter> CreateTranslateWaiter(
Shell* shell,
translate::TranslateWaiter::WaitEvent wait_event) {
return std::make_unique<translate::TranslateWaiter>(
GetTranslateClient(shell)->translate_driver(), wait_event);
}
} // namespace
class TestInfoBarManagerObserver : public infobars::InfoBarManager::Observer {
public:
TestInfoBarManagerObserver() = default;
~TestInfoBarManagerObserver() override = default;
void OnInfoBarAdded(infobars::InfoBar* infobar) override {
if (on_infobar_added_callback_)
std::move(on_infobar_added_callback_).Run();
}
void OnInfoBarRemoved(infobars::InfoBar* infobar, bool animate) override {
if (on_infobar_removed_callback_)
std::move(on_infobar_removed_callback_).Run();
}
void set_on_infobar_added_callback(base::OnceClosure callback) {
on_infobar_added_callback_ = std::move(callback);
}
void set_on_infobar_removed_callback(base::OnceClosure callback) {
on_infobar_removed_callback_ = std::move(callback);
}
private:
base::OnceClosure on_infobar_added_callback_;
base::OnceClosure on_infobar_removed_callback_;
};
class TranslateBrowserTest : public WebLayerBrowserTest {
public:
TranslateBrowserTest() {
error_subscription_ =
translate::TranslateManager::RegisterTranslateErrorCallback(
base::BindRepeating(&TranslateBrowserTest::OnTranslateError,
base::Unretained(this)));
}
~TranslateBrowserTest() override = default;
void SetUpOnMainThread() override {
embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
&TranslateBrowserTest::HandleRequest, base::Unretained(this)));
embedded_test_server()->StartAcceptingConnections();
// Translation will not be offered if NetworkChangeNotifier reports that the
// app is offline, which can occur on bots. Prevent this.
// NOTE: MockNetworkChangeNotifier cannot be instantiated earlier than this
// due to its dependence on browser state having been created.
mock_network_change_notifier_ =
std::make_unique<net::test::ScopedMockNetworkChangeNotifier>();
mock_network_change_notifier_->mock_network_change_notifier()
->SetConnectionType(net::NetworkChangeNotifier::CONNECTION_WIFI);
// By default, translation is not offered if the Google API key is not set.
GetTranslateClient(shell())
->GetTranslateManager()
->SetIgnoreMissingKeyForTesting(true);
GetTranslateClient(shell())->GetTranslatePrefs()->ResetToDefaults();
}
void TearDownOnMainThread() override {
language_determination_waiter_.reset();
page_translation_waiter_.reset();
mock_network_change_notifier_.reset();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
command_line->AppendSwitchASCII(
translate::switches::kTranslateScriptURL,
embedded_test_server()->GetURL("/mock_translate_script.js").spec());
}
protected:
translate::TranslateErrors GetPageTranslatedResult() { return error_type_; }
void SetTranslateScript(const std::string& script) { script_ = script; }
void ResetLanguageDeterminationWaiter() {
language_determination_waiter_ = CreateTranslateWaiter(
shell(), translate::TranslateWaiter::WaitEvent::kLanguageDetermined);
}
void ResetPageTranslationWaiter() {
page_translation_waiter_ = CreateTranslateWaiter(
shell(), translate::TranslateWaiter::WaitEvent::kPageTranslated);
}
std::unique_ptr<translate::TranslateWaiter> language_determination_waiter_;
std::unique_ptr<translate::TranslateWaiter> page_translation_waiter_;
private:
std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
const net::test_server::HttpRequest& request) {
if (request.GetURL().path() != "/mock_translate_script.js")
return nullptr;
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(net::HTTP_OK);
http_response->set_content(script_);
http_response->set_content_type("text/javascript");
return std::move(http_response);
}
void OnTranslateError(const translate::TranslateErrorDetails& details) {
error_type_ = details.error;
}
std::unique_ptr<net::test::ScopedMockNetworkChangeNotifier>
mock_network_change_notifier_;
translate::TranslateErrors error_type_ = translate::TranslateErrors::NONE;
base::CallbackListSubscription error_subscription_;
std::string script_;
};
// Tests that the CLD (Compact Language Detection) works properly.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, PageLanguageDetection) {
TranslateClientImpl* translate_client = GetTranslateClient(shell());
// Go to a page in English.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/english_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("en", translate_client->GetLanguageState().source_language());
// Now navigate to a page in French.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
}
// Tests that firing the page language determined notification for a
// failed-but-committed navigation does not cause a crash. Regression test for
// crbug.com/1262047.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest,
PageLanguageDetectionInFailedButCommittedNavigation) {
TranslateClientImpl* translate_client = GetTranslateClient(shell());
auto url = embedded_test_server()->GetURL("/empty404.html");
TestNavigationObserver navigation_failed_observer(
url, TestNavigationObserver::NavigationEvent::kFailure, shell());
shell()->tab()->GetNavigationController()->Navigate(url);
navigation_failed_observer.Wait();
// Fire the OnLanguageDetermined() notification manually to mimic the
// production flow in which this is crashing (crbug.com/1262047).
// TODO(blundell): Replace this manual triggering by doing a
// failed-but-committed navigation that results in the OnLanguageDetermined()
// notification firing once I determine which navigations result in that flow
// in production.
translate::LanguageDetectionDetails language_details;
language_details.adopted_language = "en";
translate_client->OnLanguageDetermined(language_details);
}
// Test that the translation was successful.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, PageTranslationSuccess) {
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
// Navigate to a page in French.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// Translate the page through TranslateManager.
ResetPageTranslationWaiter();
translate::TranslateManager* manager =
translate_client->GetTranslateManager();
manager->TranslatePage(translate_client->GetLanguageState().source_language(),
"en", true);
page_translation_waiter_->Wait();
EXPECT_FALSE(translate_client->GetLanguageState().translation_error());
EXPECT_EQ(translate::TranslateErrors::NONE, GetPageTranslatedResult());
}
class IncognitoTranslateBrowserTest : public TranslateBrowserTest {
public:
IncognitoTranslateBrowserTest() { SetShellStartsInIncognitoMode(); }
};
// Test that the translation infrastructure is set up properly when the user is
// in incognito mode.
IN_PROC_BROWSER_TEST_F(IncognitoTranslateBrowserTest,
DISABLED_PageTranslationSuccess_IncognitoMode) {
ASSERT_TRUE(GetProfile()->GetBrowserContext()->IsOffTheRecord());
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
// Navigate to a page in French.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// Translate the page through TranslateManager.
ResetPageTranslationWaiter();
translate::TranslateManager* manager =
translate_client->GetTranslateManager();
manager->TranslatePage(translate_client->GetLanguageState().source_language(),
"en", true);
page_translation_waiter_->Wait();
EXPECT_FALSE(translate_client->GetLanguageState().translation_error());
EXPECT_EQ(translate::TranslateErrors::NONE, GetPageTranslatedResult());
}
// Test if there was an error during translation.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, PageTranslationError) {
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
// Navigate to a empty page to result in the model returning "und".
// An "und" result will result in "auto" as the source language
// in the translate script.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/clipboard.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("und", translate_client->GetLanguageState().source_language());
// Translate the page through TranslateManager.
ResetPageTranslationWaiter();
translate::TranslateManager* manager =
translate_client->GetTranslateManager();
manager->TranslatePage(translate_client->GetLanguageState().source_language(),
"en", true);
page_translation_waiter_->Wait();
EXPECT_TRUE(translate_client->GetLanguageState().translation_error());
EXPECT_EQ(translate::TranslateErrors::TRANSLATION_ERROR,
GetPageTranslatedResult());
}
// Test if there was an error during translate library initialization.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest,
PageTranslationInitializationError) {
SetTranslateScript(kTestScriptInitializationError);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
// Navigate to a page in French.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// Translate the page through TranslateManager.
ResetPageTranslationWaiter();
translate::TranslateManager* manager =
translate_client->GetTranslateManager();
manager->TranslatePage(translate_client->GetLanguageState().source_language(),
"en", true);
page_translation_waiter_->Wait();
EXPECT_TRUE(translate_client->GetLanguageState().translation_error());
EXPECT_EQ(translate::TranslateErrors::INITIALIZATION_ERROR,
GetPageTranslatedResult());
}
// Test the checks translate lib never gets ready and throws timeout.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, PageTranslationTimeoutError) {
SetTranslateScript(kTestScriptTimeout);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
// Navigate to a page in French.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// Translate the page through TranslateManager.
ResetPageTranslationWaiter();
translate::TranslateManager* manager =
translate_client->GetTranslateManager();
manager->TranslatePage(translate_client->GetLanguageState().source_language(),
"en", true);
page_translation_waiter_->Wait();
EXPECT_TRUE(translate_client->GetLanguageState().translation_error());
EXPECT_EQ(translate::TranslateErrors::TRANSLATION_TIMEOUT,
GetPageTranslatedResult());
}
// Test that autotranslation kicks in if configured via prefs.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, Autotranslation) {
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
// Before browsing, set autotranslate from French to Chinese.
translate_client->GetTranslatePrefs()->AddLanguagePairToAlwaysTranslateList(
"fr", "zh-CN");
// Navigate to a page in French.
ResetLanguageDeterminationWaiter();
ResetPageTranslationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// Autotranslation should kick in.
page_translation_waiter_->Wait();
EXPECT_FALSE(translate_client->GetLanguageState().translation_error());
EXPECT_EQ(translate::TranslateErrors::NONE, GetPageTranslatedResult());
EXPECT_EQ("zh-CN", translate_client->GetLanguageState().current_language());
}
// Test that the translation infobar is presented when visiting a page with a
// translation opportunity and removed when navigating away.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, TranslateInfoBarPresentation) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
EXPECT_EQ(0u, infobar_manager->infobar_count());
// Navigate to a page in French.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// The translate infobar should be added.
run_loop.Run();
EXPECT_EQ(1u, infobar_manager->infobar_count());
auto* infobar =
static_cast<infobars::InfoBarAndroid*>(infobar_manager->infobar_at(0));
EXPECT_TRUE(infobar->HasSetJavaInfoBar());
base::RunLoop run_loop2;
infobar_observer.set_on_infobar_removed_callback(run_loop2.QuitClosure());
NavigateAndWaitForCompletion(GURL("about:blank"), shell());
// The translate infobar should be removed.
run_loop2.Run();
EXPECT_EQ(0u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Test that the translation infobar is not presented when visiting a page with
// a translation opportunity but where the page has specified that it should not
// be translated.
IN_PROC_BROWSER_TEST_F(
TranslateBrowserTest,
TranslateInfoBarNotPresentedWhenPageSpecifiesNoTranslate) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
// Navigate to a page in French.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page_no_translate.html")),
shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// NOTE: There is no notification to wait for the event of the infobar not
// showing. However, in practice the infobar is added synchronously, so if it
// were to be shown, this check would fail.
EXPECT_EQ(0u, infobar_manager->infobar_count());
}
// Test that the translation can be successfully initiated via infobar.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest, TranslationViaInfoBar) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
// Navigate to a page in French and wait for the infobar to be added.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
run_loop.Run();
// Select the target language via the Java infobar and ensure that translation
// occurs.
ResetPageTranslationWaiter();
auto* infobar =
static_cast<TranslateCompactInfoBar*>(infobar_manager->infobar_at(0));
TranslateTestBridge::SelectButton(
infobar, infobars::InfoBarAndroid::ActionType::ACTION_TRANSLATE);
page_translation_waiter_->Wait();
EXPECT_FALSE(translate_client->GetLanguageState().translation_error());
EXPECT_EQ(translate::TranslateErrors::NONE, GetPageTranslatedResult());
// The translate infobar should still be present.
EXPECT_EQ(1u, infobar_manager->infobar_count());
// NOTE: The notification that the translate state of the page changed can
// occur synchronously once reversion is initiated, so it's necessary to start
// listening for that notification prior to initiating the reversion.
auto translate_reversion_waiter = CreateTranslateWaiter(
shell(), translate::TranslateWaiter::WaitEvent::kIsPageTranslatedChanged);
// Revert to the source language via the Java infobar and ensure that the
// translation is undone.
TranslateTestBridge::SelectButton(
infobar,
infobars::InfoBarAndroid::ActionType::ACTION_TRANSLATE_SHOW_ORIGINAL);
translate_reversion_waiter->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().current_language());
// The translate infobar should still be present.
EXPECT_EQ(1u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Test that translation occurs when a target language is set.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest,
TranslationViaPredefinedTargetLanguage) {
auto* tab = static_cast<TabImpl*>(shell()->tab());
auto* web_contents = tab->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
tab->SetTranslateTargetLanguage("ru");
// Navigate to a page in French and wait for the infobar to be added and
// autotranslation to occur.
ResetPageTranslationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
run_loop.Run();
page_translation_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
EXPECT_FALSE(translate_client->GetLanguageState().translation_error());
EXPECT_EQ(translate::TranslateErrors::NONE, GetPageTranslatedResult());
EXPECT_EQ("ru", translate_client->GetLanguageState().current_language());
// The translate infobar should still be present.
EXPECT_EQ(1u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Test that the infobar appears on pages in the user's locale iff a target
// language is set.
IN_PROC_BROWSER_TEST_F(
TranslateBrowserTest,
InfoBarAppearsForDefaultLanguageWhenPredefinedTargetLanguageIsSet) {
auto* tab = static_cast<TabImpl*>(shell()->tab());
auto* web_contents = tab->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
// Navigate to a page in English: the infobar should not appear.
ResetPageTranslationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/english_page.html")), shell());
// NOTE: There is no notification to wait for for the event of the infobar not
// showing. However, in practice the infobar is added synchronously, so if it
// were to be shown, this check would fail.
EXPECT_EQ(0u, infobar_manager->infobar_count());
// Set a target language, navigate again, and verify that the infobar now
// appears.
tab->SetTranslateTargetLanguage("ru");
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/english_page.html")), shell());
run_loop.Run();
EXPECT_EQ(1u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Test that when a predefined target language is set, the infobar does not
// appear on pages in that language.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest,
InfoBarDoesNotAppearForPageInPredefinedTargetLanguage) {
auto* tab = static_cast<TabImpl*>(shell()->tab());
auto* web_contents = tab->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
// Navigate to a page in French: the infobar should appear.
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
run_loop.Run();
EXPECT_EQ(1u, infobar_manager->infobar_count());
// Set the target language to French.
tab->SetTranslateTargetLanguage("fr");
// Navigate again to a page in French: the infobar should not appear.
ResetPageTranslationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
// NOTE: There is no notification to wait for for the event of the infobar not
// showing. However, in practice the infobar is added synchronously, so if it
// were to be shown, this check would fail.
EXPECT_EQ(0u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Test that the translation infobar stays present when the "never translate
// language" item is clicked. Note that this behavior is intentionally different
// from that of Chrome, where the infobar is removed in this case and a snackbar
// is shown. As WebLayer has no snackbars, the UX decision was to simply leave
// the infobar open to allow the user to revert the decision if desired.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest,
TranslateInfoBarNeverTranslateLanguage) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
// Navigate to a page in French and wait for the infobar to be added.
ResetLanguageDeterminationWaiter();
EXPECT_EQ(0u, infobar_manager->infobar_count());
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
run_loop.Run();
auto* infobar =
static_cast<TranslateCompactInfoBar*>(infobar_manager->infobar_at(0));
TranslateTestBridge::ClickOverflowMenuItem(
infobar,
TranslateTestBridge::OverflowMenuItemId::NEVER_TRANSLATE_LANGUAGE);
// The translate infobar should still be present.
EXPECT_EQ(1u, infobar_manager->infobar_count());
// However, the infobar should not be shown on a new navigation to a page in
// French.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page2.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// NOTE: There is no notification to wait for for the event of the infobar not
// showing. However, in practice the infobar is added synchronously, so if it
// were to be shown, this check would fail.
EXPECT_EQ(0u, infobar_manager->infobar_count());
// The infobar *should* be shown on a navigation to this site if the page's
// language is detected as something other than French.
base::RunLoop run_loop2;
infobar_observer.set_on_infobar_added_callback(run_loop2.QuitClosure());
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/german_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("de", translate_client->GetLanguageState().source_language());
run_loop2.Run();
EXPECT_EQ(1u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Test that the infobar shows when a predefined target language is set even if
// the source language is in the "never translate" set.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest,
PredefinedTargetLanguageOverridesLanguageBlocklist) {
auto* tab = static_cast<TabImpl*>(shell()->tab());
auto* web_contents = tab->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
tab->SetTranslateTargetLanguage("ru");
// Navigate to a page in French and wait for the infobar to be added.
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
run_loop.Run();
EXPECT_EQ(1u, infobar_manager->infobar_count());
auto* infobar =
static_cast<TranslateCompactInfoBar*>(infobar_manager->infobar_at(0));
TranslateTestBridge::ClickOverflowMenuItem(
infobar,
TranslateTestBridge::OverflowMenuItemId::NEVER_TRANSLATE_LANGUAGE);
// Since a predefined target language is set, the infobar should still be
// shown on a new navigation to a page in French even though it's blocklisted.
ResetLanguageDeterminationWaiter();
base::RunLoop run_loop2;
infobar_observer.set_on_infobar_added_callback(run_loop2.QuitClosure());
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page2.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
run_loop2.Run();
EXPECT_EQ(1u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Test that the translation infobar stays present when the "never translate
// site" item is clicked. Note that this behavior is intentionally different
// from that of Chrome, where the infobar is removed in this case and a snackbar
// is shown. As WebLayer has no snackbars, the UX decision was to simply leave
// the infobar open to allow the user to revert the decision if desired.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest,
TranslateInfoBarNeverTranslateSite) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
// Navigate to a page in French and wait for the infobar to be added.
ResetLanguageDeterminationWaiter();
EXPECT_EQ(0u, infobar_manager->infobar_count());
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
run_loop.Run();
auto* infobar =
static_cast<TranslateCompactInfoBar*>(infobar_manager->infobar_at(0));
TranslateTestBridge::ClickOverflowMenuItem(
infobar, TranslateTestBridge::OverflowMenuItemId::NEVER_TRANSLATE_SITE);
// The translate infobar should still be present.
EXPECT_EQ(1u, infobar_manager->infobar_count());
// However, the infobar should not be shown on a new navigation to this site,
// independent of the detected language.
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page2.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// NOTE: There is no notification to wait for for the event of the infobar not
// showing. However, in practice the infobar is added synchronously, so if it
// were to be shown, this check would fail.
EXPECT_EQ(0u, infobar_manager->infobar_count());
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/german_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("de", translate_client->GetLanguageState().source_language());
EXPECT_EQ(0u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Test that the infobar does not show when a predefined target language is set
// and the user selects to never translate the site.
IN_PROC_BROWSER_TEST_F(TranslateBrowserTest,
PredefinedTargetLanguageDoesNotOverrideSiteBlocklist) {
auto* tab = static_cast<TabImpl*>(shell()->tab());
auto* web_contents = tab->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
tab->SetTranslateTargetLanguage("ru");
// Navigate and wait for the infobar to be added.
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
run_loop.Run();
EXPECT_EQ(1u, infobar_manager->infobar_count());
// Blocklist the site.
auto* infobar =
static_cast<TranslateCompactInfoBar*>(infobar_manager->infobar_at(0));
TranslateTestBridge::ClickOverflowMenuItem(
infobar, TranslateTestBridge::OverflowMenuItemId::NEVER_TRANSLATE_SITE);
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page2.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
// NOTE: There is no notification to wait for for the event of the infobar not
// showing. However, in practice the infobar is added synchronously, so if it
// were to be shown, this check would fail.
EXPECT_EQ(0u, infobar_manager->infobar_count());
infobar_manager->RemoveObserver(&infobar_observer);
}
// Parameterized to run tests on the "never translate language" and "never
// translate site" menu items.
class NeverTranslateMenuItemTranslateBrowserTest
: public TranslateBrowserTest,
public testing::WithParamInterface<
TranslateTestBridge::OverflowMenuItemId> {};
// Test that clicking and unclicking a never translate item ends up being a
// no-op.
IN_PROC_BROWSER_TEST_P(NeverTranslateMenuItemTranslateBrowserTest,
TranslateInfoBarToggleAndToggleBackNeverTranslateItem) {
auto* web_contents = static_cast<TabImpl*>(shell()->tab())->web_contents();
auto* infobar_manager =
infobars::ContentInfoBarManager::FromWebContents(web_contents);
SetTranslateScript(kTestValidScript);
TranslateClientImpl* translate_client = GetTranslateClient(shell());
TestInfoBarManagerObserver infobar_observer;
infobar_manager->AddObserver(&infobar_observer);
// Navigate to a page in French, wait for the infobar to be added, and click
// twice on the given overflow menu item.
{
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
ResetLanguageDeterminationWaiter();
EXPECT_EQ(0u, infobar_manager->infobar_count());
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
run_loop.Run();
auto* infobar =
static_cast<TranslateCompactInfoBar*>(infobar_manager->infobar_at(0));
TranslateTestBridge::ClickOverflowMenuItem(infobar, GetParam());
// The translate infobar should still be present.
EXPECT_EQ(1u, infobar_manager->infobar_count());
TranslateTestBridge::ClickOverflowMenuItem(infobar, GetParam());
}
// The infobar should be shown on a new navigation to a page in the same
// language.
{
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/french_page2.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("fr", translate_client->GetLanguageState().source_language());
run_loop.Run();
}
// The infobar should be shown on a new navigation to a page in a different
// language in the same site.
{
base::RunLoop run_loop;
infobar_observer.set_on_infobar_added_callback(run_loop.QuitClosure());
ResetLanguageDeterminationWaiter();
NavigateAndWaitForCompletion(
GURL(embedded_test_server()->GetURL("/german_page.html")), shell());
language_determination_waiter_->Wait();
EXPECT_EQ("de", translate_client->GetLanguageState().source_language());
run_loop.Run();
}
infobar_manager->RemoveObserver(&infobar_observer);
}
INSTANTIATE_TEST_SUITE_P(
All,
NeverTranslateMenuItemTranslateBrowserTest,
::testing::Values(
TranslateTestBridge::OverflowMenuItemId::NEVER_TRANSLATE_LANGUAGE,
TranslateTestBridge::OverflowMenuItemId::NEVER_TRANSLATE_SITE));
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/translate_browsertest.cc | C++ | unknown | 39,056 |
// 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/translate_client_impl.h"
#include <memory>
#include <vector>
#include "build/build_config.h"
#include "components/infobars/core/infobar.h"
#include "components/language/core/browser/pref_names.h"
#include "components/translate/content/browser/content_translate_driver.h"
#include "components/translate/content/browser/content_translate_util.h"
#include "components/translate/core/browser/translate_manager.h"
#include "components/translate/core/browser/translate_prefs.h"
#include "components/variations/service/variations_service.h"
#include "content/public/common/url_constants.h"
#include "url/gurl.h"
#include "weblayer/browser/accept_languages_service_factory.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/feature_list_creator.h"
#include "weblayer/browser/navigation_controller_impl.h"
#include "weblayer/browser/page_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/browser/translate_ranker_factory.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/infobars/content/content_infobar_manager.h"
#include "weblayer/browser/translate_compact_infobar.h"
#endif
namespace weblayer {
namespace {
std::unique_ptr<translate::TranslatePrefs> CreateTranslatePrefs(
PrefService* prefs) {
std::unique_ptr<translate::TranslatePrefs> translate_prefs(
new translate::TranslatePrefs(prefs));
// We need to obtain the country here, since it comes from VariationsService.
// components/ does not have access to that.
variations::VariationsService* variations_service =
FeatureListCreator::GetInstance()->variations_service();
if (variations_service) {
translate_prefs->SetCountry(
variations_service->GetStoredPermanentCountry());
}
return translate_prefs;
}
} // namespace
TranslateClientImpl::TranslateClientImpl(content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
content::WebContentsUserData<TranslateClientImpl>(*web_contents),
translate_driver_(*web_contents,
/*url_language_histogram=*/nullptr,
/*translate_model_service=*/nullptr),
translate_manager_(new translate::TranslateManager(
this,
TranslateRankerFactory::GetForBrowserContext(
web_contents->GetBrowserContext()),
/*language_model=*/nullptr)) {
observation_.Observe(&translate_driver_);
translate_driver_.set_translate_manager(translate_manager_.get());
}
TranslateClientImpl::~TranslateClientImpl() = default;
const translate::LanguageState& TranslateClientImpl::GetLanguageState() {
return *translate_manager_->GetLanguageState();
}
bool TranslateClientImpl::ShowTranslateUI(translate::TranslateStep step,
const std::string& source_language,
const std::string& target_language,
translate::TranslateErrors error_type,
bool triggered_from_menu) {
#if BUILDFLAG(IS_ANDROID)
if (error_type != translate::TranslateErrors::NONE)
step = translate::TRANSLATE_STEP_TRANSLATE_ERROR;
translate::TranslateInfoBarDelegate::Create(
step != translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
translate_manager_->GetWeakPtr(),
infobars::ContentInfoBarManager::FromWebContents(web_contents()), step,
source_language, target_language, error_type, triggered_from_menu);
return true;
#else
return false;
#endif
}
translate::TranslateDriver* TranslateClientImpl::GetTranslateDriver() {
return &translate_driver_;
}
translate::TranslateManager* TranslateClientImpl::GetTranslateManager() {
return translate_manager_.get();
}
PrefService* TranslateClientImpl::GetPrefs() {
BrowserContextImpl* browser_context =
static_cast<BrowserContextImpl*>(web_contents()->GetBrowserContext());
return browser_context->pref_service();
}
std::unique_ptr<translate::TranslatePrefs>
TranslateClientImpl::GetTranslatePrefs() {
return CreateTranslatePrefs(GetPrefs());
}
language::AcceptLanguagesService*
TranslateClientImpl::GetAcceptLanguagesService() {
return AcceptLanguagesServiceFactory::GetForBrowserContext(
web_contents()->GetBrowserContext());
}
#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<infobars::InfoBar> TranslateClientImpl::CreateInfoBar(
std::unique_ptr<translate::TranslateInfoBarDelegate> delegate) const {
return std::make_unique<TranslateCompactInfoBar>(std::move(delegate));
}
int TranslateClientImpl::GetInfobarIconID() const {
NOTREACHED();
return 0;
}
#endif
bool TranslateClientImpl::IsTranslatableURL(const GURL& url) {
return translate::IsTranslatableURL(url);
}
void TranslateClientImpl::OnLanguageDetermined(
const translate::LanguageDetectionDetails& details) {
// Inform NavigationControllerImpl that the language has been determined. Note
// that this event is implicitly regarded as being for the Page corresponding
// to the most recently committed primary main-frame navigation, if one exists
// (see the call to SetPageLanguageInNavigation() in
// ContentTranslateDriver::RegisterPage()); this corresponds to
// WebContents::GetPrimaryMainFrame()::GetPage(). Note also that in certain
// corner cases (e.g., tab startup) there might not be such a committed
// primary main-frame navigation; in those cases there won't be a
// weblayer::Page corresponding to the primary page, as weblayer::Page objects
// are created only at navigation commit.
// TODO(crbug.com/1231889): Rearchitect translate's renderer-browser Mojo
// connection to be able to explicitly determine the document/content::Page
// with which this language determination event is associated.
PageImpl* page =
PageImpl::GetForPage(web_contents()->GetPrimaryMainFrame()->GetPage());
if (page) {
std::string language = details.adopted_language;
auto* tab = TabImpl::FromWebContents(web_contents());
auto* navigation_controller =
static_cast<NavigationControllerImpl*>(tab->GetNavigationController());
navigation_controller->OnPageLanguageDetermined(page, language);
}
// Show translate UI if desired.
if (show_translate_ui_on_ready_) {
GetTranslateManager()->ShowTranslateUI();
show_translate_ui_on_ready_ = false;
}
}
void TranslateClientImpl::ShowTranslateUiWhenReady() {
if (GetLanguageState().source_language().empty()) {
show_translate_ui_on_ready_ = true;
} else {
GetTranslateManager()->ShowTranslateUI();
}
}
void TranslateClientImpl::WebContentsDestroyed() {
// Translation process can be interrupted.
// Destroying the TranslateManager now guarantees that it never has to deal
// with web_contents() being null.
translate_manager_.reset();
}
} // namespace weblayer
WEB_CONTENTS_USER_DATA_KEY_IMPL(weblayer::TranslateClientImpl);
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/translate_client_impl.cc | C++ | unknown | 7,032 |
// 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_TRANSLATE_CLIENT_IMPL_H_
#define WEBLAYER_BROWSER_TRANSLATE_CLIENT_IMPL_H_
#include <memory>
#include <string>
#include "base/scoped_observation.h"
#include "build/build_config.h"
#include "components/translate/content/browser/content_translate_driver.h"
#include "components/translate/core/browser/translate_client.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
namespace content {
class WebContents;
} // namespace content
namespace translate {
class LanguageState;
class TranslateManager;
} // namespace translate
namespace weblayer {
class TranslateClientImpl
: public translate::TranslateClient,
public translate::TranslateDriver::LanguageDetectionObserver,
public content::WebContentsObserver,
public content::WebContentsUserData<TranslateClientImpl> {
public:
TranslateClientImpl(const TranslateClientImpl&) = delete;
TranslateClientImpl& operator=(const TranslateClientImpl&) = delete;
~TranslateClientImpl() override;
// Gets the LanguageState associated with the page.
const translate::LanguageState& GetLanguageState();
// Returns the ContentTranslateDriver instance associated with this
// WebContents.
translate::ContentTranslateDriver* translate_driver() {
return &translate_driver_;
}
// Gets the associated TranslateManager.
translate::TranslateManager* GetTranslateManager();
// TranslateClient implementation.
translate::TranslateDriver* GetTranslateDriver() override;
PrefService* GetPrefs() override;
std::unique_ptr<translate::TranslatePrefs> GetTranslatePrefs() override;
language::AcceptLanguagesService* GetAcceptLanguagesService() override;
#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<infobars::InfoBar> CreateInfoBar(
std::unique_ptr<translate::TranslateInfoBarDelegate> delegate)
const override;
int GetInfobarIconID() const override;
#endif
bool ShowTranslateUI(translate::TranslateStep step,
const std::string& source_language,
const std::string& target_language,
translate::TranslateErrors error_type,
bool triggered_from_menu) override;
bool IsTranslatableURL(const GURL& url) override;
// TranslateDriver::LanguageDetectionObserver implementation.
void OnLanguageDetermined(
const translate::LanguageDetectionDetails& details) override;
// Show the translation UI when the necessary state (e.g. source language) is
// ready.
void ShowTranslateUiWhenReady();
private:
explicit TranslateClientImpl(content::WebContents* web_contents);
friend class content::WebContentsUserData<TranslateClientImpl>;
// content::WebContentsObserver implementation.
void WebContentsDestroyed() override;
translate::ContentTranslateDriver translate_driver_;
std::unique_ptr<translate::TranslateManager> translate_manager_;
// Whether to show translation UI when ready.
bool show_translate_ui_on_ready_ = false;
base::ScopedObservation<translate::TranslateDriver,
translate::TranslateDriver::LanguageDetectionObserver>
observation_{this};
WEB_CONTENTS_USER_DATA_KEY_DECL();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_TRANSLATE_CLIENT_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/translate_client_impl.h | C++ | unknown | 3,467 |
// 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.
#include "weblayer/browser/translate_compact_infobar.h"
#include <stddef.h>
#include <memory>
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/android/jni_weak_ref.h"
#include "base/functional/bind.h"
#include "base/metrics/field_trial_params.h"
#include "base/types/cxx23_to_underlying.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/translate/content/android/translate_utils.h"
#include "components/translate/core/browser/translate_infobar_delegate.h"
#include "content/public/browser/browser_context.h"
#include "weblayer/browser/java/jni/TranslateCompactInfoBar_jni.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/browser/translate_client_impl.h"
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
// Finch parameter names:
const char kTranslateTabDefaultTextColor[] = "translate_tab_default_text_color";
// TranslateInfoBar -----------------------------------------------------------
TranslateCompactInfoBar::TranslateCompactInfoBar(
std::unique_ptr<translate::TranslateInfoBarDelegate> delegate)
: infobars::InfoBarAndroid(std::move(delegate)), action_flags_(FLAG_NONE) {
GetDelegate()->AddObserver(this);
// Flip the translate bit if auto translate is enabled.
if (GetDelegate()->translate_step() == translate::TRANSLATE_STEP_TRANSLATING)
action_flags_ |= FLAG_TRANSLATE;
}
TranslateCompactInfoBar::~TranslateCompactInfoBar() {
GetDelegate()->RemoveObserver(this);
}
ScopedJavaLocalRef<jobject> TranslateCompactInfoBar::CreateRenderInfoBar(
JNIEnv* env,
const ResourceIdMapper& resource_id_mapper) {
translate::TranslateInfoBarDelegate* delegate = GetDelegate();
translate::JavaLanguageInfoWrapper translate_languages =
translate::TranslateUtils::GetTranslateLanguagesInJavaFormat(env,
delegate);
ScopedJavaLocalRef<jstring> source_language_code =
base::android::ConvertUTF8ToJavaString(env,
delegate->source_language_code());
ScopedJavaLocalRef<jstring> target_language_code =
base::android::ConvertUTF8ToJavaString(env,
delegate->target_language_code());
content::WebContents* web_contents =
infobars::ContentInfoBarManager::WebContentsFromInfoBar(this);
TabImpl* tab =
web_contents ? TabImpl::FromWebContents(web_contents) : nullptr;
return Java_TranslateCompactInfoBar_create(
env, tab ? tab->GetJavaTab() : nullptr, delegate->translate_step(),
source_language_code, target_language_code,
delegate->ShouldNeverTranslateLanguage(),
delegate->IsSiteOnNeverPromptList(), delegate->ShouldAlwaysTranslate(),
delegate->triggered_from_menu(), translate_languages.java_languages,
translate_languages.java_codes, translate_languages.java_hash_codes,
TabDefaultTextColor());
}
void TranslateCompactInfoBar::ProcessButton(int action) {
if (!owner())
return; // We're closing; don't call anything, it might access the owner.
translate::TranslateInfoBarDelegate* delegate = GetDelegate();
if (action == infobars::InfoBarAndroid::ACTION_TRANSLATE) {
action_flags_ |= FLAG_TRANSLATE;
delegate->Translate();
if (delegate->ShouldAutoAlwaysTranslate()) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_TranslateCompactInfoBar_setAutoAlwaysTranslate(env,
GetJavaInfoBar());
}
} else if (action ==
infobars::InfoBarAndroid::ACTION_TRANSLATE_SHOW_ORIGINAL) {
action_flags_ |= FLAG_REVERT;
delegate->RevertWithoutClosingInfobar();
} else {
DCHECK_EQ(infobars::InfoBarAndroid::ACTION_NONE, action);
}
}
void TranslateCompactInfoBar::SetJavaInfoBar(
const base::android::JavaRef<jobject>& java_info_bar) {
infobars::InfoBarAndroid::SetJavaInfoBar(java_info_bar);
JNIEnv* env = base::android::AttachCurrentThread();
Java_TranslateCompactInfoBar_setNativePtr(env, java_info_bar,
reinterpret_cast<intptr_t>(this));
}
void TranslateCompactInfoBar::ApplyStringTranslateOption(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
int option,
const JavaParamRef<jstring>& value) {
translate::TranslateInfoBarDelegate* delegate = GetDelegate();
if (option == translate::TranslateUtils::OPTION_SOURCE_CODE) {
std::string source_code =
base::android::ConvertJavaStringToUTF8(env, value);
delegate->UpdateSourceLanguage(source_code);
} else if (option == translate::TranslateUtils::OPTION_TARGET_CODE) {
std::string target_code =
base::android::ConvertJavaStringToUTF8(env, value);
delegate->UpdateTargetLanguage(target_code);
} else {
DCHECK(false);
}
}
void TranslateCompactInfoBar::ApplyBoolTranslateOption(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
int option,
jboolean value) {
translate::TranslateInfoBarDelegate* delegate = GetDelegate();
if (option == translate::TranslateUtils::OPTION_ALWAYS_TRANSLATE) {
if (delegate->ShouldAlwaysTranslate() != value) {
action_flags_ |= FLAG_ALWAYS_TRANSLATE;
delegate->ToggleAlwaysTranslate();
}
} else if (option == translate::TranslateUtils::OPTION_NEVER_TRANSLATE) {
bool language_blocklisted = !delegate->IsTranslatableLanguageByPrefs();
if (language_blocklisted != value) {
delegate->RevertWithoutClosingInfobar();
action_flags_ |= FLAG_NEVER_LANGUAGE;
delegate->ToggleTranslatableLanguageByPrefs();
}
} else if (option == translate::TranslateUtils::OPTION_NEVER_TRANSLATE_SITE) {
if (delegate->IsSiteOnNeverPromptList() != value) {
delegate->RevertWithoutClosingInfobar();
action_flags_ |= FLAG_NEVER_SITE;
delegate->ToggleNeverPromptSite();
}
} else {
DCHECK(false);
}
}
jboolean TranslateCompactInfoBar::ShouldAutoNeverTranslate(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jboolean menu_expanded) {
// Flip menu expanded bit.
if (menu_expanded)
action_flags_ |= FLAG_EXPAND_MENU;
if (!IsDeclinedByUser())
return false;
return GetDelegate()->ShouldAutoNeverTranslate();
}
// Returns true if the current tab is an incognito tab.
jboolean TranslateCompactInfoBar::IsIncognito(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
content::WebContents* web_contents =
infobars::ContentInfoBarManager::WebContentsFromInfoBar(this);
if (!web_contents)
return false;
return web_contents->GetBrowserContext()->IsOffTheRecord();
}
int TranslateCompactInfoBar::GetParam(const std::string& paramName,
int default_value) {
std::map<std::string, std::string> params;
if (!base::GetFieldTrialParams(translate::kTranslateCompactUI.name,
¶ms)) {
return default_value;
}
int value = 0;
base::StringToInt(params[paramName], &value);
return value <= 0 ? default_value : value;
}
int TranslateCompactInfoBar::TabDefaultTextColor() {
return GetParam(kTranslateTabDefaultTextColor, 0);
}
translate::TranslateInfoBarDelegate* TranslateCompactInfoBar::GetDelegate() {
return delegate()->AsTranslateInfoBarDelegate();
}
void TranslateCompactInfoBar::OnTranslateStepChanged(
translate::TranslateStep step,
translate::TranslateErrors error_type) {
// If the tab lost active state while translation was occurring, the Java
// infobar will now be gone. In that case there is nothing to do here.
if (!HasSetJavaInfoBar())
return; // No connected Java infobar
if (!owner())
return; // We're closing; don't call anything.
if ((step == translate::TRANSLATE_STEP_AFTER_TRANSLATE) ||
(step == translate::TRANSLATE_STEP_TRANSLATE_ERROR)) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_TranslateCompactInfoBar_onPageTranslated(
env, GetJavaInfoBar(), base::to_underlying(error_type));
}
}
void TranslateCompactInfoBar::OnTargetLanguageChanged(
const std::string& target_language_code) {
// In WebLayer, target language changes are only initiated by the UI. This
// method should always be a no-op.
DCHECK_EQ(GetDelegate()->target_language_code(), target_language_code);
}
bool TranslateCompactInfoBar::IsDeclinedByUser() {
// Whether there is any affirmative action bit.
return action_flags_ == FLAG_NONE;
}
void TranslateCompactInfoBar::OnTranslateInfoBarDelegateDestroyed(
translate::TranslateInfoBarDelegate* delegate) {
DCHECK_EQ(GetDelegate(), delegate);
GetDelegate()->RemoveObserver(this);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/translate_compact_infobar.cc | C++ | unknown | 8,968 |
// 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.
#ifndef WEBLAYER_BROWSER_TRANSLATE_COMPACT_INFOBAR_H_
#define WEBLAYER_BROWSER_TRANSLATE_COMPACT_INFOBAR_H_
#include "base/android/scoped_java_ref.h"
#include "components/infobars/android/infobar_android.h"
#include "components/translate/core/browser/translate_infobar_delegate.h"
#include "components/translate/core/browser/translate_step.h"
#include "components/translate/core/common/translate_errors.h"
namespace translate {
class TranslateInfoBarDelegate;
}
namespace weblayer {
class TranslateCompactInfoBar
: public infobars::InfoBarAndroid,
public translate::TranslateInfoBarDelegate::Observer {
public:
explicit TranslateCompactInfoBar(
std::unique_ptr<translate::TranslateInfoBarDelegate> delegate);
TranslateCompactInfoBar(const TranslateCompactInfoBar&) = delete;
TranslateCompactInfoBar& operator=(const TranslateCompactInfoBar&) = delete;
~TranslateCompactInfoBar() override;
// JNI method specific to string settings in translate.
void ApplyStringTranslateOption(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
int option,
const base::android::JavaParamRef<jstring>& value);
// JNI method specific to boolean settings in translate.
void ApplyBoolTranslateOption(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
int option,
jboolean value);
// Check whether we should automatically trigger "Never Translate Language".
jboolean ShouldAutoNeverTranslate(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jboolean menu_expanded);
// Returns true if the current tab is an incognito tab.
jboolean IsIncognito(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
// TranslateInfoBarDelegate::Observer implementation.
void OnTranslateStepChanged(translate::TranslateStep step,
translate::TranslateErrors error_type) override;
void OnTargetLanguageChanged(
const std::string& target_language_code) override;
// Returns true if the user didn't take any affirmative action.
// The function will be called when the translate infobar is dismissed.
// If it's true, we will record a declined event.
bool IsDeclinedByUser() override;
void OnTranslateInfoBarDelegateDestroyed(
translate::TranslateInfoBarDelegate* delegate) override;
private:
// infobars::InfoBarAndroid:
base::android::ScopedJavaLocalRef<jobject> CreateRenderInfoBar(
JNIEnv* env,
const ResourceIdMapper& resource_id_mapper) override;
void ProcessButton(int action) override;
void SetJavaInfoBar(
const base::android::JavaRef<jobject>& java_info_bar) override;
// Get the value of a specified finch parameter in TranslateCompactUI. If the
// finch parameter does not exist, default_value will be returned.
int GetParam(const std::string& paramName, int default_value);
// Get the value of the finch parameter: translate_tab_default_text_color.
// Default value is 0, which means using TabLayout default color.
// If it's not 0, we will set the text color manually based on the value.
int TabDefaultTextColor();
translate::TranslateInfoBarDelegate* GetDelegate();
// Bits for trace user's affirmative actions.
unsigned int action_flags_;
// Affirmative action flags to record what the user has done in one session.
enum ActionFlag {
FLAG_NONE = 0,
FLAG_TRANSLATE = 1 << 0,
FLAG_REVERT = 1 << 1,
FLAG_ALWAYS_TRANSLATE = 1 << 2,
FLAG_NEVER_LANGUAGE = 1 << 3,
FLAG_NEVER_SITE = 1 << 4,
FLAG_EXPAND_MENU = 1 << 5,
};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_TRANSLATE_COMPACT_INFOBAR_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/translate_compact_infobar.h | C++ | unknown | 3,918 |
// 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/translate_ranker_factory.h"
#include "base/files/file_path.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/translate/core/browser/translate_ranker_impl.h"
#include "content/public/browser/browser_context.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
namespace weblayer {
// static
translate::TranslateRanker* TranslateRankerFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<translate::TranslateRanker*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
TranslateRankerFactory* TranslateRankerFactory::GetInstance() {
static base::NoDestructor<TranslateRankerFactory> factory;
return factory.get();
}
TranslateRankerFactory::TranslateRankerFactory()
: BrowserContextKeyedServiceFactory(
"TranslateRanker",
BrowserContextDependencyManager::GetInstance()) {}
TranslateRankerFactory::~TranslateRankerFactory() = default;
KeyedService* TranslateRankerFactory::BuildServiceInstanceFor(
content::BrowserContext* browser_context) const {
return new translate::TranslateRankerImpl(
translate::TranslateRankerImpl::GetModelPath(browser_context->GetPath()),
translate::TranslateRankerImpl::GetModelURL(), ukm::UkmRecorder::Get());
}
content::BrowserContext* TranslateRankerFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/translate_ranker_factory.cc | C++ | unknown | 1,699 |
// 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_TRANSLATE_RANKER_FACTORY_H_
#define WEBLAYER_BROWSER_TRANSLATE_RANKER_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace content {
class BrowserContext;
}
namespace translate {
class TranslateRanker;
}
namespace weblayer {
// TranslateRankerFactory is a way to associate a TranslateRanker instance to a
// BrowserContext.
class TranslateRankerFactory : public BrowserContextKeyedServiceFactory {
public:
TranslateRankerFactory(const TranslateRankerFactory&) = delete;
TranslateRankerFactory& operator=(const TranslateRankerFactory&) = delete;
static TranslateRankerFactory* GetInstance();
static translate::TranslateRanker* GetForBrowserContext(
content::BrowserContext* browser_context);
private:
friend class base::NoDestructor<TranslateRankerFactory>;
TranslateRankerFactory();
~TranslateRankerFactory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
// Note: In //chrome, when the service is requested for a
// Profile in incognito mode the factory supplies the associated original
// Profile. However, WebLayer doesn't have a concept of incognito profiles
// being associated with regular profiles, so the service gets its own
// instance in incognito mode.
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_TRANSLATE_RANKER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/translate_ranker_factory.h | C++ | unknown | 1,753 |
// 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/tts_environment_android_impl.h"
#include "base/functional/callback.h"
namespace weblayer {
TtsEnvironmentAndroidImpl::TtsEnvironmentAndroidImpl() = default;
TtsEnvironmentAndroidImpl::~TtsEnvironmentAndroidImpl() = default;
bool TtsEnvironmentAndroidImpl::CanSpeakUtterancesFromHiddenWebContents() {
// For simplicity's sake, disallow playing utterances in hidden WebContents.
// Other options are to allow this, and instead cancel any utterances when
// all browsers are paused.
return false;
}
bool TtsEnvironmentAndroidImpl::CanSpeakNow() {
// Always return true, as by the time we get here we know the WebContents
// is visible (because CanSpeakUtterancesFromHiddenWebContents() returns
// false). Further, when the fragment is paused/stopped the WebContents is
// hidden, which triggers the utterance to stop (because
// CanSpeakUtterancesFromHiddenWebContents() returns false).
return true;
}
void TtsEnvironmentAndroidImpl::SetCanSpeakNowChangedCallback(
base::RepeatingClosure callback) {
// As CanSpeakNow() always returns true, there is nothing to do here.
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/tts_environment_android_impl.cc | C++ | unknown | 1,299 |
// 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_TTS_ENVIRONMENT_ANDROID_IMPL_H_
#define WEBLAYER_BROWSER_TTS_ENVIRONMENT_ANDROID_IMPL_H_
#include "content/public/browser/tts_environment_android.h"
namespace weblayer {
// WebLayer implementation of TtsEnvironmentAndroid. This does not allow
// speech from hidden WebContents.
class TtsEnvironmentAndroidImpl : public content::TtsEnvironmentAndroid {
public:
TtsEnvironmentAndroidImpl();
TtsEnvironmentAndroidImpl(const TtsEnvironmentAndroidImpl&) = delete;
TtsEnvironmentAndroidImpl& operator=(const TtsEnvironmentAndroidImpl&) =
delete;
~TtsEnvironmentAndroidImpl() override;
// TtsEnvironment:
bool CanSpeakUtterancesFromHiddenWebContents() override;
bool CanSpeakNow() override;
void SetCanSpeakNowChangedCallback(base::RepeatingClosure callback) override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_TTS_ENVIRONMENT_ANDROID_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/tts_environment_android_impl.h | C++ | unknown | 1,048 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/verdict_cache_manager_factory.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/safe_browsing/core/browser/verdict_cache_manager.h"
#include "content/public/browser/browser_context.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
safe_browsing::VerdictCacheManager*
VerdictCacheManagerFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<safe_browsing::VerdictCacheManager*>(
GetInstance()->GetServiceForBrowserContext(browser_context,
/* create= */ true));
}
// static
VerdictCacheManagerFactory* VerdictCacheManagerFactory::GetInstance() {
return base::Singleton<VerdictCacheManagerFactory>::get();
}
VerdictCacheManagerFactory::VerdictCacheManagerFactory()
: BrowserContextKeyedServiceFactory(
"VerdictCacheManager",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
KeyedService* VerdictCacheManagerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
BrowserContextImpl* context_impl = static_cast<BrowserContextImpl*>(context);
return new safe_browsing::VerdictCacheManager(
/*history_service=*/nullptr,
HostContentSettingsMapFactory::GetForBrowserContext(context),
context_impl->pref_service(), /*sync_observer=*/nullptr);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/verdict_cache_manager_factory.cc | C++ | unknown | 1,728 |
// 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_VERDICT_CACHE_MANAGER_FACTORY_H_
#define WEBLAYER_BROWSER_VERDICT_CACHE_MANAGER_FACTORY_H_
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class KeyedService;
namespace content {
class BrowserContext;
}
namespace safe_browsing {
class VerdictCacheManager;
}
namespace weblayer {
// Singleton that owns VerdictCacheManager objects and associates them
// them with BrowserContextImpl instances.
class VerdictCacheManagerFactory : public BrowserContextKeyedServiceFactory {
public:
// Creates the manager if it doesn't exist already for the given
// |browser_context|. If the manager already exists, return its pointer.
static safe_browsing::VerdictCacheManager* GetForBrowserContext(
content::BrowserContext* browser_context);
// Get the singleton instance.
static VerdictCacheManagerFactory* GetInstance();
private:
friend struct base::DefaultSingletonTraits<VerdictCacheManagerFactory>;
VerdictCacheManagerFactory();
~VerdictCacheManagerFactory() override = default;
VerdictCacheManagerFactory(const VerdictCacheManagerFactory&) = delete;
VerdictCacheManagerFactory& operator=(const VerdictCacheManagerFactory&) =
delete;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_VERDICT_CACHE_MANAGER_FACTORY_H_ | Zhao-PengFei35/chromium_src_4 | weblayer/browser/verdict_cache_manager_factory.h | C++ | unknown | 1,633 |
// 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/web_contents_view_delegate_impl.h"
#include <memory>
#include "weblayer/browser/tab_impl.h"
namespace weblayer {
WebContentsViewDelegateImpl::WebContentsViewDelegateImpl(
content::WebContents* web_contents)
: web_contents_(web_contents) {}
WebContentsViewDelegateImpl::~WebContentsViewDelegateImpl() = default;
void WebContentsViewDelegateImpl::ShowContextMenu(
content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
TabImpl* tab = TabImpl::FromWebContents(web_contents_);
if (tab)
tab->ShowContextMenu(params);
}
std::unique_ptr<content::WebContentsViewDelegate> CreateWebContentsViewDelegate(
content::WebContents* web_contents) {
return std::make_unique<WebContentsViewDelegateImpl>(web_contents);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/web_contents_view_delegate_impl.cc | C++ | unknown | 971 |
// 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_WEB_CONTENTS_VIEW_DELEGATE_IMPL_H_
#define WEBLAYER_BROWSER_WEB_CONTENTS_VIEW_DELEGATE_IMPL_H_
#include "base/memory/raw_ptr.h"
#include "content/public/browser/web_contents_view_delegate.h"
namespace content {
class WebContents;
}
namespace weblayer {
class WebContentsViewDelegateImpl : public content::WebContentsViewDelegate {
public:
explicit WebContentsViewDelegateImpl(content::WebContents* web_contents);
WebContentsViewDelegateImpl(const WebContentsViewDelegateImpl&) = delete;
WebContentsViewDelegateImpl& operator=(const WebContentsViewDelegateImpl&) =
delete;
~WebContentsViewDelegateImpl() override;
// WebContentsViewDelegate overrides.
void ShowContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) override;
private:
raw_ptr<content::WebContents> web_contents_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEB_CONTENTS_VIEW_DELEGATE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/web_contents_view_delegate_impl.h | C++ | unknown | 1,138 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/web_data_service_factory.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "components/webdata_services/web_data_service_wrapper.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "weblayer/browser/i18n_util.h"
namespace weblayer {
namespace {
// Callback to show error dialog on profile load error.
void ProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type,
sql::InitStatus status,
const std::string& diagnostics) {
NOTIMPLEMENTED();
}
} // namespace
WebDataServiceFactory::WebDataServiceFactory() = default;
WebDataServiceFactory::~WebDataServiceFactory() = default;
// static
WebDataServiceFactory* WebDataServiceFactory::GetInstance() {
static base::NoDestructor<WebDataServiceFactory> instance;
return instance.get();
}
content::BrowserContext* WebDataServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
KeyedService* WebDataServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
const base::FilePath& profile_path = context->GetPath();
return new WebDataServiceWrapper(profile_path, i18n::GetApplicationLocale(),
content::GetUIThreadTaskRunner({}),
base::BindRepeating(&ProfileErrorCallback));
}
bool WebDataServiceFactory::ServiceIsNULLWhileTesting() const {
return true;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/web_data_service_factory.cc | C++ | unknown | 1,833 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_WEB_DATA_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_WEB_DATA_SERVICE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/webdata_services/web_data_service_wrapper_factory.h"
namespace weblayer {
// Singleton that owns all WebDataServiceWrappers and associates them with
// Profiles.
class WebDataServiceFactory
: public webdata_services::WebDataServiceWrapperFactory {
public:
WebDataServiceFactory(const WebDataServiceFactory&) = delete;
WebDataServiceFactory& operator=(const WebDataServiceFactory&) = delete;
static WebDataServiceFactory* GetInstance();
private:
friend class base::NoDestructor<WebDataServiceFactory>;
WebDataServiceFactory();
~WebDataServiceFactory() override;
// |BrowserContextKeyedServiceFactory| methods:
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
bool ServiceIsNULLWhileTesting() const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEB_DATA_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/web_data_service_factory.h | C++ | unknown | 1,280 |
// 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.
#include "weblayer/browser/webapps/webapk_install_scheduler.h"
#include <utility>
#include "base/functional/bind.h"
#include "base/task/thread_pool.h"
#include "components/webapps/browser/android/shortcut_info.h"
#include "components/webapps/browser/android/webapk/webapk_icon_hasher.h"
#include "components/webapps/browser/android/webapk/webapk_proto_builder.h"
#include "components/webapps/browser/android/webapk/webapk_types.h"
#include "components/webapps/browser/android/webapps_utils.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "url/gurl.h"
#include "weblayer/browser/webapps/webapk_install_scheduler_bridge.h"
namespace weblayer {
WebApkInstallScheduler::WebApkInstallScheduler(
const webapps::ShortcutInfo& shortcut_info,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable,
WebApkInstallFinishedCallback callback)
: webapps_client_callback_(std::move(callback)),
primary_icon_(primary_icon),
is_primary_icon_maskable_(is_primary_icon_maskable) {
shortcut_info_ = std::make_unique<webapps::ShortcutInfo>(shortcut_info);
}
WebApkInstallScheduler::~WebApkInstallScheduler() = default;
// static
void WebApkInstallScheduler::FetchProtoAndScheduleInstall(
content::WebContents* web_contents,
const webapps::ShortcutInfo& shortcut_info,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable,
WebApkInstallFinishedCallback callback) {
// Self owned WebApkInstallScheduler that destroys itself as soon as its
// OnResult function is called when the scheduled installation failed or
// finished.
WebApkInstallScheduler* scheduler =
new WebApkInstallScheduler(shortcut_info, primary_icon,
is_primary_icon_maskable, std::move(callback));
scheduler->FetchMurmur2Hashes(web_contents);
}
void WebApkInstallScheduler::FetchProtoAndScheduleInstallForTesting(
content::WebContents* web_contents) {
FetchMurmur2Hashes(web_contents);
}
void WebApkInstallScheduler::FetchMurmur2Hashes(
content::WebContents* web_contents) {
// We need to take the hash of the bitmap at the icon URL prior to any
// transformations being applied to the bitmap (such as encoding/decoding
// the bitmap). The icon hash is used to determine whether the icon that
// the user sees matches the icon of a WebAPK that the WebAPK server
// generated for another user. (The icon can be dynamically generated.)
//
// We redownload the icon in order to take the Murmur2 hash. The redownload
// should be fast because the icon should be in the HTTP cache.
std::set<GURL> icons = shortcut_info_->GetWebApkIcons();
webapps::WebApkIconHasher::DownloadAndComputeMurmur2Hash(
web_contents->GetBrowserContext()
->GetDefaultStoragePartition()
->GetURLLoaderFactoryForBrowserProcess()
.get(),
web_contents->GetWeakPtr(), url::Origin::Create(shortcut_info_->url),
icons,
base::BindOnce(&WebApkInstallScheduler::OnGotIconMurmur2HashesBuildProto,
weak_ptr_factory_.GetWeakPtr()));
}
void WebApkInstallScheduler::OnGotIconMurmur2HashesBuildProto(
absl::optional<std::map<std::string, webapps::WebApkIconHasher::Icon>>
hashes) {
if (!hashes) {
OnResult(webapps::WebApkInstallResult::ICON_HASHER_ERROR);
return;
}
webapps::BuildProto(
*shortcut_info_.get(), shortcut_info_->manifest_id,
std::string() /* primary_icon_data */, is_primary_icon_maskable_,
std::string() /* splash_icon_data */, "" /* package_name */,
"" /* version */, std::move(*hashes), false /* is_manifest_stale */,
false /* is_app_identity_update_supported */,
base::BindOnce(&WebApkInstallScheduler::ScheduleWithChrome,
weak_ptr_factory_.GetWeakPtr()));
}
void WebApkInstallScheduler::ScheduleWithChrome(
std::unique_ptr<std::string> serialized_proto) {
WebApkInstallSchedulerBridge::ScheduleWebApkInstallWithChrome(
std::move(serialized_proto), primary_icon_, is_primary_icon_maskable_,
base::BindOnce(&WebApkInstallScheduler::OnResult,
weak_ptr_factory_.GetWeakPtr()));
}
void WebApkInstallScheduler::OnResult(webapps::WebApkInstallResult result) {
// Toasts have to be called on the UI thread, but the
// WebApkInstallSchedulerClient already makes sure that the callback, which is
// triggered by the Chrome-service, is invoked on the UI thread.
webapps::WebappsUtils::ShowWebApkInstallResultToast(result);
std::move(webapps_client_callback_)
.Run(shortcut_info_->manifest_url, shortcut_info_->manifest_id);
delete this;
}
// static
bool WebApkInstallScheduler::IsInstallServiceAvailable() {
return WebApkInstallSchedulerBridge::IsInstallServiceAvailable();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/webapk_install_scheduler.cc | C++ | unknown | 5,208 |
// 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.
#ifndef WEBLAYER_BROWSER_WEBAPPS_WEBAPK_INSTALL_SCHEDULER_H_
#define WEBLAYER_BROWSER_WEBAPPS_WEBAPK_INSTALL_SCHEDULER_H_
#include <memory>
#include "base/functional/callback.h"
#include "base/memory/weak_ptr.h"
#include "components/webapps/browser/android/webapk/webapk_icon_hasher.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "weblayer/browser/webapps/weblayer_webapps_client.h"
namespace content {
class WebContents;
} // namespace content
namespace webapps {
struct ShortcutInfo;
enum class WebApkInstallResult;
} // namespace webapps
namespace weblayer {
class WebApkInstallSchedulerBridge;
// Class that schedules the WebAPK installation via the Chrome
// WebApkInstallCoordinatorService. Creates a self-owned
// WebApkInstallSchedulerBridge instance when building the proto is complete.
// |finish_callback| is called once the install completed or failed.
class WebApkInstallScheduler {
public:
// Called when the scheduling of an WebAPK-installation with the Chrome
// service finished or failed.
using FinishCallback = base::OnceCallback<void(webapps::WebApkInstallResult)>;
virtual ~WebApkInstallScheduler();
using WebApkInstallFinishedCallback =
weblayer::WebLayerWebappsClient::WebApkInstallFinishedCallback;
WebApkInstallScheduler(const WebApkInstallScheduler&) = delete;
WebApkInstallScheduler& operator=(const WebApkInstallScheduler&) = delete;
static void FetchProtoAndScheduleInstall(
content::WebContents* web_contents,
const webapps::ShortcutInfo& shortcut_info,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable,
WebApkInstallFinishedCallback callback);
void FetchProtoAndScheduleInstallForTesting(
content::WebContents* web_contents);
static bool IsInstallServiceAvailable();
private:
WebApkInstallScheduler(const webapps::ShortcutInfo& shortcut_info,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable,
WebApkInstallFinishedCallback callback);
friend class TestWebApkInstallScheduler;
void FetchMurmur2Hashes(content::WebContents* web_contents);
void OnGotIconMurmur2HashesBuildProto(
absl::optional<std::map<std::string, webapps::WebApkIconHasher::Icon>>
hashes);
virtual void ScheduleWithChrome(
std::unique_ptr<std::string> serialized_proto);
virtual void OnResult(webapps::WebApkInstallResult result);
WebApkInstallFinishedCallback webapps_client_callback_;
std::unique_ptr<webapps::ShortcutInfo> shortcut_info_;
const SkBitmap primary_icon_;
bool is_primary_icon_maskable_;
// Used to get |weak_ptr_|.
base::WeakPtrFactory<WebApkInstallScheduler> weak_ptr_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBAPPS_WEBAPK_INSTALL_SCHEDULER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/webapk_install_scheduler.h | C++ | unknown | 2,982 |
// 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.
#include "weblayer/browser/webapps/webapk_install_scheduler_bridge.h"
#include <jni.h>
#include <string>
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "components/webapps/browser/android/webapk/webapk_types.h"
#include "ui/gfx/android/java_bitmap.h"
#include "url/gurl.h"
#include "weblayer/browser/java/jni/WebApkInstallSchedulerBridge_jni.h"
using base::android::ConvertUTF16ToJavaString;
using base::android::ScopedJavaLocalRef;
using base::android::ToJavaByteArray;
using gfx::ConvertToJavaBitmap;
namespace weblayer {
// static
bool WebApkInstallSchedulerBridge::IsInstallServiceAvailable() {
return Java_WebApkInstallSchedulerBridge_isInstallServiceAvailable(
base::android::AttachCurrentThread());
}
WebApkInstallSchedulerBridge::WebApkInstallSchedulerBridge(
FinishCallback finish_callback) {
finish_callback_ = std::move(finish_callback);
JNIEnv* env = base::android::AttachCurrentThread();
java_ref_.Reset(Java_WebApkInstallSchedulerBridge_create(
env, reinterpret_cast<intptr_t>(this)));
}
WebApkInstallSchedulerBridge::~WebApkInstallSchedulerBridge() {
JNIEnv* env = base::android::AttachCurrentThread();
Java_WebApkInstallSchedulerBridge_destroy(env, java_ref_);
java_ref_.Reset();
}
// static
void WebApkInstallSchedulerBridge::ScheduleWebApkInstallWithChrome(
std::unique_ptr<std::string> serialized_proto,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable,
FinishCallback finish_callback) {
// WebApkInstallSchedulerBridge owns itself and deletes itself when finished.
WebApkInstallSchedulerBridge* bridge =
new WebApkInstallSchedulerBridge(std::move(finish_callback));
bridge->ScheduleWebApkInstallWithChrome(
std::move(serialized_proto), primary_icon, is_primary_icon_maskable);
}
void WebApkInstallSchedulerBridge::ScheduleWebApkInstallWithChrome(
std::unique_ptr<std::string> serialized_proto,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> java_serialized_proto =
ToJavaByteArray(env, *serialized_proto);
ScopedJavaLocalRef<jobject> java_primary_icon =
ConvertToJavaBitmap(primary_icon);
Java_WebApkInstallSchedulerBridge_scheduleInstall(
env, java_ref_, java_serialized_proto, java_primary_icon,
is_primary_icon_maskable);
}
void WebApkInstallSchedulerBridge::OnInstallFinished(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jint result) {
std::move(finish_callback_)
.Run(static_cast<webapps::WebApkInstallResult>(result));
delete this;
}
} // namespace weblayer | Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/webapk_install_scheduler_bridge.cc | C++ | unknown | 2,836 |
// 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.
#ifndef WEBLAYER_BROWSER_WEBAPPS_WEBAPK_INSTALL_SCHEDULER_BRIDGE_H_
#define WEBLAYER_BROWSER_WEBAPPS_WEBAPK_INSTALL_SCHEDULER_BRIDGE_H_
#include "base/android/scoped_java_ref.h"
#include "components/webapps/browser/android/webapk/webapk_icon_hasher.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "weblayer/browser/webapps/webapk_install_scheduler.h"
namespace webapps {
enum class WebApkInstallResult;
} // namespace webapps
namespace weblayer {
// The native WebApkInstallSchedulerBridge owns itself, and deletes itself and
// its Java counterpart when finished.
class WebApkInstallSchedulerBridge {
public:
using FinishCallback = WebApkInstallScheduler::FinishCallback;
~WebApkInstallSchedulerBridge();
WebApkInstallSchedulerBridge(const WebApkInstallSchedulerBridge&) = delete;
WebApkInstallSchedulerBridge& operator=(const WebApkInstallSchedulerBridge&) =
delete;
static void ScheduleWebApkInstallWithChrome(
std::unique_ptr<std::string> serialized_proto,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable,
FinishCallback finish_callback);
static bool IsInstallServiceAvailable();
void OnInstallFinished(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jint result);
private:
WebApkInstallSchedulerBridge(FinishCallback finish_callback);
void ScheduleWebApkInstallWithChrome(
std::unique_ptr<std::string> serialized_proto,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable);
FinishCallback finish_callback_;
// Points to the Java Object.
base::android::ScopedJavaGlobalRef<jobject> java_ref_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBAPPS_WEBAPK_INSTALL_SCHEDULER_BRIDGE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/webapk_install_scheduler_bridge.h | C++ | unknown | 1,930 |
// 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.
#include "weblayer/browser/webapps/webapk_install_scheduler.h"
#include "base/files/file_path.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "components/webapps/browser/android/shortcut_info.h"
#include "components/webapps/browser/android/webapk/webapk_types.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
// Keep these tests in sync with tests for building the WebAPK-proto in
// chrome/browser/android/webapk/webapk_installer_unittest.cc.
namespace {
const base::FilePath::CharType kTestDataDir[] =
FILE_PATH_LITERAL("components/test/data/webapps");
// Start URL for the WebAPK
const char* kStartUrl = "/index.html";
// The URLs of best icons from Web Manifest. We use a random file in the test
// data directory. Since WebApkInstallScheduler does not try to decode the file
// as an image it is OK that the file is not an image.
const char* kBestPrimaryIconUrl = "/simple.html";
const char* kBestSplashIconUrl = "/nostore.html";
const char* kBestShortcutIconUrl = "/title1.html";
// Icon which has Cross-Origin-Resource-Policy: same-origin set.
const char* kBestPrimaryIconCorpUrl = "/cors_same_origin.png";
} // namespace
namespace weblayer {
class TestWebApkInstallScheduler : public WebApkInstallScheduler {
public:
TestWebApkInstallScheduler(const webapps::ShortcutInfo& shortcut_info,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable,
WebApkInstallFinishedCallback callback)
: WebApkInstallScheduler(shortcut_info,
primary_icon,
is_primary_icon_maskable,
std::move(callback)) {}
TestWebApkInstallScheduler(const TestWebApkInstallScheduler&) = delete;
TestWebApkInstallScheduler& operator=(const TestWebApkInstallScheduler&) =
delete;
void ScheduleWithChrome(
std::unique_ptr<std::string> serialized_proto) override {
PostTaskToRunSuccessCallback();
}
// Function used for testing FetchProtoAndScheduleInstall. |callback| can
// be set to forward the result-value in the OnResult-callback to a test for
// verification.
void FetchProtoAndScheduleInstallForTesting(
content::WebContents* web_contents,
WebApkInstallScheduler::FinishCallback callback) {
callback_ = std::move(callback);
WebApkInstallScheduler::FetchProtoAndScheduleInstallForTesting(
web_contents);
}
void OnResult(webapps::WebApkInstallResult result) override {
// Pass the |result| to the callback for verification.
std::move(callback_).Run(result);
WebApkInstallScheduler::OnResult(result);
}
void PostTaskToRunSuccessCallback() {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&TestWebApkInstallScheduler::OnResult,
base::Unretained(this),
webapps::WebApkInstallResult::SUCCESS));
}
private:
WebApkInstallScheduler::FinishCallback callback_;
};
// Wrapper class for running WebApkInstallScheduler#FetchProtoAndScheduleInstall
// that makes the WebApkInstallResult that is received in the OnResult-callback
// accessible for testing.
class WebApkInstallSchedulerRunner {
public:
WebApkInstallSchedulerRunner() {}
WebApkInstallSchedulerRunner(const WebApkInstallSchedulerRunner&) = delete;
WebApkInstallSchedulerRunner& operator=(const WebApkInstallSchedulerRunner&) =
delete;
~WebApkInstallSchedulerRunner() {}
void RunFetchProtoAndScheduleInstall(
std::unique_ptr<TestWebApkInstallScheduler> fetcher,
content::WebContents* web_contents) {
base::RunLoop run_loop;
on_completed_callback_ = run_loop.QuitClosure();
// WebApkInstallScheduler owns itself.
fetcher.release()->FetchProtoAndScheduleInstallForTesting(
web_contents, base::BindOnce(&WebApkInstallSchedulerRunner::OnCompleted,
base::Unretained(this)));
run_loop.Run();
}
webapps::WebApkInstallResult result() { return result_; }
private:
void OnCompleted(webapps::WebApkInstallResult result) {
result_ = result;
std::move(on_completed_callback_).Run();
}
// Called after the installation process has succeeded or failed.
base::OnceClosure on_completed_callback_;
// The result of the installation process.
webapps::WebApkInstallResult result_;
};
class WebApkInstallSchedulerTest : public WebLayerBrowserTest {
public:
WebApkInstallSchedulerTest() = default;
~WebApkInstallSchedulerTest() override = default;
WebApkInstallSchedulerTest(const WebApkInstallSchedulerTest&) = delete;
WebApkInstallSchedulerTest& operator=(const WebApkInstallSchedulerTest&) =
delete;
void SetUpOnMainThread() override {
WebLayerBrowserTest::SetUpOnMainThread();
web_contents_ = static_cast<TabImpl*>(shell()->tab())->web_contents();
test_server_.AddDefaultHandlers(base::FilePath(kTestDataDir));
ASSERT_TRUE(test_server_.Start());
}
content::WebContents* web_contents() { return web_contents_; }
net::test_server::EmbeddedTestServer* test_server() { return &test_server_; }
std::unique_ptr<TestWebApkInstallScheduler> DefaultWebApkInstallScheduler(
webapps::ShortcutInfo info) {
std::unique_ptr<TestWebApkInstallScheduler> scheduler_bridge(
new TestWebApkInstallScheduler(
info, SkBitmap(), false,
base::BindOnce(&WebApkInstallSchedulerTest::OnInstallFinished,
base::Unretained(this))));
return scheduler_bridge;
}
webapps::ShortcutInfo DefaultShortcutInfo() {
webapps::ShortcutInfo info(test_server_.GetURL(kStartUrl));
info.best_primary_icon_url = test_server_.GetURL(kBestPrimaryIconUrl);
info.splash_image_url = test_server_.GetURL(kBestSplashIconUrl);
info.best_shortcut_icon_urls.push_back(
test_server_.GetURL(kBestShortcutIconUrl));
return info;
}
private:
raw_ptr<content::WebContents> web_contents_;
net::EmbeddedTestServer test_server_;
void OnInstallFinished(GURL manifest_url, GURL manifest_id) {}
};
// Test building the WebAPK-proto is succeeding.
IN_PROC_BROWSER_TEST_F(WebApkInstallSchedulerTest, Success) {
WebApkInstallSchedulerRunner runner;
runner.RunFetchProtoAndScheduleInstall(
DefaultWebApkInstallScheduler(DefaultShortcutInfo()), web_contents());
EXPECT_EQ(webapps::WebApkInstallResult::SUCCESS, runner.result());
}
// Test that building the WebAPK-proto succeeds when the primary icon is guarded
// by a Cross-Origin-Resource-Policy: same-origin header and the icon is
// same-origin with the start URL.
IN_PROC_BROWSER_TEST_F(WebApkInstallSchedulerTest,
CrossOriginResourcePolicySameOriginIconSuccess) {
webapps::ShortcutInfo shortcut_info = DefaultShortcutInfo();
shortcut_info.best_primary_icon_url =
test_server()->GetURL(kBestPrimaryIconCorpUrl);
WebApkInstallSchedulerRunner runner;
runner.RunFetchProtoAndScheduleInstall(
DefaultWebApkInstallScheduler(shortcut_info), web_contents());
EXPECT_EQ(webapps::WebApkInstallResult::SUCCESS, runner.result());
}
// Test that building the WebAPK-proto fails if fetching the bitmap at the best
// primary icon URL returns no content. In a perfect world the fetch would
// always succeed because the fetch for the same icon succeeded recently.
IN_PROC_BROWSER_TEST_F(WebApkInstallSchedulerTest,
BestPrimaryIconUrlDownloadTimesOut) {
webapps::ShortcutInfo shortcut_info = DefaultShortcutInfo();
shortcut_info.best_primary_icon_url = test_server()->GetURL("/nocontent");
WebApkInstallSchedulerRunner runner;
runner.RunFetchProtoAndScheduleInstall(
DefaultWebApkInstallScheduler(shortcut_info), web_contents());
EXPECT_EQ(webapps::WebApkInstallResult::ICON_HASHER_ERROR, runner.result());
}
// Test that building the WebAPK-proto fails if fetching the bitmap at the best
// splash icon URL returns no content. In a perfect world the fetch would always
// succeed because the fetch for the same icon succeeded recently.
IN_PROC_BROWSER_TEST_F(WebApkInstallSchedulerTest,
BestSplashIconUrlDownloadTimesOut) {
webapps::ShortcutInfo shortcut_info = DefaultShortcutInfo();
shortcut_info.best_primary_icon_url = test_server()->GetURL("/nocontent");
WebApkInstallSchedulerRunner runner;
runner.RunFetchProtoAndScheduleInstall(
DefaultWebApkInstallScheduler(shortcut_info), web_contents());
EXPECT_EQ(webapps::WebApkInstallResult::ICON_HASHER_ERROR, runner.result());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/webapk_install_scheduler_browsertest.cc | C++ | unknown | 9,056 |
// 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.
#include "weblayer/browser/webapps/webapps_utils.h"
#include <string>
#include "base/android/jni_string.h"
#include "ui/gfx/android/java_bitmap.h"
#include "url/gurl.h"
#include "weblayer/browser/java/jni/WebappsHelper_jni.h"
using base::android::ConvertUTF16ToJavaString;
using base::android::ConvertUTF8ToJavaString;
using base::android::ScopedJavaLocalRef;
namespace webapps {
void addShortcutToHomescreen(const std::string& id,
const GURL& url,
const std::u16string& user_title,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> java_id = ConvertUTF8ToJavaString(env, id);
ScopedJavaLocalRef<jstring> java_url =
ConvertUTF8ToJavaString(env, url.spec());
ScopedJavaLocalRef<jstring> java_user_title =
ConvertUTF16ToJavaString(env, user_title);
ScopedJavaLocalRef<jobject> java_bitmap;
if (!primary_icon.drawsNothing())
java_bitmap = gfx::ConvertToJavaBitmap(primary_icon);
Java_WebappsHelper_addShortcutToHomescreen(env, java_id, java_url,
java_user_title, java_bitmap,
is_primary_icon_maskable);
}
} // namespace webapps
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/webapps_utils.cc | C++ | unknown | 1,507 |
// 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.
#ifndef WEBLAYER_BROWSER_WEBAPPS_WEBAPPS_UTILS_H_
#define WEBLAYER_BROWSER_WEBAPPS_WEBAPPS_UTILS_H_
#include <string>
class GURL;
class SkBitmap;
namespace webapps {
// Adds a shortcut to the home screen. Calls the native method
// addShortcutToHomescreen in WebappsHelper.java
void addShortcutToHomescreen(const std::string& id,
const GURL& url,
const std::u16string& user_title,
const SkBitmap& primary_icon,
bool is_primary_icon_maskable);
} // namespace webapps
#endif // WEBLAYER_BROWSER_WEBAPPS_WEBAPPS_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/webapps_utils.h | C++ | unknown | 786 |
// 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.
#include "weblayer/browser/webapps/weblayer_app_banner_manager_android.h"
#include "components/webapps/browser/android/app_banner_manager_android.h"
namespace weblayer {
WebLayerAppBannerManagerAndroid::WebLayerAppBannerManagerAndroid(
content::WebContents* web_contents)
: AppBannerManagerAndroid(web_contents),
content::WebContentsUserData<WebLayerAppBannerManagerAndroid>(
*web_contents) {}
WebLayerAppBannerManagerAndroid::~WebLayerAppBannerManagerAndroid() = default;
void WebLayerAppBannerManagerAndroid::MaybeShowAmbientBadge() {
// TODO(crbug/1420605): Enable WebApk install BottomSheet/Banner for WebEngine
// sandbox mode.
}
void WebLayerAppBannerManagerAndroid::ShowBannerUi(
webapps::WebappInstallSource install_source) {
// TODO(crbug/1420605): Enable WebApk install BottomSheet/Banner for WebEngine
// sandbox mode.
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(WebLayerAppBannerManagerAndroid);
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/weblayer_app_banner_manager_android.cc | C++ | unknown | 1,111 |
// 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.
#ifndef WEBLAYER_BROWSER_WEBAPPS_WEBLAYER_APP_BANNER_MANAGER_ANDROID_H_
#define WEBLAYER_BROWSER_WEBAPPS_WEBLAYER_APP_BANNER_MANAGER_ANDROID_H_
#include "components/webapps/browser/android/app_banner_manager_android.h"
#include "content/public/browser/web_contents_user_data.h"
namespace weblayer {
class WebLayerAppBannerManagerAndroid
: public webapps::AppBannerManagerAndroid,
public content::WebContentsUserData<WebLayerAppBannerManagerAndroid> {
public:
explicit WebLayerAppBannerManagerAndroid(content::WebContents* web_contents);
WebLayerAppBannerManagerAndroid(const WebLayerAppBannerManagerAndroid&) =
delete;
WebLayerAppBannerManagerAndroid& operator=(
const WebLayerAppBannerManagerAndroid&) = delete;
~WebLayerAppBannerManagerAndroid() override;
using content::WebContentsUserData<
WebLayerAppBannerManagerAndroid>::FromWebContents;
protected:
void MaybeShowAmbientBadge() override;
void ShowBannerUi(webapps::WebappInstallSource install_source) override;
private:
friend class content::WebContentsUserData<WebLayerAppBannerManagerAndroid>;
WEB_CONTENTS_USER_DATA_KEY_DECL();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBAPPS_WEBLAYER_APP_BANNER_MANAGER_ANDROID_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/weblayer_app_banner_manager_android.h | C++ | unknown | 1,393 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/webapps/weblayer_webapps_client.h"
#include <string>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/feature_list.h"
#include "base/guid.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/security_state/content/content_utils.h"
#include "components/webapps/browser/android/add_to_homescreen_params.h"
#include "components/webapps/browser/android/shortcut_info.h"
#include "components/webapps/browser/features.h"
#include "components/webapps/browser/installable/installable_metrics.h"
#include "content/public/browser/browser_context.h"
#include "ui/android/color_utils_android.h"
#include "ui/gfx/android/java_bitmap.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "weblayer/browser/webapps/webapk_install_scheduler.h"
#include "weblayer/browser/webapps/webapps_utils.h"
#include "weblayer/browser/webapps/weblayer_app_banner_manager_android.h"
namespace weblayer {
using base::android::ConvertUTF16ToJavaString;
using base::android::ConvertUTF8ToJavaString;
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
WebLayerWebappsClient::WebLayerWebappsClient() = default;
WebLayerWebappsClient::~WebLayerWebappsClient() = default;
// static
void WebLayerWebappsClient::Create() {
static base::NoDestructor<WebLayerWebappsClient> instance;
instance.get();
}
bool WebLayerWebappsClient::IsOriginConsideredSecure(
const url::Origin& origin) {
return false;
}
security_state::SecurityLevel
WebLayerWebappsClient::GetSecurityLevelForWebContents(
content::WebContents* web_contents) {
auto state = security_state::GetVisibleSecurityState(web_contents);
return security_state::GetSecurityLevel(
*state,
/* used_policy_installed_certificate */ false);
}
infobars::ContentInfoBarManager*
WebLayerWebappsClient::GetInfoBarManagerForWebContents(
content::WebContents* web_contents) {
return infobars::ContentInfoBarManager::FromWebContents(web_contents);
}
webapps::WebappInstallSource WebLayerWebappsClient::GetInstallSource(
content::WebContents* web_contents,
webapps::InstallTrigger trigger) {
if (trigger == webapps::InstallTrigger::AMBIENT_BADGE) {
// RICH_INSTALL_UI is the new name for AMBIENT_BADGE.
return webapps::WebappInstallSource::RICH_INSTALL_UI_WEBLAYER;
}
return webapps::WebappInstallSource::COUNT;
}
webapps::AppBannerManager* WebLayerWebappsClient::GetAppBannerManager(
content::WebContents* web_contents) {
return WebLayerAppBannerManagerAndroid::FromWebContents(web_contents);
}
bool WebLayerWebappsClient::IsInstallationInProgress(
content::WebContents* web_contents,
const GURL& manifest_url,
const GURL& manifest_id) {
if (base::FeatureList::IsEnabled(webapps::features::kWebApkUniqueId))
return current_install_ids_.count(manifest_id);
return current_installs_.count(manifest_url) > 0;
}
bool WebLayerWebappsClient::CanShowAppBanners(
content::WebContents* web_contents) {
return WebApkInstallScheduler::IsInstallServiceAvailable();
}
void WebLayerWebappsClient::OnWebApkInstallInitiatedFromAppMenu(
content::WebContents* web_contents) {}
void WebLayerWebappsClient::InstallWebApk(
content::WebContents* web_contents,
const webapps::AddToHomescreenParams& params) {
DCHECK(current_installs_.count(params.shortcut_info->manifest_url) == 0);
current_installs_.insert(params.shortcut_info->manifest_url);
current_install_ids_.insert(params.shortcut_info->manifest_id);
WebApkInstallScheduler::FetchProtoAndScheduleInstall(
web_contents, *(params.shortcut_info), params.primary_icon,
params.has_maskable_primary_icon,
base::BindOnce(&WebLayerWebappsClient::OnInstallFinished,
weak_ptr_factory_.GetWeakPtr()));
}
void WebLayerWebappsClient::InstallShortcut(
content::WebContents* web_contents,
const webapps::AddToHomescreenParams& params) {
const webapps::ShortcutInfo& info = *params.shortcut_info;
webapps::addShortcutToHomescreen(base::GenerateGUID(), info.url,
info.user_title, params.primary_icon,
params.has_maskable_primary_icon);
}
void WebLayerWebappsClient::OnInstallFinished(GURL manifest_url,
GURL manifest_id) {
DCHECK(current_installs_.count(manifest_url) == 1);
current_installs_.erase(manifest_url);
current_install_ids_.erase(manifest_id);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/weblayer_webapps_client.cc | C++ | unknown | 4,770 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_WEBAPPS_WEBLAYER_WEBAPPS_CLIENT_H_
#define WEBLAYER_BROWSER_WEBAPPS_WEBLAYER_WEBAPPS_CLIENT_H_
#include <set>
#include "base/memory/weak_ptr.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "components/webapps/browser/webapps_client.h"
class GURL;
namespace url {
class Origin;
}
namespace weblayer {
class WebLayerWebappsClient : public webapps::WebappsClient {
public:
// Called when the scheduling of an WebAPK installation with the Chrome
// service finished or failed.
using WebApkInstallFinishedCallback = base::OnceCallback<void(GURL, GURL)>;
WebLayerWebappsClient(const WebLayerWebappsClient&) = delete;
WebLayerWebappsClient& operator=(const WebLayerWebappsClient&) = delete;
static void Create();
// WebappsClient:
bool IsOriginConsideredSecure(const url::Origin& origin) override;
security_state::SecurityLevel GetSecurityLevelForWebContents(
content::WebContents* web_contents) override;
infobars::ContentInfoBarManager* GetInfoBarManagerForWebContents(
content::WebContents* web_contents) override;
webapps::WebappInstallSource GetInstallSource(
content::WebContents* web_contents,
webapps::InstallTrigger trigger) override;
webapps::AppBannerManager* GetAppBannerManager(
content::WebContents* web_contents) override;
#if BUILDFLAG(IS_ANDROID)
bool IsInstallationInProgress(content::WebContents* web_contents,
const GURL& manifest_url,
const GURL& manifest_id) override;
bool CanShowAppBanners(content::WebContents* web_contents) override;
void OnWebApkInstallInitiatedFromAppMenu(
content::WebContents* web_contents) override;
void InstallWebApk(content::WebContents* web_contents,
const webapps::AddToHomescreenParams& params) override;
void InstallShortcut(content::WebContents* web_contents,
const webapps::AddToHomescreenParams& params) override;
#endif
private:
friend base::NoDestructor<WebLayerWebappsClient>;
WebLayerWebappsClient();
~WebLayerWebappsClient() override;
void OnInstallFinished(GURL manifest_url, GURL manifest_id);
std::set<GURL> current_installs_;
std::set<GURL> current_install_ids_;
// Used to get |weak_ptr_|.
base::WeakPtrFactory<WebLayerWebappsClient> weak_ptr_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBAPPS_WEBLAYER_WEBAPPS_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webapps/weblayer_webapps_client.h | C++ | unknown | 2,620 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/weblayer_browser_interface_binders.h"
#include "base/functional/bind.h"
#include "build/build_config.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_contents.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_processor_impl.h"
#include "components/no_state_prefetch/common/prerender_canceler.mojom.h"
#include "components/payments/content/payment_credential_factory.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_controller.h"
#include "third_party/blink/public/mojom/payments/payment_credential.mojom.h"
#include "third_party/blink/public/mojom/payments/payment_request.mojom.h"
#include "third_party/blink/public/mojom/prerender/prerender.mojom.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_processor_impl_delegate_impl.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_utils.h"
#include "weblayer/browser/translate_client_impl.h"
#include "weblayer/browser/webui/weblayer_internals.mojom.h"
#include "weblayer/browser/webui/weblayer_internals_ui.h"
#if BUILDFLAG(IS_ANDROID)
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/mojom/installedapp/installed_app_provider.mojom.h"
#include "third_party/blink/public/mojom/webshare/webshare.mojom.h"
#endif
namespace weblayer {
namespace {
void BindContentTranslateDriver(
content::RenderFrameHost* host,
mojo::PendingReceiver<translate::mojom::ContentTranslateDriver> receiver) {
// Translation does not currently work in subframes.
// TODO(crbug.com/1073370): Transition WebLayer to per-frame translation
// architecture once it's ready.
if (host->GetParent())
return;
auto* contents = content::WebContents::FromRenderFrameHost(host);
if (!contents)
return;
TranslateClientImpl* const translate_client =
TranslateClientImpl::FromWebContents(contents);
translate_client->translate_driver()->AddReceiver(std::move(receiver));
}
void BindPageHandler(
content::RenderFrameHost* host,
mojo::PendingReceiver<weblayer_internals::mojom::PageHandler> receiver) {
auto* contents = content::WebContents::FromRenderFrameHost(host);
if (!contents)
return;
content::WebUI* web_ui = contents->GetWebUI();
// Performs a safe downcast to the concrete WebUIController subclass.
WebLayerInternalsUI* concrete_controller =
web_ui ? web_ui->GetController()->GetAs<WebLayerInternalsUI>() : nullptr;
// This is expected to be called only for main frames and for the right
// WebUI pages matching the same WebUI associated to the RenderFrameHost.
if (host->GetParent() || !concrete_controller)
return;
concrete_controller->BindInterface(std::move(receiver));
}
void BindNoStatePrefetchProcessor(
content::RenderFrameHost* frame_host,
mojo::PendingReceiver<blink::mojom::NoStatePrefetchProcessor> receiver) {
prerender::NoStatePrefetchProcessorImpl::Create(
frame_host, std::move(receiver),
std::make_unique<NoStatePrefetchProcessorImplDelegateImpl>());
}
void BindPrerenderCanceler(
content::RenderFrameHost* frame_host,
mojo::PendingReceiver<prerender::mojom::PrerenderCanceler> receiver) {
auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host);
if (!web_contents)
return;
auto* no_state_prefetch_contents =
NoStatePrefetchContentsFromWebContents(web_contents);
if (!no_state_prefetch_contents)
return;
no_state_prefetch_contents->AddPrerenderCancelerReceiver(std::move(receiver));
}
#if BUILDFLAG(IS_ANDROID)
template <typename Interface>
void ForwardToJavaWebContents(content::RenderFrameHost* frame_host,
mojo::PendingReceiver<Interface> receiver) {
content::WebContents* contents =
content::WebContents::FromRenderFrameHost(frame_host);
if (contents)
contents->GetJavaInterfaces()->GetInterface(std::move(receiver));
}
template <typename Interface>
void ForwardToJavaFrame(content::RenderFrameHost* render_frame_host,
mojo::PendingReceiver<Interface> receiver) {
render_frame_host->GetJavaInterfaces()->GetInterface(std::move(receiver));
}
#endif
} // namespace
void PopulateWebLayerFrameBinders(
content::RenderFrameHost* render_frame_host,
mojo::BinderMapWithContext<content::RenderFrameHost*>* map) {
map->Add<weblayer_internals::mojom::PageHandler>(
base::BindRepeating(&BindPageHandler));
map->Add<translate::mojom::ContentTranslateDriver>(
base::BindRepeating(&BindContentTranslateDriver));
map->Add<blink::mojom::NoStatePrefetchProcessor>(
base::BindRepeating(&BindNoStatePrefetchProcessor));
map->Add<prerender::mojom::PrerenderCanceler>(
base::BindRepeating(&BindPrerenderCanceler));
#if BUILDFLAG(IS_ANDROID)
map->Add<blink::mojom::InstalledAppProvider>(base::BindRepeating(
&ForwardToJavaFrame<blink::mojom::InstalledAppProvider>));
map->Add<blink::mojom::ShareService>(base::BindRepeating(
&ForwardToJavaWebContents<blink::mojom::ShareService>));
map->Add<payments::mojom::PaymentRequest>(base::BindRepeating(
&ForwardToJavaFrame<payments::mojom::PaymentRequest>));
map->Add<payments::mojom::PaymentCredential>(
base::BindRepeating(&payments::CreatePaymentCredential));
#endif
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_browser_interface_binders.cc | C++ | unknown | 5,714 |
// 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_WEBLAYER_BROWSER_INTERFACE_BINDERS_H_
#define WEBLAYER_BROWSER_WEBLAYER_BROWSER_INTERFACE_BINDERS_H_
#include "mojo/public/cpp/bindings/binder_map.h"
namespace content {
class RenderFrameHost;
}
namespace weblayer {
void PopulateWebLayerFrameBinders(
content::RenderFrameHost* render_frame_host,
mojo::BinderMapWithContext<content::RenderFrameHost*>* binder_map);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_BROWSER_INTERFACE_BINDERS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_browser_interface_binders.h | C++ | unknown | 638 |
// 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/weblayer_factory_impl_android.h"
#include "weblayer/browser/java/jni/WebLayerFactoryImpl_jni.h"
namespace weblayer {
int WebLayerFactoryImplAndroid::GetClientMajorVersion() {
JNIEnv* env = base::android::AttachCurrentThread();
return Java_WebLayerFactoryImpl_getClientMajorVersion(env);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_factory_impl_android.cc | C++ | unknown | 493 |
// 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_WEBLAYER_FACTORY_IMPL_ANDROID_H_
#define WEBLAYER_BROWSER_WEBLAYER_FACTORY_IMPL_ANDROID_H_
namespace weblayer {
// Exposes functionality from WebLayerFactoryImpl.java to C++.
class WebLayerFactoryImplAndroid {
public:
static int GetClientMajorVersion();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_FACTORY_IMPL_ANDROID_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_factory_impl_android.h | C++ | unknown | 519 |
// 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/weblayer_features.h"
#include "build/build_config.h"
namespace weblayer {
#if BUILDFLAG(IS_ANDROID)
// Used to disable browser-control animations.
BASE_FEATURE(kImmediatelyHideBrowserControlsForTest,
"ImmediatelyHideBrowserControlsForTest",
base::FEATURE_DISABLED_BY_DEFAULT);
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_features.cc | C++ | unknown | 510 |
// 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_WEBLAYER_FEATURES_H_
#define WEBLAYER_BROWSER_WEBLAYER_FEATURES_H_
#include "base/feature_list.h"
#include "build/build_config.h"
namespace weblayer {
#if BUILDFLAG(IS_ANDROID)
BASE_DECLARE_FEATURE(kImmediatelyHideBrowserControlsForTest);
#endif
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_FEATURES_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_features.h | C++ | unknown | 494 |
// 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/weblayer_field_trials.h"
#include "base/path_service.h"
#include "components/metrics/persistent_histograms.h"
#include "weblayer/common/weblayer_paths.h"
namespace weblayer {
void WebLayerFieldTrials::OnVariationsSetupComplete() {
// Persistent histograms must be enabled as soon as possible.
base::FilePath metrics_dir;
if (base::PathService::Get(DIR_USER_DATA, &metrics_dir)) {
InstantiatePersistentHistogramsWithFeaturesAndCleanup(metrics_dir);
} else {
NOTREACHED();
}
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_field_trials.cc | C++ | unknown | 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.
#ifndef WEBLAYER_BROWSER_WEBLAYER_FIELD_TRIALS_H_
#define WEBLAYER_BROWSER_WEBLAYER_FIELD_TRIALS_H_
#include "components/variations/platform_field_trials.h"
namespace weblayer {
// Responsible for setting up field trials specific to WebLayer. Currently all
// functions are stubs, as WebLayer has no specific field trials.
class WebLayerFieldTrials : public variations::PlatformFieldTrials {
public:
WebLayerFieldTrials() = default;
WebLayerFieldTrials(const WebLayerFieldTrials&) = delete;
WebLayerFieldTrials& operator=(const WebLayerFieldTrials&) = delete;
~WebLayerFieldTrials() override = default;
// variations::PlatformFieldTrials:
void OnVariationsSetupComplete() override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_FIELD_TRIALS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_field_trials.h | C++ | unknown | 928 |
// 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/weblayer_impl_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "components/component_updater/android/component_loader_policy.h"
#include "components/crash/core/common/crash_key.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/page_info/android/page_info_client.h"
#include "components/variations/variations_ids_provider.h"
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#include "weblayer/browser/component_updater/registration.h"
#include "weblayer/browser/devtools_server_android.h"
#include "weblayer/browser/java/jni/WebLayerImpl_jni.h"
#include "weblayer/common/crash_reporter/crash_keys.h"
using base::android::JavaParamRef;
namespace weblayer {
static void JNI_WebLayerImpl_SetRemoteDebuggingEnabled(JNIEnv* env,
jboolean enabled) {
DevToolsServerAndroid::SetRemoteDebuggingEnabled(enabled);
}
static jboolean JNI_WebLayerImpl_IsRemoteDebuggingEnabled(JNIEnv* env) {
return DevToolsServerAndroid::GetRemoteDebuggingEnabled();
}
static void JNI_WebLayerImpl_SetIsWebViewCompatMode(JNIEnv* env,
jboolean value) {
static crash_reporter::CrashKeyString<1> crash_key(
crash_keys::kWeblayerWebViewCompatMode);
crash_key.Set(value ? "1" : "0");
}
static base::android::ScopedJavaLocalRef<jstring>
JNI_WebLayerImpl_GetUserAgentString(JNIEnv* env) {
return base::android::ConvertUTF8ToJavaString(
base::android::AttachCurrentThread(), embedder_support::GetUserAgent());
}
static void JNI_WebLayerImpl_RegisterExternalExperimentIDs(
JNIEnv* env,
const JavaParamRef<jintArray>& jexperiment_ids) {
std::vector<int> experiment_ids;
// A null |jexperiment_ids| is the same as an empty list.
if (jexperiment_ids) {
base::android::JavaIntArrayToIntVector(env, jexperiment_ids,
&experiment_ids);
}
WebLayerMetricsServiceClient::GetInstance()->RegisterExternalExperiments(
experiment_ids);
}
static base::android::ScopedJavaLocalRef<jstring>
JNI_WebLayerImpl_GetXClientDataHeader(JNIEnv* env) {
std::string header;
auto headers =
variations::VariationsIdsProvider::GetInstance()->GetClientDataHeaders(
false /* is_signed_in */);
if (headers)
header =
headers->headers_map.at(variations::mojom::GoogleWebVisibility::ANY);
return base::android::ConvertUTF8ToJavaString(env, header);
}
std::u16string GetClientApplicationName() {
JNIEnv* env = base::android::AttachCurrentThread();
return base::android::ConvertJavaStringToUTF16(
env, Java_WebLayerImpl_getEmbedderName(env));
}
static base::android::ScopedJavaLocalRef<jobjectArray>
JNI_WebLayerImpl_GetComponentLoaderPolicies(JNIEnv* env) {
return component_updater::AndroidComponentLoaderPolicy::
ToJavaArrayOfAndroidComponentLoaderPolicy(env,
GetComponentLoaderPolicies());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_impl_android.cc | C++ | unknown | 3,273 |
// 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_WEBLAYER_IMPL_ANDROID_H_
#define WEBLAYER_BROWSER_WEBLAYER_IMPL_ANDROID_H_
#include <string>
namespace weblayer {
// Returns the name of the WebLayer embedder.
std::u16string GetClientApplicationName();
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_IMPL_ANDROID_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_impl_android.h | C++ | unknown | 456 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_WEBLAYER_METRICS_SERVICE_ACCESSOR_H_
#define WEBLAYER_BROWSER_WEBLAYER_METRICS_SERVICE_ACCESSOR_H_
#include "components/metrics/metrics_service_accessor.h"
namespace weblayer {
// This class gives and documents access to metrics::MetricsServiceAccessor
// methods. Since these methods are protected in the base case, each user has to
// be explicitly declared as a 'friend' below.
class WebLayerMetricsServiceAccessor : public metrics::MetricsServiceAccessor {
private:
friend class WebLayerSafeBrowsingUIManagerDelegate;
friend class WebLayerAssistantFieldTrialUtil;
WebLayerMetricsServiceAccessor() = delete;
WebLayerMetricsServiceAccessor(const WebLayerMetricsServiceAccessor&) =
delete;
WebLayerMetricsServiceAccessor& operator=(
const WebLayerMetricsServiceAccessor&) = delete;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_METRICS_SERVICE_ACCESSOR_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_metrics_service_accessor.h | C++ | unknown | 1,074 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/weblayer_page_load_metrics_memory_tracker_factory.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
#include "components/page_load_metrics/browser/page_load_metrics_memory_tracker.h"
namespace weblayer {
page_load_metrics::PageLoadMetricsMemoryTracker*
WeblayerPageLoadMetricsMemoryTrackerFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<page_load_metrics::PageLoadMetricsMemoryTracker*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
WeblayerPageLoadMetricsMemoryTrackerFactory*
WeblayerPageLoadMetricsMemoryTrackerFactory::GetInstance() {
return base::Singleton<WeblayerPageLoadMetricsMemoryTrackerFactory>::get();
}
WeblayerPageLoadMetricsMemoryTrackerFactory::
WeblayerPageLoadMetricsMemoryTrackerFactory()
: BrowserContextKeyedServiceFactory(
"PageLoadMetricsMemoryTracker",
BrowserContextDependencyManager::GetInstance()) {}
bool WeblayerPageLoadMetricsMemoryTrackerFactory::
ServiceIsCreatedWithBrowserContext() const {
return base::FeatureList::IsEnabled(features::kV8PerFrameMemoryMonitoring);
}
KeyedService*
WeblayerPageLoadMetricsMemoryTrackerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new page_load_metrics::PageLoadMetricsMemoryTracker();
}
content::BrowserContext*
WeblayerPageLoadMetricsMemoryTrackerFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_page_load_metrics_memory_tracker_factory.cc | C++ | unknown | 1,820 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_WEBLAYER_PAGE_LOAD_METRICS_MEMORY_TRACKER_FACTORY_H_
#define WEBLAYER_BROWSER_WEBLAYER_PAGE_LOAD_METRICS_MEMORY_TRACKER_FACTORY_H_
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace page_load_metrics {
class PageLoadMetricsMemoryTracker;
} // namespace page_load_metrics
namespace weblayer {
class WeblayerPageLoadMetricsMemoryTrackerFactory
: public BrowserContextKeyedServiceFactory {
public:
static page_load_metrics::PageLoadMetricsMemoryTracker* GetForBrowserContext(
content::BrowserContext* context);
static WeblayerPageLoadMetricsMemoryTrackerFactory* GetInstance();
WeblayerPageLoadMetricsMemoryTrackerFactory();
private:
// BrowserContextKeyedServiceFactory:
bool ServiceIsCreatedWithBrowserContext() const override;
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_PAGE_LOAD_METRICS_MEMORY_TRACKER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_page_load_metrics_memory_tracker_factory.h | C++ | unknown | 1,286 |
// 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/weblayer_security_blocking_page_factory.h"
#include "build/build_config.h"
#include "components/captive_portal/core/buildflags.h"
#include "components/security_interstitials/content/content_metrics_helper.h"
#include "components/security_interstitials/content/insecure_form_blocking_page.h"
#include "components/security_interstitials/content/settings_page_helper.h"
#include "components/security_interstitials/content/ssl_blocking_page.h"
#include "components/security_interstitials/core/metrics_helper.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/captive_portal_service_factory.h"
#include "weblayer/browser/insecure_form_controller_client.h"
#include "weblayer/browser/ssl_error_controller_client.h"
#if BUILDFLAG(IS_ANDROID)
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer.h"
#include "ui/base/window_open_disposition.h"
#endif
namespace weblayer {
namespace {
#if BUILDFLAG(IS_ANDROID)
GURL GetCaptivePortalLoginPageUrlInternal() {
// NOTE: This is taken from the default login URL in //chrome's
// CaptivePortalHelper.java, which is used in the implementation referenced
// in OpenLoginPage() below.
return GURL("http://connectivitycheck.gstatic.com/generate_204");
}
#endif
void OpenLoginPage(content::WebContents* web_contents) {
// TODO(https://crbug.com/1030692): Componentize and share the
// Android implementation from //chrome's
// ChromeSecurityBlockingPageFactory::OpenLoginPage(), from which this is
// adapted.
#if BUILDFLAG(IS_ANDROID)
content::OpenURLParams params(GetCaptivePortalLoginPageUrlInternal(),
content::Referrer(),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui::PAGE_TRANSITION_LINK, false);
web_contents->OpenURL(params);
#else
NOTIMPLEMENTED();
#endif
}
std::unique_ptr<security_interstitials::MetricsHelper>
CreateMetricsHelperAndStartRecording(content::WebContents* web_contents,
const GURL& request_url,
const std::string& metric_prefix,
bool overridable) {
security_interstitials::MetricsHelper::ReportDetails report_details;
report_details.metric_prefix = metric_prefix;
auto metrics_helper = std::make_unique<ContentMetricsHelper>(
/*history_service=*/nullptr, request_url, report_details);
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
metrics_helper.get()->StartRecordingCaptivePortalMetrics(
CaptivePortalServiceFactory::GetForBrowserContext(
web_contents->GetBrowserContext()),
overridable);
#endif
return metrics_helper;
}
std::unique_ptr<security_interstitials::SettingsPageHelper>
CreateSettingsPageHelper() {
// TODO(crbug.com/1078381): Set settings_page_helper once enhanced protection
// is supported on weblayer.
return nullptr;
}
} // namespace
std::unique_ptr<SSLBlockingPage>
WebLayerSecurityBlockingPageFactory::CreateSSLPage(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
int options_mask,
const base::Time& time_triggered,
const GURL& support_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter) {
bool overridable = SSLBlockingPage::IsOverridable(options_mask);
auto controller_client = std::make_unique<SSLErrorControllerClient>(
web_contents, cert_error, ssl_info, request_url,
CreateMetricsHelperAndStartRecording(
web_contents, request_url,
overridable ? "ssl_overridable" : "ssl_nonoverridable", overridable),
CreateSettingsPageHelper());
auto interstitial_page = std::make_unique<SSLBlockingPage>(
web_contents, cert_error, ssl_info, request_url, options_mask,
base::Time::NowFromSystemTime(), /*support_url=*/GURL(),
std::move(ssl_cert_reporter), overridable,
/*can_show_enhanced_protection_message=*/false,
std::move(controller_client));
return interstitial_page;
}
std::unique_ptr<CaptivePortalBlockingPage>
WebLayerSecurityBlockingPageFactory::CreateCaptivePortalBlockingPage(
content::WebContents* web_contents,
const GURL& request_url,
const GURL& login_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
const net::SSLInfo& ssl_info,
int cert_error) {
auto controller_client = std::make_unique<SSLErrorControllerClient>(
web_contents, cert_error, ssl_info, request_url,
CreateMetricsHelperAndStartRecording(web_contents, request_url,
"captive_portal", false),
CreateSettingsPageHelper());
auto interstitial_page = std::make_unique<CaptivePortalBlockingPage>(
web_contents, request_url, login_url, std::move(ssl_cert_reporter),
/*can_show_enhanced_protection_message=*/false, ssl_info,
std::move(controller_client), base::BindRepeating(&OpenLoginPage));
return interstitial_page;
}
std::unique_ptr<BadClockBlockingPage>
WebLayerSecurityBlockingPageFactory::CreateBadClockBlockingPage(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
const base::Time& time_triggered,
ssl_errors::ClockState clock_state,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter) {
auto controller_client = std::make_unique<SSLErrorControllerClient>(
web_contents, cert_error, ssl_info, request_url,
CreateMetricsHelperAndStartRecording(web_contents, request_url,
"bad_clock", false),
CreateSettingsPageHelper());
auto interstitial_page = std::make_unique<BadClockBlockingPage>(
web_contents, cert_error, ssl_info, request_url,
base::Time::NowFromSystemTime(),
/*can_show_enhanced_protection_message=*/false, clock_state,
std::move(ssl_cert_reporter), std::move(controller_client));
return interstitial_page;
}
std::unique_ptr<MITMSoftwareBlockingPage>
WebLayerSecurityBlockingPageFactory::CreateMITMSoftwareBlockingPage(
content::WebContents* web_contents,
int cert_error,
const GURL& request_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
const net::SSLInfo& ssl_info,
const std::string& mitm_software_name) {
auto controller_client = std::make_unique<SSLErrorControllerClient>(
web_contents, cert_error, ssl_info, request_url,
CreateMetricsHelperAndStartRecording(web_contents, request_url,
"mitm_software", false),
CreateSettingsPageHelper());
auto interstitial_page = std::make_unique<MITMSoftwareBlockingPage>(
web_contents, cert_error, request_url, std::move(ssl_cert_reporter),
/*can_show_enhanced_protection_message=*/false, ssl_info,
mitm_software_name,
/*is_enterprise_managed=*/false, std::move(controller_client));
return interstitial_page;
}
std::unique_ptr<BlockedInterceptionBlockingPage>
WebLayerSecurityBlockingPageFactory::CreateBlockedInterceptionBlockingPage(
content::WebContents* web_contents,
int cert_error,
const GURL& request_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
const net::SSLInfo& ssl_info) {
auto controller_client = std::make_unique<SSLErrorControllerClient>(
web_contents, cert_error, ssl_info, request_url,
CreateMetricsHelperAndStartRecording(web_contents, request_url,
"blocked_interception", false),
CreateSettingsPageHelper());
auto interstitial_page = std::make_unique<BlockedInterceptionBlockingPage>(
web_contents, cert_error, request_url, std::move(ssl_cert_reporter),
/*can_show_enhanced_protection_message=*/false, ssl_info,
std::move(controller_client));
return interstitial_page;
}
std::unique_ptr<security_interstitials::InsecureFormBlockingPage>
WebLayerSecurityBlockingPageFactory::CreateInsecureFormBlockingPage(
content::WebContents* web_contents,
const GURL& request_url) {
std::unique_ptr<InsecureFormControllerClient> client =
std::make_unique<InsecureFormControllerClient>(web_contents, request_url);
auto page =
std::make_unique<security_interstitials::InsecureFormBlockingPage>(
web_contents, request_url, std::move(client));
return page;
}
std::unique_ptr<security_interstitials::HttpsOnlyModeBlockingPage>
WebLayerSecurityBlockingPageFactory::CreateHttpsOnlyModeBlockingPage(
content::WebContents* web_contents,
const GURL& request_url) {
// HTTPS-only mode is not implemented for weblayer.
return nullptr;
}
#if BUILDFLAG(IS_ANDROID)
// static
GURL WebLayerSecurityBlockingPageFactory::
GetCaptivePortalLoginPageUrlForTesting() {
return GetCaptivePortalLoginPageUrlInternal();
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_security_blocking_page_factory.cc | C++ | unknown | 9,087 |
// 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_WEBLAYER_SECURITY_BLOCKING_PAGE_FACTORY_H_
#define WEBLAYER_BROWSER_WEBLAYER_SECURITY_BLOCKING_PAGE_FACTORY_H_
#include "build/build_config.h"
#include "components/captive_portal/core/buildflags.h"
#include "components/security_interstitials/content/bad_clock_blocking_page.h"
#include "components/security_interstitials/content/blocked_interception_blocking_page.h"
#include "components/security_interstitials/content/captive_portal_blocking_page.h"
#include "components/security_interstitials/content/https_only_mode_blocking_page.h"
#include "components/security_interstitials/content/insecure_form_blocking_page.h"
#include "components/security_interstitials/content/mitm_software_blocking_page.h"
#include "components/security_interstitials/content/security_blocking_page_factory.h"
#include "components/security_interstitials/content/ssl_blocking_page.h"
#include "components/security_interstitials/content/ssl_blocking_page_base.h"
namespace weblayer {
// //weblayer's implementation of the SecurityBlockingPageFactory interface.
class WebLayerSecurityBlockingPageFactory : public SecurityBlockingPageFactory {
public:
WebLayerSecurityBlockingPageFactory() = default;
~WebLayerSecurityBlockingPageFactory() override = default;
WebLayerSecurityBlockingPageFactory(
const WebLayerSecurityBlockingPageFactory&) = delete;
WebLayerSecurityBlockingPageFactory& operator=(
const WebLayerSecurityBlockingPageFactory&) = delete;
// SecurityBlockingPageFactory:
std::unique_ptr<SSLBlockingPage> CreateSSLPage(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
int options_mask,
const base::Time& time_triggered,
const GURL& support_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter) override;
std::unique_ptr<CaptivePortalBlockingPage> CreateCaptivePortalBlockingPage(
content::WebContents* web_contents,
const GURL& request_url,
const GURL& login_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
const net::SSLInfo& ssl_info,
int cert_error) override;
std::unique_ptr<BadClockBlockingPage> CreateBadClockBlockingPage(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
const base::Time& time_triggered,
ssl_errors::ClockState clock_state,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter) override;
std::unique_ptr<MITMSoftwareBlockingPage> CreateMITMSoftwareBlockingPage(
content::WebContents* web_contents,
int cert_error,
const GURL& request_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
const net::SSLInfo& ssl_info,
const std::string& mitm_software_name) override;
std::unique_ptr<BlockedInterceptionBlockingPage>
CreateBlockedInterceptionBlockingPage(
content::WebContents* web_contents,
int cert_error,
const GURL& request_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
const net::SSLInfo& ssl_info) override;
std::unique_ptr<security_interstitials::InsecureFormBlockingPage>
CreateInsecureFormBlockingPage(content::WebContents* web_contents,
const GURL& request_url) override;
std::unique_ptr<security_interstitials::HttpsOnlyModeBlockingPage>
CreateHttpsOnlyModeBlockingPage(content::WebContents* web_contents,
const GURL& request_url) override;
#if BUILDFLAG(IS_ANDROID)
// Returns the URL that will be navigated to when the user clicks on the
// "Connect" button of the captive portal interstitial. Used by tests to
// verify this flow.
static GURL GetCaptivePortalLoginPageUrlForTesting();
#endif
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_SECURITY_BLOCKING_PAGE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_security_blocking_page_factory.h | C++ | unknown | 4,042 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/weblayer_speech_recognition_manager_delegate.h"
#include <string>
#include "base/functional/bind.h"
#include "build/build_config.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/speech_recognition_manager.h"
#include "content/public/browser/speech_recognition_session_context.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/mojom/speech/speech_recognition_error.mojom.h"
#include "third_party/blink/public/mojom/speech/speech_recognition_result.mojom.h"
using content::BrowserThread;
namespace weblayer {
WebLayerSpeechRecognitionManagerDelegate::
WebLayerSpeechRecognitionManagerDelegate() = default;
WebLayerSpeechRecognitionManagerDelegate::
~WebLayerSpeechRecognitionManagerDelegate() = default;
void WebLayerSpeechRecognitionManagerDelegate::OnRecognitionStart(
int session_id) {}
void WebLayerSpeechRecognitionManagerDelegate::OnAudioStart(int session_id) {}
void WebLayerSpeechRecognitionManagerDelegate::OnEnvironmentEstimationComplete(
int session_id) {}
void WebLayerSpeechRecognitionManagerDelegate::OnSoundStart(int session_id) {}
void WebLayerSpeechRecognitionManagerDelegate::OnSoundEnd(int session_id) {}
void WebLayerSpeechRecognitionManagerDelegate::OnAudioEnd(int session_id) {}
void WebLayerSpeechRecognitionManagerDelegate::OnRecognitionResults(
int session_id,
const std::vector<blink::mojom::SpeechRecognitionResultPtr>& result) {}
void WebLayerSpeechRecognitionManagerDelegate::OnRecognitionError(
int session_id,
const blink::mojom::SpeechRecognitionError& error) {}
void WebLayerSpeechRecognitionManagerDelegate::OnAudioLevelsChange(
int session_id,
float volume,
float noise_volume) {}
void WebLayerSpeechRecognitionManagerDelegate::OnRecognitionEnd(
int session_id) {}
void WebLayerSpeechRecognitionManagerDelegate::CheckRecognitionIsAllowed(
int session_id,
base::OnceCallback<void(bool ask_user, bool is_allowed)> callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
const content::SpeechRecognitionSessionContext& context =
content::SpeechRecognitionManager::GetInstance()->GetSessionContext(
session_id);
// Make sure that initiators (extensions/web pages) properly set the
// |render_process_id| field, which is needed later to retrieve the profile.
DCHECK_NE(context.render_process_id, 0);
int render_process_id = context.render_process_id;
int render_frame_id = context.render_frame_id;
if (context.embedder_render_process_id) {
// If this is a request originated from a guest, we need to re-route the
// permission check through the embedder (app).
render_process_id = context.embedder_render_process_id;
render_frame_id = context.embedder_render_frame_id;
}
// Check that the render frame type is appropriate, and whether or not we
// need to request permission from the user.
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&CheckRenderFrameType, std::move(callback),
render_process_id, render_frame_id));
}
content::SpeechRecognitionEventListener*
WebLayerSpeechRecognitionManagerDelegate::GetEventListener() {
return this;
}
bool WebLayerSpeechRecognitionManagerDelegate::FilterProfanities(
int render_process_id) {
// TODO(timvolodine): to confirm how this setting should be used in weblayer.
// https://crbug.com/1068679.
return false;
}
// static.
void WebLayerSpeechRecognitionManagerDelegate::CheckRenderFrameType(
base::OnceCallback<void(bool ask_user, bool is_allowed)> callback,
int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Regular tab contents.
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), true /* check_permission */,
true /* allowed */));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_speech_recognition_manager_delegate.cc | C++ | unknown | 4,284 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_WEBLAYER_SPEECH_RECOGNITION_MANAGER_DELEGATE_H_
#define WEBLAYER_BROWSER_WEBLAYER_SPEECH_RECOGNITION_MANAGER_DELEGATE_H_
#include "content/public/browser/speech_recognition_event_listener.h"
#include "content/public/browser/speech_recognition_manager_delegate.h"
#include "content/public/browser/speech_recognition_session_config.h"
namespace weblayer {
// WebLayer implementation of the SpeechRecognitionManagerDelegate interface.
class WebLayerSpeechRecognitionManagerDelegate
: public content::SpeechRecognitionManagerDelegate,
public content::SpeechRecognitionEventListener {
public:
WebLayerSpeechRecognitionManagerDelegate();
~WebLayerSpeechRecognitionManagerDelegate() override;
WebLayerSpeechRecognitionManagerDelegate(
const WebLayerSpeechRecognitionManagerDelegate&) = delete;
WebLayerSpeechRecognitionManagerDelegate& operator=(
const WebLayerSpeechRecognitionManagerDelegate&) = delete;
protected:
// SpeechRecognitionEventListener methods.
void OnRecognitionStart(int session_id) override;
void OnAudioStart(int session_id) override;
void OnEnvironmentEstimationComplete(int session_id) override;
void OnSoundStart(int session_id) override;
void OnSoundEnd(int session_id) override;
void OnAudioEnd(int session_id) override;
void OnRecognitionEnd(int session_id) override;
void OnRecognitionResults(
int session_id,
const std::vector<blink::mojom::SpeechRecognitionResultPtr>& result)
override;
void OnRecognitionError(
int session_id,
const blink::mojom::SpeechRecognitionError& error) override;
void OnAudioLevelsChange(int session_id,
float volume,
float noise_volume) override;
// SpeechRecognitionManagerDelegate methods.
void CheckRecognitionIsAllowed(
int session_id,
base::OnceCallback<void(bool ask_user, bool is_allowed)> callback)
override;
content::SpeechRecognitionEventListener* GetEventListener() override;
bool FilterProfanities(int render_process_id) override;
private:
// Checks for mojom::ViewType::kTabContents host in the UI thread and notifies
// back the result in the IO thread through |callback|.
static void CheckRenderFrameType(
base::OnceCallback<void(bool ask_user, bool is_allowed)> callback,
int render_process_id,
int render_frame_id);
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_SPEECH_RECOGNITION_MANAGER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_speech_recognition_manager_delegate.h | C++ | unknown | 2,652 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/test/weblayer_browser_test.h"
#include "base/command_line.h"
#include "base/synchronization/lock.h"
#include "base/thread_annotations.h"
#include "components/variations/variations_ids_provider.h"
#include "content/public/test/network_connection_change_simulator.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "weblayer/public/navigation.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
// The purpose of this test is to verify Variations code is correctly wired up
// for WebLayer. It's not intended to replicate VariationsHttpHeadersBrowserTest
class WebLayerVariationsHttpBrowserTest : public WebLayerBrowserTest {
public:
WebLayerVariationsHttpBrowserTest()
: https_server_(net::test_server::EmbeddedTestServer::TYPE_HTTPS) {}
~WebLayerVariationsHttpBrowserTest() override = default;
void SetUp() override {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
// HTTPS server only serves a valid cert for localhost, so this is needed to
// load pages from "www.google.com" without an interstitial.
command_line->AppendSwitch("ignore-certificate-errors");
WebLayerBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
auto* variations_provider =
variations::VariationsIdsProvider::GetInstance();
variations_provider->ForceVariationIds({"12", "456", "t789"}, "");
// The test makes requests to google.com which we want to redirect to the
// test server.
host_resolver()->AddRule("*", "127.0.0.1");
https_server_.RegisterRequestHandler(
base::BindRepeating(&WebLayerVariationsHttpBrowserTest::RequestHandler,
base::Unretained(this)));
ASSERT_TRUE(https_server_.Start());
}
GURL GetGoogleUrlWithPath(const std::string& path) const {
return https_server_.GetURL("www.google.com", path);
}
GURL GetGoogleRedirectUrl1() const {
return GetGoogleUrlWithPath("/redirect");
}
GURL GetGoogleRedirectUrl2() const {
return GetGoogleUrlWithPath("/redirect2");
}
GURL GetExampleUrlWithPath(const std::string& path) const {
return https_server_.GetURL("www.example.com", path);
}
GURL GetExampleUrl() const { return GetExampleUrlWithPath("/landing.html"); }
// Returns whether a given |header| has been received for a |url|. If
// |url| has not been observed, fails an EXPECT and returns false.
bool HasReceivedHeader(const GURL& url, const std::string& header) {
base::AutoLock lock(received_headers_lock_);
auto it = received_headers_.find(url);
EXPECT_TRUE(it != received_headers_.end());
if (it == received_headers_.end())
return false;
return it->second.find(header) != it->second.end();
}
std::unique_ptr<net::test_server::HttpResponse> RequestHandler(
const net::test_server::HttpRequest& request) {
// Retrieve the host name (without port) from the request headers.
std::string host = "";
if (request.headers.find("Host") != request.headers.end())
host = request.headers.find("Host")->second;
if (host.find(':') != std::string::npos)
host = host.substr(0, host.find(':'));
// Recover the original URL of the request by replacing the host name in
// request.GetURL() (which is 127.0.0.1) with the host name from the request
// headers.
GURL::Replacements replacements;
replacements.SetHostStr(host);
GURL original_url = request.GetURL().ReplaceComponents(replacements);
{
base::AutoLock lock(received_headers_lock_);
// Memorize the request headers for this URL for later verification.
received_headers_[original_url] = request.headers;
}
// Set up a test server that redirects according to the
// following redirect chain:
// https://www.google.com:<port>/redirect
// --> https://www.google.com:<port>/redirect2
// --> https://www.example.com:<port>/
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
http_response->AddCustomHeader("Access-Control-Allow-Origin", "*");
if (request.relative_url == GetGoogleRedirectUrl1().path()) {
http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
http_response->AddCustomHeader("Location",
GetGoogleRedirectUrl2().spec());
} else if (request.relative_url == GetGoogleRedirectUrl2().path()) {
http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
http_response->AddCustomHeader("Location", GetExampleUrl().spec());
} else if (request.relative_url == GetExampleUrl().path()) {
http_response->set_code(net::HTTP_OK);
http_response->set_content("hello");
http_response->set_content_type("text/plain");
} else {
return nullptr;
}
return http_response;
}
protected:
net::EmbeddedTestServer https_server_;
base::Lock received_headers_lock_;
// Stores the observed HTTP Request headers.
std::map<GURL, net::test_server::HttpRequest::HeaderMap> received_headers_
GUARDED_BY(received_headers_lock_);
};
// Verify in an integration test that the variations header (X-Client-Data) is
// attached to network requests to Google but stripped on redirects.
IN_PROC_BROWSER_TEST_F(WebLayerVariationsHttpBrowserTest,
TestStrippingHeadersFromResourceRequest) {
OneShotNavigationObserver observer(shell());
shell()->tab()->GetNavigationController()->Navigate(GetGoogleRedirectUrl1());
observer.WaitForNavigation();
EXPECT_TRUE(HasReceivedHeader(GetGoogleRedirectUrl1(), "X-Client-Data"));
EXPECT_TRUE(HasReceivedHeader(GetGoogleRedirectUrl2(), "X-Client-Data"));
EXPECT_TRUE(HasReceivedHeader(GetExampleUrl(), "Host"));
EXPECT_FALSE(HasReceivedHeader(GetExampleUrl(), "X-Client-Data"));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_variations_http_browsertest.cc | C++ | unknown | 6,274 |
// 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/weblayer_variations_service_client.h"
#include "build/build_config.h"
#include "components/version_info/channel.h"
#include "components/version_info/version_info.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/system_network_context_manager.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/version_info/android/channel_getter.h"
#endif
using version_info::Channel;
namespace weblayer {
WebLayerVariationsServiceClient::WebLayerVariationsServiceClient(
SystemNetworkContextManager* network_context_manager)
: network_context_manager_(network_context_manager) {
DCHECK(network_context_manager_);
}
WebLayerVariationsServiceClient::~WebLayerVariationsServiceClient() = default;
base::Version WebLayerVariationsServiceClient::GetVersionForSimulation() {
return version_info::GetVersion();
}
scoped_refptr<network::SharedURLLoaderFactory>
WebLayerVariationsServiceClient::GetURLLoaderFactory() {
return network_context_manager_->GetSharedURLLoaderFactory();
}
network_time::NetworkTimeTracker*
WebLayerVariationsServiceClient::GetNetworkTimeTracker() {
return BrowserProcess::GetInstance()->GetNetworkTimeTracker();
}
Channel WebLayerVariationsServiceClient::GetChannel() {
#if BUILDFLAG(IS_ANDROID)
return version_info::android::GetChannel();
#else
return version_info::Channel::UNKNOWN;
#endif
}
bool WebLayerVariationsServiceClient::OverridesRestrictParameter(
std::string* parameter) {
return false;
}
bool WebLayerVariationsServiceClient::IsEnterprise() {
return false;
}
void WebLayerVariationsServiceClient::
RemoveGoogleGroupsFromPrefsForDeletedProfiles(PrefService* local_state) {}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_variations_service_client.cc | C++ | unknown | 1,924 |
// 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_WEBLAYER_VARIATIONS_SERVICE_CLIENT_H_
#define WEBLAYER_BROWSER_WEBLAYER_VARIATIONS_SERVICE_CLIENT_H_
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "components/variations/service/variations_service_client.h"
namespace weblayer {
class SystemNetworkContextManager;
// WebLayerVariationsServiceClient provides an implementation of
// VariationsServiceClient, all members are currently stubs for WebLayer.
class WebLayerVariationsServiceClient
: public variations::VariationsServiceClient {
public:
explicit WebLayerVariationsServiceClient(
SystemNetworkContextManager* network_context_manager);
WebLayerVariationsServiceClient(const WebLayerVariationsServiceClient&) =
delete;
WebLayerVariationsServiceClient& operator=(
const WebLayerVariationsServiceClient&) = delete;
~WebLayerVariationsServiceClient() override;
private:
// variations::VariationsServiceClient:
base::Version GetVersionForSimulation() override;
scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
network_time::NetworkTimeTracker* GetNetworkTimeTracker() override;
version_info::Channel GetChannel() override;
bool OverridesRestrictParameter(std::string* parameter) override;
bool IsEnterprise() override;
void RemoveGoogleGroupsFromPrefsForDeletedProfiles(
PrefService* local_state) override;
raw_ptr<SystemNetworkContextManager> network_context_manager_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBLAYER_VARIATIONS_SERVICE_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/weblayer_variations_service_client.h | C++ | unknown | 1,734 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/webrtc/media_stream_manager.h"
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/supports_user_data.h"
#include "components/webrtc/media_stream_devices_controller.h"
#include "content/public/browser/media_stream_request.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
#include "weblayer/browser/java/jni/MediaStreamManager_jni.h"
using base::android::AttachCurrentThread;
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
namespace {
constexpr int kWebContentsUserDataKey = 0;
struct UserData : public base::SupportsUserData::Data {
raw_ptr<MediaStreamManager, DanglingUntriaged> manager = nullptr;
};
} // namespace
// A class that tracks the lifecycle of a single active media stream. Ownership
// is passed off to MediaResponseCallback.
class MediaStreamManager::StreamUi : public content::MediaStreamUI {
public:
StreamUi(base::WeakPtr<MediaStreamManager> manager,
const blink::mojom::StreamDevicesSet& stream_devices)
: manager_(manager) {
DCHECK(manager_);
DCHECK_EQ(1u, stream_devices.stream_devices.size());
streaming_audio_ =
stream_devices.stream_devices[0]->audio_device.has_value();
streaming_video_ =
stream_devices.stream_devices[0]->video_device.has_value();
}
StreamUi(const StreamUi&) = delete;
StreamUi& operator=(const StreamUi&) = delete;
~StreamUi() override {
if (manager_)
manager_->UnregisterStream(this);
}
// content::MediaStreamUi:
gfx::NativeViewId OnStarted(
base::RepeatingClosure stop,
SourceCallback source,
const std::string& label,
std::vector<content::DesktopMediaID> screen_capture_ids,
StateChangeCallback state_change) override {
stop_ = std::move(stop);
if (manager_)
manager_->RegisterStream(this);
return 0;
}
void OnDeviceStoppedForSourceChange(
const std::string& label,
const content::DesktopMediaID& old_media_id,
const content::DesktopMediaID& new_media_id) override {}
void OnDeviceStopped(const std::string& label,
const content::DesktopMediaID& media_id) override {}
bool streaming_audio() const { return streaming_audio_; }
bool streaming_video() const { return streaming_video_; }
void Stop() {
// The `stop_` callback does async processing. This means Stop() may be
// called multiple times.
if (stop_)
std::move(stop_).Run();
}
private:
base::WeakPtr<MediaStreamManager> manager_;
bool streaming_audio_ = false;
bool streaming_video_ = false;
base::OnceClosure stop_;
};
MediaStreamManager::MediaStreamManager(
const JavaParamRef<jobject>& j_object,
const JavaParamRef<jobject>& j_web_contents)
: j_object_(j_object) {
auto user_data = std::make_unique<UserData>();
user_data->manager = this;
content::WebContents::FromJavaWebContents(j_web_contents)
->SetUserData(&kWebContentsUserDataKey, std::move(user_data));
}
MediaStreamManager::~MediaStreamManager() = default;
// static
MediaStreamManager* MediaStreamManager::FromWebContents(
content::WebContents* contents) {
UserData* user_data = reinterpret_cast<UserData*>(
contents->GetUserData(&kWebContentsUserDataKey));
DCHECK(user_data);
return user_data->manager;
}
void MediaStreamManager::RequestMediaAccessPermission(
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
webrtc::MediaStreamDevicesController::RequestPermissions(
request, nullptr,
base::BindOnce(&MediaStreamManager::OnMediaAccessPermissionResult,
weak_factory_.GetWeakPtr(), std::move(callback)));
}
void MediaStreamManager::OnClientReadyToStream(JNIEnv* env,
int request_id,
bool allowed) {
auto request = requests_pending_client_approval_.find(request_id);
CHECK(request != requests_pending_client_approval_.end());
if (allowed) {
std::move(request->second.callback)
.Run(*request->second.stream_devices_set_, request->second.result,
std::make_unique<StreamUi>(weak_factory_.GetWeakPtr(),
*request->second.stream_devices_set_));
} else {
std::move(request->second.callback)
.Run(blink::mojom::StreamDevicesSet(),
blink::mojom::MediaStreamRequestResult::NO_HARDWARE, {});
}
requests_pending_client_approval_.erase(request);
}
void MediaStreamManager::StopStreaming(JNIEnv* env) {
std::set<StreamUi*> active_streams = active_streams_;
for (auto* stream : active_streams)
stream->Stop();
}
void MediaStreamManager::OnMediaAccessPermissionResult(
content::MediaResponseCallback callback,
const blink::mojom::StreamDevicesSet& stream_devices_set,
blink::mojom::MediaStreamRequestResult result,
bool blocked_by_permissions_policy,
ContentSetting audio_setting,
ContentSetting video_setting) {
// TODO(crbug.com/1300883): Generalize to multiple streams.
DCHECK((result != blink::mojom::MediaStreamRequestResult::OK &&
stream_devices_set.stream_devices.empty()) ||
(result == blink::mojom::MediaStreamRequestResult::OK &&
stream_devices_set.stream_devices.size() == 1u));
if (result != blink::mojom::MediaStreamRequestResult::OK) {
std::move(callback).Run(stream_devices_set, result, {});
return;
}
int request_id = next_request_id_++;
requests_pending_client_approval_[request_id] = RequestPendingClientApproval(
std::move(callback), stream_devices_set, result);
Java_MediaStreamManager_prepareToStream(
base::android::AttachCurrentThread(), j_object_,
stream_devices_set.stream_devices[0]->audio_device.has_value(),
stream_devices_set.stream_devices[0]->video_device.has_value(),
request_id);
}
void MediaStreamManager::RegisterStream(StreamUi* stream) {
active_streams_.insert(stream);
Update();
}
void MediaStreamManager::UnregisterStream(StreamUi* stream) {
active_streams_.erase(stream);
Update();
}
void MediaStreamManager::Update() {
bool audio = false;
bool video = false;
for (const auto* stream : active_streams_) {
audio = audio || stream->streaming_audio();
video = video || stream->streaming_video();
}
Java_MediaStreamManager_update(base::android::AttachCurrentThread(),
j_object_, audio, video);
}
static jlong JNI_MediaStreamManager_Create(
JNIEnv* env,
const JavaParamRef<jobject>& j_object,
const JavaParamRef<jobject>& j_web_contents) {
return reinterpret_cast<intptr_t>(
new MediaStreamManager(j_object, j_web_contents));
}
static void JNI_MediaStreamManager_Destroy(JNIEnv* env, jlong native_manager) {
delete reinterpret_cast<MediaStreamManager*>(native_manager);
}
MediaStreamManager::RequestPendingClientApproval::
RequestPendingClientApproval() = default;
MediaStreamManager::RequestPendingClientApproval::RequestPendingClientApproval(
content::MediaResponseCallback callback,
const blink::mojom::StreamDevicesSet& stream_devices_set,
blink::mojom::MediaStreamRequestResult result)
: callback(std::move(callback)),
stream_devices_set_(stream_devices_set.Clone()),
result(result) {}
MediaStreamManager::RequestPendingClientApproval::
~RequestPendingClientApproval() = default;
MediaStreamManager::RequestPendingClientApproval&
MediaStreamManager::RequestPendingClientApproval::operator=(
RequestPendingClientApproval&& other) = default;
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webrtc/media_stream_manager.cc | C++ | unknown | 7,861 |
// 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_WEBRTC_MEDIA_STREAM_MANAGER_H_
#define WEBLAYER_BROWSER_WEBRTC_MEDIA_STREAM_MANAGER_H_
#include <map>
#include <set>
#include "base/android/scoped_java_ref.h"
#include "base/memory/weak_ptr.h"
#include "components/content_settings/core/common/content_settings.h"
#include "content/public/browser/media_stream_request.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
namespace content {
class WebContents;
}
namespace weblayer {
// On Android, this class tracks active media streams and updates the Java
// object of the same name as streams come and go. The class is created and
// destroyed by the Java object.
//
// When a site requests a new stream, this class passes off the request to
// MediaStreamDevicesController, which handles Android permissions as well as
// per-site permissions. If that succeeds, the request is passed off to the
// embedder by way of MediaCaptureCallback, at which point the response is
// returned in |OnClientReadyToStream|.
class MediaStreamManager {
public:
// It's expected that |j_web_contents| outlasts |this|.
MediaStreamManager(
const base::android::JavaParamRef<jobject>& j_object,
const base::android::JavaParamRef<jobject>& j_web_contents);
MediaStreamManager(const MediaStreamManager&) = delete;
MediaStreamManager& operator=(const MediaStreamManager&) = delete;
~MediaStreamManager();
static MediaStreamManager* FromWebContents(content::WebContents* contents);
// Requests media access permission for the tab, if necessary, and runs
// |callback| as appropriate. This will create a StreamUi.
void RequestMediaAccessPermission(const content::MediaStreamRequest& request,
content::MediaResponseCallback callback);
// The embedder has responded to the stream request.
void OnClientReadyToStream(JNIEnv* env, int request_id, bool allowed);
// The embedder has requested all streams be stopped.
void StopStreaming(JNIEnv* env);
private:
class StreamUi;
void OnMediaAccessPermissionResult(
content::MediaResponseCallback callback,
const blink::mojom::StreamDevicesSet& stream_devices_set,
blink::mojom::MediaStreamRequestResult result,
bool blocked_by_permissions_policy,
ContentSetting audio_setting,
ContentSetting video_setting);
void RegisterStream(StreamUi* stream);
void UnregisterStream(StreamUi* stream);
void Update();
std::set<StreamUi*> active_streams_;
// Represents a user-approved request for which we're waiting on embedder
// approval.
struct RequestPendingClientApproval {
RequestPendingClientApproval();
RequestPendingClientApproval(
content::MediaResponseCallback callback,
const blink::mojom::StreamDevicesSet& stream_devices_set,
blink::mojom::MediaStreamRequestResult result);
~RequestPendingClientApproval();
RequestPendingClientApproval& operator=(
RequestPendingClientApproval&& other);
content::MediaResponseCallback callback;
blink::mojom::StreamDevicesSetPtr stream_devices_set_;
blink::mojom::MediaStreamRequestResult result;
};
std::map<int, RequestPendingClientApproval> requests_pending_client_approval_;
int next_request_id_ = 0;
base::android::ScopedJavaGlobalRef<jobject> j_object_;
base::WeakPtrFactory<MediaStreamManager> weak_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBRTC_MEDIA_STREAM_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webrtc/media_stream_manager.h | C++ | unknown | 3,625 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/webui/net_export_ui.h"
#include "base/command_line.h"
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "components/net_log/net_export_file_writer.h"
#include "components/net_log/net_export_ui_constants.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "weblayer/browser/system_network_context_manager.h"
#include "weblayer/grit/weblayer_resources.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/browser_ui/share/android/intent_helper.h"
#endif
namespace weblayer {
namespace {
class NetExportMessageHandler
: public content::WebUIMessageHandler,
public net_log::NetExportFileWriter::StateObserver {
public:
NetExportMessageHandler()
: file_writer_(SystemNetworkContextManager::GetInstance()
->GetNetExportFileWriter()) {
file_writer_->Initialize();
}
NetExportMessageHandler(const NetExportMessageHandler&) = delete;
NetExportMessageHandler& operator=(const NetExportMessageHandler&) = delete;
~NetExportMessageHandler() override { file_writer_->StopNetLog(); }
// content::WebUIMessageHandler implementation.
void RegisterMessages() override {
web_ui()->RegisterMessageCallback(
net_log::kEnableNotifyUIWithStateHandler,
base::BindRepeating(&NetExportMessageHandler::OnEnableNotifyUIWithState,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
net_log::kStartNetLogHandler,
base::BindRepeating(&NetExportMessageHandler::OnStartNetLog,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
net_log::kStopNetLogHandler,
base::BindRepeating(&NetExportMessageHandler::OnStopNetLog,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
net_log::kSendNetLogHandler,
base::BindRepeating(&NetExportMessageHandler::OnSendNetLog,
base::Unretained(this)));
}
// Messages
void OnEnableNotifyUIWithState(const base::Value::List& list) {
AllowJavascript();
if (!state_observation_manager_.IsObserving()) {
state_observation_manager_.Observe(file_writer_.get());
}
NotifyUIWithState(file_writer_->GetState());
}
void OnStartNetLog(const base::Value::List& params) {
// Determine the capture mode.
if (!params.empty() && params[0].is_string()) {
capture_mode_ = net_log::NetExportFileWriter::CaptureModeFromString(
params[0].GetString());
}
// Determine the max file size.
if (params.size() > 1 && params[1].is_int() && params[1].GetInt() > 0)
max_log_file_size_ = params[1].GetInt();
StartNetLog(base::FilePath());
}
void OnStopNetLog(const base::Value::List& list) {
file_writer_->StopNetLog();
}
void OnSendNetLog(const base::Value::List& list) {
file_writer_->GetFilePathToCompletedLog(
base::BindOnce(&NetExportMessageHandler::SendEmail));
}
// net_log::NetExportFileWriter::StateObserver implementation.
void OnNewState(const base::Value::Dict& state) override {
NotifyUIWithState(state);
}
private:
// Send NetLog data via email.
static void SendEmail(const base::FilePath& file_to_send) {
#if BUILDFLAG(IS_ANDROID)
if (file_to_send.empty())
return;
std::string email;
std::string subject = "WebLayer net_internals_log";
std::string title = "Issue number: ";
std::string body =
"Please add some informative text about the network issues.";
base::FilePath::StringType file_to_attach(file_to_send.value());
browser_ui::SendEmail(base::ASCIIToUTF16(email),
base::ASCIIToUTF16(subject), base::ASCIIToUTF16(body),
base::ASCIIToUTF16(title),
base::ASCIIToUTF16(file_to_attach));
#endif
}
void StartNetLog(const base::FilePath& path) {
file_writer_->StartNetLog(
path, capture_mode_, max_log_file_size_,
base::CommandLine::ForCurrentProcess()->GetCommandLineString(),
std::string(),
web_ui()
->GetWebContents()
->GetBrowserContext()
->GetDefaultStoragePartition()
->GetNetworkContext());
}
// Fires net-log-info-changed event to update the JavaScript UI in the
// renderer.
void NotifyUIWithState(const base::Value::Dict& state) {
FireWebUIListener(net_log::kNetLogInfoChangedEvent, state);
}
// Cached pointer to SystemNetworkContextManager's NetExportFileWriter.
raw_ptr<net_log::NetExportFileWriter> file_writer_;
base::ScopedObservation<net_log::NetExportFileWriter,
net_log::NetExportFileWriter::StateObserver>
state_observation_manager_{this};
// The capture mode and file size bound that the user chose in the UI when
// logging started is cached here and is read after a file path is chosen in
// the save dialog. Their values are only valid while the save dialog is open
// on the desktop UI.
net::NetLogCaptureMode capture_mode_ = net::NetLogCaptureMode::kDefault;
uint64_t max_log_file_size_ = net_log::NetExportFileWriter::kNoLimit;
};
} // namespace
const char kChromeUINetExportHost[] = "net-export";
NetExportUI::NetExportUI(content::WebUI* web_ui) : WebUIController(web_ui) {
web_ui->AddMessageHandler(std::make_unique<NetExportMessageHandler>());
content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd(
web_ui->GetWebContents()->GetBrowserContext(), kChromeUINetExportHost);
source->UseStringsJs();
source->AddResourcePath(net_log::kNetExportUICSS, IDR_NET_LOG_NET_EXPORT_CSS);
source->AddResourcePath(net_log::kNetExportUIJS, IDR_NET_LOG_NET_EXPORT_JS);
source->SetDefaultResource(IDR_NET_LOG_NET_EXPORT_HTML);
}
NetExportUI::~NetExportUI() = default;
WEB_UI_CONTROLLER_TYPE_IMPL(NetExportUI)
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webui/net_export_ui.cc | C++ | unknown | 6,414 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_WEBUI_NET_EXPORT_UI_H_
#define WEBLAYER_BROWSER_WEBUI_NET_EXPORT_UI_H_
#include "build/build_config.h"
#include "content/public/browser/web_ui_controller.h"
namespace weblayer {
extern const char kChromeUINetExportHost[];
class NetExportUI : public content::WebUIController {
public:
explicit NetExportUI(content::WebUI* web_ui);
NetExportUI(const NetExportUI&) = delete;
NetExportUI& operator=(const NetExportUI&) = delete;
~NetExportUI() override;
private:
WEB_UI_CONTROLLER_TYPE_DECL();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBUI_NET_EXPORT_UI_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webui/net_export_ui.h | C++ | unknown | 759 |
// 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/webui/web_ui_controller_factory.h"
#include "base/memory/ptr_util.h"
#include "base/no_destructor.h"
#include "content/public/browser/web_ui.h"
#include "url/gurl.h"
#include "weblayer/browser/webui/net_export_ui.h"
#include "weblayer/browser/webui/weblayer_internals_ui.h"
namespace weblayer {
namespace {
const content::WebUI::TypeID kWebLayerID = &kWebLayerID;
// A function for creating a new WebUI. The caller owns the return value, which
// may be nullptr (for example, if the URL refers to an non-existent extension).
typedef content::WebUIController* (
*WebUIFactoryFunctionPointer)(content::WebUI* web_ui, const GURL& url);
// Template for defining WebUIFactoryFunctionPointer.
template <class T>
content::WebUIController* NewWebUI(content::WebUI* web_ui, const GURL& url) {
return new T(web_ui);
}
WebUIFactoryFunctionPointer GetWebUIFactoryFunctionPointer(const GURL& url) {
if (url.host() == kChromeUIWebLayerHost) {
return &NewWebUI<WebLayerInternalsUI>;
}
if (url.host() == kChromeUINetExportHost) {
return &NewWebUI<NetExportUI>;
}
return nullptr;
}
content::WebUI::TypeID GetWebUITypeID(const GURL& url) {
if (url.host() == kChromeUIWebLayerHost ||
url.host() == kChromeUINetExportHost) {
return kWebLayerID;
}
return content::WebUI::kNoWebUI;
}
} // namespace
// static
WebUIControllerFactory* WebUIControllerFactory::GetInstance() {
static base::NoDestructor<WebUIControllerFactory> instance;
return instance.get();
}
WebUIControllerFactory::WebUIControllerFactory() = default;
WebUIControllerFactory::~WebUIControllerFactory() = default;
content::WebUI::TypeID WebUIControllerFactory::GetWebUIType(
content::BrowserContext* browser_context,
const GURL& url) {
return GetWebUITypeID(url);
}
bool WebUIControllerFactory::UseWebUIForURL(
content::BrowserContext* browser_context,
const GURL& url) {
return GetWebUIType(browser_context, url) != content::WebUI::kNoWebUI;
}
std::unique_ptr<content::WebUIController>
WebUIControllerFactory::CreateWebUIControllerForURL(content::WebUI* web_ui,
const GURL& url) {
WebUIFactoryFunctionPointer function = GetWebUIFactoryFunctionPointer(url);
if (!function)
return nullptr;
return base::WrapUnique((*function)(web_ui, url));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webui/web_ui_controller_factory.cc | C++ | unknown | 2,526 |
// 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_WEBUI_WEB_UI_CONTROLLER_FACTORY_H_
#define WEBLAYER_BROWSER_WEBUI_WEB_UI_CONTROLLER_FACTORY_H_
#include "base/no_destructor.h"
#include "content/public/browser/web_ui_controller_factory.h"
namespace weblayer {
class WebUIControllerFactory : public content::WebUIControllerFactory {
public:
WebUIControllerFactory(const WebUIControllerFactory&) = delete;
WebUIControllerFactory& operator=(const WebUIControllerFactory&) = delete;
static WebUIControllerFactory* GetInstance();
// content::WebUIControllerFactory overrides
content::WebUI::TypeID GetWebUIType(content::BrowserContext* browser_context,
const GURL& url) override;
bool UseWebUIForURL(content::BrowserContext* browser_context,
const GURL& url) override;
std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL(
content::WebUI* web_ui,
const GURL& url) override;
private:
friend base::NoDestructor<WebUIControllerFactory>;
WebUIControllerFactory();
~WebUIControllerFactory() override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBUI_WEB_UI_CONTROLLER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webui/web_ui_controller_factory.h | C++ | unknown | 1,321 |
// 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/webui/weblayer_internals_ui.h"
#include "build/build_config.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui_data_source.h"
#include "weblayer/browser/devtools_server_android.h"
#include "weblayer/grit/weblayer_resources.h"
namespace weblayer {
const char kChromeUIWebLayerHost[] = "weblayer";
WebLayerInternalsUI::WebLayerInternalsUI(content::WebUI* web_ui)
: ui::MojoWebUIController(web_ui) {
content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd(
web_ui->GetWebContents()->GetBrowserContext(), kChromeUIWebLayerHost);
source->AddResourcePath("weblayer_internals.js", IDR_WEBLAYER_INTERNALS_JS);
source->AddResourcePath("weblayer_internals.mojom-webui.js",
IDR_WEBLAYER_INTERNALS_MOJO_JS);
source->SetDefaultResource(IDR_WEBLAYER_INTERNALS_HTML);
}
WebLayerInternalsUI::~WebLayerInternalsUI() = default;
#if BUILDFLAG(IS_ANDROID)
void WebLayerInternalsUI::GetRemoteDebuggingEnabled(
GetRemoteDebuggingEnabledCallback callback) {
std::move(callback).Run(DevToolsServerAndroid::GetRemoteDebuggingEnabled());
}
void WebLayerInternalsUI::SetRemoteDebuggingEnabled(bool enabled) {
DevToolsServerAndroid::SetRemoteDebuggingEnabled(enabled);
}
#endif
void WebLayerInternalsUI::BindInterface(
mojo::PendingReceiver<weblayer_internals::mojom::PageHandler>
pending_receiver) {
if (receiver_.is_bound())
receiver_.reset();
receiver_.Bind(std::move(pending_receiver));
}
WEB_UI_CONTROLLER_TYPE_IMPL(WebLayerInternalsUI)
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webui/weblayer_internals_ui.cc | C++ | unknown | 1,752 |
// 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_WEBUI_WEBLAYER_INTERNALS_UI_H_
#define WEBLAYER_BROWSER_WEBUI_WEBLAYER_INTERNALS_UI_H_
#include "build/build_config.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "ui/webui/mojo_web_ui_controller.h"
#include "weblayer/browser/webui/weblayer_internals.mojom.h"
namespace weblayer {
extern const char kChromeUIWebLayerHost[];
class WebLayerInternalsUI : public ui::MojoWebUIController,
public weblayer_internals::mojom::PageHandler {
public:
explicit WebLayerInternalsUI(content::WebUI* web_ui);
WebLayerInternalsUI(const WebLayerInternalsUI&) = delete;
WebLayerInternalsUI& operator=(const WebLayerInternalsUI&) = delete;
~WebLayerInternalsUI() override;
// Instantiates implementor of the mojom::PageHandler mojo interface
// passing the pending receiver that will be internally bound.
void BindInterface(
mojo::PendingReceiver<weblayer_internals::mojom::PageHandler>
pending_receiver);
private:
// weblayer_internals::mojom::PageHandler:
#if BUILDFLAG(IS_ANDROID)
void GetRemoteDebuggingEnabled(
GetRemoteDebuggingEnabledCallback callback) override;
void SetRemoteDebuggingEnabled(bool enabled) override;
#endif
mojo::Receiver<weblayer_internals::mojom::PageHandler> receiver_{this};
WEB_UI_CONTROLLER_TYPE_DECL();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_WEBUI_WEBLAYER_INTERNALS_UI_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webui/weblayer_internals_ui.h | C++ | unknown | 1,572 |
// 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/test/weblayer_browser_test.h"
#include "build/build_config.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
using WebLayerWebUIBrowserTest = WebLayerBrowserTest;
IN_PROC_BROWSER_TEST_F(WebLayerWebUIBrowserTest, DISABLED_WebUI) {
NavigateAndWaitForCompletion(GURL("chrome://weblayer"), shell());
base::RunLoop run_loop;
bool result =
ExecuteScript(shell(),
"document.getElementById('remote-debug-label').hidden",
true /* use_separate_isolate */)
.GetBool();
// The remote debug checkbox should only be visible on Android.
#if BUILDFLAG(IS_ANDROID)
EXPECT_FALSE(result);
#else
EXPECT_TRUE(result);
#endif
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/webui/webui_browsertest.cc | C++ | unknown | 896 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/xr/xr_integration_client_impl.h"
#include <memory>
#include "components/webxr/android/ar_compositor_delegate_provider.h"
#include "components/webxr/android/arcore_device_provider.h"
#include "content/public/browser/xr_install_helper.h"
#include "device/vr/public/cpp/vr_device_provider.h"
#include "device/vr/public/mojom/vr_service.mojom-shared.h"
#include "weblayer/browser/java/jni/ArCompositorDelegateProviderImpl_jni.h"
#include "weblayer/browser/java/jni/ArCoreVersionUtils_jni.h"
namespace weblayer {
namespace {
// This install helper simply checks if the necessary package (Google Play
// Services for AR, aka arcore) is installed. It doesn't attempt to initiate an
// install or update.
class ArInstallHelper : public content::XrInstallHelper {
public:
explicit ArInstallHelper() = default;
~ArInstallHelper() override = default;
ArInstallHelper(const ArInstallHelper&) = delete;
ArInstallHelper& operator=(const ArInstallHelper&) = delete;
// content::XrInstallHelper implementation.
void EnsureInstalled(
int render_process_id,
int render_frame_id,
base::OnceCallback<void(bool)> install_callback) override {
std::move(install_callback)
.Run(Java_ArCoreVersionUtils_isInstalledAndCompatible(
base::android::AttachCurrentThread()));
}
};
} // namespace
bool XrIntegrationClientImpl::IsEnabled() {
return Java_ArCoreVersionUtils_isEnabled(
base::android::AttachCurrentThread());
}
std::unique_ptr<content::XrInstallHelper>
XrIntegrationClientImpl::GetInstallHelper(device::mojom::XRDeviceId device_id) {
if (device_id == device::mojom::XRDeviceId::ARCORE_DEVICE_ID)
return std::make_unique<ArInstallHelper>();
return nullptr;
}
content::XRProviderList XrIntegrationClientImpl::GetAdditionalProviders() {
content::XRProviderList providers;
base::android::ScopedJavaLocalRef<jobject> j_ar_compositor_delegate_provider =
Java_ArCompositorDelegateProviderImpl_Constructor(
base::android::AttachCurrentThread());
providers.push_back(std::make_unique<webxr::ArCoreDeviceProvider>(
std::make_unique<webxr::ArCompositorDelegateProvider>(
std::move(j_ar_compositor_delegate_provider))));
return providers;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/xr/xr_integration_client_impl.cc | C++ | unknown | 2,434 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_XR_XR_INTEGRATION_CLIENT_IMPL_H_
#define WEBLAYER_BROWSER_XR_XR_INTEGRATION_CLIENT_IMPL_H_
#include <memory>
#include "content/public/browser/xr_integration_client.h"
namespace weblayer {
class XrIntegrationClientImpl : public content::XrIntegrationClient {
public:
XrIntegrationClientImpl() = default;
~XrIntegrationClientImpl() override = default;
XrIntegrationClientImpl(const XrIntegrationClientImpl&) = delete;
XrIntegrationClientImpl& operator=(const XrIntegrationClientImpl&) = delete;
// Returns whether XR should be enabled.
static bool IsEnabled();
// content::XrIntegrationClient:
std::unique_ptr<content::XrInstallHelper> GetInstallHelper(
device::mojom::XRDeviceId device_id) override;
content::XRProviderList GetAdditionalProviders() override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_XR_XR_INTEGRATION_CLIENT_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/xr/xr_integration_client_impl.h | C++ | unknown | 1,049 |
include_rules = [
"+components/embedder_support/origin_trials",
"+content/public/common",
"+gpu/config",
"+third_party/blink/public/strings/grit/blink_strings.h",
"+ui/base",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/common/DEPS | Python | unknown | 187 |
// 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.
#include "weblayer/common/content_client_impl.h"
#include "build/build_config.h"
#include "components/embedder_support/origin_trials/origin_trial_policy_impl.h"
#include "gpu/config/gpu_info.h"
#include "gpu/config/gpu_util.h"
#include "third_party/blink/public/strings/grit/blink_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#if BUILDFLAG(IS_ANDROID)
#include "content/public/common/url_constants.h"
#endif
namespace weblayer {
ContentClientImpl::ContentClientImpl() = default;
ContentClientImpl::~ContentClientImpl() = default;
std::u16string ContentClientImpl::GetLocalizedString(int message_id) {
return l10n_util::GetStringUTF16(message_id);
}
std::u16string ContentClientImpl::GetLocalizedString(
int message_id,
const std::u16string& replacement) {
return l10n_util::GetStringFUTF16(message_id, replacement);
}
base::StringPiece ContentClientImpl::GetDataResource(
int resource_id,
ui::ResourceScaleFactor scale_factor) {
return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
resource_id, scale_factor);
}
base::RefCountedMemory* ContentClientImpl::GetDataResourceBytes(
int resource_id) {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
resource_id);
}
std::string ContentClientImpl::GetDataResourceString(int resource_id) {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
resource_id);
}
void ContentClientImpl::SetGpuInfo(const gpu::GPUInfo& gpu_info) {
gpu::SetKeysForCrashLogging(gpu_info);
}
gfx::Image& ContentClientImpl::GetNativeImageNamed(int resource_id) {
return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(
resource_id);
}
blink::OriginTrialPolicy* ContentClientImpl::GetOriginTrialPolicy() {
// Prevent initialization race (see crbug.com/721144). There may be a
// race when the policy is needed for worker startup (which happens on a
// separate worker thread).
base::AutoLock auto_lock(origin_trial_policy_lock_);
if (!origin_trial_policy_)
origin_trial_policy_ =
std::make_unique<embedder_support::OriginTrialPolicyImpl>();
return origin_trial_policy_.get();
}
void ContentClientImpl::AddAdditionalSchemes(Schemes* schemes) {
#if BUILDFLAG(IS_ANDROID)
schemes->standard_schemes.push_back(content::kAndroidAppScheme);
schemes->referrer_schemes.push_back(content::kAndroidAppScheme);
#endif
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/common/content_client_impl.cc | C++ | unknown | 2,615 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_COMMON_CONTENT_CLIENT_IMPL_H_
#define WEBLAYER_COMMON_CONTENT_CLIENT_IMPL_H_
#include "base/synchronization/lock.h"
#include "content/public/common/content_client.h"
namespace embedder_support {
class OriginTrialPolicyImpl;
}
namespace weblayer {
class ContentClientImpl : public content::ContentClient {
public:
ContentClientImpl();
~ContentClientImpl() override;
std::u16string GetLocalizedString(int message_id) override;
std::u16string GetLocalizedString(int message_id,
const std::u16string& replacement) override;
base::StringPiece GetDataResource(
int resource_id,
ui::ResourceScaleFactor scale_factor) override;
base::RefCountedMemory* GetDataResourceBytes(int resource_id) override;
std::string GetDataResourceString(int resource_id) override;
void SetGpuInfo(const gpu::GPUInfo& gpu_info) override;
gfx::Image& GetNativeImageNamed(int resource_id) override;
blink::OriginTrialPolicy* GetOriginTrialPolicy() override;
void AddAdditionalSchemes(Schemes* schemes) override;
private:
// Used to lock when |origin_trial_policy_| is initialized.
base::Lock origin_trial_policy_lock_;
std::unique_ptr<embedder_support::OriginTrialPolicyImpl> origin_trial_policy_;
};
} // namespace weblayer
#endif // WEBLAYER_COMMON_CONTENT_CLIENT_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/common/content_client_impl.h | C++ | unknown | 1,492 |
include_rules = [
"+components/crash",
"+components/version_info",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/common/crash_reporter/DEPS | Python | unknown | 73 |
// 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/common/crash_reporter/crash_keys.h"
#include "base/android/build_info.h"
#include "base/strings/string_number_conversions.h"
#include "components/crash/core/common/crash_key.h"
namespace weblayer {
namespace crash_keys {
const char kAppPackageName[] = "app-package-name";
const char kAppPackageVersionCode[] = "app-package-version-code";
const char kAndroidSdkInt[] = "android-sdk-int";
const char kWeblayerWebViewCompatMode[] = "WEBLAYER_WEB_VIEW_COMPAT_MODE";
// clang-format off
const char* const kWebLayerCrashKeyAllowList[] = {
kAppPackageName, kAppPackageVersionCode, kAndroidSdkInt,
kWeblayerWebViewCompatMode,
// process type
"ptype",
// Java exception stack traces
"exception_info",
// gpu
"gpu-driver", "gpu-psver", "gpu-vsver", "gpu-gl-vendor", "gpu-gl-renderer",
"oop_read_failure", "gpu-gl-error-message",
// content/:
"bad_message_reason", "discardable-memory-allocated",
"discardable-memory-free", "mojo-message-error",
"total-discardable-memory-allocated",
// crash keys needed for recording finch trials
"variations", "num-experiments",
nullptr};
// clang-format on
} // namespace crash_keys
void SetWebLayerCrashKeys() {
base::android::BuildInfo* android_build_info =
base::android::BuildInfo::GetInstance();
static ::crash_reporter::CrashKeyString<64> app_name_key(
crash_keys::kAppPackageName);
app_name_key.Set(android_build_info->host_package_name());
static ::crash_reporter::CrashKeyString<64> app_version_key(
crash_keys::kAppPackageVersionCode);
app_version_key.Set(android_build_info->host_version_code());
static ::crash_reporter::CrashKeyString<8> sdk_int_key(
crash_keys::kAndroidSdkInt);
sdk_int_key.Set(base::NumberToString(android_build_info->sdk_int()));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/common/crash_reporter/crash_keys.cc | C++ | unknown | 2,000 |
// 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_COMMON_CRASH_REPORTER_CRASH_KEYS_H_
#define WEBLAYER_COMMON_CRASH_REPORTER_CRASH_KEYS_H_
namespace weblayer {
namespace crash_keys {
// Crash Key Name Constants ////////////////////////////////////////////////////
// Application information.
extern const char kAppPackageName[];
extern const char kAppPackageVersionCode[];
extern const char kAndroidSdkInt[];
extern const char kWeblayerWebViewCompatMode[];
extern const char* const kWebLayerCrashKeyAllowList[];
} // namespace crash_keys
void SetWebLayerCrashKeys();
} // namespace weblayer
#endif // WEBLAYER_COMMON_CRASH_REPORTER_CRASH_KEYS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/common/crash_reporter/crash_keys.h | C++ | unknown | 770 |
// 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/common/crash_reporter/crash_reporter_client.h"
#include <stdint.h>
#include "base/android/java_exception_reporter.h"
#include "base/android/path_utils.h"
#include "base/base_paths_android.h"
#include "base/files/file_util.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "components/crash/core/app/crash_reporter_client.h"
#include "components/crash/core/app/crashpad.h"
#include "components/version_info/android/channel_getter.h"
#include "components/version_info/version_info.h"
#include "components/version_info/version_info_values.h"
#include "weblayer/common/crash_reporter/crash_keys.h"
#include "weblayer/common/weblayer_paths.h"
namespace weblayer {
namespace {
class CrashReporterClientImpl : public crash_reporter::CrashReporterClient {
public:
CrashReporterClientImpl() = default;
CrashReporterClientImpl(const CrashReporterClientImpl&) = delete;
CrashReporterClientImpl& operator=(const CrashReporterClientImpl&) = delete;
// crash_reporter::CrashReporterClient implementation.
bool IsRunningUnattended() override { return false; }
bool GetCollectStatsConsent() override { return false; }
void GetProductNameAndVersion(std::string* product_name,
std::string* version,
std::string* channel) override {
*version = version_info::GetVersionNumber();
*product_name = "WebLayer";
*channel =
version_info::GetChannelString(version_info::android::GetChannel());
}
bool GetCrashDumpLocation(base::FilePath* crash_dir) override {
return base::PathService::Get(DIR_CRASH_DUMPS, crash_dir);
}
void GetSanitizationInformation(const char* const** crash_key_allowlist,
void** target_module,
bool* sanitize_stacks) override {
*crash_key_allowlist = crash_keys::kWebLayerCrashKeyAllowList;
#if defined(COMPONENT_BUILD)
*target_module = nullptr;
#else
// The supplied address is used to identify the .so containing WebLayer.
*target_module = reinterpret_cast<void*>(&EnableCrashReporter);
#endif
*sanitize_stacks = true;
}
static CrashReporterClientImpl* Get() {
static base::NoDestructor<CrashReporterClientImpl> crash_reporter_client;
return crash_reporter_client.get();
}
};
} // namespace
void EnableCrashReporter(const std::string& process_type) {
static bool enabled = false;
DCHECK(!enabled) << "EnableCrashReporter called more than once";
crash_reporter::SetCrashReporterClient(CrashReporterClientImpl::Get());
crash_reporter::InitializeCrashpad(process_type.empty(), process_type);
if (process_type.empty())
base::android::InitJavaExceptionReporter();
else
base::android::InitJavaExceptionReporterForChildProcess();
enabled = true;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/common/crash_reporter/crash_reporter_client.cc | C++ | unknown | 3,033 |
// 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_COMMON_CRASH_REPORTER_CRASH_REPORTER_CLIENT_H_
#define WEBLAYER_COMMON_CRASH_REPORTER_CRASH_REPORTER_CLIENT_H_
#include <string>
namespace weblayer {
// Enable the collection of crashes for this process (of type |process_type|)
// via crashpad. This will collect both native crashes and uncaught Java
// exceptions as minidumps plus associated metadata.
void EnableCrashReporter(const std::string& process_type);
} // namespace weblayer
#endif // WEBLAYER_COMMON_CRASH_REPORTER_CRASH_REPORTER_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/common/crash_reporter/crash_reporter_client.h | C++ | unknown | 671 |
// 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/common/features.h"
namespace weblayer {
namespace features {
// Weblayer features in alphabetical order.
// Client side phishing detection support for weblayer
BASE_FEATURE(kWebLayerClientSidePhishingDetection,
"WebLayerClientSidePhishingDetection",
base::FEATURE_DISABLED_BY_DEFAULT);
// Safebrowsing support for weblayer.
BASE_FEATURE(kWebLayerSafeBrowsing,
"WebLayerSafeBrowsing",
base::FEATURE_ENABLED_BY_DEFAULT);
} // namespace features
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/common/features.cc | C++ | unknown | 689 |
// 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_COMMON_FEATURES_H_
#define WEBLAYER_COMMON_FEATURES_H_
#include "base/feature_list.h"
namespace weblayer {
namespace features {
// Weblayer features in alphabetical order.
BASE_DECLARE_FEATURE(kWebLayerClientSidePhishingDetection);
BASE_DECLARE_FEATURE(kWebLayerSafeBrowsing);
} // namespace features
} // namespace weblayer
#endif // WEBLAYER_COMMON_FEATURES_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/common/features.h | C++ | unknown | 533 |
// 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_COMMON_ISOLATED_WORLD_IDS_H_
#define WEBLAYER_COMMON_ISOLATED_WORLD_IDS_H_
#include "content/public/common/isolated_world_ids.h"
namespace weblayer {
enum IsolatedWorldIDs {
// Isolated world ID for internal WebLayer features.
ISOLATED_WORLD_ID_WEBLAYER = content::ISOLATED_WORLD_ID_CONTENT_END + 1,
// Isolated world ID for WebLayer translate.
ISOLATED_WORLD_ID_TRANSLATE,
};
} // namespace weblayer
#endif // WEBLAYER_COMMON_ISOLATED_WORLD_IDS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/common/isolated_world_ids.h | C++ | unknown | 626 |
// 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/common/weblayer_paths.h"
#include "base/environment.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/path_utils.h"
#include "base/base_paths_android.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "base/base_paths_win.h"
#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
#include "base/nix/xdg_util.h"
#endif
namespace weblayer {
namespace {
bool GetDefaultUserDataDirectory(base::FilePath* result) {
#if BUILDFLAG(IS_ANDROID)
// No need to append "weblayer" here. It's done in java with
// PathUtils.setPrivateDataDirectorySuffix.
return base::PathService::Get(base::DIR_ANDROID_APP_DATA, result);
#elif BUILDFLAG(IS_WIN)
if (!base::PathService::Get(base::DIR_LOCAL_APP_DATA, result))
return false;
*result = result->AppendASCII("weblayer");
return true;
#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
std::unique_ptr<base::Environment> env(base::Environment::Create());
base::FilePath config_dir(base::nix::GetXDGDirectory(
env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir));
*result = config_dir.AppendASCII("weblayer");
return true;
#else
return false;
#endif
}
} // namespace
class WebLayerPathProvider {
public:
static void CreateDir(const base::FilePath& path) {
base::ScopedAllowBlocking allow_io;
if (!base::PathExists(path))
base::CreateDirectory(path);
}
};
bool PathProvider(int key, base::FilePath* result) {
base::FilePath cur;
switch (key) {
case DIR_USER_DATA: {
bool rv = GetDefaultUserDataDirectory(result);
if (rv)
WebLayerPathProvider::CreateDir(*result);
return rv;
}
#if BUILDFLAG(IS_ANDROID)
case DIR_CRASH_DUMPS:
if (!base::android::GetCacheDirectory(&cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Crashpad"));
WebLayerPathProvider::CreateDir(cur);
*result = cur;
return true;
#endif
default:
return false;
}
}
void RegisterPathProvider() {
base::PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/common/weblayer_paths.cc | C++ | unknown | 2,417 |
// 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_COMMON_WEBLAYER_PATHS_H_
#define WEBLAYER_COMMON_WEBLAYER_PATHS_H_
#include "build/build_config.h"
// This file declares path keys for weblayer. These can be used with
// the PathService to access various special directories and files.
namespace weblayer {
enum {
PATH_START = 1000,
DIR_USER_DATA = PATH_START, // Directory where user data can be written.
#if BUILDFLAG(IS_ANDROID)
DIR_CRASH_DUMPS, // Directory where crash dumps are written.
#endif
PATH_END
};
// Call once to register the provider for the path keys defined above.
void RegisterPathProvider();
} // namespace weblayer
#endif // WEBLAYER_COMMON_WEBLAYER_PATHS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/common/weblayer_paths.h | C++ | unknown | 814 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/public/browser.h"
namespace weblayer {
Browser::PersistenceInfo::PersistenceInfo() = default;
Browser::PersistenceInfo::PersistenceInfo(const PersistenceInfo& other) =
default;
Browser::PersistenceInfo::~PersistenceInfo() = default;
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/public/browser.cc | C++ | unknown | 430 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_BROWSER_H_
#define WEBLAYER_PUBLIC_BROWSER_H_
#include <stddef.h>
#include <memory>
#include <string>
#include <vector>
namespace weblayer {
class BrowserObserver;
class BrowserRestoreObserver;
class Profile;
class Tab;
// Represents an ordered list of Tabs, with one active. Browser does not own
// the set of Tabs.
class Browser {
public:
struct PersistenceInfo {
PersistenceInfo();
PersistenceInfo(const PersistenceInfo& other);
~PersistenceInfo();
// Uniquely identifies this browser for session restore, empty is not a
// valid id.
std::string id;
// Last key used to encrypt incognito profile.
std::vector<uint8_t> last_crypto_key;
};
// Creates a new Browser. |persistence_info|, if non-null, is used for saving
// and restoring the state of the browser.
static std::unique_ptr<Browser> Create(
Profile* profile,
const PersistenceInfo* persistence_info);
virtual ~Browser() {}
virtual void AddTab(Tab* tab) = 0;
virtual void DestroyTab(Tab* tab) = 0;
virtual void SetActiveTab(Tab* tab) = 0;
virtual Tab* GetActiveTab() = 0;
virtual std::vector<Tab*> GetTabs() = 0;
// Creates a tab attached to this browser. The returned tab is owned by the
// browser.
virtual Tab* CreateTab() = 0;
// Called early on in shutdown, before any tabs have been removed.
virtual void PrepareForShutdown() = 0;
// Returns the id supplied to Create() that is used for persistence.
virtual std::string GetPersistenceId() = 0;
// Returns true if this Browser is in the process of restoring the previous
// state.
virtual bool IsRestoringPreviousState() = 0;
virtual void AddObserver(BrowserObserver* observer) = 0;
virtual void RemoveObserver(BrowserObserver* observer) = 0;
virtual void AddBrowserRestoreObserver(BrowserRestoreObserver* observer) = 0;
virtual void RemoveBrowserRestoreObserver(
BrowserRestoreObserver* observer) = 0;
virtual void VisibleSecurityStateOfActiveTabChanged() = 0;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_BROWSER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/browser.h | C++ | unknown | 2,233 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_BROWSER_OBSERVER_H_
#define WEBLAYER_PUBLIC_BROWSER_OBSERVER_H_
#include "base/observer_list_types.h"
namespace weblayer {
class Tab;
class BrowserObserver : public base::CheckedObserver {
public:
// A Tab has been been added to the Browser.
virtual void OnTabAdded(Tab* tab) {}
// A Tab has been removed from the Browser. |active_tab_changed| indicates
// if the active tab changed as a result. If the active tab changed,
// OnActiveTabChanged() is also called.
virtual void OnTabRemoved(Tab* tab, bool active_tab_changed) {}
// The tab the user is interacting with has changed. |tab| may be null if no
// tabs are active.
virtual void OnActiveTabChanged(Tab* tab) {}
protected:
~BrowserObserver() override {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_BROWSER_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/browser_observer.h | C++ | unknown | 985 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_BROWSER_RESTORE_OBSERVER_H_
#define WEBLAYER_PUBLIC_BROWSER_RESTORE_OBSERVER_H_
#include "base/observer_list_types.h"
namespace weblayer {
// Used for observing events related to restoring the previous state of a
// Browser.
class BrowserRestoreObserver : public base::CheckedObserver {
public:
// Called when the Browser has completed restoring the previous state.
virtual void OnRestoreCompleted() {}
protected:
~BrowserRestoreObserver() override = default;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_BROWSER_RESTORE_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/browser_restore_observer.h | C++ | unknown | 725 |
// 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/public/common/switches.h"
namespace weblayer {
namespace switches {
// Makes WebEngine Shell use the given path for its data directory.
// NOTE: If changing this value, change the corresponding Java-side value in
// WebLayerBrowserTestsActivity.java#getUserDataDirectoryCommandLineSwitch() to
// match.
const char kWebEngineUserDataDir[] = "webengine-user-data-dir";
} // namespace switches
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/public/common/switches.cc | C++ | unknown | 584 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_COMMON_SWITCHES_H_
#define WEBLAYER_PUBLIC_COMMON_SWITCHES_H_
namespace weblayer {
namespace switches {
extern const char kWebEngineUserDataDir[];
} // namespace switches
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_COMMON_SWITCHES_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/common/switches.h | C++ | unknown | 416 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_COOKIE_MANAGER_H_
#define WEBLAYER_PUBLIC_COOKIE_MANAGER_H_
#include <string>
#include "base/callback_list.h"
class GURL;
namespace net {
struct CookieChangeInfo;
}
namespace weblayer {
class CookieManager {
public:
virtual ~CookieManager() = default;
// Sets a cookie for the given URL.
using SetCookieCallback = base::OnceCallback<void(bool)>;
virtual void SetCookie(const GURL& url,
const std::string& value,
SetCookieCallback callback) = 0;
// Gets the cookies for the given URL.
using GetCookieCallback = base::OnceCallback<void(const std::string&)>;
virtual void GetCookie(const GURL& url, GetCookieCallback callback) = 0;
// Gets the cookies for the given URL in the form of the 'Set-Cookie' HTTP
// response header.
using GetResponseCookiesCallback =
base::OnceCallback<void(const std::vector<std::string>&)>;
virtual void GetResponseCookies(const GURL& url,
GetResponseCookiesCallback callback) = 0;
// Adds a callback to listen for changes to cookies for the given URL.
using CookieChangedCallbackList =
base::RepeatingCallbackList<void(const net::CookieChangeInfo&)>;
using CookieChangedCallback = CookieChangedCallbackList::CallbackType;
virtual base::CallbackListSubscription AddCookieChangedCallback(
const GURL& url,
const std::string* name,
CookieChangedCallback callback) = 0;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_COOKIE_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/cookie_manager.h | C++ | unknown | 1,692 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_DOWNLOAD_H_
#define WEBLAYER_PUBLIC_DOWNLOAD_H_
#include <string>
namespace base {
class FilePath;
}
namespace weblayer {
// These types are sent over IPC and across different versions. Never remove
// or change the order.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.weblayer_private
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: ImplDownloadState
enum class DownloadState {
// Download is actively progressing.
kInProgress = 0,
// Download is completely finished.
kComplete = 1,
// Download is paused by the user.
kPaused = 2,
// Download has been cancelled by the user.
kCancelled = 3,
// Download has failed (e.g. server or connection problem).
kFailed = 4,
};
// These types are sent over IPC and across different versions. Never remove
// or change the order.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.weblayer_private
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: ImplDownloadError
enum class DownloadError {
kNoError = 0, // Download completed successfully.
kServerError = 1, // Server failed, e.g. unauthorized or forbidden,
// server unreachable,
kSSLError = 2, // Certificate error.
kConnectivityError = 3, // A network error occur. e.g. disconnected, timed
// out, invalid request.
kNoSpace = 4, // There isn't enough room in the storage location.
kFileError = 5, // Various errors related to file access. e.g.
// access denied, directory or filename too long,
// file is too large for file system, file in use,
// too many files open at once etc...
kCancelled = 6, // The user cancelled the download.
kOtherError = 7, // An error not listed above occurred.
};
// Contains information about a single download that's in progress.
class Download {
public:
virtual ~Download() {}
virtual DownloadState GetState() = 0;
// Returns the total number of expected bytes. Returns -1 if the total size is
// not known.
virtual int64_t GetTotalBytes() = 0;
// Total number of bytes that have been received and written to the download
// file.
virtual int64_t GetReceivedBytes() = 0;
// Pauses the download.
virtual void Pause() = 0;
// Resumes the download.
virtual void Resume() = 0;
// Cancels the download.
virtual void Cancel() = 0;
// Returns the location of the downloaded file. This may be empty if the
// target path hasn't been determined yet. The file it points to won't be
// available until the download completes successfully.
virtual base::FilePath GetLocation() = 0;
// Returns the display name for the download.
virtual std::u16string GetFileNameToReportToUser() = 0;
// Returns the effective MIME type of downloaded content.
virtual std::string GetMimeType() = 0;
// Return information about the error, if any, that was encountered during the
// download.
virtual DownloadError GetError() = 0;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_DOWNLOAD_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/download.h | C++ | unknown | 3,241 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_DOWNLOAD_DELEGATE_H_
#define WEBLAYER_PUBLIC_DOWNLOAD_DELEGATE_H_
#include <string>
#include "base/functional/callback_forward.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/origin.h"
class GURL;
namespace weblayer {
class Download;
class Tab;
using AllowDownloadCallback = base::OnceCallback<void(bool /*allow*/)>;
// An interface that allows clients to handle download requests originating in
// the browser. The object is safe to hold on to until DownloadCompleted or
// DownloadFailed are called.
class DownloadDelegate {
public:
// Gives the embedder the opportunity to asynchronously allow or disallow the
// given download. The download is paused until the callback is run. It's safe
// to run |callback| synchronously.
virtual void AllowDownload(Tab* tab,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
AllowDownloadCallback callback) = 0;
// A download of |url| has been requested with the specified details. If
// it returns true the download will be considered intercepted and WebLayer
// won't proceed with it. Note that there are many corner cases where the
// embedder downloading it won't work (e.g. POSTs, one-time URLs, requests
// that depend on cookies or auth state). This is called after AllowDownload.
virtual bool InterceptDownload(const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
int64_t content_length) = 0;
// A download has started. There will be 0..n calls to
// DownloadProgressChanged, then either a call to DownloadCompleted or
// DownloadFailed.
virtual void DownloadStarted(Download* download) {}
// The progress percentage of a download has changed.
virtual void DownloadProgressChanged(Download* download) {}
// A download has completed successfully.
virtual void DownloadCompleted(Download* download) {}
// A download has failed because the user cancelled it or because of a server
// or network error.
virtual void DownloadFailed(Download* download) {}
protected:
virtual ~DownloadDelegate() {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_DOWNLOAD_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/download_delegate.h | C++ | unknown | 2,631 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_ERROR_PAGE_H_
#define WEBLAYER_PUBLIC_ERROR_PAGE_H_
#include <string>
namespace weblayer {
// Contains the html to show when an error is encountered.
struct ErrorPage {
std::string html;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_ERROR_PAGE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/error_page.h | C++ | unknown | 431 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_ERROR_PAGE_DELEGATE_H_
#define WEBLAYER_PUBLIC_ERROR_PAGE_DELEGATE_H_
#include <memory>
namespace weblayer {
struct ErrorPage;
class Navigation;
// An interface that allows handling of interactions with error pages (such as
// SSL interstitials). If this interface is not used, default actions will be
// taken.
class ErrorPageDelegate {
public:
// The user has pressed "back to safety" on a blocking page. A return value of
// true will cause WebLayer to skip the default action.
virtual bool OnBackToSafety() = 0;
// Returns the html to shown when an error is encountered. A null return value
// results in showing the default error page. |navigation| is the Navigation
// that encountered the error.
virtual std::unique_ptr<ErrorPage> GetErrorPageContent(
Navigation* navigation) = 0;
protected:
virtual ~ErrorPageDelegate() = default;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_ERROR_PAGE_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/error_page_delegate.h | C++ | unknown | 1,117 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_FAVICON_FETCHER_H_
#define WEBLAYER_PUBLIC_FAVICON_FETCHER_H_
namespace gfx {
class Image;
}
namespace weblayer {
// FaviconFetcher is responsible for downloading a favicon for the current
// navigation. FaviconFetcher caches favicons, updating the cache every so
// often to ensure the cache is up to date.
class FaviconFetcher {
public:
virtual ~FaviconFetcher() = default;
// Returns the favicon for the current navigation, which may be empty.
virtual gfx::Image GetFavicon() = 0;
protected:
FaviconFetcher() = default;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_FAVICON_FETCHER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/favicon_fetcher.h | C++ | unknown | 782 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_FAVICON_FETCHER_DELEGATE_H_
#define WEBLAYER_PUBLIC_FAVICON_FETCHER_DELEGATE_H_
#include "base/observer_list_types.h"
namespace gfx {
class Image;
}
namespace weblayer {
// Notified of interesting events related to FaviconFetcher.
class FaviconFetcherDelegate : public base::CheckedObserver {
public:
// Called when the favicon of the current navigation has changed. This may be
// called multiple times for the same navigation.
virtual void OnFaviconChanged(const gfx::Image& image) = 0;
protected:
~FaviconFetcherDelegate() override = default;
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_FAVICON_FETCHER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/favicon_fetcher_delegate.h | C++ | unknown | 814 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_FULLSCREEN_DELEGATE_H_
#define WEBLAYER_PUBLIC_FULLSCREEN_DELEGATE_H_
#include "base/functional/callback_forward.h"
namespace weblayer {
class FullscreenDelegate {
public:
// Called when the page has requested to go fullscreen.
virtual void EnterFullscreen(base::OnceClosure exit_closure) = 0;
// Informs the delegate the page has exited fullscreen.
virtual void ExitFullscreen() = 0;
protected:
virtual ~FullscreenDelegate() {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_FULLSCREEN_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/public/fullscreen_delegate.h | C++ | unknown | 694 |